From 19018d130f0d25fd1d56c9e02ee9d582cd197988 Mon Sep 17 00:00:00 2001 From: James Criscuolo Date: Wed, 25 Sep 2019 13:28:25 -0400 Subject: [PATCH] Revert "dist/ lib/ files for 0.15.5" This reverts commit 8d62434d7dcdcef5136262b060b39ec28afb03cc. --- dist/sip-0.15.5.js | 21461 ---------------- dist/sip-0.15.5.min.js | 1 - dist/sip-api.js | 20215 --------------- dist/sip-api.min.js | 1 - dist/sip-core.js | 12067 --------- dist/sip-core.min.js | 1 - dist/sip.js | 21461 ---------------- dist/sip.min.js | 1 - lib/ClientContext.d.ts | 36 - lib/ClientContext.d.ts.map | 1 - lib/ClientContext.js | 123 - lib/Constants.d.ts | 64 - lib/Constants.d.ts.map | 1 - lib/Constants.js | 192 - lib/Enums.d.ts | 62 - lib/Enums.d.ts.map | 1 - lib/Enums.js | 71 - lib/Exceptions.d.ts | 68 - lib/Exceptions.d.ts.map | 1 - lib/Exceptions.js | 137 - lib/Parser.d.ts | 19 - lib/Parser.d.ts.map | 1 - lib/Parser.js | 241 - lib/PublishContext.d.ts | 39 - lib/PublishContext.d.ts.map | 1 - lib/PublishContext.js | 272 - lib/React/SessionDescriptionHandler.d.ts | 94 - lib/React/SessionDescriptionHandler.d.ts.map | 1 - lib/React/SessionDescriptionHandler.js | 639 - .../SessionDescriptionHandlerObserver.d.ts | 11 - ...SessionDescriptionHandlerObserver.d.ts.map | 1 - .../SessionDescriptionHandlerObserver.js | 23 - lib/React/index.d.ts | 2 - lib/React/index.d.ts.map | 1 - lib/React/index.js | 4 - lib/ReferContext.d.ts | 57 - lib/ReferContext.d.ts.map | 1 - lib/ReferContext.js | 344 - lib/RegisterContext.d.ts | 40 - lib/RegisterContext.d.ts.map | 1 - lib/RegisterContext.js | 411 - lib/ServerContext.d.ts | 29 - lib/ServerContext.d.ts.map | 1 - lib/ServerContext.js | 119 - lib/Session.d.ts | 376 - lib/Session.d.ts.map | 1 - lib/Session.js | 2207 -- lib/Session/DTMF.d.ts | 26 - lib/Session/DTMF.d.ts.map | 1 - lib/Session/DTMF.js | 152 - lib/Subscription.d.ts | 128 - lib/Subscription.d.ts.map | 1 - lib/Subscription.js | 433 - lib/UA.d.ts | 230 - lib/UA.d.ts.map | 1 - lib/UA.js | 1107 - lib/Utils.d.ts | 37 - lib/Utils.d.ts.map | 1 - lib/Utils.js | 238 - lib/Web/Modifiers.d.ts | 9 - lib/Web/Modifiers.d.ts.map | 1 - lib/Web/Modifiers.js | 121 - lib/Web/SessionDescriptionHandler.d.ts | 124 - lib/Web/SessionDescriptionHandler.d.ts.map | 1 - lib/Web/SessionDescriptionHandler.js | 619 - .../SessionDescriptionHandlerObserver.d.ts | 12 - ...SessionDescriptionHandlerObserver.d.ts.map | 1 - lib/Web/SessionDescriptionHandlerObserver.js | 23 - lib/Web/Simple.d.ts | 46 - lib/Web/Simple.d.ts.map | 1 - lib/Web/Simple.js | 411 - lib/Web/Transport.d.ts | 159 - lib/Web/Transport.d.ts.map | 1 - lib/Web/Transport.js | 709 - lib/Web/index.d.ts | 6 - lib/Web/index.d.ts.map | 1 - lib/Web/index.js | 11 - lib/api/byer-bye-options.d.ts | 12 - lib/api/byer-bye-options.d.ts.map | 1 - lib/api/byer-bye-options.js | 2 - lib/api/byer-options.d.ts | 7 - lib/api/byer-options.d.ts.map | 1 - lib/api/byer-options.js | 2 - lib/api/byer.d.ts | 28 - lib/api/byer.d.ts.map | 1 - lib/api/byer.js | 58 - lib/api/dtmf.d.ts | 16 - lib/api/dtmf.d.ts.map | 1 - lib/api/dtmf.js | 35 - lib/api/emitter.d.ts | 31 - lib/api/emitter.d.ts.map | 1 - lib/api/emitter.js | 23 - lib/api/index.d.ts | 58 - lib/api/index.d.ts.map | 1 - lib/api/index.js | 24 - lib/api/info.d.ts | 17 - lib/api/info.d.ts.map | 1 - lib/api/info.js | 32 - lib/api/infoer-info-options.d.ts | 12 - lib/api/infoer-info-options.d.ts.map | 1 - lib/api/infoer-info-options.js | 2 - lib/api/infoer-options.d.ts | 7 - lib/api/infoer-options.d.ts.map | 1 - lib/api/infoer-options.js | 2 - lib/api/infoer.d.ts | 28 - lib/api/infoer.d.ts.map | 1 - lib/api/infoer.js | 43 - lib/api/invitation-accept-options.d.ts | 22 - lib/api/invitation-accept-options.d.ts.map | 1 - lib/api/invitation-accept-options.js | 2 - lib/api/invitation-progress-options.d.ts | 39 - lib/api/invitation-progress-options.d.ts.map | 1 - lib/api/invitation-progress-options.js | 2 - lib/api/invitation-reject-options.d.ts | 26 - lib/api/invitation-reject-options.d.ts.map | 1 - lib/api/invitation-reject-options.js | 2 - lib/api/invitation.d.ts | 146 - lib/api/invitation.d.ts.map | 1 - lib/api/invitation.js | 705 - lib/api/inviter-cancel-options.d.ts | 10 - lib/api/inviter-cancel-options.d.ts.map | 1 - lib/api/inviter-cancel-options.js | 2 - lib/api/inviter-invite-options.d.ts | 17 - lib/api/inviter-invite-options.d.ts.map | 1 - lib/api/inviter-invite-options.js | 2 - lib/api/inviter-options.d.ts | 46 - lib/api/inviter-options.d.ts.map | 1 - lib/api/inviter-options.js | 2 - lib/api/inviter.d.ts | 196 - lib/api/inviter.d.ts.map | 1 - lib/api/inviter.js | 987 - lib/api/message.d.ts | 17 - lib/api/message.d.ts.map | 1 - lib/api/message.js | 32 - lib/api/messager-message-options.d.ts | 12 - lib/api/messager-message-options.d.ts.map | 1 - lib/api/messager-message-options.js | 2 - lib/api/messager-options.d.ts | 18 - lib/api/messager-options.d.ts.map | 1 - lib/api/messager-options.js | 2 - lib/api/messager.d.ts | 35 - lib/api/messager.d.ts.map | 1 - lib/api/messager.js | 87 - lib/api/notification.d.ts | 17 - lib/api/notification.d.ts.map | 1 - lib/api/notification.js | 32 - lib/api/notifier.d.ts | 9 - lib/api/notifier.d.ts.map | 1 - lib/api/notifier.js | 14 - lib/api/publisher-options.d.ts | 34 - lib/api/publisher-options.d.ts.map | 1 - lib/api/publisher-options.js | 2 - lib/api/publisher-publish-options.d.ts | 7 - lib/api/publisher-publish-options.d.ts.map | 1 - lib/api/publisher-publish-options.js | 2 - lib/api/publisher-unpublish-options.d.ts | 7 - lib/api/publisher-unpublish-options.d.ts.map | 1 - lib/api/publisher-unpublish-options.js | 2 - lib/api/publisher.d.ts | 52 - lib/api/publisher.d.ts.map | 1 - lib/api/publisher.js | 273 - lib/api/referral.d.ts | 39 - lib/api/referral.d.ts.map | 1 - lib/api/referral.js | 96 - lib/api/referrer-delegate.d.ts | 10 - lib/api/referrer-delegate.d.ts.map | 1 - lib/api/referrer-delegate.js | 2 - lib/api/referrer-options.d.ts | 8 - lib/api/referrer-options.d.ts.map | 1 - lib/api/referrer-options.js | 2 - lib/api/referrer-refer-options.d.ts | 13 - lib/api/referrer-refer-options.d.ts.map | 1 - lib/api/referrer-refer-options.js | 2 - lib/api/referrer.d.ts | 36 - lib/api/referrer.d.ts.map | 1 - lib/api/referrer.js | 90 - lib/api/registerer-options.d.ts | 15 - lib/api/registerer-options.d.ts.map | 1 - lib/api/registerer-options.js | 2 - lib/api/registerer-register-options.d.ts | 12 - lib/api/registerer-register-options.d.ts.map | 1 - lib/api/registerer-register-options.js | 2 - lib/api/registerer-state.d.ts | 18 - lib/api/registerer-state.d.ts.map | 1 - lib/api/registerer-state.js | 20 - lib/api/registerer-unregister-options.d.ts | 17 - .../registerer-unregister-options.d.ts.map | 1 - lib/api/registerer-unregister-options.js | 2 - lib/api/registerer.d.ts | 84 - lib/api/registerer.d.ts.map | 1 - lib/api/registerer.js | 647 - lib/api/session-delegate.d.ts | 41 - lib/api/session-delegate.d.ts.map | 1 - lib/api/session-delegate.js | 2 - .../session-description-handler-factory.d.ts | 16 - ...ssion-description-handler-factory.d.ts.map | 1 - .../session-description-handler-factory.js | 2 - lib/api/session-description-handler.d.ts | 83 - lib/api/session-description-handler.d.ts.map | 1 - lib/api/session-description-handler.js | 3 - lib/api/session-invite-options.d.ts | 17 - lib/api/session-invite-options.d.ts.map | 1 - lib/api/session-invite-options.js | 2 - lib/api/session-options.d.ts | 9 - lib/api/session-options.d.ts.map | 1 - lib/api/session-options.js | 2 - lib/api/session-state.d.ts | 26 - lib/api/session-state.d.ts.map | 1 - lib/api/session-state.js | 28 - lib/api/session.d.ts | 430 - lib/api/session.d.ts.map | 1 - lib/api/session.js | 996 - lib/api/subscriber-options.d.ts | 12 - lib/api/subscriber-options.d.ts.map | 1 - lib/api/subscriber-options.js | 2 - lib/api/subscriber-subscribe-options.d.ts | 7 - lib/api/subscriber-subscribe-options.d.ts.map | 1 - lib/api/subscriber-subscribe-options.js | 2 - lib/api/subscriber.d.ts | 160 - lib/api/subscriber.d.ts.map | 1 - lib/api/subscriber.js | 455 - lib/api/subscription-delegate.d.ts | 13 - lib/api/subscription-delegate.d.ts.map | 1 - lib/api/subscription-delegate.js | 2 - lib/api/subscription-options.d.ts | 9 - lib/api/subscription-options.d.ts.map | 1 - lib/api/subscription-options.js | 2 - lib/api/subscription-state.d.ts | 18 - lib/api/subscription-state.d.ts.map | 1 - lib/api/subscription-state.js | 20 - lib/api/subscription-subscribe-options.d.ts | 7 - .../subscription-subscribe-options.d.ts.map | 1 - lib/api/subscription-subscribe-options.js | 2 - lib/api/subscription-unsubscribe-options.d.ts | 7 - .../subscription-unsubscribe-options.d.ts.map | 1 - lib/api/subscription-unsubscribe-options.js | 2 - lib/api/subscription.d.ts | 81 - lib/api/subscription.d.ts.map | 1 - lib/api/subscription.js | 116 - lib/api/user-agent-delegate.d.ts | 60 - lib/api/user-agent-delegate.d.ts.map | 1 - lib/api/user-agent-delegate.js | 2 - lib/api/user-agent-options.d.ts | 227 - lib/api/user-agent-options.d.ts.map | 1 - lib/api/user-agent-options.js | 53 - lib/api/user-agent-state.d.ts | 22 - lib/api/user-agent-state.d.ts.map | 1 - lib/api/user-agent-state.js | 24 - lib/api/user-agent.d.ts | 127 - lib/api/user-agent.d.ts.map | 1 - lib/api/user-agent.js | 711 - lib/core/dialogs/dialog-state.d.ts | 35 - lib/core/dialogs/dialog-state.d.ts.map | 1 - lib/core/dialogs/dialog-state.js | 2 - lib/core/dialogs/dialog.d.ts | 155 - lib/core/dialogs/dialog.d.ts.map | 1 - lib/core/dialogs/dialog.js | 562 - lib/core/dialogs/index.d.ts | 5 - lib/core/dialogs/index.d.ts.map | 1 - lib/core/dialogs/index.js | 6 - lib/core/dialogs/session-dialog.d.ts | 182 - lib/core/dialogs/session-dialog.d.ts.map | 1 - lib/core/dialogs/session-dialog.js | 823 - lib/core/dialogs/subscription-dialog.d.ts | 119 - lib/core/dialogs/subscription-dialog.d.ts.map | 1 - lib/core/dialogs/subscription-dialog.js | 494 - lib/core/exceptions/exception.d.ts | 9 - lib/core/exceptions/exception.d.ts.map | 1 - lib/core/exceptions/exception.js | 19 - lib/core/exceptions/index.d.ts | 4 - lib/core/exceptions/index.d.ts.map | 1 - lib/core/exceptions/index.js | 6 - .../exceptions/transaction-state-error.d.ts | 9 - .../transaction-state-error.d.ts.map | 1 - .../exceptions/transaction-state-error.js | 16 - lib/core/exceptions/transport-error.d.ts | 9 - lib/core/exceptions/transport-error.d.ts.map | 1 - lib/core/exceptions/transport-error.js | 16 - lib/core/index.d.ts | 16 - lib/core/index.d.ts.map | 1 - lib/core/index.js | 20 - lib/core/log/index.d.ts | 4 - lib/core/log/index.d.ts.map | 1 - lib/core/log/index.js | 6 - lib/core/log/levels.d.ts | 11 - lib/core/log/levels.d.ts.map | 1 - lib/core/log/levels.js | 13 - lib/core/log/logger-factory.d.ts | 20 - lib/core/log/logger-factory.d.ts.map | 1 - lib/core/log/logger-factory.js | 107 - lib/core/log/logger.d.ts | 17 - lib/core/log/logger.d.ts.map | 1 - lib/core/log/logger.js | 23 - lib/core/messages/body.d.ts | 65 - lib/core/messages/body.d.ts.map | 1 - lib/core/messages/body.js | 120 - lib/core/messages/digest-authentication.d.ts | 51 - .../messages/digest-authentication.d.ts.map | 1 - lib/core/messages/digest-authentication.js | 146 - lib/core/messages/grammar.d.ts | 27 - lib/core/messages/grammar.d.ts.map | 1 - lib/core/messages/grammar.js | 47 - lib/core/messages/incoming-message.d.ts | 80 - lib/core/messages/incoming-message.d.ts.map | 1 - lib/core/messages/incoming-message.js | 132 - .../messages/incoming-request-message.d.ts | 11 - .../incoming-request-message.d.ts.map | 1 - lib/core/messages/incoming-request-message.js | 16 - lib/core/messages/incoming-request.d.ts | 68 - lib/core/messages/incoming-request.d.ts.map | 1 - lib/core/messages/incoming-request.js | 2 - .../messages/incoming-response-message.d.ts | 11 - .../incoming-response-message.d.ts.map | 1 - .../messages/incoming-response-message.js | 16 - lib/core/messages/incoming-response.d.ts | 13 - lib/core/messages/incoming-response.d.ts.map | 1 - lib/core/messages/incoming-response.js | 2 - lib/core/messages/index.d.ts | 16 - lib/core/messages/index.d.ts.map | 1 - lib/core/messages/index.js | 17 - lib/core/messages/methods/ack.d.ts | 19 - lib/core/messages/methods/ack.d.ts.map | 1 - lib/core/messages/methods/ack.js | 2 - lib/core/messages/methods/bye.d.ts | 22 - lib/core/messages/methods/bye.d.ts.map | 1 - lib/core/messages/methods/bye.js | 2 - lib/core/messages/methods/cancel.d.ts | 22 - lib/core/messages/methods/cancel.d.ts.map | 1 - lib/core/messages/methods/cancel.js | 2 - lib/core/messages/methods/constants.d.ts | 21 - lib/core/messages/methods/constants.d.ts.map | 1 - lib/core/messages/methods/constants.js | 23 - lib/core/messages/methods/index.d.ts | 14 - lib/core/messages/methods/index.d.ts.map | 1 - lib/core/messages/methods/index.js | 4 - lib/core/messages/methods/info.d.ts | 22 - lib/core/messages/methods/info.d.ts.map | 1 - lib/core/messages/methods/info.js | 2 - lib/core/messages/methods/invite.d.ts | 87 - lib/core/messages/methods/invite.d.ts.map | 1 - lib/core/messages/methods/invite.js | 2 - lib/core/messages/methods/message.d.ts | 22 - lib/core/messages/methods/message.d.ts.map | 1 - lib/core/messages/methods/message.js | 2 - lib/core/messages/methods/notify.d.ts | 22 - lib/core/messages/methods/notify.d.ts.map | 1 - lib/core/messages/methods/notify.js | 2 - lib/core/messages/methods/prack.d.ts | 22 - lib/core/messages/methods/prack.d.ts.map | 1 - lib/core/messages/methods/prack.js | 2 - lib/core/messages/methods/publish.d.ts | 22 - lib/core/messages/methods/publish.d.ts.map | 1 - lib/core/messages/methods/publish.js | 2 - lib/core/messages/methods/refer.d.ts | 22 - lib/core/messages/methods/refer.d.ts.map | 1 - lib/core/messages/methods/refer.js | 2 - lib/core/messages/methods/register.d.ts | 22 - lib/core/messages/methods/register.d.ts.map | 1 - lib/core/messages/methods/register.js | 2 - lib/core/messages/methods/subscribe.d.ts | 55 - lib/core/messages/methods/subscribe.d.ts.map | 1 - lib/core/messages/methods/subscribe.js | 2 - lib/core/messages/name-addr-header.d.ts | 24 - lib/core/messages/name-addr-header.d.ts.map | 1 - lib/core/messages/name-addr-header.js | 56 - .../messages/outgoing-request-message.d.ts | 96 - .../outgoing-request-message.d.ts.map | 1 - lib/core/messages/outgoing-request-message.js | 240 - lib/core/messages/outgoing-request.d.ts | 68 - lib/core/messages/outgoing-request.d.ts.map | 1 - lib/core/messages/outgoing-request.js | 2 - lib/core/messages/outgoing-response.d.ts | 43 - lib/core/messages/outgoing-response.d.ts.map | 1 - lib/core/messages/outgoing-response.js | 129 - lib/core/messages/parameters.d.ts | 17 - lib/core/messages/parameters.d.ts.map | 1 - lib/core/messages/parameters.js | 44 - lib/core/messages/uri.d.ts | 39 - lib/core/messages/uri.d.ts.map | 1 - lib/core/messages/uri.js | 217 - lib/core/messages/utils.d.ts | 25 - lib/core/messages/utils.d.ts.map | 1 - lib/core/messages/utils.js | 145 - lib/core/session/index.d.ts | 3 - lib/core/session/index.d.ts.map | 1 - lib/core/session/index.js | 4 - lib/core/session/session-delegate.d.ts | 54 - lib/core/session/session-delegate.d.ts.map | 1 - lib/core/session/session-delegate.js | 2 - lib/core/session/session.d.ts | 127 - lib/core/session/session.d.ts.map | 1 - lib/core/session/session.js | 42 - lib/core/subscription/index.d.ts | 3 - lib/core/subscription/index.d.ts.map | 1 - lib/core/subscription/index.js | 4 - .../subscription/subscription-delegate.d.ts | 28 - .../subscription-delegate.d.ts.map | 1 - .../subscription/subscription-delegate.js | 2 - lib/core/subscription/subscription.d.ts | 56 - lib/core/subscription/subscription.d.ts.map | 1 - lib/core/subscription/subscription.js | 16 - lib/core/timers.d.ts | 21 - lib/core/timers.d.ts.map | 1 - lib/core/timers.js | 25 - lib/core/transactions/client-transaction.d.ts | 46 - .../transactions/client-transaction.d.ts.map | 1 - lib/core/transactions/client-transaction.js | 73 - lib/core/transactions/index.d.ts | 11 - lib/core/transactions/index.d.ts.map | 1 - lib/core/transactions/index.js | 12 - .../invite-client-transaction.d.ts | 117 - .../invite-client-transaction.d.ts.map | 1 - .../transactions/invite-client-transaction.js | 486 - .../invite-server-transaction.d.ts | 128 - .../invite-server-transaction.d.ts.map | 1 - .../transactions/invite-server-transaction.js | 391 - .../non-invite-client-transaction.d.ts | 70 - .../non-invite-client-transaction.d.ts.map | 1 - .../non-invite-client-transaction.js | 246 - .../non-invite-server-transaction.d.ts | 58 - .../non-invite-server-transaction.d.ts.map | 1 - .../non-invite-server-transaction.js | 231 - lib/core/transactions/server-transaction.d.ts | 36 - .../transactions/server-transaction.d.ts.map | 1 - lib/core/transactions/server-transaction.js | 34 - lib/core/transactions/transaction-state.d.ts | 14 - .../transactions/transaction-state.d.ts.map | 1 - lib/core/transactions/transaction-state.js | 16 - lib/core/transactions/transaction-user.d.ts | 73 - .../transactions/transaction-user.d.ts.map | 1 - lib/core/transactions/transaction-user.js | 2 - lib/core/transactions/transaction.d.ts | 63 - lib/core/transactions/transaction.d.ts.map | 1 - lib/core/transactions/transaction.js | 124 - lib/core/transport.d.ts | 77 - lib/core/transport.d.ts.map | 1 - lib/core/transport.js | 91 - lib/core/user-agent-core/allowed-methods.d.ts | 5 - .../user-agent-core/allowed-methods.d.ts.map | 1 - lib/core/user-agent-core/allowed-methods.js | 20 - lib/core/user-agent-core/index.d.ts | 4 - lib/core/user-agent-core/index.d.ts.map | 1 - lib/core/user-agent-core/index.js | 4 - .../user-agent-core-configuration.d.ts | 97 - .../user-agent-core-configuration.d.ts.map | 1 - .../user-agent-core-configuration.js | 2 - .../user-agent-core-delegate.d.ts | 38 - .../user-agent-core-delegate.d.ts.map | 1 - .../user-agent-core-delegate.js | 2 - lib/core/user-agent-core/user-agent-core.d.ts | 180 - .../user-agent-core/user-agent-core.d.ts.map | 1 - lib/core/user-agent-core/user-agent-core.js | 803 - .../user-agents/bye-user-agent-client.d.ts | 11 - .../bye-user-agent-client.d.ts.map | 1 - lib/core/user-agents/bye-user-agent-client.js | 22 - .../user-agents/bye-user-agent-server.d.ts | 11 - .../bye-user-agent-server.d.ts.map | 1 - lib/core/user-agents/bye-user-agent-server.js | 17 - .../user-agents/cancel-user-agent-client.d.ts | 11 - .../cancel-user-agent-client.d.ts.map | 1 - .../user-agents/cancel-user-agent-client.js | 17 - lib/core/user-agents/index.d.ts | 27 - lib/core/user-agents/index.d.ts.map | 1 - lib/core/user-agents/index.js | 29 - .../user-agents/info-user-agent-client.d.ts | 11 - .../info-user-agent-client.d.ts.map | 1 - .../user-agents/info-user-agent-client.js | 21 - .../user-agents/info-user-agent-server.d.ts | 11 - .../info-user-agent-server.d.ts.map | 1 - .../user-agents/info-user-agent-server.js | 17 - .../user-agents/invite-user-agent-client.d.ts | 30 - .../invite-user-agent-client.d.ts.map | 1 - .../user-agents/invite-user-agent-client.js | 311 - .../user-agents/invite-user-agent-server.d.ts | 78 - .../invite-user-agent-server.d.ts.map | 1 - .../user-agents/invite-user-agent-server.js | 247 - .../message-user-agent-client.d.ts | 11 - .../message-user-agent-client.d.ts.map | 1 - .../user-agents/message-user-agent-client.js | 17 - .../message-user-agent-server.d.ts | 12 - .../message-user-agent-server.d.ts.map | 1 - .../user-agents/message-user-agent-server.js | 19 - .../user-agents/notify-user-agent-client.d.ts | 11 - .../notify-user-agent-client.d.ts.map | 1 - .../user-agents/notify-user-agent-client.js | 21 - .../user-agents/notify-user-agent-server.d.ts | 17 - .../notify-user-agent-server.d.ts.map | 1 - .../user-agents/notify-user-agent-server.js | 30 - .../user-agents/prack-user-agent-client.d.ts | 11 - .../prack-user-agent-client.d.ts.map | 1 - .../user-agents/prack-user-agent-client.js | 22 - .../user-agents/prack-user-agent-server.d.ts | 17 - .../prack-user-agent-server.d.ts.map | 1 - .../user-agents/prack-user-agent-server.js | 33 - .../publish-user-agent-client.d.ts | 11 - .../publish-user-agent-client.d.ts.map | 1 - .../user-agents/publish-user-agent-client.js | 17 - .../re-invite-user-agent-client.d.ts | 19 - .../re-invite-user-agent-client.d.ts.map | 1 - .../re-invite-user-agent-client.js | 113 - .../re-invite-user-agent-server.d.ts | 42 - .../re-invite-user-agent-server.d.ts.map | 1 - .../re-invite-user-agent-server.js | 96 - .../re-subscribe-user-agent-client.d.ts | 18 - .../re-subscribe-user-agent-client.d.ts.map | 1 - .../re-subscribe-user-agent-client.js | 73 - .../re-subscribe-user-agent-server.d.ts | 11 - .../re-subscribe-user-agent-server.d.ts.map | 1 - .../re-subscribe-user-agent-server.js | 17 - .../user-agents/refer-user-agent-client.d.ts | 11 - .../refer-user-agent-client.d.ts.map | 1 - .../user-agents/refer-user-agent-client.js | 21 - .../user-agents/refer-user-agent-server.d.ts | 17 - .../refer-user-agent-server.d.ts.map | 1 - .../user-agents/refer-user-agent-server.js | 30 - .../register-user-agent-client.d.ts | 11 - .../register-user-agent-client.d.ts.map | 1 - .../user-agents/register-user-agent-client.js | 17 - .../register-user-agent-server.d.ts | 12 - .../register-user-agent-server.d.ts.map | 1 - .../user-agents/register-user-agent-server.js | 19 - .../subscribe-user-agent-client.d.ts | 66 - .../subscribe-user-agent-client.d.ts.map | 1 - .../subscribe-user-agent-client.js | 297 - .../subscribe-user-agent-server.d.ts | 12 - .../subscribe-user-agent-server.d.ts.map | 1 - .../subscribe-user-agent-server.js | 19 - lib/core/user-agents/user-agent-client.d.ts | 100 - .../user-agents/user-agent-client.d.ts.map | 1 - lib/core/user-agents/user-agent-client.js | 313 - lib/core/user-agents/user-agent-server.d.ts | 80 - .../user-agents/user-agent-server.d.ts.map | 1 - lib/core/user-agents/user-agent-server.js | 261 - lib/grammar/dist/grammar.d.ts | 51 - lib/grammar/dist/grammar.d.ts.map | 1 - lib/grammar/dist/grammar.js | 1508 -- lib/index.d.ts | 33 - lib/index.d.ts.map | 1 - lib/index.js | 63 - lib/session-description-handler-factory.d.ts | 15 - ...ssion-description-handler-factory.d.ts.map | 1 - lib/session-description-handler-factory.js | 2 - lib/session-description-handler.d.ts | 71 - lib/session-description-handler.d.ts.map | 1 - lib/session-description-handler.js | 3 - lib/version.d.ts | 2 - lib/version.d.ts.map | 1 - lib/version.js | 3 - 548 files changed, 107512 deletions(-) delete mode 100644 dist/sip-0.15.5.js delete mode 100644 dist/sip-0.15.5.min.js delete mode 100644 dist/sip-api.js delete mode 100644 dist/sip-api.min.js delete mode 100644 dist/sip-core.js delete mode 100644 dist/sip-core.min.js delete mode 100644 dist/sip.js delete mode 100644 dist/sip.min.js delete mode 100644 lib/ClientContext.d.ts delete mode 100644 lib/ClientContext.d.ts.map delete mode 100644 lib/ClientContext.js delete mode 100644 lib/Constants.d.ts delete mode 100644 lib/Constants.d.ts.map delete mode 100644 lib/Constants.js delete mode 100644 lib/Enums.d.ts delete mode 100644 lib/Enums.d.ts.map delete mode 100644 lib/Enums.js delete mode 100644 lib/Exceptions.d.ts delete mode 100644 lib/Exceptions.d.ts.map delete mode 100644 lib/Exceptions.js delete mode 100644 lib/Parser.d.ts delete mode 100644 lib/Parser.d.ts.map delete mode 100644 lib/Parser.js delete mode 100644 lib/PublishContext.d.ts delete mode 100644 lib/PublishContext.d.ts.map delete mode 100644 lib/PublishContext.js delete mode 100644 lib/React/SessionDescriptionHandler.d.ts delete mode 100644 lib/React/SessionDescriptionHandler.d.ts.map delete mode 100644 lib/React/SessionDescriptionHandler.js delete mode 100644 lib/React/SessionDescriptionHandlerObserver.d.ts delete mode 100644 lib/React/SessionDescriptionHandlerObserver.d.ts.map delete mode 100644 lib/React/SessionDescriptionHandlerObserver.js delete mode 100644 lib/React/index.d.ts delete mode 100644 lib/React/index.d.ts.map delete mode 100644 lib/React/index.js delete mode 100644 lib/ReferContext.d.ts delete mode 100644 lib/ReferContext.d.ts.map delete mode 100644 lib/ReferContext.js delete mode 100644 lib/RegisterContext.d.ts delete mode 100644 lib/RegisterContext.d.ts.map delete mode 100644 lib/RegisterContext.js delete mode 100644 lib/ServerContext.d.ts delete mode 100644 lib/ServerContext.d.ts.map delete mode 100644 lib/ServerContext.js delete mode 100644 lib/Session.d.ts delete mode 100644 lib/Session.d.ts.map delete mode 100644 lib/Session.js delete mode 100644 lib/Session/DTMF.d.ts delete mode 100644 lib/Session/DTMF.d.ts.map delete mode 100644 lib/Session/DTMF.js delete mode 100644 lib/Subscription.d.ts delete mode 100644 lib/Subscription.d.ts.map delete mode 100644 lib/Subscription.js delete mode 100644 lib/UA.d.ts delete mode 100644 lib/UA.d.ts.map delete mode 100644 lib/UA.js delete mode 100644 lib/Utils.d.ts delete mode 100644 lib/Utils.d.ts.map delete mode 100644 lib/Utils.js delete mode 100644 lib/Web/Modifiers.d.ts delete mode 100644 lib/Web/Modifiers.d.ts.map delete mode 100644 lib/Web/Modifiers.js delete mode 100644 lib/Web/SessionDescriptionHandler.d.ts delete mode 100644 lib/Web/SessionDescriptionHandler.d.ts.map delete mode 100644 lib/Web/SessionDescriptionHandler.js delete mode 100644 lib/Web/SessionDescriptionHandlerObserver.d.ts delete mode 100644 lib/Web/SessionDescriptionHandlerObserver.d.ts.map delete mode 100644 lib/Web/SessionDescriptionHandlerObserver.js delete mode 100644 lib/Web/Simple.d.ts delete mode 100644 lib/Web/Simple.d.ts.map delete mode 100644 lib/Web/Simple.js delete mode 100644 lib/Web/Transport.d.ts delete mode 100644 lib/Web/Transport.d.ts.map delete mode 100644 lib/Web/Transport.js delete mode 100644 lib/Web/index.d.ts delete mode 100644 lib/Web/index.d.ts.map delete mode 100644 lib/Web/index.js delete mode 100644 lib/api/byer-bye-options.d.ts delete mode 100644 lib/api/byer-bye-options.d.ts.map delete mode 100644 lib/api/byer-bye-options.js delete mode 100644 lib/api/byer-options.d.ts delete mode 100644 lib/api/byer-options.d.ts.map delete mode 100644 lib/api/byer-options.js delete mode 100644 lib/api/byer.d.ts delete mode 100644 lib/api/byer.d.ts.map delete mode 100644 lib/api/byer.js delete mode 100644 lib/api/dtmf.d.ts delete mode 100644 lib/api/dtmf.d.ts.map delete mode 100644 lib/api/dtmf.js delete mode 100644 lib/api/emitter.d.ts delete mode 100644 lib/api/emitter.d.ts.map delete mode 100644 lib/api/emitter.js delete mode 100644 lib/api/index.d.ts delete mode 100644 lib/api/index.d.ts.map delete mode 100644 lib/api/index.js delete mode 100644 lib/api/info.d.ts delete mode 100644 lib/api/info.d.ts.map delete mode 100644 lib/api/info.js delete mode 100644 lib/api/infoer-info-options.d.ts delete mode 100644 lib/api/infoer-info-options.d.ts.map delete mode 100644 lib/api/infoer-info-options.js delete mode 100644 lib/api/infoer-options.d.ts delete mode 100644 lib/api/infoer-options.d.ts.map delete mode 100644 lib/api/infoer-options.js delete mode 100644 lib/api/infoer.d.ts delete mode 100644 lib/api/infoer.d.ts.map delete mode 100644 lib/api/infoer.js delete mode 100644 lib/api/invitation-accept-options.d.ts delete mode 100644 lib/api/invitation-accept-options.d.ts.map delete mode 100644 lib/api/invitation-accept-options.js delete mode 100644 lib/api/invitation-progress-options.d.ts delete mode 100644 lib/api/invitation-progress-options.d.ts.map delete mode 100644 lib/api/invitation-progress-options.js delete mode 100644 lib/api/invitation-reject-options.d.ts delete mode 100644 lib/api/invitation-reject-options.d.ts.map delete mode 100644 lib/api/invitation-reject-options.js delete mode 100644 lib/api/invitation.d.ts delete mode 100644 lib/api/invitation.d.ts.map delete mode 100644 lib/api/invitation.js delete mode 100644 lib/api/inviter-cancel-options.d.ts delete mode 100644 lib/api/inviter-cancel-options.d.ts.map delete mode 100644 lib/api/inviter-cancel-options.js delete mode 100644 lib/api/inviter-invite-options.d.ts delete mode 100644 lib/api/inviter-invite-options.d.ts.map delete mode 100644 lib/api/inviter-invite-options.js delete mode 100644 lib/api/inviter-options.d.ts delete mode 100644 lib/api/inviter-options.d.ts.map delete mode 100644 lib/api/inviter-options.js delete mode 100644 lib/api/inviter.d.ts delete mode 100644 lib/api/inviter.d.ts.map delete mode 100644 lib/api/inviter.js delete mode 100644 lib/api/message.d.ts delete mode 100644 lib/api/message.d.ts.map delete mode 100644 lib/api/message.js delete mode 100644 lib/api/messager-message-options.d.ts delete mode 100644 lib/api/messager-message-options.d.ts.map delete mode 100644 lib/api/messager-message-options.js delete mode 100644 lib/api/messager-options.d.ts delete mode 100644 lib/api/messager-options.d.ts.map delete mode 100644 lib/api/messager-options.js delete mode 100644 lib/api/messager.d.ts delete mode 100644 lib/api/messager.d.ts.map delete mode 100644 lib/api/messager.js delete mode 100644 lib/api/notification.d.ts delete mode 100644 lib/api/notification.d.ts.map delete mode 100644 lib/api/notification.js delete mode 100644 lib/api/notifier.d.ts delete mode 100644 lib/api/notifier.d.ts.map delete mode 100644 lib/api/notifier.js delete mode 100644 lib/api/publisher-options.d.ts delete mode 100644 lib/api/publisher-options.d.ts.map delete mode 100644 lib/api/publisher-options.js delete mode 100644 lib/api/publisher-publish-options.d.ts delete mode 100644 lib/api/publisher-publish-options.d.ts.map delete mode 100644 lib/api/publisher-publish-options.js delete mode 100644 lib/api/publisher-unpublish-options.d.ts delete mode 100644 lib/api/publisher-unpublish-options.d.ts.map delete mode 100644 lib/api/publisher-unpublish-options.js delete mode 100644 lib/api/publisher.d.ts delete mode 100644 lib/api/publisher.d.ts.map delete mode 100644 lib/api/publisher.js delete mode 100644 lib/api/referral.d.ts delete mode 100644 lib/api/referral.d.ts.map delete mode 100644 lib/api/referral.js delete mode 100644 lib/api/referrer-delegate.d.ts delete mode 100644 lib/api/referrer-delegate.d.ts.map delete mode 100644 lib/api/referrer-delegate.js delete mode 100644 lib/api/referrer-options.d.ts delete mode 100644 lib/api/referrer-options.d.ts.map delete mode 100644 lib/api/referrer-options.js delete mode 100644 lib/api/referrer-refer-options.d.ts delete mode 100644 lib/api/referrer-refer-options.d.ts.map delete mode 100644 lib/api/referrer-refer-options.js delete mode 100644 lib/api/referrer.d.ts delete mode 100644 lib/api/referrer.d.ts.map delete mode 100644 lib/api/referrer.js delete mode 100644 lib/api/registerer-options.d.ts delete mode 100644 lib/api/registerer-options.d.ts.map delete mode 100644 lib/api/registerer-options.js delete mode 100644 lib/api/registerer-register-options.d.ts delete mode 100644 lib/api/registerer-register-options.d.ts.map delete mode 100644 lib/api/registerer-register-options.js delete mode 100644 lib/api/registerer-state.d.ts delete mode 100644 lib/api/registerer-state.d.ts.map delete mode 100644 lib/api/registerer-state.js delete mode 100644 lib/api/registerer-unregister-options.d.ts delete mode 100644 lib/api/registerer-unregister-options.d.ts.map delete mode 100644 lib/api/registerer-unregister-options.js delete mode 100644 lib/api/registerer.d.ts delete mode 100644 lib/api/registerer.d.ts.map delete mode 100644 lib/api/registerer.js delete mode 100644 lib/api/session-delegate.d.ts delete mode 100644 lib/api/session-delegate.d.ts.map delete mode 100644 lib/api/session-delegate.js delete mode 100644 lib/api/session-description-handler-factory.d.ts delete mode 100644 lib/api/session-description-handler-factory.d.ts.map delete mode 100644 lib/api/session-description-handler-factory.js delete mode 100644 lib/api/session-description-handler.d.ts delete mode 100644 lib/api/session-description-handler.d.ts.map delete mode 100644 lib/api/session-description-handler.js delete mode 100644 lib/api/session-invite-options.d.ts delete mode 100644 lib/api/session-invite-options.d.ts.map delete mode 100644 lib/api/session-invite-options.js delete mode 100644 lib/api/session-options.d.ts delete mode 100644 lib/api/session-options.d.ts.map delete mode 100644 lib/api/session-options.js delete mode 100644 lib/api/session-state.d.ts delete mode 100644 lib/api/session-state.d.ts.map delete mode 100644 lib/api/session-state.js delete mode 100644 lib/api/session.d.ts delete mode 100644 lib/api/session.d.ts.map delete mode 100644 lib/api/session.js delete mode 100644 lib/api/subscriber-options.d.ts delete mode 100644 lib/api/subscriber-options.d.ts.map delete mode 100644 lib/api/subscriber-options.js delete mode 100644 lib/api/subscriber-subscribe-options.d.ts delete mode 100644 lib/api/subscriber-subscribe-options.d.ts.map delete mode 100644 lib/api/subscriber-subscribe-options.js delete mode 100644 lib/api/subscriber.d.ts delete mode 100644 lib/api/subscriber.d.ts.map delete mode 100644 lib/api/subscriber.js delete mode 100644 lib/api/subscription-delegate.d.ts delete mode 100644 lib/api/subscription-delegate.d.ts.map delete mode 100644 lib/api/subscription-delegate.js delete mode 100644 lib/api/subscription-options.d.ts delete mode 100644 lib/api/subscription-options.d.ts.map delete mode 100644 lib/api/subscription-options.js delete mode 100644 lib/api/subscription-state.d.ts delete mode 100644 lib/api/subscription-state.d.ts.map delete mode 100644 lib/api/subscription-state.js delete mode 100644 lib/api/subscription-subscribe-options.d.ts delete mode 100644 lib/api/subscription-subscribe-options.d.ts.map delete mode 100644 lib/api/subscription-subscribe-options.js delete mode 100644 lib/api/subscription-unsubscribe-options.d.ts delete mode 100644 lib/api/subscription-unsubscribe-options.d.ts.map delete mode 100644 lib/api/subscription-unsubscribe-options.js delete mode 100644 lib/api/subscription.d.ts delete mode 100644 lib/api/subscription.d.ts.map delete mode 100644 lib/api/subscription.js delete mode 100644 lib/api/user-agent-delegate.d.ts delete mode 100644 lib/api/user-agent-delegate.d.ts.map delete mode 100644 lib/api/user-agent-delegate.js delete mode 100644 lib/api/user-agent-options.d.ts delete mode 100644 lib/api/user-agent-options.d.ts.map delete mode 100644 lib/api/user-agent-options.js delete mode 100644 lib/api/user-agent-state.d.ts delete mode 100644 lib/api/user-agent-state.d.ts.map delete mode 100644 lib/api/user-agent-state.js delete mode 100644 lib/api/user-agent.d.ts delete mode 100644 lib/api/user-agent.d.ts.map delete mode 100644 lib/api/user-agent.js delete mode 100644 lib/core/dialogs/dialog-state.d.ts delete mode 100644 lib/core/dialogs/dialog-state.d.ts.map delete mode 100644 lib/core/dialogs/dialog-state.js delete mode 100644 lib/core/dialogs/dialog.d.ts delete mode 100644 lib/core/dialogs/dialog.d.ts.map delete mode 100644 lib/core/dialogs/dialog.js delete mode 100644 lib/core/dialogs/index.d.ts delete mode 100644 lib/core/dialogs/index.d.ts.map delete mode 100644 lib/core/dialogs/index.js delete mode 100644 lib/core/dialogs/session-dialog.d.ts delete mode 100644 lib/core/dialogs/session-dialog.d.ts.map delete mode 100644 lib/core/dialogs/session-dialog.js delete mode 100644 lib/core/dialogs/subscription-dialog.d.ts delete mode 100644 lib/core/dialogs/subscription-dialog.d.ts.map delete mode 100644 lib/core/dialogs/subscription-dialog.js delete mode 100644 lib/core/exceptions/exception.d.ts delete mode 100644 lib/core/exceptions/exception.d.ts.map delete mode 100644 lib/core/exceptions/exception.js delete mode 100644 lib/core/exceptions/index.d.ts delete mode 100644 lib/core/exceptions/index.d.ts.map delete mode 100644 lib/core/exceptions/index.js delete mode 100644 lib/core/exceptions/transaction-state-error.d.ts delete mode 100644 lib/core/exceptions/transaction-state-error.d.ts.map delete mode 100644 lib/core/exceptions/transaction-state-error.js delete mode 100644 lib/core/exceptions/transport-error.d.ts delete mode 100644 lib/core/exceptions/transport-error.d.ts.map delete mode 100644 lib/core/exceptions/transport-error.js delete mode 100644 lib/core/index.d.ts delete mode 100644 lib/core/index.d.ts.map delete mode 100644 lib/core/index.js delete mode 100644 lib/core/log/index.d.ts delete mode 100644 lib/core/log/index.d.ts.map delete mode 100644 lib/core/log/index.js delete mode 100644 lib/core/log/levels.d.ts delete mode 100644 lib/core/log/levels.d.ts.map delete mode 100644 lib/core/log/levels.js delete mode 100644 lib/core/log/logger-factory.d.ts delete mode 100644 lib/core/log/logger-factory.d.ts.map delete mode 100644 lib/core/log/logger-factory.js delete mode 100644 lib/core/log/logger.d.ts delete mode 100644 lib/core/log/logger.d.ts.map delete mode 100644 lib/core/log/logger.js delete mode 100644 lib/core/messages/body.d.ts delete mode 100644 lib/core/messages/body.d.ts.map delete mode 100644 lib/core/messages/body.js delete mode 100644 lib/core/messages/digest-authentication.d.ts delete mode 100644 lib/core/messages/digest-authentication.d.ts.map delete mode 100644 lib/core/messages/digest-authentication.js delete mode 100644 lib/core/messages/grammar.d.ts delete mode 100644 lib/core/messages/grammar.d.ts.map delete mode 100644 lib/core/messages/grammar.js delete mode 100644 lib/core/messages/incoming-message.d.ts delete mode 100644 lib/core/messages/incoming-message.d.ts.map delete mode 100644 lib/core/messages/incoming-message.js delete mode 100644 lib/core/messages/incoming-request-message.d.ts delete mode 100644 lib/core/messages/incoming-request-message.d.ts.map delete mode 100644 lib/core/messages/incoming-request-message.js delete mode 100644 lib/core/messages/incoming-request.d.ts delete mode 100644 lib/core/messages/incoming-request.d.ts.map delete mode 100644 lib/core/messages/incoming-request.js delete mode 100644 lib/core/messages/incoming-response-message.d.ts delete mode 100644 lib/core/messages/incoming-response-message.d.ts.map delete mode 100644 lib/core/messages/incoming-response-message.js delete mode 100644 lib/core/messages/incoming-response.d.ts delete mode 100644 lib/core/messages/incoming-response.d.ts.map delete mode 100644 lib/core/messages/incoming-response.js delete mode 100644 lib/core/messages/index.d.ts delete mode 100644 lib/core/messages/index.d.ts.map delete mode 100644 lib/core/messages/index.js delete mode 100644 lib/core/messages/methods/ack.d.ts delete mode 100644 lib/core/messages/methods/ack.d.ts.map delete mode 100644 lib/core/messages/methods/ack.js delete mode 100644 lib/core/messages/methods/bye.d.ts delete mode 100644 lib/core/messages/methods/bye.d.ts.map delete mode 100644 lib/core/messages/methods/bye.js delete mode 100644 lib/core/messages/methods/cancel.d.ts delete mode 100644 lib/core/messages/methods/cancel.d.ts.map delete mode 100644 lib/core/messages/methods/cancel.js delete mode 100644 lib/core/messages/methods/constants.d.ts delete mode 100644 lib/core/messages/methods/constants.d.ts.map delete mode 100644 lib/core/messages/methods/constants.js delete mode 100644 lib/core/messages/methods/index.d.ts delete mode 100644 lib/core/messages/methods/index.d.ts.map delete mode 100644 lib/core/messages/methods/index.js delete mode 100644 lib/core/messages/methods/info.d.ts delete mode 100644 lib/core/messages/methods/info.d.ts.map delete mode 100644 lib/core/messages/methods/info.js delete mode 100644 lib/core/messages/methods/invite.d.ts delete mode 100644 lib/core/messages/methods/invite.d.ts.map delete mode 100644 lib/core/messages/methods/invite.js delete mode 100644 lib/core/messages/methods/message.d.ts delete mode 100644 lib/core/messages/methods/message.d.ts.map delete mode 100644 lib/core/messages/methods/message.js delete mode 100644 lib/core/messages/methods/notify.d.ts delete mode 100644 lib/core/messages/methods/notify.d.ts.map delete mode 100644 lib/core/messages/methods/notify.js delete mode 100644 lib/core/messages/methods/prack.d.ts delete mode 100644 lib/core/messages/methods/prack.d.ts.map delete mode 100644 lib/core/messages/methods/prack.js delete mode 100644 lib/core/messages/methods/publish.d.ts delete mode 100644 lib/core/messages/methods/publish.d.ts.map delete mode 100644 lib/core/messages/methods/publish.js delete mode 100644 lib/core/messages/methods/refer.d.ts delete mode 100644 lib/core/messages/methods/refer.d.ts.map delete mode 100644 lib/core/messages/methods/refer.js delete mode 100644 lib/core/messages/methods/register.d.ts delete mode 100644 lib/core/messages/methods/register.d.ts.map delete mode 100644 lib/core/messages/methods/register.js delete mode 100644 lib/core/messages/methods/subscribe.d.ts delete mode 100644 lib/core/messages/methods/subscribe.d.ts.map delete mode 100644 lib/core/messages/methods/subscribe.js delete mode 100644 lib/core/messages/name-addr-header.d.ts delete mode 100644 lib/core/messages/name-addr-header.d.ts.map delete mode 100644 lib/core/messages/name-addr-header.js delete mode 100644 lib/core/messages/outgoing-request-message.d.ts delete mode 100644 lib/core/messages/outgoing-request-message.d.ts.map delete mode 100644 lib/core/messages/outgoing-request-message.js delete mode 100644 lib/core/messages/outgoing-request.d.ts delete mode 100644 lib/core/messages/outgoing-request.d.ts.map delete mode 100644 lib/core/messages/outgoing-request.js delete mode 100644 lib/core/messages/outgoing-response.d.ts delete mode 100644 lib/core/messages/outgoing-response.d.ts.map delete mode 100644 lib/core/messages/outgoing-response.js delete mode 100644 lib/core/messages/parameters.d.ts delete mode 100644 lib/core/messages/parameters.d.ts.map delete mode 100644 lib/core/messages/parameters.js delete mode 100644 lib/core/messages/uri.d.ts delete mode 100644 lib/core/messages/uri.d.ts.map delete mode 100644 lib/core/messages/uri.js delete mode 100644 lib/core/messages/utils.d.ts delete mode 100644 lib/core/messages/utils.d.ts.map delete mode 100644 lib/core/messages/utils.js delete mode 100644 lib/core/session/index.d.ts delete mode 100644 lib/core/session/index.d.ts.map delete mode 100644 lib/core/session/index.js delete mode 100644 lib/core/session/session-delegate.d.ts delete mode 100644 lib/core/session/session-delegate.d.ts.map delete mode 100644 lib/core/session/session-delegate.js delete mode 100644 lib/core/session/session.d.ts delete mode 100644 lib/core/session/session.d.ts.map delete mode 100644 lib/core/session/session.js delete mode 100644 lib/core/subscription/index.d.ts delete mode 100644 lib/core/subscription/index.d.ts.map delete mode 100644 lib/core/subscription/index.js delete mode 100644 lib/core/subscription/subscription-delegate.d.ts delete mode 100644 lib/core/subscription/subscription-delegate.d.ts.map delete mode 100644 lib/core/subscription/subscription-delegate.js delete mode 100644 lib/core/subscription/subscription.d.ts delete mode 100644 lib/core/subscription/subscription.d.ts.map delete mode 100644 lib/core/subscription/subscription.js delete mode 100644 lib/core/timers.d.ts delete mode 100644 lib/core/timers.d.ts.map delete mode 100644 lib/core/timers.js delete mode 100644 lib/core/transactions/client-transaction.d.ts delete mode 100644 lib/core/transactions/client-transaction.d.ts.map delete mode 100644 lib/core/transactions/client-transaction.js delete mode 100644 lib/core/transactions/index.d.ts delete mode 100644 lib/core/transactions/index.d.ts.map delete mode 100644 lib/core/transactions/index.js delete mode 100644 lib/core/transactions/invite-client-transaction.d.ts delete mode 100644 lib/core/transactions/invite-client-transaction.d.ts.map delete mode 100644 lib/core/transactions/invite-client-transaction.js delete mode 100644 lib/core/transactions/invite-server-transaction.d.ts delete mode 100644 lib/core/transactions/invite-server-transaction.d.ts.map delete mode 100644 lib/core/transactions/invite-server-transaction.js delete mode 100644 lib/core/transactions/non-invite-client-transaction.d.ts delete mode 100644 lib/core/transactions/non-invite-client-transaction.d.ts.map delete mode 100644 lib/core/transactions/non-invite-client-transaction.js delete mode 100644 lib/core/transactions/non-invite-server-transaction.d.ts delete mode 100644 lib/core/transactions/non-invite-server-transaction.d.ts.map delete mode 100644 lib/core/transactions/non-invite-server-transaction.js delete mode 100644 lib/core/transactions/server-transaction.d.ts delete mode 100644 lib/core/transactions/server-transaction.d.ts.map delete mode 100644 lib/core/transactions/server-transaction.js delete mode 100644 lib/core/transactions/transaction-state.d.ts delete mode 100644 lib/core/transactions/transaction-state.d.ts.map delete mode 100644 lib/core/transactions/transaction-state.js delete mode 100644 lib/core/transactions/transaction-user.d.ts delete mode 100644 lib/core/transactions/transaction-user.d.ts.map delete mode 100644 lib/core/transactions/transaction-user.js delete mode 100644 lib/core/transactions/transaction.d.ts delete mode 100644 lib/core/transactions/transaction.d.ts.map delete mode 100644 lib/core/transactions/transaction.js delete mode 100644 lib/core/transport.d.ts delete mode 100644 lib/core/transport.d.ts.map delete mode 100644 lib/core/transport.js delete mode 100644 lib/core/user-agent-core/allowed-methods.d.ts delete mode 100644 lib/core/user-agent-core/allowed-methods.d.ts.map delete mode 100644 lib/core/user-agent-core/allowed-methods.js delete mode 100644 lib/core/user-agent-core/index.d.ts delete mode 100644 lib/core/user-agent-core/index.d.ts.map delete mode 100644 lib/core/user-agent-core/index.js delete mode 100644 lib/core/user-agent-core/user-agent-core-configuration.d.ts delete mode 100644 lib/core/user-agent-core/user-agent-core-configuration.d.ts.map delete mode 100644 lib/core/user-agent-core/user-agent-core-configuration.js delete mode 100644 lib/core/user-agent-core/user-agent-core-delegate.d.ts delete mode 100644 lib/core/user-agent-core/user-agent-core-delegate.d.ts.map delete mode 100644 lib/core/user-agent-core/user-agent-core-delegate.js delete mode 100644 lib/core/user-agent-core/user-agent-core.d.ts delete mode 100644 lib/core/user-agent-core/user-agent-core.d.ts.map delete mode 100644 lib/core/user-agent-core/user-agent-core.js delete mode 100644 lib/core/user-agents/bye-user-agent-client.d.ts delete mode 100644 lib/core/user-agents/bye-user-agent-client.d.ts.map delete mode 100644 lib/core/user-agents/bye-user-agent-client.js delete mode 100644 lib/core/user-agents/bye-user-agent-server.d.ts delete mode 100644 lib/core/user-agents/bye-user-agent-server.d.ts.map delete mode 100644 lib/core/user-agents/bye-user-agent-server.js delete mode 100644 lib/core/user-agents/cancel-user-agent-client.d.ts delete mode 100644 lib/core/user-agents/cancel-user-agent-client.d.ts.map delete mode 100644 lib/core/user-agents/cancel-user-agent-client.js delete mode 100644 lib/core/user-agents/index.d.ts delete mode 100644 lib/core/user-agents/index.d.ts.map delete mode 100644 lib/core/user-agents/index.js delete mode 100644 lib/core/user-agents/info-user-agent-client.d.ts delete mode 100644 lib/core/user-agents/info-user-agent-client.d.ts.map delete mode 100644 lib/core/user-agents/info-user-agent-client.js delete mode 100644 lib/core/user-agents/info-user-agent-server.d.ts delete mode 100644 lib/core/user-agents/info-user-agent-server.d.ts.map delete mode 100644 lib/core/user-agents/info-user-agent-server.js delete mode 100644 lib/core/user-agents/invite-user-agent-client.d.ts delete mode 100644 lib/core/user-agents/invite-user-agent-client.d.ts.map delete mode 100644 lib/core/user-agents/invite-user-agent-client.js delete mode 100644 lib/core/user-agents/invite-user-agent-server.d.ts delete mode 100644 lib/core/user-agents/invite-user-agent-server.d.ts.map delete mode 100644 lib/core/user-agents/invite-user-agent-server.js delete mode 100644 lib/core/user-agents/message-user-agent-client.d.ts delete mode 100644 lib/core/user-agents/message-user-agent-client.d.ts.map delete mode 100644 lib/core/user-agents/message-user-agent-client.js delete mode 100644 lib/core/user-agents/message-user-agent-server.d.ts delete mode 100644 lib/core/user-agents/message-user-agent-server.d.ts.map delete mode 100644 lib/core/user-agents/message-user-agent-server.js delete mode 100644 lib/core/user-agents/notify-user-agent-client.d.ts delete mode 100644 lib/core/user-agents/notify-user-agent-client.d.ts.map delete mode 100644 lib/core/user-agents/notify-user-agent-client.js delete mode 100644 lib/core/user-agents/notify-user-agent-server.d.ts delete mode 100644 lib/core/user-agents/notify-user-agent-server.d.ts.map delete mode 100644 lib/core/user-agents/notify-user-agent-server.js delete mode 100644 lib/core/user-agents/prack-user-agent-client.d.ts delete mode 100644 lib/core/user-agents/prack-user-agent-client.d.ts.map delete mode 100644 lib/core/user-agents/prack-user-agent-client.js delete mode 100644 lib/core/user-agents/prack-user-agent-server.d.ts delete mode 100644 lib/core/user-agents/prack-user-agent-server.d.ts.map delete mode 100644 lib/core/user-agents/prack-user-agent-server.js delete mode 100644 lib/core/user-agents/publish-user-agent-client.d.ts delete mode 100644 lib/core/user-agents/publish-user-agent-client.d.ts.map delete mode 100644 lib/core/user-agents/publish-user-agent-client.js delete mode 100644 lib/core/user-agents/re-invite-user-agent-client.d.ts delete mode 100644 lib/core/user-agents/re-invite-user-agent-client.d.ts.map delete mode 100644 lib/core/user-agents/re-invite-user-agent-client.js delete mode 100644 lib/core/user-agents/re-invite-user-agent-server.d.ts delete mode 100644 lib/core/user-agents/re-invite-user-agent-server.d.ts.map delete mode 100644 lib/core/user-agents/re-invite-user-agent-server.js delete mode 100644 lib/core/user-agents/re-subscribe-user-agent-client.d.ts delete mode 100644 lib/core/user-agents/re-subscribe-user-agent-client.d.ts.map delete mode 100644 lib/core/user-agents/re-subscribe-user-agent-client.js delete mode 100644 lib/core/user-agents/re-subscribe-user-agent-server.d.ts delete mode 100644 lib/core/user-agents/re-subscribe-user-agent-server.d.ts.map delete mode 100644 lib/core/user-agents/re-subscribe-user-agent-server.js delete mode 100644 lib/core/user-agents/refer-user-agent-client.d.ts delete mode 100644 lib/core/user-agents/refer-user-agent-client.d.ts.map delete mode 100644 lib/core/user-agents/refer-user-agent-client.js delete mode 100644 lib/core/user-agents/refer-user-agent-server.d.ts delete mode 100644 lib/core/user-agents/refer-user-agent-server.d.ts.map delete mode 100644 lib/core/user-agents/refer-user-agent-server.js delete mode 100644 lib/core/user-agents/register-user-agent-client.d.ts delete mode 100644 lib/core/user-agents/register-user-agent-client.d.ts.map delete mode 100644 lib/core/user-agents/register-user-agent-client.js delete mode 100644 lib/core/user-agents/register-user-agent-server.d.ts delete mode 100644 lib/core/user-agents/register-user-agent-server.d.ts.map delete mode 100644 lib/core/user-agents/register-user-agent-server.js delete mode 100644 lib/core/user-agents/subscribe-user-agent-client.d.ts delete mode 100644 lib/core/user-agents/subscribe-user-agent-client.d.ts.map delete mode 100644 lib/core/user-agents/subscribe-user-agent-client.js delete mode 100644 lib/core/user-agents/subscribe-user-agent-server.d.ts delete mode 100644 lib/core/user-agents/subscribe-user-agent-server.d.ts.map delete mode 100644 lib/core/user-agents/subscribe-user-agent-server.js delete mode 100644 lib/core/user-agents/user-agent-client.d.ts delete mode 100644 lib/core/user-agents/user-agent-client.d.ts.map delete mode 100644 lib/core/user-agents/user-agent-client.js delete mode 100644 lib/core/user-agents/user-agent-server.d.ts delete mode 100644 lib/core/user-agents/user-agent-server.d.ts.map delete mode 100644 lib/core/user-agents/user-agent-server.js delete mode 100644 lib/grammar/dist/grammar.d.ts delete mode 100644 lib/grammar/dist/grammar.d.ts.map delete mode 100644 lib/grammar/dist/grammar.js delete mode 100644 lib/index.d.ts delete mode 100644 lib/index.d.ts.map delete mode 100644 lib/index.js delete mode 100644 lib/session-description-handler-factory.d.ts delete mode 100644 lib/session-description-handler-factory.d.ts.map delete mode 100644 lib/session-description-handler-factory.js delete mode 100644 lib/session-description-handler.d.ts delete mode 100644 lib/session-description-handler.d.ts.map delete mode 100644 lib/session-description-handler.js delete mode 100644 lib/version.d.ts delete mode 100644 lib/version.d.ts.map delete mode 100644 lib/version.js diff --git a/dist/sip-0.15.5.js b/dist/sip-0.15.5.js deleted file mode 100644 index 20d4c368b..000000000 --- a/dist/sip-0.15.5.js +++ /dev/null @@ -1,21461 +0,0 @@ -/*! - * - * SIP version 0.15.5 - * Copyright (c) 2014-2019 Junction Networks, Inc - * Homepage: https://sipjs.com - * License: https://sipjs.com/license/ - * - * - * ~~~SIP.js contains substantial portions of JsSIP under the following license~~~ - * Homepage: http://jssip.net - * Copyright (c) 2012-2013 José Luis Millán - Versatica - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * ~~~ end JsSIP license ~~~ - * - * - * - * - */ -(function webpackUniversalModuleDefinition(root, factory) { - if(typeof exports === 'object' && typeof module === 'object') - module.exports = factory(); - else if(typeof define === 'function' && define.amd) - define([], factory); - else if(typeof exports === 'object') - exports["SIP"] = factory(); - else - root["SIP"] = factory(); -})(this, function() { -return /******/ (function(modules) { // webpackBootstrap -/******/ // The module cache -/******/ var installedModules = {}; -/******/ -/******/ // The require function -/******/ function __webpack_require__(moduleId) { -/******/ -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) { -/******/ return installedModules[moduleId].exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ i: moduleId, -/******/ l: false, -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); -/******/ -/******/ // Flag the module as loaded -/******/ module.l = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/******/ -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; -/******/ -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; -/******/ -/******/ // define getter function for harmony exports -/******/ __webpack_require__.d = function(exports, name, getter) { -/******/ if(!__webpack_require__.o(exports, name)) { -/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); -/******/ } -/******/ }; -/******/ -/******/ // define __esModule on exports -/******/ __webpack_require__.r = function(exports) { -/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { -/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); -/******/ } -/******/ Object.defineProperty(exports, '__esModule', { value: true }); -/******/ }; -/******/ -/******/ // create a fake namespace object -/******/ // mode & 1: value is a module id, require it -/******/ // mode & 2: merge all properties of value into the ns -/******/ // mode & 4: return value when already ns object -/******/ // mode & 8|1: behave like require -/******/ __webpack_require__.t = function(value, mode) { -/******/ if(mode & 1) value = __webpack_require__(value); -/******/ if(mode & 8) return value; -/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; -/******/ var ns = Object.create(null); -/******/ __webpack_require__.r(ns); -/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); -/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); -/******/ return ns; -/******/ }; -/******/ -/******/ // getDefaultExport function for compatibility with non-harmony modules -/******/ __webpack_require__.n = function(module) { -/******/ var getter = module && module.__esModule ? -/******/ function getDefault() { return module['default']; } : -/******/ function getModuleExports() { return module; }; -/******/ __webpack_require__.d(getter, 'a', getter); -/******/ return getter; -/******/ }; -/******/ -/******/ // Object.prototype.hasOwnProperty.call -/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; -/******/ -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = ""; -/******/ -/******/ -/******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = 0); -/******/ }) -/************************************************************************/ -/******/ ([ -/* 0 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var core_1 = __webpack_require__(2); -exports.DigestAuthentication = core_1.DigestAuthentication; -exports.Grammar = core_1.Grammar; -exports.IncomingRequest = core_1.IncomingRequestMessage; -exports.IncomingResponse = core_1.IncomingResponseMessage; -exports.LoggerFactory = core_1.LoggerFactory; -exports.NameAddrHeader = core_1.NameAddrHeader; -exports.OutgoingRequest = core_1.OutgoingRequestMessage; -exports.Timers = core_1.Timers; -exports.Transport = core_1.Transport; -exports.URI = core_1.URI; -var ClientContext_1 = __webpack_require__(79); -exports.ClientContext = ClientContext_1.ClientContext; -var Constants_1 = __webpack_require__(80); -exports.C = Constants_1.C; -var Enums_1 = __webpack_require__(82); -exports.DialogStatus = Enums_1.DialogStatus; -exports.SessionStatus = Enums_1.SessionStatus; -exports.TypeStrings = Enums_1.TypeStrings; -exports.UAStatus = Enums_1.UAStatus; -var Exceptions_1 = __webpack_require__(84); -exports.Exceptions = Exceptions_1.Exceptions; -var Parser_1 = __webpack_require__(85); -exports.Parser = Parser_1.Parser; -var PublishContext_1 = __webpack_require__(86); -exports.PublishContext = PublishContext_1.PublishContext; -var ReferContext_1 = __webpack_require__(87); -exports.ReferClientContext = ReferContext_1.ReferClientContext; -exports.ReferServerContext = ReferContext_1.ReferServerContext; -var RegisterContext_1 = __webpack_require__(89); -exports.RegisterContext = RegisterContext_1.RegisterContext; -var ServerContext_1 = __webpack_require__(88); -exports.ServerContext = ServerContext_1.ServerContext; -var Session_1 = __webpack_require__(90); -exports.InviteClientContext = Session_1.InviteClientContext; -exports.InviteServerContext = Session_1.InviteServerContext; -exports.Session = Session_1.Session; -var Subscription_1 = __webpack_require__(92); -exports.Subscription = Subscription_1.Subscription; -var transactions_1 = __webpack_require__(27); -var Transactions = { - InviteClientTransaction: transactions_1.InviteClientTransaction, - InviteServerTransaction: transactions_1.InviteServerTransaction, - NonInviteClientTransaction: transactions_1.NonInviteClientTransaction, - NonInviteServerTransaction: transactions_1.NonInviteServerTransaction -}; -exports.Transactions = Transactions; -var UA_1 = __webpack_require__(93); -exports.makeUserAgentCoreConfigurationFromUA = UA_1.makeUserAgentCoreConfigurationFromUA; -exports.UA = UA_1.UA; -var Utils_1 = __webpack_require__(83); -exports.Utils = Utils_1.Utils; -var Web = tslib_1.__importStar(__webpack_require__(104)); -exports.Web = Web; -var version = Constants_1.C.version; -exports.version = version; -var name = "sip.js"; -exports.name = name; -var Core = tslib_1.__importStar(__webpack_require__(2)); -exports.Core = Core; - - -/***/ }), -/* 1 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__extends", function() { return __extends; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__assign", function() { return __assign; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__rest", function() { return __rest; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__decorate", function() { return __decorate; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__param", function() { return __param; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__metadata", function() { return __metadata; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__awaiter", function() { return __awaiter; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__generator", function() { return __generator; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__exportStar", function() { return __exportStar; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__values", function() { return __values; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__read", function() { return __read; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__spread", function() { return __spread; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__spreadArrays", function() { return __spreadArrays; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__await", function() { return __await; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncGenerator", function() { return __asyncGenerator; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncDelegator", function() { return __asyncDelegator; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncValues", function() { return __asyncValues; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__makeTemplateObject", function() { return __makeTemplateObject; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__importStar", function() { return __importStar; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__importDefault", function() { return __importDefault; }); -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ -/* global Reflect, Promise */ - -var extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); -}; - -function __extends(d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -} - -var __assign = function() { - __assign = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - } - return __assign.apply(this, arguments); -} - -function __rest(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; -} - -function __decorate(decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -} - -function __param(paramIndex, decorator) { - return function (target, key) { decorator(target, key, paramIndex); } -} - -function __metadata(metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); -} - -function __awaiter(thisArg, _arguments, P, generator) { - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -} - -function __generator(thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -} - -function __exportStar(m, exports) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; -} - -function __values(o) { - var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; - if (m) return m.call(o); - return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; -} - -function __read(o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; -} - -function __spread() { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read(arguments[i])); - return ar; -} - -function __spreadArrays() { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) - for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) - r[k] = a[j]; - return r; -}; - -function __await(v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); -} - -function __asyncGenerator(thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function fulfill(value) { resume("next", value); } - function reject(value) { resume("throw", value); } - function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } -} - -function __asyncDelegator(o) { - var i, p; - return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } -} - -function __asyncValues(o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } -} - -function __makeTemplateObject(cooked, raw) { - if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } - return cooked; -}; - -function __importStar(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result.default = mod; - return result; -} - -function __importDefault(mod) { - return (mod && mod.__esModule) ? mod : { default: mod }; -} - - -/***/ }), -/* 2 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -/** - * A core library implementing low level SIP protocol elements. - * @packageDocumentation - */ -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -// Directories -tslib_1.__exportStar(__webpack_require__(3), exports); -tslib_1.__exportStar(__webpack_require__(31), exports); -tslib_1.__exportStar(__webpack_require__(60), exports); -tslib_1.__exportStar(__webpack_require__(5), exports); -tslib_1.__exportStar(__webpack_require__(24), exports); -tslib_1.__exportStar(__webpack_require__(56), exports); -tslib_1.__exportStar(__webpack_require__(27), exports); -tslib_1.__exportStar(__webpack_require__(64), exports); -tslib_1.__exportStar(__webpack_require__(66), exports); -// Files -tslib_1.__exportStar(__webpack_require__(26), exports); -tslib_1.__exportStar(__webpack_require__(78), exports); - - -/***/ }), -/* 3 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -tslib_1.__exportStar(__webpack_require__(4), exports); -tslib_1.__exportStar(__webpack_require__(23), exports); -tslib_1.__exportStar(__webpack_require__(55), exports); - - -/***/ }), -/* 4 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var messages_1 = __webpack_require__(5); -/** - * Dialog. - * @remarks - * A key concept for a user agent is that of a dialog. A dialog - * represents a peer-to-peer SIP relationship between two user agents - * that persists for some time. The dialog facilitates sequencing of - * messages between the user agents and proper routing of requests - * between both of them. The dialog represents a context in which to - * interpret SIP messages. - * https://tools.ietf.org/html/rfc3261#section-12 - * @public - */ -var Dialog = /** @class */ (function () { - /** - * Dialog constructor. - * @param core - User agent core. - * @param dialogState - Initial dialog state. - */ - function Dialog(core, dialogState) { - this.core = core; - this.dialogState = dialogState; - this.core.dialogs.set(this.id, this); - } - /** - * When a UAC receives a response that establishes a dialog, it - * constructs the state of the dialog. This state MUST be maintained - * for the duration of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.1.2 - * @param outgoingRequestMessage - Outgoing request message for dialog. - * @param incomingResponseMessage - Incoming response message creating dialog. - */ - Dialog.initialDialogStateForUserAgentClient = function (outgoingRequestMessage, incomingResponseMessage) { - // If the request was sent over TLS, and the Request-URI contained a - // SIPS URI, the "secure" flag is set to TRUE. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - var secure = false; // FIXME: Currently no support for TLS. - // The route set MUST be set to the list of URIs in the Record-Route - // header field from the response, taken in reverse order and preserving - // all URI parameters. If no Record-Route header field is present in - // the response, the route set MUST be set to the empty set. This route - // set, even if empty, overrides any pre-existing route set for future - // requests in this dialog. The remote target MUST be set to the URI - // from the Contact header field of the response. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - var routeSet = incomingResponseMessage.getHeaders("record-route").reverse(); - var contact = incomingResponseMessage.parseHeader("contact"); - if (!contact) { // TODO: Review to make sure this will never happen - throw new Error("Contact undefined."); - } - if (!(contact instanceof messages_1.NameAddrHeader)) { - throw new Error("Contact not instance of NameAddrHeader."); - } - var remoteTarget = contact.uri; - // The local sequence number MUST be set to the value of the sequence - // number in the CSeq header field of the request. The remote sequence - // number MUST be empty (it is established when the remote UA sends a - // request within the dialog). The call identifier component of the - // dialog ID MUST be set to the value of the Call-ID in the request. - // The local tag component of the dialog ID MUST be set to the tag in - // the From field in the request, and the remote tag component of the - // dialog ID MUST be set to the tag in the To field of the response. A - // UAC MUST be prepared to receive a response without a tag in the To - // field, in which case the tag is considered to have a value of null. - // - // This is to maintain backwards compatibility with RFC 2543, which - // did not mandate To tags. - // - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - var localSequenceNumber = outgoingRequestMessage.cseq; - var remoteSequenceNumber = undefined; - var callId = outgoingRequestMessage.callId; - var localTag = outgoingRequestMessage.fromTag; - var remoteTag = incomingResponseMessage.toTag; - if (!callId) { // TODO: Review to make sure this will never happen - throw new Error("Call id undefined."); - } - if (!localTag) { // TODO: Review to make sure this will never happen - throw new Error("From tag undefined."); - } - if (!remoteTag) { // TODO: Review to make sure this will never happen - throw new Error("To tag undefined."); // FIXME: No backwards compatibility with RFC 2543 - } - // The remote URI MUST be set to the URI in the To field, and the local - // URI MUST be set to the URI in the From field. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - if (!outgoingRequestMessage.from) { // TODO: Review to make sure this will never happen - throw new Error("From undefined."); - } - if (!outgoingRequestMessage.to) { // TODO: Review to make sure this will never happen - throw new Error("To undefined."); - } - var localURI = outgoingRequestMessage.from.uri; - var remoteURI = outgoingRequestMessage.to.uri; - // A dialog can also be in the "early" state, which occurs when it is - // created with a provisional response, and then transition to the - // "confirmed" state when a 2xx final response arrives. - // https://tools.ietf.org/html/rfc3261#section-12 - if (!incomingResponseMessage.statusCode) { - throw new Error("Incoming response status code undefined."); - } - var early = incomingResponseMessage.statusCode < 200 ? true : false; - var dialogState = { - id: callId + localTag + remoteTag, - early: early, - callId: callId, - localTag: localTag, - remoteTag: remoteTag, - localSequenceNumber: localSequenceNumber, - remoteSequenceNumber: remoteSequenceNumber, - localURI: localURI, - remoteURI: remoteURI, - remoteTarget: remoteTarget, - routeSet: routeSet, - secure: secure - }; - return dialogState; - }; - /** - * The UAS then constructs the state of the dialog. This state MUST be - * maintained for the duration of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.1.1 - * @param incomingRequestMessage - Incoming request message creating dialog. - * @param toTag - Tag in the To field in the response to the incoming request. - */ - Dialog.initialDialogStateForUserAgentServer = function (incomingRequestMessage, toTag, early) { - if (early === void 0) { early = false; } - // If the request arrived over TLS, and the Request-URI contained a SIPS - // URI, the "secure" flag is set to TRUE. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - var secure = false; // FIXME: Currently no support for TLS. - // The route set MUST be set to the list of URIs in the Record-Route - // header field from the request, taken in order and preserving all URI - // parameters. If no Record-Route header field is present in the - // request, the route set MUST be set to the empty set. This route set, - // even if empty, overrides any pre-existing route set for future - // requests in this dialog. The remote target MUST be set to the URI - // from the Contact header field of the request. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - var routeSet = incomingRequestMessage.getHeaders("record-route"); - var contact = incomingRequestMessage.parseHeader("contact"); - if (!contact) { // TODO: Review to make sure this will never happen - throw new Error("Contact undefined."); - } - if (!(contact instanceof messages_1.NameAddrHeader)) { - throw new Error("Contact not instance of NameAddrHeader."); - } - var remoteTarget = contact.uri; - // The remote sequence number MUST be set to the value of the sequence - // number in the CSeq header field of the request. The local sequence - // number MUST be empty. The call identifier component of the dialog ID - // MUST be set to the value of the Call-ID in the request. The local - // tag component of the dialog ID MUST be set to the tag in the To field - // in the response to the request (which always includes a tag), and the - // remote tag component of the dialog ID MUST be set to the tag from the - // From field in the request. A UAS MUST be prepared to receive a - // request without a tag in the From field, in which case the tag is - // considered to have a value of null. - // - // This is to maintain backwards compatibility with RFC 2543, which - // did not mandate From tags. - // - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - var remoteSequenceNumber = incomingRequestMessage.cseq; - var localSequenceNumber = undefined; - var callId = incomingRequestMessage.callId; - var localTag = toTag; - var remoteTag = incomingRequestMessage.fromTag; - // The remote URI MUST be set to the URI in the From field, and the - // local URI MUST be set to the URI in the To field. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - var remoteURI = incomingRequestMessage.from.uri; - var localURI = incomingRequestMessage.to.uri; - var dialogState = { - id: callId + localTag + remoteTag, - early: early, - callId: callId, - localTag: localTag, - remoteTag: remoteTag, - localSequenceNumber: localSequenceNumber, - remoteSequenceNumber: remoteSequenceNumber, - localURI: localURI, - remoteURI: remoteURI, - remoteTarget: remoteTarget, - routeSet: routeSet, - secure: secure - }; - return dialogState; - }; - /** Destructor. */ - Dialog.prototype.dispose = function () { - this.core.dialogs.delete(this.id); - }; - Object.defineProperty(Dialog.prototype, "id", { - /** - * A dialog is identified at each UA with a dialog ID, which consists of - * a Call-ID value, a local tag and a remote tag. The dialog ID at each - * UA involved in the dialog is not the same. Specifically, the local - * tag at one UA is identical to the remote tag at the peer UA. The - * tags are opaque tokens that facilitate the generation of unique - * dialog IDs. - * https://tools.ietf.org/html/rfc3261#section-12 - */ - get: function () { - return this.dialogState.id; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "early", { - /** - * A dialog can also be in the "early" state, which occurs when it is - * created with a provisional response, and then it transition to the - * "confirmed" state when a 2xx final response received or is sent. - * - * Note: RFC 3261 is concise on when a dialog is "confirmed", but it - * can be a point of confusion if an INVITE dialog is "confirmed" after - * a 2xx is sent or after receiving the ACK for the 2xx response. - * With careful reading it can be inferred a dialog is always is - * "confirmed" when the 2xx is sent (regardless of type of dialog). - * However a INVITE dialog does have additional considerations - * when it is confirmed but an ACK has not yet been received (in - * particular with regard to a callee sending BYE requests). - */ - get: function () { - return this.dialogState.early; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "callId", { - /** Call identifier component of the dialog id. */ - get: function () { - return this.dialogState.callId; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "localTag", { - /** Local tag component of the dialog id. */ - get: function () { - return this.dialogState.localTag; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "remoteTag", { - /** Remote tag component of the dialog id. */ - get: function () { - return this.dialogState.remoteTag; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "localSequenceNumber", { - /** Local sequence number (used to order requests from the UA to its peer). */ - get: function () { - return this.dialogState.localSequenceNumber; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "remoteSequenceNumber", { - /** Remote sequence number (used to order requests from its peer to the UA). */ - get: function () { - return this.dialogState.remoteSequenceNumber; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "localURI", { - /** Local URI. */ - get: function () { - return this.dialogState.localURI; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "remoteURI", { - /** Remote URI. */ - get: function () { - return this.dialogState.remoteURI; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "remoteTarget", { - /** Remote target. */ - get: function () { - return this.dialogState.remoteTarget; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "routeSet", { - /** - * Route set, which is an ordered list of URIs. The route set is the - * list of servers that need to be traversed to send a request to the peer. - */ - get: function () { - return this.dialogState.routeSet; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "secure", { - /** - * If the request was sent over TLS, and the Request-URI contained - * a SIPS URI, the "secure" flag is set to true. *NOT IMPLEMENTED* - */ - get: function () { - return this.dialogState.secure; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "userAgentCore", { - /** The user agent core servicing this dialog. */ - get: function () { - return this.core; - }, - enumerable: true, - configurable: true - }); - /** Confirm the dialog. Only matters if dialog is currently early. */ - Dialog.prototype.confirm = function () { - this.dialogState.early = false; - }; - /** - * Requests sent within a dialog, as any other requests, are atomic. If - * a particular request is accepted by the UAS, all the state changes - * associated with it are performed. If the request is rejected, none - * of the state changes are performed. - * - * Note that some requests, such as INVITEs, affect several pieces of - * state. - * - * https://tools.ietf.org/html/rfc3261#section-12.2.2 - * @param message - Incoming request message within this dialog. - */ - Dialog.prototype.receiveRequest = function (message) { - // ACK guard. - // By convention, the handling of ACKs is the responsibility - // the particular dialog implementation. For example, see SessionDialog. - // Furthermore, ACKs have same sequence number as the associated INVITE. - if (message.method === messages_1.C.ACK) { - return; - } - // If the remote sequence number was not empty, but the sequence number - // of the request is lower than the remote sequence number, the request - // is out of order and MUST be rejected with a 500 (Server Internal - // Error) response. If the remote sequence number was not empty, and - // the sequence number of the request is greater than the remote - // sequence number, the request is in order. It is possible for the - // CSeq sequence number to be higher than the remote sequence number by - // more than one. This is not an error condition, and a UAS SHOULD be - // prepared to receive and process requests with CSeq values more than - // one higher than the previous received request. The UAS MUST then set - // the remote sequence number to the value of the sequence number in the - // CSeq header field value in the request. - // - // If a proxy challenges a request generated by the UAC, the UAC has - // to resubmit the request with credentials. The resubmitted request - // will have a new CSeq number. The UAS will never see the first - // request, and thus, it will notice a gap in the CSeq number space. - // Such a gap does not represent any error condition. - // - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (this.remoteSequenceNumber) { - if (message.cseq <= this.remoteSequenceNumber) { - throw new Error("Out of sequence in dialog request. Did you forget to call sequenceGuard()?"); - } - this.dialogState.remoteSequenceNumber = message.cseq; - } - // If the remote sequence number is empty, it MUST be set to the value - // of the sequence number in the CSeq header field value in the request. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (!this.remoteSequenceNumber) { - this.dialogState.remoteSequenceNumber = message.cseq; - } - // When a UAS receives a target refresh request, it MUST replace the - // dialog's remote target URI with the URI from the Contact header field - // in that request, if present. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - // Note: "target refresh request" processing delegated to sub-class. - }; - /** - * If the dialog identifier in the 2xx response matches the dialog - * identifier of an existing dialog, the dialog MUST be transitioned to - * the "confirmed" state, and the route set for the dialog MUST be - * recomputed based on the 2xx response using the procedures of Section - * 12.2.1.2. Otherwise, a new dialog in the "confirmed" state MUST be - * constructed using the procedures of Section 12.1.2. - * - * Note that the only piece of state that is recomputed is the route - * set. Other pieces of state such as the highest sequence numbers - * (remote and local) sent within the dialog are not recomputed. The - * route set only is recomputed for backwards compatibility. RFC - * 2543 did not mandate mirroring of the Record-Route header field in - * a 1xx, only 2xx. However, we cannot update the entire state of - * the dialog, since mid-dialog requests may have been sent within - * the early dialog, modifying the sequence numbers, for example. - * - * https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - */ - Dialog.prototype.recomputeRouteSet = function (message) { - this.dialogState.routeSet = message.getHeaders("record-route").reverse(); - }; - /** - * A request within a dialog is constructed by using many of the - * components of the state stored as part of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - * @param method - Outgoing request method. - */ - Dialog.prototype.createOutgoingRequestMessage = function (method, options) { - // The URI in the To field of the request MUST be set to the remote URI - // from the dialog state. The tag in the To header field of the request - // MUST be set to the remote tag of the dialog ID. The From URI of the - // request MUST be set to the local URI from the dialog state. The tag - // in the From header field of the request MUST be set to the local tag - // of the dialog ID. If the value of the remote or local tags is null, - // the tag parameter MUST be omitted from the To or From header fields, - // respectively. - // - // Usage of the URI from the To and From fields in the original - // request within subsequent requests is done for backwards - // compatibility with RFC 2543, which used the URI for dialog - // identification. In this specification, only the tags are used for - // dialog identification. It is expected that mandatory reflection - // of the original To and From URI in mid-dialog requests will be - // deprecated in a subsequent revision of this specification. - // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - var toUri = this.remoteURI; - var toTag = this.remoteTag; - var fromUri = this.localURI; - var fromTag = this.localTag; - // The Call-ID of the request MUST be set to the Call-ID of the dialog. - // Requests within a dialog MUST contain strictly monotonically - // increasing and contiguous CSeq sequence numbers (increasing-by-one) - // in each direction (excepting ACK and CANCEL of course, whose numbers - // equal the requests being acknowledged or cancelled). Therefore, if - // the local sequence number is not empty, the value of the local - // sequence number MUST be incremented by one, and this value MUST be - // placed into the CSeq header field. If the local sequence number is - // empty, an initial value MUST be chosen using the guidelines of - // Section 8.1.1.5. The method field in the CSeq header field value - // MUST match the method of the request. - // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - var callId = this.callId; - var cseq; - if (options && options.cseq) { - cseq = options.cseq; - } - else if (!this.dialogState.localSequenceNumber) { - cseq = this.dialogState.localSequenceNumber = 1; // https://tools.ietf.org/html/rfc3261#section-8.1.1.5 - } - else { - cseq = this.dialogState.localSequenceNumber += 1; - } - // The UAC uses the remote target and route set to build the Request-URI - // and Route header field of the request. - // - // If the route set is empty, the UAC MUST place the remote target URI - // into the Request-URI. The UAC MUST NOT add a Route header field to - // the request. - // - // If the route set is not empty, and the first URI in the route set - // contains the lr parameter (see Section 19.1.1), the UAC MUST place - // the remote target URI into the Request-URI and MUST include a Route - // header field containing the route set values in order, including all - // parameters. - // - // If the route set is not empty, and its first URI does not contain the - // lr parameter, the UAC MUST place the first URI from the route set - // into the Request-URI, stripping any parameters that are not allowed - // in a Request-URI. The UAC MUST add a Route header field containing - // the remainder of the route set values in order, including all - // parameters. The UAC MUST then place the remote target URI into the - // Route header field as the last value. - // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - // The lr parameter, when present, indicates that the element - // responsible for this resource implements the routing mechanisms - // specified in this document. This parameter will be used in the - // URIs proxies place into Record-Route header field values, and - // may appear in the URIs in a pre-existing route set. - // - // This parameter is used to achieve backwards compatibility with - // systems implementing the strict-routing mechanisms of RFC 2543 - // and the rfc2543bis drafts up to bis-05. An element preparing - // to send a request based on a URI not containing this parameter - // can assume the receiving element implements strict-routing and - // reformat the message to preserve the information in the - // Request-URI. - // https://tools.ietf.org/html/rfc3261#section-19.1.1 - // NOTE: Not backwards compatible with RFC 2543 (no support for strict-routing). - var ruri = this.remoteTarget; - var routeSet = this.routeSet; - var extraHeaders = options && options.extraHeaders; - var body = options && options.body; - // The relative order of header fields with different field names is not - // significant. However, it is RECOMMENDED that header fields which are - // needed for proxy processing (Via, Route, Record-Route, Proxy-Require, - // Max-Forwards, and Proxy-Authorization, for example) appear towards - // the top of the message to facilitate rapid parsing. - // https://tools.ietf.org/html/rfc3261#section-7.3.1 - var message = this.userAgentCore.makeOutgoingRequestMessage(method, ruri, fromUri, toUri, { - callId: callId, - cseq: cseq, - fromTag: fromTag, - toTag: toTag, - routeSet: routeSet - }, extraHeaders, body); - return message; - }; - /** - * If the remote sequence number was not empty, but the sequence number - * of the request is lower than the remote sequence number, the request - * is out of order and MUST be rejected with a 500 (Server Internal - * Error) response. - * https://tools.ietf.org/html/rfc3261#section-12.2.2 - * @param request - Incoming request to guard. - * @returns True if the program execution is to continue in the branch in question. - * Otherwise a 500 Server Internal Error was stateless sent and request processing must stop. - */ - Dialog.prototype.sequenceGuard = function (message) { - // ACK guard. - // By convention, handling of unexpected ACKs is responsibility - // the particular dialog implementation. For example, see SessionDialog. - // Furthermore, we cannot reply to an "out of sequence" ACK. - if (message.method === messages_1.C.ACK) { - return true; - } - // Note: We are rejecting on "less than or equal to" the remote - // sequence number (excepting ACK whose numbers equal the requests - // being acknowledged or cancelled), which is the correct thing to - // do in our case. The only time a request with the same sequence number - // will show up here if is a) it is a very late retransmission of a - // request we already handled or b) it is a different request with the - // same sequence number which would be violation of the standard. - // Request retransmissions are absorbed by the transaction layer, - // so any request with a duplicate sequence number getting here - // would have to be a retransmission after the transaction terminated - // or a broken request (with unique via branch value). - // Requests within a dialog MUST contain strictly monotonically - // increasing and contiguous CSeq sequence numbers (increasing-by-one) - // in each direction (excepting ACK and CANCEL of course, whose numbers - // equal the requests being acknowledged or cancelled). Therefore, if - // the local sequence number is not empty, the value of the local - // sequence number MUST be incremented by one, and this value MUST be - // placed into the CSeq header field. - // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - if (this.remoteSequenceNumber && message.cseq <= this.remoteSequenceNumber) { - this.core.replyStateless(message, { statusCode: 500 }); - return false; - } - return true; - }; - return Dialog; -}()); -exports.Dialog = Dialog; - - -/***/ }), -/* 5 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -// Directories -tslib_1.__exportStar(__webpack_require__(6), exports); -// Files -tslib_1.__exportStar(__webpack_require__(8), exports); -tslib_1.__exportStar(__webpack_require__(19), exports); -tslib_1.__exportStar(__webpack_require__(11), exports); -tslib_1.__exportStar(__webpack_require__(10), exports); -tslib_1.__exportStar(__webpack_require__(9), exports); -tslib_1.__exportStar(__webpack_require__(17), exports); -tslib_1.__exportStar(__webpack_require__(13), exports); -tslib_1.__exportStar(__webpack_require__(18), exports); -tslib_1.__exportStar(__webpack_require__(22), exports); -tslib_1.__exportStar(__webpack_require__(14), exports); -tslib_1.__exportStar(__webpack_require__(15), exports); - - -/***/ }), -/* 6 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -tslib_1.__exportStar(__webpack_require__(7), exports); - - -/***/ }), -/* 7 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * SIP Methods - * @internal - */ -var C; -(function (C) { - C.ACK = "ACK"; - C.BYE = "BYE"; - C.CANCEL = "CANCEL"; - C.INFO = "INFO"; - C.INVITE = "INVITE"; - C.MESSAGE = "MESSAGE"; - C.NOTIFY = "NOTIFY"; - C.OPTIONS = "OPTIONS"; - C.REGISTER = "REGISTER"; - C.UPDATE = "UPDATE"; - C.SUBSCRIBE = "SUBSCRIBE"; - C.PUBLISH = "PUBLISH"; - C.REFER = "REFER"; - C.PRACK = "PRACK"; -})(C = exports.C || (exports.C = {})); - - -/***/ }), -/* 8 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var incoming_request_message_1 = __webpack_require__(9); -var incoming_response_message_1 = __webpack_require__(17); -var outgoing_request_message_1 = __webpack_require__(18); -/** - * Create a Body given a legacy body type. - * @param bodyLegacy - Body Object - * @internal - */ -function fromBodyLegacy(bodyLegacy) { - var content = (typeof bodyLegacy === "string") ? bodyLegacy : bodyLegacy.body; - var contentType = (typeof bodyLegacy === "string") ? "application/sdp" : bodyLegacy.contentType; - var contentDisposition = contentTypeToContentDisposition(contentType); - var body = { contentDisposition: contentDisposition, contentType: contentType, content: content }; - return body; -} -exports.fromBodyLegacy = fromBodyLegacy; -/** - * Given a message, get a normalized body. - * The content disposition is inferred if not set. - * @param message - The message. - * @internal - */ -function getBody(message) { - var contentDisposition; - var contentType; - var content; - // We're in UAS role, receiving incoming request - if (message instanceof incoming_request_message_1.IncomingRequestMessage) { - if (message.body) { - // FIXME: Parsing needs typing - var parse = message.parseHeader("Content-Disposition"); - contentDisposition = parse ? parse.type : undefined; - contentType = message.parseHeader("Content-Type"); - content = message.body; - } - } - // We're in UAC role, receiving incoming response - if (message instanceof incoming_response_message_1.IncomingResponseMessage) { - if (message.body) { - // FIXME: Parsing needs typing - var parse = message.parseHeader("Content-Disposition"); - contentDisposition = parse ? parse.type : undefined; - contentType = message.parseHeader("Content-Type"); - content = message.body; - } - } - // We're in UAC role, sending outgoing request - if (message instanceof outgoing_request_message_1.OutgoingRequestMessage) { - if (message.body) { - contentDisposition = message.getHeader("Content-Disposition"); - contentType = message.getHeader("Content-Type"); - if (typeof message.body === "string") { - // FIXME: OutgoingRequest should not allow a "string" body without a "Content-Type" header. - if (!contentType) { - throw new Error("Header content type header does not equal body content type."); - } - content = message.body; - } - else { - // FIXME: OutgoingRequest should not allow the "Content-Type" header not to match th body content type - if (contentType && contentType !== message.body.contentType) { - throw new Error("Header content type header does not equal body content type."); - } - contentType = message.body.contentType; - content = message.body.body; - } - } - } - // We're in UAS role, sending outgoing response - if (isBody(message)) { - contentDisposition = message.contentDisposition; - contentType = message.contentType; - content = message.content; - } - // No content, no body. - if (!content) { - return undefined; - } - if (contentType && !contentDisposition) { - contentDisposition = contentTypeToContentDisposition(contentType); - } - if (!contentDisposition) { - throw new Error("Content disposition undefined."); - } - if (!contentType) { - throw new Error("Content type undefined."); - } - return { - contentDisposition: contentDisposition, - contentType: contentType, - content: content - }; -} -exports.getBody = getBody; -/** - * User-Defined Type Guard for Body. - * @param body - Body to check. - * @internal - */ -function isBody(body) { - return body && - typeof body.content === "string" && - typeof body.contentType === "string" && - body.contentDisposition === undefined ? true : typeof body.contentDisposition === "string"; -} -exports.isBody = isBody; -// If the Content-Disposition header field is missing, bodies of -// Content-Type application/sdp imply the disposition "session", while -// other content types imply "render". -// https://tools.ietf.org/html/rfc3261#section-13.2.1 -function contentTypeToContentDisposition(contentType) { - if (contentType === "application/sdp") { - return "session"; - } - else { - return "render"; - } -} - - -/***/ }), -/* 9 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var incoming_message_1 = __webpack_require__(10); -/** - * Incoming request message. - * @public - */ -var IncomingRequestMessage = /** @class */ (function (_super) { - tslib_1.__extends(IncomingRequestMessage, _super); - function IncomingRequestMessage() { - return _super.call(this) || this; - } - return IncomingRequestMessage; -}(incoming_message_1.IncomingMessage)); -exports.IncomingRequestMessage = IncomingRequestMessage; - - -/***/ }), -/* 10 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var grammar_1 = __webpack_require__(11); -var utils_1 = __webpack_require__(16); -/** - * Incoming message. - * @public - */ -var IncomingMessage = /** @class */ (function () { - function IncomingMessage() { - this.headers = {}; - } - /** - * Insert a header of the given name and value into the last position of the - * header array. - * @param name - header name - * @param value - header value - */ - IncomingMessage.prototype.addHeader = function (name, value) { - var header = { raw: value }; - name = utils_1.headerize(name); - if (this.headers[name]) { - this.headers[name].push(header); - } - else { - this.headers[name] = [header]; - } - }; - /** - * Get the value of the given header name at the given position. - * @param name - header name - * @returns Returns the specified header, undefined if header doesn't exist. - */ - IncomingMessage.prototype.getHeader = function (name) { - var header = this.headers[utils_1.headerize(name)]; - if (header) { - if (header[0]) { - return header[0].raw; - } - } - else { - return; - } - }; - /** - * Get the header/s of the given name. - * @param name - header name - * @returns Array - with all the headers of the specified name. - */ - IncomingMessage.prototype.getHeaders = function (name) { - var header = this.headers[utils_1.headerize(name)]; - var result = []; - if (!header) { - return []; - } - for (var _i = 0, header_1 = header; _i < header_1.length; _i++) { - var headerPart = header_1[_i]; - result.push(headerPart.raw); - } - return result; - }; - /** - * Verify the existence of the given header. - * @param name - header name - * @returns true if header with given name exists, false otherwise - */ - IncomingMessage.prototype.hasHeader = function (name) { - return !!this.headers[utils_1.headerize(name)]; - }; - /** - * Parse the given header on the given index. - * @param name - header name - * @param idx - header index - * @returns Parsed header object, undefined if the - * header is not present or in case of a parsing error. - */ - IncomingMessage.prototype.parseHeader = function (name, idx) { - if (idx === void 0) { idx = 0; } - name = utils_1.headerize(name); - if (!this.headers[name]) { - // this.logger.log("header '" + name + "' not present"); - return; - } - else if (idx >= this.headers[name].length) { - // this.logger.log("not so many '" + name + "' headers present"); - return; - } - var header = this.headers[name][idx]; - var value = header.raw; - if (header.parsed) { - return header.parsed; - } - // substitute '-' by '_' for grammar rule matching. - var parsed = grammar_1.Grammar.parse(value, name.replace(/-/g, "_")); - if (parsed === -1) { - this.headers[name].splice(idx, 1); // delete from headers - // this.logger.warn('error parsing "' + name + '" header field with value "' + value + '"'); - return; - } - else { - header.parsed = parsed; - return parsed; - } - }; - /** - * Message Header attribute selector. Alias of parseHeader. - * @param name - header name - * @param idx - header index - * @returns Parsed header object, undefined if the - * header is not present or in case of a parsing error. - * - * @example - * message.s('via',3).port - */ - IncomingMessage.prototype.s = function (name, idx) { - if (idx === void 0) { idx = 0; } - return this.parseHeader(name, idx); - }; - /** - * Replace the value of the given header by the value. - * @param name - header name - * @param value - header value - */ - IncomingMessage.prototype.setHeader = function (name, value) { - this.headers[utils_1.headerize(name)] = [{ raw: value }]; - }; - IncomingMessage.prototype.toString = function () { - return this.data; - }; - return IncomingMessage; -}()); -exports.IncomingMessage = IncomingMessage; - - -/***/ }), -/* 11 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var pegGrammar = tslib_1.__importStar(__webpack_require__(12)); -/** - * Grammar. - * @internal - */ -var Grammar; -(function (Grammar) { - /** - * Parse. - * @param input - - * @param startRule - - */ - function parse(input, startRule) { - var options = { startRule: startRule }; - try { - pegGrammar.parse(input, options); - } - catch (e) { - options.data = -1; - } - return options.data; - } - Grammar.parse = parse; - /** - * Parse the given string and returns a SIP.NameAddrHeader instance or undefined if - * it is an invalid NameAddrHeader. - * @param name_addr_header - - */ - function nameAddrHeaderParse(nameAddrHeader) { - var parsedNameAddrHeader = Grammar.parse(nameAddrHeader, "Name_Addr_Header"); - return parsedNameAddrHeader !== -1 ? parsedNameAddrHeader : undefined; - } - Grammar.nameAddrHeaderParse = nameAddrHeaderParse; - /** - * Parse the given string and returns a SIP.URI instance or undefined if - * it is an invalid URI. - * @param uri - - */ - function URIParse(uri) { - var parsedUri = Grammar.parse(uri, "SIP_URI"); - return parsedUri !== -1 ? parsedUri : undefined; - } - Grammar.URIParse = URIParse; -})(Grammar = exports.Grammar || (exports.Grammar = {})); - - -/***/ }), -/* 12 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// tslint:disable:interface-name -// tslint:disable: trailing-comma -// tslint:disable: object-literal-sort-keys -// tslint:disable: max-line-length -// tslint:disable: only-arrow-functions -// tslint:disable: one-variable-per-declaration -// tslint:disable: no-consecutive-blank-lines -// tslint:disable: align -// tslint:disable: radix -// tslint:disable: quotemark -// tslint:disable: semicolon -// tslint:disable: object-literal-shorthand -// tslint:disable: variable-name -// tslint:disable: no-var-keyword -// tslint:disable: whitespace -// tslint:disable: curly -// tslint:disable: prefer-const -// tslint:disable: object-literal-key-quotes -// tslint:disable: no-string-literal -// tslint:disable: one-line -// tslint:disable: no-unused-expression -// tslint:disable: space-before-function-paren -// tslint:disable: arrow-return-shorthand -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -// Generated by PEG.js v. 0.10.0 (ts-pegjs plugin v. 0.2.6 ) -// -// https://pegjs.org/ https://github.com/metadevpro/ts-pegjs -var name_addr_header_1 = __webpack_require__(13); -var uri_1 = __webpack_require__(15); -var SyntaxError = /** @class */ (function (_super) { - tslib_1.__extends(SyntaxError, _super); - function SyntaxError(message, expected, found, location) { - var _this = _super.call(this) || this; - _this.message = message; - _this.expected = expected; - _this.found = found; - _this.location = location; - _this.name = "SyntaxError"; - if (typeof Error.captureStackTrace === "function") { - Error.captureStackTrace(_this, SyntaxError); - } - return _this; - } - SyntaxError.buildMessage = function (expected, found) { - function hex(ch) { - return ch.charCodeAt(0).toString(16).toUpperCase(); - } - function literalEscape(s) { - return s - .replace(/\\/g, "\\\\") - .replace(/"/g, "\\\"") - .replace(/\0/g, "\\0") - .replace(/\t/g, "\\t") - .replace(/\n/g, "\\n") - .replace(/\r/g, "\\r") - .replace(/[\x00-\x0F]/g, function (ch) { return "\\x0" + hex(ch); }) - .replace(/[\x10-\x1F\x7F-\x9F]/g, function (ch) { return "\\x" + hex(ch); }); - } - function classEscape(s) { - return s - .replace(/\\/g, "\\\\") - .replace(/\]/g, "\\]") - .replace(/\^/g, "\\^") - .replace(/-/g, "\\-") - .replace(/\0/g, "\\0") - .replace(/\t/g, "\\t") - .replace(/\n/g, "\\n") - .replace(/\r/g, "\\r") - .replace(/[\x00-\x0F]/g, function (ch) { return "\\x0" + hex(ch); }) - .replace(/[\x10-\x1F\x7F-\x9F]/g, function (ch) { return "\\x" + hex(ch); }); - } - function describeExpectation(expectation) { - switch (expectation.type) { - case "literal": - return "\"" + literalEscape(expectation.text) + "\""; - case "class": - var escapedParts = expectation.parts.map(function (part) { - return Array.isArray(part) - ? classEscape(part[0]) + "-" + classEscape(part[1]) - : classEscape(part); - }); - return "[" + (expectation.inverted ? "^" : "") + escapedParts + "]"; - case "any": - return "any character"; - case "end": - return "end of input"; - case "other": - return expectation.description; - } - } - function describeExpected(expected1) { - var descriptions = expected1.map(describeExpectation); - var i; - var j; - descriptions.sort(); - if (descriptions.length > 0) { - for (i = 1, j = 1; i < descriptions.length; i++) { - if (descriptions[i - 1] !== descriptions[i]) { - descriptions[j] = descriptions[i]; - j++; - } - } - descriptions.length = j; - } - switch (descriptions.length) { - case 1: - return descriptions[0]; - case 2: - return descriptions[0] + " or " + descriptions[1]; - default: - return descriptions.slice(0, -1).join(", ") - + ", or " - + descriptions[descriptions.length - 1]; - } - } - function describeFound(found1) { - return found1 ? "\"" + literalEscape(found1) + "\"" : "end of input"; - } - return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found."; - }; - return SyntaxError; -}(Error)); -exports.SyntaxError = SyntaxError; -function peg$parse(input, options) { - options = options !== undefined ? options : {}; - var peg$FAILED = {}; - var peg$startRuleIndices = { Contact: 119, Name_Addr_Header: 156, Record_Route: 176, Request_Response: 81, SIP_URI: 45, Subscription_State: 186, Supported: 191, Require: 182, Via: 194, absoluteURI: 84, Call_ID: 118, Content_Disposition: 130, Content_Length: 135, Content_Type: 136, CSeq: 146, displayName: 122, Event: 149, From: 151, host: 52, Max_Forwards: 154, Min_SE: 213, Proxy_Authenticate: 157, quoted_string: 40, Refer_To: 178, Replaces: 179, Session_Expires: 210, stun_URI: 217, To: 192, turn_URI: 223, uuid: 226, WWW_Authenticate: 209, challenge: 158, sipfrag: 230, Referred_By: 231 }; - var peg$startRuleIndex = 119; - var peg$consts = [ - "\r\n", - peg$literalExpectation("\r\n", false), - /^[0-9]/, - peg$classExpectation([["0", "9"]], false, false), - /^[a-zA-Z]/, - peg$classExpectation([["a", "z"], ["A", "Z"]], false, false), - /^[0-9a-fA-F]/, - peg$classExpectation([["0", "9"], ["a", "f"], ["A", "F"]], false, false), - /^[\0-\xFF]/, - peg$classExpectation([["\0", "\xFF"]], false, false), - /^["]/, - peg$classExpectation(["\""], false, false), - " ", - peg$literalExpectation(" ", false), - "\t", - peg$literalExpectation("\t", false), - /^[a-zA-Z0-9]/, - peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"]], false, false), - ";", - peg$literalExpectation(";", false), - "/", - peg$literalExpectation("/", false), - "?", - peg$literalExpectation("?", false), - ":", - peg$literalExpectation(":", false), - "@", - peg$literalExpectation("@", false), - "&", - peg$literalExpectation("&", false), - "=", - peg$literalExpectation("=", false), - "+", - peg$literalExpectation("+", false), - "$", - peg$literalExpectation("$", false), - ",", - peg$literalExpectation(",", false), - "-", - peg$literalExpectation("-", false), - "_", - peg$literalExpectation("_", false), - ".", - peg$literalExpectation(".", false), - "!", - peg$literalExpectation("!", false), - "~", - peg$literalExpectation("~", false), - "*", - peg$literalExpectation("*", false), - "'", - peg$literalExpectation("'", false), - "(", - peg$literalExpectation("(", false), - ")", - peg$literalExpectation(")", false), - "%", - peg$literalExpectation("%", false), - function () { return " "; }, - function () { return ':'; }, - /^[!-~]/, - peg$classExpectation([["!", "~"]], false, false), - /^[\x80-\uFFFF]/, - peg$classExpectation([["\x80", "\uFFFF"]], false, false), - /^[\x80-\xBF]/, - peg$classExpectation([["\x80", "\xBF"]], false, false), - /^[a-f]/, - peg$classExpectation([["a", "f"]], false, false), - "`", - peg$literalExpectation("`", false), - "<", - peg$literalExpectation("<", false), - ">", - peg$literalExpectation(">", false), - "\\", - peg$literalExpectation("\\", false), - "[", - peg$literalExpectation("[", false), - "]", - peg$literalExpectation("]", false), - "{", - peg$literalExpectation("{", false), - "}", - peg$literalExpectation("}", false), - function () { return "*"; }, - function () { return "/"; }, - function () { return "="; }, - function () { return "("; }, - function () { return ")"; }, - function () { return ">"; }, - function () { return "<"; }, - function () { return ","; }, - function () { return ";"; }, - function () { return ":"; }, - function () { return "\""; }, - /^[!-']/, - peg$classExpectation([["!", "'"]], false, false), - /^[*-[]/, - peg$classExpectation([["*", "["]], false, false), - /^[\]-~]/, - peg$classExpectation([["]", "~"]], false, false), - function (contents) { - return contents; - }, - /^[#-[]/, - peg$classExpectation([["#", "["]], false, false), - /^[\0-\t]/, - peg$classExpectation([["\0", "\t"]], false, false), - /^[\x0B-\f]/, - peg$classExpectation([["\x0B", "\f"]], false, false), - /^[\x0E-\x7F]/, - peg$classExpectation([["\x0E", "\x7F"]], false, false), - function () { - options = options || { data: {} }; - options.data.uri = new uri_1.URI(options.data.scheme, options.data.user, options.data.host, options.data.port); - delete options.data.scheme; - delete options.data.user; - delete options.data.host; - delete options.data.host_type; - delete options.data.port; - }, - function () { - options = options || { data: {} }; - options.data.uri = new uri_1.URI(options.data.scheme, options.data.user, options.data.host, options.data.port, options.data.uri_params, options.data.uri_headers); - delete options.data.scheme; - delete options.data.user; - delete options.data.host; - delete options.data.host_type; - delete options.data.port; - delete options.data.uri_params; - if (options.startRule === 'SIP_URI') { - options.data = options.data.uri; - } - }, - "sips", - peg$literalExpectation("sips", true), - "sip", - peg$literalExpectation("sip", true), - function (uri_scheme) { - options = options || { data: {} }; - options.data.scheme = uri_scheme; - }, - function () { - options = options || { data: {} }; - options.data.user = decodeURIComponent(text().slice(0, -1)); - }, - function () { - options = options || { data: {} }; - options.data.password = text(); - }, - function () { - options = options || { data: {} }; - options.data.host = text(); - return options.data.host; - }, - function () { - options = options || { data: {} }; - options.data.host_type = 'domain'; - return text(); - }, - /^[a-zA-Z0-9_\-]/, - peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"], "_", "-"], false, false), - /^[a-zA-Z0-9\-]/, - peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"], "-"], false, false), - function () { - options = options || { data: {} }; - options.data.host_type = 'IPv6'; - return text(); - }, - "::", - peg$literalExpectation("::", false), - function () { - options = options || { data: {} }; - options.data.host_type = 'IPv6'; - return text(); - }, - function () { - options = options || { data: {} }; - options.data.host_type = 'IPv4'; - return text(); - }, - "25", - peg$literalExpectation("25", false), - /^[0-5]/, - peg$classExpectation([["0", "5"]], false, false), - "2", - peg$literalExpectation("2", false), - /^[0-4]/, - peg$classExpectation([["0", "4"]], false, false), - "1", - peg$literalExpectation("1", false), - /^[1-9]/, - peg$classExpectation([["1", "9"]], false, false), - function (port) { - options = options || { data: {} }; - port = parseInt(port.join('')); - options.data.port = port; - return port; - }, - "transport=", - peg$literalExpectation("transport=", true), - "udp", - peg$literalExpectation("udp", true), - "tcp", - peg$literalExpectation("tcp", true), - "sctp", - peg$literalExpectation("sctp", true), - "tls", - peg$literalExpectation("tls", true), - function (transport) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['transport'] = transport.toLowerCase(); - }, - "user=", - peg$literalExpectation("user=", true), - "phone", - peg$literalExpectation("phone", true), - "ip", - peg$literalExpectation("ip", true), - function (user) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['user'] = user.toLowerCase(); - }, - "method=", - peg$literalExpectation("method=", true), - function (method) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['method'] = method; - }, - "ttl=", - peg$literalExpectation("ttl=", true), - function (ttl) { - options = options || { data: {} }; - if (!options.data.params) - options.data.params = {}; - options.data.params['ttl'] = ttl; - }, - "maddr=", - peg$literalExpectation("maddr=", true), - function (maddr) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['maddr'] = maddr; - }, - "lr", - peg$literalExpectation("lr", true), - function () { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['lr'] = undefined; - }, - function (param, value) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - if (value === null) { - value = undefined; - } - else { - value = value[1]; - } - options.data.uri_params[param.toLowerCase()] = value; - }, - function (hname, hvalue) { - hname = hname.join('').toLowerCase(); - hvalue = hvalue.join(''); - options = options || { data: {} }; - if (!options.data.uri_headers) - options.data.uri_headers = {}; - if (!options.data.uri_headers[hname]) { - options.data.uri_headers[hname] = [hvalue]; - } - else { - options.data.uri_headers[hname].push(hvalue); - } - }, - function () { - options = options || { data: {} }; - // lots of tests fail if this isn't guarded... - if (options.startRule === 'Refer_To') { - options.data.uri = new uri_1.URI(options.data.scheme, options.data.user, options.data.host, options.data.port, options.data.uri_params, options.data.uri_headers); - delete options.data.scheme; - delete options.data.user; - delete options.data.host; - delete options.data.host_type; - delete options.data.port; - delete options.data.uri_params; - } - }, - "//", - peg$literalExpectation("//", false), - function () { - options = options || { data: {} }; - options.data.scheme = text(); - }, - peg$literalExpectation("SIP", true), - function () { - options = options || { data: {} }; - options.data.sip_version = text(); - }, - "INVITE", - peg$literalExpectation("INVITE", false), - "ACK", - peg$literalExpectation("ACK", false), - "VXACH", - peg$literalExpectation("VXACH", false), - "OPTIONS", - peg$literalExpectation("OPTIONS", false), - "BYE", - peg$literalExpectation("BYE", false), - "CANCEL", - peg$literalExpectation("CANCEL", false), - "REGISTER", - peg$literalExpectation("REGISTER", false), - "SUBSCRIBE", - peg$literalExpectation("SUBSCRIBE", false), - "NOTIFY", - peg$literalExpectation("NOTIFY", false), - "REFER", - peg$literalExpectation("REFER", false), - "PUBLISH", - peg$literalExpectation("PUBLISH", false), - function () { - options = options || { data: {} }; - options.data.method = text(); - return options.data.method; - }, - function (status_code) { - options = options || { data: {} }; - options.data.status_code = parseInt(status_code.join('')); - }, - function () { - options = options || { data: {} }; - options.data.reason_phrase = text(); - }, - function () { - options = options || { data: {} }; - options.data = text(); - }, - function () { - var idx, length; - options = options || { data: {} }; - length = options.data.multi_header.length; - for (idx = 0; idx < length; idx++) { - if (options.data.multi_header[idx].parsed === null) { - options.data = null; - break; - } - } - if (options.data !== null) { - options.data = options.data.multi_header; - } - else { - options.data = -1; - } - }, - function () { - var header; - options = options || { data: {} }; - if (!options.data.multi_header) - options.data.multi_header = []; - try { - header = new name_addr_header_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); - delete options.data.uri; - delete options.data.displayName; - delete options.data.params; - } - catch (e) { - header = null; - } - options.data.multi_header.push({ 'position': peg$currPos, - 'offset': location().start.offset, - 'parsed': header - }); - }, - function (displayName) { - displayName = text().trim(); - if (displayName[0] === '\"') { - displayName = displayName.substring(1, displayName.length - 1); - } - options = options || { data: {} }; - options.data.displayName = displayName; - }, - "q", - peg$literalExpectation("q", true), - function (q) { - options = options || { data: {} }; - if (!options.data.params) - options.data.params = {}; - options.data.params['q'] = q; - }, - "expires", - peg$literalExpectation("expires", true), - function (expires) { - options = options || { data: {} }; - if (!options.data.params) - options.data.params = {}; - options.data.params['expires'] = expires; - }, - function (delta_seconds) { - return parseInt(delta_seconds.join('')); - }, - "0", - peg$literalExpectation("0", false), - function () { - return parseFloat(text()); - }, - function (param, value) { - options = options || { data: {} }; - if (!options.data.params) - options.data.params = {}; - if (value === null) { - value = undefined; - } - else { - value = value[1]; - } - options.data.params[param.toLowerCase()] = value; - }, - "render", - peg$literalExpectation("render", true), - "session", - peg$literalExpectation("session", true), - "icon", - peg$literalExpectation("icon", true), - "alert", - peg$literalExpectation("alert", true), - function () { - options = options || { data: {} }; - if (options.startRule === 'Content_Disposition') { - options.data.type = text().toLowerCase(); - } - }, - "handling", - peg$literalExpectation("handling", true), - "optional", - peg$literalExpectation("optional", true), - "required", - peg$literalExpectation("required", true), - function (length) { - options = options || { data: {} }; - options.data = parseInt(length.join('')); - }, - function () { - options = options || { data: {} }; - options.data = text(); - }, - "text", - peg$literalExpectation("text", true), - "image", - peg$literalExpectation("image", true), - "audio", - peg$literalExpectation("audio", true), - "video", - peg$literalExpectation("video", true), - "application", - peg$literalExpectation("application", true), - "message", - peg$literalExpectation("message", true), - "multipart", - peg$literalExpectation("multipart", true), - "x-", - peg$literalExpectation("x-", true), - function (cseq_value) { - options = options || { data: {} }; - options.data.value = parseInt(cseq_value.join('')); - }, - function (expires) { options = options || { data: {} }; options.data = expires; }, - function (event_type) { - options = options || { data: {} }; - options.data.event = event_type.toLowerCase(); - }, - function () { - options = options || { data: {} }; - var tag = options.data.tag; - options.data = new name_addr_header_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); - if (tag) { - options.data.setParam('tag', tag); - } - }, - "tag", - peg$literalExpectation("tag", true), - function (tag) { options = options || { data: {} }; options.data.tag = tag; }, - function (forwards) { - options = options || { data: {} }; - options.data = parseInt(forwards.join('')); - }, - function (min_expires) { options = options || { data: {} }; options.data = min_expires; }, - function () { - options = options || { data: {} }; - options.data = new name_addr_header_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); - }, - "digest", - peg$literalExpectation("Digest", true), - "realm", - peg$literalExpectation("realm", true), - function (realm) { options = options || { data: {} }; options.data.realm = realm; }, - "domain", - peg$literalExpectation("domain", true), - "nonce", - peg$literalExpectation("nonce", true), - function (nonce) { options = options || { data: {} }; options.data.nonce = nonce; }, - "opaque", - peg$literalExpectation("opaque", true), - function (opaque) { options = options || { data: {} }; options.data.opaque = opaque; }, - "stale", - peg$literalExpectation("stale", true), - "true", - peg$literalExpectation("true", true), - function () { options = options || { data: {} }; options.data.stale = true; }, - "false", - peg$literalExpectation("false", true), - function () { options = options || { data: {} }; options.data.stale = false; }, - "algorithm", - peg$literalExpectation("algorithm", true), - "md5", - peg$literalExpectation("MD5", true), - "md5-sess", - peg$literalExpectation("MD5-sess", true), - function (algorithm) { - options = options || { data: {} }; - options.data.algorithm = algorithm.toUpperCase(); - }, - "qop", - peg$literalExpectation("qop", true), - "auth-int", - peg$literalExpectation("auth-int", true), - "auth", - peg$literalExpectation("auth", true), - function (qop_value) { - options = options || { data: {} }; - options.data.qop || (options.data.qop = []); - options.data.qop.push(qop_value.toLowerCase()); - }, - function (rack_value) { - options = options || { data: {} }; - options.data.value = parseInt(rack_value.join('')); - }, - function () { - var idx, length; - options = options || { data: {} }; - length = options.data.multi_header.length; - for (idx = 0; idx < length; idx++) { - if (options.data.multi_header[idx].parsed === null) { - options.data = null; - break; - } - } - if (options.data !== null) { - options.data = options.data.multi_header; - } - else { - options.data = -1; - } - }, - function () { - var header; - options = options || { data: {} }; - if (!options.data.multi_header) - options.data.multi_header = []; - try { - header = new name_addr_header_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); - delete options.data.uri; - delete options.data.displayName; - delete options.data.params; - } - catch (e) { - header = null; - } - options.data.multi_header.push({ 'position': peg$currPos, - 'offset': location().start.offset, - 'parsed': header - }); - }, - function () { - options = options || { data: {} }; - options.data = new name_addr_header_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); - }, - function () { - options = options || { data: {} }; - if (!(options.data.replaces_from_tag && options.data.replaces_to_tag)) { - options.data = -1; - } - }, - function () { - options = options || { data: {} }; - options.data = { - call_id: options.data - }; - }, - "from-tag", - peg$literalExpectation("from-tag", true), - function (from_tag) { - options = options || { data: {} }; - options.data.replaces_from_tag = from_tag; - }, - "to-tag", - peg$literalExpectation("to-tag", true), - function (to_tag) { - options = options || { data: {} }; - options.data.replaces_to_tag = to_tag; - }, - "early-only", - peg$literalExpectation("early-only", true), - function () { - options = options || { data: {} }; - options.data.early_only = true; - }, - function (head, r) { return r; }, - function (head, tail) { return list(head, tail); }, - function (value) { - options = options || { data: {} }; - if (options.startRule === 'Require') { - options.data = value || []; - } - }, - function (rseq_value) { - options = options || { data: {} }; - options.data.value = parseInt(rseq_value.join('')); - }, - "active", - peg$literalExpectation("active", true), - "pending", - peg$literalExpectation("pending", true), - "terminated", - peg$literalExpectation("terminated", true), - function () { - options = options || { data: {} }; - options.data.state = text(); - }, - "reason", - peg$literalExpectation("reason", true), - function (reason) { - options = options || { data: {} }; - if (typeof reason !== 'undefined') - options.data.reason = reason; - }, - function (expires) { - options = options || { data: {} }; - if (typeof expires !== 'undefined') - options.data.expires = expires; - }, - "retry_after", - peg$literalExpectation("retry_after", true), - function (retry_after) { - options = options || { data: {} }; - if (typeof retry_after !== 'undefined') - options.data.retry_after = retry_after; - }, - "deactivated", - peg$literalExpectation("deactivated", true), - "probation", - peg$literalExpectation("probation", true), - "rejected", - peg$literalExpectation("rejected", true), - "timeout", - peg$literalExpectation("timeout", true), - "giveup", - peg$literalExpectation("giveup", true), - "noresource", - peg$literalExpectation("noresource", true), - "invariant", - peg$literalExpectation("invariant", true), - function (value) { - options = options || { data: {} }; - if (options.startRule === 'Supported') { - options.data = value || []; - } - }, - function () { - options = options || { data: {} }; - var tag = options.data.tag; - options.data = new name_addr_header_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); - if (tag) { - options.data.setParam('tag', tag); - } - }, - "ttl", - peg$literalExpectation("ttl", true), - function (via_ttl_value) { - options = options || { data: {} }; - options.data.ttl = via_ttl_value; - }, - "maddr", - peg$literalExpectation("maddr", true), - function (via_maddr) { - options = options || { data: {} }; - options.data.maddr = via_maddr; - }, - "received", - peg$literalExpectation("received", true), - function (via_received) { - options = options || { data: {} }; - options.data.received = via_received; - }, - "branch", - peg$literalExpectation("branch", true), - function (via_branch) { - options = options || { data: {} }; - options.data.branch = via_branch; - }, - "rport", - peg$literalExpectation("rport", true), - function (response_port) { - options = options || { data: {} }; - if (typeof response_port !== 'undefined') - options.data.rport = response_port.join(''); - }, - function (via_protocol) { - options = options || { data: {} }; - options.data.protocol = via_protocol; - }, - peg$literalExpectation("UDP", true), - peg$literalExpectation("TCP", true), - peg$literalExpectation("TLS", true), - peg$literalExpectation("SCTP", true), - function (via_transport) { - options = options || { data: {} }; - options.data.transport = via_transport; - }, - function () { - options = options || { data: {} }; - options.data.host = text(); - }, - function (via_sent_by_port) { - options = options || { data: {} }; - options.data.port = parseInt(via_sent_by_port.join('')); - }, - function (ttl) { - return parseInt(ttl.join('')); - }, - function (deltaSeconds) { - options = options || { data: {} }; - if (options.startRule === 'Session_Expires') { - options.data.deltaSeconds = deltaSeconds; - } - }, - "refresher", - peg$literalExpectation("refresher", false), - "uas", - peg$literalExpectation("uas", false), - "uac", - peg$literalExpectation("uac", false), - function (endpoint) { - options = options || { data: {} }; - if (options.startRule === 'Session_Expires') { - options.data.refresher = endpoint; - } - }, - function (deltaSeconds) { - options = options || { data: {} }; - if (options.startRule === 'Min_SE') { - options.data = deltaSeconds; - } - }, - "stuns", - peg$literalExpectation("stuns", true), - "stun", - peg$literalExpectation("stun", true), - function (scheme) { - options = options || { data: {} }; - options.data.scheme = scheme; - }, - function (host) { - options = options || { data: {} }; - options.data.host = host; - }, - "?transport=", - peg$literalExpectation("?transport=", false), - "turns", - peg$literalExpectation("turns", true), - "turn", - peg$literalExpectation("turn", true), - function (transport) { - options = options || { data: {} }; - options.data.transport = transport; - }, - function () { - options = options || { data: {} }; - options.data = text(); - }, - "Referred-By", - peg$literalExpectation("Referred-By", false), - "b", - peg$literalExpectation("b", false), - "cid", - peg$literalExpectation("cid", false) - ]; - var peg$bytecode = [ - peg$decode("2 \"\"6 7!"), - peg$decode("4\"\"\"5!7#"), - peg$decode("4$\"\"5!7%"), - peg$decode("4&\"\"5!7'"), - peg$decode(";'.# &;("), - peg$decode("4(\"\"5!7)"), - peg$decode("4*\"\"5!7+"), - peg$decode("2,\"\"6,7-"), - peg$decode("2.\"\"6.7/"), - peg$decode("40\"\"5!71"), - peg$decode("22\"\"6273.\x89 &24\"\"6475.} &26\"\"6677.q &28\"\"6879.e &2:\"\"6:7;.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E"), - peg$decode(";).# &;,"), - peg$decode("2F\"\"6F7G.} &2H\"\"6H7I.q &2J\"\"6J7K.e &2L\"\"6L7M.Y &2N\"\"6N7O.M &2P\"\"6P7Q.A &2R\"\"6R7S.5 &2T\"\"6T7U.) &2V\"\"6V7W"), - peg$decode("%%2X\"\"6X7Y/5#;#/,$;#/#$+#)(#'#(\"'#&'#/\"!&,)"), - peg$decode("%%$;$0#*;$&/,#; /#$+\")(\"'#&'#.\" &\"/=#$;$/�#*;$&&&#/'$8\":Z\" )(\"'#&'#"), - peg$decode(";..\" &\""), - peg$decode("%$;'.# &;(0)*;'.# &;(&/?#28\"\"6879/0$;//'$8#:[# )(#'#(\"'#&'#"), - peg$decode("%%$;2/�#*;2&&&#/g#$%$;.0#*;.&/,#;2/#$+\")(\"'#&'#0=*%$;.0#*;.&/,#;2/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/\"!&,)"), - peg$decode("4\\\"\"5!7].# &;3"), - peg$decode("4^\"\"5!7_"), - peg$decode("4`\"\"5!7a"), - peg$decode(";!.) &4b\"\"5!7c"), - peg$decode("%$;).\x95 &2F\"\"6F7G.\x89 &2J\"\"6J7K.} &2L\"\"6L7M.q &2X\"\"6X7Y.e &2P\"\"6P7Q.Y &2H\"\"6H7I.M &2@\"\"6@7A.A &2d\"\"6d7e.5 &2R\"\"6R7S.) &2N\"\"6N7O/\x9E#0\x9B*;).\x95 &2F\"\"6F7G.\x89 &2J\"\"6J7K.} &2L\"\"6L7M.q &2X\"\"6X7Y.e &2P\"\"6P7Q.Y &2H\"\"6H7I.M &2@\"\"6@7A.A &2d\"\"6d7e.5 &2R\"\"6R7S.) &2N\"\"6N7O&&&#/\"!&,)"), - peg$decode("%$;).\x89 &2F\"\"6F7G.} &2L\"\"6L7M.q &2X\"\"6X7Y.e &2P\"\"6P7Q.Y &2H\"\"6H7I.M &2@\"\"6@7A.A &2d\"\"6d7e.5 &2R\"\"6R7S.) &2N\"\"6N7O/\x92#0\x8F*;).\x89 &2F\"\"6F7G.} &2L\"\"6L7M.q &2X\"\"6X7Y.e &2P\"\"6P7Q.Y &2H\"\"6H7I.M &2@\"\"6@7A.A &2d\"\"6d7e.5 &2R\"\"6R7S.) &2N\"\"6N7O&&&#/\"!&,)"), - peg$decode("2T\"\"6T7U.\xE3 &2V\"\"6V7W.\xD7 &2f\"\"6f7g.\xCB &2h\"\"6h7i.\xBF &2:\"\"6:7;.\xB3 &2D\"\"6D7E.\xA7 &22\"\"6273.\x9B &28\"\"6879.\x8F &2j\"\"6j7k.\x83 &;&.} &24\"\"6475.q &2l\"\"6l7m.e &2n\"\"6n7o.Y &26\"\"6677.M &2>\"\"6>7?.A &2p\"\"6p7q.5 &2r\"\"6r7s.) &;'.# &;("), - peg$decode("%$;).\u012B &2F\"\"6F7G.\u011F &2J\"\"6J7K.\u0113 &2L\"\"6L7M.\u0107 &2X\"\"6X7Y.\xFB &2P\"\"6P7Q.\xEF &2H\"\"6H7I.\xE3 &2@\"\"6@7A.\xD7 &2d\"\"6d7e.\xCB &2R\"\"6R7S.\xBF &2N\"\"6N7O.\xB3 &2T\"\"6T7U.\xA7 &2V\"\"6V7W.\x9B &2f\"\"6f7g.\x8F &2h\"\"6h7i.\x83 &28\"\"6879.w &2j\"\"6j7k.k &;&.e &24\"\"6475.Y &2l\"\"6l7m.M &2n\"\"6n7o.A &26\"\"6677.5 &2p\"\"6p7q.) &2r\"\"6r7s/\u0134#0\u0131*;).\u012B &2F\"\"6F7G.\u011F &2J\"\"6J7K.\u0113 &2L\"\"6L7M.\u0107 &2X\"\"6X7Y.\xFB &2P\"\"6P7Q.\xEF &2H\"\"6H7I.\xE3 &2@\"\"6@7A.\xD7 &2d\"\"6d7e.\xCB &2R\"\"6R7S.\xBF &2N\"\"6N7O.\xB3 &2T\"\"6T7U.\xA7 &2V\"\"6V7W.\x9B &2f\"\"6f7g.\x8F &2h\"\"6h7i.\x83 &28\"\"6879.w &2j\"\"6j7k.k &;&.e &24\"\"6475.Y &2l\"\"6l7m.M &2n\"\"6n7o.A &26\"\"6677.5 &2p\"\"6p7q.) &2r\"\"6r7s&&&#/\"!&,)"), - peg$decode("%;//?#2P\"\"6P7Q/0$;//'$8#:t# )(#'#(\"'#&'#"), - peg$decode("%;//?#24\"\"6475/0$;//'$8#:u# )(#'#(\"'#&'#"), - peg$decode("%;//?#2>\"\"6>7?/0$;//'$8#:v# )(#'#(\"'#&'#"), - peg$decode("%;//?#2T\"\"6T7U/0$;//'$8#:w# )(#'#(\"'#&'#"), - peg$decode("%;//?#2V\"\"6V7W/0$;//'$8#:x# )(#'#(\"'#&'#"), - peg$decode("%2h\"\"6h7i/0#;//'$8\":y\" )(\"'#&'#"), - peg$decode("%;//6#2f\"\"6f7g/'$8\":z\" )(\"'#&'#"), - peg$decode("%;//?#2D\"\"6D7E/0$;//'$8#:{# )(#'#(\"'#&'#"), - peg$decode("%;//?#22\"\"6273/0$;//'$8#:|# )(#'#(\"'#&'#"), - peg$decode("%;//?#28\"\"6879/0$;//'$8#:}# )(#'#(\"'#&'#"), - peg$decode("%;//0#;&/'$8\":~\" )(\"'#&'#"), - peg$decode("%;&/0#;//'$8\":~\" )(\"'#&'#"), - peg$decode("%;=/T#$;G.) &;K.# &;F0/*;G.) &;K.# &;F&/,$;>/#$+#)(#'#(\"'#&'#"), - peg$decode("4\x7F\"\"5!7\x80.A &4\x81\"\"5!7\x82.5 &4\x83\"\"5!7\x84.) &;3.# &;."), - peg$decode("%%;//Q#;&/H$$;J.# &;K0)*;J.# &;K&/,$;&/#$+$)($'#(#'#(\"'#&'#/\"!&,)"), - peg$decode("%;//]#;&/T$%$;J.# &;K0)*;J.# &;K&/\"!&,)/1$;&/($8$:\x85$!!)($'#(#'#(\"'#&'#"), - peg$decode(";..G &2L\"\"6L7M.; &4\x86\"\"5!7\x87./ &4\x83\"\"5!7\x84.# &;3"), - peg$decode("%2j\"\"6j7k/J#4\x88\"\"5!7\x89.5 &4\x8A\"\"5!7\x8B.) &4\x8C\"\"5!7\x8D/#$+\")(\"'#&'#"), - peg$decode("%;N/M#28\"\"6879/>$;O.\" &\"/0$;S/'$8$:\x8E$ )($'#(#'#(\"'#&'#"), - peg$decode("%;N/d#28\"\"6879/U$;O.\" &\"/G$;S/>$;_/5$;l.\" &\"/'$8&:\x8F& )(&'#(%'#($'#(#'#(\"'#&'#"), - peg$decode("%3\x90\"\"5$7\x91.) &3\x92\"\"5#7\x93/' 8!:\x94!! )"), - peg$decode("%;P/]#%28\"\"6879/,#;R/#$+\")(\"'#&'#.\" &\"/6$2:\"\"6:7;/'$8#:\x95# )(#'#(\"'#&'#"), - peg$decode("$;+.) &;-.# &;Q/2#0/*;+.) &;-.# &;Q&&&#"), - peg$decode("2<\"\"6<7=.q &2>\"\"6>7?.e &2@\"\"6@7A.Y &2B\"\"6B7C.M &2D\"\"6D7E.A &22\"\"6273.5 &26\"\"6677.) &24\"\"6475"), - peg$decode("%$;+._ &;-.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E0e*;+._ &;-.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E&/& 8!:\x96! )"), - peg$decode("%;T/J#%28\"\"6879/,#;^/#$+\")(\"'#&'#.\" &\"/#$+\")(\"'#&'#"), - peg$decode("%;U.) &;\\.# &;X/& 8!:\x97! )"), - peg$decode("%$%;V/2#2J\"\"6J7K/#$+\")(\"'#&'#0<*%;V/2#2J\"\"6J7K/#$+\")(\"'#&'#&/D#;W/;$2J\"\"6J7K.\" &\"/'$8#:\x98# )(#'#(\"'#&'#"), - peg$decode("$4\x99\"\"5!7\x9A/,#0)*4\x99\"\"5!7\x9A&&&#"), - peg$decode("%4$\"\"5!7%/?#$4\x9B\"\"5!7\x9C0)*4\x9B\"\"5!7\x9C&/#$+\")(\"'#&'#"), - peg$decode("%2l\"\"6l7m/?#;Y/6$2n\"\"6n7o/'$8#:\x9D# )(#'#(\"'#&'#"), - peg$decode("%%;Z/\xB3#28\"\"6879/\xA4$;Z/\x9B$28\"\"6879/\x8C$;Z/\x83$28\"\"6879/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+-)(-'#(,'#(+'#(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0790 &%2\x9E\"\"6\x9E7\x9F/\xA4#;Z/\x9B$28\"\"6879/\x8C$;Z/\x83$28\"\"6879/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+,)(,'#(+'#(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u06F9 &%2\x9E\"\"6\x9E7\x9F/\x8C#;Z/\x83$28\"\"6879/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+*)(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u067A &%2\x9E\"\"6\x9E7\x9F/t#;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+()(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0613 &%2\x9E\"\"6\x9E7\x9F/\\#;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+&)(&'#(%'#($'#(#'#(\"'#&'#.\u05C4 &%2\x9E\"\"6\x9E7\x9F/D#;Z/;$28\"\"6879/,$;[/#$+$)($'#(#'#(\"'#&'#.\u058D &%2\x9E\"\"6\x9E7\x9F/,#;[/#$+\")(\"'#&'#.\u056E &%2\x9E\"\"6\x9E7\x9F/,#;Z/#$+\")(\"'#&'#.\u054F &%;Z/\x9B#2\x9E\"\"6\x9E7\x9F/\x8C$;Z/\x83$28\"\"6879/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$++)(+'#(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u04C7 &%;Z/\xAA#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x83$2\x9E\"\"6\x9E7\x9F/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+*)(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0430 &%;Z/\xB9#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x92$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/k$2\x9E\"\"6\x9E7\x9F/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+))()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u038A &%;Z/\xC8#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xA1$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/z$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/S$2\x9E\"\"6\x9E7\x9F/D$;Z/;$28\"\"6879/,$;[/#$+()(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u02D5 &%;Z/\xD7#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xB0$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x89$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/b$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/;$2\x9E\"\"6\x9E7\x9F/,$;[/#$+')(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0211 &%;Z/\xFE#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xD7$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xB0$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x89$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/b$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/;$2\x9E\"\"6\x9E7\x9F/,$;Z/#$+()(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0126 &%;Z/\u011C#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xF5$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xCE$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xA7$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x80$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/Y$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/2$2\x9E\"\"6\x9E7\x9F/#$+()(('#(''#(&'#(%'#($'#(#'#(\"'#&'#/& 8!:\xA0! )"), - peg$decode("%;#/M#;#.\" &\"/?$;#.\" &\"/1$;#.\" &\"/#$+$)($'#(#'#(\"'#&'#"), - peg$decode("%;Z/;#28\"\"6879/,$;Z/#$+#)(#'#(\"'#&'#.# &;\\"), - peg$decode("%;]/o#2J\"\"6J7K/`$;]/W$2J\"\"6J7K/H$;]/?$2J\"\"6J7K/0$;]/'$8':\xA1' )(''#(&'#(%'#($'#(#'#(\"'#&'#"), - peg$decode("%2\xA2\"\"6\xA27\xA3/2#4\xA4\"\"5!7\xA5/#$+\")(\"'#&'#.\x98 &%2\xA6\"\"6\xA67\xA7/;#4\xA8\"\"5!7\xA9/,$;!/#$+#)(#'#(\"'#&'#.j &%2\xAA\"\"6\xAA7\xAB/5#;!/,$;!/#$+#)(#'#(\"'#&'#.B &%4\xAC\"\"5!7\xAD/,#;!/#$+\")(\"'#&'#.# &;!"), - peg$decode("%%;!.\" &\"/[#;!.\" &\"/M$;!.\" &\"/?$;!.\" &\"/1$;!.\" &\"/#$+%)(%'#($'#(#'#(\"'#&'#/' 8!:\xAE!! )"), - peg$decode("$%22\"\"6273/,#;`/#$+\")(\"'#&'#0<*%22\"\"6273/,#;`/#$+\")(\"'#&'#&"), - peg$decode(";a.A &;b.; &;c.5 &;d./ &;e.) &;f.# &;g"), - peg$decode("%3\xAF\"\"5*7\xB0/a#3\xB1\"\"5#7\xB2.G &3\xB3\"\"5#7\xB4.; &3\xB5\"\"5$7\xB6./ &3\xB7\"\"5#7\xB8.# &;6/($8\":\xB9\"! )(\"'#&'#"), - peg$decode("%3\xBA\"\"5%7\xBB/I#3\xBC\"\"5%7\xBD./ &3\xBE\"\"5\"7\xBF.# &;6/($8\":\xC0\"! )(\"'#&'#"), - peg$decode("%3\xC1\"\"5'7\xC2/1#;\x90/($8\":\xC3\"! )(\"'#&'#"), - peg$decode("%3\xC4\"\"5$7\xC5/1#;\xF0/($8\":\xC6\"! )(\"'#&'#"), - peg$decode("%3\xC7\"\"5&7\xC8/1#;T/($8\":\xC9\"! )(\"'#&'#"), - peg$decode("%3\xCA\"\"5\"7\xCB/N#%2>\"\"6>7?/,#;6/#$+\")(\"'#&'#.\" &\"/'$8\":\xCC\" )(\"'#&'#"), - peg$decode("%;h/P#%2>\"\"6>7?/,#;i/#$+\")(\"'#&'#.\" &\"/)$8\":\xCD\"\"! )(\"'#&'#"), - peg$decode("%$;j/�#*;j&&&#/\"!&,)"), - peg$decode("%$;j/�#*;j&&&#/\"!&,)"), - peg$decode(";k.) &;+.# &;-"), - peg$decode("2l\"\"6l7m.e &2n\"\"6n7o.Y &24\"\"6475.M &28\"\"6879.A &2<\"\"6<7=.5 &2@\"\"6@7A.) &2B\"\"6B7C"), - peg$decode("%26\"\"6677/n#;m/e$$%2<\"\"6<7=/,#;m/#$+\")(\"'#&'#0<*%2<\"\"6<7=/,#;m/#$+\")(\"'#&'#&/#$+#)(#'#(\"'#&'#"), - peg$decode("%;n/A#2>\"\"6>7?/2$;o/)$8#:\xCE#\"\" )(#'#(\"'#&'#"), - peg$decode("$;p.) &;+.# &;-/2#0/*;p.) &;+.# &;-&&&#"), - peg$decode("$;p.) &;+.# &;-0/*;p.) &;+.# &;-&"), - peg$decode("2l\"\"6l7m.e &2n\"\"6n7o.Y &24\"\"6475.M &26\"\"6677.A &28\"\"6879.5 &2@\"\"6@7A.) &2B\"\"6B7C"), - peg$decode(";\x91.# &;r"), - peg$decode("%;\x90/G#;'/>$;s/5$;'/,$;\x84/#$+%)(%'#($'#(#'#(\"'#&'#"), - peg$decode(";M.# &;t"), - peg$decode("%;\x7F/E#28\"\"6879/6$;u.# &;x/'$8#:\xCF# )(#'#(\"'#&'#"), - peg$decode("%;v.# &;w/J#%26\"\"6677/,#;\x83/#$+\")(\"'#&'#.\" &\"/#$+\")(\"'#&'#"), - peg$decode("%2\xD0\"\"6\xD07\xD1/:#;\x80/1$;w.\" &\"/#$+#)(#'#(\"'#&'#"), - peg$decode("%24\"\"6475/,#;{/#$+\")(\"'#&'#"), - peg$decode("%;z/3#$;y0#*;y&/#$+\")(\"'#&'#"), - peg$decode(";*.) &;+.# &;-"), - peg$decode(";+.\x8F &;-.\x89 &22\"\"6273.} &26\"\"6677.q &28\"\"6879.e &2:\"\"6:7;.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E"), - peg$decode("%;|/e#$%24\"\"6475/,#;|/#$+\")(\"'#&'#0<*%24\"\"6475/,#;|/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"), - peg$decode("%$;~0#*;~&/e#$%22\"\"6273/,#;}/#$+\")(\"'#&'#0<*%22\"\"6273/,#;}/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"), - peg$decode("$;~0#*;~&"), - peg$decode(";+.w &;-.q &28\"\"6879.e &2:\"\"6:7;.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E"), - peg$decode("%%;\"/\x87#$;\".G &;!.A &2@\"\"6@7A.5 &2F\"\"6F7G.) &2J\"\"6J7K0M*;\".G &;!.A &2@\"\"6@7A.5 &2F\"\"6F7G.) &2J\"\"6J7K&/#$+\")(\"'#&'#/& 8!:\xD2! )"), - peg$decode(";\x81.# &;\x82"), - peg$decode("%%;O/2#2:\"\"6:7;/#$+\")(\"'#&'#.\" &\"/,#;S/#$+\")(\"'#&'#.\" &\""), - peg$decode("$;+.\x83 &;-.} &2B\"\"6B7C.q &2D\"\"6D7E.e &22\"\"6273.Y &28\"\"6879.M &2:\"\"6:7;.A &2<\"\"6<7=.5 &2>\"\"6>7?.) &2@\"\"6@7A/\x8C#0\x89*;+.\x83 &;-.} &2B\"\"6B7C.q &2D\"\"6D7E.e &22\"\"6273.Y &28\"\"6879.M &2:\"\"6:7;.A &2<\"\"6<7=.5 &2>\"\"6>7?.) &2@\"\"6@7A&&&#"), - peg$decode("$;y0#*;y&"), - peg$decode("%3\x92\"\"5#7\xD3/q#24\"\"6475/b$$;!/�#*;!&&&#/L$2J\"\"6J7K/=$$;!/�#*;!&&&#/'$8%:\xD4% )(%'#($'#(#'#(\"'#&'#"), - peg$decode("2\xD5\"\"6\xD57\xD6"), - peg$decode("2\xD7\"\"6\xD77\xD8"), - peg$decode("2\xD9\"\"6\xD97\xDA"), - peg$decode("2\xDB\"\"6\xDB7\xDC"), - peg$decode("2\xDD\"\"6\xDD7\xDE"), - peg$decode("2\xDF\"\"6\xDF7\xE0"), - peg$decode("2\xE1\"\"6\xE17\xE2"), - peg$decode("2\xE3\"\"6\xE37\xE4"), - peg$decode("2\xE5\"\"6\xE57\xE6"), - peg$decode("2\xE7\"\"6\xE77\xE8"), - peg$decode("2\xE9\"\"6\xE97\xEA"), - peg$decode("%;\x85.Y &;\x86.S &;\x88.M &;\x89.G &;\x8A.A &;\x8B.; &;\x8C.5 &;\x8F./ &;\x8D.) &;\x8E.# &;6/& 8!:\xEB! )"), - peg$decode("%;\x84/G#;'/>$;\x92/5$;'/,$;\x94/#$+%)(%'#($'#(#'#(\"'#&'#"), - peg$decode("%;\x93/' 8!:\xEC!! )"), - peg$decode("%;!/5#;!/,$;!/#$+#)(#'#(\"'#&'#"), - peg$decode("%$;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(0G*;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(&/& 8!:\xED! )"), - peg$decode("%;\xB6/Y#$%;A/,#;\xB6/#$+\")(\"'#&'#06*%;A/,#;\xB6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"), - peg$decode("%;9/N#%2:\"\"6:7;/,#;9/#$+\")(\"'#&'#.\" &\"/'$8\":\xEE\" )(\"'#&'#"), - peg$decode("%;:.c &%;\x98/Y#$%;A/,#;\x98/#$+\")(\"'#&'#06*%;A/,#;\x98/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/& 8!:\xEF! )"), - peg$decode("%;L.# &;\x99/]#$%;B/,#;\x9B/#$+\")(\"'#&'#06*%;B/,#;\x9B/#$+\")(\"'#&'#&/'$8\":\xF0\" )(\"'#&'#"), - peg$decode("%;\x9A.\" &\"/>#;@/5$;M/,$;?/#$+$)($'#(#'#(\"'#&'#"), - peg$decode("%%;6/Y#$%;./,#;6/#$+\")(\"'#&'#06*%;./,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#.# &;H/' 8!:\xF1!! )"), - peg$decode(";\x9C.) &;\x9D.# &;\xA0"), - peg$decode("%3\xF2\"\"5!7\xF3/:#;$;\xCF/5$;./,$;\x90/#$+%)(%'#($'#(#'#(\"'#&'#"), - peg$decode("%$;!/�#*;!&&&#/' 8!:\u014B!! )"), - peg$decode("%;\xD1/]#$%;A/,#;\xD1/#$+\")(\"'#&'#06*%;A/,#;\xD1/#$+\")(\"'#&'#&/'$8\":\u014C\" )(\"'#&'#"), - peg$decode("%;\x99/]#$%;B/,#;\xA0/#$+\")(\"'#&'#06*%;B/,#;\xA0/#$+\")(\"'#&'#&/'$8\":\u014D\" )(\"'#&'#"), - peg$decode("%;L.O &;\x99.I &%;@.\" &\"/:#;t/1$;?.\" &\"/#$+#)(#'#(\"'#&'#/]#$%;B/,#;\xA0/#$+\")(\"'#&'#06*%;B/,#;\xA0/#$+\")(\"'#&'#&/'$8\":\u014E\" )(\"'#&'#"), - peg$decode("%;\xD4/]#$%;B/,#;\xD5/#$+\")(\"'#&'#06*%;B/,#;\xD5/#$+\")(\"'#&'#&/'$8\":\u014F\" )(\"'#&'#"), - peg$decode("%;\x96/& 8!:\u0150! )"), - peg$decode("%3\u0151\"\"5(7\u0152/:#;$;6/5$;;/,$;\xEC/#$+%)(%'#($'#(#'#(\"'#&'#"), - peg$decode("%3\x92\"\"5#7\xD3.# &;6/' 8!:\u018B!! )"), - peg$decode("%3\xB1\"\"5#7\u018C.G &3\xB3\"\"5#7\u018D.; &3\xB7\"\"5#7\u018E./ &3\xB5\"\"5$7\u018F.# &;6/' 8!:\u0190!! )"), - peg$decode("%;\xEE/D#%;C/,#;\xEF/#$+\")(\"'#&'#.\" &\"/#$+\")(\"'#&'#"), - peg$decode("%;U.) &;\\.# &;X/& 8!:\u0191! )"), - peg$decode("%%;!.\" &\"/[#;!.\" &\"/M$;!.\" &\"/?$;!.\" &\"/1$;!.\" &\"/#$+%)(%'#($'#(#'#(\"'#&'#/' 8!:\u0192!! )"), - peg$decode("%%;!/?#;!.\" &\"/1$;!.\" &\"/#$+#)(#'#(\"'#&'#/' 8!:\u0193!! )"), - peg$decode(";\xBE"), - peg$decode("%;\x9E/^#$%;B/,#;\xF3/#$+\")(\"'#&'#06*%;B/,#;\xF3/#$+\")(\"'#&'#&/($8\":\u0194\"!!)(\"'#&'#"), - peg$decode(";\xF4.# &;\xA0"), - peg$decode("%2\u0195\"\"6\u01957\u0196/L#;\"\"6>7?"), - peg$decode("%;\u0100/b#28\"\"6879/S$;\xFB/J$%2\u01A3\"\"6\u01A37\u01A4/,#;\xEC/#$+\")(\"'#&'#.\" &\"/#$+$)($'#(#'#(\"'#&'#"), - peg$decode("%3\u01A5\"\"5%7\u01A6.) &3\u01A7\"\"5$7\u01A8/' 8!:\u01A1!! )"), - peg$decode("%3\xB1\"\"5#7\xB2.6 &3\xB3\"\"5#7\xB4.* &$;+0#*;+&/' 8!:\u01A9!! )"), - peg$decode("%;\u0104/\x87#2F\"\"6F7G/x$;\u0103/o$2F\"\"6F7G/`$;\u0103/W$2F\"\"6F7G/H$;\u0103/?$2F\"\"6F7G/0$;\u0105/'$8):\u01AA) )()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#"), - peg$decode("%;#/>#;#/5$;#/,$;#/#$+$)($'#(#'#(\"'#&'#"), - peg$decode("%;\u0103/,#;\u0103/#$+\")(\"'#&'#"), - peg$decode("%;\u0103/5#;\u0103/,$;\u0103/#$+#)(#'#(\"'#&'#"), - peg$decode("%;q/T#$;m0#*;m&/D$%; /,#;\xF8/#$+\")(\"'#&'#.\" &\"/#$+#)(#'#(\"'#&'#"), - peg$decode("%2\u01AB\"\"6\u01AB7\u01AC.) &2\u01AD\"\"6\u01AD7\u01AE/w#;0/n$;\u0108/e$$%;B/2#;\u0109.# &;\xA0/#$+\")(\"'#&'#0<*%;B/2#;\u0109.# &;\xA0/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"), - peg$decode(";\x99.# &;L"), - peg$decode("%2\u01AF\"\"6\u01AF7\u01B0/5#; peg$maxFailPos) { - peg$maxFailPos = peg$currPos; - peg$maxFailExpected = []; - } - peg$maxFailExpected.push(expected1); - } - function peg$buildSimpleError(message, location1) { - return new SyntaxError(message, [], "", location1); - } - function peg$buildStructuredError(expected1, found, location1) { - return new SyntaxError(SyntaxError.buildMessage(expected1, found), expected1, found, location1); - } - function peg$decode(s) { - return s.split("").map(function (ch) { return ch.charCodeAt(0) - 32; }); - } - function peg$parseRule(index) { - var bc = peg$bytecode[index]; - var ip = 0; - var ips = []; - var end = bc.length; - var ends = []; - var stack = []; - var params; - while (true) { - while (ip < end) { - switch (bc[ip]) { - case 0: - stack.push(peg$consts[bc[ip + 1]]); - ip += 2; - break; - case 1: - stack.push(undefined); - ip++; - break; - case 2: - stack.push(null); - ip++; - break; - case 3: - stack.push(peg$FAILED); - ip++; - break; - case 4: - stack.push([]); - ip++; - break; - case 5: - stack.push(peg$currPos); - ip++; - break; - case 6: - stack.pop(); - ip++; - break; - case 7: - peg$currPos = stack.pop(); - ip++; - break; - case 8: - stack.length -= bc[ip + 1]; - ip += 2; - break; - case 9: - stack.splice(-2, 1); - ip++; - break; - case 10: - stack[stack.length - 2].push(stack.pop()); - ip++; - break; - case 11: - stack.push(stack.splice(stack.length - bc[ip + 1], bc[ip + 1])); - ip += 2; - break; - case 12: - stack.push(input.substring(stack.pop(), peg$currPos)); - ip++; - break; - case 13: - ends.push(end); - ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); - if (stack[stack.length - 1]) { - end = ip + 3 + bc[ip + 1]; - ip += 3; - } - else { - end = ip + 3 + bc[ip + 1] + bc[ip + 2]; - ip += 3 + bc[ip + 1]; - } - break; - case 14: - ends.push(end); - ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); - if (stack[stack.length - 1] === peg$FAILED) { - end = ip + 3 + bc[ip + 1]; - ip += 3; - } - else { - end = ip + 3 + bc[ip + 1] + bc[ip + 2]; - ip += 3 + bc[ip + 1]; - } - break; - case 15: - ends.push(end); - ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); - if (stack[stack.length - 1] !== peg$FAILED) { - end = ip + 3 + bc[ip + 1]; - ip += 3; - } - else { - end = ip + 3 + bc[ip + 1] + bc[ip + 2]; - ip += 3 + bc[ip + 1]; - } - break; - case 16: - if (stack[stack.length - 1] !== peg$FAILED) { - ends.push(end); - ips.push(ip); - end = ip + 2 + bc[ip + 1]; - ip += 2; - } - else { - ip += 2 + bc[ip + 1]; - } - break; - case 17: - ends.push(end); - ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); - if (input.length > peg$currPos) { - end = ip + 3 + bc[ip + 1]; - ip += 3; - } - else { - end = ip + 3 + bc[ip + 1] + bc[ip + 2]; - ip += 3 + bc[ip + 1]; - } - break; - case 18: - ends.push(end); - ips.push(ip + 4 + bc[ip + 2] + bc[ip + 3]); - if (input.substr(peg$currPos, peg$consts[bc[ip + 1]].length) === peg$consts[bc[ip + 1]]) { - end = ip + 4 + bc[ip + 2]; - ip += 4; - } - else { - end = ip + 4 + bc[ip + 2] + bc[ip + 3]; - ip += 4 + bc[ip + 2]; - } - break; - case 19: - ends.push(end); - ips.push(ip + 4 + bc[ip + 2] + bc[ip + 3]); - if (input.substr(peg$currPos, peg$consts[bc[ip + 1]].length).toLowerCase() === peg$consts[bc[ip + 1]]) { - end = ip + 4 + bc[ip + 2]; - ip += 4; - } - else { - end = ip + 4 + bc[ip + 2] + bc[ip + 3]; - ip += 4 + bc[ip + 2]; - } - break; - case 20: - ends.push(end); - ips.push(ip + 4 + bc[ip + 2] + bc[ip + 3]); - if (peg$consts[bc[ip + 1]].test(input.charAt(peg$currPos))) { - end = ip + 4 + bc[ip + 2]; - ip += 4; - } - else { - end = ip + 4 + bc[ip + 2] + bc[ip + 3]; - ip += 4 + bc[ip + 2]; - } - break; - case 21: - stack.push(input.substr(peg$currPos, bc[ip + 1])); - peg$currPos += bc[ip + 1]; - ip += 2; - break; - case 22: - stack.push(peg$consts[bc[ip + 1]]); - peg$currPos += peg$consts[bc[ip + 1]].length; - ip += 2; - break; - case 23: - stack.push(peg$FAILED); - if (peg$silentFails === 0) { - peg$fail(peg$consts[bc[ip + 1]]); - } - ip += 2; - break; - case 24: - peg$savedPos = stack[stack.length - 1 - bc[ip + 1]]; - ip += 2; - break; - case 25: - peg$savedPos = peg$currPos; - ip++; - break; - case 26: - params = bc.slice(ip + 4, ip + 4 + bc[ip + 3]) - .map(function (p) { return stack[stack.length - 1 - p]; }); - stack.splice(stack.length - bc[ip + 2], bc[ip + 2], peg$consts[bc[ip + 1]].apply(null, params)); - ip += 4 + bc[ip + 3]; - break; - case 27: - stack.push(peg$parseRule(bc[ip + 1])); - ip += 2; - break; - case 28: - peg$silentFails++; - ip++; - break; - case 29: - peg$silentFails--; - ip++; - break; - default: - throw new Error("Invalid opcode: " + bc[ip] + "."); - } - } - if (ends.length > 0) { - end = ends.pop(); - ip = ips.pop(); - } - else { - break; - } - } - return stack[0]; - } - options.data = {}; // Object to which header attributes will be assigned during parsing - function list(head, tail) { - return [head].concat(tail); - } - peg$result = peg$parseRule(peg$startRuleIndex); - if (peg$result !== peg$FAILED && peg$currPos === input.length) { - return peg$result; - } - else { - if (peg$result !== peg$FAILED && peg$currPos < input.length) { - peg$fail(peg$endExpectation()); - } - throw peg$buildStructuredError(peg$maxFailExpected, peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, peg$maxFailPos < input.length - ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) - : peg$computeLocation(peg$maxFailPos, peg$maxFailPos)); - } -} -exports.parse = peg$parse; - - -/***/ }), -/* 13 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var parameters_1 = __webpack_require__(14); -/** - * Name Address SIP header. - * @public - */ -var NameAddrHeader = /** @class */ (function (_super) { - tslib_1.__extends(NameAddrHeader, _super); - /** - * Constructor - * @param uri - - * @param displayName - - * @param parameters - - */ - function NameAddrHeader(uri, displayName, parameters) { - var _this = _super.call(this, parameters) || this; - _this.uri = uri; - _this._displayName = displayName; - return _this; - } - Object.defineProperty(NameAddrHeader.prototype, "friendlyName", { - get: function () { - return this.displayName || this.uri.aor; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(NameAddrHeader.prototype, "displayName", { - get: function () { return this._displayName; }, - set: function (value) { - this._displayName = value; - }, - enumerable: true, - configurable: true - }); - NameAddrHeader.prototype.clone = function () { - return new NameAddrHeader(this.uri.clone(), this._displayName, JSON.parse(JSON.stringify(this.parameters))); - }; - NameAddrHeader.prototype.toString = function () { - var body = (this.displayName || this.displayName === "0") ? '"' + this.displayName + '" ' : ""; - body += "<" + this.uri.toString() + ">"; - for (var parameter in this.parameters) { - if (this.parameters.hasOwnProperty(parameter)) { - body += ";" + parameter; - if (this.parameters[parameter] !== null) { - body += "=" + this.parameters[parameter]; - } - } - } - return body; - }; - return NameAddrHeader; -}(parameters_1.Parameters)); -exports.NameAddrHeader = NameAddrHeader; - - -/***/ }), -/* 14 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * @internal - */ -var Parameters = /** @class */ (function () { - function Parameters(parameters) { - this.parameters = {}; - for (var param in parameters) { - if (parameters.hasOwnProperty(param)) { - this.setParam(param, parameters[param]); - } - } - } - Parameters.prototype.setParam = function (key, value) { - if (key) { - this.parameters[key.toLowerCase()] = (typeof value === "undefined" || value === null) ? null : value.toString(); - } - }; - Parameters.prototype.getParam = function (key) { - if (key) { - return this.parameters[key.toLowerCase()]; - } - }; - Parameters.prototype.hasParam = function (key) { - if (key) { - return !!this.parameters.hasOwnProperty(key.toLowerCase()); - } - return false; - }; - Parameters.prototype.deleteParam = function (parameter) { - parameter = parameter.toLowerCase(); - if (this.parameters.hasOwnProperty(parameter)) { - var value = this.parameters[parameter]; - delete this.parameters[parameter]; - return value; - } - }; - Parameters.prototype.clearParams = function () { - this.parameters = {}; - }; - return Parameters; -}()); -exports.Parameters = Parameters; - - -/***/ }), -/* 15 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var parameters_1 = __webpack_require__(14); -/** - * URI. - * @public - */ -var URI = /** @class */ (function (_super) { - tslib_1.__extends(URI, _super); - /** - * Constructor - * @param scheme - - * @param user - - * @param host - - * @param port - - * @param parameters - - * @param headers - - */ - function URI(scheme, user, host, port, parameters, headers) { - var _this = _super.call(this, parameters) || this; - _this.headers = {}; - // Checks - if (!host) { - throw new TypeError('missing or invalid "host" parameter'); - } - // Initialize parameters - scheme = scheme || "sip"; - for (var header in headers) { - if (headers.hasOwnProperty(header)) { - _this.setHeader(header, headers[header]); - } - } - // Raw URI - _this.raw = { - scheme: scheme, - user: user, - host: host, - port: port - }; - // Normalized URI - _this.normal = { - scheme: scheme.toLowerCase(), - user: user, - host: host.toLowerCase(), - port: port - }; - return _this; - } - Object.defineProperty(URI.prototype, "scheme", { - get: function () { return this.normal.scheme; }, - set: function (value) { - this.raw.scheme = value; - this.normal.scheme = value.toLowerCase(); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(URI.prototype, "user", { - get: function () { return this.normal.user; }, - set: function (value) { - this.normal.user = this.raw.user = value; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(URI.prototype, "host", { - get: function () { return this.normal.host; }, - set: function (value) { - this.raw.host = value; - this.normal.host = value.toLowerCase(); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(URI.prototype, "aor", { - get: function () { return this.normal.user + "@" + this.normal.host; }, - enumerable: true, - configurable: true - }); - Object.defineProperty(URI.prototype, "port", { - get: function () { return this.normal.port; }, - set: function (value) { - this.normal.port = this.raw.port = value === 0 ? value : value; - }, - enumerable: true, - configurable: true - }); - URI.prototype.setHeader = function (name, value) { - this.headers[this.headerize(name)] = (value instanceof Array) ? value : [value]; - }; - URI.prototype.getHeader = function (name) { - if (name) { - return this.headers[this.headerize(name)]; - } - }; - URI.prototype.hasHeader = function (name) { - return !!name && !!this.headers.hasOwnProperty(this.headerize(name)); - }; - URI.prototype.deleteHeader = function (header) { - header = this.headerize(header); - if (this.headers.hasOwnProperty(header)) { - var value = this.headers[header]; - delete this.headers[header]; - return value; - } - }; - URI.prototype.clearHeaders = function () { - this.headers = {}; - }; - URI.prototype.clone = function () { - return new URI(this._raw.scheme, this._raw.user || "", this._raw.host, this._raw.port, JSON.parse(JSON.stringify(this.parameters)), JSON.parse(JSON.stringify(this.headers))); - }; - URI.prototype.toRaw = function () { - return this._toString(this._raw); - }; - URI.prototype.toString = function () { - return this._toString(this._normal); - }; - Object.defineProperty(URI.prototype, "_normal", { - get: function () { return this.normal; }, - enumerable: true, - configurable: true - }); - Object.defineProperty(URI.prototype, "_raw", { - get: function () { return this.raw; }, - enumerable: true, - configurable: true - }); - URI.prototype._toString = function (uri) { - var uriString = uri.scheme + ":"; - // add slashes if it's not a sip(s) URI - if (!uri.scheme.toLowerCase().match("^sips?$")) { - uriString += "//"; - } - if (uri.user) { - uriString += this.escapeUser(uri.user) + "@"; - } - uriString += uri.host; - if (uri.port || uri.port === 0) { - uriString += ":" + uri.port; - } - for (var parameter in this.parameters) { - if (this.parameters.hasOwnProperty(parameter)) { - uriString += ";" + parameter; - if (this.parameters[parameter] !== null) { - uriString += "=" + this.parameters[parameter]; - } - } - } - var headers = []; - for (var header in this.headers) { - if (this.headers.hasOwnProperty(header)) { - for (var idx in this.headers[header]) { - if (this.headers[header].hasOwnProperty(idx)) { - headers.push(header + "=" + this.headers[header][idx]); - } - } - } - } - if (headers.length > 0) { - uriString += "?" + headers.join("&"); - } - return uriString; - }; - /* - * Hex-escape a SIP URI user. - * @private - * @param {String} user - */ - URI.prototype.escapeUser = function (user) { - var decodedUser; - // FIXME: This is called by toString above which should never throw, but - // decodeURIComponent can throw and I've seen one case in production where - // it did throw resulting in a cascading failure. This class should be - // fixed so that decodeURIComponent is not called at this point (in toString). - // The user should be decoded when the URI is constructor or some other - // place where we can catch the error before the URI is created or somesuch. - try { - decodedUser = decodeURIComponent(user); - } - catch (error) { - throw error; - } - // Don't hex-escape ':' (%3A), '+' (%2B), '?' (%3F"), '/' (%2F). - return encodeURIComponent(decodedUser) - .replace(/%3A/ig, ":") - .replace(/%2B/ig, "+") - .replace(/%3F/ig, "?") - .replace(/%2F/ig, "/"); - }; - URI.prototype.headerize = function (str) { - var exceptions = { - "Call-Id": "Call-ID", - "Cseq": "CSeq", - "Min-Se": "Min-SE", - "Rack": "RAck", - "Rseq": "RSeq", - "Www-Authenticate": "WWW-Authenticate", - }; - var name = str.toLowerCase().replace(/_/g, "-").split("-"); - var parts = name.length; - var hname = ""; - for (var part = 0; part < parts; part++) { - if (part !== 0) { - hname += "-"; - } - hname += name[part].charAt(0).toUpperCase() + name[part].substring(1); - } - if (exceptions[hname]) { - hname = exceptions[hname]; - } - return hname; - }; - return URI; -}(parameters_1.Parameters)); -exports.URI = URI; - - -/***/ }), -/* 16 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * @param size - - * @param base - - * @internal - */ -function createRandomToken(size, base) { - if (base === void 0) { base = 32; } - var token = ""; - for (var i = 0; i < size; i++) { - var r = Math.floor(Math.random() * base); - token += r.toString(base); - } - return token; -} -exports.createRandomToken = createRandomToken; -/** - * @internal - */ -function getReasonPhrase(code) { - return REASON_PHRASE[code] || ""; -} -exports.getReasonPhrase = getReasonPhrase; -/** - * @internal - */ -function newTag() { - return createRandomToken(10); -} -exports.newTag = newTag; -/** - * @param str - - * @internal - */ -function headerize(str) { - var exceptions = { - "Call-Id": "Call-ID", - "Cseq": "CSeq", - "Min-Se": "Min-SE", - "Rack": "RAck", - "Rseq": "RSeq", - "Www-Authenticate": "WWW-Authenticate", - }; - var name = str.toLowerCase().replace(/_/g, "-").split("-"); - var parts = name.length; - var hname = ""; - for (var part = 0; part < parts; part++) { - if (part !== 0) { - hname += "-"; - } - hname += name[part].charAt(0).toUpperCase() + name[part].substring(1); - } - if (exceptions[hname]) { - hname = exceptions[hname]; - } - return hname; -} -exports.headerize = headerize; -/** - * @param str - - * @internal - */ -function str_utf8_length(str) { - return encodeURIComponent(str).replace(/%[A-F\d]{2}/g, "U").length; -} -exports.str_utf8_length = str_utf8_length; -/** - * SIP Response Reasons - * DOC: http://www.iana.org/assignments/sip-parameters - * @internal - */ -var REASON_PHRASE = { - 100: "Trying", - 180: "Ringing", - 181: "Call Is Being Forwarded", - 182: "Queued", - 183: "Session Progress", - 199: "Early Dialog Terminated", - 200: "OK", - 202: "Accepted", - 204: "No Notification", - 300: "Multiple Choices", - 301: "Moved Permanently", - 302: "Moved Temporarily", - 305: "Use Proxy", - 380: "Alternative Service", - 400: "Bad Request", - 401: "Unauthorized", - 402: "Payment Required", - 403: "Forbidden", - 404: "Not Found", - 405: "Method Not Allowed", - 406: "Not Acceptable", - 407: "Proxy Authentication Required", - 408: "Request Timeout", - 410: "Gone", - 412: "Conditional Request Failed", - 413: "Request Entity Too Large", - 414: "Request-URI Too Long", - 415: "Unsupported Media Type", - 416: "Unsupported URI Scheme", - 417: "Unknown Resource-Priority", - 420: "Bad Extension", - 421: "Extension Required", - 422: "Session Interval Too Small", - 423: "Interval Too Brief", - 428: "Use Identity Header", - 429: "Provide Referrer Identity", - 430: "Flow Failed", - 433: "Anonymity Disallowed", - 436: "Bad Identity-Info", - 437: "Unsupported Certificate", - 438: "Invalid Identity Header", - 439: "First Hop Lacks Outbound Support", - 440: "Max-Breadth Exceeded", - 469: "Bad Info Package", - 470: "Consent Needed", - 478: "Unresolvable Destination", - 480: "Temporarily Unavailable", - 481: "Call/Transaction Does Not Exist", - 482: "Loop Detected", - 483: "Too Many Hops", - 484: "Address Incomplete", - 485: "Ambiguous", - 486: "Busy Here", - 487: "Request Terminated", - 488: "Not Acceptable Here", - 489: "Bad Event", - 491: "Request Pending", - 493: "Undecipherable", - 494: "Security Agreement Required", - 500: "Internal Server Error", - 501: "Not Implemented", - 502: "Bad Gateway", - 503: "Service Unavailable", - 504: "Server Time-out", - 505: "Version Not Supported", - 513: "Message Too Large", - 580: "Precondition Failure", - 600: "Busy Everywhere", - 603: "Decline", - 604: "Does Not Exist Anywhere", - 606: "Not Acceptable" -}; - - -/***/ }), -/* 17 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var incoming_message_1 = __webpack_require__(10); -/** - * Incoming response message. - * @public - */ -var IncomingResponseMessage = /** @class */ (function (_super) { - tslib_1.__extends(IncomingResponseMessage, _super); - function IncomingResponseMessage() { - return _super.call(this) || this; - } - return IncomingResponseMessage; -}(incoming_message_1.IncomingMessage)); -exports.IncomingResponseMessage = IncomingResponseMessage; - - -/***/ }), -/* 18 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var name_addr_header_1 = __webpack_require__(13); -var utils_1 = __webpack_require__(16); -/** - * Outgoing SIP request message. - * @public - */ -var OutgoingRequestMessage = /** @class */ (function () { - function OutgoingRequestMessage(method, ruri, fromURI, toURI, options, extraHeaders, body) { - this.headers = {}; - this.extraHeaders = []; - this.options = OutgoingRequestMessage.getDefaultOptions(); - // Options - merge a deep copy - if (options) { - this.options = tslib_1.__assign({}, this.options, options); - if (this.options.optionTags && this.options.optionTags.length) { - this.options.optionTags = this.options.optionTags.slice(); - } - if (this.options.routeSet && this.options.routeSet.length) { - this.options.routeSet = this.options.routeSet.slice(); - } - } - // Extra headers - deep copy - if (extraHeaders && extraHeaders.length) { - this.extraHeaders = extraHeaders.slice(); - } - // Body - deep copy - if (body) { - // TODO: internal representation should be Body - // this.body = { ...body }; - this.body = { - body: body.content, - contentType: body.contentType - }; - } - // Method - this.method = method; - // RURI - this.ruri = ruri.clone(); - // From - this.fromURI = fromURI.clone(); - this.fromTag = this.options.fromTag ? this.options.fromTag : utils_1.newTag(); - this.from = OutgoingRequestMessage.makeNameAddrHeader(this.fromURI, this.options.fromDisplayName, this.fromTag); - // To - this.toURI = toURI.clone(); - this.toTag = this.options.toTag; - this.to = OutgoingRequestMessage.makeNameAddrHeader(this.toURI, this.options.toDisplayName, this.toTag); - // Call-ID - this.callId = this.options.callId ? this.options.callId : this.options.callIdPrefix + utils_1.createRandomToken(15); - // CSeq - this.cseq = this.options.cseq; - // The relative order of header fields with different field names is not - // significant. However, it is RECOMMENDED that header fields which are - // needed for proxy processing (Via, Route, Record-Route, Proxy-Require, - // Max-Forwards, and Proxy-Authorization, for example) appear towards - // the top of the message to facilitate rapid parsing. - // https://tools.ietf.org/html/rfc3261#section-7.3.1 - this.setHeader("route", this.options.routeSet); - this.setHeader("via", ""); - this.setHeader("to", this.to.toString()); - this.setHeader("from", this.from.toString()); - this.setHeader("cseq", this.cseq + " " + this.method); - this.setHeader("call-id", this.callId); - this.setHeader("max-forwards", "70"); - } - /** Get a copy of the default options. */ - OutgoingRequestMessage.getDefaultOptions = function () { - return { - callId: "", - callIdPrefix: "", - cseq: 1, - toDisplayName: "", - toTag: "", - fromDisplayName: "", - fromTag: "", - forceRport: false, - hackViaTcp: false, - optionTags: ["outbound"], - routeSet: [], - userAgentString: "sip.js", - viaHost: "" - }; - }; - OutgoingRequestMessage.makeNameAddrHeader = function (uri, displayName, tag) { - var parameters = {}; - if (tag) { - parameters.tag = tag; - } - return new name_addr_header_1.NameAddrHeader(uri, displayName, parameters); - }; - /** - * Get the value of the given header name at the given position. - * @param name - header name - * @returns Returns the specified header, undefined if header doesn't exist. - */ - OutgoingRequestMessage.prototype.getHeader = function (name) { - var header = this.headers[utils_1.headerize(name)]; - if (header) { - if (header[0]) { - return header[0]; - } - } - else { - var regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); - for (var _i = 0, _a = this.extraHeaders; _i < _a.length; _i++) { - var exHeader = _a[_i]; - if (regexp.test(exHeader)) { - return exHeader.substring(exHeader.indexOf(":") + 1).trim(); - } - } - } - return; - }; - /** - * Get the header/s of the given name. - * @param name - header name - * @returns Array with all the headers of the specified name. - */ - OutgoingRequestMessage.prototype.getHeaders = function (name) { - var result = []; - var headerArray = this.headers[utils_1.headerize(name)]; - if (headerArray) { - for (var _i = 0, headerArray_1 = headerArray; _i < headerArray_1.length; _i++) { - var headerPart = headerArray_1[_i]; - result.push(headerPart); - } - } - else { - var regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); - for (var _a = 0, _b = this.extraHeaders; _a < _b.length; _a++) { - var exHeader = _b[_a]; - if (regexp.test(exHeader)) { - result.push(exHeader.substring(exHeader.indexOf(":") + 1).trim()); - } - } - } - return result; - }; - /** - * Verify the existence of the given header. - * @param name - header name - * @returns true if header with given name exists, false otherwise - */ - OutgoingRequestMessage.prototype.hasHeader = function (name) { - if (this.headers[utils_1.headerize(name)]) { - return true; - } - else { - var regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); - for (var _i = 0, _a = this.extraHeaders; _i < _a.length; _i++) { - var extraHeader = _a[_i]; - if (regexp.test(extraHeader)) { - return true; - } - } - } - return false; - }; - /** - * Replace the the given header by the given value. - * @param name - header name - * @param value - header value - */ - OutgoingRequestMessage.prototype.setHeader = function (name, value) { - this.headers[utils_1.headerize(name)] = (value instanceof Array) ? value : [value]; - }; - /** - * The Via header field indicates the transport used for the transaction - * and identifies the location where the response is to be sent. A Via - * header field value is added only after the transport that will be - * used to reach the next hop has been selected (which may involve the - * usage of the procedures in [4]). - * - * When the UAC creates a request, it MUST insert a Via into that - * request. The protocol name and protocol version in the header field - * MUST be SIP and 2.0, respectively. The Via header field value MUST - * contain a branch parameter. This parameter is used to identify the - * transaction created by that request. This parameter is used by both - * the client and the server. - * https://tools.ietf.org/html/rfc3261#section-8.1.1.7 - * @param branchParameter - The branch parameter. - * @param scheme - The scheme. - */ - OutgoingRequestMessage.prototype.setViaHeader = function (branch, scheme) { - if (scheme === void 0) { scheme = "WSS"; } - // FIXME: Hack - if (this.options.hackViaTcp) { - scheme = "TCP"; - } - var via = "SIP/2.0/" + scheme; - via += " " + this.options.viaHost + ";branch=" + branch; - if (this.options.forceRport) { - via += ";rport"; - } - this.setHeader("via", via); - this.branch = branch; - }; - OutgoingRequestMessage.prototype.toString = function () { - var msg = ""; - msg += this.method + " " + this.ruri.toRaw() + " SIP/2.0\r\n"; - for (var header in this.headers) { - if (this.headers[header]) { - for (var _i = 0, _a = this.headers[header]; _i < _a.length; _i++) { - var headerPart = _a[_i]; - msg += header + ": " + headerPart + "\r\n"; - } - } - } - for (var _b = 0, _c = this.extraHeaders; _b < _c.length; _b++) { - var header = _c[_b]; - msg += header.trim() + "\r\n"; - } - msg += "Supported: " + this.options.optionTags.join(", ") + "\r\n"; - msg += "User-Agent: " + this.options.userAgentString + "\r\n"; - if (this.body) { - if (typeof this.body === "string") { - msg += "Content-Length: " + utils_1.str_utf8_length(this.body) + "\r\n\r\n"; - msg += this.body; - } - else { - if (this.body.body && this.body.contentType) { - msg += "Content-Type: " + this.body.contentType + "\r\n"; - msg += "Content-Length: " + utils_1.str_utf8_length(this.body.body) + "\r\n\r\n"; - msg += this.body.body; - } - else { - msg += "Content-Length: " + 0 + "\r\n\r\n"; - } - } - } - else { - msg += "Content-Length: " + 0 + "\r\n\r\n"; - } - return msg; - }; - return OutgoingRequestMessage; -}()); -exports.OutgoingRequestMessage = OutgoingRequestMessage; - - -/***/ }), -/* 19 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var md5_1 = tslib_1.__importDefault(__webpack_require__(20)); -var utils_1 = __webpack_require__(16); -/** - * Digest Authentication. - * @internal - */ -var DigestAuthentication = /** @class */ (function () { - /** - * Constructor. - * @param loggerFactory - LoggerFactory. - * @param username - Username. - * @param password - Password. - */ - function DigestAuthentication(loggerFactory, username, password) { - this.logger = loggerFactory.getLogger("sipjs.digestauthentication"); - this.username = username; - this.password = password; - this.nc = 0; - this.ncHex = "00000000"; - } - /** - * Performs Digest authentication given a SIP request and the challenge - * received in a response to that request. - * @param request - - * @param challenge - - * @returns true if credentials were successfully generated, false otherwise. - */ - DigestAuthentication.prototype.authenticate = function (request, challenge, body) { - // Inspect and validate the challenge. - this.algorithm = challenge.algorithm; - this.realm = challenge.realm; - this.nonce = challenge.nonce; - this.opaque = challenge.opaque; - this.stale = challenge.stale; - if (this.algorithm) { - if (this.algorithm !== "MD5") { - this.logger.warn("challenge with Digest algorithm different than 'MD5', authentication aborted"); - return false; - } - } - else { - this.algorithm = "MD5"; - } - if (!this.realm) { - this.logger.warn("challenge without Digest realm, authentication aborted"); - return false; - } - if (!this.nonce) { - this.logger.warn("challenge without Digest nonce, authentication aborted"); - return false; - } - // 'qop' can contain a list of values (Array). Let's choose just one. - if (challenge.qop) { - if (challenge.qop.indexOf("auth") > -1) { - this.qop = "auth"; - } - else if (challenge.qop.indexOf("auth-int") > -1) { - this.qop = "auth-int"; - } - else { - // Otherwise 'qop' is present but does not contain 'auth' or 'auth-int', so abort here. - this.logger.warn("challenge without Digest qop different than 'auth' or 'auth-int', authentication aborted"); - return false; - } - } - else { - this.qop = undefined; - } - // Fill other attributes. - this.method = request.method; - this.uri = request.ruri; - this.cnonce = utils_1.createRandomToken(12); - this.nc += 1; - this.updateNcHex(); - // nc-value = 8LHEX. Max value = 'FFFFFFFF'. - if (this.nc === 4294967296) { - this.nc = 1; - this.ncHex = "00000001"; - } - // Calculate the Digest "response" value. - this.calculateResponse(body); - return true; - }; - /** - * Return the Proxy-Authorization or WWW-Authorization header value. - */ - DigestAuthentication.prototype.toString = function () { - var authParams = []; - if (!this.response) { - throw new Error("response field does not exist, cannot generate Authorization header"); - } - authParams.push("algorithm=" + this.algorithm); - authParams.push('username="' + this.username + '"'); - authParams.push('realm="' + this.realm + '"'); - authParams.push('nonce="' + this.nonce + '"'); - authParams.push('uri="' + this.uri + '"'); - authParams.push('response="' + this.response + '"'); - if (this.opaque) { - authParams.push('opaque="' + this.opaque + '"'); - } - if (this.qop) { - authParams.push("qop=" + this.qop); - authParams.push('cnonce="' + this.cnonce + '"'); - authParams.push("nc=" + this.ncHex); - } - return "Digest " + authParams.join(", "); - }; - /** - * Generate the 'nc' value as required by Digest in this.ncHex by reading this.nc. - */ - DigestAuthentication.prototype.updateNcHex = function () { - var hex = Number(this.nc).toString(16); - this.ncHex = "00000000".substr(0, 8 - hex.length) + hex; - }; - /** - * Generate Digest 'response' value. - */ - DigestAuthentication.prototype.calculateResponse = function (body) { - var ha2; - // HA1 = MD5(A1) = MD5(username:realm:password) - var ha1 = md5_1.default(this.username + ":" + this.realm + ":" + this.password); - if (this.qop === "auth") { - // HA2 = MD5(A2) = MD5(method:digestURI) - ha2 = md5_1.default(this.method + ":" + this.uri); - // response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2) - this.response = md5_1.default(ha1 + ":" + this.nonce + ":" + this.ncHex + ":" + this.cnonce + ":auth:" + ha2); - } - else if (this.qop === "auth-int") { - // HA2 = MD5(A2) = MD5(method:digestURI:MD5(entityBody)) - ha2 = md5_1.default(this.method + ":" + this.uri + ":" + md5_1.default(body ? body : "")); - // response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2) - this.response = md5_1.default(ha1 + ":" + this.nonce + ":" + this.ncHex + ":" + this.cnonce + ":auth-int:" + ha2); - } - else if (this.qop === undefined) { - // HA2 = MD5(A2) = MD5(method:digestURI) - ha2 = md5_1.default(this.method + ":" + this.uri); - // response = MD5(HA1:nonce:HA2) - this.response = md5_1.default(ha1 + ":" + this.nonce + ":" + ha2); - } - }; - return DigestAuthentication; -}()); -exports.DigestAuthentication = DigestAuthentication; - - -/***/ }), -/* 20 */ -/***/ (function(module, exports, __webpack_require__) { - -;(function (root, factory) { - if (true) { - // CommonJS - module.exports = exports = factory(__webpack_require__(21)); - } - else {} -}(this, function (CryptoJS) { - - (function (Math) { - // Shortcuts - var C = CryptoJS; - var C_lib = C.lib; - var WordArray = C_lib.WordArray; - var Hasher = C_lib.Hasher; - var C_algo = C.algo; - - // Constants table - var T = []; - - // Compute constants - (function () { - for (var i = 0; i < 64; i++) { - T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0; - } - }()); - - /** - * MD5 hash algorithm. - */ - var MD5 = C_algo.MD5 = Hasher.extend({ - _doReset: function () { - this._hash = new WordArray.init([ - 0x67452301, 0xefcdab89, - 0x98badcfe, 0x10325476 - ]); - }, - - _doProcessBlock: function (M, offset) { - // Swap endian - for (var i = 0; i < 16; i++) { - // Shortcuts - var offset_i = offset + i; - var M_offset_i = M[offset_i]; - - M[offset_i] = ( - (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | - (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) - ); - } - - // Shortcuts - var H = this._hash.words; - - var M_offset_0 = M[offset + 0]; - var M_offset_1 = M[offset + 1]; - var M_offset_2 = M[offset + 2]; - var M_offset_3 = M[offset + 3]; - var M_offset_4 = M[offset + 4]; - var M_offset_5 = M[offset + 5]; - var M_offset_6 = M[offset + 6]; - var M_offset_7 = M[offset + 7]; - var M_offset_8 = M[offset + 8]; - var M_offset_9 = M[offset + 9]; - var M_offset_10 = M[offset + 10]; - var M_offset_11 = M[offset + 11]; - var M_offset_12 = M[offset + 12]; - var M_offset_13 = M[offset + 13]; - var M_offset_14 = M[offset + 14]; - var M_offset_15 = M[offset + 15]; - - // Working varialbes - var a = H[0]; - var b = H[1]; - var c = H[2]; - var d = H[3]; - - // Computation - a = FF(a, b, c, d, M_offset_0, 7, T[0]); - d = FF(d, a, b, c, M_offset_1, 12, T[1]); - c = FF(c, d, a, b, M_offset_2, 17, T[2]); - b = FF(b, c, d, a, M_offset_3, 22, T[3]); - a = FF(a, b, c, d, M_offset_4, 7, T[4]); - d = FF(d, a, b, c, M_offset_5, 12, T[5]); - c = FF(c, d, a, b, M_offset_6, 17, T[6]); - b = FF(b, c, d, a, M_offset_7, 22, T[7]); - a = FF(a, b, c, d, M_offset_8, 7, T[8]); - d = FF(d, a, b, c, M_offset_9, 12, T[9]); - c = FF(c, d, a, b, M_offset_10, 17, T[10]); - b = FF(b, c, d, a, M_offset_11, 22, T[11]); - a = FF(a, b, c, d, M_offset_12, 7, T[12]); - d = FF(d, a, b, c, M_offset_13, 12, T[13]); - c = FF(c, d, a, b, M_offset_14, 17, T[14]); - b = FF(b, c, d, a, M_offset_15, 22, T[15]); - - a = GG(a, b, c, d, M_offset_1, 5, T[16]); - d = GG(d, a, b, c, M_offset_6, 9, T[17]); - c = GG(c, d, a, b, M_offset_11, 14, T[18]); - b = GG(b, c, d, a, M_offset_0, 20, T[19]); - a = GG(a, b, c, d, M_offset_5, 5, T[20]); - d = GG(d, a, b, c, M_offset_10, 9, T[21]); - c = GG(c, d, a, b, M_offset_15, 14, T[22]); - b = GG(b, c, d, a, M_offset_4, 20, T[23]); - a = GG(a, b, c, d, M_offset_9, 5, T[24]); - d = GG(d, a, b, c, M_offset_14, 9, T[25]); - c = GG(c, d, a, b, M_offset_3, 14, T[26]); - b = GG(b, c, d, a, M_offset_8, 20, T[27]); - a = GG(a, b, c, d, M_offset_13, 5, T[28]); - d = GG(d, a, b, c, M_offset_2, 9, T[29]); - c = GG(c, d, a, b, M_offset_7, 14, T[30]); - b = GG(b, c, d, a, M_offset_12, 20, T[31]); - - a = HH(a, b, c, d, M_offset_5, 4, T[32]); - d = HH(d, a, b, c, M_offset_8, 11, T[33]); - c = HH(c, d, a, b, M_offset_11, 16, T[34]); - b = HH(b, c, d, a, M_offset_14, 23, T[35]); - a = HH(a, b, c, d, M_offset_1, 4, T[36]); - d = HH(d, a, b, c, M_offset_4, 11, T[37]); - c = HH(c, d, a, b, M_offset_7, 16, T[38]); - b = HH(b, c, d, a, M_offset_10, 23, T[39]); - a = HH(a, b, c, d, M_offset_13, 4, T[40]); - d = HH(d, a, b, c, M_offset_0, 11, T[41]); - c = HH(c, d, a, b, M_offset_3, 16, T[42]); - b = HH(b, c, d, a, M_offset_6, 23, T[43]); - a = HH(a, b, c, d, M_offset_9, 4, T[44]); - d = HH(d, a, b, c, M_offset_12, 11, T[45]); - c = HH(c, d, a, b, M_offset_15, 16, T[46]); - b = HH(b, c, d, a, M_offset_2, 23, T[47]); - - a = II(a, b, c, d, M_offset_0, 6, T[48]); - d = II(d, a, b, c, M_offset_7, 10, T[49]); - c = II(c, d, a, b, M_offset_14, 15, T[50]); - b = II(b, c, d, a, M_offset_5, 21, T[51]); - a = II(a, b, c, d, M_offset_12, 6, T[52]); - d = II(d, a, b, c, M_offset_3, 10, T[53]); - c = II(c, d, a, b, M_offset_10, 15, T[54]); - b = II(b, c, d, a, M_offset_1, 21, T[55]); - a = II(a, b, c, d, M_offset_8, 6, T[56]); - d = II(d, a, b, c, M_offset_15, 10, T[57]); - c = II(c, d, a, b, M_offset_6, 15, T[58]); - b = II(b, c, d, a, M_offset_13, 21, T[59]); - a = II(a, b, c, d, M_offset_4, 6, T[60]); - d = II(d, a, b, c, M_offset_11, 10, T[61]); - c = II(c, d, a, b, M_offset_2, 15, T[62]); - b = II(b, c, d, a, M_offset_9, 21, T[63]); - - // Intermediate hash value - H[0] = (H[0] + a) | 0; - H[1] = (H[1] + b) | 0; - H[2] = (H[2] + c) | 0; - H[3] = (H[3] + d) | 0; - }, - - _doFinalize: function () { - // Shortcuts - var data = this._data; - var dataWords = data.words; - - var nBitsTotal = this._nDataBytes * 8; - var nBitsLeft = data.sigBytes * 8; - - // Add padding - dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); - - var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000); - var nBitsTotalL = nBitsTotal; - dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = ( - (((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) | - (((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00) - ); - dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( - (((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) | - (((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00) - ); - - data.sigBytes = (dataWords.length + 1) * 4; - - // Hash final blocks - this._process(); - - // Shortcuts - var hash = this._hash; - var H = hash.words; - - // Swap endian - for (var i = 0; i < 4; i++) { - // Shortcut - var H_i = H[i]; - - H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | - (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); - } - - // Return final computed hash - return hash; - }, - - clone: function () { - var clone = Hasher.clone.call(this); - clone._hash = this._hash.clone(); - - return clone; - } - }); - - function FF(a, b, c, d, x, s, t) { - var n = a + ((b & c) | (~b & d)) + x + t; - return ((n << s) | (n >>> (32 - s))) + b; - } - - function GG(a, b, c, d, x, s, t) { - var n = a + ((b & d) | (c & ~d)) + x + t; - return ((n << s) | (n >>> (32 - s))) + b; - } - - function HH(a, b, c, d, x, s, t) { - var n = a + (b ^ c ^ d) + x + t; - return ((n << s) | (n >>> (32 - s))) + b; - } - - function II(a, b, c, d, x, s, t) { - var n = a + (c ^ (b | ~d)) + x + t; - return ((n << s) | (n >>> (32 - s))) + b; - } - - /** - * Shortcut function to the hasher's object interface. - * - * @param {WordArray|string} message The message to hash. - * - * @return {WordArray} The hash. - * - * @static - * - * @example - * - * var hash = CryptoJS.MD5('message'); - * var hash = CryptoJS.MD5(wordArray); - */ - C.MD5 = Hasher._createHelper(MD5); - - /** - * Shortcut function to the HMAC's object interface. - * - * @param {WordArray|string} message The message to hash. - * @param {WordArray|string} key The secret key. - * - * @return {WordArray} The HMAC. - * - * @static - * - * @example - * - * var hmac = CryptoJS.HmacMD5(message, key); - */ - C.HmacMD5 = Hasher._createHmacHelper(MD5); - }(Math)); - - - return CryptoJS.MD5; - -})); - -/***/ }), -/* 21 */ -/***/ (function(module, exports, __webpack_require__) { - -;(function (root, factory) { - if (true) { - // CommonJS - module.exports = exports = factory(); - } - else {} -}(this, function () { - - /** - * CryptoJS core components. - */ - var CryptoJS = CryptoJS || (function (Math, undefined) { - /* - * Local polyfil of Object.create - */ - var create = Object.create || (function () { - function F() {}; - - return function (obj) { - var subtype; - - F.prototype = obj; - - subtype = new F(); - - F.prototype = null; - - return subtype; - }; - }()) - - /** - * CryptoJS namespace. - */ - var C = {}; - - /** - * Library namespace. - */ - var C_lib = C.lib = {}; - - /** - * Base object for prototypal inheritance. - */ - var Base = C_lib.Base = (function () { - - - return { - /** - * Creates a new object that inherits from this object. - * - * @param {Object} overrides Properties to copy into the new object. - * - * @return {Object} The new object. - * - * @static - * - * @example - * - * var MyType = CryptoJS.lib.Base.extend({ - * field: 'value', - * - * method: function () { - * } - * }); - */ - extend: function (overrides) { - // Spawn - var subtype = create(this); - - // Augment - if (overrides) { - subtype.mixIn(overrides); - } - - // Create default initializer - if (!subtype.hasOwnProperty('init') || this.init === subtype.init) { - subtype.init = function () { - subtype.$super.init.apply(this, arguments); - }; - } - - // Initializer's prototype is the subtype object - subtype.init.prototype = subtype; - - // Reference supertype - subtype.$super = this; - - return subtype; - }, - - /** - * Extends this object and runs the init method. - * Arguments to create() will be passed to init(). - * - * @return {Object} The new object. - * - * @static - * - * @example - * - * var instance = MyType.create(); - */ - create: function () { - var instance = this.extend(); - instance.init.apply(instance, arguments); - - return instance; - }, - - /** - * Initializes a newly created object. - * Override this method to add some logic when your objects are created. - * - * @example - * - * var MyType = CryptoJS.lib.Base.extend({ - * init: function () { - * // ... - * } - * }); - */ - init: function () { - }, - - /** - * Copies properties into this object. - * - * @param {Object} properties The properties to mix in. - * - * @example - * - * MyType.mixIn({ - * field: 'value' - * }); - */ - mixIn: function (properties) { - for (var propertyName in properties) { - if (properties.hasOwnProperty(propertyName)) { - this[propertyName] = properties[propertyName]; - } - } - - // IE won't copy toString using the loop above - if (properties.hasOwnProperty('toString')) { - this.toString = properties.toString; - } - }, - - /** - * Creates a copy of this object. - * - * @return {Object} The clone. - * - * @example - * - * var clone = instance.clone(); - */ - clone: function () { - return this.init.prototype.extend(this); - } - }; - }()); - - /** - * An array of 32-bit words. - * - * @property {Array} words The array of 32-bit words. - * @property {number} sigBytes The number of significant bytes in this word array. - */ - var WordArray = C_lib.WordArray = Base.extend({ - /** - * Initializes a newly created word array. - * - * @param {Array} words (Optional) An array of 32-bit words. - * @param {number} sigBytes (Optional) The number of significant bytes in the words. - * - * @example - * - * var wordArray = CryptoJS.lib.WordArray.create(); - * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); - * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); - */ - init: function (words, sigBytes) { - words = this.words = words || []; - - if (sigBytes != undefined) { - this.sigBytes = sigBytes; - } else { - this.sigBytes = words.length * 4; - } - }, - - /** - * Converts this word array to a string. - * - * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex - * - * @return {string} The stringified word array. - * - * @example - * - * var string = wordArray + ''; - * var string = wordArray.toString(); - * var string = wordArray.toString(CryptoJS.enc.Utf8); - */ - toString: function (encoder) { - return (encoder || Hex).stringify(this); - }, - - /** - * Concatenates a word array to this word array. - * - * @param {WordArray} wordArray The word array to append. - * - * @return {WordArray} This word array. - * - * @example - * - * wordArray1.concat(wordArray2); - */ - concat: function (wordArray) { - // Shortcuts - var thisWords = this.words; - var thatWords = wordArray.words; - var thisSigBytes = this.sigBytes; - var thatSigBytes = wordArray.sigBytes; - - // Clamp excess bits - this.clamp(); - - // Concat - if (thisSigBytes % 4) { - // Copy one byte at a time - for (var i = 0; i < thatSigBytes; i++) { - var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; - thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); - } - } else { - // Copy one word at a time - for (var i = 0; i < thatSigBytes; i += 4) { - thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2]; - } - } - this.sigBytes += thatSigBytes; - - // Chainable - return this; - }, - - /** - * Removes insignificant bits. - * - * @example - * - * wordArray.clamp(); - */ - clamp: function () { - // Shortcuts - var words = this.words; - var sigBytes = this.sigBytes; - - // Clamp - words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); - words.length = Math.ceil(sigBytes / 4); - }, - - /** - * Creates a copy of this word array. - * - * @return {WordArray} The clone. - * - * @example - * - * var clone = wordArray.clone(); - */ - clone: function () { - var clone = Base.clone.call(this); - clone.words = this.words.slice(0); - - return clone; - }, - - /** - * Creates a word array filled with random bytes. - * - * @param {number} nBytes The number of random bytes to generate. - * - * @return {WordArray} The random word array. - * - * @static - * - * @example - * - * var wordArray = CryptoJS.lib.WordArray.random(16); - */ - random: function (nBytes) { - var words = []; - - var r = (function (m_w) { - var m_w = m_w; - var m_z = 0x3ade68b1; - var mask = 0xffffffff; - - return function () { - m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask; - m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask; - var result = ((m_z << 0x10) + m_w) & mask; - result /= 0x100000000; - result += 0.5; - return result * (Math.random() > .5 ? 1 : -1); - } - }); - - for (var i = 0, rcache; i < nBytes; i += 4) { - var _r = r((rcache || Math.random()) * 0x100000000); - - rcache = _r() * 0x3ade67b7; - words.push((_r() * 0x100000000) | 0); - } - - return new WordArray.init(words, nBytes); - } - }); - - /** - * Encoder namespace. - */ - var C_enc = C.enc = {}; - - /** - * Hex encoding strategy. - */ - var Hex = C_enc.Hex = { - /** - * Converts a word array to a hex string. - * - * @param {WordArray} wordArray The word array. - * - * @return {string} The hex string. - * - * @static - * - * @example - * - * var hexString = CryptoJS.enc.Hex.stringify(wordArray); - */ - stringify: function (wordArray) { - // Shortcuts - var words = wordArray.words; - var sigBytes = wordArray.sigBytes; - - // Convert - var hexChars = []; - for (var i = 0; i < sigBytes; i++) { - var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; - hexChars.push((bite >>> 4).toString(16)); - hexChars.push((bite & 0x0f).toString(16)); - } - - return hexChars.join(''); - }, - - /** - * Converts a hex string to a word array. - * - * @param {string} hexStr The hex string. - * - * @return {WordArray} The word array. - * - * @static - * - * @example - * - * var wordArray = CryptoJS.enc.Hex.parse(hexString); - */ - parse: function (hexStr) { - // Shortcut - var hexStrLength = hexStr.length; - - // Convert - var words = []; - for (var i = 0; i < hexStrLength; i += 2) { - words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); - } - - return new WordArray.init(words, hexStrLength / 2); - } - }; - - /** - * Latin1 encoding strategy. - */ - var Latin1 = C_enc.Latin1 = { - /** - * Converts a word array to a Latin1 string. - * - * @param {WordArray} wordArray The word array. - * - * @return {string} The Latin1 string. - * - * @static - * - * @example - * - * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); - */ - stringify: function (wordArray) { - // Shortcuts - var words = wordArray.words; - var sigBytes = wordArray.sigBytes; - - // Convert - var latin1Chars = []; - for (var i = 0; i < sigBytes; i++) { - var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; - latin1Chars.push(String.fromCharCode(bite)); - } - - return latin1Chars.join(''); - }, - - /** - * Converts a Latin1 string to a word array. - * - * @param {string} latin1Str The Latin1 string. - * - * @return {WordArray} The word array. - * - * @static - * - * @example - * - * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); - */ - parse: function (latin1Str) { - // Shortcut - var latin1StrLength = latin1Str.length; - - // Convert - var words = []; - for (var i = 0; i < latin1StrLength; i++) { - words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); - } - - return new WordArray.init(words, latin1StrLength); - } - }; - - /** - * UTF-8 encoding strategy. - */ - var Utf8 = C_enc.Utf8 = { - /** - * Converts a word array to a UTF-8 string. - * - * @param {WordArray} wordArray The word array. - * - * @return {string} The UTF-8 string. - * - * @static - * - * @example - * - * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); - */ - stringify: function (wordArray) { - try { - return decodeURIComponent(escape(Latin1.stringify(wordArray))); - } catch (e) { - throw new Error('Malformed UTF-8 data'); - } - }, - - /** - * Converts a UTF-8 string to a word array. - * - * @param {string} utf8Str The UTF-8 string. - * - * @return {WordArray} The word array. - * - * @static - * - * @example - * - * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); - */ - parse: function (utf8Str) { - return Latin1.parse(unescape(encodeURIComponent(utf8Str))); - } - }; - - /** - * Abstract buffered block algorithm template. - * - * The property blockSize must be implemented in a concrete subtype. - * - * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 - */ - var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ - /** - * Resets this block algorithm's data buffer to its initial state. - * - * @example - * - * bufferedBlockAlgorithm.reset(); - */ - reset: function () { - // Initial values - this._data = new WordArray.init(); - this._nDataBytes = 0; - }, - - /** - * Adds new data to this block algorithm's buffer. - * - * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. - * - * @example - * - * bufferedBlockAlgorithm._append('data'); - * bufferedBlockAlgorithm._append(wordArray); - */ - _append: function (data) { - // Convert string to WordArray, else assume WordArray already - if (typeof data == 'string') { - data = Utf8.parse(data); - } - - // Append - this._data.concat(data); - this._nDataBytes += data.sigBytes; - }, - - /** - * Processes available data blocks. - * - * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. - * - * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. - * - * @return {WordArray} The processed data. - * - * @example - * - * var processedData = bufferedBlockAlgorithm._process(); - * var processedData = bufferedBlockAlgorithm._process(!!'flush'); - */ - _process: function (doFlush) { - // Shortcuts - var data = this._data; - var dataWords = data.words; - var dataSigBytes = data.sigBytes; - var blockSize = this.blockSize; - var blockSizeBytes = blockSize * 4; - - // Count blocks ready - var nBlocksReady = dataSigBytes / blockSizeBytes; - if (doFlush) { - // Round up to include partial blocks - nBlocksReady = Math.ceil(nBlocksReady); - } else { - // Round down to include only full blocks, - // less the number of blocks that must remain in the buffer - nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); - } - - // Count words ready - var nWordsReady = nBlocksReady * blockSize; - - // Count bytes ready - var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); - - // Process blocks - if (nWordsReady) { - for (var offset = 0; offset < nWordsReady; offset += blockSize) { - // Perform concrete-algorithm logic - this._doProcessBlock(dataWords, offset); - } - - // Remove processed words - var processedWords = dataWords.splice(0, nWordsReady); - data.sigBytes -= nBytesReady; - } - - // Return processed words - return new WordArray.init(processedWords, nBytesReady); - }, - - /** - * Creates a copy of this object. - * - * @return {Object} The clone. - * - * @example - * - * var clone = bufferedBlockAlgorithm.clone(); - */ - clone: function () { - var clone = Base.clone.call(this); - clone._data = this._data.clone(); - - return clone; - }, - - _minBufferSize: 0 - }); - - /** - * Abstract hasher template. - * - * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) - */ - var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ - /** - * Configuration options. - */ - cfg: Base.extend(), - - /** - * Initializes a newly created hasher. - * - * @param {Object} cfg (Optional) The configuration options to use for this hash computation. - * - * @example - * - * var hasher = CryptoJS.algo.SHA256.create(); - */ - init: function (cfg) { - // Apply config defaults - this.cfg = this.cfg.extend(cfg); - - // Set initial values - this.reset(); - }, - - /** - * Resets this hasher to its initial state. - * - * @example - * - * hasher.reset(); - */ - reset: function () { - // Reset data buffer - BufferedBlockAlgorithm.reset.call(this); - - // Perform concrete-hasher logic - this._doReset(); - }, - - /** - * Updates this hasher with a message. - * - * @param {WordArray|string} messageUpdate The message to append. - * - * @return {Hasher} This hasher. - * - * @example - * - * hasher.update('message'); - * hasher.update(wordArray); - */ - update: function (messageUpdate) { - // Append - this._append(messageUpdate); - - // Update the hash - this._process(); - - // Chainable - return this; - }, - - /** - * Finalizes the hash computation. - * Note that the finalize operation is effectively a destructive, read-once operation. - * - * @param {WordArray|string} messageUpdate (Optional) A final message update. - * - * @return {WordArray} The hash. - * - * @example - * - * var hash = hasher.finalize(); - * var hash = hasher.finalize('message'); - * var hash = hasher.finalize(wordArray); - */ - finalize: function (messageUpdate) { - // Final message update - if (messageUpdate) { - this._append(messageUpdate); - } - - // Perform concrete-hasher logic - var hash = this._doFinalize(); - - return hash; - }, - - blockSize: 512/32, - - /** - * Creates a shortcut function to a hasher's object interface. - * - * @param {Hasher} hasher The hasher to create a helper for. - * - * @return {Function} The shortcut function. - * - * @static - * - * @example - * - * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); - */ - _createHelper: function (hasher) { - return function (message, cfg) { - return new hasher.init(cfg).finalize(message); - }; - }, - - /** - * Creates a shortcut function to the HMAC's object interface. - * - * @param {Hasher} hasher The hasher to use in this HMAC helper. - * - * @return {Function} The shortcut function. - * - * @static - * - * @example - * - * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); - */ - _createHmacHelper: function (hasher) { - return function (message, key) { - return new C_algo.HMAC.init(hasher, key).finalize(message); - }; - } - }); - - /** - * Algorithm namespace. - */ - var C_algo = C.algo = {}; - - return C; - }(Math)); - - - return CryptoJS; - -})); - -/***/ }), -/* 22 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var utils_1 = __webpack_require__(16); -/** - * When a UAS wishes to construct a response to a request, it follows - * the general procedures detailed in the following subsections. - * Additional behaviors specific to the response code in question, which - * are not detailed in this section, may also be required. - * https://tools.ietf.org/html/rfc3261#section-8.2.6 - * @internal - */ -function constructOutgoingResponse(message, options) { - var CRLF = "\r\n"; - if (options.statusCode < 100 || options.statusCode > 699) { - throw new TypeError("Invalid statusCode: " + options.statusCode); - } - var reasonPhrase = options.reasonPhrase ? options.reasonPhrase : utils_1.getReasonPhrase(options.statusCode); - // SIP responses are distinguished from requests by having a Status-Line - // as their start-line. A Status-Line consists of the protocol version - // followed by a numeric Status-Code and its associated textual phrase, - // with each element separated by a single SP character. - // https://tools.ietf.org/html/rfc3261#section-7.2 - var response = "SIP/2.0 " + options.statusCode + " " + reasonPhrase + CRLF; - // One largely non-method-specific guideline for the generation of - // responses is that UASs SHOULD NOT issue a provisional response for a - // non-INVITE request. Rather, UASs SHOULD generate a final response to - // a non-INVITE request as soon as possible. - // https://tools.ietf.org/html/rfc3261#section-8.2.6.1 - if (options.statusCode >= 100 && options.statusCode < 200) { - // TODO - } - // When a 100 (Trying) response is generated, any Timestamp header field - // present in the request MUST be copied into this 100 (Trying) - // response. If there is a delay in generating the response, the UAS - // SHOULD add a delay value into the Timestamp value in the response. - // This value MUST contain the difference between the time of sending of - // the response and receipt of the request, measured in seconds. - // https://tools.ietf.org/html/rfc3261#section-8.2.6.1 - if (options.statusCode === 100) { - // TODO - } - // The From field of the response MUST equal the From header field of - // the request. The Call-ID header field of the response MUST equal the - // Call-ID header field of the request. The CSeq header field of the - // response MUST equal the CSeq field of the request. The Via header - // field values in the response MUST equal the Via header field values - // in the request and MUST maintain the same ordering. - // https://tools.ietf.org/html/rfc3261#section-8.2.6.2 - var fromHeader = "From: " + message.getHeader("From") + CRLF; - var callIdHeader = "Call-ID: " + message.callId + CRLF; - var cSeqHeader = "CSeq: " + message.cseq + " " + message.method + CRLF; - var viaHeaders = message.getHeaders("via").reduce(function (previous, current) { - return previous + "Via: " + current + CRLF; - }, ""); - // If a request contained a To tag in the request, the To header field - // in the response MUST equal that of the request. However, if the To - // header field in the request did not contain a tag, the URI in the To - // header field in the response MUST equal the URI in the To header - // field; additionally, the UAS MUST add a tag to the To header field in - // the response (with the exception of the 100 (Trying) response, in - // which a tag MAY be present). This serves to identify the UAS that is - // responding, possibly resulting in a component of a dialog ID. The - // same tag MUST be used for all responses to that request, both final - // and provisional (again excepting the 100 (Trying)). - // https://tools.ietf.org/html/rfc3261#section-8.2.6.2 - var toHeader = "To: " + message.getHeader("to"); - if (options.statusCode > 100 && !message.parseHeader("to").hasParam("tag")) { - var toTag = options.toTag; - if (!toTag) { - // Stateless UAS Behavior... - // o To header tags MUST be generated for responses in a stateless - // manner - in a manner that will generate the same tag for the - // same request consistently. For information on tag construction - // see Section 19.3. - // https://tools.ietf.org/html/rfc3261#section-8.2.7 - toTag = utils_1.newTag(); // FIXME: newTag() currently generates random tags - } - toHeader += ";tag=" + toTag; - } - toHeader += CRLF; - // FIXME: TODO: needs review... moved to InviteUserAgentServer (as it is specific to that) - // let recordRouteHeaders = ""; - // if (request.method === C.INVITE && statusCode > 100 && statusCode <= 200) { - // recordRouteHeaders = request.getHeaders("record-route").reduce((previous, current) => { - // return previous + "Record-Route: " + current + CRLF; - // }, ""); - // } - // FIXME: TODO: needs review... - var supportedHeader = ""; - if (options.supported) { - supportedHeader = "Supported: " + options.supported.join(", ") + CRLF; - } - // FIXME: TODO: needs review... - var userAgentHeader = ""; - if (options.userAgent) { - userAgentHeader = "User-Agent: " + options.userAgent + CRLF; - } - var extensionHeaders = ""; - if (options.extraHeaders) { - extensionHeaders = options.extraHeaders.reduce(function (previous, current) { - return previous + current.trim() + CRLF; - }, ""); - } - // The relative order of header fields with different field names is not - // significant. However, it is RECOMMENDED that header fields which are - // needed for proxy processing (Via, Route, Record-Route, Proxy-Require, - // Max-Forwards, and Proxy-Authorization, for example) appear towards - // the top of the message to facilitate rapid parsing. - // https://tools.ietf.org/html/rfc3261#section-7.3.1 - // response += recordRouteHeaders; - response += viaHeaders; - response += fromHeader; - response += toHeader; - response += cSeqHeader; - response += callIdHeader; - response += supportedHeader; - response += userAgentHeader; - response += extensionHeaders; - if (options.body) { - response += "Content-Type: " + options.body.contentType + CRLF; - response += "Content-Length: " + utils_1.str_utf8_length(options.body.content) + CRLF + CRLF; - response += options.body.content; - } - else { - response += "Content-Length: " + 0 + CRLF + CRLF; - } - return { message: response }; -} -exports.constructOutgoingResponse = constructOutgoingResponse; - - -/***/ }), -/* 23 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var session_1 = __webpack_require__(24); -var timers_1 = __webpack_require__(26); -var transactions_1 = __webpack_require__(27); -var bye_user_agent_client_1 = __webpack_require__(41); -var bye_user_agent_server_1 = __webpack_require__(43); -var info_user_agent_client_1 = __webpack_require__(45); -var info_user_agent_server_1 = __webpack_require__(46); -var notify_user_agent_client_1 = __webpack_require__(47); -var notify_user_agent_server_1 = __webpack_require__(48); -var prack_user_agent_client_1 = __webpack_require__(49); -var prack_user_agent_server_1 = __webpack_require__(50); -var re_invite_user_agent_client_1 = __webpack_require__(51); -var re_invite_user_agent_server_1 = __webpack_require__(52); -var refer_user_agent_client_1 = __webpack_require__(53); -var refer_user_agent_server_1 = __webpack_require__(54); -var dialog_1 = __webpack_require__(4); -/** - * Session Dialog. - * @public - */ -var SessionDialog = /** @class */ (function (_super) { - tslib_1.__extends(SessionDialog, _super); - function SessionDialog(initialTransaction, core, state, delegate) { - var _this = _super.call(this, core, state) || this; - _this.initialTransaction = initialTransaction; - /** The state of the offer/answer exchange. */ - _this._signalingState = session_1.SignalingState.Initial; - /** True if waiting for an ACK to the initial transaction 2xx (UAS only). */ - _this.ackWait = false; - _this.delegate = delegate; - if (initialTransaction instanceof transactions_1.InviteServerTransaction) { - // If we're created by an invite server transaction, we're - // going to be waiting for an ACK if are to be confirmed. - _this.ackWait = true; - } - // If we're confirmed upon creation start the retransmitting whatever - // the 2xx final response was that confirmed us into existence. - if (!_this.early) { - _this.start2xxRetransmissionTimer(); - } - _this.signalingStateTransition(initialTransaction.request); - _this.logger = core.loggerFactory.getLogger("sip.invite-dialog"); - _this.logger.log("INVITE dialog " + _this.id + " constructed"); - return _this; - } - SessionDialog.prototype.dispose = function () { - _super.prototype.dispose.call(this); - this._signalingState = session_1.SignalingState.Closed; - this._offer = undefined; - this._answer = undefined; - if (this.invite2xxTimer) { - clearTimeout(this.invite2xxTimer); - this.invite2xxTimer = undefined; - } - // The UAS MUST still respond to any pending requests received for that - // dialog. It is RECOMMENDED that a 487 (Request Terminated) response - // be generated to those pending requests. - // https://tools.ietf.org/html/rfc3261#section-15.1.2 - // TODO: - // this.userAgentServers.forEach((uas) => uas.reply(487)); - this.logger.log("INVITE dialog " + this.id + " destroyed"); - }; - Object.defineProperty(SessionDialog.prototype, "sessionState", { - // FIXME: Need real state machine - get: function () { - if (this.early) { - return session_1.SessionState.Early; - } - else if (this.ackWait) { - return session_1.SessionState.AckWait; - } - else if (this._signalingState === session_1.SignalingState.Closed) { - return session_1.SessionState.Terminated; - } - else { - return session_1.SessionState.Confirmed; - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SessionDialog.prototype, "signalingState", { - /** The state of the offer/answer exchange. */ - get: function () { - return this._signalingState; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SessionDialog.prototype, "offer", { - /** The current offer. Undefined unless signaling state HaveLocalOffer, HaveRemoteOffer, of Stable. */ - get: function () { - return this._offer; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SessionDialog.prototype, "answer", { - /** The current answer. Undefined unless signaling state Stable. */ - get: function () { - return this._answer; - }, - enumerable: true, - configurable: true - }); - /** Confirm the dialog. Only matters if dialog is currently early. */ - SessionDialog.prototype.confirm = function () { - // When we're confirmed start the retransmitting whatever - // the 2xx final response that may have confirmed us. - if (this.early) { - this.start2xxRetransmissionTimer(); - } - _super.prototype.confirm.call(this); - }; - /** Re-confirm the dialog. Only matters if handling re-INVITE request. */ - SessionDialog.prototype.reConfirm = function () { - // When we're confirmed start the retransmitting whatever - // the 2xx final response that may have confirmed us. - if (this.reinviteUserAgentServer) { - this.startReInvite2xxRetransmissionTimer(); - } - }; - /** - * The UAC core MUST generate an ACK request for each 2xx received from - * the transaction layer. The header fields of the ACK are constructed - * in the same way as for any request sent within a dialog (see Section - * 12) with the exception of the CSeq and the header fields related to - * authentication. The sequence number of the CSeq header field MUST be - * the same as the INVITE being acknowledged, but the CSeq method MUST - * be ACK. The ACK MUST contain the same credentials as the INVITE. If - * the 2xx contains an offer (based on the rules above), the ACK MUST - * carry an answer in its body. If the offer in the 2xx response is not - * acceptable, the UAC core MUST generate a valid answer in the ACK and - * then send a BYE immediately. - * https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - * @param options - ACK options bucket. - */ - SessionDialog.prototype.ack = function (options) { - if (options === void 0) { options = {}; } - this.logger.log("INVITE dialog " + this.id + " sending ACK request"); - var transaction; - if (this.reinviteUserAgentClient) { - // We're sending ACK for a re-INVITE - if (!(this.reinviteUserAgentClient.transaction instanceof transactions_1.InviteClientTransaction)) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - transaction = this.reinviteUserAgentClient.transaction; - this.reinviteUserAgentClient = undefined; - } - else { - // We're sending ACK for the initial INVITE - if (!(this.initialTransaction instanceof transactions_1.InviteClientTransaction)) { - throw new Error("Initial transaction not instance of InviteClientTransaction."); - } - transaction = this.initialTransaction; - } - options.cseq = transaction.request.cseq; // ACK cseq is INVITE cseq - var message = this.createOutgoingRequestMessage(messages_1.C.ACK, options); - transaction.ackResponse(message); // See InviteClientTransaction for details. - this.signalingStateTransition(message); - return { message: message }; - }; - /** - * Terminating a Session - * - * This section describes the procedures for terminating a session - * established by SIP. The state of the session and the state of the - * dialog are very closely related. When a session is initiated with an - * INVITE, each 1xx or 2xx response from a distinct UAS creates a - * dialog, and if that response completes the offer/answer exchange, it - * also creates a session. As a result, each session is "associated" - * with a single dialog - the one which resulted in its creation. If an - * initial INVITE generates a non-2xx final response, that terminates - * all sessions (if any) and all dialogs (if any) that were created - * through responses to the request. By virtue of completing the - * transaction, a non-2xx final response also prevents further sessions - * from being created as a result of the INVITE. The BYE request is - * used to terminate a specific session or attempted session. In this - * case, the specific session is the one with the peer UA on the other - * side of the dialog. When a BYE is received on a dialog, any session - * associated with that dialog SHOULD terminate. A UA MUST NOT send a - * BYE outside of a dialog. The caller's UA MAY send a BYE for either - * confirmed or early dialogs, and the callee's UA MAY send a BYE on - * confirmed dialogs, but MUST NOT send a BYE on early dialogs. - * - * However, the callee's UA MUST NOT send a BYE on a confirmed dialog - * until it has received an ACK for its 2xx response or until the server - * transaction times out. If no SIP extensions have defined other - * application layer states associated with the dialog, the BYE also - * terminates the dialog. - * - * https://tools.ietf.org/html/rfc3261#section-15 - * FIXME: Make these proper Exceptions... - * @param options - BYE options bucket. - * @returns - * Throws `Error` if callee's UA attempts a BYE on an early dialog. - * Throws `Error` if callee's UA attempts a BYE on a confirmed dialog - * while it's waiting on the ACK for its 2xx response. - */ - SessionDialog.prototype.bye = function (delegate, options) { - this.logger.log("INVITE dialog " + this.id + " sending BYE request"); - // The caller's UA MAY send a BYE for either - // confirmed or early dialogs, and the callee's UA MAY send a BYE on - // confirmed dialogs, but MUST NOT send a BYE on early dialogs. - // - // However, the callee's UA MUST NOT send a BYE on a confirmed dialog - // until it has received an ACK for its 2xx response or until the server - // transaction times out. - // https://tools.ietf.org/html/rfc3261#section-15 - if (this.initialTransaction instanceof transactions_1.InviteServerTransaction) { - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("UAS MUST NOT send a BYE on early dialogs."); - } - if (this.ackWait && this.initialTransaction.state !== transactions_1.TransactionState.Terminated) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("UAS MUST NOT send a BYE on a confirmed dialog " + - "until it has received an ACK for its 2xx response " + - "or until the server transaction times out."); - } - } - // A BYE request is constructed as would any other request within a - // dialog, as described in Section 12. - // - // Once the BYE is constructed, the UAC core creates a new non-INVITE - // client transaction, and passes it the BYE request. The UAC MUST - // consider the session terminated (and therefore stop sending or - // listening for media) as soon as the BYE request is passed to the - // client transaction. If the response for the BYE is a 481 - // (Call/Transaction Does Not Exist) or a 408 (Request Timeout) or no - // response at all is received for the BYE (that is, a timeout is - // returned by the client transaction), the UAC MUST consider the - // session and the dialog terminated. - // https://tools.ietf.org/html/rfc3261#section-15.1.1 - return new bye_user_agent_client_1.ByeUserAgentClient(this, delegate, options); - }; - /** - * An INFO request can be associated with an Info Package (see - * Section 5), or associated with a legacy INFO usage (see Section 2). - * - * The construction of the INFO request is the same as any other - * non-target refresh request within an existing invite dialog usage as - * described in Section 12.2 of RFC 3261. - * https://tools.ietf.org/html/rfc6086#section-4.2.1 - * @param options - Options bucket. - */ - SessionDialog.prototype.info = function (delegate, options) { - this.logger.log("INVITE dialog " + this.id + " sending INFO request"); - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("Dialog not confirmed."); - } - return new info_user_agent_client_1.InfoUserAgentClient(this, delegate, options); - }; - /** - * Modifying an Existing Session - * - * A successful INVITE request (see Section 13) establishes both a - * dialog between two user agents and a session using the offer-answer - * model. Section 12 explains how to modify an existing dialog using a - * target refresh request (for example, changing the remote target URI - * of the dialog). This section describes how to modify the actual - * session. This modification can involve changing addresses or ports, - * adding a media stream, deleting a media stream, and so on. This is - * accomplished by sending a new INVITE request within the same dialog - * that established the session. An INVITE request sent within an - * existing dialog is known as a re-INVITE. - * - * Note that a single re-INVITE can modify the dialog and the - * parameters of the session at the same time. - * - * Either the caller or callee can modify an existing session. - * https://tools.ietf.org/html/rfc3261#section-14 - * @param options - Options bucket - */ - SessionDialog.prototype.invite = function (delegate, options) { - this.logger.log("INVITE dialog " + this.id + " sending INVITE request"); - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("Dialog not confirmed."); - } - // Note that a UAC MUST NOT initiate a new INVITE transaction within a - // dialog while another INVITE transaction is in progress in either - // direction. - // - // 1. If there is an ongoing INVITE client transaction, the TU MUST - // wait until the transaction reaches the completed or terminated - // state before initiating the new INVITE. - // - // 2. If there is an ongoing INVITE server transaction, the TU MUST - // wait until the transaction reaches the confirmed or terminated - // state before initiating the new INVITE. - // - // However, a UA MAY initiate a regular transaction while an INVITE - // transaction is in progress. A UA MAY also initiate an INVITE - // transaction while a regular transaction is in progress. - // https://tools.ietf.org/html/rfc3261#section-14.1 - if (this.reinviteUserAgentClient) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("There is an ongoing re-INVITE client transaction."); - } - if (this.reinviteUserAgentServer) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("There is an ongoing re-INVITE server transaction."); - } - return new re_invite_user_agent_client_1.ReInviteUserAgentClient(this, delegate, options); - }; - /** - * The NOTIFY mechanism defined in [2] MUST be used to inform the agent - * sending the REFER of the status of the reference. - * https://tools.ietf.org/html/rfc3515#section-2.4.4 - * @param options - Options bucket. - */ - SessionDialog.prototype.notify = function (delegate, options) { - this.logger.log("INVITE dialog " + this.id + " sending NOTIFY request"); - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("Dialog not confirmed."); - } - return new notify_user_agent_client_1.NotifyUserAgentClient(this, delegate, options); - }; - /** - * Assuming the response is to be transmitted reliably, the UAC MUST - * create a new request with method PRACK. This request is sent within - * the dialog associated with the provisional response (indeed, the - * provisional response may have created the dialog). PRACK requests - * MAY contain bodies, which are interpreted according to their type and - * disposition. - * https://tools.ietf.org/html/rfc3262#section-4 - * @param options - Options bucket. - */ - SessionDialog.prototype.prack = function (delegate, options) { - this.logger.log("INVITE dialog " + this.id + " sending PRACK request"); - return new prack_user_agent_client_1.PrackUserAgentClient(this, delegate, options); - }; - /** - * REFER is a SIP request and is constructed as defined in [1]. A REFER - * request MUST contain exactly one Refer-To header field value. - * https://tools.ietf.org/html/rfc3515#section-2.4.1 - * @param options - Options bucket. - */ - SessionDialog.prototype.refer = function (delegate, options) { - this.logger.log("INVITE dialog " + this.id + " sending REFER request"); - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("Dialog not confirmed."); - } - // FIXME: TODO: Validate Refer-To header field value. - return new refer_user_agent_client_1.ReferUserAgentClient(this, delegate, options); - }; - /** - * Requests sent within a dialog, as any other requests, are atomic. If - * a particular request is accepted by the UAS, all the state changes - * associated with it are performed. If the request is rejected, none - * of the state changes are performed. - * https://tools.ietf.org/html/rfc3261#section-12.2.2 - * @param message - Incoming request message within this dialog. - */ - SessionDialog.prototype.receiveRequest = function (message) { - this.logger.log("INVITE dialog " + this.id + " received " + message.method + " request"); - // Response retransmissions cease when an ACK request for the - // response is received. This is independent of whatever transport - // protocols are used to send the response. - // https://tools.ietf.org/html/rfc6026#section-8.1 - if (message.method === messages_1.C.ACK) { - // If ackWait is true, then this is the ACK to the initial INVITE, - // otherwise this is an ACK to an in dialog INVITE. In either case, - // guard to make sure the sequence number of the ACK matches the INVITE. - if (this.ackWait) { - if (this.initialTransaction instanceof transactions_1.InviteClientTransaction) { - this.logger.warn("INVITE dialog " + this.id + " received unexpected " + message.method + " request, dropping."); - return; - } - if (this.initialTransaction.request.cseq !== message.cseq) { - this.logger.warn("INVITE dialog " + this.id + " received unexpected " + message.method + " request, dropping."); - return; - } - // Update before the delegate has a chance to handle the - // message as delegate may callback into this dialog. - this.ackWait = false; - } - else { - if (!this.reinviteUserAgentServer) { - this.logger.warn("INVITE dialog " + this.id + " received unexpected " + message.method + " request, dropping."); - return; - } - if (this.reinviteUserAgentServer.transaction.request.cseq !== message.cseq) { - this.logger.warn("INVITE dialog " + this.id + " received unexpected " + message.method + " request, dropping."); - return; - } - this.reinviteUserAgentServer = undefined; - } - this.signalingStateTransition(message); - if (this.delegate && this.delegate.onAck) { - this.delegate.onAck({ message: message }); - } - return; - } - // Request within a dialog out of sequence guard. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (!this.sequenceGuard(message)) { - this.logger.log("INVITE dialog " + this.id + " rejected out of order " + message.method + " request."); - return; - } - if (message.method === messages_1.C.INVITE) { - // A UAS that receives a second INVITE before it sends the final - // response to a first INVITE with a lower CSeq sequence number on the - // same dialog MUST return a 500 (Server Internal Error) response to the - // second INVITE and MUST include a Retry-After header field with a - // randomly chosen value of between 0 and 10 seconds. - // https://tools.ietf.org/html/rfc3261#section-14.2 - if (this.reinviteUserAgentServer) { - // https://tools.ietf.org/html/rfc3261#section-20.33 - var retryAfter = Math.floor((Math.random() * 10)) + 1; - var extraHeaders = ["Retry-After: " + retryAfter]; - this.core.replyStateless(message, { statusCode: 500, extraHeaders: extraHeaders }); - return; - } - // A UAS that receives an INVITE on a dialog while an INVITE it had sent - // on that dialog is in progress MUST return a 491 (Request Pending) - // response to the received INVITE. - // https://tools.ietf.org/html/rfc3261#section-14.2 - if (this.reinviteUserAgentClient) { - this.core.replyStateless(message, { statusCode: 491 }); - return; - } - } - // Request within a dialog common processing. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - _super.prototype.receiveRequest.call(this, message); - // Requests within a dialog MAY contain Record-Route and Contact header - // fields. However, these requests do not cause the dialog's route set - // to be modified, although they may modify the remote target URI. - // Specifically, requests that are not target refresh requests do not - // modify the dialog's remote target URI, and requests that are target - // refresh requests do. For dialogs that have been established with an - // INVITE, the only target refresh request defined is re-INVITE (see - // Section 14). Other extensions may define different target refresh - // requests for dialogs established in other ways. - // - // Note that an ACK is NOT a target refresh request. - // - // Target refresh requests only update the dialog's remote target URI, - // and not the route set formed from the Record-Route. Updating the - // latter would introduce severe backwards compatibility problems with - // RFC 2543-compliant systems. - // https://tools.ietf.org/html/rfc3261#section-15 - if (message.method === messages_1.C.INVITE) { - // FIXME: parser needs to be typed... - var contact = message.parseHeader("contact"); - if (!contact) { // TODO: Review to make sure this will never happen - throw new Error("Contact undefined."); - } - if (!(contact instanceof messages_1.NameAddrHeader)) { - throw new Error("Contact not instance of NameAddrHeader."); - } - this.dialogState.remoteTarget = contact.uri; - } - // Switch on method and then delegate. - switch (message.method) { - case messages_1.C.BYE: - // A UAS core receiving a BYE request for an existing dialog MUST follow - // the procedures of Section 12.2.2 to process the request. Once done, - // the UAS SHOULD terminate the session (and therefore stop sending and - // listening for media). The only case where it can elect not to are - // multicast sessions, where participation is possible even if the other - // participant in the dialog has terminated its involvement in the - // session. Whether or not it ends its participation on the session, - // the UAS core MUST generate a 2xx response to the BYE, and MUST pass - // that to the server transaction for transmission. - // - // The UAS MUST still respond to any pending requests received for that - // dialog. It is RECOMMENDED that a 487 (Request Terminated) response - // be generated to those pending requests. - // https://tools.ietf.org/html/rfc3261#section-15.1.2 - { - var uas = new bye_user_agent_server_1.ByeUserAgentServer(this, message); - this.delegate && this.delegate.onBye ? - this.delegate.onBye(uas) : - uas.accept(); - this.dispose(); - } - break; - case messages_1.C.INFO: - // If a UA receives an INFO request associated with an Info Package that - // the UA has not indicated willingness to receive, the UA MUST send a - // 469 (Bad Info Package) response (see Section 11.6), which contains a - // Recv-Info header field with Info Packages for which the UA is willing - // to receive INFO requests. - { - var uas = new info_user_agent_server_1.InfoUserAgentServer(this, message); - this.delegate && this.delegate.onInfo ? - this.delegate.onInfo(uas) : - uas.reject({ - statusCode: 469, - extraHeaders: ["Recv-Info :"] - }); - } - break; - case messages_1.C.INVITE: - // If the new session description is not acceptable, the UAS can reject - // it by returning a 488 (Not Acceptable Here) response for the re- - // INVITE. This response SHOULD include a Warning header field. - // https://tools.ietf.org/html/rfc3261#section-14.2 - { - var uas = new re_invite_user_agent_server_1.ReInviteUserAgentServer(this, message); - this.signalingStateTransition(message); - this.delegate && this.delegate.onInvite ? - this.delegate.onInvite(uas) : - uas.reject({ statusCode: 488 }); // TODO: Warning header field. - } - break; - case messages_1.C.NOTIFY: - // https://tools.ietf.org/html/rfc3515#section-2.4.4 - { - var uas = new notify_user_agent_server_1.NotifyUserAgentServer(this, message); - this.delegate && this.delegate.onNotify ? - this.delegate.onNotify(uas) : - uas.accept(); - } - break; - case messages_1.C.PRACK: - // https://tools.ietf.org/html/rfc3262#section-4 - { - var uas = new prack_user_agent_server_1.PrackUserAgentServer(this, message); - this.delegate && this.delegate.onPrack ? - this.delegate.onPrack(uas) : - uas.accept(); - } - break; - case messages_1.C.REFER: - // https://tools.ietf.org/html/rfc3515#section-2.4.2 - { - var uas = new refer_user_agent_server_1.ReferUserAgentServer(this, message); - this.delegate && this.delegate.onRefer ? - this.delegate.onRefer(uas) : - uas.reject(); - } - break; - default: - { - this.logger.log("INVITE dialog " + this.id + " received unimplemented " + message.method + " request"); - this.core.replyStateless(message, { statusCode: 501 }); - } - break; - } - }; - SessionDialog.prototype.reliableSequenceGuard = function (message) { - var statusCode = message.statusCode; - if (!statusCode) { - throw new Error("Status code undefined"); - } - if (statusCode > 100 && statusCode < 200) { - // If a provisional response is received for an initial request, and - // that response contains a Require header field containing the option - // tag 100rel, the response is to be sent reliably. If the response is - // a 100 (Trying) (as opposed to 101 to 199), this option tag MUST be - // ignored, and the procedures below MUST NOT be used. - // https://tools.ietf.org/html/rfc3262#section-4 - var requireHeader = message.getHeader("require"); - var rseqHeader = message.getHeader("rseq"); - var rseq = requireHeader && requireHeader.includes("100rel") && rseqHeader ? Number(rseqHeader) : undefined; - if (rseq) { - // Handling of subsequent reliable provisional responses for the same - // initial request follows the same rules as above, with the following - // difference: reliable provisional responses are guaranteed to be in - // order. As a result, if the UAC receives another reliable provisional - // response to the same request, and its RSeq value is not one higher - // than the value of the sequence number, that response MUST NOT be - // acknowledged with a PRACK, and MUST NOT be processed further by the - // UAC. An implementation MAY discard the response, or MAY cache the - // response in the hopes of receiving the missing responses. - // https://tools.ietf.org/html/rfc3262#section-4 - if (this.rseq && this.rseq + 1 !== rseq) { - return false; - } - // Once a reliable provisional response is received, retransmissions of - // that response MUST be discarded. A response is a retransmission when - // its dialog ID, CSeq, and RSeq match the original response. The UAC - // MUST maintain a sequence number that indicates the most recently - // received in-order reliable provisional response for the initial - // request. This sequence number MUST be maintained until a final - // response is received for the initial request. Its value MUST be - // initialized to the RSeq header field in the first reliable - // provisional response received for the initial request. - // https://tools.ietf.org/html/rfc3262#section-4 - if (!this.rseq) { - this.rseq = rseq; - } - } - } - return true; - }; - /** - * If not in a stable signaling state, rollback to prior stable signaling state. - */ - SessionDialog.prototype.signalingStateRollback = function () { - if (this._signalingState === session_1.SignalingState.HaveLocalOffer || - this.signalingState === session_1.SignalingState.HaveRemoteOffer) { - if (this._rollbackOffer && this._rollbackAnswer) { - this._signalingState = session_1.SignalingState.Stable; - this._offer = this._rollbackOffer; - this._answer = this._rollbackAnswer; - } - } - }; - /** - * Update the signaling state of the dialog. - * @param message - The message to base the update off of. - */ - SessionDialog.prototype.signalingStateTransition = function (message) { - var body = messages_1.getBody(message); - // No body, no session. No, woman, no cry. - if (!body || body.contentDisposition !== "session") { - return; - } - // We've got an existing offer and answer which we may wish to rollback to - if (this._signalingState === session_1.SignalingState.Stable) { - this._rollbackOffer = this._offer; - this._rollbackAnswer = this._answer; - } - // We're in UAS role, receiving incoming request with session description - if (message instanceof messages_1.IncomingRequestMessage) { - switch (this._signalingState) { - case session_1.SignalingState.Initial: - case session_1.SignalingState.Stable: - this._signalingState = session_1.SignalingState.HaveRemoteOffer; - this._offer = body; - this._answer = undefined; - break; - case session_1.SignalingState.HaveLocalOffer: - this._signalingState = session_1.SignalingState.Stable; - this._answer = body; - break; - case session_1.SignalingState.HaveRemoteOffer: - // You cannot make a new offer while one is in progress. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // FIXME: What to do here? - break; - case session_1.SignalingState.Closed: - break; - default: - throw new Error("Unexpected signaling state."); - } - } - // We're in UAC role, receiving incoming response with session description - if (message instanceof messages_1.IncomingResponseMessage) { - switch (this._signalingState) { - case session_1.SignalingState.Initial: - case session_1.SignalingState.Stable: - this._signalingState = session_1.SignalingState.HaveRemoteOffer; - this._offer = body; - this._answer = undefined; - break; - case session_1.SignalingState.HaveLocalOffer: - this._signalingState = session_1.SignalingState.Stable; - this._answer = body; - break; - case session_1.SignalingState.HaveRemoteOffer: - // You cannot make a new offer while one is in progress. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // FIXME: What to do here? - break; - case session_1.SignalingState.Closed: - break; - default: - throw new Error("Unexpected signaling state."); - } - } - // We're in UAC role, sending outgoing request with session description - if (message instanceof messages_1.OutgoingRequestMessage) { - switch (this._signalingState) { - case session_1.SignalingState.Initial: - case session_1.SignalingState.Stable: - this._signalingState = session_1.SignalingState.HaveLocalOffer; - this._offer = body; - this._answer = undefined; - break; - case session_1.SignalingState.HaveLocalOffer: - // You cannot make a new offer while one is in progress. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // FIXME: What to do here? - break; - case session_1.SignalingState.HaveRemoteOffer: - this._signalingState = session_1.SignalingState.Stable; - this._answer = body; - break; - case session_1.SignalingState.Closed: - break; - default: - throw new Error("Unexpected signaling state."); - } - } - // We're in UAS role, sending outgoing response with session description - if (messages_1.isBody(message)) { - switch (this._signalingState) { - case session_1.SignalingState.Initial: - case session_1.SignalingState.Stable: - this._signalingState = session_1.SignalingState.HaveLocalOffer; - this._offer = body; - this._answer = undefined; - break; - case session_1.SignalingState.HaveLocalOffer: - // You cannot make a new offer while one is in progress. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // FIXME: What to do here? - break; - case session_1.SignalingState.HaveRemoteOffer: - this._signalingState = session_1.SignalingState.Stable; - this._answer = body; - break; - case session_1.SignalingState.Closed: - break; - default: - throw new Error("Unexpected signaling state."); - } - } - }; - SessionDialog.prototype.start2xxRetransmissionTimer = function () { - var _this = this; - if (this.initialTransaction instanceof transactions_1.InviteServerTransaction) { - var transaction_1 = this.initialTransaction; - // Once the response has been constructed, it is passed to the INVITE - // server transaction. In order to ensure reliable end-to-end - // transport of the response, it is necessary to periodically pass - // the response directly to the transport until the ACK arrives. The - // 2xx response is passed to the transport with an interval that - // starts at T1 seconds and doubles for each retransmission until it - // reaches T2 seconds (T1 and T2 are defined in Section 17). - // Response retransmissions cease when an ACK request for the - // response is received. This is independent of whatever transport - // protocols are used to send the response. - // https://tools.ietf.org/html/rfc6026#section-8.1 - var timeout_1 = timers_1.Timers.T1; - var retransmission_1 = function () { - if (!_this.ackWait) { - _this.invite2xxTimer = undefined; - return; - } - _this.logger.log("No ACK for 2xx response received, attempting retransmission"); - transaction_1.retransmitAcceptedResponse(); - timeout_1 = Math.min(timeout_1 * 2, timers_1.Timers.T2); - _this.invite2xxTimer = setTimeout(retransmission_1, timeout_1); - }; - this.invite2xxTimer = setTimeout(retransmission_1, timeout_1); - // If the server retransmits the 2xx response for 64*T1 seconds without - // receiving an ACK, the dialog is confirmed, but the session SHOULD be - // terminated. This is accomplished with a BYE, as described in Section 15. - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - var stateChanged_1 = function () { - if (transaction_1.state === transactions_1.TransactionState.Terminated) { - transaction_1.removeListener("stateChanged", stateChanged_1); - if (_this.invite2xxTimer) { - clearTimeout(_this.invite2xxTimer); - _this.invite2xxTimer = undefined; - } - if (_this.ackWait) { - if (_this.delegate && _this.delegate.onAckTimeout) { - _this.delegate.onAckTimeout(); - } - else { - _this.bye(); - } - } - } - }; - transaction_1.addListener("stateChanged", stateChanged_1); - } - }; - // FIXME: Refactor - SessionDialog.prototype.startReInvite2xxRetransmissionTimer = function () { - var _this = this; - if (this.reinviteUserAgentServer && this.reinviteUserAgentServer.transaction instanceof transactions_1.InviteServerTransaction) { - var transaction_2 = this.reinviteUserAgentServer.transaction; - // Once the response has been constructed, it is passed to the INVITE - // server transaction. In order to ensure reliable end-to-end - // transport of the response, it is necessary to periodically pass - // the response directly to the transport until the ACK arrives. The - // 2xx response is passed to the transport with an interval that - // starts at T1 seconds and doubles for each retransmission until it - // reaches T2 seconds (T1 and T2 are defined in Section 17). - // Response retransmissions cease when an ACK request for the - // response is received. This is independent of whatever transport - // protocols are used to send the response. - // https://tools.ietf.org/html/rfc6026#section-8.1 - var timeout_2 = timers_1.Timers.T1; - var retransmission_2 = function () { - if (!_this.reinviteUserAgentServer) { - _this.invite2xxTimer = undefined; - return; - } - _this.logger.log("No ACK for 2xx response received, attempting retransmission"); - transaction_2.retransmitAcceptedResponse(); - timeout_2 = Math.min(timeout_2 * 2, timers_1.Timers.T2); - _this.invite2xxTimer = setTimeout(retransmission_2, timeout_2); - }; - this.invite2xxTimer = setTimeout(retransmission_2, timeout_2); - // If the server retransmits the 2xx response for 64*T1 seconds without - // receiving an ACK, the dialog is confirmed, but the session SHOULD be - // terminated. This is accomplished with a BYE, as described in Section 15. - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - var stateChanged_2 = function () { - if (transaction_2.state === transactions_1.TransactionState.Terminated) { - transaction_2.removeListener("stateChanged", stateChanged_2); - if (_this.invite2xxTimer) { - clearTimeout(_this.invite2xxTimer); - _this.invite2xxTimer = undefined; - } - if (_this.reinviteUserAgentServer) { - // FIXME: TODO: What to do here - } - } - }; - transaction_2.addListener("stateChanged", stateChanged_2); - } - }; - return SessionDialog; -}(dialog_1.Dialog)); -exports.SessionDialog = SessionDialog; - - -/***/ }), -/* 24 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -tslib_1.__exportStar(__webpack_require__(25), exports); - - -/***/ }), -/* 25 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * Session state. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-13 - * @public - */ -var SessionState; -(function (SessionState) { - SessionState["Initial"] = "Initial"; - SessionState["Early"] = "Early"; - SessionState["AckWait"] = "AckWait"; - SessionState["Confirmed"] = "Confirmed"; - SessionState["Terminated"] = "Terminated"; -})(SessionState = exports.SessionState || (exports.SessionState = {})); -/** - * Offer/Answer state. - * @remarks - * ```txt - * Offer Answer RFC Ini Est Early - * ------------------------------------------------------------------- - * 1. INVITE Req. 2xx INVITE Resp. RFC 3261 Y Y N - * 2. 2xx INVITE Resp. ACK Req. RFC 3261 Y Y N - * 3. INVITE Req. 1xx-rel INVITE Resp. RFC 3262 Y Y N - * 4. 1xx-rel INVITE Resp. PRACK Req. RFC 3262 Y Y N - * 5. PRACK Req. 200 PRACK Resp. RFC 3262 N Y Y - * 6. UPDATE Req. 2xx UPDATE Resp. RFC 3311 N Y Y - * - * Table 1: Summary of SIP Usage of the Offer/Answer Model - * ``` - * https://tools.ietf.org/html/rfc6337#section-2.2 - * @public - */ -var SignalingState; -(function (SignalingState) { - SignalingState["Initial"] = "Initial"; - SignalingState["HaveLocalOffer"] = "HaveLocalOffer"; - SignalingState["HaveRemoteOffer"] = "HaveRemoteOffer"; - SignalingState["Stable"] = "Stable"; - SignalingState["Closed"] = "Closed"; -})(SignalingState = exports.SignalingState || (exports.SignalingState = {})); - - -/***/ }), -/* 26 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var T1 = 500; -var T2 = 4000; -var T4 = 5000; -/** - * Timers. - * @public - */ -exports.Timers = { - T1: T1, - T2: T2, - T4: T4, - TIMER_B: 64 * T1, - TIMER_D: 0 * T1, - TIMER_F: 64 * T1, - TIMER_H: 64 * T1, - TIMER_I: 0 * T4, - TIMER_J: 0 * T1, - TIMER_K: 0 * T4, - TIMER_L: 64 * T1, - TIMER_M: 64 * T1, - TIMER_N: 64 * T1, - PROVISIONAL_RESPONSE_INTERVAL: 60000 // See RFC 3261 Section 13.3.1.1 -}; - - -/***/ }), -/* 27 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -tslib_1.__exportStar(__webpack_require__(28), exports); -tslib_1.__exportStar(__webpack_require__(35), exports); -tslib_1.__exportStar(__webpack_require__(37), exports); -tslib_1.__exportStar(__webpack_require__(39), exports); -tslib_1.__exportStar(__webpack_require__(40), exports); -tslib_1.__exportStar(__webpack_require__(35), exports); -tslib_1.__exportStar(__webpack_require__(38), exports); -tslib_1.__exportStar(__webpack_require__(36), exports); -tslib_1.__exportStar(__webpack_require__(29), exports); - - -/***/ }), -/* 28 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transaction_1 = __webpack_require__(29); -/** - * Client Transaction. - * @remarks - * The client transaction provides its functionality through the - * maintenance of a state machine. - * - * The TU communicates with the client transaction through a simple - * interface. When the TU wishes to initiate a new transaction, it - * creates a client transaction and passes it the SIP request to send - * and an IP address, port, and transport to which to send it. The - * client transaction begins execution of its state machine. Valid - * responses are passed up to the TU from the client transaction. - * https://tools.ietf.org/html/rfc3261#section-17.1 - * @public - */ -var ClientTransaction = /** @class */ (function (_super) { - tslib_1.__extends(ClientTransaction, _super); - function ClientTransaction(_request, transport, user, state, loggerCategory) { - var _this = _super.call(this, transport, user, ClientTransaction.makeId(_request), state, loggerCategory) || this; - _this._request = _request; - _this.user = user; - // The Via header field indicates the transport used for the transaction - // and identifies the location where the response is to be sent. A Via - // header field value is added only after the transport that will be - // used to reach the next hop has been selected (which may involve the - // usage of the procedures in [4]). - // https://tools.ietf.org/html/rfc3261#section-8.1.1.7 - // FIXME: Transport's server property is not typed (as of writing this). - var scheme = transport.server && transport.server.scheme ? transport.server.scheme : undefined; - _request.setViaHeader(_this.id, scheme); - return _this; - } - ClientTransaction.makeId = function (request) { - if (request.method === "CANCEL") { - if (!request.branch) { - throw new Error("Outgoing CANCEL request without a branch."); - } - return request.branch; - } - else { - return "z9hG4bK" + Math.floor(Math.random() * 10000000); - } - }; - Object.defineProperty(ClientTransaction.prototype, "request", { - /** The outgoing request the transaction handling. */ - get: function () { - return this._request; - }, - enumerable: true, - configurable: true - }); - /** - * A 408 to non-INVITE will always arrive too late to be useful ([3]), - * The client already has full knowledge of the timeout. The only - * information this message would convey is whether or not the server - * believed the transaction timed out. However, with the current design - * of the NIT, a client cannot do anything with this knowledge. Thus, - * the 408 is simply wasting network resources and contributes to the - * response bombardment illustrated in [3]. - * https://tools.ietf.org/html/rfc4320#section-4.1 - */ - ClientTransaction.prototype.onRequestTimeout = function () { - if (this.user.onRequestTimeout) { - this.user.onRequestTimeout(); - } - }; - return ClientTransaction; -}(transaction_1.Transaction)); -exports.ClientTransaction = ClientTransaction; - - -/***/ }), -/* 29 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var events_1 = __webpack_require__(30); -var exceptions_1 = __webpack_require__(31); -/** - * Transaction. - * @remarks - * SIP is a transactional protocol: interactions between components take - * place in a series of independent message exchanges. Specifically, a - * SIP transaction consists of a single request and any responses to - * that request, which include zero or more provisional responses and - * one or more final responses. In the case of a transaction where the - * request was an INVITE (known as an INVITE transaction), the - * transaction also includes the ACK only if the final response was not - * a 2xx response. If the response was a 2xx, the ACK is not considered - * part of the transaction. - * https://tools.ietf.org/html/rfc3261#section-17 - * @public - */ -var Transaction = /** @class */ (function (_super) { - tslib_1.__extends(Transaction, _super); - function Transaction(_transport, _user, _id, _state, loggerCategory) { - var _this = _super.call(this) || this; - _this._transport = _transport; - _this._user = _user; - _this._id = _id; - _this._state = _state; - _this.logger = _user.loggerFactory.getLogger(loggerCategory, _id); - _this.logger.debug("Constructing " + _this.typeToString() + " with id " + _this.id + "."); - return _this; - } - /** - * Destructor. - * Once the transaction is in the "terminated" state, it is destroyed - * immediately and there is no need to call `dispose`. However, if a - * transaction needs to be ended prematurely, the transaction user may - * do so by calling this method (for example, perhaps the UA is shutting down). - * No state transition will occur upon calling this method, all outstanding - * transmission timers will be cancelled, and use of the transaction after - * calling `dispose` is undefined. - */ - Transaction.prototype.dispose = function () { - this.logger.debug("Destroyed " + this.typeToString() + " with id " + this.id + "."); - }; - Object.defineProperty(Transaction.prototype, "id", { - /** Transaction id. */ - get: function () { - return this._id; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Transaction.prototype, "kind", { - /** Transaction kind. Deprecated. */ - get: function () { - throw new Error("Invalid kind."); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Transaction.prototype, "state", { - /** Transaction state. */ - get: function () { - return this._state; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Transaction.prototype, "transport", { - /** Transaction transport. */ - get: function () { - return this._transport; - }, - enumerable: true, - configurable: true - }); - Transaction.prototype.on = function (name, callback) { return _super.prototype.on.call(this, name, callback); }; - Transaction.prototype.logTransportError = function (error, message) { - this.logger.error(error.message); - this.logger.error("Transport error occurred in " + this.typeToString() + " with id " + this.id + "."); - this.logger.error(message); - }; - /** - * Pass message to transport for transmission. If transport fails, - * the transaction user is notified by callback to onTransportError(). - * @returns - * Rejects with `TransportError` if transport fails. - */ - Transaction.prototype.send = function (message) { - var _this = this; - return this.transport.send(message).catch(function (error) { - // FIXME: Transport is not, yet, typed and it is not clear - // yet what send() may or may not send our way. So for now, - // make sure we convert it to a TransportError if need be. - if (error instanceof exceptions_1.TransportError) { - _this.onTransportError(error); - return; - } - var transportError; - if (error && typeof error.message === "string") { - transportError = new exceptions_1.TransportError(error.message); - } - else { - transportError = new exceptions_1.TransportError(); - } - _this.onTransportError(transportError); - throw transportError; - }); - }; - Transaction.prototype.setState = function (state) { - this.logger.debug("State change to \"" + state + "\" on " + this.typeToString() + " with id " + this.id + "."); - this._state = state; - if (this._user.onStateChange) { - this._user.onStateChange(state); - } - this.emit("stateChanged"); - }; - Transaction.prototype.typeToString = function () { - return "UnknownType"; - }; - return Transaction; -}(events_1.EventEmitter)); -exports.Transaction = Transaction; - - -/***/ }), -/* 30 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - -var R = typeof Reflect === 'object' ? Reflect : null -var ReflectApply = R && typeof R.apply === 'function' - ? R.apply - : function ReflectApply(target, receiver, args) { - return Function.prototype.apply.call(target, receiver, args); - } - -var ReflectOwnKeys -if (R && typeof R.ownKeys === 'function') { - ReflectOwnKeys = R.ownKeys -} else if (Object.getOwnPropertySymbols) { - ReflectOwnKeys = function ReflectOwnKeys(target) { - return Object.getOwnPropertyNames(target) - .concat(Object.getOwnPropertySymbols(target)); - }; -} else { - ReflectOwnKeys = function ReflectOwnKeys(target) { - return Object.getOwnPropertyNames(target); - }; -} - -function ProcessEmitWarning(warning) { - if (console && console.warn) console.warn(warning); -} - -var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { - return value !== value; -} - -function EventEmitter() { - EventEmitter.init.call(this); -} -module.exports = EventEmitter; - -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; - -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._eventsCount = 0; -EventEmitter.prototype._maxListeners = undefined; - -// By default EventEmitters will print a warning if more than 10 listeners are -// added to it. This is a useful default which helps finding memory leaks. -var defaultMaxListeners = 10; - -Object.defineProperty(EventEmitter, 'defaultMaxListeners', { - enumerable: true, - get: function() { - return defaultMaxListeners; - }, - set: function(arg) { - if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { - throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); - } - defaultMaxListeners = arg; - } -}); - -EventEmitter.init = function() { - - if (this._events === undefined || - this._events === Object.getPrototypeOf(this)._events) { - this._events = Object.create(null); - this._eventsCount = 0; - } - - this._maxListeners = this._maxListeners || undefined; -}; - -// Obviously not all Emitters should be limited to 10. This function allows -// that to be increased. Set to zero for unlimited. -EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { - if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { - throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); - } - this._maxListeners = n; - return this; -}; - -function $getMaxListeners(that) { - if (that._maxListeners === undefined) - return EventEmitter.defaultMaxListeners; - return that._maxListeners; -} - -EventEmitter.prototype.getMaxListeners = function getMaxListeners() { - return $getMaxListeners(this); -}; - -EventEmitter.prototype.emit = function emit(type) { - var args = []; - for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); - var doError = (type === 'error'); - - var events = this._events; - if (events !== undefined) - doError = (doError && events.error === undefined); - else if (!doError) - return false; - - // If there is no 'error' event listener then throw. - if (doError) { - var er; - if (args.length > 0) - er = args[0]; - if (er instanceof Error) { - // Note: The comments on the `throw` lines are intentional, they show - // up in Node's output if this results in an unhandled exception. - throw er; // Unhandled 'error' event - } - // At least give some kind of context to the user - var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); - err.context = er; - throw err; // Unhandled 'error' event - } - - var handler = events[type]; - - if (handler === undefined) - return false; - - if (typeof handler === 'function') { - ReflectApply(handler, this, args); - } else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - ReflectApply(listeners[i], this, args); - } - - return true; -}; - -function _addListener(target, type, listener, prepend) { - var m; - var events; - var existing; - - if (typeof listener !== 'function') { - throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); - } - - events = target._events; - if (events === undefined) { - events = target._events = Object.create(null); - target._eventsCount = 0; - } else { - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (events.newListener !== undefined) { - target.emit('newListener', type, - listener.listener ? listener.listener : listener); - - // Re-assign `events` because a newListener handler could have caused the - // this._events to be assigned to a new object - events = target._events; - } - existing = events[type]; - } - - if (existing === undefined) { - // Optimize the case of one listener. Don't need the extra array object. - existing = events[type] = listener; - ++target._eventsCount; - } else { - if (typeof existing === 'function') { - // Adding the second element, need to change to array. - existing = events[type] = - prepend ? [listener, existing] : [existing, listener]; - // If we've already got an array, just append. - } else if (prepend) { - existing.unshift(listener); - } else { - existing.push(listener); - } - - // Check for listener leak - m = $getMaxListeners(target); - if (m > 0 && existing.length > m && !existing.warned) { - existing.warned = true; - // No error code for this since it is a Warning - // eslint-disable-next-line no-restricted-syntax - var w = new Error('Possible EventEmitter memory leak detected. ' + - existing.length + ' ' + String(type) + ' listeners ' + - 'added. Use emitter.setMaxListeners() to ' + - 'increase limit'); - w.name = 'MaxListenersExceededWarning'; - w.emitter = target; - w.type = type; - w.count = existing.length; - ProcessEmitWarning(w); - } - } - - return target; -} - -EventEmitter.prototype.addListener = function addListener(type, listener) { - return _addListener(this, type, listener, false); -}; - -EventEmitter.prototype.on = EventEmitter.prototype.addListener; - -EventEmitter.prototype.prependListener = - function prependListener(type, listener) { - return _addListener(this, type, listener, true); - }; - -function onceWrapper() { - var args = []; - for (var i = 0; i < arguments.length; i++) args.push(arguments[i]); - if (!this.fired) { - this.target.removeListener(this.type, this.wrapFn); - this.fired = true; - ReflectApply(this.listener, this.target, args); - } -} - -function _onceWrap(target, type, listener) { - var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; - var wrapped = onceWrapper.bind(state); - wrapped.listener = listener; - state.wrapFn = wrapped; - return wrapped; -} - -EventEmitter.prototype.once = function once(type, listener) { - if (typeof listener !== 'function') { - throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); - } - this.on(type, _onceWrap(this, type, listener)); - return this; -}; - -EventEmitter.prototype.prependOnceListener = - function prependOnceListener(type, listener) { - if (typeof listener !== 'function') { - throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); - } - this.prependListener(type, _onceWrap(this, type, listener)); - return this; - }; - -// Emits a 'removeListener' event if and only if the listener was removed. -EventEmitter.prototype.removeListener = - function removeListener(type, listener) { - var list, events, position, i, originalListener; - - if (typeof listener !== 'function') { - throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); - } - - events = this._events; - if (events === undefined) - return this; - - list = events[type]; - if (list === undefined) - return this; - - if (list === listener || list.listener === listener) { - if (--this._eventsCount === 0) - this._events = Object.create(null); - else { - delete events[type]; - if (events.removeListener) - this.emit('removeListener', type, list.listener || listener); - } - } else if (typeof list !== 'function') { - position = -1; - - for (i = list.length - 1; i >= 0; i--) { - if (list[i] === listener || list[i].listener === listener) { - originalListener = list[i].listener; - position = i; - break; - } - } - - if (position < 0) - return this; - - if (position === 0) - list.shift(); - else { - spliceOne(list, position); - } - - if (list.length === 1) - events[type] = list[0]; - - if (events.removeListener !== undefined) - this.emit('removeListener', type, originalListener || listener); - } - - return this; - }; - -EventEmitter.prototype.off = EventEmitter.prototype.removeListener; - -EventEmitter.prototype.removeAllListeners = - function removeAllListeners(type) { - var listeners, events, i; - - events = this._events; - if (events === undefined) - return this; - - // not listening for removeListener, no need to emit - if (events.removeListener === undefined) { - if (arguments.length === 0) { - this._events = Object.create(null); - this._eventsCount = 0; - } else if (events[type] !== undefined) { - if (--this._eventsCount === 0) - this._events = Object.create(null); - else - delete events[type]; - } - return this; - } - - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - var keys = Object.keys(events); - var key; - for (i = 0; i < keys.length; ++i) { - key = keys[i]; - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = Object.create(null); - this._eventsCount = 0; - return this; - } - - listeners = events[type]; - - if (typeof listeners === 'function') { - this.removeListener(type, listeners); - } else if (listeners !== undefined) { - // LIFO order - for (i = listeners.length - 1; i >= 0; i--) { - this.removeListener(type, listeners[i]); - } - } - - return this; - }; - -function _listeners(target, type, unwrap) { - var events = target._events; - - if (events === undefined) - return []; - - var evlistener = events[type]; - if (evlistener === undefined) - return []; - - if (typeof evlistener === 'function') - return unwrap ? [evlistener.listener || evlistener] : [evlistener]; - - return unwrap ? - unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); -} - -EventEmitter.prototype.listeners = function listeners(type) { - return _listeners(this, type, true); -}; - -EventEmitter.prototype.rawListeners = function rawListeners(type) { - return _listeners(this, type, false); -}; - -EventEmitter.listenerCount = function(emitter, type) { - if (typeof emitter.listenerCount === 'function') { - return emitter.listenerCount(type); - } else { - return listenerCount.call(emitter, type); - } -}; - -EventEmitter.prototype.listenerCount = listenerCount; -function listenerCount(type) { - var events = this._events; - - if (events !== undefined) { - var evlistener = events[type]; - - if (typeof evlistener === 'function') { - return 1; - } else if (evlistener !== undefined) { - return evlistener.length; - } - } - - return 0; -} - -EventEmitter.prototype.eventNames = function eventNames() { - return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; -}; - -function arrayClone(arr, n) { - var copy = new Array(n); - for (var i = 0; i < n; ++i) - copy[i] = arr[i]; - return copy; -} - -function spliceOne(list, index) { - for (; index + 1 < list.length; index++) - list[index] = list[index + 1]; - list.pop(); -} - -function unwrapListeners(arr) { - var ret = new Array(arr.length); - for (var i = 0; i < ret.length; ++i) { - ret[i] = arr[i].listener || arr[i]; - } - return ret; -} - - -/***/ }), -/* 31 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -tslib_1.__exportStar(__webpack_require__(32), exports); -tslib_1.__exportStar(__webpack_require__(33), exports); -tslib_1.__exportStar(__webpack_require__(34), exports); - - -/***/ }), -/* 32 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -/** - * An Exception is considered a condition that a reasonable application may wish to catch. - * An Error indicates serious problems that a reasonable application should not try to catch. - * @public - */ -var Exception = /** @class */ (function (_super) { - tslib_1.__extends(Exception, _super); - function Exception(message) { - var _newTarget = this.constructor; - var _this = _super.call(this, message) || this; - Object.setPrototypeOf(_this, _newTarget.prototype); // restore prototype chain - return _this; - } - return Exception; -}(Error)); -exports.Exception = Exception; - - -/***/ }), -/* 33 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var exception_1 = __webpack_require__(32); -/** - * Indicates that the operation could not be completed given the current transaction state. - * @public - */ -var TransactionStateError = /** @class */ (function (_super) { - tslib_1.__extends(TransactionStateError, _super); - function TransactionStateError(message) { - return _super.call(this, message ? message : "Transaction state error.") || this; - } - return TransactionStateError; -}(exception_1.Exception)); -exports.TransactionStateError = TransactionStateError; - - -/***/ }), -/* 34 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var exception_1 = __webpack_require__(32); -/** - * Transport error. - * @public - */ -var TransportError = /** @class */ (function (_super) { - tslib_1.__extends(TransportError, _super); - function TransportError(message) { - return _super.call(this, message ? message : "Unspecified transport error.") || this; - } - return TransportError; -}(exception_1.Exception)); -exports.TransportError = TransportError; - - -/***/ }), -/* 35 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var timers_1 = __webpack_require__(26); -var client_transaction_1 = __webpack_require__(28); -var transaction_state_1 = __webpack_require__(36); -/** - * INVITE Client Transaction. - * @remarks - * The INVITE transaction consists of a three-way handshake. The client - * transaction sends an INVITE, the server transaction sends responses, - * and the client transaction sends an ACK. - * https://tools.ietf.org/html/rfc3261#section-17.1.1 - * @public - */ -var InviteClientTransaction = /** @class */ (function (_super) { - tslib_1.__extends(InviteClientTransaction, _super); - /** - * Constructor. - * Upon construction, the outgoing request's Via header is updated by calling `setViaHeader`. - * Then `toString` is called on the outgoing request and the message is sent via the transport. - * After construction the transaction will be in the "calling" state and the transaction id - * will equal the branch parameter set in the Via header of the outgoing request. - * https://tools.ietf.org/html/rfc3261#section-17.1.1 - * @param request - The outgoing INVITE request. - * @param transport - The transport. - * @param user - The transaction user. - */ - function InviteClientTransaction(request, transport, user) { - var _this = _super.call(this, request, transport, user, transaction_state_1.TransactionState.Calling, "sip.transaction.ict") || this; - /** - * Map of 2xx to-tag to ACK. - * If value is not undefined, value is the ACK which was sent. - * If key exists but value is undefined, a 2xx was received but the ACK not yet sent. - * Otherwise, a 2xx was not (yet) received for this transaction. - */ - _this.ackRetransmissionCache = new Map(); - // FIXME: Timer A for unreliable transport not implemented - // - // If an unreliable transport is being used, the client transaction - // MUST start timer A with a value of T1. If a reliable transport is being used, - // the client transaction SHOULD NOT start timer A (Timer A controls request retransmissions). - // For any transport, the client transaction MUST start timer B with a value - // of 64*T1 seconds (Timer B controls transaction timeouts). - // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - // - // While not spelled out in the RFC, Timer B is the maximum amount of time that a sender - // will wait for an INVITE message to be acknowledged (a SIP response message is received). - // So Timer B should be cleared when the transaction state proceeds from "Calling". - _this.B = setTimeout(function () { return _this.timer_B(); }, timers_1.Timers.TIMER_B); - _this.send(request.toString()).catch(function (error) { - _this.logTransportError(error, "Failed to send initial outgoing request."); - }); - return _this; - } - /** - * Destructor. - */ - InviteClientTransaction.prototype.dispose = function () { - if (this.B) { - clearTimeout(this.B); - this.B = undefined; - } - if (this.D) { - clearTimeout(this.D); - this.D = undefined; - } - if (this.M) { - clearTimeout(this.M); - this.M = undefined; - } - _super.prototype.dispose.call(this); - }; - Object.defineProperty(InviteClientTransaction.prototype, "kind", { - /** Transaction kind. Deprecated. */ - get: function () { - return "ict"; - }, - enumerable: true, - configurable: true - }); - /** - * ACK a 2xx final response. - * - * The transaction includes the ACK only if the final response was not a 2xx response (the - * transaction will generate and send the ACK to the transport automagically). If the - * final response was a 2xx, the ACK is not considered part of the transaction (the - * transaction user needs to generate and send the ACK). - * - * This library is not strictly RFC compliant with regard to ACK handling for 2xx final - * responses. Specifically, retransmissions of ACKs to a 2xx final responses is handled - * by the transaction layer (instead of the UAC core). The "standard" approach is for - * the UAC core to receive all 2xx responses and manage sending ACK retransmissions to - * the transport directly. Herein the transaction layer manages sending ACKs to 2xx responses - * and any retransmissions of those ACKs as needed. - * - * @param ack - The outgoing ACK request. - */ - InviteClientTransaction.prototype.ackResponse = function (ack) { - var _this = this; - var toTag = ack.toTag; - if (!toTag) { - throw new Error("To tag undefined."); - } - var id = "z9hG4bK" + Math.floor(Math.random() * 10000000); - // FIXME: Transport's server property is not typed (as of writing this). - var scheme = this.transport.server && this.transport.server.scheme ? this.transport.server.scheme : undefined; - ack.setViaHeader(id, scheme); - this.ackRetransmissionCache.set(toTag, ack); // Add to ACK retransmission cache - this.send(ack.toString()).catch(function (error) { - _this.logTransportError(error, "Failed to send ACK to 2xx response."); - }); - }; - /** - * Handler for incoming responses from the transport which match this transaction. - * @param response - The incoming response. - */ - InviteClientTransaction.prototype.receiveResponse = function (response) { - var _this = this; - var statusCode = response.statusCode; - if (!statusCode || statusCode < 100 || statusCode > 699) { - throw new Error("Invalid status code " + statusCode); - } - switch (this.state) { - case transaction_state_1.TransactionState.Calling: - // If the client transaction receives a provisional response while in - // the "Calling" state, it transitions to the "Proceeding" state. In the - // "Proceeding" state, the client transaction SHOULD NOT retransmit the - // request any longer. Furthermore, the provisional response MUST be - // passed to the TU. Any further provisional responses MUST be passed - // up to the TU while in the "Proceeding" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - if (statusCode >= 100 && statusCode <= 199) { - this.stateTransition(transaction_state_1.TransactionState.Proceeding); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // When a 2xx response is received while in either the "Calling" or - // "Proceeding" states, the client transaction MUST transition to - // the "Accepted" state... The 2xx response MUST be passed up to the TU. - // The client transaction MUST NOT generate an ACK to the 2xx response -- its - // handling is delegated to the TU. A UAC core will send an ACK to - // the 2xx response using a new transaction. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 200 && statusCode <= 299) { - this.ackRetransmissionCache.set(response.toTag, undefined); // Prime the ACK cache - this.stateTransition(transaction_state_1.TransactionState.Accepted); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // When in either the "Calling" or "Proceeding" states, reception of - // a response with status code from 300-699 MUST cause the client - // transaction to transition to "Completed". The client transaction - // MUST pass the received response up to the TU, and the client - // transaction MUST generate an ACK request, even if the transport is - // reliable (guidelines for constructing the ACK from the response - // are given in Section 17.1.1.3), and then pass the ACK to the - // transport layer for transmission. The ACK MUST be sent to the - // same address, port, and transport to which the original request was sent. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 300 && statusCode <= 699) { - this.stateTransition(transaction_state_1.TransactionState.Completed); - this.ack(response); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - break; - case transaction_state_1.TransactionState.Proceeding: - // In the "Proceeding" state, the client transaction SHOULD NOT retransmit the - // request any longer. Furthermore, the provisional response MUST be - // passed to the TU. Any further provisional responses MUST be passed - // up to the TU while in the "Proceeding" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - if (statusCode >= 100 && statusCode <= 199) { - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // When a 2xx response is received while in either the "Calling" or "Proceeding" states, - // the client transaction MUST transition to the "Accepted" state... - // The 2xx response MUST be passed up to the TU. The client - // transaction MUST NOT generate an ACK to the 2xx response -- its - // handling is delegated to the TU. A UAC core will send an ACK to - // the 2xx response using a new transaction. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 200 && statusCode <= 299) { - this.ackRetransmissionCache.set(response.toTag, undefined); // Prime the ACK cache - this.stateTransition(transaction_state_1.TransactionState.Accepted); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // When in either the "Calling" or "Proceeding" states, reception of - // a response with status code from 300-699 MUST cause the client - // transaction to transition to "Completed". The client transaction - // MUST pass the received response up to the TU, and the client - // transaction MUST generate an ACK request, even if the transport is - // reliable (guidelines for constructing the ACK from the response - // are given in Section 17.1.1.3), and then pass the ACK to the - // transport layer for transmission. The ACK MUST be sent to the - // same address, port, and transport to which the original request was sent. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 300 && statusCode <= 699) { - this.stateTransition(transaction_state_1.TransactionState.Completed); - this.ack(response); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - break; - case transaction_state_1.TransactionState.Accepted: - // The purpose of the "Accepted" state is to allow the client - // transaction to continue to exist to receive, and pass to the TU, - // any retransmissions of the 2xx response and any additional 2xx - // responses from other branches of the INVITE if it forked - // downstream. Timer M reflects the amount of time that the - // transaction user will wait for such messages. - // - // Any 2xx responses that match this client transaction and that are - // received while in the "Accepted" state MUST be passed up to the - // TU. The client transaction MUST NOT generate an ACK to the 2xx - // response. The client transaction takes no further action. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 200 && statusCode <= 299) { - // NOTE: This implementation herein is intentionally not RFC compliant. - // While the first 2xx response for a given branch is passed up to the TU, - // retransmissions of 2xx responses are absorbed and the ACK associated - // with the original response is resent. This approach is taken because - // our current transaction users are not currently in a good position to - // deal with 2xx retransmission. This SHOULD NOT cause any compliance issues - ;) - // - // If we don't have a cache hit, pass the response to the TU. - if (!this.ackRetransmissionCache.has(response.toTag)) { - this.ackRetransmissionCache.set(response.toTag, undefined); // Prime the ACK cache - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // If we have a cache hit, try pulling the ACK from cache and retransmitting it. - var ack = this.ackRetransmissionCache.get(response.toTag); - if (ack) { - this.send(ack.toString()).catch(function (error) { - _this.logTransportError(error, "Failed to send retransmission of ACK to 2xx response."); - }); - return; - } - // If an ACK was not found in cache then we have received a retransmitted 2xx - // response before the TU responded to the original response (we don't have an ACK yet). - // So discard this response under the assumption that the TU will eventually - // get us a ACK for the original response. - return; - } - break; - case transaction_state_1.TransactionState.Completed: - // Any retransmissions of a response with status code 300-699 that - // are received while in the "Completed" state MUST cause the ACK to - // be re-passed to the transport layer for retransmission, but the - // newly received response MUST NOT be passed up to the TU. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 300 && statusCode <= 699) { - this.ack(response); - return; - } - break; - case transaction_state_1.TransactionState.Terminated: - break; - default: - throw new Error("Invalid state " + this.state); - } - // Any response received that does not match an existing client - // transaction state machine is simply dropped. (Implementations are, - // of course, free to log or do other implementation-specific things - // with such responses, but the implementer should be sure to consider - // the impact of large numbers of malicious stray responses.) - // https://tools.ietf.org/html/rfc6026#section-7.2 - var message = "Received unexpected " + statusCode + " response while in state " + this.state + "."; - this.logger.warn(message); - return; - }; - /** - * The client transaction SHOULD inform the TU that a transport failure - * has occurred, and the client transaction SHOULD transition directly - * to the "Terminated" state. The TU will handle the failover - * mechanisms described in [4]. - * https://tools.ietf.org/html/rfc3261#section-17.1.4 - * @param error - The error. - */ - InviteClientTransaction.prototype.onTransportError = function (error) { - if (this.user.onTransportError) { - this.user.onTransportError(error); - } - this.stateTransition(transaction_state_1.TransactionState.Terminated, true); - }; - /** For logging. */ - InviteClientTransaction.prototype.typeToString = function () { - return "INVITE client transaction"; - }; - InviteClientTransaction.prototype.ack = function (response) { - var _this = this; - // The ACK request constructed by the client transaction MUST contain - // values for the Call-ID, From, and Request-URI that are equal to the - // values of those header fields in the request passed to the transport - // by the client transaction (call this the "original request"). The To - // header field in the ACK MUST equal the To header field in the - // response being acknowledged, and therefore will usually differ from - // the To header field in the original request by the addition of the - // tag parameter. The ACK MUST contain a single Via header field, and - // this MUST be equal to the top Via header field of the original - // request. The CSeq header field in the ACK MUST contain the same - // value for the sequence number as was present in the original request, - // but the method parameter MUST be equal to "ACK". - // - // If the INVITE request whose response is being acknowledged had Route - // header fields, those header fields MUST appear in the ACK. This is - // to ensure that the ACK can be routed properly through any downstream - // stateless proxies. - // https://tools.ietf.org/html/rfc3261#section-17.1.1.3 - var ruri = this.request.ruri; - var callId = this.request.callId; - var cseq = this.request.cseq; - var from = this.request.getHeader("from"); - var to = response.getHeader("to"); - var via = this.request.getHeader("via"); - var route = this.request.getHeader("route"); - if (!from) { - throw new Error("From undefined."); - } - if (!to) { - throw new Error("To undefined."); - } - if (!via) { - throw new Error("Via undefined."); - } - var ack = "ACK " + ruri + " SIP/2.0\r\n"; - if (route) { - ack += "Route: " + route + "\r\n"; - } - ack += "Via: " + via + "\r\n"; - ack += "To: " + to + "\r\n"; - ack += "From: " + from + "\r\n"; - ack += "Call-ID: " + callId + "\r\n"; - ack += "CSeq: " + cseq + " ACK\r\n"; - ack += "Max-Forwards: 70\r\n"; - ack += "Content-Length: 0\r\n\r\n"; - // TOOO: "User-Agent" header - this.send(ack).catch(function (error) { - _this.logTransportError(error, "Failed to send ACK to non-2xx response."); - }); - return; - }; - /** - * Execute a state transition. - * @param newState - New state. - */ - InviteClientTransaction.prototype.stateTransition = function (newState, dueToTransportError) { - var _this = this; - if (dueToTransportError === void 0) { dueToTransportError = false; } - // Assert valid state transitions. - var invalidStateTransition = function () { - throw new Error("Invalid state transition from " + _this.state + " to " + newState); - }; - switch (newState) { - case transaction_state_1.TransactionState.Calling: - invalidStateTransition(); - break; - case transaction_state_1.TransactionState.Proceeding: - if (this.state !== transaction_state_1.TransactionState.Calling) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Accepted: - case transaction_state_1.TransactionState.Completed: - if (this.state !== transaction_state_1.TransactionState.Calling && - this.state !== transaction_state_1.TransactionState.Proceeding) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Terminated: - if (this.state !== transaction_state_1.TransactionState.Calling && - this.state !== transaction_state_1.TransactionState.Accepted && - this.state !== transaction_state_1.TransactionState.Completed) { - if (!dueToTransportError) { - invalidStateTransition(); - } - } - break; - default: - invalidStateTransition(); - } - // While not spelled out in the RFC, Timer B is the maximum amount of time that a sender - // will wait for an INVITE message to be acknowledged (a SIP response message is received). - // So Timer B should be cleared when the transaction state proceeds from "Calling". - if (this.B) { - clearTimeout(this.B); - this.B = undefined; - } - if (newState === transaction_state_1.TransactionState.Proceeding) { - // Timers have no effect on "Proceeding" state. - // In the "Proceeding" state, the client transaction - // SHOULD NOT retransmit the request any longer. - // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - } - // The client transaction MUST start Timer D when it enters the "Completed" state - // for any reason, with a value of at least 32 seconds for unreliable transports, - // and a value of zero seconds for reliable transports. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (newState === transaction_state_1.TransactionState.Completed) { - this.D = setTimeout(function () { return _this.timer_D(); }, timers_1.Timers.TIMER_D); - } - // The client transaction MUST transition to the "Accepted" state, - // and Timer M MUST be started with a value of 64*T1. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (newState === transaction_state_1.TransactionState.Accepted) { - this.M = setTimeout(function () { return _this.timer_M(); }, timers_1.Timers.TIMER_M); - } - // Once the transaction is in the "Terminated" state, it MUST be destroyed immediately. - // https://tools.ietf.org/html/rfc6026#section-8.7 - if (newState === transaction_state_1.TransactionState.Terminated) { - this.dispose(); - } - // Update state. - this.setState(newState); - }; - /** - * When timer A fires, the client transaction MUST retransmit the - * request by passing it to the transport layer, and MUST reset the - * timer with a value of 2*T1. - * When timer A fires 2*T1 seconds later, the request MUST be - * retransmitted again (assuming the client transaction is still in this - * state). This process MUST continue so that the request is - * retransmitted with intervals that double after each transmission. - * These retransmissions SHOULD only be done while the client - * transaction is in the "Calling" state. - * https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - */ - InviteClientTransaction.prototype.timer_A = function () { - // TODO - }; - /** - * If the client transaction is still in the "Calling" state when timer - * B fires, the client transaction SHOULD inform the TU that a timeout - * has occurred. The client transaction MUST NOT generate an ACK. - * https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - */ - InviteClientTransaction.prototype.timer_B = function () { - this.logger.debug("Timer B expired for INVITE client transaction " + this.id + "."); - if (this.state === transaction_state_1.TransactionState.Calling) { - this.onRequestTimeout(); - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - /** - * If Timer D fires while the client transaction is in the "Completed" state, - * the client transaction MUST move to the "Terminated" state. - * https://tools.ietf.org/html/rfc6026#section-8.4 - */ - InviteClientTransaction.prototype.timer_D = function () { - this.logger.debug("Timer D expired for INVITE client transaction " + this.id + "."); - if (this.state === transaction_state_1.TransactionState.Completed) { - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - /** - * If Timer M fires while the client transaction is in the "Accepted" - * state, the client transaction MUST move to the "Terminated" state. - * https://tools.ietf.org/html/rfc6026#section-8.4 - */ - InviteClientTransaction.prototype.timer_M = function () { - this.logger.debug("Timer M expired for INVITE client transaction " + this.id + "."); - if (this.state === transaction_state_1.TransactionState.Accepted) { - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - return InviteClientTransaction; -}(client_transaction_1.ClientTransaction)); -exports.InviteClientTransaction = InviteClientTransaction; - - -/***/ }), -/* 36 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * Transaction state. - * @public - */ -var TransactionState; -(function (TransactionState) { - TransactionState["Accepted"] = "Accepted"; - TransactionState["Calling"] = "Calling"; - TransactionState["Completed"] = "Completed"; - TransactionState["Confirmed"] = "Confirmed"; - TransactionState["Proceeding"] = "Proceeding"; - TransactionState["Terminated"] = "Terminated"; - TransactionState["Trying"] = "Trying"; -})(TransactionState = exports.TransactionState || (exports.TransactionState = {})); - - -/***/ }), -/* 37 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var timers_1 = __webpack_require__(26); -var server_transaction_1 = __webpack_require__(38); -var transaction_state_1 = __webpack_require__(36); -/** - * INVITE Server Transaction. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - * @public - */ -var InviteServerTransaction = /** @class */ (function (_super) { - tslib_1.__extends(InviteServerTransaction, _super); - /** - * Constructor. - * Upon construction, a "100 Trying" reply will be immediately sent. - * After construction the transaction will be in the "proceeding" state and the transaction - * `id` will equal the branch parameter set in the Via header of the incoming request. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - * @param request - Incoming INVITE request from the transport. - * @param transport - The transport. - * @param user - The transaction user. - */ - function InviteServerTransaction(request, transport, user) { - return _super.call(this, request, transport, user, transaction_state_1.TransactionState.Proceeding, "sip.transaction.ist") || this; - } - /** - * Destructor. - */ - InviteServerTransaction.prototype.dispose = function () { - this.stopProgressExtensionTimer(); - if (this.H) { - clearTimeout(this.H); - this.H = undefined; - } - if (this.I) { - clearTimeout(this.I); - this.I = undefined; - } - if (this.L) { - clearTimeout(this.L); - this.L = undefined; - } - _super.prototype.dispose.call(this); - }; - Object.defineProperty(InviteServerTransaction.prototype, "kind", { - /** Transaction kind. Deprecated. */ - get: function () { - return "ist"; - }, - enumerable: true, - configurable: true - }); - /** - * Receive requests from transport matching this transaction. - * @param request - Request matching this transaction. - */ - InviteServerTransaction.prototype.receiveRequest = function (request) { - var _this = this; - switch (this.state) { - case transaction_state_1.TransactionState.Proceeding: - // If a request retransmission is received while in the "Proceeding" state, the most - // recent provisional response that was received from the TU MUST be passed to the - // transport layer for retransmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (request.method === messages_1.C.INVITE) { - if (this.lastProvisionalResponse) { - this.send(this.lastProvisionalResponse).catch(function (error) { - _this.logTransportError(error, "Failed to send retransmission of provisional response."); - }); - } - return; - } - break; - case transaction_state_1.TransactionState.Accepted: - // While in the "Accepted" state, any retransmissions of the INVITE - // received will match this transaction state machine and will be - // absorbed by the machine without changing its state. These - // retransmissions are not passed onto the TU. - // https://tools.ietf.org/html/rfc6026#section-7.1 - if (request.method === messages_1.C.INVITE) { - return; - } - break; - case transaction_state_1.TransactionState.Completed: - // Furthermore, while in the "Completed" state, if a request retransmission is - // received, the server SHOULD pass the response to the transport for retransmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (request.method === messages_1.C.INVITE) { - if (!this.lastFinalResponse) { - throw new Error("Last final response undefined."); - } - this.send(this.lastFinalResponse).catch(function (error) { - _this.logTransportError(error, "Failed to send retransmission of final response."); - }); - return; - } - // If an ACK is received while the server transaction is in the "Completed" state, - // the server transaction MUST transition to the "Confirmed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (request.method === messages_1.C.ACK) { - this.stateTransition(transaction_state_1.TransactionState.Confirmed); - return; - } - break; - case transaction_state_1.TransactionState.Confirmed: - // The purpose of the "Confirmed" state is to absorb any additional ACK messages that arrive, - // triggered from retransmissions of the final response. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (request.method === messages_1.C.INVITE || request.method === messages_1.C.ACK) { - return; - } - break; - case transaction_state_1.TransactionState.Terminated: - // For good measure absorb any additional messages that arrive (should not happen). - if (request.method === messages_1.C.INVITE || request.method === messages_1.C.ACK) { - return; - } - break; - default: - throw new Error("Invalid state " + this.state); - } - var message = "INVITE server transaction received unexpected " + request.method + " request while in state " + this.state + "."; - this.logger.warn(message); - return; - }; - /** - * Receive responses from TU for this transaction. - * @param statusCode - Status code of response. - * @param response - Response. - */ - InviteServerTransaction.prototype.receiveResponse = function (statusCode, response) { - var _this = this; - if (statusCode < 100 || statusCode > 699) { - throw new Error("Invalid status code " + statusCode); - } - switch (this.state) { - case transaction_state_1.TransactionState.Proceeding: - // The TU passes any number of provisional responses to the server - // transaction. So long as the server transaction is in the - // "Proceeding" state, each of these MUST be passed to the transport - // layer for transmission. They are not sent reliably by the - // transaction layer (they are not retransmitted by it) and do not cause - // a change in the state of the server transaction. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (statusCode >= 100 && statusCode <= 199) { - this.lastProvisionalResponse = response; - // Start the progress extension timer only for a non-100 provisional response. - if (statusCode > 100) { - this.startProgressExtensionTimer(); // FIXME: remove - } - this.send(response).catch(function (error) { - _this.logTransportError(error, "Failed to send 1xx response."); - }); - return; - } - // If, while in the "Proceeding" state, the TU passes a 2xx response - // to the server transaction, the server transaction MUST pass this - // response to the transport layer for transmission. It is not - // retransmitted by the server transaction; retransmissions of 2xx - // responses are handled by the TU. The server transaction MUST then - // transition to the "Accepted" state. - // https://tools.ietf.org/html/rfc6026#section-8.5 - if (statusCode >= 200 && statusCode <= 299) { - this.lastFinalResponse = response; - this.stateTransition(transaction_state_1.TransactionState.Accepted); - this.send(response).catch(function (error) { - _this.logTransportError(error, "Failed to send 2xx response."); - }); - return; - } - // While in the "Proceeding" state, if the TU passes a response with - // status code from 300 to 699 to the server transaction, the response - // MUST be passed to the transport layer for transmission, and the state - // machine MUST enter the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (statusCode >= 300 && statusCode <= 699) { - this.lastFinalResponse = response; - this.stateTransition(transaction_state_1.TransactionState.Completed); - this.send(response).catch(function (error) { - _this.logTransportError(error, "Failed to send non-2xx final response."); - }); - return; - } - break; - case transaction_state_1.TransactionState.Accepted: - // While in the "Accepted" state, if the TU passes a 2xx response, - // the server transaction MUST pass the response to the transport layer for transmission. - // https://tools.ietf.org/html/rfc6026#section-8.7 - if (statusCode >= 200 && statusCode <= 299) { - this.send(response).catch(function (error) { - _this.logTransportError(error, "Failed to send 2xx response."); - }); - return; - } - break; - case transaction_state_1.TransactionState.Completed: - break; - case transaction_state_1.TransactionState.Confirmed: - break; - case transaction_state_1.TransactionState.Terminated: - break; - default: - throw new Error("Invalid state " + this.state); - } - var message = "INVITE server transaction received unexpected " + statusCode + " response from TU while in state " + this.state + "."; - this.logger.error(message); - throw new Error(message); - }; - /** - * Retransmit the last 2xx response. This is a noop if not in the "accepted" state. - */ - InviteServerTransaction.prototype.retransmitAcceptedResponse = function () { - var _this = this; - if (this.state === transaction_state_1.TransactionState.Accepted && this.lastFinalResponse) { - this.send(this.lastFinalResponse).catch(function (error) { - _this.logTransportError(error, "Failed to send 2xx response."); - }); - } - }; - /** - * First, the procedures in [4] are followed, which attempt to deliver the response to a backup. - * If those should all fail, based on the definition of failure in [4], the server transaction SHOULD - * inform the TU that a failure has occurred, and MUST remain in the current state. - * https://tools.ietf.org/html/rfc6026#section-8.8 - */ - InviteServerTransaction.prototype.onTransportError = function (error) { - if (this.user.onTransportError) { - this.user.onTransportError(error); - } - }; - /** For logging. */ - InviteServerTransaction.prototype.typeToString = function () { - return "INVITE server transaction"; - }; - /** - * Execute a state transition. - * @param newState - New state. - */ - InviteServerTransaction.prototype.stateTransition = function (newState) { - var _this = this; - // Assert valid state transitions. - var invalidStateTransition = function () { - throw new Error("Invalid state transition from " + _this.state + " to " + newState); - }; - switch (newState) { - case transaction_state_1.TransactionState.Proceeding: - invalidStateTransition(); - break; - case transaction_state_1.TransactionState.Accepted: - case transaction_state_1.TransactionState.Completed: - if (this.state !== transaction_state_1.TransactionState.Proceeding) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Confirmed: - if (this.state !== transaction_state_1.TransactionState.Completed) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Terminated: - if (this.state !== transaction_state_1.TransactionState.Accepted && - this.state !== transaction_state_1.TransactionState.Completed && - this.state !== transaction_state_1.TransactionState.Confirmed) { - invalidStateTransition(); - } - break; - default: - invalidStateTransition(); - } - // On any state transition, stop resending provisonal responses - this.stopProgressExtensionTimer(); - // The purpose of the "Accepted" state is to absorb retransmissions of an accepted INVITE request. - // Any such retransmissions are absorbed entirely within the server transaction. - // They are not passed up to the TU since any downstream UAS cores that accepted the request have - // taken responsibility for reliability and will already retransmit their 2xx responses if necessary. - // https://tools.ietf.org/html/rfc6026#section-8.7 - if (newState === transaction_state_1.TransactionState.Accepted) { - this.L = setTimeout(function () { return _this.timer_L(); }, timers_1.Timers.TIMER_L); - } - // When the "Completed" state is entered, timer H MUST be set to fire in 64*T1 seconds for all transports. - // Timer H determines when the server transaction abandons retransmitting the response. - // If an ACK is received while the server transaction is in the "Completed" state, - // the server transaction MUST transition to the "Confirmed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (newState === transaction_state_1.TransactionState.Completed) { - // FIXME: Missing timer G for unreliable transports. - this.H = setTimeout(function () { return _this.timer_H(); }, timers_1.Timers.TIMER_H); - } - // The purpose of the "Confirmed" state is to absorb any additional ACK messages that arrive, - // triggered from retransmissions of the final response. When this state is entered, timer I - // is set to fire in T4 seconds for unreliable transports, and zero seconds for reliable - // transports. Once timer I fires, the server MUST transition to the "Terminated" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (newState === transaction_state_1.TransactionState.Confirmed) { - // FIXME: This timer is not getting set correctly for unreliable transports. - this.I = setTimeout(function () { return _this.timer_I(); }, timers_1.Timers.TIMER_I); - } - // Once the transaction is in the "Terminated" state, it MUST be destroyed immediately. - // https://tools.ietf.org/html/rfc6026#section-8.7 - if (newState === transaction_state_1.TransactionState.Terminated) { - this.dispose(); - } - // Update state. - this.setState(newState); - }; - /** - * FIXME: UAS Provisional Retransmission Timer. See RFC 3261 Section 13.3.1.1 - * This is in the wrong place. This is not a transaction level thing. It's a UAS level thing. - */ - InviteServerTransaction.prototype.startProgressExtensionTimer = function () { - var _this = this; - // Start the progress extension timer only for the first non-100 provisional response. - if (this.progressExtensionTimer === undefined) { - this.progressExtensionTimer = setInterval(function () { - _this.logger.debug("Progress extension timer expired for INVITE server transaction " + _this.id + "."); - if (!_this.lastProvisionalResponse) { - throw new Error("Last provisional response undefined."); - } - _this.send(_this.lastProvisionalResponse).catch(function (error) { - _this.logTransportError(error, "Failed to send retransmission of provisional response."); - }); - }, timers_1.Timers.PROVISIONAL_RESPONSE_INTERVAL); - } - }; - /** - * FIXME: UAS Provisional Retransmission Timer id. See RFC 3261 Section 13.3.1.1 - * This is in the wrong place. This is not a transaction level thing. It's a UAS level thing. - */ - InviteServerTransaction.prototype.stopProgressExtensionTimer = function () { - if (this.progressExtensionTimer !== undefined) { - clearInterval(this.progressExtensionTimer); - this.progressExtensionTimer = undefined; - } - }; - /** - * While in the "Proceeding" state, if the TU passes a response with status code - * from 300 to 699 to the server transaction, the response MUST be passed to the - * transport layer for transmission, and the state machine MUST enter the "Completed" state. - * For unreliable transports, timer G is set to fire in T1 seconds, and is not set to fire for - * reliable transports. If timer G fires, the response is passed to the transport layer once - * more for retransmission, and timer G is set to fire in MIN(2*T1, T2) seconds. From then on, - * when timer G fires, the response is passed to the transport again for transmission, and - * timer G is reset with a value that doubles, unless that value exceeds T2, in which case - * it is reset with the value of T2. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - */ - InviteServerTransaction.prototype.timer_G = function () { - // TODO - }; - /** - * If timer H fires while in the "Completed" state, it implies that the ACK was never received. - * In this case, the server transaction MUST transition to the "Terminated" state, and MUST - * indicate to the TU that a transaction failure has occurred. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - */ - InviteServerTransaction.prototype.timer_H = function () { - this.logger.debug("Timer H expired for INVITE server transaction " + this.id + "."); - if (this.state === transaction_state_1.TransactionState.Completed) { - this.logger.warn("ACK to negative final response was never received, terminating transaction."); - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - /** - * Once timer I fires, the server MUST transition to the "Terminated" state. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - */ - InviteServerTransaction.prototype.timer_I = function () { - this.logger.debug("Timer I expired for INVITE server transaction " + this.id + "."); - this.stateTransition(transaction_state_1.TransactionState.Terminated); - }; - /** - * When Timer L fires and the state machine is in the "Accepted" state, the machine MUST - * transition to the "Terminated" state. Once the transaction is in the "Terminated" state, - * it MUST be destroyed immediately. Timer L reflects the amount of time the server - * transaction could receive 2xx responses for retransmission from the - * TU while it is waiting to receive an ACK. - * https://tools.ietf.org/html/rfc6026#section-7.1 - * https://tools.ietf.org/html/rfc6026#section-8.7 - */ - InviteServerTransaction.prototype.timer_L = function () { - this.logger.debug("Timer L expired for INVITE server transaction " + this.id + "."); - if (this.state === transaction_state_1.TransactionState.Accepted) { - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - return InviteServerTransaction; -}(server_transaction_1.ServerTransaction)); -exports.InviteServerTransaction = InviteServerTransaction; - - -/***/ }), -/* 38 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transaction_1 = __webpack_require__(29); -/** - * Server Transaction. - * @remarks - * The server transaction is responsible for the delivery of requests to - * the TU and the reliable transmission of responses. It accomplishes - * this through a state machine. Server transactions are created by the - * core when a request is received, and transaction handling is desired - * for that request (this is not always the case). - * https://tools.ietf.org/html/rfc3261#section-17.2 - * @public - */ -var ServerTransaction = /** @class */ (function (_super) { - tslib_1.__extends(ServerTransaction, _super); - function ServerTransaction(_request, transport, user, state, loggerCategory) { - var _this = _super.call(this, transport, user, _request.viaBranch, state, loggerCategory) || this; - _this._request = _request; - _this.user = user; - return _this; - } - Object.defineProperty(ServerTransaction.prototype, "request", { - /** The incoming request the transaction handling. */ - get: function () { - return this._request; - }, - enumerable: true, - configurable: true - }); - return ServerTransaction; -}(transaction_1.Transaction)); -exports.ServerTransaction = ServerTransaction; - - -/***/ }), -/* 39 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var timers_1 = __webpack_require__(26); -var client_transaction_1 = __webpack_require__(28); -var transaction_state_1 = __webpack_require__(36); -/** - * Non-INVITE Client Transaction. - * @remarks - * Non-INVITE transactions do not make use of ACK. - * They are simple request-response interactions. - * https://tools.ietf.org/html/rfc3261#section-17.1.2 - * @public - */ -var NonInviteClientTransaction = /** @class */ (function (_super) { - tslib_1.__extends(NonInviteClientTransaction, _super); - /** - * Constructor - * Upon construction, the outgoing request's Via header is updated by calling `setViaHeader`. - * Then `toString` is called on the outgoing request and the message is sent via the transport. - * After construction the transaction will be in the "calling" state and the transaction id - * will equal the branch parameter set in the Via header of the outgoing request. - * https://tools.ietf.org/html/rfc3261#section-17.1.2 - * @param request - The outgoing Non-INVITE request. - * @param transport - The transport. - * @param user - The transaction user. - */ - function NonInviteClientTransaction(request, transport, user) { - var _this = _super.call(this, request, transport, user, transaction_state_1.TransactionState.Trying, "sip.transaction.nict") || this; - // FIXME: Timer E for unreliable transports not implemented. - // - // The "Trying" state is entered when the TU initiates a new client - // transaction with a request. When entering this state, the client - // transaction SHOULD set timer F to fire in 64*T1 seconds. The request - // MUST be passed to the transport layer for transmission. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - _this.F = setTimeout(function () { return _this.timer_F(); }, timers_1.Timers.TIMER_F); - _this.send(request.toString()).catch(function (error) { - _this.logTransportError(error, "Failed to send initial outgoing request."); - }); - return _this; - } - /** - * Destructor. - */ - NonInviteClientTransaction.prototype.dispose = function () { - if (this.F) { - clearTimeout(this.F); - this.F = undefined; - } - if (this.K) { - clearTimeout(this.K); - this.K = undefined; - } - _super.prototype.dispose.call(this); - }; - Object.defineProperty(NonInviteClientTransaction.prototype, "kind", { - /** Transaction kind. Deprecated. */ - get: function () { - return "nict"; - }, - enumerable: true, - configurable: true - }); - /** - * Handler for incoming responses from the transport which match this transaction. - * @param response - The incoming response. - */ - NonInviteClientTransaction.prototype.receiveResponse = function (response) { - var statusCode = response.statusCode; - if (!statusCode || statusCode < 100 || statusCode > 699) { - throw new Error("Invalid status code " + statusCode); - } - switch (this.state) { - case transaction_state_1.TransactionState.Trying: - // If a provisional response is received while in the "Trying" state, the - // response MUST be passed to the TU, and then the client transaction - // SHOULD move to the "Proceeding" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (statusCode >= 100 && statusCode <= 199) { - this.stateTransition(transaction_state_1.TransactionState.Proceeding); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // If a final response (status codes 200-699) is received while in the - // "Trying" state, the response MUST be passed to the TU, and the - // client transaction MUST transition to the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (statusCode >= 200 && statusCode <= 699) { - this.stateTransition(transaction_state_1.TransactionState.Completed); - if (statusCode === 408) { - this.onRequestTimeout(); - return; - } - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - break; - case transaction_state_1.TransactionState.Proceeding: - // If a provisional response is received while in the "Proceeding" state, - // the response MUST be passed to the TU. (From Figure 6) - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (statusCode >= 100 && statusCode <= 199) { - if (this.user.receiveResponse) { - return this.user.receiveResponse(response); - } - } - // If a final response (status codes 200-699) is received while in the - // "Proceeding" state, the response MUST be passed to the TU, and the - // client transaction MUST transition to the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (statusCode >= 200 && statusCode <= 699) { - this.stateTransition(transaction_state_1.TransactionState.Completed); - if (statusCode === 408) { - this.onRequestTimeout(); - return; - } - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - case transaction_state_1.TransactionState.Completed: - // The "Completed" state exists to buffer any additional response - // retransmissions that may be received (which is why the client - // transaction remains there only for unreliable transports). - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - return; - case transaction_state_1.TransactionState.Terminated: - // For good measure just absorb additional response retransmissions. - return; - default: - throw new Error("Invalid state " + this.state); - } - var message = "Non-INVITE client transaction received unexpected " + statusCode + " response while in state " + this.state + "."; - this.logger.warn(message); - return; - }; - /** - * The client transaction SHOULD inform the TU that a transport failure has occurred, - * and the client transaction SHOULD transition directly to the "Terminated" state. - * The TU will handle the failover mechanisms described in [4]. - * https://tools.ietf.org/html/rfc3261#section-17.1.4 - * @param error - Trasnsport error - */ - NonInviteClientTransaction.prototype.onTransportError = function (error) { - if (this.user.onTransportError) { - this.user.onTransportError(error); - } - this.stateTransition(transaction_state_1.TransactionState.Terminated, true); - }; - /** For logging. */ - NonInviteClientTransaction.prototype.typeToString = function () { - return "non-INVITE client transaction"; - }; - /** - * Execute a state transition. - * @param newState - New state. - */ - NonInviteClientTransaction.prototype.stateTransition = function (newState, dueToTransportError) { - var _this = this; - if (dueToTransportError === void 0) { dueToTransportError = false; } - // Assert valid state transitions. - var invalidStateTransition = function () { - throw new Error("Invalid state transition from " + _this.state + " to " + newState); - }; - switch (newState) { - case transaction_state_1.TransactionState.Trying: - invalidStateTransition(); - break; - case transaction_state_1.TransactionState.Proceeding: - if (this.state !== transaction_state_1.TransactionState.Trying) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Completed: - if (this.state !== transaction_state_1.TransactionState.Trying && - this.state !== transaction_state_1.TransactionState.Proceeding) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Terminated: - if (this.state !== transaction_state_1.TransactionState.Trying && - this.state !== transaction_state_1.TransactionState.Proceeding && - this.state !== transaction_state_1.TransactionState.Completed) { - if (!dueToTransportError) { - invalidStateTransition(); - } - } - break; - default: - invalidStateTransition(); - } - // Once the client transaction enters the "Completed" state, it MUST set - // Timer K to fire in T4 seconds for unreliable transports, and zero - // seconds for reliable transports The "Completed" state exists to - // buffer any additional response retransmissions that may be received - // (which is why the client transaction remains there only for unreliable transports). - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (newState === transaction_state_1.TransactionState.Completed) { - if (this.F) { - clearTimeout(this.F); - this.F = undefined; - } - this.K = setTimeout(function () { return _this.timer_K(); }, timers_1.Timers.TIMER_K); - } - // Once the transaction is in the terminated state, it MUST be destroyed immediately. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (newState === transaction_state_1.TransactionState.Terminated) { - this.dispose(); - } - // Update state. - this.setState(newState); - }; - /** - * If Timer F fires while the client transaction is still in the - * "Trying" state, the client transaction SHOULD inform the TU about the - * timeout, and then it SHOULD enter the "Terminated" state. - * If timer F fires while in the "Proceeding" state, the TU MUST be informed of - * a timeout, and the client transaction MUST transition to the terminated state. - * https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - */ - NonInviteClientTransaction.prototype.timer_F = function () { - this.logger.debug("Timer F expired for non-INVITE client transaction " + this.id + "."); - if (this.state === transaction_state_1.TransactionState.Trying || this.state === transaction_state_1.TransactionState.Proceeding) { - this.onRequestTimeout(); - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - /** - * If Timer K fires while in this (COMPLETED) state, the client transaction - * MUST transition to the "Terminated" state. - * https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - */ - NonInviteClientTransaction.prototype.timer_K = function () { - if (this.state === transaction_state_1.TransactionState.Completed) { - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - return NonInviteClientTransaction; -}(client_transaction_1.ClientTransaction)); -exports.NonInviteClientTransaction = NonInviteClientTransaction; - - -/***/ }), -/* 40 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var timers_1 = __webpack_require__(26); -var server_transaction_1 = __webpack_require__(38); -var transaction_state_1 = __webpack_require__(36); -/** - * Non-INVITE Server Transaction. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-17.2.2 - * @public - */ -var NonInviteServerTransaction = /** @class */ (function (_super) { - tslib_1.__extends(NonInviteServerTransaction, _super); - /** - * Constructor. - * After construction the transaction will be in the "trying": state and the transaction - * `id` will equal the branch parameter set in the Via header of the incoming request. - * https://tools.ietf.org/html/rfc3261#section-17.2.2 - * @param request - Incoming Non-INVITE request from the transport. - * @param transport - The transport. - * @param user - The transaction user. - */ - function NonInviteServerTransaction(request, transport, user) { - return _super.call(this, request, transport, user, transaction_state_1.TransactionState.Trying, "sip.transaction.nist") || this; - } - /** - * Destructor. - */ - NonInviteServerTransaction.prototype.dispose = function () { - if (this.J) { - clearTimeout(this.J); - this.J = undefined; - } - _super.prototype.dispose.call(this); - }; - Object.defineProperty(NonInviteServerTransaction.prototype, "kind", { - /** Transaction kind. Deprecated. */ - get: function () { - return "nist"; - }, - enumerable: true, - configurable: true - }); - /** - * Receive requests from transport matching this transaction. - * @param request - Request matching this transaction. - */ - NonInviteServerTransaction.prototype.receiveRequest = function (request) { - var _this = this; - switch (this.state) { - case transaction_state_1.TransactionState.Trying: - // Once in the "Trying" state, any further request retransmissions are discarded. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - break; - case transaction_state_1.TransactionState.Proceeding: - // If a retransmission of the request is received while in the "Proceeding" state, - // the most recently sent provisional response MUST be passed to the transport layer for retransmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - if (!this.lastResponse) { - throw new Error("Last response undefined."); - } - this.send(this.lastResponse).catch(function (error) { - _this.logTransportError(error, "Failed to send retransmission of provisional response."); - }); - break; - case transaction_state_1.TransactionState.Completed: - // While in the "Completed" state, the server transaction MUST pass the final response to the transport - // layer for retransmission whenever a retransmission of the request is received. Any other final responses - // passed by the TU to the server transaction MUST be discarded while in the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - if (!this.lastResponse) { - throw new Error("Last response undefined."); - } - this.send(this.lastResponse).catch(function (error) { - _this.logTransportError(error, "Failed to send retransmission of final response."); - }); - break; - case transaction_state_1.TransactionState.Terminated: - break; - default: - throw new Error("Invalid state " + this.state); - } - }; - /** - * Receive responses from TU for this transaction. - * @param statusCode - Status code of repsonse. 101-199 not allowed per RFC 4320. - * @param response - Response to send. - */ - NonInviteServerTransaction.prototype.receiveResponse = function (statusCode, response) { - var _this = this; - if (statusCode < 100 || statusCode > 699) { - throw new Error("Invalid status code " + statusCode); - } - // An SIP element MUST NOT send any provisional response with a - // Status-Code other than 100 to a non-INVITE request. - // An SIP element MUST NOT respond to a non-INVITE request with a - // Status-Code of 100 over any unreliable transport, such as UDP, - // before the amount of time it takes a client transaction's Timer E to be reset to T2. - // An SIP element MAY respond to a non-INVITE request with a - // Status-Code of 100 over a reliable transport at any time. - // https://tools.ietf.org/html/rfc4320#section-4.1 - if (statusCode > 100 && statusCode <= 199) { - throw new Error("Provisional response other than 100 not allowed."); - } - switch (this.state) { - case transaction_state_1.TransactionState.Trying: - // While in the "Trying" state, if the TU passes a provisional response - // to the server transaction, the server transaction MUST enter the "Proceeding" state. - // The response MUST be passed to the transport layer for transmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - this.lastResponse = response; - if (statusCode >= 100 && statusCode < 200) { - this.stateTransition(transaction_state_1.TransactionState.Proceeding); - this.send(response).catch(function (error) { - _this.logTransportError(error, "Failed to send provisional response."); - }); - return; - } - if (statusCode >= 200 && statusCode <= 699) { - this.stateTransition(transaction_state_1.TransactionState.Completed); - this.send(response).catch(function (error) { - _this.logTransportError(error, "Failed to send final response."); - }); - return; - } - break; - case transaction_state_1.TransactionState.Proceeding: - // Any further provisional responses that are received from the TU while - // in the "Proceeding" state MUST be passed to the transport layer for transmission. - // If the TU passes a final response (status codes 200-699) to the server while in - // the "Proceeding" state, the transaction MUST enter the "Completed" state, and - // the response MUST be passed to the transport layer for transmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - this.lastResponse = response; - if (statusCode >= 200 && statusCode <= 699) { - this.stateTransition(transaction_state_1.TransactionState.Completed); - this.send(response).catch(function (error) { - _this.logTransportError(error, "Failed to send final response."); - }); - return; - } - break; - case transaction_state_1.TransactionState.Completed: - // Any other final responses passed by the TU to the server - // transaction MUST be discarded while in the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - return; - case transaction_state_1.TransactionState.Terminated: - break; - default: - throw new Error("Invalid state " + this.state); - } - var message = "Non-INVITE server transaction received unexpected " + statusCode + " response from TU while in state " + this.state + "."; - this.logger.error(message); - throw new Error(message); - }; - /** - * First, the procedures in [4] are followed, which attempt to deliver the response to a backup. - * If those should all fail, based on the definition of failure in [4], the server transaction SHOULD - * inform the TU that a failure has occurred, and SHOULD transition to the terminated state. - * https://tools.ietf.org/html/rfc3261#section-17.2.4 - */ - NonInviteServerTransaction.prototype.onTransportError = function (error) { - if (this.user.onTransportError) { - this.user.onTransportError(error); - } - this.stateTransition(transaction_state_1.TransactionState.Terminated, true); - }; - /** For logging. */ - NonInviteServerTransaction.prototype.typeToString = function () { - return "non-INVITE server transaction"; - }; - NonInviteServerTransaction.prototype.stateTransition = function (newState, dueToTransportError) { - var _this = this; - if (dueToTransportError === void 0) { dueToTransportError = false; } - // Assert valid state transitions. - var invalidStateTransition = function () { - throw new Error("Invalid state transition from " + _this.state + " to " + newState); - }; - switch (newState) { - case transaction_state_1.TransactionState.Trying: - invalidStateTransition(); - break; - case transaction_state_1.TransactionState.Proceeding: - if (this.state !== transaction_state_1.TransactionState.Trying) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Completed: - if (this.state !== transaction_state_1.TransactionState.Trying && this.state !== transaction_state_1.TransactionState.Proceeding) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Terminated: - if (this.state !== transaction_state_1.TransactionState.Proceeding && this.state !== transaction_state_1.TransactionState.Completed) { - if (!dueToTransportError) { - invalidStateTransition(); - } - } - break; - default: - invalidStateTransition(); - } - // When the server transaction enters the "Completed" state, it MUST set Timer J to fire - // in 64*T1 seconds for unreliable transports, and zero seconds for reliable transports. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - if (newState === transaction_state_1.TransactionState.Completed) { - this.J = setTimeout(function () { return _this.timer_J(); }, timers_1.Timers.TIMER_J); - } - // The server transaction MUST be destroyed the instant it enters the "Terminated" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - if (newState === transaction_state_1.TransactionState.Terminated) { - this.dispose(); - } - this.setState(newState); - }; - /** - * The server transaction remains in this state until Timer J fires, - * at which point it MUST transition to the "Terminated" state. - * https://tools.ietf.org/html/rfc3261#section-17.2.2 - */ - NonInviteServerTransaction.prototype.timer_J = function () { - this.logger.debug("Timer J expired for NON-INVITE server transaction " + this.id + "."); - if (this.state === transaction_state_1.TransactionState.Completed) { - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - return NonInviteServerTransaction; -}(server_transaction_1.ServerTransaction)); -exports.NonInviteServerTransaction = NonInviteServerTransaction; - - -/***/ }), -/* 41 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * BYE UAC. - * @public - */ -var ByeUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(ByeUserAgentClient, _super); - function ByeUserAgentClient(dialog, delegate, options) { - var _this = this; - var message = dialog.createOutgoingRequestMessage(messages_1.C.BYE, options); - _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; - dialog.dispose(); - return _this; - } - return ByeUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.ByeUserAgentClient = ByeUserAgentClient; - - -/***/ }), -/* 42 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var messages_1 = __webpack_require__(5); -var transactions_1 = __webpack_require__(27); -/** - * User Agent Client (UAC). - * @remarks - * A user agent client is a logical entity - * that creates a new request, and then uses the client - * transaction state machinery to send it. The role of UAC lasts - * only for the duration of that transaction. In other words, if - * a piece of software initiates a request, it acts as a UAC for - * the duration of that transaction. If it receives a request - * later, it assumes the role of a user agent server for the - * processing of that transaction. - * https://tools.ietf.org/html/rfc3261#section-6 - * @public - */ -var UserAgentClient = /** @class */ (function () { - function UserAgentClient(transactionConstructor, core, message, delegate) { - this.transactionConstructor = transactionConstructor; - this.core = core; - this.message = message; - this.delegate = delegate; - this.challenged = false; - this.stale = false; - this.logger = this.loggerFactory.getLogger("sip.user-agent-client"); - this.init(); - } - UserAgentClient.prototype.dispose = function () { - this.transaction.dispose(); - }; - Object.defineProperty(UserAgentClient.prototype, "loggerFactory", { - get: function () { - return this.core.loggerFactory; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(UserAgentClient.prototype, "transaction", { - /** The transaction associated with this request. */ - get: function () { - if (!this._transaction) { - throw new Error("Transaction undefined."); - } - return this._transaction; - }, - enumerable: true, - configurable: true - }); - /** - * Since requests other than INVITE are responded to immediately, sending a - * CANCEL for a non-INVITE request would always create a race condition. - * A CANCEL request SHOULD NOT be sent to cancel a request other than INVITE. - * https://tools.ietf.org/html/rfc3261#section-9.1 - * @param options - Cancel options bucket. - */ - UserAgentClient.prototype.cancel = function (reason, options) { - var _this = this; - if (options === void 0) { options = {}; } - if (!this.transaction) { - throw new Error("Transaction undefined."); - } - if (!this.message.to) { - throw new Error("To undefined."); - } - if (!this.message.from) { - throw new Error("From undefined."); - } - // The following procedures are used to construct a CANCEL request. The - // Request-URI, Call-ID, To, the numeric part of CSeq, and From header - // fields in the CANCEL request MUST be identical to those in the - // request being cancelled, including tags. A CANCEL constructed by a - // client MUST have only a single Via header field value matching the - // top Via value in the request being cancelled. Using the same values - // for these header fields allows the CANCEL to be matched with the - // request it cancels (Section 9.2 indicates how such matching occurs). - // However, the method part of the CSeq header field MUST have a value - // of CANCEL. This allows it to be identified and processed as a - // transaction in its own right (See Section 17). - // https://tools.ietf.org/html/rfc3261#section-9.1 - var message = this.core.makeOutgoingRequestMessage(messages_1.C.CANCEL, this.message.ruri, this.message.from.uri, this.message.to.uri, { - toTag: this.message.toTag, - fromTag: this.message.fromTag, - callId: this.message.callId, - cseq: this.message.cseq - }, options.extraHeaders); - // TODO: Revisit this. - // The CANCEL needs to use the same branch parameter so that - // it matches the INVITE transaction, but this is a hacky way to do this. - // Or at the very least not well documented. If the the branch parameter - // is set on the outgoing request, the transaction will use it. - // Otherwise the transaction will make a new one. - message.branch = this.message.branch; - if (this.message.headers.Route) { - message.headers.Route = this.message.headers.Route; - } - if (reason) { - message.setHeader("Reason", reason); - } - // If no provisional response has been received, the CANCEL request MUST - // NOT be sent; rather, the client MUST wait for the arrival of a - // provisional response before sending the request. If the original - // request has generated a final response, the CANCEL SHOULD NOT be - // sent, as it is an effective no-op, since CANCEL has no effect on - // requests that have already generated a final response. - // https://tools.ietf.org/html/rfc3261#section-9.1 - if (this.transaction.state === transactions_1.TransactionState.Proceeding) { - var uac = new UserAgentClient(transactions_1.NonInviteClientTransaction, this.core, message); - } - else { - this.transaction.once("stateChanged", function () { - if (_this.transaction && _this.transaction.state === transactions_1.TransactionState.Proceeding) { - var uac = new UserAgentClient(transactions_1.NonInviteClientTransaction, _this.core, message); - } - }); - } - return message; - }; - /** - * If a 401 (Unauthorized) or 407 (Proxy Authentication Required) - * response is received, the UAC SHOULD follow the authorization - * procedures of Section 22.2 and Section 22.3 to retry the request with - * credentials. - * https://tools.ietf.org/html/rfc3261#section-8.1.3.5 - * 22 Usage of HTTP Authentication - * https://tools.ietf.org/html/rfc3261#section-22 - * 22.1 Framework - * https://tools.ietf.org/html/rfc3261#section-22.1 - * 22.2 User-to-User Authentication - * https://tools.ietf.org/html/rfc3261#section-22.2 - * 22.3 Proxy-to-User Authentication - * https://tools.ietf.org/html/rfc3261#section-22.3 - * - * FIXME: This "guard for and retry the request with credentials" - * implementation is not complete and at best minimally passable. - * @param response - The incoming response to guard. - * @returns True if the program execution is to continue in the branch in question. - * Otherwise the request is retried with credentials and current request processing must stop. - */ - UserAgentClient.prototype.authenticationGuard = function (message) { - var statusCode = message.statusCode; - if (!statusCode) { - throw new Error("Response status code undefined."); - } - // If a 401 (Unauthorized) or 407 (Proxy Authentication Required) - // response is received, the UAC SHOULD follow the authorization - // procedures of Section 22.2 and Section 22.3 to retry the request with - // credentials. - // https://tools.ietf.org/html/rfc3261#section-8.1.3.5 - if (statusCode !== 401 && statusCode !== 407) { - return true; - } - // Get and parse the appropriate WWW-Authenticate or Proxy-Authenticate header. - var challenge; - var authorizationHeaderName; - if (statusCode === 401) { - challenge = message.parseHeader("www-authenticate"); - authorizationHeaderName = "authorization"; - } - else { - challenge = message.parseHeader("proxy-authenticate"); - authorizationHeaderName = "proxy-authorization"; - } - // Verify it seems a valid challenge. - if (!challenge) { - this.logger.warn(statusCode + " with wrong or missing challenge, cannot authenticate"); - return true; - } - // Avoid infinite authentications. - if (this.challenged && (this.stale || challenge.stale !== true)) { - this.logger.warn(statusCode + " apparently in authentication loop, cannot authenticate"); - return true; - } - // Get credentials. - if (!this.credentials) { - this.credentials = this.core.configuration.authenticationFactory(); - if (!this.credentials) { - this.logger.warn("Unable to obtain credentials, cannot authenticate"); - return true; - } - } - // Verify that the challenge is really valid. - if (!this.credentials.authenticate(this.message, challenge)) { - return true; - } - this.challenged = true; - if (challenge.stale) { - this.stale = true; - } - var cseq = this.message.cseq += 1; - this.message.setHeader("cseq", cseq + " " + this.message.method); - this.message.setHeader(authorizationHeaderName, this.credentials.toString()); - // Calling init (again) will swap out our existing client transaction with a new one. - // FIXME: HACK: An assumption is being made here that there is nothing that needs to - // be cleaned up beyond the client transaction which is being replaced. For example, - // it is assumed that no early dialogs have been created. - this.init(); - return false; - }; - /** - * Receive a response from the transaction layer. - * @param message - Incoming response message. - */ - UserAgentClient.prototype.receiveResponse = function (message) { - if (!this.authenticationGuard(message)) { - return; - } - var statusCode = message.statusCode ? message.statusCode.toString() : ""; - if (!statusCode) { - throw new Error("Response status code undefined."); - } - switch (true) { - case /^100$/.test(statusCode): - if (this.delegate && this.delegate.onTrying) { - this.delegate.onTrying({ message: message }); - } - break; - case /^1[0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onProgress) { - this.delegate.onProgress({ message: message }); - } - break; - case /^2[0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onAccept) { - this.delegate.onAccept({ message: message }); - } - break; - case /^3[0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onRedirect) { - this.delegate.onRedirect({ message: message }); - } - break; - case /^[4-6][0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onReject) { - this.delegate.onReject({ message: message }); - } - break; - default: - throw new Error("Invalid status code " + statusCode); - } - }; - UserAgentClient.prototype.init = function () { - var _this = this; - // We are the transaction user. - var user = { - loggerFactory: this.loggerFactory, - onRequestTimeout: function () { return _this.onRequestTimeout(); }, - onStateChange: function (newState) { - if (newState === transactions_1.TransactionState.Terminated) { - // Remove the terminated transaction from the core. - _this.core.userAgentClients.delete(userAgentClientId); - // FIXME: HACK: Our transaction may have been swapped out with a new one - // post authentication (see above), so make sure to only to dispose of - // ourselves if this terminating transaction is our current transaction. - if (transaction === _this._transaction) { - _this.dispose(); - } - } - }, - onTransportError: function (error) { return _this.onTransportError(error); }, - receiveResponse: function (message) { return _this.receiveResponse(message); } - }; - // Create a new transaction with us as the user. - var transaction = new this.transactionConstructor(this.message, this.core.transport, user); - this._transaction = transaction; - // Add the new transaction to the core. - var userAgentClientId = transaction.id + transaction.request.method; - this.core.userAgentClients.set(userAgentClientId, this); - }; - /** - * 8.1.3.1 Transaction Layer Errors - * In some cases, the response returned by the transaction layer will - * not be a SIP message, but rather a transaction layer error. When a - * timeout error is received from the transaction layer, it MUST be - * treated as if a 408 (Request Timeout) status code has been received. - * If a fatal transport error is reported by the transport layer - * (generally, due to fatal ICMP errors in UDP or connection failures in - * TCP), the condition MUST be treated as a 503 (Service Unavailable) - * status code. - * https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - */ - UserAgentClient.prototype.onRequestTimeout = function () { - this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout."); - var message = new messages_1.IncomingResponseMessage(); - message.statusCode = 408; - message.reasonPhrase = "Request Timeout"; - this.receiveResponse(message); - return; - }; - /** - * 8.1.3.1 Transaction Layer Errors - * In some cases, the response returned by the transaction layer will - * not be a SIP message, but rather a transaction layer error. When a - * timeout error is received from the transaction layer, it MUST be - * treated as if a 408 (Request Timeout) status code has been received. - * If a fatal transport error is reported by the transport layer - * (generally, due to fatal ICMP errors in UDP or connection failures in - * TCP), the condition MUST be treated as a 503 (Service Unavailable) - * status code. - * https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - */ - UserAgentClient.prototype.onTransportError = function (error) { - this.logger.error(error.message); - this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable."); - var message = new messages_1.IncomingResponseMessage(); - message.statusCode = 503; - message.reasonPhrase = "Service Unavailable"; - this.receiveResponse(message); - }; - return UserAgentClient; -}()); -exports.UserAgentClient = UserAgentClient; - - -/***/ }), -/* 43 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * BYE UAS. - * @public - */ -var ByeUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(ByeUserAgentServer, _super); - function ByeUserAgentServer(dialog, message, delegate) { - return _super.call(this, transactions_1.NonInviteServerTransaction, dialog.userAgentCore, message, delegate) || this; - } - return ByeUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.ByeUserAgentServer = ByeUserAgentServer; - - -/***/ }), -/* 44 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var exceptions_1 = __webpack_require__(31); -var messages_1 = __webpack_require__(5); -var utils_1 = __webpack_require__(16); -var transactions_1 = __webpack_require__(27); -/** - * User Agent Server (UAS). - * @remarks - * A user agent server is a logical entity - * that generates a response to a SIP request. The response - * accepts, rejects, or redirects the request. This role lasts - * only for the duration of that transaction. In other words, if - * a piece of software responds to a request, it acts as a UAS for - * the duration of that transaction. If it generates a request - * later, it assumes the role of a user agent client for the - * processing of that transaction. - * https://tools.ietf.org/html/rfc3261#section-6 - * @public - */ -var UserAgentServer = /** @class */ (function () { - function UserAgentServer(transactionConstructor, core, message, delegate) { - this.transactionConstructor = transactionConstructor; - this.core = core; - this.message = message; - this.delegate = delegate; - this.logger = this.loggerFactory.getLogger("sip.user-agent-server"); - this.toTag = message.toTag ? message.toTag : utils_1.newTag(); - this.init(); - } - UserAgentServer.prototype.dispose = function () { - this.transaction.dispose(); - }; - Object.defineProperty(UserAgentServer.prototype, "loggerFactory", { - get: function () { - return this.core.loggerFactory; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(UserAgentServer.prototype, "transaction", { - /** The transaction associated with this request. */ - get: function () { - if (!this._transaction) { - throw new Error("Transaction undefined."); - } - return this._transaction; - }, - enumerable: true, - configurable: true - }); - UserAgentServer.prototype.accept = function (options) { - if (options === void 0) { options = { statusCode: 200 }; } - if (!this.acceptable) { - throw new exceptions_1.TransactionStateError(this.message.method + " not acceptable in state " + this.transaction.state + "."); - } - var statusCode = options.statusCode; - if (statusCode < 200 || statusCode > 299) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - var response = this.reply(options); - return response; - }; - UserAgentServer.prototype.progress = function (options) { - if (options === void 0) { options = { statusCode: 180 }; } - if (!this.progressable) { - throw new exceptions_1.TransactionStateError(this.message.method + " not progressable in state " + this.transaction.state + "."); - } - var statusCode = options.statusCode; - if (statusCode < 101 || statusCode > 199) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - var response = this.reply(options); - return response; - }; - UserAgentServer.prototype.redirect = function (contacts, options) { - if (options === void 0) { options = { statusCode: 302 }; } - if (!this.redirectable) { - throw new exceptions_1.TransactionStateError(this.message.method + " not redirectable in state " + this.transaction.state + "."); - } - var statusCode = options.statusCode; - if (statusCode < 300 || statusCode > 399) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - var contactHeaders = new Array(); - contacts.forEach(function (contact) { return contactHeaders.push("Contact: " + contact.toString()); }); - options.extraHeaders = (options.extraHeaders || []).concat(contactHeaders); - var response = this.reply(options); - return response; - }; - UserAgentServer.prototype.reject = function (options) { - if (options === void 0) { options = { statusCode: 480 }; } - if (!this.rejectable) { - throw new exceptions_1.TransactionStateError(this.message.method + " not rejectable in state " + this.transaction.state + "."); - } - var statusCode = options.statusCode; - if (statusCode < 400 || statusCode > 699) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - var response = this.reply(options); - return response; - }; - UserAgentServer.prototype.trying = function (options) { - if (!this.tryingable) { - throw new exceptions_1.TransactionStateError(this.message.method + " not tryingable in state " + this.transaction.state + "."); - } - var response = this.reply({ statusCode: 100 }); - return response; - }; - /** - * If the UAS did not find a matching transaction for the CANCEL - * according to the procedure above, it SHOULD respond to the CANCEL - * with a 481 (Call Leg/Transaction Does Not Exist). If the transaction - * for the original request still exists, the behavior of the UAS on - * receiving a CANCEL request depends on whether it has already sent a - * final response for the original request. If it has, the CANCEL - * request has no effect on the processing of the original request, no - * effect on any session state, and no effect on the responses generated - * for the original request. If the UAS has not issued a final response - * for the original request, its behavior depends on the method of the - * original request. If the original request was an INVITE, the UAS - * SHOULD immediately respond to the INVITE with a 487 (Request - * Terminated). A CANCEL request has no impact on the processing of - * transactions with any other method defined in this specification. - * https://tools.ietf.org/html/rfc3261#section-9.2 - * @param request - Incoming CANCEL request. - */ - UserAgentServer.prototype.receiveCancel = function (message) { - // Note: Currently CANCEL is being handled as a special case. - // No UAS is created to handle the CANCEL and the response to - // it CANCEL is being handled statelessly by the user agent core. - // As such, there is currently no way to externally impact the - // response to the a CANCEL request. - if (this.delegate && this.delegate.onCancel) { - this.delegate.onCancel(message); - } - }; - Object.defineProperty(UserAgentServer.prototype, "acceptable", { - get: function () { - if (this.transaction instanceof transactions_1.InviteServerTransaction) { - return (this.transaction.state === transactions_1.TransactionState.Proceeding || - this.transaction.state === transactions_1.TransactionState.Accepted); - } - if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { - return (this.transaction.state === transactions_1.TransactionState.Trying || - this.transaction.state === transactions_1.TransactionState.Proceeding); - } - throw new Error("Unknown transaction type."); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(UserAgentServer.prototype, "progressable", { - get: function () { - if (this.transaction instanceof transactions_1.InviteServerTransaction) { - return this.transaction.state === transactions_1.TransactionState.Proceeding; - } - if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { - return false; // https://tools.ietf.org/html/rfc4320#section-4.1 - } - throw new Error("Unknown transaction type."); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(UserAgentServer.prototype, "redirectable", { - get: function () { - if (this.transaction instanceof transactions_1.InviteServerTransaction) { - return this.transaction.state === transactions_1.TransactionState.Proceeding; - } - if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { - return (this.transaction.state === transactions_1.TransactionState.Trying || - this.transaction.state === transactions_1.TransactionState.Proceeding); - } - throw new Error("Unknown transaction type."); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(UserAgentServer.prototype, "rejectable", { - get: function () { - if (this.transaction instanceof transactions_1.InviteServerTransaction) { - return this.transaction.state === transactions_1.TransactionState.Proceeding; - } - if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { - return (this.transaction.state === transactions_1.TransactionState.Trying || - this.transaction.state === transactions_1.TransactionState.Proceeding); - } - throw new Error("Unknown transaction type."); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(UserAgentServer.prototype, "tryingable", { - get: function () { - if (this.transaction instanceof transactions_1.InviteServerTransaction) { - return this.transaction.state === transactions_1.TransactionState.Proceeding; - } - if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { - return this.transaction.state === transactions_1.TransactionState.Trying; - } - throw new Error("Unknown transaction type."); - }, - enumerable: true, - configurable: true - }); - /** - * When a UAS wishes to construct a response to a request, it follows - * the general procedures detailed in the following subsections. - * Additional behaviors specific to the response code in question, which - * are not detailed in this section, may also be required. - * - * Once all procedures associated with the creation of a response have - * been completed, the UAS hands the response back to the server - * transaction from which it received the request. - * https://tools.ietf.org/html/rfc3261#section-8.2.6 - * @param statusCode - Status code to reply with. - * @param options - Reply options bucket. - */ - UserAgentServer.prototype.reply = function (options) { - if (!options.toTag && options.statusCode !== 100) { - options.toTag = this.toTag; - } - options.userAgent = options.userAgent || this.core.configuration.userAgentHeaderFieldValue; - options.supported = options.supported || this.core.configuration.supportedOptionTagsResponse; - var response = messages_1.constructOutgoingResponse(this.message, options); - this.transaction.receiveResponse(options.statusCode, response.message); - return response; - }; - UserAgentServer.prototype.init = function () { - var _this = this; - // We are the transaction user. - var user = { - loggerFactory: this.loggerFactory, - onStateChange: function (newState) { - if (newState === transactions_1.TransactionState.Terminated) { - // Remove the terminated transaction from the core. - _this.core.userAgentServers.delete(userAgentServerId); - _this.dispose(); - } - }, - onTransportError: function (error) { - _this.logger.error(error.message); - if (_this.delegate && _this.delegate.onTransportError) { - _this.delegate.onTransportError(error); - } - else { - _this.logger.error("User agent server response transport error."); - } - } - }; - // Create a new transaction with us as the user. - var transaction = new this.transactionConstructor(this.message, this.core.transport, user); - this._transaction = transaction; - // Add the new transaction to the core. - var userAgentServerId = transaction.id; - this.core.userAgentServers.set(transaction.id, this); - }; - return UserAgentServer; -}()); -exports.UserAgentServer = UserAgentServer; - - -/***/ }), -/* 45 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * INFO UAC. - * @public - */ -var InfoUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(InfoUserAgentClient, _super); - function InfoUserAgentClient(dialog, delegate, options) { - var _this = this; - var message = dialog.createOutgoingRequestMessage(messages_1.C.INFO, options); - _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; - return _this; - } - return InfoUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.InfoUserAgentClient = InfoUserAgentClient; - - -/***/ }), -/* 46 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * INFO UAS. - * @public - */ -var InfoUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(InfoUserAgentServer, _super); - function InfoUserAgentServer(dialog, message, delegate) { - return _super.call(this, transactions_1.NonInviteServerTransaction, dialog.userAgentCore, message, delegate) || this; - } - return InfoUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.InfoUserAgentServer = InfoUserAgentServer; - - -/***/ }), -/* 47 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * NOTIFY UAS. - * @public - */ -var NotifyUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(NotifyUserAgentClient, _super); - function NotifyUserAgentClient(dialog, delegate, options) { - var _this = this; - var message = dialog.createOutgoingRequestMessage(messages_1.C.NOTIFY, options); - _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; - return _this; - } - return NotifyUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.NotifyUserAgentClient = NotifyUserAgentClient; - - -/***/ }), -/* 48 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * NOTIFY UAS. - * @public - */ -var NotifyUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(NotifyUserAgentServer, _super); - /** - * NOTIFY UAS constructor. - * @param dialogOrCore - Dialog for in dialog NOTIFY, UserAgentCore for out of dialog NOTIFY (deprecated). - * @param message - Incoming NOTIFY request message. - */ - function NotifyUserAgentServer(dialogOrCore, message, delegate) { - var _this = this; - var userAgentCore = instanceOfDialog(dialogOrCore) ? - dialogOrCore.userAgentCore : - dialogOrCore; - _this = _super.call(this, transactions_1.NonInviteServerTransaction, userAgentCore, message, delegate) || this; - return _this; - } - return NotifyUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.NotifyUserAgentServer = NotifyUserAgentServer; -function instanceOfDialog(object) { - return object.userAgentCore !== undefined; -} - - -/***/ }), -/* 49 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * PRACK UAC. - * @public - */ -var PrackUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(PrackUserAgentClient, _super); - function PrackUserAgentClient(dialog, delegate, options) { - var _this = this; - var message = dialog.createOutgoingRequestMessage(messages_1.C.PRACK, options); - _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; - dialog.signalingStateTransition(message); - return _this; - } - return PrackUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.PrackUserAgentClient = PrackUserAgentClient; - - -/***/ }), -/* 50 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * PRACK UAS. - * @public - */ -var PrackUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(PrackUserAgentServer, _super); - function PrackUserAgentServer(dialog, message, delegate) { - var _this = _super.call(this, transactions_1.NonInviteServerTransaction, dialog.userAgentCore, message, delegate) || this; - // Update dialog signaling state with offer/answer in body - dialog.signalingStateTransition(message); - _this.dialog = dialog; - return _this; - } - /** - * Update the dialog signaling state on a 2xx response. - * @param options - Options bucket. - */ - PrackUserAgentServer.prototype.accept = function (options) { - if (options === void 0) { options = { statusCode: 200 }; } - if (options.body) { - // Update dialog signaling state with offer/answer in body - this.dialog.signalingStateTransition(options.body); - } - return _super.prototype.accept.call(this, options); - }; - return PrackUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.PrackUserAgentServer = PrackUserAgentServer; - - -/***/ }), -/* 51 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * Re-INVITE UAC. - * @remarks - * 14 Modifying an Existing Session - * https://tools.ietf.org/html/rfc3261#section-14 - * 14.1 UAC Behavior - * https://tools.ietf.org/html/rfc3261#section-14.1 - * @public - */ -var ReInviteUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(ReInviteUserAgentClient, _super); - function ReInviteUserAgentClient(dialog, delegate, options) { - var _this = this; - var message = dialog.createOutgoingRequestMessage(messages_1.C.INVITE, options); - _this = _super.call(this, transactions_1.InviteClientTransaction, dialog.userAgentCore, message, delegate) || this; - _this.delegate = delegate; - dialog.signalingStateTransition(message); - // FIXME: TODO: next line obviously needs to be improved... - dialog.reinviteUserAgentClient = _this; // let the dialog know re-invite request sent - _this.dialog = dialog; - return _this; - } - ReInviteUserAgentClient.prototype.receiveResponse = function (message) { - var _this = this; - var statusCode = message.statusCode ? message.statusCode.toString() : ""; - if (!statusCode) { - throw new Error("Response status code undefined."); - } - switch (true) { - case /^100$/.test(statusCode): - if (this.delegate && this.delegate.onTrying) { - this.delegate.onTrying({ message: message }); - } - break; - case /^1[0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onProgress) { - this.delegate.onProgress({ - message: message, - session: this.dialog, - prack: function (options) { - throw new Error("Unimplemented."); - } - }); - } - break; - case /^2[0-9]{2}$/.test(statusCode): - // Update dialog signaling state with offer/answer in body - this.dialog.signalingStateTransition(message); - if (this.delegate && this.delegate.onAccept) { - this.delegate.onAccept({ - message: message, - session: this.dialog, - ack: function (options) { - var outgoingAckRequest = _this.dialog.ack(options); - return outgoingAckRequest; - } - }); - } - break; - case /^3[0-9]{2}$/.test(statusCode): - this.dialog.signalingStateRollback(); - this.dialog.reinviteUserAgentClient = undefined; // ACK was handled by transaction - if (this.delegate && this.delegate.onRedirect) { - this.delegate.onRedirect({ message: message }); - } - break; - case /^[4-6][0-9]{2}$/.test(statusCode): - this.dialog.signalingStateRollback(); - this.dialog.reinviteUserAgentClient = undefined; // ACK was handled by transaction - if (this.delegate && this.delegate.onReject) { - this.delegate.onReject({ message: message }); - } - else { - // If a UA receives a non-2xx final response to a re-INVITE, the session - // parameters MUST remain unchanged, as if no re-INVITE had been issued. - // Note that, as stated in Section 12.2.1.2, if the non-2xx final - // response is a 481 (Call/Transaction Does Not Exist), or a 408 - // (Request Timeout), or no response at all is received for the re- - // INVITE (that is, a timeout is returned by the INVITE client - // transaction), the UAC will terminate the dialog. - // - // If a UAC receives a 491 response to a re-INVITE, it SHOULD start a - // timer with a value T chosen as follows: - // - // 1. If the UAC is the owner of the Call-ID of the dialog ID - // (meaning it generated the value), T has a randomly chosen value - // between 2.1 and 4 seconds in units of 10 ms. - // - // 2. If the UAC is not the owner of the Call-ID of the dialog ID, T - // has a randomly chosen value of between 0 and 2 seconds in units - // of 10 ms. - // - // When the timer fires, the UAC SHOULD attempt the re-INVITE once more, - // if it still desires for that session modification to take place. For - // example, if the call was already hung up with a BYE, the re-INVITE - // would not take place. - // https://tools.ietf.org/html/rfc3261#section-14.1 - // FIXME: TODO: The above. - } - break; - default: - throw new Error("Invalid status code " + statusCode); - } - }; - return ReInviteUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.ReInviteUserAgentClient = ReInviteUserAgentClient; - - -/***/ }), -/* 52 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * Re-INVITE UAS. - * @remarks - * 14 Modifying an Existing Session - * https://tools.ietf.org/html/rfc3261#section-14 - * 14.2 UAS Behavior - * https://tools.ietf.org/html/rfc3261#section-14.2 - * @public - */ -var ReInviteUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(ReInviteUserAgentServer, _super); - function ReInviteUserAgentServer(dialog, message, delegate) { - var _this = _super.call(this, transactions_1.InviteServerTransaction, dialog.userAgentCore, message, delegate) || this; - dialog.reinviteUserAgentServer = _this; - _this.dialog = dialog; - return _this; - } - /** - * Update the dialog signaling state on a 2xx response. - * @param options - Options bucket. - */ - ReInviteUserAgentServer.prototype.accept = function (options) { - if (options === void 0) { options = { statusCode: 200 }; } - // FIXME: The next two lines SHOULD go away, but I suppose it's technically harmless... - // These are here because some versions of SIP.js prior to 0.13.8 set the route set - // of all in dialog ACKs based on the Record-Route headers in the associated 2xx - // response. While this worked for dialog forming 2xx responses, it was technically - // broken for re-INVITE ACKS as it only worked if the UAS populated the Record-Route - // headers in the re-INVITE 2xx response (which is not required and a waste of bandwidth - // as the should be ignored if present in re-INVITE ACKS) and the UAS populated - // the Record-Route headers with the correct values (would be weird not too, but...). - // Anyway, for now the technically useless Record-Route headers are being added - // to maintain "backwards compatibility" with the older broken versions of SIP.js. - options.extraHeaders = options.extraHeaders || []; - options.extraHeaders = options.extraHeaders.concat(this.dialog.routeSet.map(function (route) { return "Record-Route: " + route; })); - // Send and return the response - var response = _super.prototype.accept.call(this, options); - var session = this.dialog; - var result = tslib_1.__assign({}, response, { session: session }); - if (options.body) { - // Update dialog signaling state with offer/answer in body - this.dialog.signalingStateTransition(options.body); - } - // Update dialog - this.dialog.reConfirm(); - return result; - }; - /** - * Update the dialog signaling state on a 1xx response. - * @param options - Progress options bucket. - */ - ReInviteUserAgentServer.prototype.progress = function (options) { - if (options === void 0) { options = { statusCode: 180 }; } - // Send and return the response - var response = _super.prototype.progress.call(this, options); - var session = this.dialog; - var result = tslib_1.__assign({}, response, { session: session }); - // Update dialog signaling state - if (options.body) { - this.dialog.signalingStateTransition(options.body); - } - return result; - }; - /** - * TODO: Not Yet Supported - * @param contacts - Contacts to redirect to. - * @param options - Redirect options bucket. - */ - ReInviteUserAgentServer.prototype.redirect = function (contacts, options) { - if (options === void 0) { options = { statusCode: 302 }; } - this.dialog.signalingStateRollback(); - this.dialog.reinviteUserAgentServer = undefined; // ACK will be handled by transaction - throw new Error("Unimplemented."); - }; - /** - * 3.1 Background on Re-INVITE Handling by UASs - * An error response to a re-INVITE has the following semantics. As - * specified in Section 12.2.2 of RFC 3261 [RFC3261], if a re-INVITE is - * rejected, no state changes are performed. - * https://tools.ietf.org/html/rfc6141#section-3.1 - * @param options - Reject options bucket. - */ - ReInviteUserAgentServer.prototype.reject = function (options) { - if (options === void 0) { options = { statusCode: 488 }; } - this.dialog.signalingStateRollback(); - this.dialog.reinviteUserAgentServer = undefined; // ACK will be handled by transaction - return _super.prototype.reject.call(this, options); - }; - return ReInviteUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.ReInviteUserAgentServer = ReInviteUserAgentServer; - - -/***/ }), -/* 53 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * REFER UAC. - * @public - */ -var ReferUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(ReferUserAgentClient, _super); - function ReferUserAgentClient(dialog, delegate, options) { - var _this = this; - var message = dialog.createOutgoingRequestMessage(messages_1.C.REFER, options); - _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; - return _this; - } - return ReferUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.ReferUserAgentClient = ReferUserAgentClient; - - -/***/ }), -/* 54 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * REFER UAS. - * @public - */ -var ReferUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(ReferUserAgentServer, _super); - /** - * REFER UAS constructor. - * @param dialogOrCore - Dialog for in dialog REFER, UserAgentCore for out of dialog REFER. - * @param message - Incoming REFER request message. - */ - function ReferUserAgentServer(dialogOrCore, message, delegate) { - var _this = this; - var userAgentCore = instanceOfSessionDialog(dialogOrCore) ? - dialogOrCore.userAgentCore : - dialogOrCore; - _this = _super.call(this, transactions_1.NonInviteServerTransaction, userAgentCore, message, delegate) || this; - return _this; - } - return ReferUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.ReferUserAgentServer = ReferUserAgentServer; -function instanceOfSessionDialog(object) { - return object.userAgentCore !== undefined; -} - - -/***/ }), -/* 55 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var subscription_1 = __webpack_require__(56); -var timers_1 = __webpack_require__(26); -var allowed_methods_1 = __webpack_require__(58); -var notify_user_agent_server_1 = __webpack_require__(48); -var re_subscribe_user_agent_client_1 = __webpack_require__(59); -var dialog_1 = __webpack_require__(4); -/** - * Subscription Dialog. - * @remarks - * SIP-Specific Event Notification - * - * Abstract - * - * This document describes an extension to the Session Initiation - * Protocol (SIP) defined by RFC 3261. The purpose of this extension is - * to provide an extensible framework by which SIP nodes can request - * notification from remote nodes indicating that certain events have - * occurred. - * - * Note that the event notification mechanisms defined herein are NOT - * intended to be a general-purpose infrastructure for all classes of - * event subscription and notification. - * - * This document represents a backwards-compatible improvement on the - * original mechanism described by RFC 3265, taking into account several - * years of implementation experience. Accordingly, this document - * obsoletes RFC 3265. This document also updates RFC 4660 slightly to - * accommodate some small changes to the mechanism that were discussed - * in that document. - * - * https://tools.ietf.org/html/rfc6665 - * @public - */ -var SubscriptionDialog = /** @class */ (function (_super) { - tslib_1.__extends(SubscriptionDialog, _super); - function SubscriptionDialog(subscriptionEvent, subscriptionExpires, subscriptionState, core, state, delegate) { - var _this = _super.call(this, core, state) || this; - _this.delegate = delegate; - _this._autoRefresh = false; - _this._subscriptionEvent = subscriptionEvent; - _this._subscriptionExpires = subscriptionExpires; - _this._subscriptionExpiresInitial = subscriptionExpires; - _this._subscriptionExpiresLastSet = Math.floor(Date.now() / 1000); - _this._subscriptionRefresh = undefined; - _this._subscriptionRefreshLastSet = undefined; - _this._subscriptionState = subscriptionState; - _this.logger = core.loggerFactory.getLogger("sip.subscribe-dialog"); - _this.logger.log("SUBSCRIBE dialog " + _this.id + " constructed"); - return _this; - } - /** - * When a UAC receives a response that establishes a dialog, it - * constructs the state of the dialog. This state MUST be maintained - * for the duration of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.1.2 - * @param outgoingRequestMessage - Outgoing request message for dialog. - * @param incomingResponseMessage - Incoming response message creating dialog. - */ - SubscriptionDialog.initialDialogStateForSubscription = function (outgoingSubscribeRequestMessage, incomingNotifyRequestMessage) { - // If the request was sent over TLS, and the Request-URI contained a - // SIPS URI, the "secure" flag is set to TRUE. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - var secure = false; // FIXME: Currently no support for TLS. - // The route set MUST be set to the list of URIs in the Record-Route - // header field from the response, taken in reverse order and preserving - // all URI parameters. If no Record-Route header field is present in - // the response, the route set MUST be set to the empty set. This route - // set, even if empty, overrides any pre-existing route set for future - // requests in this dialog. The remote target MUST be set to the URI - // from the Contact header field of the response. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - var routeSet = incomingNotifyRequestMessage.getHeaders("record-route"); - var contact = incomingNotifyRequestMessage.parseHeader("contact"); - if (!contact) { // TODO: Review to make sure this will never happen - throw new Error("Contact undefined."); - } - if (!(contact instanceof messages_1.NameAddrHeader)) { - throw new Error("Contact not instance of NameAddrHeader."); - } - var remoteTarget = contact.uri; - // The local sequence number MUST be set to the value of the sequence - // number in the CSeq header field of the request. The remote sequence - // number MUST be empty (it is established when the remote UA sends a - // request within the dialog). The call identifier component of the - // dialog ID MUST be set to the value of the Call-ID in the request. - // The local tag component of the dialog ID MUST be set to the tag in - // the From field in the request, and the remote tag component of the - // dialog ID MUST be set to the tag in the To field of the response. A - // UAC MUST be prepared to receive a response without a tag in the To - // field, in which case the tag is considered to have a value of null. - // - // This is to maintain backwards compatibility with RFC 2543, which - // did not mandate To tags. - // - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - var localSequenceNumber = outgoingSubscribeRequestMessage.cseq; - var remoteSequenceNumber = undefined; - var callId = outgoingSubscribeRequestMessage.callId; - var localTag = outgoingSubscribeRequestMessage.fromTag; - var remoteTag = incomingNotifyRequestMessage.fromTag; - if (!callId) { // TODO: Review to make sure this will never happen - throw new Error("Call id undefined."); - } - if (!localTag) { // TODO: Review to make sure this will never happen - throw new Error("From tag undefined."); - } - if (!remoteTag) { // TODO: Review to make sure this will never happen - throw new Error("To tag undefined."); // FIXME: No backwards compatibility with RFC 2543 - } - // The remote URI MUST be set to the URI in the To field, and the local - // URI MUST be set to the URI in the From field. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - if (!outgoingSubscribeRequestMessage.from) { // TODO: Review to make sure this will never happen - throw new Error("From undefined."); - } - if (!outgoingSubscribeRequestMessage.to) { // TODO: Review to make sure this will never happen - throw new Error("To undefined."); - } - var localURI = outgoingSubscribeRequestMessage.from.uri; - var remoteURI = outgoingSubscribeRequestMessage.to.uri; - // A dialog can also be in the "early" state, which occurs when it is - // created with a provisional response, and then transition to the - // "confirmed" state when a 2xx final response arrives. - // https://tools.ietf.org/html/rfc3261#section-12 - var early = false; - var dialogState = { - id: callId + localTag + remoteTag, - early: early, - callId: callId, - localTag: localTag, - remoteTag: remoteTag, - localSequenceNumber: localSequenceNumber, - remoteSequenceNumber: remoteSequenceNumber, - localURI: localURI, - remoteURI: remoteURI, - remoteTarget: remoteTarget, - routeSet: routeSet, - secure: secure - }; - return dialogState; - }; - SubscriptionDialog.prototype.dispose = function () { - _super.prototype.dispose.call(this); - if (this.N) { - clearTimeout(this.N); - this.N = undefined; - } - this.refreshTimerClear(); - this.logger.log("SUBSCRIBE dialog " + this.id + " destroyed"); - }; - Object.defineProperty(SubscriptionDialog.prototype, "autoRefresh", { - get: function () { - return this._autoRefresh; - }, - set: function (autoRefresh) { - this._autoRefresh = true; - this.refreshTimerSet(); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SubscriptionDialog.prototype, "subscriptionEvent", { - get: function () { - return this._subscriptionEvent; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SubscriptionDialog.prototype, "subscriptionExpires", { - /** Number of seconds until subscription expires. */ - get: function () { - var secondsSinceLastSet = Math.floor(Date.now() / 1000) - this._subscriptionExpiresLastSet; - var secondsUntilExpires = this._subscriptionExpires - secondsSinceLastSet; - return Math.max(secondsUntilExpires, 0); - }, - set: function (expires) { - if (expires < 0) { - throw new Error("Expires must be greater than or equal to zero."); - } - this._subscriptionExpires = expires; - this._subscriptionExpiresLastSet = Math.floor(Date.now() / 1000); - if (this.autoRefresh) { - var refresh = this.subscriptionRefresh; - if (refresh === undefined || refresh >= expires) { - this.refreshTimerSet(); - } - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SubscriptionDialog.prototype, "subscriptionExpiresInitial", { - get: function () { - return this._subscriptionExpiresInitial; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SubscriptionDialog.prototype, "subscriptionRefresh", { - /** Number of seconds until subscription auto refresh. */ - get: function () { - if (this._subscriptionRefresh === undefined || this._subscriptionRefreshLastSet === undefined) { - return undefined; - } - var secondsSinceLastSet = Math.floor(Date.now() / 1000) - this._subscriptionRefreshLastSet; - var secondsUntilExpires = this._subscriptionRefresh - secondsSinceLastSet; - return Math.max(secondsUntilExpires, 0); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SubscriptionDialog.prototype, "subscriptionState", { - get: function () { - return this._subscriptionState; - }, - enumerable: true, - configurable: true - }); - /** - * Receive in dialog request message from transport. - * @param message - The incoming request message. - */ - SubscriptionDialog.prototype.receiveRequest = function (message) { - this.logger.log("SUBSCRIBE dialog " + this.id + " received " + message.method + " request"); - // Request within a dialog out of sequence guard. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (!this.sequenceGuard(message)) { - this.logger.log("SUBSCRIBE dialog " + this.id + " rejected out of order " + message.method + " request."); - return; - } - // Request within a dialog common processing. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - _super.prototype.receiveRequest.call(this, message); - // Switch on method and then delegate. - switch (message.method) { - case messages_1.C.NOTIFY: - this.onNotify(message); - break; - default: - this.logger.log("SUBSCRIBE dialog " + this.id + " received unimplemented " + message.method + " request"); - this.core.replyStateless(message, { statusCode: 501 }); - break; - } - }; - /** - * 4.1.2.2. Refreshing of Subscriptions - * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - */ - SubscriptionDialog.prototype.refresh = function () { - var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); - var options = {}; - options.extraHeaders = (options.extraHeaders || []).slice(); - options.extraHeaders.push(allowHeader); - options.extraHeaders.push("Event: " + this.subscriptionEvent); - options.extraHeaders.push("Expires: " + this.subscriptionExpiresInitial); - options.extraHeaders.push("Contact: " + this.core.configuration.contact.toString()); - return this.subscribe(undefined, options); - }; - /** - * 4.1.2.2. Refreshing of Subscriptions - * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - * @param delegate - Delegate to handle responses. - * @param options - Options bucket. - */ - SubscriptionDialog.prototype.subscribe = function (delegate, options) { - var _this = this; - if (options === void 0) { options = {}; } - if (this.subscriptionState !== subscription_1.SubscriptionState.Pending && this.subscriptionState !== subscription_1.SubscriptionState.Active) { - // FIXME: This needs to be a proper exception - throw new Error("Invalid state " + this.subscriptionState + ". May only re-subscribe while in state \"pending\" or \"active\"."); - } - this.logger.log("SUBSCRIBE dialog " + this.id + " sending SUBSCRIBE request"); - var uac = new re_subscribe_user_agent_client_1.ReSubscribeUserAgentClient(this, delegate, options); - // When refreshing a subscription, a subscriber starts Timer N, set to - // 64*T1, when it sends the SUBSCRIBE request. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - this.N = setTimeout(function () { return _this.timer_N(); }, timers_1.Timers.TIMER_N); - return uac; - }; - /** - * 4.4.1. Dialog Creation and Termination - * A subscription is destroyed after a notifier sends a NOTIFY request - * with a "Subscription-State" of "terminated", or in certain error - * situations described elsewhere in this document. - * https://tools.ietf.org/html/rfc6665#section-4.4.1 - */ - SubscriptionDialog.prototype.terminate = function () { - this.stateTransition(subscription_1.SubscriptionState.Terminated); - this.onTerminated(); - }; - /** - * 4.1.2.3. Unsubscribing - * https://tools.ietf.org/html/rfc6665#section-4.1.2.3 - */ - SubscriptionDialog.prototype.unsubscribe = function () { - var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); - var options = {}; - options.extraHeaders = (options.extraHeaders || []).slice(); - options.extraHeaders.push(allowHeader); - options.extraHeaders.push("Event: " + this.subscriptionEvent); - options.extraHeaders.push("Expires: 0"); - options.extraHeaders.push("Contact: " + this.core.configuration.contact.toString()); - return this.subscribe(undefined, options); - }; - /** - * Handle in dialog NOTIFY requests. - * This does not include the first NOTIFY which created the dialog. - * @param message - The incoming NOTIFY request message. - */ - SubscriptionDialog.prototype.onNotify = function (message) { - // If, for some reason, the event package designated in the "Event" - // header field of the NOTIFY request is not supported, the subscriber - // will respond with a 489 (Bad Event) response. - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - var event = message.parseHeader("Event").event; - if (!event || event !== this.subscriptionEvent) { - this.core.replyStateless(message, { statusCode: 489 }); - return; - } - // In the state diagram, "Re-subscription times out" means that an - // attempt to refresh or update the subscription using a new SUBSCRIBE - // request does not result in a NOTIFY request before the corresponding - // Timer N expires. - // https://tools.ietf.org/html/rfc6665#section-4.1.2 - if (this.N) { - clearTimeout(this.N); - this.N = undefined; - } - // NOTIFY requests MUST contain "Subscription-State" header fields that - // indicate the status of the subscription. - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - var subscriptionState = message.parseHeader("Subscription-State"); - if (!subscriptionState || !subscriptionState.state) { - this.core.replyStateless(message, { statusCode: 489 }); - return; - } - var state = subscriptionState.state; - var expires = subscriptionState.expires ? Math.max(subscriptionState.expires, 0) : undefined; - // Update our state and expiration. - switch (state) { - case "pending": - this.stateTransition(subscription_1.SubscriptionState.Pending, expires); - break; - case "active": - this.stateTransition(subscription_1.SubscriptionState.Active, expires); - break; - case "terminated": - this.stateTransition(subscription_1.SubscriptionState.Terminated, expires); - break; - default: - this.logger.warn("Unrecognized subscription state."); - break; - } - // Delegate remainder of NOTIFY handling. - var uas = new notify_user_agent_server_1.NotifyUserAgentServer(this, message); - if (this.delegate && this.delegate.onNotify) { - this.delegate.onNotify(uas); - } - else { - uas.accept(); - } - }; - SubscriptionDialog.prototype.onRefresh = function (request) { - if (this.delegate && this.delegate.onRefresh) { - this.delegate.onRefresh(request); - } - }; - SubscriptionDialog.prototype.onTerminated = function () { - if (this.delegate && this.delegate.onTerminated) { - this.delegate.onTerminated(); - } - }; - SubscriptionDialog.prototype.refreshTimerClear = function () { - if (this.refreshTimer) { - clearTimeout(this.refreshTimer); - this.refreshTimer = undefined; - } - }; - SubscriptionDialog.prototype.refreshTimerSet = function () { - var _this = this; - this.refreshTimerClear(); - if (this.autoRefresh && this.subscriptionExpires > 0) { - var refresh = this.subscriptionExpires * 900; - this._subscriptionRefresh = Math.floor(refresh / 1000); - this._subscriptionRefreshLastSet = Math.floor(Date.now() / 1000); - this.refreshTimer = setTimeout(function () { - _this.refreshTimer = undefined; - _this._subscriptionRefresh = undefined; - _this._subscriptionRefreshLastSet = undefined; - _this.onRefresh(_this.refresh()); - }, refresh); - } - }; - SubscriptionDialog.prototype.stateTransition = function (newState, newExpires) { - var _this = this; - // Assert valid state transitions. - var invalidStateTransition = function () { - _this.logger.warn("Invalid subscription state transition from " + _this.subscriptionState + " to " + newState); - }; - switch (newState) { - case subscription_1.SubscriptionState.Initial: - invalidStateTransition(); - return; - case subscription_1.SubscriptionState.NotifyWait: - invalidStateTransition(); - return; - case subscription_1.SubscriptionState.Pending: - if (this.subscriptionState !== subscription_1.SubscriptionState.NotifyWait && - this.subscriptionState !== subscription_1.SubscriptionState.Pending) { - invalidStateTransition(); - return; - } - break; - case subscription_1.SubscriptionState.Active: - if (this.subscriptionState !== subscription_1.SubscriptionState.NotifyWait && - this.subscriptionState !== subscription_1.SubscriptionState.Pending && - this.subscriptionState !== subscription_1.SubscriptionState.Active) { - invalidStateTransition(); - return; - } - break; - case subscription_1.SubscriptionState.Terminated: - if (this.subscriptionState !== subscription_1.SubscriptionState.NotifyWait && - this.subscriptionState !== subscription_1.SubscriptionState.Pending && - this.subscriptionState !== subscription_1.SubscriptionState.Active) { - invalidStateTransition(); - return; - } - break; - default: - invalidStateTransition(); - return; - } - // If the "Subscription-State" value is "pending", the subscription has - // been received by the notifier, but there is insufficient policy - // information to grant or deny the subscription yet. If the header - // field also contains an "expires" parameter, the subscriber SHOULD - // take it as the authoritative subscription duration and adjust - // accordingly. No further action is necessary on the part of the - // subscriber. The "retry-after" and "reason" parameters have no - // semantics for "pending". - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - if (newState === subscription_1.SubscriptionState.Pending) { - if (newExpires) { - this.subscriptionExpires = newExpires; - } - } - // If the "Subscription-State" header field value is "active", it means - // that the subscription has been accepted and (in general) has been - // authorized. If the header field also contains an "expires" - // parameter, the subscriber SHOULD take it as the authoritative - // subscription duration and adjust accordingly. The "retry-after" and - // "reason" parameters have no semantics for "active". - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - if (newState === subscription_1.SubscriptionState.Active) { - if (newExpires) { - this.subscriptionExpires = newExpires; - } - } - // If the "Subscription-State" value is "terminated", the subscriber - // MUST consider the subscription terminated. The "expires" parameter - // has no semantics for "terminated" -- notifiers SHOULD NOT include an - // "expires" parameter on a "Subscription-State" header field with a - // value of "terminated", and subscribers MUST ignore any such - // parameter, if present. - if (newState === subscription_1.SubscriptionState.Terminated) { - this.dispose(); - } - this._subscriptionState = newState; - }; - /** - * When refreshing a subscription, a subscriber starts Timer N, set to - * 64*T1, when it sends the SUBSCRIBE request. If this Timer N expires - * prior to the receipt of a NOTIFY request, the subscriber considers - * the subscription terminated. If the subscriber receives a success - * response to the SUBSCRIBE request that indicates that no NOTIFY - * request will be generated -- such as the 204 response defined for use - * with the optional extension described in [RFC5839] -- then it MUST - * cancel Timer N. - * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - */ - SubscriptionDialog.prototype.timer_N = function () { - if (this.subscriptionState !== subscription_1.SubscriptionState.Terminated) { - this.stateTransition(subscription_1.SubscriptionState.Terminated); - this.onTerminated(); - } - }; - return SubscriptionDialog; -}(dialog_1.Dialog)); -exports.SubscriptionDialog = SubscriptionDialog; - - -/***/ }), -/* 56 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -tslib_1.__exportStar(__webpack_require__(57), exports); - - -/***/ }), -/* 57 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * Subscription state. - * @remarks - * https://tools.ietf.org/html/rfc6665#section-4.1.2 - * @public - */ -var SubscriptionState; -(function (SubscriptionState) { - SubscriptionState["Initial"] = "Initial"; - SubscriptionState["NotifyWait"] = "NotifyWait"; - SubscriptionState["Pending"] = "Pending"; - SubscriptionState["Active"] = "Active"; - SubscriptionState["Terminated"] = "Terminated"; -})(SubscriptionState = exports.SubscriptionState || (exports.SubscriptionState = {})); - - -/***/ }), -/* 58 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var messages_1 = __webpack_require__(5); -/** - * FIXME: TODO: Should be configurable/variable. - */ -exports.AllowedMethods = [ - messages_1.C.ACK, - messages_1.C.BYE, - messages_1.C.CANCEL, - messages_1.C.INFO, - messages_1.C.INVITE, - messages_1.C.MESSAGE, - messages_1.C.NOTIFY, - messages_1.C.OPTIONS, - messages_1.C.PRACK, - messages_1.C.REFER, - messages_1.C.REGISTER, - messages_1.C.SUBSCRIBE -]; - - -/***/ }), -/* 59 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * Re-SUBSCRIBE UAC. - * @public - */ -var ReSubscribeUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(ReSubscribeUserAgentClient, _super); - function ReSubscribeUserAgentClient(dialog, delegate, options) { - var _this = this; - var message = dialog.createOutgoingRequestMessage(messages_1.C.SUBSCRIBE, options); - _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; - _this.dialog = dialog; - return _this; - } - ReSubscribeUserAgentClient.prototype.waitNotifyStop = function () { - // TODO: Placeholder. Not utilized currently. - return; - }; - /** - * Receive a response from the transaction layer. - * @param message - Incoming response message. - */ - ReSubscribeUserAgentClient.prototype.receiveResponse = function (message) { - if (message.statusCode && message.statusCode >= 200 && message.statusCode < 300) { - // The "Expires" header field in a 200-class response to SUBSCRIBE - // request indicates the actual duration for which the subscription will - // remain active (unless refreshed). The received value might be - // smaller than the value indicated in the SUBSCRIBE request but cannot - // be larger; see Section 4.2.1 for details. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - var expires = message.getHeader("Expires"); - if (!expires) { - this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE"); - } - else { - var subscriptionExpiresReceived = Number(expires); - if (this.dialog.subscriptionExpires > subscriptionExpiresReceived) { - this.dialog.subscriptionExpires = subscriptionExpiresReceived; - } - } - } - if (message.statusCode && message.statusCode >= 400 && message.statusCode < 700) { - // If a SUBSCRIBE request to refresh a subscription receives a 404, 405, - // 410, 416, 480-485, 489, 501, or 604 response, the subscriber MUST - // consider the subscription terminated. (See [RFC5057] for further - // details and notes about the effect of error codes on dialogs and - // usages within dialog, such as subscriptions). If the subscriber - // wishes to re-subscribe to the state, he does so by composing an - // unrelated initial SUBSCRIBE request with a freshly generated Call-ID - // and a new, unique "From" tag (see Section 4.1.2.1). - // https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - var errorCodes = [404, 405, 410, 416, 480, 481, 482, 483, 484, 485, 489, 501, 604]; - if (errorCodes.includes(message.statusCode)) { - this.dialog.terminate(); - } - // If a SUBSCRIBE request to refresh a subscription fails with any error - // code other than those listed above, the original subscription is - // still considered valid for the duration of the most recently known - // "Expires" value as negotiated by the most recent successful SUBSCRIBE - // transaction, or as communicated by a NOTIFY request in its - // "Subscription-State" header field "expires" parameter. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - } - _super.prototype.receiveResponse.call(this, message); - }; - return ReSubscribeUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.ReSubscribeUserAgentClient = ReSubscribeUserAgentClient; - - -/***/ }), -/* 60 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -tslib_1.__exportStar(__webpack_require__(61), exports); -tslib_1.__exportStar(__webpack_require__(62), exports); -tslib_1.__exportStar(__webpack_require__(63), exports); - - -/***/ }), -/* 61 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * Log levels. - * @public - */ -var Levels; -(function (Levels) { - Levels[Levels["error"] = 0] = "error"; - Levels[Levels["warn"] = 1] = "warn"; - Levels[Levels["log"] = 2] = "log"; - Levels[Levels["debug"] = 3] = "debug"; -})(Levels = exports.Levels || (exports.Levels = {})); - - -/***/ }), -/* 62 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var levels_1 = __webpack_require__(61); -var logger_1 = __webpack_require__(63); -/** - * Logger. - * @public - */ -var LoggerFactory = /** @class */ (function () { - function LoggerFactory() { - this.builtinEnabled = true; - this._level = levels_1.Levels.log; - this.loggers = {}; - this.logger = this.getLogger("sip:loggerfactory"); - } - Object.defineProperty(LoggerFactory.prototype, "level", { - get: function () { return this._level; }, - set: function (newLevel) { - if (newLevel >= 0 && newLevel <= 3) { - this._level = newLevel; - } - else if (newLevel > 3) { - this._level = 3; - } - else if (levels_1.Levels.hasOwnProperty(newLevel)) { - this._level = newLevel; - } - else { - this.logger.error("invalid 'level' parameter value: " + JSON.stringify(newLevel)); - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(LoggerFactory.prototype, "connector", { - get: function () { - return this._connector; - }, - set: function (value) { - if (!value) { - this._connector = undefined; - } - else if (typeof value === "function") { - this._connector = value; - } - else { - this.logger.error("invalid 'connector' parameter value: " + JSON.stringify(value)); - } - }, - enumerable: true, - configurable: true - }); - LoggerFactory.prototype.getLogger = function (category, label) { - if (label && this.level === 3) { - return new logger_1.Logger(this, category, label); - } - else if (this.loggers[category]) { - return this.loggers[category]; - } - else { - var logger = new logger_1.Logger(this, category); - this.loggers[category] = logger; - return logger; - } - }; - LoggerFactory.prototype.genericLog = function (levelToLog, category, label, content) { - if (this.level >= levelToLog) { - if (this.builtinEnabled) { - this.print(levelToLog, category, label, content); - } - } - if (this.connector) { - this.connector(levels_1.Levels[levelToLog], category, label, content); - } - }; - LoggerFactory.prototype.print = function (levelToLog, category, label, content) { - if (typeof content === "string") { - var prefix = [new Date(), category]; - if (label) { - prefix.push(label); - } - content = prefix.concat(content).join(" | "); - } - switch (levelToLog) { - case levels_1.Levels.error: - // tslint:disable-next-line:no-console - console.error(content); - break; - case levels_1.Levels.warn: - // tslint:disable-next-line:no-console - console.warn(content); - break; - case levels_1.Levels.log: - // tslint:disable-next-line:no-console - console.log(content); - break; - case levels_1.Levels.debug: - // tslint:disable-next-line:no-console - console.debug(content); - break; - default: - break; - } - }; - return LoggerFactory; -}()); -exports.LoggerFactory = LoggerFactory; - - -/***/ }), -/* 63 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var levels_1 = __webpack_require__(61); -/** - * Logger. - * @public - */ -var Logger = /** @class */ (function () { - function Logger(logger, category, label) { - this.logger = logger; - this.category = category; - this.label = label; - } - Logger.prototype.error = function (content) { this.genericLog(levels_1.Levels.error, content); }; - Logger.prototype.warn = function (content) { this.genericLog(levels_1.Levels.warn, content); }; - Logger.prototype.log = function (content) { this.genericLog(levels_1.Levels.log, content); }; - Logger.prototype.debug = function (content) { this.genericLog(levels_1.Levels.debug, content); }; - Logger.prototype.genericLog = function (level, content) { - this.logger.genericLog(level, this.category, this.label, content); - }; - return Logger; -}()); -exports.Logger = Logger; - - -/***/ }), -/* 64 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -tslib_1.__exportStar(__webpack_require__(65), exports); - - -/***/ }), -/* 65 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var transactions_1 = __webpack_require__(27); -var user_agents_1 = __webpack_require__(66); -var allowed_methods_1 = __webpack_require__(58); -/** - * This is ported from UA.C.ACCEPTED_BODY_TYPES. - * FIXME: TODO: Should be configurable/variable. - */ -var acceptedBodyTypes = [ - "application/sdp", - "application/dtmf-relay" -]; -/** - * User Agent Core. - * @remarks - * Core designates the functions specific to a particular type - * of SIP entity, i.e., specific to either a stateful or stateless - * proxy, a user agent or registrar. All cores, except those for - * the stateless proxy, are transaction users. - * https://tools.ietf.org/html/rfc3261#section-6 - * - * UAC Core: The set of processing functions required of a UAC that - * reside above the transaction and transport layers. - * https://tools.ietf.org/html/rfc3261#section-6 - * - * UAS Core: The set of processing functions required at a UAS that - * resides above the transaction and transport layers. - * https://tools.ietf.org/html/rfc3261#section-6 - * @public - */ -var UserAgentCore = /** @class */ (function () { - /** - * Constructor. - * @param configuration - Configuration. - * @param delegate - Delegate. - */ - function UserAgentCore(configuration, delegate) { - if (delegate === void 0) { delegate = {}; } - /** UACs. */ - this.userAgentClients = new Map(); - /** UASs. */ - this.userAgentServers = new Map(); - this.configuration = configuration; - this.delegate = delegate; - this.dialogs = new Map(); - this.subscribers = new Map(); - this.logger = configuration.loggerFactory.getLogger("sip.user-agent-core"); - } - /** Destructor. */ - UserAgentCore.prototype.dispose = function () { - this.reset(); - }; - /** Reset. */ - UserAgentCore.prototype.reset = function () { - this.dialogs.forEach(function (dialog) { return dialog.dispose(); }); - this.dialogs.clear(); - this.subscribers.forEach(function (subscriber) { return subscriber.dispose(); }); - this.subscribers.clear(); - this.userAgentClients.forEach(function (uac) { return uac.dispose(); }); - this.userAgentClients.clear(); - this.userAgentServers.forEach(function (uac) { return uac.dispose(); }); - this.userAgentServers.clear(); - }; - Object.defineProperty(UserAgentCore.prototype, "loggerFactory", { - /** Logger factory. */ - get: function () { - return this.configuration.loggerFactory; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(UserAgentCore.prototype, "transport", { - /** Transport. */ - get: function () { - var transport = this.configuration.transportAccessor(); - if (!transport) { - throw new Error("Transport undefined."); - } - return transport; - }, - enumerable: true, - configurable: true - }); - /** - * Send INVITE. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - UserAgentCore.prototype.invite = function (request, delegate) { - return new user_agents_1.InviteUserAgentClient(this, request, delegate); - }; - /** - * Send MESSAGE. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - UserAgentCore.prototype.message = function (request, delegate) { - return new user_agents_1.MessageUserAgentClient(this, request, delegate); - }; - /** - * Send PUBLISH. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - UserAgentCore.prototype.publish = function (request, delegate) { - return new user_agents_1.PublishUserAgentClient(this, request, delegate); - }; - /** - * Send REGISTER. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - UserAgentCore.prototype.register = function (request, delegate) { - return new user_agents_1.RegisterUserAgentClient(this, request, delegate); - }; - /** - * Send SUBSCRIBE. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - UserAgentCore.prototype.subscribe = function (request, delegate) { - return new user_agents_1.SubscribeUserAgentClient(this, request, delegate); - }; - /** - * Send a request. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - UserAgentCore.prototype.request = function (request, delegate) { - return new user_agents_1.UserAgentClient(transactions_1.NonInviteClientTransaction, this, request, delegate); - }; - /** - * Outgoing request message factory function. - * @param method - Method. - * @param requestURI - Request-URI. - * @param fromURI - From URI. - * @param toURI - To URI. - * @param options - Request options. - * @param extraHeaders - Extra headers to add. - * @param body - Message body. - */ - UserAgentCore.prototype.makeOutgoingRequestMessage = function (method, requestURI, fromURI, toURI, options, extraHeaders, body) { - // default values from user agent configuration - var callIdPrefix = this.configuration.sipjsId; - var fromDisplayName = this.configuration.displayName; - var forceRport = this.configuration.viaForceRport; - var hackViaTcp = this.configuration.hackViaTcp; - var optionTags = this.configuration.supportedOptionTags.slice(); - if (method === messages_1.C.REGISTER) { - optionTags.push("path", "gruu"); - } - if (method === messages_1.C.INVITE && (this.configuration.contact.pubGruu || this.configuration.contact.tempGruu)) { - optionTags.push("gruu"); - } - var routeSet = this.configuration.routeSet; - var userAgentString = this.configuration.userAgentHeaderFieldValue; - var viaHost = this.configuration.viaHost; - var defaultOptions = { - callIdPrefix: callIdPrefix, - forceRport: forceRport, - fromDisplayName: fromDisplayName, - hackViaTcp: hackViaTcp, - optionTags: optionTags, - routeSet: routeSet, - userAgentString: userAgentString, - viaHost: viaHost, - }; - // merge provided options with default options - var requestOptions = tslib_1.__assign({}, defaultOptions, options); - return new messages_1.OutgoingRequestMessage(method, requestURI, fromURI, toURI, requestOptions, extraHeaders, body); - }; - /** - * Handle an incoming request message from the transport. - * @param message - Incoming request message from transport layer. - */ - UserAgentCore.prototype.receiveIncomingRequestFromTransport = function (message) { - this.receiveRequestFromTransport(message); - }; - /** - * Handle an incoming response message from the transport. - * @param message - Incoming response message from transport layer. - */ - UserAgentCore.prototype.receiveIncomingResponseFromTransport = function (message) { - this.receiveResponseFromTransport(message); - }; - /** - * A stateless UAS is a UAS that does not maintain transaction state. - * It replies to requests normally, but discards any state that would - * ordinarily be retained by a UAS after a response has been sent. If a - * stateless UAS receives a retransmission of a request, it regenerates - * the response and re-sends it, just as if it were replying to the first - * instance of the request. A UAS cannot be stateless unless the request - * processing for that method would always result in the same response - * if the requests are identical. This rules out stateless registrars, - * for example. Stateless UASs do not use a transaction layer; they - * receive requests directly from the transport layer and send responses - * directly to the transport layer. - * https://tools.ietf.org/html/rfc3261#section-8.2.7 - * @param message - Incoming request message to reply to. - * @param statusCode - Status code to reply with. - */ - UserAgentCore.prototype.replyStateless = function (message, options) { - var userAgent = this.configuration.userAgentHeaderFieldValue; - var supported = this.configuration.supportedOptionTagsResponse; - options = tslib_1.__assign({}, options, { userAgent: userAgent, supported: supported }); - var response = messages_1.constructOutgoingResponse(message, options); - this.transport.send(response.message); - return response; - }; - /** - * In Section 18.2.1, replace the last paragraph with: - * - * Next, the server transport attempts to match the request to a - * server transaction. It does so using the matching rules described - * in Section 17.2.3. If a matching server transaction is found, the - * request is passed to that transaction for processing. If no match - * is found, the request is passed to the core, which may decide to - * construct a new server transaction for that request. - * https://tools.ietf.org/html/rfc6026#section-8.10 - * @param message - Incoming request message from transport layer. - */ - UserAgentCore.prototype.receiveRequestFromTransport = function (message) { - // When a request is received from the network by the server, it has to - // be matched to an existing transaction. This is accomplished in the - // following manner. - // - // The branch parameter in the topmost Via header field of the request - // is examined. If it is present and begins with the magic cookie - // "z9hG4bK", the request was generated by a client transaction - // compliant to this specification. Therefore, the branch parameter - // will be unique across all transactions sent by that client. The - // request matches a transaction if: - // - // 1. the branch parameter in the request is equal to the one in the - // top Via header field of the request that created the - // transaction, and - // - // 2. the sent-by value in the top Via of the request is equal to the - // one in the request that created the transaction, and - // - // 3. the method of the request matches the one that created the - // transaction, except for ACK, where the method of the request - // that created the transaction is INVITE. - // - // This matching rule applies to both INVITE and non-INVITE transactions - // alike. - // - // The sent-by value is used as part of the matching process because - // there could be accidental or malicious duplication of branch - // parameters from different clients. - // https://tools.ietf.org/html/rfc3261#section-17.2.3 - var transactionId = message.viaBranch; // FIXME: Currently only using rule 1... - var uas = this.userAgentServers.get(transactionId); - // When receiving an ACK that matches an existing INVITE server - // transaction and that does not contain a branch parameter containing - // the magic cookie defined in RFC 3261, the matching transaction MUST - // be checked to see if it is in the "Accepted" state. If it is, then - // the ACK must be passed directly to the transaction user instead of - // being absorbed by the transaction state machine. This is necessary - // as requests from RFC 2543 clients will not include a unique branch - // parameter, and the mechanisms for calculating the transaction ID from - // such a request will be the same for both INVITE and ACKs. - // https://tools.ietf.org/html/rfc6026#section-6 - // Any ACKs received from the network while in the "Accepted" state MUST be - // passed directly to the TU and not absorbed. - // https://tools.ietf.org/html/rfc6026#section-7.1 - if (message.method === messages_1.C.ACK) { - if (uas && uas.transaction.state === transactions_1.TransactionState.Accepted) { - if (uas instanceof user_agents_1.InviteUserAgentServer) { - // These are ACKs matching an INVITE server transaction. - // These should never happen with RFC 3261 compliant user agents - // (would be a broken ACK to negative final response or something) - // but is apparently how RFC 2543 user agents do things. - // We are not currently supporting this case. - // NOTE: Not backwards compatible with RFC 2543 (no support for strict-routing). - this.logger.warn("Discarding out of dialog ACK after 2xx response sent on transaction " + transactionId + "."); - return; - } - } - } - // The CANCEL method requests that the TU at the server side cancel a - // pending transaction. The TU determines the transaction to be - // cancelled by taking the CANCEL request, and then assuming that the - // request method is anything but CANCEL or ACK and applying the - // transaction matching procedures of Section 17.2.3. The matching - // transaction is the one to be cancelled. - // https://tools.ietf.org/html/rfc3261#section-9.2 - if (message.method === messages_1.C.CANCEL) { - if (uas) { - // Regardless of the method of the original request, as long as the - // CANCEL matched an existing transaction, the UAS answers the CANCEL - // request itself with a 200 (OK) response. - // https://tools.ietf.org/html/rfc3261#section-9.2 - this.replyStateless(message, { statusCode: 200 }); - // If the transaction for the original request still exists, the behavior - // of the UAS on receiving a CANCEL request depends on whether it has already - // sent a final response for the original request. If it has, the CANCEL - // request has no effect on the processing of the original request, no - // effect on any session state, and no effect on the responses generated - // for the original request. If the UAS has not issued a final response - // for the original request, its behavior depends on the method of the - // original request. If the original request was an INVITE, the UAS - // SHOULD immediately respond to the INVITE with a 487 (Request - // Terminated). - // https://tools.ietf.org/html/rfc3261#section-9.2 - if (uas.transaction instanceof transactions_1.InviteServerTransaction && - uas.transaction.state === transactions_1.TransactionState.Proceeding) { - if (uas instanceof user_agents_1.InviteUserAgentServer) { - uas.receiveCancel(message); - } - // A CANCEL request has no impact on the processing of - // transactions with any other method defined in this specification. - // https://tools.ietf.org/html/rfc3261#section-9.2 - } - } - else { - // If the UAS did not find a matching transaction for the CANCEL - // according to the procedure above, it SHOULD respond to the CANCEL - // with a 481 (Call Leg/Transaction Does Not Exist). - // https://tools.ietf.org/html/rfc3261#section-9.2 - this.replyStateless(message, { statusCode: 481 }); - } - return; - } - // If a matching server transaction is found, the request is passed to that - // transaction for processing. - // https://tools.ietf.org/html/rfc6026#section-8.10 - if (uas) { - uas.transaction.receiveRequest(message); - return; - } - // If no match is found, the request is passed to the core, which may decide to - // construct a new server transaction for that request. - // https://tools.ietf.org/html/rfc6026#section-8.10 - this.receiveRequest(message); - return; - }; - /** - * UAC and UAS procedures depend strongly on two factors. First, based - * on whether the request or response is inside or outside of a dialog, - * and second, based on the method of a request. Dialogs are discussed - * thoroughly in Section 12; they represent a peer-to-peer relationship - * between user agents and are established by specific SIP methods, such - * as INVITE. - * @param message - Incoming request message. - */ - UserAgentCore.prototype.receiveRequest = function (message) { - // 8.2 UAS Behavior - // UASs SHOULD process the requests in the order of the steps that - // follow in this section (that is, starting with authentication, then - // inspecting the method, the header fields, and so on throughout the - // remainder of this section). - // https://tools.ietf.org/html/rfc3261#section-8.2 - // 8.2.1 Method Inspection - // Once a request is authenticated (or authentication is skipped), the - // UAS MUST inspect the method of the request. If the UAS recognizes - // but does not support the method of a request, it MUST generate a 405 - // (Method Not Allowed) response. Procedures for generating responses - // are described in Section 8.2.6. The UAS MUST also add an Allow - // header field to the 405 (Method Not Allowed) response. The Allow - // header field MUST list the set of methods supported by the UAS - // generating the message. - // https://tools.ietf.org/html/rfc3261#section-8.2.1 - if (!allowed_methods_1.AllowedMethods.includes(message.method)) { - var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); - this.replyStateless(message, { - statusCode: 405, - extraHeaders: [allowHeader] - }); - return; - } - // 8.2.2 Header Inspection - // https://tools.ietf.org/html/rfc3261#section-8.2.2 - if (!message.ruri) { // FIXME: A request message should always have an ruri - throw new Error("Request-URI undefined."); - } - // 8.2.2.1 To and Request-URI - // If the Request-URI uses a scheme not supported by the UAS, it SHOULD - // reject the request with a 416 (Unsupported URI Scheme) response. - // https://tools.ietf.org/html/rfc3261#section-8.2.2.1 - if (message.ruri.scheme !== "sip") { - this.replyStateless(message, { statusCode: 416 }); - return; - } - // 8.2.2.1 To and Request-URI - // If the Request-URI does not identify an address that the - // UAS is willing to accept requests for, it SHOULD reject - // the request with a 404 (Not Found) response. - // https://tools.ietf.org/html/rfc3261#section-8.2.2.1 - var ruri = message.ruri; - var ruriMatches = function (uri) { - return !!uri && uri.user === ruri.user; - }; - if (!ruriMatches(this.configuration.aor) && - !(ruriMatches(this.configuration.contact.uri) || - ruriMatches(this.configuration.contact.pubGruu) || - ruriMatches(this.configuration.contact.tempGruu))) { - this.logger.warn("Request-URI does not point to us."); - if (message.method !== messages_1.C.ACK) { - this.replyStateless(message, { statusCode: 404 }); - } - return; - } - // 8.2.2.1 To and Request-URI - // Other potential sources of received Request-URIs include - // the Contact header fields of requests and responses sent by the UA - // that establish or refresh dialogs. - // https://tools.ietf.org/html/rfc3261#section-8.2.2.1 - if (message.method === messages_1.C.INVITE) { - if (!message.hasHeader("Contact")) { - this.replyStateless(message, { - statusCode: 400, - reasonPhrase: "Missing Contact Header" - }); - return; - } - } - // 8.2.2.2 Merged Requests - // If the request has no tag in the To header field, the UAS core MUST - // check the request against ongoing transactions. If the From tag, - // Call-ID, and CSeq exactly match those associated with an ongoing - // transaction, but the request does not match that transaction (based - // on the matching rules in Section 17.2.3), the UAS core SHOULD - // generate a 482 (Loop Detected) response and pass it to the server - // transaction. - // - // The same request has arrived at the UAS more than once, following - // different paths, most likely due to forking. The UAS processes - // the first such request received and responds with a 482 (Loop - // Detected) to the rest of them. - // https://tools.ietf.org/html/rfc3261#section-8.2.2.2 - if (!message.toTag) { - var transactionId = message.viaBranch; - if (!this.userAgentServers.has(transactionId)) { - var mergedRequest = Array.from(this.userAgentServers.values()) - .some(function (uas) { - return uas.transaction.request.fromTag === message.fromTag && - uas.transaction.request.callId === message.callId && - uas.transaction.request.cseq === message.cseq; - }); - if (mergedRequest) { - this.replyStateless(message, { statusCode: 482 }); - return; - } - } - } - // 8.2.2.3 Require - // https://tools.ietf.org/html/rfc3261#section-8.2.2.3 - // TODO - // 8.2.3 Content Processing - // https://tools.ietf.org/html/rfc3261#section-8.2.3 - // TODO - // 8.2.4 Applying Extensions - // https://tools.ietf.org/html/rfc3261#section-8.2.4 - // TODO - // 8.2.5 Processing the Request - // Assuming all of the checks in the previous subsections are passed, - // the UAS processing becomes method-specific. - // https://tools.ietf.org/html/rfc3261#section-8.2.5 - // The UAS will receive the request from the transaction layer. If the - // request has a tag in the To header field, the UAS core computes the - // dialog identifier corresponding to the request and compares it with - // existing dialogs. If there is a match, this is a mid-dialog request. - // In that case, the UAS first applies the same processing rules for - // requests outside of a dialog, discussed in Section 8.2. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (message.toTag) { - this.receiveInsideDialogRequest(message); - } - else { - this.receiveOutsideDialogRequest(message); - } - return; - }; - /** - * Once a dialog has been established between two UAs, either of them - * MAY initiate new transactions as needed within the dialog. The UA - * sending the request will take the UAC role for the transaction. The - * UA receiving the request will take the UAS role. Note that these may - * be different roles than the UAs held during the transaction that - * established the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.2 - * @param message - Incoming request message. - */ - UserAgentCore.prototype.receiveInsideDialogRequest = function (message) { - // NOTIFY requests are matched to such SUBSCRIBE requests if they - // contain the same "Call-ID", a "To" header field "tag" parameter that - // matches the "From" header field "tag" parameter of the SUBSCRIBE - // request, and the same "Event" header field. Rules for comparisons of - // the "Event" header fields are described in Section 8.2.1. - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - if (message.method === messages_1.C.NOTIFY) { - var event_1 = message.parseHeader("Event"); - if (!event_1 || !event_1.event) { - this.replyStateless(message, { statusCode: 489 }); - return; - } - // FIXME: Subscriber id should also matching on event id. - var subscriberId = message.callId + message.toTag + event_1.event; - var subscriber = this.subscribers.get(subscriberId); - if (subscriber) { - var uas = new user_agents_1.NotifyUserAgentServer(this, message); - subscriber.onNotify(uas); - return; - } - } - // Requests sent within a dialog, as any other requests, are atomic. If - // a particular request is accepted by the UAS, all the state changes - // associated with it are performed. If the request is rejected, none - // of the state changes are performed. - // - // Note that some requests, such as INVITEs, affect several pieces of - // state. - // - // The UAS will receive the request from the transaction layer. If the - // request has a tag in the To header field, the UAS core computes the - // dialog identifier corresponding to the request and compares it with - // existing dialogs. If there is a match, this is a mid-dialog request. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - var dialogId = message.callId + message.toTag + message.fromTag; - var dialog = this.dialogs.get(dialogId); - if (dialog) { - // [Sip-implementors] Reg. SIP reinvite, UPDATE and OPTIONS - // You got the question right. - // - // And you got the right answer too. :-) - // - // Thanks, - // Paul - // - // Robert Sparks wrote: - // > So I've lost track of the question during the musing. - // > - // > I _think_ the fundamental question being asked is this: - // > - // > Is an endpoint required to reject (with a 481) an OPTIONS request that - // > arrives with at to-tag but does not match any existing dialog state. - // > (Assuming some earlier requirement hasn't forced another error code). Or - // > is it OK if it just sends - // > a 200 OK anyhow. - // > - // > My take on the collection of specs is that its _not_ ok for it to send - // > the 200 OK anyhow and that it is required to send - // > the 481. I base this primarily on these sentences from 11.2 in 3261: - // > - // > The response to an OPTIONS is constructed using the standard rules - // > for a SIP response as discussed in Section 8.2.6. The response code - // > chosen MUST be the same that would have been chosen had the request - // > been an INVITE. - // > - // > Did I miss the point of the question? - // > - // > On May 15, 2008, at 12:48 PM, Paul Kyzivat wrote: - // > - // >> [Including Robert in hopes of getting his insight on this.] - // https://lists.cs.columbia.edu/pipermail/sip-implementors/2008-May/019178.html - // - // Requests that do not change in any way the state of a dialog may be - // received within a dialog (for example, an OPTIONS request). They are - // processed as if they had been received outside the dialog. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (message.method === messages_1.C.OPTIONS) { - var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); - var acceptHeader = "Accept: " + acceptedBodyTypes.toString(); - this.replyStateless(message, { - statusCode: 200, - extraHeaders: [allowHeader, acceptHeader] - }); - return; - } - // Pass the incoming request to the dialog for further handling. - dialog.receiveRequest(message); - return; - } - // The most important behaviors of a stateless UAS are the following: - // ... - // o A stateless UAS MUST ignore ACK requests. - // ... - // https://tools.ietf.org/html/rfc3261#section-8.2.7 - if (message.method === messages_1.C.ACK) { - // If a final response to an INVITE was sent statelessly, - // the corresponding ACK: - // - will not match an existing transaction - // - may have tag in the To header field - // - not not match any existing dialogs - // Absorb unmatched ACKs. - return; - } - // If the request has a tag in the To header field, but the dialog - // identifier does not match any existing dialogs, the UAS may have - // crashed and restarted, or it may have received a request for a - // different (possibly failed) UAS (the UASs can construct the To tags - // so that a UAS can identify that the tag was for a UAS for which it is - // providing recovery). Another possibility is that the incoming - // request has been simply mis-routed. Based on the To tag, the UAS MAY - // either accept or reject the request. Accepting the request for - // acceptable To tags provides robustness, so that dialogs can persist - // even through crashes. UAs wishing to support this capability must - // take into consideration some issues such as choosing monotonically - // increasing CSeq sequence numbers even across reboots, reconstructing - // the route set, and accepting out-of-range RTP timestamps and sequence - // numbers. - // - // If the UAS wishes to reject the request because it does not wish to - // recreate the dialog, it MUST respond to the request with a 481 - // (Call/Transaction Does Not Exist) status code and pass that to the - // server transaction. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - this.replyStateless(message, { statusCode: 481 }); - return; - }; - /** - * Assuming all of the checks in the previous subsections are passed, - * the UAS processing becomes method-specific. - * https://tools.ietf.org/html/rfc3261#section-8.2.5 - * @param message - Incoming request message. - */ - UserAgentCore.prototype.receiveOutsideDialogRequest = function (message) { - switch (message.method) { - case messages_1.C.ACK: - // Absorb stray out of dialog ACKs - break; - case messages_1.C.BYE: - // If the BYE does not match an existing dialog, the UAS core SHOULD - // generate a 481 (Call/Transaction Does Not Exist) response and pass - // that to the server transaction. This rule means that a BYE sent - // without tags by a UAC will be rejected. - // https://tools.ietf.org/html/rfc3261#section-15.1.2 - this.replyStateless(message, { statusCode: 481 }); - break; - case messages_1.C.CANCEL: - throw new Error("Unexpected out of dialog request method " + message.method + "."); - break; - case messages_1.C.INFO: - // Use of the INFO method does not constitute a separate dialog usage. - // INFO messages are always part of, and share the fate of, an invite - // dialog usage [RFC5057]. INFO messages cannot be sent as part of - // other dialog usages, or outside an existing dialog. - // https://tools.ietf.org/html/rfc6086#section-1 - this.replyStateless(message, { statusCode: 405 }); // Should never happen - break; - case messages_1.C.INVITE: - // https://tools.ietf.org/html/rfc3261#section-13.3.1 - { - var uas = new user_agents_1.InviteUserAgentServer(this, message); - this.delegate.onInvite ? - this.delegate.onInvite(uas) : - uas.reject(); - } - break; - case messages_1.C.MESSAGE: - // MESSAGE requests are discouraged inside a dialog. Implementations - // are restricted from creating a usage for the purpose of carrying a - // sequence of MESSAGE requests (though some implementations use it that - // way, against the standard recommendation). - // https://tools.ietf.org/html/rfc5057#section-5.3 - { - var uas = new user_agents_1.MessageUserAgentServer(this, message); - this.delegate.onMessage ? - this.delegate.onMessage(uas) : - uas.accept(); - } - break; - case messages_1.C.NOTIFY: - // Obsoleted by: RFC 6665 - // If any non-SUBSCRIBE mechanisms are defined to create subscriptions, - // it is the responsibility of the parties defining those mechanisms to - // ensure that correlation of a NOTIFY message to the corresponding - // subscription is possible. Designers of such mechanisms are also - // warned to make a distinction between sending a NOTIFY message to a - // subscriber who is aware of the subscription, and sending a NOTIFY - // message to an unsuspecting node. The latter behavior is invalid, and - // MUST receive a "481 Subscription does not exist" response (unless - // some other 400- or 500-class error code is more applicable), as - // described in section 3.2.4. In other words, knowledge of a - // subscription must exist in both the subscriber and the notifier to be - // valid, even if installed via a non-SUBSCRIBE mechanism. - // https://tools.ietf.org/html/rfc3265#section-3.2 - // - // NOTIFY requests are sent to inform subscribers of changes in state to - // which the subscriber has a subscription. Subscriptions are created - // using the SUBSCRIBE method. In legacy implementations, it is - // possible that other means of subscription creation have been used. - // However, this specification does not allow the creation of - // subscriptions except through SUBSCRIBE requests and (for backwards- - // compatibility) REFER requests [RFC3515]. - // https://tools.ietf.org/html/rfc6665#section-3.2 - { - var uas = new user_agents_1.NotifyUserAgentServer(this, message); - this.delegate.onNotify ? - this.delegate.onNotify(uas) : - uas.reject({ statusCode: 405 }); - } - break; - case messages_1.C.OPTIONS: - // https://tools.ietf.org/html/rfc3261#section-11.2 - { - var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); - var acceptHeader = "Accept: " + acceptedBodyTypes.toString(); - this.replyStateless(message, { - statusCode: 200, - extraHeaders: [allowHeader, acceptHeader] - }); - } - break; - case messages_1.C.REFER: - // https://tools.ietf.org/html/rfc3515#section-2.4.2 - { - var uas = new user_agents_1.ReferUserAgentServer(this, message); - this.delegate.onRefer ? - this.delegate.onRefer(uas) : - uas.reject({ statusCode: 405 }); - } - break; - case messages_1.C.REGISTER: - // https://tools.ietf.org/html/rfc3261#section-10.3 - { - var uas = new user_agents_1.RegisterUserAgentServer(this, message); - this.delegate.onRegister ? - this.delegate.onRegister(uas) : - uas.reject({ statusCode: 405 }); - } - break; - case messages_1.C.SUBSCRIBE: - // https://tools.ietf.org/html/rfc6665#section-4.2 - { - var uas = new user_agents_1.SubscribeUserAgentServer(this, message); - this.delegate.onSubscribe ? - this.delegate.onSubscribe(uas) : - uas.reject({ statusCode: 480 }); - } - break; - default: - throw new Error("Unexpected out of dialog request method " + message.method + "."); - } - return; - }; - /** - * Responses are first processed by the transport layer and then passed - * up to the transaction layer. The transaction layer performs its - * processing and then passes the response up to the TU. The majority - * of response processing in the TU is method specific. However, there - * are some general behaviors independent of the method. - * https://tools.ietf.org/html/rfc3261#section-8.1.3 - * @param message - Incoming response message from transport layer. - */ - UserAgentCore.prototype.receiveResponseFromTransport = function (message) { - // 8.1.3.1 Transaction Layer Errors - // https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - // Handled by transaction layer callbacks. - // 8.1.3.2 Unrecognized Responses - // https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - // TODO - // 8.1.3.3 Vias - // https://tools.ietf.org/html/rfc3261#section-8.1.3.3 - if (message.getHeaders("via").length > 1) { - this.logger.warn("More than one Via header field present in the response, dropping"); - return; - } - // 8.1.3.4 Processing 3xx Responses - // https://tools.ietf.org/html/rfc3261#section-8.1.3.4 - // TODO - // 8.1.3.5 Processing 4xx Responses - // https://tools.ietf.org/html/rfc3261#section-8.1.3.5 - // TODO - // When the transport layer in the client receives a response, it has to - // determine which client transaction will handle the response, so that - // the processing of Sections 17.1.1 and 17.1.2 can take place. The - // branch parameter in the top Via header field is used for this - // purpose. A response matches a client transaction under two - // conditions: - // - // 1. If the response has the same value of the branch parameter in - // the top Via header field as the branch parameter in the top - // Via header field of the request that created the transaction. - // - // 2. If the method parameter in the CSeq header field matches the - // method of the request that created the transaction. The - // method is needed since a CANCEL request constitutes a - // different transaction, but shares the same value of the branch - // parameter. - // https://tools.ietf.org/html/rfc3261#section-17.1.3 - var userAgentClientId = message.viaBranch + message.method; - var userAgentClient = this.userAgentClients.get(userAgentClientId); - // The client transport uses the matching procedures of Section - // 17.1.3 to attempt to match the response to an existing - // transaction. If there is a match, the response MUST be passed to - // that transaction. Otherwise, any element other than a stateless - // proxy MUST silently discard the response. - // https://tools.ietf.org/html/rfc6026#section-8.9 - if (userAgentClient) { - userAgentClient.transaction.receiveResponse(message); - } - else { - this.logger.warn("Discarding unmatched " + message.statusCode + " response to " + message.method + " " + userAgentClientId + "."); - } - }; - return UserAgentCore; -}()); -exports.UserAgentCore = UserAgentCore; - - -/***/ }), -/* 66 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -tslib_1.__exportStar(__webpack_require__(41), exports); -tslib_1.__exportStar(__webpack_require__(43), exports); -tslib_1.__exportStar(__webpack_require__(67), exports); -tslib_1.__exportStar(__webpack_require__(45), exports); -tslib_1.__exportStar(__webpack_require__(46), exports); -tslib_1.__exportStar(__webpack_require__(68), exports); -tslib_1.__exportStar(__webpack_require__(69), exports); -tslib_1.__exportStar(__webpack_require__(70), exports); -tslib_1.__exportStar(__webpack_require__(71), exports); -tslib_1.__exportStar(__webpack_require__(47), exports); -tslib_1.__exportStar(__webpack_require__(48), exports); -tslib_1.__exportStar(__webpack_require__(72), exports); -tslib_1.__exportStar(__webpack_require__(49), exports); -tslib_1.__exportStar(__webpack_require__(50), exports); -tslib_1.__exportStar(__webpack_require__(51), exports); -tslib_1.__exportStar(__webpack_require__(52), exports); -tslib_1.__exportStar(__webpack_require__(59), exports); -tslib_1.__exportStar(__webpack_require__(73), exports); -tslib_1.__exportStar(__webpack_require__(53), exports); -tslib_1.__exportStar(__webpack_require__(54), exports); -tslib_1.__exportStar(__webpack_require__(74), exports); -tslib_1.__exportStar(__webpack_require__(75), exports); -tslib_1.__exportStar(__webpack_require__(76), exports); -tslib_1.__exportStar(__webpack_require__(77), exports); -tslib_1.__exportStar(__webpack_require__(42), exports); -tslib_1.__exportStar(__webpack_require__(44), exports); - - -/***/ }), -/* 67 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * CANCEL UAC. - * @public - */ -var CancelUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(CancelUserAgentClient, _super); - function CancelUserAgentClient(core, message, delegate) { - return _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; - } - return CancelUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.CancelUserAgentClient = CancelUserAgentClient; - - -/***/ }), -/* 68 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var dialogs_1 = __webpack_require__(3); -var session_1 = __webpack_require__(24); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * INVITE UAC. - * @remarks - * 13 Initiating a Session - * https://tools.ietf.org/html/rfc3261#section-13 - * 13.1 Overview - * https://tools.ietf.org/html/rfc3261#section-13.1 - * 13.2 UAC Processing - * https://tools.ietf.org/html/rfc3261#section-13.2 - * @public - */ -var InviteUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(InviteUserAgentClient, _super); - function InviteUserAgentClient(core, message, delegate) { - var _this = _super.call(this, transactions_1.InviteClientTransaction, core, message, delegate) || this; - _this.confirmedDialogAcks = new Map(); - _this.confirmedDialogs = new Map(); - _this.earlyDialogs = new Map(); - _this.delegate = delegate; - return _this; - } - InviteUserAgentClient.prototype.dispose = function () { - // The UAC core considers the INVITE transaction completed 64*T1 seconds - // after the reception of the first 2xx response. At this point all the - // early dialogs that have not transitioned to established dialogs are - // terminated. Once the INVITE transaction is considered completed by - // the UAC core, no more new 2xx responses are expected to arrive. - // - // If, after acknowledging any 2xx response to an INVITE, the UAC does - // not want to continue with that dialog, then the UAC MUST terminate - // the dialog by sending a BYE request as described in Section 15. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - this.earlyDialogs.forEach(function (earlyDialog) { return earlyDialog.dispose(); }); - this.earlyDialogs.clear(); - _super.prototype.dispose.call(this); - }; - /** - * Once the INVITE has been passed to the INVITE client transaction, the - * UAC waits for responses for the INVITE. - * https://tools.ietf.org/html/rfc3261#section-13.2.2 - * @param incomingResponse - Incoming response to INVITE request. - */ - InviteUserAgentClient.prototype.receiveResponse = function (message) { - var _this = this; - if (!this.authenticationGuard(message)) { - return; - } - var statusCode = message.statusCode ? message.statusCode.toString() : ""; - if (!statusCode) { - throw new Error("Response status code undefined."); - } - switch (true) { - case /^100$/.test(statusCode): - if (this.delegate && this.delegate.onTrying) { - this.delegate.onTrying({ message: message }); - } - return; - case /^1[0-9]{2}$/.test(statusCode): - // Zero, one or multiple provisional responses may arrive before one or - // more final responses are received. Provisional responses for an - // INVITE request can create "early dialogs". If a provisional response - // has a tag in the To field, and if the dialog ID of the response does - // not match an existing dialog, one is constructed using the procedures - // defined in Section 12.1.2. - // - // The early dialog will only be needed if the UAC needs to send a - // request to its peer within the dialog before the initial INVITE - // transaction completes. Header fields present in a provisional - // response are applicable as long as the dialog is in the early state - // (for example, an Allow header field in a provisional response - // contains the methods that can be used in the dialog while this is in - // the early state). - // https://tools.ietf.org/html/rfc3261#section-13.2.2.1 - { - // Provisional without to tag, no dialog to create. - if (!message.toTag) { - this.logger.warn("Non-100 1xx INVITE response received without a to tag, dropping."); - return; - } - // Compute dialog state. - var dialogState = dialogs_1.Dialog.initialDialogStateForUserAgentClient(this.message, message); - // Have existing early dialog or create a new one. - var earlyDialog = this.earlyDialogs.get(dialogState.id); - if (!earlyDialog) { - var transaction = this.transaction; - if (!(transaction instanceof transactions_1.InviteClientTransaction)) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - earlyDialog = new dialogs_1.SessionDialog(transaction, this.core, dialogState); - this.earlyDialogs.set(earlyDialog.id, earlyDialog); - } - // Guard against out of order reliable provisional responses. - // Note that this is where the rseq tracking is done. - if (!earlyDialog.reliableSequenceGuard(message)) { - this.logger.warn("1xx INVITE reliable response received out of order, dropping."); - return; - } - // If the initial offer is in an INVITE, the answer MUST be in a - // reliable non-failure message from UAS back to UAC which is - // correlated to that INVITE. For this specification, that is - // only the final 2xx response to that INVITE. That same exact - // answer MAY also be placed in any provisional responses sent - // prior to the answer. The UAC MUST treat the first session - // description it receives as the answer, and MUST ignore any - // session descriptions in subsequent responses to the initial - // INVITE. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - if (earlyDialog.signalingState === session_1.SignalingState.Initial || - earlyDialog.signalingState === session_1.SignalingState.HaveLocalOffer) { - earlyDialog.signalingStateTransition(message); - } - // Pass response to delegate. - var session_2 = earlyDialog; - if (this.delegate && this.delegate.onProgress) { - this.delegate.onProgress({ - message: message, - session: session_2, - prack: function (options) { - var outgoingPrackRequest = session_2.prack(undefined, options); - return outgoingPrackRequest; - } - }); - } - } - return; - case /^2[0-9]{2}$/.test(statusCode): - // Multiple 2xx responses may arrive at the UAC for a single INVITE - // request due to a forking proxy. Each response is distinguished by - // the tag parameter in the To header field, and each represents a - // distinct dialog, with a distinct dialog identifier. - // - // If the dialog identifier in the 2xx response matches the dialog - // identifier of an existing dialog, the dialog MUST be transitioned to - // the "confirmed" state, and the route set for the dialog MUST be - // recomputed based on the 2xx response using the procedures of Section - // 12.2.1.2. Otherwise, a new dialog in the "confirmed" state MUST be - // constructed using the procedures of Section 12.1.2. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - { - // Compute dialog state. - var dialogState = dialogs_1.Dialog.initialDialogStateForUserAgentClient(this.message, message); - // NOTE: Currently our transaction layer is caching the 2xx ACKs and - // handling retransmissions of the ACK which is an approach which is - // not to spec. In any event, this block is intended to provide a to - // spec implementation of ACK retransmissions, but it should not be - // hit currently. - var dialog = this.confirmedDialogs.get(dialogState.id); - if (dialog) { - // Once the ACK has been constructed, the procedures of [4] are used to - // determine the destination address, port and transport. However, the - // request is passed to the transport layer directly for transmission, - // rather than a client transaction. This is because the UAC core - // handles retransmissions of the ACK, not the transaction layer. The - // ACK MUST be passed to the client transport every time a - // retransmission of the 2xx final response that triggered the ACK - // arrives. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - var outgoingAckRequest = this.confirmedDialogAcks.get(dialogState.id); - if (outgoingAckRequest) { - var transaction = this.transaction; - if (!(transaction instanceof transactions_1.InviteClientTransaction)) { - throw new Error("Client transaction not instance of InviteClientTransaction."); - } - transaction.ackResponse(outgoingAckRequest.message); - } - else { - // If still waiting for an ACK, drop the retransmission of the 2xx final response. - } - return; - } - // If the dialog identifier in the 2xx response matches the dialog - // identifier of an existing dialog, the dialog MUST be transitioned to - // the "confirmed" state, and the route set for the dialog MUST be - // recomputed based on the 2xx response using the procedures of Section - // 12.2.1.2. Otherwise, a new dialog in the "confirmed" state MUST be - // constructed using the procedures of Section 12.1.2. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - dialog = this.earlyDialogs.get(dialogState.id); - if (dialog) { - dialog.confirm(); - dialog.recomputeRouteSet(message); - this.earlyDialogs.delete(dialog.id); - this.confirmedDialogs.set(dialog.id, dialog); - } - else { - var transaction = this.transaction; - if (!(transaction instanceof transactions_1.InviteClientTransaction)) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - dialog = new dialogs_1.SessionDialog(transaction, this.core, dialogState); - this.confirmedDialogs.set(dialog.id, dialog); - } - // If the initial offer is in an INVITE, the answer MUST be in a - // reliable non-failure message from UAS back to UAC which is - // correlated to that INVITE. For this specification, that is - // only the final 2xx response to that INVITE. That same exact - // answer MAY also be placed in any provisional responses sent - // prior to the answer. The UAC MUST treat the first session - // description it receives as the answer, and MUST ignore any - // session descriptions in subsequent responses to the initial - // INVITE. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - if (dialog.signalingState === session_1.SignalingState.Initial || - dialog.signalingState === session_1.SignalingState.HaveLocalOffer) { - dialog.signalingStateTransition(message); - } - // Session Initiated! :) - var session_3 = dialog; - // The UAC core MUST generate an ACK request for each 2xx received from - // the transaction layer. The header fields of the ACK are constructed - // in the same way as for any request sent within a dialog (see Section - // 12) with the exception of the CSeq and the header fields related to - // authentication. The sequence number of the CSeq header field MUST be - // the same as the INVITE being acknowledged, but the CSeq method MUST - // be ACK. The ACK MUST contain the same credentials as the INVITE. If - // the 2xx contains an offer (based on the rules above), the ACK MUST - // carry an answer in its body. If the offer in the 2xx response is not - // acceptable, the UAC core MUST generate a valid answer in the ACK and - // then send a BYE immediately. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - if (this.delegate && this.delegate.onAccept) { - this.delegate.onAccept({ - message: message, - session: session_3, - ack: function (options) { - var outgoingAckRequest = session_3.ack(options); - _this.confirmedDialogAcks.set(session_3.id, outgoingAckRequest); - return outgoingAckRequest; - } - }); - } - else { - var outgoingAckRequest = session_3.ack(); - this.confirmedDialogAcks.set(session_3.id, outgoingAckRequest); - } - } - return; - case /^3[0-9]{2}$/.test(statusCode): - // 12.3 Termination of a Dialog - // - // Independent of the method, if a request outside of a dialog generates - // a non-2xx final response, any early dialogs created through - // provisional responses to that request are terminated. The mechanism - // for terminating confirmed dialogs is method specific. In this - // specification, the BYE method terminates a session and the dialog - // associated with it. See Section 15 for details. - // https://tools.ietf.org/html/rfc3261#section-12.3 - // All early dialogs are considered terminated upon reception of the - // non-2xx final response. - // - // After having received the non-2xx final response the UAC core - // considers the INVITE transaction completed. The INVITE client - // transaction handles the generation of ACKs for the response (see - // Section 17). - // https://tools.ietf.org/html/rfc3261#section-13.2.2.3 - this.earlyDialogs.forEach(function (earlyDialog) { return earlyDialog.dispose(); }); - this.earlyDialogs.clear(); - // A 3xx response may contain one or more Contact header field values - // providing new addresses where the callee might be reachable. - // Depending on the status code of the 3xx response (see Section 21.3), - // the UAC MAY choose to try those new addresses. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.2 - if (this.delegate && this.delegate.onRedirect) { - this.delegate.onRedirect({ message: message }); - } - return; - case /^[4-6][0-9]{2}$/.test(statusCode): - // 12.3 Termination of a Dialog - // - // Independent of the method, if a request outside of a dialog generates - // a non-2xx final response, any early dialogs created through - // provisional responses to that request are terminated. The mechanism - // for terminating confirmed dialogs is method specific. In this - // specification, the BYE method terminates a session and the dialog - // associated with it. See Section 15 for details. - // https://tools.ietf.org/html/rfc3261#section-12.3 - // All early dialogs are considered terminated upon reception of the - // non-2xx final response. - // - // After having received the non-2xx final response the UAC core - // considers the INVITE transaction completed. The INVITE client - // transaction handles the generation of ACKs for the response (see - // Section 17). - // https://tools.ietf.org/html/rfc3261#section-13.2.2.3 - this.earlyDialogs.forEach(function (earlyDialog) { return earlyDialog.dispose(); }); - this.earlyDialogs.clear(); - // A single non-2xx final response may be received for the INVITE. 4xx, - // 5xx and 6xx responses may contain a Contact header field value - // indicating the location where additional information about the error - // can be found. Subsequent final responses (which would only arrive - // under error conditions) MUST be ignored. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.3 - if (this.delegate && this.delegate.onReject) { - this.delegate.onReject({ message: message }); - } - return; - default: - throw new Error("Invalid status code " + statusCode); - } - throw new Error("Executing what should be an unreachable code path receiving " + statusCode + " response."); - }; - return InviteUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.InviteUserAgentClient = InviteUserAgentClient; - - -/***/ }), -/* 69 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var dialogs_1 = __webpack_require__(3); -var exceptions_1 = __webpack_require__(31); -var session_1 = __webpack_require__(24); -var transactions_1 = __webpack_require__(27); -var allowed_methods_1 = __webpack_require__(58); -var user_agent_server_1 = __webpack_require__(44); -/** - * INVITE UAS. - * @remarks - * 13 Initiating a Session - * https://tools.ietf.org/html/rfc3261#section-13 - * 13.1 Overview - * https://tools.ietf.org/html/rfc3261#section-13.1 - * 13.3 UAS Processing - * https://tools.ietf.org/html/rfc3261#section-13.3 - * @public - */ -var InviteUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(InviteUserAgentServer, _super); - function InviteUserAgentServer(core, message, delegate) { - var _this = _super.call(this, transactions_1.InviteServerTransaction, core, message, delegate) || this; - _this.core = core; - return _this; - } - InviteUserAgentServer.prototype.dispose = function () { - if (this.earlyDialog) { - this.earlyDialog.dispose(); - } - _super.prototype.dispose.call(this); - }; - /** - * 13.3.1.4 The INVITE is Accepted - * The UAS core generates a 2xx response. This response establishes a - * dialog, and therefore follows the procedures of Section 12.1.1 in - * addition to those of Section 8.2.6. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - * @param options - Accept options bucket. - */ - InviteUserAgentServer.prototype.accept = function (options) { - if (options === void 0) { options = { statusCode: 200 }; } - if (!this.acceptable) { - throw new exceptions_1.TransactionStateError(this.message.method + " not acceptable in state " + this.transaction.state + "."); - } - // This response establishes a dialog... - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - if (!this.confirmedDialog) { - if (this.earlyDialog) { - this.earlyDialog.confirm(); - this.confirmedDialog = this.earlyDialog; - this.earlyDialog = undefined; - } - else { - var transaction = this.transaction; - if (!(transaction instanceof transactions_1.InviteServerTransaction)) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - var state = dialogs_1.Dialog.initialDialogStateForUserAgentServer(this.message, this.toTag); - this.confirmedDialog = new dialogs_1.SessionDialog(transaction, this.core, state); - } - } - // When a UAS responds to a request with a response that establishes a - // dialog (such as a 2xx to INVITE), the UAS MUST copy all Record-Route - // header field values from the request into the response (including the - // URIs, URI parameters, and any Record-Route header field parameters, - // whether they are known or unknown to the UAS) and MUST maintain the - // order of those values. The UAS MUST add a Contact header field to - // the response. The Contact header field contains an address where the - // UAS would like to be contacted for subsequent requests in the dialog - // (which includes the ACK for a 2xx response in the case of an INVITE). - // Generally, the host portion of this URI is the IP address or FQDN of - // the host. The URI provided in the Contact header field MUST be a SIP - // or SIPS URI. If the request that initiated the dialog contained a - // SIPS URI in the Request-URI or in the top Record-Route header field - // value, if there was any, or the Contact header field if there was no - // Record-Route header field, the Contact header field in the response - // MUST be a SIPS URI. The URI SHOULD have global scope (that is, the - // same URI can be used in messages outside this dialog). The same way, - // the scope of the URI in the Contact header field of the INVITE is not - // limited to this dialog either. It can therefore be used in messages - // to the UAC even outside this dialog. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - var recordRouteHeader = this.message - .getHeaders("record-route") - .map(function (header) { return "Record-Route: " + header; }); - var contactHeader = "Contact: " + this.core.configuration.contact.toString(); - // A 2xx response to an INVITE SHOULD contain the Allow header field and - // the Supported header field, and MAY contain the Accept header field. - // Including these header fields allows the UAC to determine the - // features and extensions supported by the UAS for the duration of the - // call, without probing. - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - // FIXME: TODO: This should not be hard coded. - var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); - // FIXME: TODO: Supported header (see reply()) - // FIXME: TODO: Accept header - // If the INVITE request contained an offer, and the UAS had not yet - // sent an answer, the 2xx MUST contain an answer. If the INVITE did - // not contain an offer, the 2xx MUST contain an offer if the UAS had - // not yet sent an offer. - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - if (!options.body) { - if (this.confirmedDialog.signalingState === session_1.SignalingState.Stable) { - options.body = this.confirmedDialog.answer; // resend the answer sent in provisional response - } - else if (this.confirmedDialog.signalingState === session_1.SignalingState.Initial || - this.confirmedDialog.signalingState === session_1.SignalingState.HaveRemoteOffer) { - throw new Error("Response must have a body."); - } - } - options.statusCode = options.statusCode || 200; - options.extraHeaders = options.extraHeaders || []; - options.extraHeaders = options.extraHeaders.concat(recordRouteHeader); - options.extraHeaders.push(allowHeader); - options.extraHeaders.push(contactHeader); - var response = _super.prototype.accept.call(this, options); - var session = this.confirmedDialog; - var result = tslib_1.__assign({}, response, { session: session }); - // Update dialog signaling state - if (options.body) { - // Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - if (this.confirmedDialog.signalingState !== session_1.SignalingState.Stable) { - this.confirmedDialog.signalingStateTransition(options.body); - } - } - return result; - }; - /** - * 13.3.1.1 Progress - * If the UAS is not able to answer the invitation immediately, it can - * choose to indicate some kind of progress to the UAC (for example, an - * indication that a phone is ringing). This is accomplished with a - * provisional response between 101 and 199. These provisional - * responses establish early dialogs and therefore follow the procedures - * of Section 12.1.1 in addition to those of Section 8.2.6. A UAS MAY - * send as many provisional responses as it likes. Each of these MUST - * indicate the same dialog ID. However, these will not be delivered - * reliably. - * - * If the UAS desires an extended period of time to answer the INVITE, - * it will need to ask for an "extension" in order to prevent proxies - * from canceling the transaction. A proxy has the option of canceling - * a transaction when there is a gap of 3 minutes between responses in a - * transaction. To prevent cancellation, the UAS MUST send a non-100 - * provisional response at every minute, to handle the possibility of - * lost provisional responses. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.1 - * @param options - Progress options bucket. - */ - InviteUserAgentServer.prototype.progress = function (options) { - if (options === void 0) { options = { statusCode: 180 }; } - if (!this.progressable) { - throw new exceptions_1.TransactionStateError(this.message.method + " not progressable in state " + this.transaction.state + "."); - } - // This response establishes a dialog... - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - if (!this.earlyDialog) { - var transaction = this.transaction; - if (!(transaction instanceof transactions_1.InviteServerTransaction)) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - var state = dialogs_1.Dialog.initialDialogStateForUserAgentServer(this.message, this.toTag, true); - this.earlyDialog = new dialogs_1.SessionDialog(transaction, this.core, state); - } - // When a UAS responds to a request with a response that establishes a - // dialog (such as a 2xx to INVITE), the UAS MUST copy all Record-Route - // header field values from the request into the response (including the - // URIs, URI parameters, and any Record-Route header field parameters, - // whether they are known or unknown to the UAS) and MUST maintain the - // order of those values. The UAS MUST add a Contact header field to - // the response. The Contact header field contains an address where the - // UAS would like to be contacted for subsequent requests in the dialog - // (which includes the ACK for a 2xx response in the case of an INVITE). - // Generally, the host portion of this URI is the IP address or FQDN of - // the host. The URI provided in the Contact header field MUST be a SIP - // or SIPS URI. If the request that initiated the dialog contained a - // SIPS URI in the Request-URI or in the top Record-Route header field - // value, if there was any, or the Contact header field if there was no - // Record-Route header field, the Contact header field in the response - // MUST be a SIPS URI. The URI SHOULD have global scope (that is, the - // same URI can be used in messages outside this dialog). The same way, - // the scope of the URI in the Contact header field of the INVITE is not - // limited to this dialog either. It can therefore be used in messages - // to the UAC even outside this dialog. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - var recordRouteHeader = this.message - .getHeaders("record-route") - .map(function (header) { return "Record-Route: " + header; }); - var contactHeader = "Contact: " + this.core.configuration.contact; - options.extraHeaders = options.extraHeaders || []; - options.extraHeaders = options.extraHeaders.concat(recordRouteHeader); - options.extraHeaders.push(contactHeader); - var response = _super.prototype.progress.call(this, options); - var session = this.earlyDialog; - var result = tslib_1.__assign({}, response, { session: session }); - // Update dialog signaling state - if (options.body) { - // Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - if (this.earlyDialog.signalingState !== session_1.SignalingState.Stable) { - this.earlyDialog.signalingStateTransition(options.body); - } - } - return result; - }; - /** - * 13.3.1.2 The INVITE is Redirected - * If the UAS decides to redirect the call, a 3xx response is sent. A - * 300 (Multiple Choices), 301 (Moved Permanently) or 302 (Moved - * Temporarily) response SHOULD contain a Contact header field - * containing one or more URIs of new addresses to be tried. The - * response is passed to the INVITE server transaction, which will deal - * with its retransmissions. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.2 - * @param contacts - Contacts to redirect to. - * @param options - Redirect options bucket. - */ - InviteUserAgentServer.prototype.redirect = function (contacts, options) { - if (options === void 0) { options = { statusCode: 302 }; } - return _super.prototype.redirect.call(this, contacts, options); - }; - /** - * 13.3.1.3 The INVITE is Rejected - * A common scenario occurs when the callee is currently not willing or - * able to take additional calls at this end system. A 486 (Busy Here) - * SHOULD be returned in such a scenario. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.3 - * @param options - Reject options bucket. - */ - InviteUserAgentServer.prototype.reject = function (options) { - if (options === void 0) { options = { statusCode: 486 }; } - return _super.prototype.reject.call(this, options); - }; - return InviteUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.InviteUserAgentServer = InviteUserAgentServer; - - -/***/ }), -/* 70 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * MESSAGE UAS. - * @public - */ -var MessageUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(MessageUserAgentClient, _super); - function MessageUserAgentClient(core, message, delegate) { - return _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; - } - return MessageUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.MessageUserAgentClient = MessageUserAgentClient; - - -/***/ }), -/* 71 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * MESSAGE UAS. - * @public - */ -var MessageUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(MessageUserAgentServer, _super); - function MessageUserAgentServer(core, message, delegate) { - var _this = _super.call(this, transactions_1.NonInviteServerTransaction, core, message, delegate) || this; - _this.core = core; - return _this; - } - return MessageUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.MessageUserAgentServer = MessageUserAgentServer; - - -/***/ }), -/* 72 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * PUBLISH UAC. - * @public - */ -var PublishUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(PublishUserAgentClient, _super); - function PublishUserAgentClient(core, message, delegate) { - return _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; - } - return PublishUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.PublishUserAgentClient = PublishUserAgentClient; - - -/***/ }), -/* 73 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * Re-SUBSCRIBE UAS. - * @public - */ -var ReSubscribeUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(ReSubscribeUserAgentServer, _super); - function ReSubscribeUserAgentServer(dialog, message, delegate) { - return _super.call(this, transactions_1.NonInviteServerTransaction, dialog.userAgentCore, message, delegate) || this; - } - return ReSubscribeUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.ReSubscribeUserAgentServer = ReSubscribeUserAgentServer; - - -/***/ }), -/* 74 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * REGISTER UAC. - * @public - */ -var RegisterUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(RegisterUserAgentClient, _super); - function RegisterUserAgentClient(core, message, delegate) { - return _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; - } - return RegisterUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.RegisterUserAgentClient = RegisterUserAgentClient; - - -/***/ }), -/* 75 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * REGISTER UAS. - * @public - */ -var RegisterUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(RegisterUserAgentServer, _super); - function RegisterUserAgentServer(core, message, delegate) { - var _this = _super.call(this, transactions_1.NonInviteServerTransaction, core, message, delegate) || this; - _this.core = core; - return _this; - } - return RegisterUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.RegisterUserAgentServer = RegisterUserAgentServer; - - -/***/ }), -/* 76 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var subscription_dialog_1 = __webpack_require__(55); -var subscription_1 = __webpack_require__(56); -var timers_1 = __webpack_require__(26); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * SUBSCRIBE UAC. - * @remarks - * 4.1. Subscriber Behavior - * https://tools.ietf.org/html/rfc6665#section-4.1 - * - * User agent client for installation of a single subscription per SUBSCRIBE request. - * TODO: Support for installation of multiple subscriptions on forked SUBSCRIBE reqeuests. - * @public - */ -var SubscribeUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(SubscribeUserAgentClient, _super); - function SubscribeUserAgentClient(core, message, delegate) { - var _this = this; - // Get event from request message. - var event = message.getHeader("Event"); - if (!event) { - throw new Error("Event undefined"); - } - // Get expires from reqeust message. - var expires = message.getHeader("Expires"); - if (!expires) { - throw new Error("Expires undefined"); - } - _this = _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; - _this.delegate = delegate; - // FIXME: Subscriber id should also be matching on event id. - _this.subscriberId = message.callId + message.fromTag + event; - _this.subscriptionExpiresRequested = _this.subscriptionExpires = Number(expires); - _this.subscriptionEvent = event; - _this.subscriptionState = subscription_1.SubscriptionState.NotifyWait; - // Start waiting for a NOTIFY we can use to create a subscription. - _this.waitNotifyStart(); - return _this; - } - /** - * Destructor. - * Note that Timer N may live on waiting for an initial NOTIFY and - * the delegate may still receive that NOTIFY. If you don't want - * that behavior then either clear the delegate so the delegate - * doesn't get called (a 200 will be sent in response to the NOTIFY) - * or call `waitNotifyStop` which will clear Timer N and remove this - * UAC from the core (a 481 will be sent in response to the NOTIFY). - */ - SubscribeUserAgentClient.prototype.dispose = function () { - _super.prototype.dispose.call(this); - }; - /** - * Handle out of dialog NOTIFY assoicated with SUBSCRIBE request. - * This is the first NOTIFY received after the SUBSCRIBE request. - * @param uas - User agent server handling the subscription creating NOTIFY. - */ - SubscribeUserAgentClient.prototype.onNotify = function (uas) { - // NOTIFY requests are matched to such SUBSCRIBE requests if they - // contain the same "Call-ID", a "To" header field "tag" parameter that - // matches the "From" header field "tag" parameter of the SUBSCRIBE - // request, and the same "Event" header field. Rules for comparisons of - // the "Event" header fields are described in Section 8.2.1. - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - var event = uas.message.parseHeader("Event").event; - if (!event || event !== this.subscriptionEvent) { - this.logger.warn("Failed to parse event."); - uas.reject({ statusCode: 489 }); - return; - } - // NOTIFY requests MUST contain "Subscription-State" header fields that - // indicate the status of the subscription. - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - var subscriptionState = uas.message.parseHeader("Subscription-State"); - if (!subscriptionState || !subscriptionState.state) { - this.logger.warn("Failed to parse subscription state."); - uas.reject({ statusCode: 489 }); - return; - } - // Validate subscription state. - var state = subscriptionState.state; - switch (state) { - case "pending": - break; - case "active": - break; - case "terminated": - break; - default: - this.logger.warn("Invalid subscription state " + state); - uas.reject({ statusCode: 489 }); - return; - } - // Dialogs usages are created upon completion of a NOTIFY transaction - // for a new subscription, unless the NOTIFY request contains a - // "Subscription-State" of "terminated." - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - if (state !== "terminated") { - // The Contact header field MUST be present and contain exactly one SIP - // or SIPS URI in any request that can result in the establishment of a - // dialog. - // https://tools.ietf.org/html/rfc3261#section-8.1.1.8 - var contact = uas.message.parseHeader("contact"); - if (!contact) { - this.logger.warn("Failed to parse contact."); - uas.reject({ statusCode: 489 }); - return; - } - } - // In accordance with the rules for proxying non-INVITE requests as - // defined in [RFC3261], successful SUBSCRIBE requests will receive only - // one 200-class response; however, due to forking, the subscription may - // have been accepted by multiple nodes. The subscriber MUST therefore - // be prepared to receive NOTIFY requests with "From:" tags that differ - // from the "To:" tag received in the SUBSCRIBE 200-class response. - // - // If multiple NOTIFY requests are received in different dialogs in - // response to a single SUBSCRIBE request, each dialog represents a - // different destination to which the SUBSCRIBE request was forked. - // Subscriber handling in such situations varies by event package; see - // Section 5.4.9 for details. - // https://tools.ietf.org/html/rfc6665#section-4.1.4 - // Each event package MUST specify whether forked SUBSCRIBE requests are - // allowed to install multiple subscriptions. - // - // If such behavior is not allowed, the first potential dialog- - // establishing message will create a dialog. All subsequent NOTIFY - // requests that correspond to the SUBSCRIBE request (i.e., have - // matching "To", "From", "Call-ID", and "Event" header fields, as well - // as "From" header field "tag" parameter and "Event" header field "id" - // parameter) but that do not match the dialog would be rejected with a - // 481 response. Note that the 200-class response to the SUBSCRIBE - // request can arrive after a matching NOTIFY request has been received; - // such responses might not correlate to the same dialog established by - // the NOTIFY request. Except as required to complete the SUBSCRIBE - // transaction, such non-matching 200-class responses are ignored. - // - // If installing of multiple subscriptions by way of a single forked - // SUBSCRIBE request is allowed, the subscriber establishes a new dialog - // towards each notifier by returning a 200-class response to each - // NOTIFY request. Each dialog is then handled as its own entity and is - // refreshed independently of the other dialogs. - // - // In the case that multiple subscriptions are allowed, the event - // package MUST specify whether merging of the notifications to form a - // single state is required, and how such merging is to be performed. - // Note that it is possible that some event packages may be defined in - // such a way that each dialog is tied to a mutually exclusive state - // that is unaffected by the other dialogs; this MUST be clearly stated - // if it is the case. - // https://tools.ietf.org/html/rfc6665#section-5.4.9 - // *** NOTE: This implementation is only for event packages which - // do not allow forked requests to install muliple subscriptions. - // As such and in accordance with the specificaiton, we stop waiting - // and any future NOTIFY requests will be rejected with a 481. - if (this.dialog) { - throw new Error("Dialog already created. This implementation only supports install of single subscriptions."); - } - this.waitNotifyStop(); - // Update expires. - this.subscriptionExpires = - subscriptionState.expires ? - Math.min(this.subscriptionExpires, Math.max(subscriptionState.expires, 0)) : - this.subscriptionExpires; - // Update subscriptoin state. - switch (state) { - case "pending": - this.subscriptionState = subscription_1.SubscriptionState.Pending; - break; - case "active": - this.subscriptionState = subscription_1.SubscriptionState.Active; - break; - case "terminated": - this.subscriptionState = subscription_1.SubscriptionState.Terminated; - break; - default: - throw new Error("Unrecognized state " + state + "."); - } - // Dialogs usages are created upon completion of a NOTIFY transaction - // for a new subscription, unless the NOTIFY request contains a - // "Subscription-State" of "terminated." - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - if (this.subscriptionState !== subscription_1.SubscriptionState.Terminated) { - // Because the dialog usage is established by the NOTIFY request, the - // route set at the subscriber is taken from the NOTIFY request itself, - // as opposed to the route set present in the 200-class response to the - // SUBSCRIBE request. - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - var dialogState = subscription_dialog_1.SubscriptionDialog.initialDialogStateForSubscription(this.message, uas.message); - // Subscription Initiated! :) - this.dialog = new subscription_dialog_1.SubscriptionDialog(this.subscriptionEvent, this.subscriptionExpires, this.subscriptionState, this.core, dialogState); - } - // Delegate. - if (this.delegate && this.delegate.onNotify) { - var request = uas; - var subscription = this.dialog; - this.delegate.onNotify({ request: request, subscription: subscription }); - } - else { - uas.accept(); - } - }; - SubscribeUserAgentClient.prototype.waitNotifyStart = function () { - var _this = this; - if (!this.N) { - // Add ourselves to the core's subscriber map. - // This allows the core to route out of dialog NOTIFY messages to us. - this.core.subscribers.set(this.subscriberId, this); - this.N = setTimeout(function () { return _this.timer_N(); }, timers_1.Timers.TIMER_N); - } - }; - SubscribeUserAgentClient.prototype.waitNotifyStop = function () { - if (this.N) { - // Remove ourselves to the core's subscriber map. - // Any future out of dialog NOTIFY messages will be rejected with a 481. - this.core.subscribers.delete(this.subscriberId); - clearTimeout(this.N); - this.N = undefined; - } - }; - /** - * Receive a response from the transaction layer. - * @param message - Incoming response message. - */ - SubscribeUserAgentClient.prototype.receiveResponse = function (message) { - if (!this.authenticationGuard(message)) { - return; - } - if (message.statusCode && message.statusCode >= 200 && message.statusCode < 300) { - // The "Expires" header field in a 200-class response to SUBSCRIBE - // request indicates the actual duration for which the subscription will - // remain active (unless refreshed). The received value might be - // smaller than the value indicated in the SUBSCRIBE request but cannot - // be larger; see Section 4.2.1 for details. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - // The "Expires" values present in SUBSCRIBE 200-class responses behave - // in the same way as they do in REGISTER responses: the server MAY - // shorten the interval but MUST NOT lengthen it. - // - // If the duration specified in a SUBSCRIBE request is unacceptably - // short, the notifier may be able to send a 423 response, as - // described earlier in this section. - // - // 200-class responses to SUBSCRIBE requests will not generally contain - // any useful information beyond subscription duration; their primary - // purpose is to serve as a reliability mechanism. State information - // will be communicated via a subsequent NOTIFY request from the - // notifier. - // https://tools.ietf.org/html/rfc6665#section-4.2.1.1 - var expires = message.getHeader("Expires"); - if (!expires) { - this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE"); - } - else { - var subscriptionExpiresReceived = Number(expires); - if (subscriptionExpiresReceived > this.subscriptionExpiresRequested) { - this.logger.warn("Expires header in a 200-class response to SUBSCRIBE with a higher value than the one in the request"); - } - if (subscriptionExpiresReceived < this.subscriptionExpires) { - this.subscriptionExpires = subscriptionExpiresReceived; - } - } - // If a NOTIFY arrived before 200-class response a dialog may have been created. - // Updated the dialogs expiration only if this indicates earlier expiration. - if (this.dialog) { - if (this.dialog.subscriptionExpires > this.subscriptionExpires) { - this.dialog.subscriptionExpires = this.subscriptionExpires; - } - } - } - if (message.statusCode && message.statusCode >= 300 && message.statusCode < 700) { - this.waitNotifyStop(); // No NOTIFY will be sent after a negative final response. - } - _super.prototype.receiveResponse.call(this, message); - }; - /** - * To ensure that subscribers do not wait indefinitely for a - * subscription to be established, a subscriber starts a Timer N, set to - * 64*T1, when it sends a SUBSCRIBE request. If this Timer N expires - * prior to the receipt of a NOTIFY request, the subscriber considers - * the subscription failed, and cleans up any state associated with the - * subscription attempt. - * https://tools.ietf.org/html/rfc6665#section-4.1.2.4 - */ - SubscribeUserAgentClient.prototype.timer_N = function () { - this.logger.warn("Timer N expired for SUBSCRIBE user agent client. Timed out waiting for NOTIFY."); - this.waitNotifyStop(); - if (this.delegate && this.delegate.onNotifyTimeout) { - this.delegate.onNotifyTimeout(); - } - }; - return SubscribeUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.SubscribeUserAgentClient = SubscribeUserAgentClient; - - -/***/ }), -/* 77 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * SUBSCRIBE UAS. - * @public - */ -var SubscribeUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(SubscribeUserAgentServer, _super); - function SubscribeUserAgentServer(core, message, delegate) { - var _this = _super.call(this, transactions_1.NonInviteServerTransaction, core, message, delegate) || this; - _this.core = core; - return _this; - } - return SubscribeUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.SubscribeUserAgentServer = SubscribeUserAgentServer; - - -/***/ }), -/* 78 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var events_1 = __webpack_require__(30); -/** - * Transport. - * @remarks - * Abstract transport layer base class. - * @public - */ -var Transport = /** @class */ (function (_super) { - tslib_1.__extends(Transport, _super); - /** - * Constructor - * @param logger - Logger. - * @param options - Options bucket. - */ - function Transport(logger, options) { - var _this = _super.call(this) || this; - _this.logger = logger; - return _this; - } - /** - * Returns the promise designated by the child layer then emits a connected event. - * Automatically emits an event upon resolution, unless overrideEvent is set. If you - * override the event in this fashion, you should emit it in your implementation of connectPromise - * @param options - Options bucket. - */ - Transport.prototype.connect = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - return this.connectPromise(options).then(function (data) { - if (!data.overrideEvent) { - _this.emit("connected"); - } - }); - }; - /** - * Sends a message then emits a 'messageSent' event. Automatically emits an - * event upon resolution, unless data.overrideEvent is set. If you override - * the event in this fashion, you should emit it in your implementation of sendPromise - * @param msg - Message. - * @param options - Options bucket. - */ - Transport.prototype.send = function (msg, options) { - var _this = this; - if (options === void 0) { options = {}; } - return this.sendPromise(msg).then(function (data) { - if (!data.overrideEvent) { - _this.emit("messageSent", data.msg); - } - }); - }; - /** - * Returns the promise designated by the child layer then emits a - * disconnected event. Automatically emits an event upon resolution, - * unless overrideEvent is set. If you override the event in this fashion, - * you should emit it in your implementation of disconnectPromise - * @param options - Options bucket - */ - Transport.prototype.disconnect = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - return this.disconnectPromise(options).then(function (data) { - if (!data.overrideEvent) { - _this.emit("disconnected"); - } - }); - }; - Transport.prototype.afterConnected = function (callback) { - if (this.isConnected()) { - callback(); - } - else { - this.once("connected", callback); - } - }; - /** - * Returns a promise which resolves once the UA is connected. DEPRECATION WARNING: just use afterConnected() - */ - Transport.prototype.waitForConnected = function () { - var _this = this; - // tslint:disable-next-line:no-console - console.warn("DEPRECATION WARNING Transport.waitForConnected(): use afterConnected() instead"); - return new Promise(function (resolve) { - _this.afterConnected(resolve); - }); - }; - return Transport; -}(events_1.EventEmitter)); -exports.Transport = Transport; - - -/***/ }), -/* 79 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var events_1 = __webpack_require__(30); -var Constants_1 = __webpack_require__(80); -var core_1 = __webpack_require__(2); -var Enums_1 = __webpack_require__(82); -var Utils_1 = __webpack_require__(83); -var ClientContext = /** @class */ (function (_super) { - tslib_1.__extends(ClientContext, _super); - function ClientContext(ua, method, target, options) { - var _this = _super.call(this) || this; - _this.data = {}; - ClientContext.initializer(_this, ua, method, target, options); - return _this; - } - ClientContext.initializer = function (objToConstruct, ua, method, originalTarget, options) { - objToConstruct.type = Enums_1.TypeStrings.ClientContext; - // Validate arguments - if (originalTarget === undefined) { - throw new TypeError("Not enough arguments"); - } - objToConstruct.ua = ua; - objToConstruct.logger = ua.getLogger("sip.clientcontext"); - objToConstruct.method = method; - var target = ua.normalizeTarget(originalTarget); - if (!target) { - throw new TypeError("Invalid target: " + originalTarget); - } - var fromURI = ua.userAgentCore.configuration.aor; - if (options && options.params && options.params.fromUri) { - fromURI = - (typeof options.params.fromUri === "string") ? - core_1.Grammar.URIParse(options.params.fromUri) : - options.params.fromUri; - if (!fromURI) { - throw new TypeError("Invalid from URI: " + options.params.fromUri); - } - } - var toURI = target; - if (options && options.params && options.params.toUri) { - toURI = - (typeof options.params.toUri === "string") ? - core_1.Grammar.URIParse(options.params.toUri) : - options.params.toUri; - if (!toURI) { - throw new TypeError("Invalid to URI: " + options.params.toUri); - } - } - /* Options - * - extraHeaders - * - params - * - contentType - * - body - */ - options = Object.create(options || Object.prototype); - options = options || {}; - var extraHeaders = (options.extraHeaders || []).slice(); - var params = options.params || {}; - var bodyObj; - if (options.body) { - bodyObj = { - body: options.body, - contentType: options.contentType ? options.contentType : "application/sdp" - }; - objToConstruct.body = bodyObj; - } - var body; - if (bodyObj) { - body = Utils_1.Utils.fromBodyObj(bodyObj); - } - // Build the request - objToConstruct.request = ua.userAgentCore.makeOutgoingRequestMessage(method, target, fromURI, toURI, params, extraHeaders, body); - /* Set other properties from the request */ - if (objToConstruct.request.from) { - objToConstruct.localIdentity = objToConstruct.request.from; - } - if (objToConstruct.request.to) { - objToConstruct.remoteIdentity = objToConstruct.request.to; - } - }; - ClientContext.prototype.send = function () { - var _this = this; - this.ua.userAgentCore.request(this.request, { - onAccept: function (response) { return _this.receiveResponse(response.message); }, - onProgress: function (response) { return _this.receiveResponse(response.message); }, - onRedirect: function (response) { return _this.receiveResponse(response.message); }, - onReject: function (response) { return _this.receiveResponse(response.message); }, - onTrying: function (response) { return _this.receiveResponse(response.message); } - }); - return this; - }; - ClientContext.prototype.receiveResponse = function (response) { - var statusCode = response.statusCode || 0; - var cause = Utils_1.Utils.getReasonPhrase(statusCode); - switch (true) { - case /^1[0-9]{2}$/.test(statusCode.toString()): - this.emit("progress", response, cause); - break; - case /^2[0-9]{2}$/.test(statusCode.toString()): - if (this.ua.applicants[this.toString()]) { - delete this.ua.applicants[this.toString()]; - } - this.emit("accepted", response, cause); - break; - default: - if (this.ua.applicants[this.toString()]) { - delete this.ua.applicants[this.toString()]; - } - this.emit("rejected", response, cause); - this.emit("failed", response, cause); - break; - } - }; - ClientContext.prototype.onRequestTimeout = function () { - this.emit("failed", undefined, Constants_1.C.causes.REQUEST_TIMEOUT); - }; - ClientContext.prototype.onTransportError = function () { - this.emit("failed", undefined, Constants_1.C.causes.CONNECTION_ERROR); - }; - return ClientContext; -}(events_1.EventEmitter)); -exports.ClientContext = ClientContext; - - -/***/ }), -/* 80 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var version_1 = __webpack_require__(81); -var C; -(function (C) { - C.version = version_1.LIBRARY_VERSION; - C.USER_AGENT = "SIP.js/" + version_1.LIBRARY_VERSION; - // SIP scheme - C.SIP = "sip"; - C.SIPS = "sips"; - // End and Failure causes - var causes; - (function (causes) { - // Generic error causes - causes["CONNECTION_ERROR"] = "Connection Error"; - causes["INTERNAL_ERROR"] = "Internal Error"; - causes["REQUEST_TIMEOUT"] = "Request Timeout"; - causes["SIP_FAILURE_CODE"] = "SIP Failure Code"; - // SIP error causes - causes["ADDRESS_INCOMPLETE"] = "Address Incomplete"; - causes["AUTHENTICATION_ERROR"] = "Authentication Error"; - causes["BUSY"] = "Busy"; - causes["DIALOG_ERROR"] = "Dialog Error"; - causes["INCOMPATIBLE_SDP"] = "Incompatible SDP"; - causes["NOT_FOUND"] = "Not Found"; - causes["REDIRECTED"] = "Redirected"; - causes["REJECTED"] = "Rejected"; - causes["UNAVAILABLE"] = "Unavailable"; - // Session error causes - causes["BAD_MEDIA_DESCRIPTION"] = "Bad Media Description"; - causes["CANCELED"] = "Canceled"; - causes["EXPIRES"] = "Expires"; - causes["NO_ACK"] = "No ACK"; - causes["NO_ANSWER"] = "No Answer"; - causes["NO_PRACK"] = "No PRACK"; - causes["RTP_TIMEOUT"] = "RTP Timeout"; - causes["USER_DENIED_MEDIA_ACCESS"] = "User Denied Media Access"; - causes["WEBRTC_ERROR"] = "WebRTC Error"; - causes["WEBRTC_NOT_SUPPORTED"] = "WebRTC Not Supported"; - })(causes = C.causes || (C.causes = {})); - var supported; - (function (supported) { - supported["REQUIRED"] = "required"; - supported["SUPPORTED"] = "supported"; - supported["UNSUPPORTED"] = "none"; - })(supported = C.supported || (C.supported = {})); - C.SIP_ERROR_CAUSES = { - ADDRESS_INCOMPLETE: [484], - AUTHENTICATION_ERROR: [401, 407], - BUSY: [486, 600], - INCOMPATIBLE_SDP: [488, 606], - NOT_FOUND: [404, 604], - REDIRECTED: [300, 301, 302, 305, 380], - REJECTED: [403, 603], - UNAVAILABLE: [480, 410, 408, 430] - }; - // SIP Methods - C.ACK = "ACK"; - C.BYE = "BYE"; - C.CANCEL = "CANCEL"; - C.INFO = "INFO"; - C.INVITE = "INVITE"; - C.MESSAGE = "MESSAGE"; - C.NOTIFY = "NOTIFY"; - C.OPTIONS = "OPTIONS"; - C.REGISTER = "REGISTER"; - C.UPDATE = "UPDATE"; - C.SUBSCRIBE = "SUBSCRIBE"; - C.PUBLISH = "PUBLISH"; - C.REFER = "REFER"; - C.PRACK = "PRACK"; - /* SIP Response Reasons - * DOC: http://www.iana.org/assignments/sip-parameters - * Copied from https://github.com/versatica/OverSIP/blob/master/lib/oversip/sip/constants.rb#L7 - */ - C.REASON_PHRASE = { - 100: "Trying", - 180: "Ringing", - 181: "Call Is Being Forwarded", - 182: "Queued", - 183: "Session Progress", - 199: "Early Dialog Terminated", - 200: "OK", - 202: "Accepted", - 204: "No Notification", - 300: "Multiple Choices", - 301: "Moved Permanently", - 302: "Moved Temporarily", - 305: "Use Proxy", - 380: "Alternative Service", - 400: "Bad Request", - 401: "Unauthorized", - 402: "Payment Required", - 403: "Forbidden", - 404: "Not Found", - 405: "Method Not Allowed", - 406: "Not Acceptable", - 407: "Proxy Authentication Required", - 408: "Request Timeout", - 410: "Gone", - 412: "Conditional Request Failed", - 413: "Request Entity Too Large", - 414: "Request-URI Too Long", - 415: "Unsupported Media Type", - 416: "Unsupported URI Scheme", - 417: "Unknown Resource-Priority", - 420: "Bad Extension", - 421: "Extension Required", - 422: "Session Interval Too Small", - 423: "Interval Too Brief", - 428: "Use Identity Header", - 429: "Provide Referrer Identity", - 430: "Flow Failed", - 433: "Anonymity Disallowed", - 436: "Bad Identity-Info", - 437: "Unsupported Certificate", - 438: "Invalid Identity Header", - 439: "First Hop Lacks Outbound Support", - 440: "Max-Breadth Exceeded", - 469: "Bad Info Package", - 470: "Consent Needed", - 478: "Unresolvable Destination", - 480: "Temporarily Unavailable", - 481: "Call/Transaction Does Not Exist", - 482: "Loop Detected", - 483: "Too Many Hops", - 484: "Address Incomplete", - 485: "Ambiguous", - 486: "Busy Here", - 487: "Request Terminated", - 488: "Not Acceptable Here", - 489: "Bad Event", - 491: "Request Pending", - 493: "Undecipherable", - 494: "Security Agreement Required", - 500: "Internal Server Error", - 501: "Not Implemented", - 502: "Bad Gateway", - 503: "Service Unavailable", - 504: "Server Time-out", - 505: "Version Not Supported", - 513: "Message Too Large", - 580: "Precondition Failure", - 600: "Busy Everywhere", - 603: "Decline", - 604: "Does Not Exist Anywhere", - 606: "Not Acceptable" - }; - /* SIP Option Tags - * DOC: http://www.iana.org/assignments/sip-parameters/sip-parameters.xhtml#sip-parameters-4 - */ - C.OPTION_TAGS = { - "100rel": true, - "199": true, - "answermode": true, - "early-session": true, - "eventlist": true, - "explicitsub": true, - "from-change": true, - "geolocation-http": true, - "geolocation-sip": true, - "gin": true, - "gruu": true, - "histinfo": true, - "ice": true, - "join": true, - "multiple-refer": true, - "norefersub": true, - "nosub": true, - "outbound": true, - "path": true, - "policy": true, - "precondition": true, - "pref": true, - "privacy": true, - "recipient-list-invite": true, - "recipient-list-message": true, - "recipient-list-subscribe": true, - "replaces": true, - "resource-priority": true, - "sdp-anat": true, - "sec-agree": true, - "tdialog": true, - "timer": true, - "uui": true // RFC 7433 - }; - var dtmfType; - (function (dtmfType) { - dtmfType["INFO"] = "info"; - dtmfType["RTP"] = "rtp"; - })(dtmfType = C.dtmfType || (C.dtmfType = {})); -})(C = exports.C || (exports.C = {})); - - -/***/ }), -/* 81 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.LIBRARY_VERSION = "0.15.5"; - - -/***/ }), -/* 82 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// enums can't really be declared, so they are set here. -// pulled out of individual files to avoid circular dependencies -Object.defineProperty(exports, "__esModule", { value: true }); -var DialogStatus; -(function (DialogStatus) { - DialogStatus[DialogStatus["STATUS_EARLY"] = 1] = "STATUS_EARLY"; - DialogStatus[DialogStatus["STATUS_CONFIRMED"] = 2] = "STATUS_CONFIRMED"; -})(DialogStatus = exports.DialogStatus || (exports.DialogStatus = {})); -var SessionStatus; -(function (SessionStatus) { - // Session states - SessionStatus[SessionStatus["STATUS_NULL"] = 0] = "STATUS_NULL"; - SessionStatus[SessionStatus["STATUS_INVITE_SENT"] = 1] = "STATUS_INVITE_SENT"; - SessionStatus[SessionStatus["STATUS_1XX_RECEIVED"] = 2] = "STATUS_1XX_RECEIVED"; - SessionStatus[SessionStatus["STATUS_INVITE_RECEIVED"] = 3] = "STATUS_INVITE_RECEIVED"; - SessionStatus[SessionStatus["STATUS_WAITING_FOR_ANSWER"] = 4] = "STATUS_WAITING_FOR_ANSWER"; - SessionStatus[SessionStatus["STATUS_ANSWERED"] = 5] = "STATUS_ANSWERED"; - SessionStatus[SessionStatus["STATUS_WAITING_FOR_PRACK"] = 6] = "STATUS_WAITING_FOR_PRACK"; - SessionStatus[SessionStatus["STATUS_WAITING_FOR_ACK"] = 7] = "STATUS_WAITING_FOR_ACK"; - SessionStatus[SessionStatus["STATUS_CANCELED"] = 8] = "STATUS_CANCELED"; - SessionStatus[SessionStatus["STATUS_TERMINATED"] = 9] = "STATUS_TERMINATED"; - SessionStatus[SessionStatus["STATUS_ANSWERED_WAITING_FOR_PRACK"] = 10] = "STATUS_ANSWERED_WAITING_FOR_PRACK"; - SessionStatus[SessionStatus["STATUS_EARLY_MEDIA"] = 11] = "STATUS_EARLY_MEDIA"; - SessionStatus[SessionStatus["STATUS_CONFIRMED"] = 12] = "STATUS_CONFIRMED"; -})(SessionStatus = exports.SessionStatus || (exports.SessionStatus = {})); -var TypeStrings; -(function (TypeStrings) { - TypeStrings[TypeStrings["ClientContext"] = 0] = "ClientContext"; - TypeStrings[TypeStrings["ConfigurationError"] = 1] = "ConfigurationError"; - TypeStrings[TypeStrings["Dialog"] = 2] = "Dialog"; - TypeStrings[TypeStrings["DigestAuthentication"] = 3] = "DigestAuthentication"; - TypeStrings[TypeStrings["DTMF"] = 4] = "DTMF"; - TypeStrings[TypeStrings["IncomingMessage"] = 5] = "IncomingMessage"; - TypeStrings[TypeStrings["IncomingRequest"] = 6] = "IncomingRequest"; - TypeStrings[TypeStrings["IncomingResponse"] = 7] = "IncomingResponse"; - TypeStrings[TypeStrings["InvalidStateError"] = 8] = "InvalidStateError"; - TypeStrings[TypeStrings["InviteClientContext"] = 9] = "InviteClientContext"; - TypeStrings[TypeStrings["InviteServerContext"] = 10] = "InviteServerContext"; - TypeStrings[TypeStrings["Logger"] = 11] = "Logger"; - TypeStrings[TypeStrings["LoggerFactory"] = 12] = "LoggerFactory"; - TypeStrings[TypeStrings["MethodParameterError"] = 13] = "MethodParameterError"; - TypeStrings[TypeStrings["NameAddrHeader"] = 14] = "NameAddrHeader"; - TypeStrings[TypeStrings["NotSupportedError"] = 15] = "NotSupportedError"; - TypeStrings[TypeStrings["OutgoingRequest"] = 16] = "OutgoingRequest"; - TypeStrings[TypeStrings["Parameters"] = 17] = "Parameters"; - TypeStrings[TypeStrings["PublishContext"] = 18] = "PublishContext"; - TypeStrings[TypeStrings["ReferClientContext"] = 19] = "ReferClientContext"; - TypeStrings[TypeStrings["ReferServerContext"] = 20] = "ReferServerContext"; - TypeStrings[TypeStrings["RegisterContext"] = 21] = "RegisterContext"; - TypeStrings[TypeStrings["RenegotiationError"] = 22] = "RenegotiationError"; - TypeStrings[TypeStrings["RequestSender"] = 23] = "RequestSender"; - TypeStrings[TypeStrings["ServerContext"] = 24] = "ServerContext"; - TypeStrings[TypeStrings["Session"] = 25] = "Session"; - TypeStrings[TypeStrings["SessionDescriptionHandler"] = 26] = "SessionDescriptionHandler"; - TypeStrings[TypeStrings["SessionDescriptionHandlerError"] = 27] = "SessionDescriptionHandlerError"; - TypeStrings[TypeStrings["SessionDescriptionHandlerObserver"] = 28] = "SessionDescriptionHandlerObserver"; - TypeStrings[TypeStrings["Subscription"] = 29] = "Subscription"; - TypeStrings[TypeStrings["Transport"] = 30] = "Transport"; - TypeStrings[TypeStrings["UA"] = 31] = "UA"; - TypeStrings[TypeStrings["URI"] = 32] = "URI"; -})(TypeStrings = exports.TypeStrings || (exports.TypeStrings = {})); -// UA status codes -var UAStatus; -(function (UAStatus) { - UAStatus[UAStatus["STATUS_INIT"] = 0] = "STATUS_INIT"; - UAStatus[UAStatus["STATUS_STARTING"] = 1] = "STATUS_STARTING"; - UAStatus[UAStatus["STATUS_READY"] = 2] = "STATUS_READY"; - UAStatus[UAStatus["STATUS_USER_CLOSED"] = 3] = "STATUS_USER_CLOSED"; - UAStatus[UAStatus["STATUS_NOT_READY"] = 4] = "STATUS_NOT_READY"; -})(UAStatus = exports.UAStatus || (exports.UAStatus = {})); - - -/***/ }), -/* 83 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var Constants_1 = __webpack_require__(80); -var grammar_1 = __webpack_require__(11); -var uri_1 = __webpack_require__(15); -var Utils; -(function (Utils) { - function defer() { - var deferred = {}; - deferred.promise = new Promise(function (resolve, reject) { - deferred.resolve = resolve; - deferred.reject = reject; - }); - return deferred; - } - Utils.defer = defer; - function reducePromises(arr, val) { - return arr.reduce(function (acc, fn) { - acc = acc.then(fn); - return acc; - }, Promise.resolve(val)); - } - Utils.reducePromises = reducePromises; - function str_utf8_length(str) { - return encodeURIComponent(str).replace(/%[A-F\d]{2}/g, "U").length; - } - Utils.str_utf8_length = str_utf8_length; - function generateFakeSDP(body) { - if (!body) { - return; - } - var start = body.indexOf("o="); - var end = body.indexOf("\r\n", start); - return "v=0\r\n" + body.slice(start, end) + "\r\ns=-\r\nt=0 0\r\nc=IN IP4 0.0.0.0"; - } - Utils.generateFakeSDP = generateFakeSDP; - function isDecimal(num) { - var numAsNum = parseInt(num, 10); - return !isNaN(numAsNum) && (parseFloat(num) === numAsNum); - } - Utils.isDecimal = isDecimal; - function createRandomToken(size, base) { - if (base === void 0) { base = 32; } - var token = ""; - for (var i = 0; i < size; i++) { - var r = Math.floor(Math.random() * base); - token += r.toString(base); - } - return token; - } - Utils.createRandomToken = createRandomToken; - function newTag() { - // used to use the constant in UA - return Utils.createRandomToken(10); - } - Utils.newTag = newTag; - // http://stackoverflow.com/users/109538/broofa - function newUUID() { - var UUID = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) { - var r = Math.floor(Math.random() * 16); - var v = c === "x" ? r : (r % 4 + 8); - return v.toString(16); - }); - return UUID; - } - Utils.newUUID = newUUID; - /* - * Normalize SIP URI. - * NOTE: It does not allow a SIP URI without username. - * Accepts 'sip', 'sips' and 'tel' URIs and convert them into 'sip'. - * Detects the domain part (if given) and properly hex-escapes the user portion. - * If the user portion has only 'tel' number symbols the user portion is clean of 'tel' visual separators. - * @private - * @param {String} target - * @param {String} [domain] - */ - function normalizeTarget(target, domain) { - // If no target is given then raise an error. - if (!target) { - return; - // If a SIP.URI instance is given then return it. - } - else if (target instanceof uri_1.URI) { - return target; - // If a string is given split it by '@': - // - Last fragment is the desired domain. - // - Otherwise append the given domain argument. - } - else if (typeof target === "string") { - var targetArray = target.split("@"); - var targetUser = void 0; - var targetDomain = void 0; - switch (targetArray.length) { - case 1: - if (!domain) { - return; - } - targetUser = target; - targetDomain = domain; - break; - case 2: - targetUser = targetArray[0]; - targetDomain = targetArray[1]; - break; - default: - targetUser = targetArray.slice(0, targetArray.length - 1).join("@"); - targetDomain = targetArray[targetArray.length - 1]; - } - // Remove the URI scheme (if present). - targetUser = targetUser.replace(/^(sips?|tel):/i, ""); - // Remove 'tel' visual separators if the user portion just contains 'tel' number symbols. - if (/^[\-\.\(\)]*\+?[0-9\-\.\(\)]+$/.test(targetUser)) { - targetUser = targetUser.replace(/[\-\.\(\)]/g, ""); - } - // Build the complete SIP URI. - target = Constants_1.C.SIP + ":" + Utils.escapeUser(targetUser) + "@" + targetDomain; - // Finally parse the resulting URI. - return grammar_1.Grammar.URIParse(target); - } - else { - return; - } - } - Utils.normalizeTarget = normalizeTarget; - /* - * Hex-escape a SIP URI user. - * @private - * @param {String} user - */ - function escapeUser(user) { - // Don't hex-escape ':' (%3A), '+' (%2B), '?' (%3F"), '/' (%2F). - return encodeURIComponent(decodeURIComponent(user)) - .replace(/%3A/ig, ":") - .replace(/%2B/ig, "+") - .replace(/%3F/ig, "?") - .replace(/%2F/ig, "/"); - } - Utils.escapeUser = escapeUser; - function headerize(str) { - var exceptions = { - "Call-Id": "Call-ID", - "Cseq": "CSeq", - "Min-Se": "Min-SE", - "Rack": "RAck", - "Rseq": "RSeq", - "Www-Authenticate": "WWW-Authenticate", - }; - var name = str.toLowerCase().replace(/_/g, "-").split("-"); - var parts = name.length; - var hname = ""; - for (var part = 0; part < parts; part++) { - if (part !== 0) { - hname += "-"; - } - hname += name[part].charAt(0).toUpperCase() + name[part].substring(1); - } - if (exceptions[hname]) { - hname = exceptions[hname]; - } - return hname; - } - Utils.headerize = headerize; - function sipErrorCause(statusCode) { - for (var cause in Constants_1.C.SIP_ERROR_CAUSES) { - if (Constants_1.C.SIP_ERROR_CAUSES[cause].indexOf(statusCode) !== -1) { - return Constants_1.C.causes[cause]; - } - } - return Constants_1.C.causes.SIP_FAILURE_CODE; - } - Utils.sipErrorCause = sipErrorCause; - function getReasonPhrase(code, specific) { - return specific || Constants_1.C.REASON_PHRASE[code] || ""; - } - Utils.getReasonPhrase = getReasonPhrase; - function getReasonHeaderValue(code, reason) { - reason = Utils.getReasonPhrase(code, reason); - return "SIP;cause=" + code + ';text="' + reason + '"'; - } - Utils.getReasonHeaderValue = getReasonHeaderValue; - function getCancelReason(code, reason) { - if (code && code < 200 || code > 699) { - throw new TypeError("Invalid statusCode: " + code); - } - else if (code) { - return Utils.getReasonHeaderValue(code, reason); - } - } - Utils.getCancelReason = getCancelReason; - function buildStatusLine(code, reason) { - // Validate code and reason values - if (!code || (code < 100 || code > 699)) { - throw new TypeError("Invalid statusCode: " + code); - } - else if (reason && typeof reason !== "string" && !(reason instanceof String)) { - throw new TypeError("Invalid reason: " + reason); - } - reason = Utils.getReasonPhrase(code, reason); - return "SIP/2.0 " + code + " " + reason + "\r\n"; - } - Utils.buildStatusLine = buildStatusLine; - /** - * Create a Body given a BodyObj. - * @param bodyObj Body Object - */ - function fromBodyObj(bodyObj) { - var content = bodyObj.body; - var contentType = bodyObj.contentType; - var contentDisposition = contentTypeToContentDisposition(contentType); - var body = { contentDisposition: contentDisposition, contentType: contentType, content: content }; - return body; - } - Utils.fromBodyObj = fromBodyObj; - /** - * Create a BodyObj given a Body. - * @param bodyObj Body Object - */ - function toBodyObj(body) { - var bodyObj = { - body: body.content, - contentType: body.contentType - }; - return bodyObj; - } - Utils.toBodyObj = toBodyObj; - // If the Content-Disposition header field is missing, bodies of - // Content-Type application/sdp imply the disposition "session", while - // other content types imply "render". - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - function contentTypeToContentDisposition(contentType) { - if (contentType === "application/sdp") { - return "session"; - } - else { - return "render"; - } - } -})(Utils = exports.Utils || (exports.Utils = {})); - - -/***/ }), -/* 84 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var core_1 = __webpack_require__(2); -var Enums_1 = __webpack_require__(82); -// tslint:disable:max-classes-per-file -var Exceptions; -(function (Exceptions) { - /** - * Indicates the session description handler has closed. - * Occurs when getDescription() or setDescription() are called after close() has been called. - * Occurs when close() is called while getDescription() or setDescription() are in progress. - */ - var ClosedSessionDescriptionHandlerError = /** @class */ (function (_super) { - tslib_1.__extends(ClosedSessionDescriptionHandlerError, _super); - function ClosedSessionDescriptionHandlerError() { - return _super.call(this, "The session description handler has closed.") || this; - } - return ClosedSessionDescriptionHandlerError; - }(core_1.Exception)); - Exceptions.ClosedSessionDescriptionHandlerError = ClosedSessionDescriptionHandlerError; - /** - * Indicates the session terminated before the action completed. - */ - var TerminatedSessionError = /** @class */ (function (_super) { - tslib_1.__extends(TerminatedSessionError, _super); - function TerminatedSessionError() { - return _super.call(this, "The session has terminated.") || this; - } - return TerminatedSessionError; - }(core_1.Exception)); - Exceptions.TerminatedSessionError = TerminatedSessionError; - /** - * Unsupported session description content type. - */ - var UnsupportedSessionDescriptionContentTypeError = /** @class */ (function (_super) { - tslib_1.__extends(UnsupportedSessionDescriptionContentTypeError, _super); - function UnsupportedSessionDescriptionContentTypeError(message) { - return _super.call(this, message ? message : "Unsupported session description content type.") || this; - } - return UnsupportedSessionDescriptionContentTypeError; - }(core_1.Exception)); - Exceptions.UnsupportedSessionDescriptionContentTypeError = UnsupportedSessionDescriptionContentTypeError; -})(Exceptions = exports.Exceptions || (exports.Exceptions = {})); -/** - * DEPRECATED: The original implementation of exceptions in this library attempted to - * deal with the lack of type checking in JavaScript by adding a "type" attribute - * to objects and using that to discriminate. On top of that it layered allcoated - * "code" numbers and constant "name" strings. All of that is unnecessary when using - * TypeScript, inheriting from Error and properly setting up the prototype chain... - */ -var LegacyException = /** @class */ (function (_super) { - tslib_1.__extends(LegacyException, _super); - function LegacyException(code, name, message) { - var _this = _super.call(this, message) || this; - _this.code = code; - _this.name = name; - _this.message = message; - return _this; - } - return LegacyException; -}(core_1.Exception)); -(function (Exceptions) { - var ConfigurationError = /** @class */ (function (_super) { - tslib_1.__extends(ConfigurationError, _super); - function ConfigurationError(parameter, value) { - var _this = _super.call(this, 1, "CONFIGURATION_ERROR", (!value) ? "Missing parameter: " + parameter : - "Invalid value " + JSON.stringify(value) + " for parameter '" + parameter + "'") || this; - _this.type = Enums_1.TypeStrings.ConfigurationError; - _this.parameter = parameter; - _this.value = value; - return _this; - } - return ConfigurationError; - }(LegacyException)); - Exceptions.ConfigurationError = ConfigurationError; - var InvalidStateError = /** @class */ (function (_super) { - tslib_1.__extends(InvalidStateError, _super); - function InvalidStateError(status) { - var _this = _super.call(this, 2, "INVALID_STATE_ERROR", "Invalid status: " + status) || this; - _this.type = Enums_1.TypeStrings.InvalidStateError; - _this.status = status; - return _this; - } - return InvalidStateError; - }(LegacyException)); - Exceptions.InvalidStateError = InvalidStateError; - var NotSupportedError = /** @class */ (function (_super) { - tslib_1.__extends(NotSupportedError, _super); - function NotSupportedError(message) { - var _this = _super.call(this, 3, "NOT_SUPPORTED_ERROR", message) || this; - _this.type = Enums_1.TypeStrings.NotSupportedError; - return _this; - } - return NotSupportedError; - }(LegacyException)); - Exceptions.NotSupportedError = NotSupportedError; - // 4 was GetDescriptionError, which was deprecated and now removed - var RenegotiationError = /** @class */ (function (_super) { - tslib_1.__extends(RenegotiationError, _super); - function RenegotiationError(message) { - var _this = _super.call(this, 5, "RENEGOTIATION_ERROR", message) || this; - _this.type = Enums_1.TypeStrings.RenegotiationError; - return _this; - } - return RenegotiationError; - }(LegacyException)); - Exceptions.RenegotiationError = RenegotiationError; - var MethodParameterError = /** @class */ (function (_super) { - tslib_1.__extends(MethodParameterError, _super); - function MethodParameterError(method, parameter, value) { - var _this = _super.call(this, 6, "METHOD_PARAMETER_ERROR", (!value) ? - "Missing parameter: " + parameter : - "Invalid value " + JSON.stringify(value) + " for parameter '" + parameter + "'") || this; - _this.type = Enums_1.TypeStrings.MethodParameterError; - _this.method = method; - _this.parameter = parameter; - _this.value = value; - return _this; - } - return MethodParameterError; - }(LegacyException)); - Exceptions.MethodParameterError = MethodParameterError; - // 7 was TransportError, which was replaced - var SessionDescriptionHandlerError = /** @class */ (function (_super) { - tslib_1.__extends(SessionDescriptionHandlerError, _super); - function SessionDescriptionHandlerError(method, error, message) { - var _this = _super.call(this, 8, "SESSION_DESCRIPTION_HANDLER_ERROR", message || "Error with Session Description Handler") || this; - _this.type = Enums_1.TypeStrings.SessionDescriptionHandlerError; - _this.method = method; - _this.error = error; - return _this; - } - return SessionDescriptionHandlerError; - }(LegacyException)); - Exceptions.SessionDescriptionHandlerError = SessionDescriptionHandlerError; -})(Exceptions = exports.Exceptions || (exports.Exceptions = {})); - - -/***/ }), -/* 85 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var core_1 = __webpack_require__(2); -/** - * Extract and parse every header of a SIP message. - * @namespace - */ -var Parser; -(function (Parser) { - function getHeader(data, headerStart) { - // 'start' position of the header. - var start = headerStart; - // 'end' position of the header. - var end = 0; - // 'partial end' position of the header. - var partialEnd = 0; - // End of message. - if (data.substring(start, start + 2).match(/(^\r\n)/)) { - return -2; - } - while (end === 0) { - // Partial End of Header. - partialEnd = data.indexOf("\r\n", start); - // 'indexOf' returns -1 if the value to be found never occurs. - if (partialEnd === -1) { - return partialEnd; - } - if (!data.substring(partialEnd + 2, partialEnd + 4).match(/(^\r\n)/) && - data.charAt(partialEnd + 2).match(/(^\s+)/)) { - // Not the end of the message. Continue from the next position. - start = partialEnd + 2; - } - else { - end = partialEnd; - } - } - return end; - } - Parser.getHeader = getHeader; - function parseHeader(message, data, headerStart, headerEnd) { - var hcolonIndex = data.indexOf(":", headerStart); - var headerName = data.substring(headerStart, hcolonIndex).trim(); - var headerValue = data.substring(hcolonIndex + 1, headerEnd).trim(); - var parsed; - // If header-field is well-known, parse it. - switch (headerName.toLowerCase()) { - case "via": - case "v": - message.addHeader("via", headerValue); - if (message.getHeaders("via").length === 1) { - parsed = message.parseHeader("Via"); - if (parsed) { - message.via = parsed; - message.viaBranch = parsed.branch; - } - } - else { - parsed = 0; - } - break; - case "from": - case "f": - message.setHeader("from", headerValue); - parsed = message.parseHeader("from"); - if (parsed) { - message.from = parsed; - message.fromTag = parsed.getParam("tag"); - } - break; - case "to": - case "t": - message.setHeader("to", headerValue); - parsed = message.parseHeader("to"); - if (parsed) { - message.to = parsed; - message.toTag = parsed.getParam("tag"); - } - break; - case "record-route": - parsed = core_1.Grammar.parse(headerValue, "Record_Route"); - if (parsed === -1) { - parsed = undefined; - break; - } - for (var header in parsed) { - if (parsed[header]) { - message.addHeader("record-route", headerValue.substring(parsed[header].position, parsed[header].offset)); - message.headers["Record-Route"][message.getHeaders("record-route").length - 1].parsed = - parsed[header].parsed; - } - } - break; - case "call-id": - case "i": - message.setHeader("call-id", headerValue); - parsed = message.parseHeader("call-id"); - if (parsed) { - message.callId = headerValue; - } - break; - case "contact": - case "m": - parsed = core_1.Grammar.parse(headerValue, "Contact"); - if (parsed === -1) { - parsed = undefined; - break; - } - if (!(parsed instanceof Array)) { - parsed = undefined; - break; - } - parsed.forEach(function (header) { - message.addHeader("contact", headerValue.substring(header.position, header.offset)); - message.headers.Contact[message.getHeaders("contact").length - 1].parsed = header.parsed; - }); - break; - case "content-length": - case "l": - message.setHeader("content-length", headerValue); - parsed = message.parseHeader("content-length"); - break; - case "content-type": - case "c": - message.setHeader("content-type", headerValue); - parsed = message.parseHeader("content-type"); - break; - case "cseq": - message.setHeader("cseq", headerValue); - parsed = message.parseHeader("cseq"); - if (parsed) { - message.cseq = parsed.value; - } - if (message instanceof core_1.IncomingResponseMessage) { - message.method = parsed.method; - } - break; - case "max-forwards": - message.setHeader("max-forwards", headerValue); - parsed = message.parseHeader("max-forwards"); - break; - case "www-authenticate": - message.setHeader("www-authenticate", headerValue); - parsed = message.parseHeader("www-authenticate"); - break; - case "proxy-authenticate": - message.setHeader("proxy-authenticate", headerValue); - parsed = message.parseHeader("proxy-authenticate"); - break; - case "refer-to": - case "r": - message.setHeader("refer-to", headerValue); - parsed = message.parseHeader("refer-to"); - if (parsed) { - message.referTo = parsed; - } - break; - default: - // Do not parse this header. - message.addHeader(headerName.toLowerCase(), headerValue); - parsed = 0; - } - if (parsed === undefined) { - return { - error: "error parsing header '" + headerName + "'" - }; - } - else { - return true; - } - } - Parser.parseHeader = parseHeader; - /** Parse SIP Message - * @function - * @param {String} message SIP message. - * @param {Object} logger object. - * @returns {SIP.IncomingRequest|SIP.IncomingResponse|undefined} - */ - function parseMessage(data, logger) { - var headerStart = 0; - var headerEnd = data.indexOf("\r\n"); - if (headerEnd === -1) { - logger.warn("no CRLF found, not a SIP message, discarded"); - return; - } - // Parse first line. Check if it is a Request or a Reply. - var firstLine = data.substring(0, headerEnd); - var parsed = core_1.Grammar.parse(firstLine, "Request_Response"); - var message; - if (parsed === -1) { - logger.warn('error parsing first line of SIP message: "' + firstLine + '"'); - return; - } - else if (!parsed.status_code) { - message = new core_1.IncomingRequestMessage(); - message.method = parsed.method; - message.ruri = parsed.uri; - } - else { - message = new core_1.IncomingResponseMessage(); - message.statusCode = parsed.status_code; - message.reasonPhrase = parsed.reason_phrase; - } - message.data = data; - headerStart = headerEnd + 2; - /* Loop over every line in data. Detect the end of each header and parse - * it or simply add to the headers collection. - */ - var bodyStart; - while (true) { - headerEnd = getHeader(data, headerStart); - // The SIP message has normally finished. - if (headerEnd === -2) { - bodyStart = headerStart + 2; - break; - } - else if (headerEnd === -1) { - // data.indexOf returned -1 due to a malformed message. - logger.error("malformed message"); - return; - } - var parsedHeader = parseHeader(message, data, headerStart, headerEnd); - if (parsedHeader !== true) { - logger.error(parsed.error); - return; - } - headerStart = headerEnd + 2; - } - /* RFC3261 18.3. - * If there are additional bytes in the transport packet - * beyond the end of the body, they MUST be discarded. - */ - if (message.hasHeader("content-length")) { - message.body = data.substr(bodyStart, Number(message.getHeader("content-length"))); - } - else { - message.body = data.substring(bodyStart); - } - return message; - } - Parser.parseMessage = parseMessage; -})(Parser = exports.Parser || (exports.Parser = {})); - - -/***/ }), -/* 86 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var ClientContext_1 = __webpack_require__(79); -var Constants_1 = __webpack_require__(80); -var core_1 = __webpack_require__(2); -var Enums_1 = __webpack_require__(82); -var Exceptions_1 = __webpack_require__(84); -var Utils_1 = __webpack_require__(83); -/** - * SIP Publish (SIP Extension for Event State Publication RFC3903) - * @class Class creating a SIP PublishContext. - */ -var PublishContext = /** @class */ (function (_super) { - tslib_1.__extends(PublishContext, _super); - function PublishContext(ua, target, event, options) { - if (options === void 0) { options = {}; } - var _this = this; - options.extraHeaders = (options.extraHeaders || []).slice(); - options.contentType = (options.contentType || "text/plain"); - if (typeof options.expires !== "number" || (options.expires % 1) !== 0) { - options.expires = 3600; - } - else { - options.expires = Number(options.expires); - } - if (typeof (options.unpublishOnClose) !== "boolean") { - options.unpublishOnClose = true; - } - if (target === undefined || target === null || target === "") { - throw new Exceptions_1.Exceptions.MethodParameterError("Publish", "Target", target); - } - else { - target = ua.normalizeTarget(target); - if (target === undefined) { - throw new Exceptions_1.Exceptions.MethodParameterError("Publish", "Target", target); - } - } - _this = _super.call(this, ua, Constants_1.C.PUBLISH, target, options) || this; - _this.type = Enums_1.TypeStrings.PublishContext; - _this.options = options; - _this.target = target; - if (event === undefined || event === null || event === "") { - throw new Exceptions_1.Exceptions.MethodParameterError("Publish", "Event", event); - } - else { - _this.event = event; - } - _this.logger = ua.getLogger("sip.publish"); - _this.pubRequestExpires = _this.options.expires; - return _this; - } - /** - * Publish - * @param {string} Event body to publish, optional - */ - PublishContext.prototype.publish = function (body) { - // Clean up before the run - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - // is Inital or Modify request - this.options.body = body; - this.pubRequestBody = this.options.body; - if (this.pubRequestExpires === 0) { - // This is Initial request after unpublish - this.pubRequestExpires = this.options.expires; - this.pubRequestEtag = undefined; - } - if (!(this.ua.publishers[this.target.toString() + ":" + this.event])) { - this.ua.publishers[this.target.toString() + ":" + this.event] = this; - } - this.sendPublishRequest(); - }; - /** - * Unpublish - */ - PublishContext.prototype.unpublish = function () { - // Clean up before the run - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - this.pubRequestBody = undefined; - this.pubRequestExpires = 0; - if (this.pubRequestEtag !== undefined) { - this.sendPublishRequest(); - } - }; - /** - * Close - */ - PublishContext.prototype.close = function () { - // Send unpublish, if requested - if (this.options.unpublishOnClose) { - this.unpublish(); - } - else { - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - this.pubRequestBody = undefined; - this.pubRequestExpires = 0; - this.pubRequestEtag = undefined; - } - if (this.ua.publishers[this.target.toString() + ":" + this.event]) { - delete this.ua.publishers[this.target.toString() + ":" + this.event]; - } - }; - PublishContext.prototype.onRequestTimeout = function () { - _super.prototype.onRequestTimeout.call(this); - this.emit("unpublished", undefined, Constants_1.C.causes.REQUEST_TIMEOUT); - }; - PublishContext.prototype.onTransportError = function () { - _super.prototype.onTransportError.call(this); - this.emit("unpublished", undefined, Constants_1.C.causes.CONNECTION_ERROR); - }; - PublishContext.prototype.receiveResponse = function (response) { - var _this = this; - var statusCode = response.statusCode || 0; - var cause = Utils_1.Utils.getReasonPhrase(statusCode); - switch (true) { - case /^1[0-9]{2}$/.test(statusCode.toString()): - this.emit("progress", response, cause); - break; - case /^2[0-9]{2}$/.test(statusCode.toString()): - // Set SIP-Etag - if (response.hasHeader("SIP-ETag")) { - this.pubRequestEtag = response.getHeader("SIP-ETag"); - } - else { - this.logger.warn("SIP-ETag header missing in a 200-class response to PUBLISH"); - } - // Update Expire - if (response.hasHeader("Expires")) { - var expires = Number(response.getHeader("Expires")); - if (typeof expires === "number" && expires >= 0 && expires <= this.pubRequestExpires) { - this.pubRequestExpires = expires; - } - else { - this.logger.warn("Bad Expires header in a 200-class response to PUBLISH"); - } - } - else { - this.logger.warn("Expires header missing in a 200-class response to PUBLISH"); - } - if (this.pubRequestExpires !== 0) { - // Schedule refresh - this.publishRefreshTimer = setTimeout(function () { return _this.refreshRequest(); }, this.pubRequestExpires * 900); - this.emit("published", response, cause); - } - else { - this.emit("unpublished", response, cause); - } - break; - case /^412$/.test(statusCode.toString()): - // 412 code means no matching ETag - possibly the PUBLISH expired - // Resubmit as new request, if the current request is not a "remove" - if (this.pubRequestEtag !== undefined && this.pubRequestExpires !== 0) { - this.logger.warn("412 response to PUBLISH, recovering"); - this.pubRequestEtag = undefined; - this.emit("progress", response, cause); - this.publish(this.options.body); - } - else { - this.logger.warn("412 response to PUBLISH, recovery failed"); - this.pubRequestExpires = 0; - this.emit("failed", response, cause); - this.emit("unpublished", response, cause); - } - break; - case /^423$/.test(statusCode.toString()): - // 423 code means we need to adjust the Expires interval up - if (this.pubRequestExpires !== 0 && response.hasHeader("Min-Expires")) { - var minExpires = Number(response.getHeader("Min-Expires")); - if (typeof minExpires === "number" || minExpires > this.pubRequestExpires) { - this.logger.warn("423 code in response to PUBLISH, adjusting the Expires value and trying to recover"); - this.pubRequestExpires = minExpires; - this.emit("progress", response, cause); - this.publish(this.options.body); - } - else { - this.logger.warn("Bad 423 response Min-Expires header received for PUBLISH"); - this.pubRequestExpires = 0; - this.emit("failed", response, cause); - this.emit("unpublished", response, cause); - } - } - else { - this.logger.warn("423 response to PUBLISH, recovery failed"); - this.pubRequestExpires = 0; - this.emit("failed", response, cause); - this.emit("unpublished", response, cause); - } - break; - default: - this.pubRequestExpires = 0; - this.emit("failed", response, cause); - this.emit("unpublished", response, cause); - break; - } - // Do the cleanup - if (this.pubRequestExpires === 0) { - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - this.pubRequestBody = undefined; - this.pubRequestEtag = undefined; - } - }; - PublishContext.prototype.send = function () { - var _this = this; - this.ua.userAgentCore.publish(this.request, { - onAccept: function (response) { return _this.receiveResponse(response.message); }, - onProgress: function (response) { return _this.receiveResponse(response.message); }, - onRedirect: function (response) { return _this.receiveResponse(response.message); }, - onReject: function (response) { return _this.receiveResponse(response.message); }, - onTrying: function (response) { return _this.receiveResponse(response.message); } - }); - return this; - }; - PublishContext.prototype.refreshRequest = function () { - // Clean up before the run - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - // This is Refresh request - this.pubRequestBody = undefined; - if (this.pubRequestEtag === undefined) { - // Request not valid - throw new Exceptions_1.Exceptions.MethodParameterError("Publish", "Body", undefined); - } - if (this.pubRequestExpires === 0) { - // Request not valid - throw new Exceptions_1.Exceptions.MethodParameterError("Publish", "Expire", this.pubRequestExpires); - } - this.sendPublishRequest(); - }; - PublishContext.prototype.sendPublishRequest = function () { - var reqOptions = Object.create(this.options || Object.prototype); - reqOptions.extraHeaders = (this.options.extraHeaders || []).slice(); - reqOptions.extraHeaders.push("Event: " + this.event); - reqOptions.extraHeaders.push("Expires: " + this.pubRequestExpires); - if (this.pubRequestEtag !== undefined) { - reqOptions.extraHeaders.push("SIP-If-Match: " + this.pubRequestEtag); - } - var ruri = this.target instanceof core_1.URI ? this.target : this.ua.normalizeTarget(this.target); - if (!ruri) { - throw new Error("ruri undefined."); - } - var params = this.options.params || {}; - var bodyObj; - if (this.pubRequestBody !== undefined) { - bodyObj = { - body: this.pubRequestBody, - contentType: this.options.contentType - }; - } - var body; - if (bodyObj) { - body = Utils_1.Utils.fromBodyObj(bodyObj); - } - this.request = this.ua.userAgentCore.makeOutgoingRequestMessage(Constants_1.C.PUBLISH, ruri, params.fromUri ? params.fromUri : this.ua.userAgentCore.configuration.aor, params.toUri ? params.toUri : this.target, params, reqOptions.extraHeaders, body); - this.send(); - }; - return PublishContext; -}(ClientContext_1.ClientContext)); -exports.PublishContext = PublishContext; - - -/***/ }), -/* 87 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var ClientContext_1 = __webpack_require__(79); -var Constants_1 = __webpack_require__(80); -var core_1 = __webpack_require__(2); -var Enums_1 = __webpack_require__(82); -var Exceptions_1 = __webpack_require__(84); -var ServerContext_1 = __webpack_require__(88); -// tslint:disable-next-line:max-classes-per-file -var ReferClientContext = /** @class */ (function (_super) { - tslib_1.__extends(ReferClientContext, _super); - function ReferClientContext(ua, applicant, target, options) { - if (options === void 0) { options = {}; } - var _this = this; - if (ua === undefined || applicant === undefined || target === undefined) { - throw new TypeError("Not enough arguments"); - } - _this = _super.call(this, ua, Constants_1.C.REFER, applicant.remoteIdentity.uri.toString(), options) || this; - _this.type = Enums_1.TypeStrings.ReferClientContext; - _this.options = options; - _this.extraHeaders = (_this.options.extraHeaders || []).slice(); - _this.applicant = applicant; - _this.target = _this.initReferTo(target); - if (_this.ua) { - _this.extraHeaders.push("Referred-By: <" + _this.ua.configuration.uri + ">"); - } - // TODO: Check that this is correct isc/icc - _this.extraHeaders.push("Contact: " + applicant.contact); - // this is UA.C.ALLOWED_METHODS, removed to get around circular dependency - _this.extraHeaders.push("Allow: " + [ - "ACK", - "CANCEL", - "INVITE", - "MESSAGE", - "BYE", - "OPTIONS", - "INFO", - "NOTIFY", - "REFER" - ].toString()); - _this.extraHeaders.push("Refer-To: " + _this.target); - _this.errorListener = _this.onTransportError.bind(_this); - if (ua.transport) { - ua.transport.on("transportError", _this.errorListener); - } - return _this; - } - ReferClientContext.prototype.refer = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - var extraHeaders = (this.extraHeaders || []).slice(); - if (options.extraHeaders) { - extraHeaders.concat(options.extraHeaders); - } - this.applicant.sendRequest(Constants_1.C.REFER, { - extraHeaders: this.extraHeaders, - receiveResponse: function (response) { - var statusCode = response && response.statusCode ? response.statusCode.toString() : ""; - if (/^1[0-9]{2}$/.test(statusCode)) { - _this.emit("referRequestProgress", _this); - } - else if (/^2[0-9]{2}$/.test(statusCode)) { - _this.emit("referRequestAccepted", _this); - } - else if (/^[4-6][0-9]{2}$/.test(statusCode)) { - _this.emit("referRequestRejected", _this); - } - if (options.receiveResponse) { - options.receiveResponse(response); - } - } - }); - return this; - }; - ReferClientContext.prototype.receiveNotify = function (request) { - // If we can correctly handle this, then we need to send a 200 OK! - var contentType = request.message.hasHeader("Content-Type") ? - request.message.getHeader("Content-Type") : undefined; - if (contentType && contentType.search(/^message\/sipfrag/) !== -1) { - var messageBody = core_1.Grammar.parse(request.message.body, "sipfrag"); - if (messageBody === -1) { - request.reject({ - statusCode: 489, - reasonPhrase: "Bad Event" - }); - return; - } - switch (true) { - case (/^1[0-9]{2}$/.test(messageBody.status_code)): - this.emit("referProgress", this); - break; - case (/^2[0-9]{2}$/.test(messageBody.status_code)): - this.emit("referAccepted", this); - if (!this.options.activeAfterTransfer && this.applicant.terminate) { - this.applicant.terminate(); - } - break; - default: - this.emit("referRejected", this); - break; - } - request.accept(); - this.emit("notify", request.message); - return; - } - request.reject({ - statusCode: 489, - reasonPhrase: "Bad Event" - }); - }; - ReferClientContext.prototype.initReferTo = function (target) { - var stringOrURI; - if (typeof target === "string") { - // REFER without Replaces (Blind Transfer) - var targetString = core_1.Grammar.parse(target, "Refer_To"); - stringOrURI = targetString && targetString.uri ? targetString.uri : target; - // Check target validity - var targetUri = this.ua.normalizeTarget(target); - if (!targetUri) { - throw new TypeError("Invalid target: " + target); - } - stringOrURI = targetUri; - } - else { - // REFER with Replaces (Attended Transfer) - if (!target.session) { - throw new Error("Session undefined."); - } - var displayName = target.remoteIdentity.friendlyName; - var remoteTarget = target.session.remoteTarget.toString(); - var callId = target.session.callId; - var remoteTag = target.session.remoteTag; - var localTag = target.session.localTag; - var replaces = encodeURIComponent(callId + ";to-tag=" + remoteTag + ";from-tag=" + localTag); - stringOrURI = "\"" + displayName + "\" <" + remoteTarget + "?Replaces=" + replaces + ">"; - } - return stringOrURI; - }; - return ReferClientContext; -}(ClientContext_1.ClientContext)); -exports.ReferClientContext = ReferClientContext; -// tslint:disable-next-line:max-classes-per-file -var ReferServerContext = /** @class */ (function (_super) { - tslib_1.__extends(ReferServerContext, _super); - function ReferServerContext(ua, incomingRequest, session) { - var _this = _super.call(this, ua, incomingRequest) || this; - _this.session = session; - _this.type = Enums_1.TypeStrings.ReferServerContext; - _this.ua = ua; - _this.status = Enums_1.SessionStatus.STATUS_INVITE_RECEIVED; - _this.fromTag = _this.request.fromTag; - _this.id = _this.request.callId + _this.fromTag; - _this.contact = _this.ua.contact.toString(); - _this.logger = ua.getLogger("sip.referservercontext", _this.id); - // Needed to send the NOTIFY's - _this.cseq = Math.floor(Math.random() * 10000); - _this.callId = _this.request.callId; - _this.fromUri = _this.request.to.uri; - _this.fromTag = _this.request.to.parameters.tag; - _this.remoteTarget = _this.request.headers.Contact[0].parsed.uri; - _this.toUri = _this.request.from.uri; - _this.toTag = _this.request.fromTag; - _this.routeSet = _this.request.getHeaders("record-route"); - // RFC 3515 2.4.1 - if (!_this.request.hasHeader("refer-to")) { - _this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting refer."); - _this.reject(); - return _this; - } - _this.referTo = _this.request.parseHeader("refer-to"); - // TODO: Must set expiration timer and send 202 if there is no response by then - _this.referredSession = _this.ua.findSession(_this.request); - if (_this.request.hasHeader("referred-by")) { - _this.referredBy = _this.request.getHeader("referred-by"); - } - if (_this.referTo.uri.hasHeader("replaces")) { - _this.replaces = _this.referTo.uri.getHeader("replaces"); - } - _this.errorListener = _this.onTransportError.bind(_this); - if (ua.transport) { - ua.transport.on("transportError", _this.errorListener); - } - _this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER; - return _this; - } - ReferServerContext.prototype.progress = function () { - if (this.status !== Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER) { - throw new Exceptions_1.Exceptions.InvalidStateError(this.status); - } - this.incomingRequest.trying(); - }; - ReferServerContext.prototype.reject = function (options) { - if (options === void 0) { options = {}; } - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - throw new Exceptions_1.Exceptions.InvalidStateError(this.status); - } - this.logger.log("Rejecting refer"); - this.status = Enums_1.SessionStatus.STATUS_TERMINATED; - _super.prototype.reject.call(this, options); - this.emit("referRequestRejected", this); - }; - ReferServerContext.prototype.accept = function (options, modifiers) { - var _this = this; - if (options === void 0) { options = {}; } - if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER) { - this.status = Enums_1.SessionStatus.STATUS_ANSWERED; - } - else { - throw new Exceptions_1.Exceptions.InvalidStateError(this.status); - } - this.incomingRequest.accept({ - statusCode: 202, - reasonPhrase: "Accepted" - }); - this.emit("referRequestAccepted", this); - if (options.followRefer) { - this.logger.log("Accepted refer, attempting to automatically follow it"); - var target = this.referTo.uri; - if (!target.scheme || !target.scheme.match("^sips?$")) { - this.logger.error("SIP.js can only automatically follow SIP refer target"); - this.reject(); - return; - } - var inviteOptions = options.inviteOptions || {}; - var extraHeaders = (inviteOptions.extraHeaders || []).slice(); - if (this.replaces) { - // decodeURIComponent is a holdover from 2c086eb4. Not sure that it is actually necessary - extraHeaders.push("Replaces: " + decodeURIComponent(this.replaces)); - } - if (this.referredBy) { - extraHeaders.push("Referred-By: " + this.referredBy); - } - inviteOptions.extraHeaders = extraHeaders; - target.clearHeaders(); - this.targetSession = this.ua.invite(target.toString(), inviteOptions, modifiers); - this.emit("referInviteSent", this); - if (this.targetSession) { - this.targetSession.once("progress", function (response) { - var statusCode = response.statusCode || 100; - var reasonPhrase = response.reasonPhrase; - _this.sendNotify(("SIP/2.0 " + statusCode + " " + reasonPhrase).trim()); - _this.emit("referProgress", _this); - if (_this.referredSession) { - _this.referredSession.emit("referProgress", _this); - } - }); - this.targetSession.once("accepted", function () { - _this.logger.log("Successfully followed the refer"); - _this.sendNotify("SIP/2.0 200 OK"); - _this.emit("referAccepted", _this); - if (_this.referredSession) { - _this.referredSession.emit("referAccepted", _this); - } - }); - var referFailed = function (response) { - if (_this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return; // No throw here because it is possible this gets called multiple times - } - _this.logger.log("Refer was not successful. Resuming session"); - if (response && response.statusCode === 429) { - _this.logger.log("Alerting referrer that identity is required."); - _this.sendNotify("SIP/2.0 429 Provide Referrer Identity"); - return; - } - _this.sendNotify("SIP/2.0 603 Declined"); - // Must change the status after sending the final Notify or it will not send due to check - _this.status = Enums_1.SessionStatus.STATUS_TERMINATED; - _this.emit("referRejected", _this); - if (_this.referredSession) { - _this.referredSession.emit("referRejected"); - } - }; - this.targetSession.once("rejected", referFailed); - this.targetSession.once("failed", referFailed); - } - } - else { - this.logger.log("Accepted refer, but did not automatically follow it"); - this.sendNotify("SIP/2.0 200 OK"); - this.emit("referAccepted", this); - if (this.referredSession) { - this.referredSession.emit("referAccepted", this); - } - } - }; - ReferServerContext.prototype.sendNotify = function (bodyStr) { - // FIXME: Ported this. Clean it up. Session knows its state. - if (this.status !== Enums_1.SessionStatus.STATUS_ANSWERED) { - throw new Exceptions_1.Exceptions.InvalidStateError(this.status); - } - if (core_1.Grammar.parse(bodyStr, "sipfrag") === -1) { - throw new Error("sipfrag body is required to send notify for refer"); - } - var body = { - contentDisposition: "render", - contentType: "message/sipfrag", - content: bodyStr - }; - // NOTIFY requests sent in same dialog as in dialog REFER. - if (this.session) { - this.session.notify(undefined, { - extraHeaders: [ - "Event: refer", - "Subscription-State: terminated", - ], - body: body - }); - return; - } - // The implicit subscription created by a REFER is the same as a - // subscription created with a SUBSCRIBE request. The agent issuing the - // REFER can terminate this subscription prematurely by unsubscribing - // using the mechanisms described in [2]. Terminating a subscription, - // either by explicitly unsubscribing or rejecting NOTIFY, is not an - // indication that the referenced request should be withdrawn or - // abandoned. - // https://tools.ietf.org/html/rfc3515#section-2.4.4 - // NOTIFY requests sent in new dialog for out of dialog REFER. - // FIXME: TODO: This should be done in a subscribe dialog to satisfy the above. - var request = this.ua.userAgentCore.makeOutgoingRequestMessage(Constants_1.C.NOTIFY, this.remoteTarget, this.fromUri, this.toUri, { - cseq: this.cseq += 1, - callId: this.callId, - fromTag: this.fromTag, - toTag: this.toTag, - routeSet: this.routeSet - }, [ - "Event: refer", - "Subscription-State: terminated", - "Content-Type: message/sipfrag" - ], body); - var transport = this.ua.transport; - if (!transport) { - throw new Error("Transport undefined."); - } - var user = { - loggerFactory: this.ua.getLoggerFactory() - }; - var nic = new core_1.NonInviteClientTransaction(request, transport, user); - }; - ReferServerContext.prototype.on = function (name, callback) { return _super.prototype.on.call(this, name, callback); }; - return ReferServerContext; -}(ServerContext_1.ServerContext)); -exports.ReferServerContext = ReferServerContext; - - -/***/ }), -/* 88 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var events_1 = __webpack_require__(30); -var Constants_1 = __webpack_require__(80); -var core_1 = __webpack_require__(2); -var Enums_1 = __webpack_require__(82); -var Utils_1 = __webpack_require__(83); -var ServerContext = /** @class */ (function (_super) { - tslib_1.__extends(ServerContext, _super); - function ServerContext(ua, incomingRequest) { - var _this = _super.call(this) || this; - _this.incomingRequest = incomingRequest; - _this.data = {}; - ServerContext.initializer(_this, ua, incomingRequest); - return _this; - } - // hack to get around our multiple inheritance issues - ServerContext.initializer = function (objectToConstruct, ua, incomingRequest) { - var request = incomingRequest.message; - objectToConstruct.type = Enums_1.TypeStrings.ServerContext; - objectToConstruct.ua = ua; - objectToConstruct.logger = ua.getLogger("sip.servercontext"); - objectToConstruct.request = request; - if (request.body) { - objectToConstruct.body = request.body; - } - if (request.hasHeader("Content-Type")) { - objectToConstruct.contentType = request.getHeader("Content-Type"); - } - objectToConstruct.method = request.method; - objectToConstruct.localIdentity = request.to; - objectToConstruct.remoteIdentity = request.from; - var hasAssertedIdentity = request.hasHeader("P-Asserted-Identity"); - if (hasAssertedIdentity) { - var assertedIdentity = request.getHeader("P-Asserted-Identity"); - if (assertedIdentity) { - objectToConstruct.assertedIdentity = core_1.Grammar.nameAddrHeaderParse(assertedIdentity); - } - } - }; - ServerContext.prototype.progress = function (options) { - if (options === void 0) { options = {}; } - options.statusCode = options.statusCode || 180; - options.minCode = 100; - options.maxCode = 199; - options.events = ["progress"]; - return this.reply(options); - }; - ServerContext.prototype.accept = function (options) { - if (options === void 0) { options = {}; } - options.statusCode = options.statusCode || 200; - options.minCode = 200; - options.maxCode = 299; - options.events = ["accepted"]; - return this.reply(options); - }; - ServerContext.prototype.reject = function (options) { - if (options === void 0) { options = {}; } - options.statusCode = options.statusCode || 480; - options.minCode = 300; - options.maxCode = 699; - options.events = ["rejected", "failed"]; - return this.reply(options); - }; - ServerContext.prototype.reply = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - var statusCode = options.statusCode || 100; - var minCode = options.minCode || 100; - var maxCode = options.maxCode || 699; - var reasonPhrase = Utils_1.Utils.getReasonPhrase(statusCode, options.reasonPhrase); - var extraHeaders = options.extraHeaders || []; - var body = options.body ? core_1.fromBodyLegacy(options.body) : undefined; - var events = options.events || []; - if (statusCode < minCode || statusCode > maxCode) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - var responseOptions = { - statusCode: statusCode, - reasonPhrase: reasonPhrase, - extraHeaders: extraHeaders, - body: body - }; - var response; - var statusCodeString = statusCode.toString(); - switch (true) { - case /^100$/.test(statusCodeString): - response = this.incomingRequest.trying(responseOptions).message; - break; - case /^1[0-9]{2}$/.test(statusCodeString): - response = this.incomingRequest.progress(responseOptions).message; - break; - case /^2[0-9]{2}$/.test(statusCodeString): - response = this.incomingRequest.accept(responseOptions).message; - break; - case /^3[0-9]{2}$/.test(statusCodeString): - response = this.incomingRequest.redirect([], responseOptions).message; - break; - case /^[4-6][0-9]{2}$/.test(statusCodeString): - response = this.incomingRequest.reject(responseOptions).message; - break; - default: - throw new Error("Invalid status code " + statusCode); - } - events.forEach(function (event) { - _this.emit(event, response, reasonPhrase); - }); - return this; - }; - ServerContext.prototype.onRequestTimeout = function () { - this.emit("failed", undefined, Constants_1.C.causes.REQUEST_TIMEOUT); - }; - ServerContext.prototype.onTransportError = function () { - this.emit("failed", undefined, Constants_1.C.causes.CONNECTION_ERROR); - }; - return ServerContext; -}(events_1.EventEmitter)); -exports.ServerContext = ServerContext; - - -/***/ }), -/* 89 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var ClientContext_1 = __webpack_require__(79); -var Constants_1 = __webpack_require__(80); -var core_1 = __webpack_require__(2); -var Enums_1 = __webpack_require__(82); -var Exceptions_1 = __webpack_require__(84); -var Utils_1 = __webpack_require__(83); -/** - * Configuration load. - * @private - * returns {any} - */ -function loadConfig(configuration) { - var settings = { - expires: 600, - extraContactHeaderParams: [], - instanceId: undefined, - params: {}, - regId: undefined, - registrar: undefined, - }; - var configCheck = getConfigurationCheck(); - // Check Mandatory parameters - for (var parameter in configCheck.mandatory) { - if (!configuration.hasOwnProperty(parameter)) { - throw new Exceptions_1.Exceptions.ConfigurationError(parameter); - } - else { - var value = configuration[parameter]; - var checkedValue = configCheck.mandatory[parameter](value); - if (checkedValue !== undefined) { - settings[parameter] = checkedValue; - } - else { - throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); - } - } - } - // Check Optional parameters - for (var parameter in configCheck.optional) { - if (configuration.hasOwnProperty(parameter)) { - var value = configuration[parameter]; - // If the parameter value is an empty array, but shouldn't be, apply its default value. - if (value instanceof Array && value.length === 0) { - continue; - } - // If the parameter value is null, empty string, or undefined then apply its default value. - // If it's a number with NaN value then also apply its default value. - // NOTE: JS does not allow "value === NaN", the following does the work: - if (value === null || value === "" || value === undefined || - (typeof (value) === "number" && isNaN(value))) { - continue; - } - var checkedValue = configCheck.optional[parameter](value); - if (checkedValue !== undefined) { - settings[parameter] = checkedValue; - } - else { - throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); - } - } - } - return settings; -} -function getConfigurationCheck() { - return { - mandatory: {}, - optional: { - expires: function (expires) { - if (Utils_1.Utils.isDecimal(expires)) { - var value = Number(expires); - if (value >= 0) { - return value; - } - } - }, - extraContactHeaderParams: function (extraContactHeaderParams) { - if (extraContactHeaderParams instanceof Array) { - return extraContactHeaderParams.filter(function (contactHeaderParam) { return (typeof contactHeaderParam === "string"); }); - } - }, - instanceId: function (instanceId) { - if (typeof instanceId !== "string") { - return; - } - if ((/^uuid:/i.test(instanceId))) { - instanceId = instanceId.substr(5); - } - if (core_1.Grammar.parse(instanceId, "uuid") === -1) { - return; - } - else { - return instanceId; - } - }, - params: function (params) { - if (typeof params === "object") { - return params; - } - }, - regId: function (regId) { - if (Utils_1.Utils.isDecimal(regId)) { - var value = Number(regId); - if (value >= 0) { - return value; - } - } - }, - registrar: function (registrar) { - if (typeof registrar !== "string") { - return; - } - if (!/^sip:/i.test(registrar)) { - registrar = Constants_1.C.SIP + ":" + registrar; - } - var parsed = core_1.Grammar.URIParse(registrar); - if (!parsed) { - return; - } - else if (parsed.user) { - return; - } - else { - return parsed; - } - } - } - }; -} -var RegisterContext = /** @class */ (function (_super) { - tslib_1.__extends(RegisterContext, _super); - function RegisterContext(ua, options) { - if (options === void 0) { options = {}; } - var _this = this; - var settings = loadConfig(options); - if (settings.regId && !settings.instanceId) { - settings.instanceId = Utils_1.Utils.newUUID(); - } - else if (!settings.regId && settings.instanceId) { - settings.regId = 1; - } - settings.params.toUri = settings.params.toUri || ua.configuration.uri; - settings.params.toDisplayName = settings.params.toDisplayName || ua.configuration.displayName; - settings.params.callId = settings.params.callId || Utils_1.Utils.createRandomToken(22); - settings.params.cseq = settings.params.cseq || Math.floor(Math.random() * 10000); - /* If no 'registrarServer' is set use the 'uri' value without user portion. */ - if (!settings.registrar) { - var registrarServer = {}; - if (typeof ua.configuration.uri === "object") { - registrarServer = ua.configuration.uri.clone(); - registrarServer.user = undefined; - } - else { - registrarServer = ua.configuration.uri; - } - settings.registrar = registrarServer; - } - _this = _super.call(this, ua, Constants_1.C.REGISTER, settings.registrar, settings) || this; - _this.type = Enums_1.TypeStrings.RegisterContext; - _this.options = settings; - _this.logger = ua.getLogger("sip.registercontext"); - _this.logger.log("configuration parameters for RegisterContext after validation:"); - for (var parameter in settings) { - if (settings.hasOwnProperty(parameter)) { - _this.logger.log("· " + parameter + ": " + JSON.stringify(settings[parameter])); - } - } - // Registration expires - _this.expires = settings.expires; - // Contact header - _this.contact = ua.contact.toString(); - // Set status - _this.registered = false; - ua.transport.on("disconnected", function () { return _this.onTransportDisconnected(); }); - return _this; - } - RegisterContext.prototype.register = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - // Handle Options - this.options = tslib_1.__assign({}, this.options, options); - var extraHeaders = (this.options.extraHeaders || []).slice(); - extraHeaders.push("Contact: " + this.generateContactHeader(this.expires)); - // this is UA.C.ALLOWED_METHODS, removed to get around circular dependency - extraHeaders.push("Allow: " + [ - "ACK", - "CANCEL", - "INVITE", - "MESSAGE", - "BYE", - "OPTIONS", - "INFO", - "NOTIFY", - "REFER" - ].toString()); - // Save original extraHeaders to be used in .close - this.closeHeaders = this.options.closeWithHeaders ? - (this.options.extraHeaders || []).slice() : []; - this.receiveResponse = function (response) { - // Discard responses to older REGISTER/un-REGISTER requests. - if (response.cseq !== _this.request.cseq) { - return; - } - // Clear registration timer - if (_this.registrationTimer !== undefined) { - clearTimeout(_this.registrationTimer); - _this.registrationTimer = undefined; - } - var statusCode = (response.statusCode || 0).toString(); - switch (true) { - case /^1[0-9]{2}$/.test(statusCode): - _this.emit("progress", response); - break; - case /^2[0-9]{2}$/.test(statusCode): - _this.emit("accepted", response); - var expires = void 0; - if (response.hasHeader("expires")) { - expires = Number(response.getHeader("expires")); - } - if (_this.registrationExpiredTimer !== undefined) { - clearTimeout(_this.registrationExpiredTimer); - _this.registrationExpiredTimer = undefined; - } - // Search the Contact pointing to us and update the expires value accordingly. - var contacts = response.getHeaders("contact").length; - if (!contacts) { - _this.logger.warn("no Contact header in response to REGISTER, response ignored"); - break; - } - var contact = void 0; - while (contacts--) { - contact = response.parseHeader("contact", contacts); - if (contact.uri.user === _this.ua.contact.uri.user) { - expires = contact.getParam("expires"); - break; - } - else { - contact = undefined; - } - } - if (!contact) { - _this.logger.warn("no Contact header pointing to us, response ignored"); - break; - } - if (expires === undefined) { - expires = _this.expires; - } - // Re-Register before the expiration interval has elapsed. - // For that, decrease the expires value. ie: 3 seconds - _this.registrationTimer = setTimeout(function () { - _this.registrationTimer = undefined; - _this.register(_this.options); - }, (expires * 1000) - 3000); - _this.registrationExpiredTimer = setTimeout(function () { - _this.logger.warn("registration expired"); - if (_this.registered) { - _this.unregistered(undefined, Constants_1.C.causes.EXPIRES); - } - }, expires * 1000); - // Save gruu values - if (contact.hasParam("temp-gruu")) { - _this.ua.contact.tempGruu = core_1.Grammar.URIParse(contact.getParam("temp-gruu").replace(/"/g, "")); - } - if (contact.hasParam("pub-gruu")) { - _this.ua.contact.pubGruu = core_1.Grammar.URIParse(contact.getParam("pub-gruu").replace(/"/g, "")); - } - _this.registered = true; - _this.emit("registered", response || undefined); - break; - // Interval too brief RFC3261 10.2.8 - case /^423$/.test(statusCode): - if (response.hasHeader("min-expires")) { - // Increase our registration interval to the suggested minimum - _this.expires = Number(response.getHeader("min-expires")); - // Attempt the registration again immediately - _this.register(_this.options); - } - else { // This response MUST contain a Min-Expires header field - _this.logger.warn("423 response received for REGISTER without Min-Expires"); - _this.registrationFailure(response, Constants_1.C.causes.SIP_FAILURE_CODE); - } - break; - default: - _this.registrationFailure(response, Utils_1.Utils.sipErrorCause(response.statusCode || 0)); - } - }; - this.onRequestTimeout = function () { - _this.registrationFailure(undefined, Constants_1.C.causes.REQUEST_TIMEOUT); - }; - this.onTransportError = function () { - _this.registrationFailure(undefined, Constants_1.C.causes.CONNECTION_ERROR); - }; - this.request.cseq++; - this.request.setHeader("cseq", this.request.cseq + " REGISTER"); - this.request.extraHeaders = extraHeaders; - this.send(); - }; - RegisterContext.prototype.close = function () { - var options = { - all: false, - extraHeaders: this.closeHeaders - }; - this.registeredBefore = this.registered; - if (this.registered) { - this.unregister(options); - } - }; - RegisterContext.prototype.unregister = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - if (!this.registered && !options.all) { - this.logger.warn("Already unregistered, but sending an unregister anyways."); - } - var extraHeaders = (options.extraHeaders || []).slice(); - this.registered = false; - // Clear the registration timer. - if (this.registrationTimer !== undefined) { - clearTimeout(this.registrationTimer); - this.registrationTimer = undefined; - } - if (options.all) { - extraHeaders.push("Contact: *"); - extraHeaders.push("Expires: 0"); - } - else { - extraHeaders.push("Contact: " + this.generateContactHeader(0)); - } - this.receiveResponse = function (response) { - var statusCode = (response && response.statusCode) ? response.statusCode.toString() : ""; - switch (true) { - case /^1[0-9]{2}$/.test(statusCode): - _this.emit("progress", response); - break; - case /^2[0-9]{2}$/.test(statusCode): - _this.emit("accepted", response); - if (_this.registrationExpiredTimer !== undefined) { - clearTimeout(_this.registrationExpiredTimer); - _this.registrationExpiredTimer = undefined; - } - _this.unregistered(response); - break; - default: - _this.unregistered(response, Utils_1.Utils.sipErrorCause(response.statusCode || 0)); - } - }; - this.onRequestTimeout = function () { - // Not actually unregistered... - // this.unregistered(undefined, SIP.C.causes.REQUEST_TIMEOUT); - }; - this.request.cseq++; - this.request.setHeader("cseq", this.request.cseq + " REGISTER"); - this.request.extraHeaders = extraHeaders; - this.send(); - }; - RegisterContext.prototype.unregistered = function (response, cause) { - this.registered = false; - this.emit("unregistered", response || undefined, cause || undefined); - }; - RegisterContext.prototype.send = function () { - var _this = this; - this.ua.userAgentCore.register(this.request, { - onAccept: function (response) { return _this.receiveResponse(response.message); }, - onProgress: function (response) { return _this.receiveResponse(response.message); }, - onRedirect: function (response) { return _this.receiveResponse(response.message); }, - onReject: function (response) { return _this.receiveResponse(response.message); }, - onTrying: function (response) { return _this.receiveResponse(response.message); } - }); - return this; - }; - RegisterContext.prototype.registrationFailure = function (response, cause) { - this.emit("failed", response || undefined, cause || undefined); - }; - RegisterContext.prototype.onTransportDisconnected = function () { - this.registeredBefore = this.registered; - if (this.registrationTimer !== undefined) { - clearTimeout(this.registrationTimer); - this.registrationTimer = undefined; - } - if (this.registrationExpiredTimer !== undefined) { - clearTimeout(this.registrationExpiredTimer); - this.registrationExpiredTimer = undefined; - } - if (this.registered) { - this.unregistered(undefined, Constants_1.C.causes.CONNECTION_ERROR); - } - }; - /** - * Helper Function to generate Contact Header - * @private - * returns {String} - */ - RegisterContext.prototype.generateContactHeader = function (expires) { - if (expires === void 0) { expires = 0; } - var contact = this.contact; - if (this.options.regId && this.options.instanceId) { - contact += ";reg-id=" + this.options.regId; - contact += ';+sip.instance=""'; - } - if (this.options.extraContactHeaderParams) { - this.options.extraContactHeaderParams.forEach(function (header) { - contact += ";" + header; - }); - } - contact += ";expires=" + expires; - return contact; - }; - return RegisterContext; -}(ClientContext_1.ClientContext)); -exports.RegisterContext = RegisterContext; - - -/***/ }), -/* 90 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var events_1 = __webpack_require__(30); -var ClientContext_1 = __webpack_require__(79); -var Constants_1 = __webpack_require__(80); -var core_1 = __webpack_require__(2); -var Enums_1 = __webpack_require__(82); -var Exceptions_1 = __webpack_require__(84); -var ReferContext_1 = __webpack_require__(87); -var ServerContext_1 = __webpack_require__(88); -var DTMF_1 = __webpack_require__(91); -var Utils_1 = __webpack_require__(83); -/* - * @param {function returning SIP.sessionDescriptionHandler} [sessionDescriptionHandlerFactory] - * (See the documentation for the sessionDescriptionHandlerFactory argument of the UA constructor.) - */ -var Session = /** @class */ (function (_super) { - tslib_1.__extends(Session, _super); - function Session(sessionDescriptionHandlerFactory) { - var _this = _super.call(this) || this; - _this.data = {}; - _this.type = Enums_1.TypeStrings.Session; - if (!sessionDescriptionHandlerFactory) { - throw new Exceptions_1.Exceptions.SessionDescriptionHandlerError("A session description handler is required for the session to function"); - } - _this.status = Session.C.STATUS_NULL; - _this.pendingReinvite = false; - _this.sessionDescriptionHandlerFactory = sessionDescriptionHandlerFactory; - _this.hasOffer = false; - _this.hasAnswer = false; - // Session Timers - _this.timers = { - ackTimer: undefined, - expiresTimer: undefined, - invite2xxTimer: undefined, - userNoAnswerTimer: undefined, - rel1xxTimer: undefined, - prackTimer: undefined - }; - // Session info - _this.startTime = undefined; - _this.endTime = undefined; - _this.tones = undefined; - // Hold state - _this.localHold = false; - _this.earlySdp = undefined; - _this.rel100 = Constants_1.C.supported.UNSUPPORTED; - return _this; - } - Session.prototype.dtmf = function (tones, options) { - var _this = this; - if (options === void 0) { options = {}; } - // Check Session Status - if (this.status !== Enums_1.SessionStatus.STATUS_CONFIRMED && this.status !== Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK) { - throw new Exceptions_1.Exceptions.InvalidStateError(this.status); - } - // Check tones - if (!tones || !tones.toString().match(/^[0-9A-D#*,]+$/i)) { - throw new TypeError("Invalid tones: " + tones); - } - var sendDTMF = function () { - if (_this.status === Enums_1.SessionStatus.STATUS_TERMINATED || !_this.tones || _this.tones.length === 0) { - // Stop sending DTMF - _this.tones = undefined; - return; - } - var dtmf = _this.tones.shift(); - var timeout; - if (dtmf.tone === ",") { - timeout = 2000; - } - else { - dtmf.on("failed", function () { _this.tones = undefined; }); - dtmf.send(options); - timeout = dtmf.duration + dtmf.interToneGap; - } - // Set timeout for the next tone - setTimeout(sendDTMF, timeout); - }; - tones = tones.toString(); - var dtmfType = this.ua.configuration.dtmfType; - if (this.sessionDescriptionHandler && dtmfType === Constants_1.C.dtmfType.RTP) { - var sent = this.sessionDescriptionHandler.sendDtmf(tones, options); - if (!sent) { - this.logger.warn("Attempt to use dtmfType 'RTP' has failed, falling back to INFO packet method"); - dtmfType = Constants_1.C.dtmfType.INFO; - } - } - if (dtmfType === Constants_1.C.dtmfType.INFO) { - var dtmfs = []; - var tonesArray = tones.split(""); - while (tonesArray.length > 0) { - dtmfs.push(new DTMF_1.DTMF(this, tonesArray.shift(), options)); - } - if (this.tones) { - // Tones are already queued, just add to the queue - this.tones = this.tones.concat(dtmfs); - return this; - } - this.tones = dtmfs; - sendDTMF(); - } - return this; - }; - Session.prototype.bye = function (options) { - if (options === void 0) { options = {}; } - // Check Session Status - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - this.logger.error("Error: Attempted to send BYE in a terminated session."); - return this; - } - this.logger.log("terminating Session"); - var statusCode = options.statusCode; - if (statusCode && (statusCode < 200 || statusCode >= 700)) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - options.receiveResponse = function () { }; - return this.sendRequest(Constants_1.C.BYE, options).terminated(); - }; - Session.prototype.refer = function (target, options) { - if (options === void 0) { options = {}; } - // Check Session Status - if (this.status !== Enums_1.SessionStatus.STATUS_CONFIRMED) { - throw new Exceptions_1.Exceptions.InvalidStateError(this.status); - } - this.referContext = new ReferContext_1.ReferClientContext(this.ua, this, target, options); - this.emit("referRequested", this.referContext); - this.referContext.refer(options); - return this.referContext; - }; - /** - * Sends in dialog request. - * @param method Request method. - * @param options Options bucket. - */ - Session.prototype.sendRequest = function (method, options) { - if (options === void 0) { options = {}; } - if (!this.session) { - throw new Error("Session undefined."); - } - // Convert any "body" option to a Body. - if (options.body) { - options.body = Utils_1.Utils.fromBodyObj(options.body); - } - // Convert any "receiveResponse" callback option passed to an OutgoingRequestDelegate. - var delegate; - var callback = options.receiveResponse; - if (callback) { - delegate = { - onAccept: function (response) { return callback(response.message); }, - onProgress: function (response) { return callback(response.message); }, - onRedirect: function (response) { return callback(response.message); }, - onReject: function (response) { return callback(response.message); }, - onTrying: function (response) { return callback(response.message); } - }; - } - var request; - var requestOptions = options; - switch (method) { - case Constants_1.C.BYE: - request = this.session.bye(delegate, requestOptions); - break; - case Constants_1.C.INVITE: - request = this.session.invite(delegate, requestOptions); - break; - case Constants_1.C.REFER: - request = this.session.refer(delegate, requestOptions); - break; - default: - throw new Error("Unexpected " + method + ". Method not implemented by user agent core."); - } - // Ported - Emit the request event - this.emit(method.toLowerCase(), request.message); - return this; - }; - Session.prototype.close = function () { - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return this; - } - this.logger.log("closing INVITE session " + this.id); - // 1st Step. Terminate media. - if (this.sessionDescriptionHandler) { - this.sessionDescriptionHandler.close(); - } - // 2nd Step. Terminate signaling. - // Clear session timers - for (var timer in this.timers) { - if (this.timers[timer]) { - clearTimeout(this.timers[timer]); - } - } - this.status = Enums_1.SessionStatus.STATUS_TERMINATED; - if (this.ua.transport) { - this.ua.transport.removeListener("transportError", this.errorListener); - } - delete this.ua.sessions[this.id]; - return this; - }; - Session.prototype.hold = function (options, modifiers) { - if (options === void 0) { options = {}; } - if (modifiers === void 0) { modifiers = []; } - if (this.status !== Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK && this.status !== Enums_1.SessionStatus.STATUS_CONFIRMED) { - throw new Exceptions_1.Exceptions.InvalidStateError(this.status); - } - if (this.localHold) { - this.logger.log("Session is already on hold, cannot put it on hold again"); - return; - } - options.modifiers = modifiers; - if (this.sessionDescriptionHandler) { - options.modifiers.push(this.sessionDescriptionHandler.holdModifier); - } - this.localHold = true; - this.sendReinvite(options); - }; - Session.prototype.unhold = function (options, modifiers) { - if (options === void 0) { options = {}; } - if (modifiers === void 0) { modifiers = []; } - if (this.status !== Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK && this.status !== Enums_1.SessionStatus.STATUS_CONFIRMED) { - throw new Exceptions_1.Exceptions.InvalidStateError(this.status); - } - if (!this.localHold) { - this.logger.log("Session is not on hold, cannot unhold it"); - return; - } - options.modifiers = modifiers; - this.localHold = false; - this.sendReinvite(options); - }; - Session.prototype.reinvite = function (options, modifiers) { - if (options === void 0) { options = {}; } - if (modifiers === void 0) { modifiers = []; } - options.modifiers = modifiers; - return this.sendReinvite(options); - }; - Session.prototype.terminate = function (options) { - // here for types and to be overridden - return this; - }; - Session.prototype.onTransportError = function () { - if (this.status !== Enums_1.SessionStatus.STATUS_CONFIRMED && this.status !== Enums_1.SessionStatus.STATUS_TERMINATED) { - this.failed(undefined, Constants_1.C.causes.CONNECTION_ERROR); - } - }; - Session.prototype.onRequestTimeout = function () { - if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { - this.terminated(undefined, Constants_1.C.causes.REQUEST_TIMEOUT); - } - else if (this.status !== Enums_1.SessionStatus.STATUS_TERMINATED) { - this.failed(undefined, Constants_1.C.causes.REQUEST_TIMEOUT); - this.terminated(undefined, Constants_1.C.causes.REQUEST_TIMEOUT); - } - }; - Session.prototype.onDialogError = function (response) { - if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { - this.terminated(response, Constants_1.C.causes.DIALOG_ERROR); - } - else if (this.status !== Enums_1.SessionStatus.STATUS_TERMINATED) { - this.failed(response, Constants_1.C.causes.DIALOG_ERROR); - this.terminated(response, Constants_1.C.causes.DIALOG_ERROR); - } - }; - Session.prototype.on = function (name, callback) { - return _super.prototype.on.call(this, name, callback); - }; - Session.prototype.onAck = function (incomingRequest) { - var _this = this; - var confirmSession = function () { - clearTimeout(_this.timers.ackTimer); - clearTimeout(_this.timers.invite2xxTimer); - _this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; - var contentDisp = incomingRequest.message.getHeader("Content-Disposition"); - if (contentDisp && contentDisp.type === "render") { - _this.renderbody = incomingRequest.message.body; - _this.rendertype = incomingRequest.message.getHeader("Content-Type"); - } - _this.emit("confirmed", incomingRequest.message); - }; - if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK) { - if (this.sessionDescriptionHandler && - this.sessionDescriptionHandler.hasDescription(incomingRequest.message.getHeader("Content-Type") || "")) { - this.hasAnswer = true; - this.sessionDescriptionHandler.setDescription(incomingRequest.message.body, this.sessionDescriptionHandlerOptions, this.modifiers).catch(function (e) { - _this.logger.warn(e); - _this.terminate({ - statusCode: "488", - reasonPhrase: "Bad Media Description" - }); - _this.failed(incomingRequest.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - _this.terminated(incomingRequest.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - throw e; - }).then(function () { return confirmSession(); }); - } - else { - confirmSession(); - } - } - }; - Session.prototype.receiveRequest = function (incomingRequest) { - switch (incomingRequest.message.method) { // TODO: This needs a default case - case Constants_1.C.BYE: - incomingRequest.accept(); - if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { - this.emit("bye", incomingRequest.message); - this.terminated(incomingRequest.message, Constants_1.C.BYE); - } - break; - case Constants_1.C.INVITE: - if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { - this.logger.log("re-INVITE received"); - this.receiveReinvite(incomingRequest); - } - break; - case Constants_1.C.INFO: - if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED || this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK) { - if (this.onInfo) { - return this.onInfo(incomingRequest.message); - } - var contentType = incomingRequest.message.getHeader("content-type"); - if (contentType) { - if (contentType.match(/^application\/dtmf-relay/i)) { - if (incomingRequest.message.body) { - var body = incomingRequest.message.body.split("\r\n", 2); - if (body.length === 2) { - var tone = void 0; - var duration = void 0; - var regTone = /^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/; - if (regTone.test(body[0])) { - tone = body[0].replace(regTone, "$2"); - } - var regDuration = /^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/; - if (regDuration.test(body[1])) { - duration = parseInt(body[1].replace(regDuration, "$2"), 10); - } - if (tone && duration) { - new DTMF_1.DTMF(this, tone, { duration: duration }).init_incoming(incomingRequest); - } - } - } - } - else { - incomingRequest.reject({ - statusCode: 415, - extraHeaders: ["Accept: application/dtmf-relay"] - }); - } - } - } - break; - case Constants_1.C.REFER: - if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { - this.logger.log("REFER received"); - this.referContext = new ReferContext_1.ReferServerContext(this.ua, incomingRequest, this.session); - if (this.listeners("referRequested").length) { - this.emit("referRequested", this.referContext); - } - else { - this.logger.log("No referRequested listeners, automatically accepting and following the refer"); - var options = { followRefer: true }; - if (this.passedOptions) { - options.inviteOptions = this.passedOptions; - } - this.referContext.accept(options, this.modifiers); - } - } - break; - case Constants_1.C.NOTIFY: - if (this.referContext && - this.referContext.type === Enums_1.TypeStrings.ReferClientContext && - incomingRequest.message.hasHeader("event") && - /^refer(;.*)?$/.test(incomingRequest.message.getHeader("event"))) { - this.referContext.receiveNotify(incomingRequest); - return; - } - incomingRequest.accept(); - this.emit("notify", incomingRequest.message); - break; - } - }; - // In dialog INVITE Reception - Session.prototype.receiveReinvite = function (incomingRequest) { - // TODO: Should probably check state of the session - var _this = this; - this.emit("reinvite", this, incomingRequest.message); - if (incomingRequest.message.hasHeader("P-Asserted-Identity")) { - this.assertedIdentity = - core_1.Grammar.nameAddrHeaderParse(incomingRequest.message.getHeader("P-Asserted-Identity")); - } - var promise; - if (!this.sessionDescriptionHandler) { - this.logger.warn("No SessionDescriptionHandler to reinvite"); - return; - } - if (incomingRequest.message.getHeader("Content-Length") === "0" && - !incomingRequest.message.getHeader("Content-Type")) { // Invite w/o SDP - promise = this.sessionDescriptionHandler.getDescription(this.sessionDescriptionHandlerOptions, this.modifiers); - } - else if (this.sessionDescriptionHandler.hasDescription(incomingRequest.message.getHeader("Content-Type") || "")) { - // Invite w/ SDP - promise = this.sessionDescriptionHandler.setDescription(incomingRequest.message.body, this.sessionDescriptionHandlerOptions, this.modifiers).then(this.sessionDescriptionHandler.getDescription.bind(this.sessionDescriptionHandler, this.sessionDescriptionHandlerOptions, this.modifiers)); - } - else { // Bad Packet (should never get hit) - incomingRequest.reject({ statusCode: 415 }); - this.emit("reinviteFailed", this); - return; - } - promise.catch(function (e) { - var statusCode; - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - statusCode = 500; - } - else if (e.type === Enums_1.TypeStrings.RenegotiationError) { - _this.emit("renegotiationError", e); - _this.logger.warn(e.toString()); - statusCode = 488; - } - else { - _this.logger.error(e); - statusCode = 488; - } - incomingRequest.reject({ statusCode: statusCode }); - _this.emit("reinviteFailed", _this); - // TODO: This could be better - throw e; - }).then(function (description) { - var extraHeaders = ["Contact: " + _this.contact]; - incomingRequest.accept({ - statusCode: 200, - extraHeaders: extraHeaders, - body: Utils_1.Utils.fromBodyObj(description) - }); - _this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK; - _this.emit("reinviteAccepted", _this); - }); - }; - Session.prototype.sendReinvite = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - if (this.pendingReinvite) { - this.logger.warn("Reinvite in progress. Please wait until complete, then try again."); - return; - } - if (!this.sessionDescriptionHandler) { - this.logger.warn("No SessionDescriptionHandler, can't reinvite.."); - return; - } - this.pendingReinvite = true; - options.modifiers = options.modifiers || []; - var extraHeaders = (options.extraHeaders || []).slice(); - extraHeaders.push("Contact: " + this.contact); - // this is UA.C.ALLOWED_METHODS, removed to get around circular dependency - extraHeaders.push("Allow: " + [ - "ACK", - "CANCEL", - "INVITE", - "MESSAGE", - "BYE", - "OPTIONS", - "INFO", - "NOTIFY", - "REFER" - ].toString()); - this.sessionDescriptionHandler.getDescription(options.sessionDescriptionHandlerOptions, options.modifiers) - .then(function (description) { - if (!_this.session) { - throw new Error("Session undefined."); - } - var delegate = { - onAccept: function (response) { - if (_this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - _this.logger.error("Received reinvite response, but in STATUS_TERMINATED"); - // TODO: Do we need to send a SIP response? - return; - } - if (!_this.pendingReinvite) { - _this.logger.error("Received reinvite response, but have no pending reinvite"); - // TODO: Do we need to send a SIP response? - return; - } - // FIXME: Why is this set here? - _this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; - // 17.1.1.1 - For each final response that is received at the client transaction, - // the client transaction sends an ACK, - _this.emit("ack", response.ack()); - _this.pendingReinvite = false; - // TODO: All of these timers should move into the Transaction layer - clearTimeout(_this.timers.invite2xxTimer); - if (!_this.sessionDescriptionHandler || - !_this.sessionDescriptionHandler.hasDescription(response.message.getHeader("Content-Type") || "")) { - _this.logger.error("2XX response received to re-invite but did not have a description"); - _this.emit("reinviteFailed", _this); - _this.emit("renegotiationError", new Exceptions_1.Exceptions.RenegotiationError("2XX response received to re-invite but did not have a description")); - return; - } - _this.sessionDescriptionHandler - .setDescription(response.message.body, _this.sessionDescriptionHandlerOptions, _this.modifiers) - .catch(function (e) { - _this.logger.error("Could not set the description in 2XX response"); - _this.logger.error(e); - _this.emit("reinviteFailed", _this); - _this.emit("renegotiationError", e); - _this.sendRequest(Constants_1.C.BYE, { - extraHeaders: ["Reason: " + Utils_1.Utils.getReasonHeaderValue(488, "Not Acceptable Here")] - }); - _this.terminated(undefined, Constants_1.C.causes.INCOMPATIBLE_SDP); - throw e; - }) - .then(function () { - _this.emit("reinviteAccepted", _this); - }); - }, - onProgress: function (response) { - return; - }, - onRedirect: function (response) { - // FIXME: Does ACK need to be sent? - _this.pendingReinvite = false; - _this.logger.log("Received a non 1XX or 2XX response to a re-invite"); - _this.emit("reinviteFailed", _this); - _this.emit("renegotiationError", new Exceptions_1.Exceptions.RenegotiationError("Invalid response to a re-invite")); - }, - onReject: function (response) { - // FIXME: Does ACK need to be sent? - _this.pendingReinvite = false; - _this.logger.log("Received a non 1XX or 2XX response to a re-invite"); - _this.emit("reinviteFailed", _this); - _this.emit("renegotiationError", new Exceptions_1.Exceptions.RenegotiationError("Invalid response to a re-invite")); - }, - onTrying: function (response) { - return; - } - }; - var requestOptions = { - extraHeaders: extraHeaders, - body: Utils_1.Utils.fromBodyObj(description) - }; - _this.session.invite(delegate, requestOptions); - }).catch(function (e) { - if (e.type === Enums_1.TypeStrings.RenegotiationError) { - _this.pendingReinvite = false; - _this.emit("renegotiationError", e); - _this.logger.warn("Renegotiation Error"); - _this.logger.warn(e.toString()); - throw e; - } - _this.logger.error("sessionDescriptionHandler error"); - _this.logger.error(e); - throw e; - }); - }; - Session.prototype.failed = function (response, cause) { - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return this; - } - this.emit("failed", response, cause); - return this; - }; - Session.prototype.rejected = function (response, cause) { - this.emit("rejected", response, cause); - return this; - }; - Session.prototype.canceled = function () { - if (this.sessionDescriptionHandler) { - this.sessionDescriptionHandler.close(); - } - this.emit("cancel"); - return this; - }; - Session.prototype.accepted = function (response, cause) { - if (!(response instanceof String)) { - cause = Utils_1.Utils.getReasonPhrase((response && response.statusCode) || 0, cause); - } - this.startTime = new Date(); - if (this.replacee) { - this.replacee.emit("replaced", this); - this.replacee.terminate(); - } - this.emit("accepted", response, cause); - return this; - }; - Session.prototype.terminated = function (message, cause) { - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return this; - } - this.endTime = new Date(); - this.close(); - this.emit("terminated", message, cause); - return this; - }; - Session.prototype.connecting = function (request) { - this.emit("connecting", { request: request }); - return this; - }; - Session.C = Enums_1.SessionStatus; - return Session; -}(events_1.EventEmitter)); -exports.Session = Session; -// tslint:disable-next-line:max-classes-per-file -var InviteServerContext = /** @class */ (function (_super) { - tslib_1.__extends(InviteServerContext, _super); - function InviteServerContext(ua, incomingInviteRequest) { - var _this = this; - if (!ua.configuration.sessionDescriptionHandlerFactory) { - ua.logger.warn("Can't build ISC without SDH Factory"); - throw new Error("ISC Constructor Failed"); - } - _this = _super.call(this, ua.configuration.sessionDescriptionHandlerFactory) || this; - _this._canceled = false; - _this.rseq = Math.floor(Math.random() * 10000); - _this.incomingRequest = incomingInviteRequest; - var request = incomingInviteRequest.message; - ServerContext_1.ServerContext.initializer(_this, ua, incomingInviteRequest); - _this.type = Enums_1.TypeStrings.InviteServerContext; - var contentDisp = request.parseHeader("Content-Disposition"); - if (contentDisp && contentDisp.type === "render") { - _this.renderbody = request.body; - _this.rendertype = request.getHeader("Content-Type"); - } - _this.status = Enums_1.SessionStatus.STATUS_INVITE_RECEIVED; - _this.fromTag = request.fromTag; - _this.id = request.callId + _this.fromTag; - _this.request = request; - _this.contact = _this.ua.contact.toString(); - _this.logger = ua.getLogger("sip.inviteservercontext", _this.id); - // Save the session into the ua sessions collection. - _this.ua.sessions[_this.id] = _this; - // Set 100rel if necessary - var set100rel = function (header, relSetting) { - if (request.hasHeader(header) && request.getHeader(header).toLowerCase().indexOf("100rel") >= 0) { - _this.rel100 = relSetting; - } - }; - set100rel("require", Constants_1.C.supported.REQUIRED); - set100rel("supported", Constants_1.C.supported.SUPPORTED); - // Set the toTag on the incoming request to the toTag which - // will be used in the response to the incoming request!!! - // FIXME: HACK: This is a hack to port an existing behavior. - // The behavior being ported appears to be a hack itself, - // so this is a hack to port a hack. At least one test spec - // relies on it (which is yet another hack). - _this.request.toTag = incomingInviteRequest.toTag; - _this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER; - // Set userNoAnswerTimer - _this.timers.userNoAnswerTimer = setTimeout(function () { - incomingInviteRequest.reject({ statusCode: 408 }); - _this.failed(request, Constants_1.C.causes.NO_ANSWER); - _this.terminated(request, Constants_1.C.causes.NO_ANSWER); - }, _this.ua.configuration.noAnswerTimeout || 60); - /* Set expiresTimer - * RFC3261 13.3.1 - */ - // Get the Expires header value if exists - if (request.hasHeader("expires")) { - var expires = Number(request.getHeader("expires") || 0) * 1000; - _this.timers.expiresTimer = setTimeout(function () { - if (_this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER) { - incomingInviteRequest.reject({ statusCode: 487 }); - _this.failed(request, Constants_1.C.causes.EXPIRES); - _this.terminated(request, Constants_1.C.causes.EXPIRES); - } - }, expires); - } - _this.errorListener = _this.onTransportError.bind(_this); - if (ua.transport) { - ua.transport.on("transportError", _this.errorListener); - } - return _this; - } - Object.defineProperty(InviteServerContext.prototype, "autoSendAnInitialProvisionalResponse", { - /** - * If true, a first provisional response after the 100 Trying - * will be sent automatically. This is false it the UAC required - * reliable provisional responses (100rel in Require header), - * otherwise it is true. The provisional is sent by calling - * `progress()` without any options. - * - * FIXME: TODO: It seems reasonable that the ISC user should - * be able to optionally disable this behavior. As the provisional - * is sent prior to the "invite" event being emitted, it's a known - * issue that the ISC user cannot register listeners or do any other - * setup prior to the call to `progress()`. As an example why this is - * an issue, setting `ua.configuration.rel100` to REQUIRED will result - * in an attempt by `progress()` to send a 183 with SDP produced by - * calling `getDescription()` on a session description handler, but - * the ISC user cannot perform any potentially required session description - * handler initialization (thus preventing the utilization of setting - * `ua.configuration.rel100` to REQUIRED). That begs the question of - * why this behavior is disabled when the UAC requires 100rel but not - * when the UAS requires 100rel? But ignoring that, it's just one example - * of a class of cases where the ISC user needs to do something prior - * to the first call to `progress()` and is unable to do so. - */ - get: function () { - return this.rel100 === Constants_1.C.supported.REQUIRED ? false : true; - }, - enumerable: true, - configurable: true - }); - // type hack for servercontext interface - InviteServerContext.prototype.reply = function (options) { - if (options === void 0) { options = {}; } - return this; - }; - // typing note: this was the only function using its super in ServerContext - // so the bottom half of this function is copied and paired down from that - InviteServerContext.prototype.reject = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - // Check Session Status - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - throw new Exceptions_1.Exceptions.InvalidStateError(this.status); - } - this.logger.log("rejecting RTCSession"); - var statusCode = options.statusCode || 480; - var reasonPhrase = Utils_1.Utils.getReasonPhrase(statusCode, options.reasonPhrase); - var extraHeaders = options.extraHeaders || []; - if (statusCode < 300 || statusCode > 699) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - var body = options.body ? core_1.fromBodyLegacy(options.body) : undefined; - // FIXME: Need to redirect to someplae - var response = statusCode < 400 ? - this.incomingRequest.redirect([], { statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }) : - this.incomingRequest.reject({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); - (["rejected", "failed"]).forEach(function (event) { - _this.emit(event, response.message, reasonPhrase); - }); - return this.terminated(); - }; - /** - * Accept the incoming INVITE request to start a Session. - * Replies to the INVITE request with a 200 Ok response. - * @param options Options bucket. - */ - InviteServerContext.prototype.accept = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - // FIXME: Need guard against calling more than once. - this._accept(options) - .then(function (_a) { - var message = _a.message, session = _a.session; - session.delegate = { - onAck: function (ackRequest) { return _this.onAck(ackRequest); }, - onAckTimeout: function () { return _this.onAckTimeout(); }, - onBye: function (byeRequest) { return _this.receiveRequest(byeRequest); }, - onInfo: function (infoRequest) { return _this.receiveRequest(infoRequest); }, - onInvite: function (inviteRequest) { return _this.receiveRequest(inviteRequest); }, - onNotify: function (notifyRequest) { return _this.receiveRequest(notifyRequest); }, - onPrack: function (prackRequest) { return _this.receiveRequest(prackRequest); }, - onRefer: function (referRequest) { return _this.receiveRequest(referRequest); } - }; - _this.session = session; - _this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK; - _this.accepted(message, Utils_1.Utils.getReasonPhrase(200)); - }) - .catch(function (error) { - _this.onContextError(error); - // FIXME: Assuming error due to async race on CANCEL and eating error. - if (!_this._canceled) { - throw error; - } - }); - return this; - }; - /** - * Report progress to the the caller. - * Replies to the INVITE request with a 1xx provisional response. - * @param options Options bucket. - */ - InviteServerContext.prototype.progress = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - // Ported - var statusCode = options.statusCode || 180; - if (statusCode < 100 || statusCode > 199) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - // Ported - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - this.logger.warn("Unexpected call for progress while terminated, ignoring"); - return this; - } - // Added - if (this.status === Enums_1.SessionStatus.STATUS_ANSWERED) { - this.logger.warn("Unexpected call for progress while answered, ignoring"); - return this; - } - // Added - if (this.status === Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK) { - this.logger.warn("Unexpected call for progress while answered (waiting for prack), ignoring"); - return this; - } - // After the first reliable provisional response for a request has been - // acknowledged, the UAS MAY send additional reliable provisional - // responses. The UAS MUST NOT send a second reliable provisional - // response until the first is acknowledged. After the first, it is - // RECOMMENDED that the UAS not send an additional reliable provisional - // response until the previous is acknowledged. The first reliable - // provisional response receives special treatment because it conveys - // the initial sequence number. If additional reliable provisional - // responses were sent before the first was acknowledged, the UAS could - // not be certain these were received in order. - // https://tools.ietf.org/html/rfc3262#section-3 - if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK) { - this.logger.warn("Unexpected call for progress while waiting for prack, ignoring"); - return this; - } - // Ported - if (options.statusCode === 100) { - try { - this.incomingRequest.trying(); - } - catch (error) { - this.onContextError(error); - // FIXME: Assuming error due to async race on CANCEL and eating error. - if (!this._canceled) { - throw error; - } - } - return this; - } - // Standard provisional response. - if (!(this.rel100 === Constants_1.C.supported.REQUIRED) && - !(this.rel100 === Constants_1.C.supported.SUPPORTED && options.rel100) && - !(this.rel100 === Constants_1.C.supported.SUPPORTED && this.ua.configuration.rel100 === Constants_1.C.supported.REQUIRED)) { - this._progress(options) - .catch(function (error) { - _this.onContextError(error); - // FIXME: Assuming error due to async race on CANCEL and eating error. - if (!_this._canceled) { - throw error; - } - }); - return this; - } - // Reliable provisional response. - this._reliableProgressWaitForPrack(options) - .catch(function (error) { - _this.onContextError(error); - // FIXME: Assuming error due to async race on CANCEL and eating error. - if (!_this._canceled) { - throw error; - } - }); - return this; - }; - /** - * Reject an unaccepted incoming INVITE request or send BYE if established session. - * @param options Options bucket. FIXME: This options bucket needs to be typed. - */ - InviteServerContext.prototype.terminate = function (options) { - // The caller's UA MAY send a BYE for either confirmed or early dialogs, - // and the callee's UA MAY send a BYE on confirmed dialogs, but MUST NOT - // send a BYE on early dialogs. However, the callee's UA MUST NOT send a - // BYE on a confirmed dialog until it has received an ACK for its 2xx - // response or until the server transaction times out. - // https://tools.ietf.org/html/rfc3261#section-15 - var _this = this; - if (options === void 0) { options = {}; } - // We don't yet have a dialog, so reject request. - if (!this.session) { - this.reject(options); - return this; - } - switch (this.session.sessionState) { - case core_1.SessionState.Initial: - this.reject(options); - return this; - case core_1.SessionState.Early: - this.reject(options); - return this; - case core_1.SessionState.AckWait: - this.session.delegate = { - // When ACK shows up, say BYE. - onAck: function () { - _this.sendRequest(Constants_1.C.BYE, options); - }, - // Or the server transaction times out before the ACK arrives. - onAckTimeout: function () { - _this.sendRequest(Constants_1.C.BYE, options); - } - }; - // Ported - this.emit("bye", this.request); - this.terminated(); - return this; - case core_1.SessionState.Confirmed: - this.bye(options); - return this; - case core_1.SessionState.Terminated: - return this; - default: - return this; - } - }; - InviteServerContext.prototype.onCancel = function (message) { - if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER || - this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK || - this.status === Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK || - this.status === Enums_1.SessionStatus.STATUS_EARLY_MEDIA || - this.status === Enums_1.SessionStatus.STATUS_ANSWERED) { - this.status = Enums_1.SessionStatus.STATUS_CANCELED; - this.incomingRequest.reject({ statusCode: 487 }); - this.canceled(); - this.rejected(message, Constants_1.C.causes.CANCELED); - this.failed(message, Constants_1.C.causes.CANCELED); - this.terminated(message, Constants_1.C.causes.CANCELED); - } - }; - InviteServerContext.prototype.receiveRequest = function (incomingRequest) { - var _this = this; - switch (incomingRequest.message.method) { - case Constants_1.C.PRACK: - if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK || - this.status === Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK) { - if (!this.hasAnswer) { - this.sessionDescriptionHandler = this.setupSessionDescriptionHandler(); - this.emit("SessionDescriptionHandler-created", this.sessionDescriptionHandler); - if (this.sessionDescriptionHandler.hasDescription(incomingRequest.message.getHeader("Content-Type") || "")) { - this.hasAnswer = true; - this.sessionDescriptionHandler.setDescription(incomingRequest.message.body, this.sessionDescriptionHandlerOptions, this.modifiers).then(function () { - clearTimeout(_this.timers.rel1xxTimer); - clearTimeout(_this.timers.prackTimer); - incomingRequest.accept(); - if (_this.status === Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK) { - _this.status = Enums_1.SessionStatus.STATUS_EARLY_MEDIA; - _this.accept(); - } - _this.status = Enums_1.SessionStatus.STATUS_EARLY_MEDIA; - }, function (e) { - _this.logger.warn(e); - _this.terminate({ - statusCode: "488", - reasonPhrase: "Bad Media Description" - }); - _this.failed(incomingRequest.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - _this.terminated(incomingRequest.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - }); - } - else { - this.terminate({ - statusCode: "488", - reasonPhrase: "Bad Media Description" - }); - this.failed(incomingRequest.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - this.terminated(incomingRequest.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - } - } - else { - clearTimeout(this.timers.rel1xxTimer); - clearTimeout(this.timers.prackTimer); - incomingRequest.accept(); - if (this.status === Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK) { - this.status = Enums_1.SessionStatus.STATUS_EARLY_MEDIA; - this.accept(); - } - this.status = Enums_1.SessionStatus.STATUS_EARLY_MEDIA; - } - } - else if (this.status === Enums_1.SessionStatus.STATUS_EARLY_MEDIA) { - incomingRequest.accept(); - } - break; - default: - _super.prototype.receiveRequest.call(this, incomingRequest); - break; - } - }; - // Internal Function to setup the handler consistently - InviteServerContext.prototype.setupSessionDescriptionHandler = function () { - if (this.sessionDescriptionHandler) { - return this.sessionDescriptionHandler; - } - return this.sessionDescriptionHandlerFactory(this, this.ua.configuration.sessionDescriptionHandlerFactoryOptions); - }; - InviteServerContext.prototype.generateResponseOfferAnswer = function (options) { - if (!this.session) { - var body = core_1.getBody(this.incomingRequest.message); - if (!body || body.contentDisposition !== "session") { - return this.getOffer(options); - } - else { - return this.setOfferAndGetAnswer(body, options); - } - } - else { - switch (this.session.signalingState) { - case core_1.SignalingState.Initial: - return this.getOffer(options); - case core_1.SignalingState.Stable: - return Promise.resolve(undefined); - case core_1.SignalingState.HaveLocalOffer: - // o Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - return Promise.resolve(undefined); - case core_1.SignalingState.HaveRemoteOffer: - if (!this.session.offer) { - throw new Error("Session offer undefined"); - } - return this.setOfferAndGetAnswer(this.session.offer, options); - case core_1.SignalingState.Closed: - throw new Error("Invalid signaling state " + this.session.signalingState + "."); - default: - throw new Error("Invalid signaling state " + this.session.signalingState + "."); - } - } - }; - InviteServerContext.prototype.handlePrackOfferAnswer = function (request, options) { - if (!this.session) { - throw new Error("Session undefined."); - } - // If the PRACK doesn't have an offer/answer, nothing to be done. - var body = core_1.getBody(request.message); - if (!body || body.contentDisposition !== "session") { - return Promise.resolve(undefined); - } - // If the UAC receives a reliable provisional response with an offer - // (this would occur if the UAC sent an INVITE without an offer, in - // which case the first reliable provisional response will contain the - // offer), it MUST generate an answer in the PRACK. If the UAC receives - // a reliable provisional response with an answer, it MAY generate an - // additional offer in the PRACK. If the UAS receives a PRACK with an - // offer, it MUST place the answer in the 2xx to the PRACK. - // https://tools.ietf.org/html/rfc3262#section-5 - switch (this.session.signalingState) { - case core_1.SignalingState.Initial: - // State should never be reached as first reliable provisional response must have answer/offer. - throw new Error("Invalid signaling state " + this.session.signalingState + "."); - case core_1.SignalingState.Stable: - // Receved answer. - return this.setAnswer(body, options).then(function () { return undefined; }); - case core_1.SignalingState.HaveLocalOffer: - // State should never be reached as local offer would be answered by this PRACK - throw new Error("Invalid signaling state " + this.session.signalingState + "."); - case core_1.SignalingState.HaveRemoteOffer: - // Receved offer, generate answer. - return this.setOfferAndGetAnswer(body, options); - case core_1.SignalingState.Closed: - throw new Error("Invalid signaling state " + this.session.signalingState + "."); - default: - throw new Error("Invalid signaling state " + this.session.signalingState + "."); - } - }; - /** - * Called when session canceled. - */ - InviteServerContext.prototype.canceled = function () { - this._canceled = true; - return _super.prototype.canceled.call(this); - }; - /** - * Called when session terminated. - * Using it here just for the PRACK timeout. - */ - InviteServerContext.prototype.terminated = function (message, cause) { - this.prackNeverArrived(); - return _super.prototype.terminated.call(this, message, cause); - }; - /** - * A version of `accept` which resolves a session when the 200 Ok response is sent. - * @param options Options bucket. - * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. - * @throws {TransactionStateError} The transaction state does not allow for `accept()` to be called. - * Note that the transaction state can change while this call is in progress. - */ - InviteServerContext.prototype._accept = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - // FIXME: Ported - callback for in dialog INFO requests. - // Turns out accept() can be called more than once if we are waiting - // for a PRACK in which case "options" get completely tossed away. - // So this is broken in that case (and potentially other uses of options). - // Tempted to just try to fix it now, but leaving it broken for the moment. - this.onInfo = options.onInfo; - // The UAS MAY send a final response to the initial request before - // having received PRACKs for all unacknowledged reliable provisional - // responses, unless the final response is 2xx and any of the - // unacknowledged reliable provisional responses contained a session - // description. In that case, it MUST NOT send a final response until - // those provisional responses are acknowledged. If the UAS does send a - // final response when reliable responses are still unacknowledged, it - // SHOULD NOT continue to retransmit the unacknowledged reliable - // provisional responses, but it MUST be prepared to process PRACK - // requests for those outstanding responses. A UAS MUST NOT send new - // reliable provisional responses (as opposed to retransmissions of - // unacknowledged ones) after sending a final response to a request. - // https://tools.ietf.org/html/rfc3262#section-3 - if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK) { - this.status = Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK; - return this.waitForArrivalOfPrack() - .then(function () { - _this.status = Enums_1.SessionStatus.STATUS_ANSWERED; - clearTimeout(_this.timers.userNoAnswerTimer); // Ported - }) - .then(function () { return _this.generateResponseOfferAnswer(options); }) - .then(function (body) { return _this.incomingRequest.accept({ statusCode: 200, body: body }); }); - } - // Ported - if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER) { - this.status = Enums_1.SessionStatus.STATUS_ANSWERED; - } - else { - return Promise.reject(new Exceptions_1.Exceptions.InvalidStateError(this.status)); - } - this.status = Enums_1.SessionStatus.STATUS_ANSWERED; - clearTimeout(this.timers.userNoAnswerTimer); // Ported - return this.generateResponseOfferAnswer(options) - .then(function (body) { return _this.incomingRequest.accept({ statusCode: 200, body: body }); }); - }; - /** - * A version of `progress` which resolves when the provisional response is sent. - * @param options Options bucket. - * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. - * @throws {TransactionStateError} The transaction state does not allow for `progress()` to be called. - * Note that the transaction state can change while this call is in progress. - */ - InviteServerContext.prototype._progress = function (options) { - if (options === void 0) { options = {}; } - // Ported - var statusCode = options.statusCode || 180; - var reasonPhrase = options.reasonPhrase; - var extraHeaders = (options.extraHeaders || []).slice(); - var body = options.body ? core_1.fromBodyLegacy(options.body) : undefined; - // The 183 (Session Progress) response is used to convey information - // about the progress of the call that is not otherwise classified. The - // Reason-Phrase, header fields, or message body MAY be used to convey - // more details about the call progress. - // https://tools.ietf.org/html/rfc3261#section-21.1.5 - // It is the de facto industry standard to utilize 183 with SDP to provide "early media". - // While it is unlikely someone would want to send a 183 without SDP, so it should be an option. - if (statusCode === 183 && !body) { - return this._progressWithSDP(options); - } - try { - var progressResponse = this.incomingRequest.progress({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); - this.emit("progress", progressResponse.message, reasonPhrase); // Ported - this.session = progressResponse.session; - return Promise.resolve(progressResponse); - } - catch (error) { - return Promise.reject(error); - } - }; - /** - * A version of `progress` which resolves when the provisional response with sdp is sent. - * @param options Options bucket. - * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. - * @throws {TransactionStateError} The transaction state does not allow for `progress()` to be called. - * Note that the transaction state can change while this call is in progress. - */ - InviteServerContext.prototype._progressWithSDP = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - var statusCode = options.statusCode || 183; - var reasonPhrase = options.reasonPhrase; - var extraHeaders = (options.extraHeaders || []).slice(); - // Get an offer/answer and send a reply. - return this.generateResponseOfferAnswer(options) - .then(function (body) { return _this.incomingRequest.progress({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); }) - .then(function (progressResponse) { - _this.emit("progress", progressResponse.message, reasonPhrase); // Ported - _this.session = progressResponse.session; - return progressResponse; - }); - }; - /** - * A version of `progress` which resolves when the reliable provisional response is sent. - * @param options Options bucket. - * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. - * @throws {TransactionStateError} The transaction state does not allow for `progress()` to be called. - * Note that the transaction state can change while this call is in progress. - */ - InviteServerContext.prototype._reliableProgress = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - var statusCode = options.statusCode || 183; - var reasonPhrase = options.reasonPhrase; - var extraHeaders = (options.extraHeaders || []).slice(); - extraHeaders.push("Require: 100rel"); - extraHeaders.push("RSeq: " + Math.floor(Math.random() * 10000)); - // Get an offer/answer and send a reply. - return this.generateResponseOfferAnswer(options) - .then(function (body) { return _this.incomingRequest.progress({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); }) - .then(function (progressResponse) { - _this.emit("progress", progressResponse.message, reasonPhrase); // Ported - _this.session = progressResponse.session; - return progressResponse; - }); - }; - /** - * A version of `progress` which resolves when the reliable provisional response is acknowledged. - * @param options Options bucket. - * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. - * @throws {TransactionStateError} The transaction state does not allow for `progress()` to be called. - * Note that the transaction state can change while this call is in progress. - */ - InviteServerContext.prototype._reliableProgressWaitForPrack = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - var statusCode = options.statusCode || 183; - var reasonPhrase = options.reasonPhrase; - var extraHeaders = (options.extraHeaders || []).slice(); - extraHeaders.push("Require: 100rel"); - extraHeaders.push("RSeq: " + this.rseq++); - var body; - // Ported - set status. - this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK; - return new Promise(function (resolve, reject) { - var waitingForPrack = true; - return _this.generateResponseOfferAnswer(options) - .then(function (offerAnswer) { - body = offerAnswer; - return _this.incomingRequest.progress({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); - }) - .then(function (progressResponse) { - _this.emit("progress", progressResponse.message, reasonPhrase); // Ported - _this.session = progressResponse.session; - var prackRequest; - var prackResponse; - progressResponse.session.delegate = { - onPrack: function (request) { - prackRequest = request; - clearTimeout(prackWaitTimeoutTimer); - clearTimeout(rel1xxRetransmissionTimer); - if (!waitingForPrack) { - return; - } - waitingForPrack = false; - _this.handlePrackOfferAnswer(prackRequest, options) - .then(function (prackResponseBody) { - try { - prackResponse = prackRequest.accept({ statusCode: 200, body: prackResponseBody }); - // Ported - set status. - if (_this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK) { - _this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER; - } - _this.prackArrived(); - resolve({ prackRequest: prackRequest, prackResponse: prackResponse, progressResponse: progressResponse }); - } - catch (error) { - reject(error); - } - }); - } - }; - // https://tools.ietf.org/html/rfc3262#section-3 - var prackWaitTimeout = function () { - if (!waitingForPrack) { - return; - } - waitingForPrack = false; - _this.logger.warn("No PRACK received, rejecting INVITE."); - clearTimeout(rel1xxRetransmissionTimer); - try { - _this.incomingRequest.reject({ statusCode: 504 }); - _this.terminated(undefined, Constants_1.C.causes.NO_PRACK); - reject(new Exceptions_1.Exceptions.TerminatedSessionError()); - } - catch (error) { - reject(error); - } - }; - var prackWaitTimeoutTimer = setTimeout(prackWaitTimeout, core_1.Timers.T1 * 64); - // https://tools.ietf.org/html/rfc3262#section-3 - var rel1xxRetransmission = function () { - try { - _this.incomingRequest.progress({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); - } - catch (error) { - waitingForPrack = false; - reject(error); - return; - } - rel1xxRetransmissionTimer = setTimeout(rel1xxRetransmission, timeout *= 2); - }; - var timeout = core_1.Timers.T1; - var rel1xxRetransmissionTimer = setTimeout(rel1xxRetransmission, timeout); - }); - }); - }; - /** - * Callback for when ACK for a 2xx response is never received. - * @param session Session the ACK never arrived for - */ - InviteServerContext.prototype.onAckTimeout = function () { - if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK) { - this.logger.log("no ACK received for an extended period of time, terminating the call"); - if (!this.session) { - throw new Error("Session undefined."); - } - this.session.bye(); - this.terminated(undefined, Constants_1.C.causes.NO_ACK); - } - }; - /** - * FIXME: TODO: The current library interface presents async methods without a - * proper async error handling mechanism. Arguably a promise based interface - * would be an improvement over the pattern of returning `this`. The approach has - * been generally along the lines of log a error and terminate. - */ - InviteServerContext.prototype.onContextError = function (error) { - var statusCode = 480; - if (error instanceof core_1.Exception) { // There might be interest in catching these Exceptions. - if (error instanceof Exceptions_1.Exceptions.SessionDescriptionHandlerError) { - this.logger.error(error.message); - if (error.error) { - this.logger.error(error.error); - } - } - else if (error instanceof Exceptions_1.Exceptions.TerminatedSessionError) { - // PRACK never arrived, so we timed out waiting for it. - this.logger.warn("Incoming session terminated while waiting for PRACK."); - } - else if (error instanceof Exceptions_1.Exceptions.UnsupportedSessionDescriptionContentTypeError) { - statusCode = 415; - } - else if (error instanceof core_1.Exception) { - this.logger.error(error.message); - } - } - else if (error instanceof Error) { // Other Errors hould go uncaught. - this.logger.error(error.message); - } - else { - // We don't actually know what a session description handler implementation might throw - // our way, so as a last resort, just assume we are getting an "any" and log it. - this.logger.error("An error occurred in the session description handler."); - this.logger.error(error); - } - try { - this.incomingRequest.reject({ statusCode: statusCode }); // "Temporarily Unavailable" - this.failed(this.incomingRequest.message, error.message); - this.terminated(this.incomingRequest.message, error.message); - } - catch (error) { - return; - } - }; - InviteServerContext.prototype.prackArrived = function () { - if (this.waitingForPrackResolve) { - this.waitingForPrackResolve(); - } - this.waitingForPrackPromise = undefined; - this.waitingForPrackResolve = undefined; - this.waitingForPrackReject = undefined; - }; - InviteServerContext.prototype.prackNeverArrived = function () { - if (this.waitingForPrackReject) { - this.waitingForPrackReject(new Exceptions_1.Exceptions.TerminatedSessionError()); - } - this.waitingForPrackPromise = undefined; - this.waitingForPrackResolve = undefined; - this.waitingForPrackReject = undefined; - }; - /** - * @throws {Exceptions.TerminatedSessionError} The session terminated before being accepted (i.e. cancel arrived). - */ - InviteServerContext.prototype.waitForArrivalOfPrack = function () { - var _this = this; - if (this.waitingForPrackPromise) { - throw new Error("Already waiting for PRACK"); - } - this.waitingForPrackPromise = new Promise(function (resolve, reject) { - _this.waitingForPrackResolve = resolve; - _this.waitingForPrackReject = reject; - }); - return this.waitingForPrackPromise; - }; - InviteServerContext.prototype.getOffer = function (options) { - this.hasOffer = true; - var sdh = this.getSessionDescriptionHandler(); - return sdh - .getDescription(options.sessionDescriptionHandlerOptions, options.modifiers) - .then(function (bodyObj) { return Utils_1.Utils.fromBodyObj(bodyObj); }); - }; - InviteServerContext.prototype.setAnswer = function (answer, options) { - this.hasAnswer = true; - var sdh = this.getSessionDescriptionHandler(); - if (!sdh.hasDescription(answer.contentType)) { - return Promise.reject(new Exceptions_1.Exceptions.UnsupportedSessionDescriptionContentTypeError()); - } - return sdh - .setDescription(answer.content, options.sessionDescriptionHandlerOptions, options.modifiers); - }; - InviteServerContext.prototype.setOfferAndGetAnswer = function (offer, options) { - this.hasOffer = true; - this.hasAnswer = true; - var sdh = this.getSessionDescriptionHandler(); - if (!sdh.hasDescription(offer.contentType)) { - return Promise.reject(new Exceptions_1.Exceptions.UnsupportedSessionDescriptionContentTypeError()); - } - return sdh - .setDescription(offer.content, options.sessionDescriptionHandlerOptions, options.modifiers) - .then(function () { return sdh.getDescription(options.sessionDescriptionHandlerOptions, options.modifiers); }) - .then(function (bodyObj) { return Utils_1.Utils.fromBodyObj(bodyObj); }); - }; - InviteServerContext.prototype.getSessionDescriptionHandler = function () { - // Create our session description handler if not already done so... - var sdh = this.sessionDescriptionHandler = this.setupSessionDescriptionHandler(); - // FIXME: Ported - this can get emitted multiple times even when only created once... don't we care? - this.emit("SessionDescriptionHandler-created", this.sessionDescriptionHandler); - // Return. - return sdh; - }; - return InviteServerContext; -}(Session)); -exports.InviteServerContext = InviteServerContext; -// tslint:disable-next-line:max-classes-per-file -var InviteClientContext = /** @class */ (function (_super) { - tslib_1.__extends(InviteClientContext, _super); - function InviteClientContext(ua, target, options, modifiers) { - if (options === void 0) { options = {}; } - if (modifiers === void 0) { modifiers = []; } - var _this = this; - if (!ua.configuration.sessionDescriptionHandlerFactory) { - ua.logger.warn("Can't build ISC without SDH Factory"); - throw new Error("ICC Constructor Failed"); - } - options.params = options.params || {}; - var anonymous = options.anonymous || false; - var fromTag = Utils_1.Utils.newTag(); - options.params.fromTag = fromTag; - /* Do not add ;ob in initial forming dialog requests if the registration over - * the current connection got a GRUU URI. - */ - var contact = ua.contact.toString({ - anonymous: anonymous, - outbound: anonymous ? !ua.contact.tempGruu : !ua.contact.pubGruu - }); - var extraHeaders = (options.extraHeaders || []).slice(); - if (anonymous && ua.configuration.uri) { - options.params.fromDisplayName = "Anonymous"; - options.params.fromUri = "sip:anonymous@anonymous.invalid"; - extraHeaders.push("P-Preferred-Identity: " + ua.configuration.uri.toString()); - extraHeaders.push("Privacy: id"); - } - extraHeaders.push("Contact: " + contact); - // this is UA.C.ALLOWED_METHODS, removed to get around circular dependency - extraHeaders.push("Allow: " + [ - "ACK", - "CANCEL", - "INVITE", - "MESSAGE", - "BYE", - "OPTIONS", - "INFO", - "NOTIFY", - "REFER" - ].toString()); - if (ua.configuration.rel100 === Constants_1.C.supported.REQUIRED) { - extraHeaders.push("Require: 100rel"); - } - if (ua.configuration.replaces === Constants_1.C.supported.REQUIRED) { - extraHeaders.push("Require: replaces"); - } - options.extraHeaders = extraHeaders; - _this = _super.call(this, ua.configuration.sessionDescriptionHandlerFactory) || this; - ClientContext_1.ClientContext.initializer(_this, ua, Constants_1.C.INVITE, target, options); - _this.earlyMediaSessionDescriptionHandlers = new Map(); - _this.type = Enums_1.TypeStrings.InviteClientContext; - _this.passedOptions = options; // Save for later to use with refer - _this.sessionDescriptionHandlerOptions = options.sessionDescriptionHandlerOptions || {}; - _this.modifiers = modifiers; - _this.inviteWithoutSdp = options.inviteWithoutSdp || false; - // Set anonymous property - _this.anonymous = options.anonymous || false; - // Custom data to be sent either in INVITE or in ACK - _this.renderbody = options.renderbody || undefined; - _this.rendertype = options.rendertype || "text/plain"; - // Session parameter initialization - _this.fromTag = fromTag; - _this.contact = contact; - // Check Session Status - if (_this.status !== Enums_1.SessionStatus.STATUS_NULL) { - throw new Exceptions_1.Exceptions.InvalidStateError(_this.status); - } - // OutgoingSession specific parameters - _this.isCanceled = false; - _this.received100 = false; - _this.method = Constants_1.C.INVITE; - _this.logger = ua.getLogger("sip.inviteclientcontext"); - ua.applicants[_this.toString()] = _this; - _this.id = _this.request.callId + _this.fromTag; - _this.onInfo = options.onInfo; - _this.errorListener = _this.onTransportError.bind(_this); - if (ua.transport) { - ua.transport.on("transportError", _this.errorListener); - } - return _this; - } - InviteClientContext.prototype.receiveResponse = function (response) { - throw new Error("Unimplemented."); - }; - // hack for getting around ClientContext interface - InviteClientContext.prototype.send = function () { - this.sendInvite(); - return this; - }; - InviteClientContext.prototype.invite = function () { - var _this = this; - // Save the session into the ua sessions collection. - // Note: placing in constructor breaks call to request.cancel on close... User does not need this anyway - this.ua.sessions[this.id] = this; - // This should allow the function to return so that listeners can be set up for these events - Promise.resolve().then(function () { - // FIXME: There is a race condition where cancel (or terminate) can be called synchronously after invite. - if (_this.isCanceled || _this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return; - } - if (_this.inviteWithoutSdp) { - // just send an invite with no sdp... - if (_this.renderbody && _this.rendertype) { - _this.request.body = { - body: _this.renderbody, - contentType: _this.rendertype - }; - } - _this.status = Enums_1.SessionStatus.STATUS_INVITE_SENT; - _this.send(); - } - else { - // Initialize Media Session - _this.sessionDescriptionHandler = _this.sessionDescriptionHandlerFactory(_this, _this.ua.configuration.sessionDescriptionHandlerFactoryOptions || {}); - _this.emit("SessionDescriptionHandler-created", _this.sessionDescriptionHandler); - _this.sessionDescriptionHandler.getDescription(_this.sessionDescriptionHandlerOptions, _this.modifiers) - .then(function (description) { - // FIXME: There is a race condition where cancel (or terminate) can be called (a)synchronously after invite. - if (_this.isCanceled || _this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return; - } - _this.hasOffer = true; - _this.request.body = description; - _this.status = Enums_1.SessionStatus.STATUS_INVITE_SENT; - _this.send(); - }, function (err) { - if (err.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - _this.logger.log(err.message); - if (err.error) { - _this.logger.log(err.error); - } - } - if (_this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return; - } - _this.failed(undefined, Constants_1.C.causes.WEBRTC_ERROR); - _this.terminated(undefined, Constants_1.C.causes.WEBRTC_ERROR); - }); - } - }); - return this; - }; - InviteClientContext.prototype.cancel = function (options) { - if (options === void 0) { options = {}; } - // Check Session Status - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED || this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { - throw new Exceptions_1.Exceptions.InvalidStateError(this.status); - } - if (this.isCanceled) { - throw new Exceptions_1.Exceptions.InvalidStateError(Enums_1.SessionStatus.STATUS_CANCELED); - } - this.isCanceled = true; - this.logger.log("Canceling session"); - var cancelReason = Utils_1.Utils.getCancelReason(options.statusCode, options.reasonPhrase); - options.extraHeaders = (options.extraHeaders || []).slice(); - if (this.outgoingInviteRequest) { - this.logger.warn("Canceling session before it was created"); - this.outgoingInviteRequest.cancel(cancelReason, options); - } - return this.canceled(); - }; - InviteClientContext.prototype.terminate = function (options) { - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return this; - } - if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK || this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { - this.bye(options); - } - else { - this.cancel(options); - } - return this; - }; - /** - * 13.2.1 Creating the Initial INVITE - * - * Since the initial INVITE represents a request outside of a dialog, - * its construction follows the procedures of Section 8.1.1. Additional - * processing is required for the specific case of INVITE. - * - * An Allow header field (Section 20.5) SHOULD be present in the INVITE. - * It indicates what methods can be invoked within a dialog, on the UA - * sending the INVITE, for the duration of the dialog. For example, a - * UA capable of receiving INFO requests within a dialog [34] SHOULD - * include an Allow header field listing the INFO method. - * - * A Supported header field (Section 20.37) SHOULD be present in the - * INVITE. It enumerates all the extensions understood by the UAC. - * - * An Accept (Section 20.1) header field MAY be present in the INVITE. - * It indicates which Content-Types are acceptable to the UA, in both - * the response received by it, and in any subsequent requests sent to - * it within dialogs established by the INVITE. The Accept header field - * is especially useful for indicating support of various session - * description formats. - * - * The UAC MAY add an Expires header field (Section 20.19) to limit the - * validity of the invitation. If the time indicated in the Expires - * header field is reached and no final answer for the INVITE has been - * received, the UAC core SHOULD generate a CANCEL request for the - * INVITE, as per Section 9. - * - * A UAC MAY also find it useful to add, among others, Subject (Section - * 20.36), Organization (Section 20.25) and User-Agent (Section 20.41) - * header fields. They all contain information related to the INVITE. - * - * The UAC MAY choose to add a message body to the INVITE. Section - * 8.1.1.10 deals with how to construct the header fields -- Content- - * Type among others -- needed to describe the message body. - * - * https://tools.ietf.org/html/rfc3261#section-13.2.1 - */ - InviteClientContext.prototype.sendInvite = function () { - // There are special rules for message bodies that contain a session - // description - their corresponding Content-Disposition is "session". - // SIP uses an offer/answer model where one UA sends a session - // description, called the offer, which contains a proposed description - // of the session. The offer indicates the desired communications means - // (audio, video, games), parameters of those means (such as codec - // types) and addresses for receiving media from the answerer. The - // other UA responds with another session description, called the - // answer, which indicates which communications means are accepted, the - // parameters that apply to those means, and addresses for receiving - // media from the offerer. An offer/answer exchange is within the - // context of a dialog, so that if a SIP INVITE results in multiple - // dialogs, each is a separate offer/answer exchange. The offer/answer - // model defines restrictions on when offers and answers can be made - // (for example, you cannot make a new offer while one is in progress). - // This results in restrictions on where the offers and answers can - // appear in SIP messages. In this specification, offers and answers - // can only appear in INVITE requests and responses, and ACK. The usage - // of offers and answers is further restricted. For the initial INVITE - // transaction, the rules are: - // - // o The initial offer MUST be in either an INVITE or, if not there, - // in the first reliable non-failure message from the UAS back to - // the UAC. In this specification, that is the final 2xx - // response. - // - // o If the initial offer is in an INVITE, the answer MUST be in a - // reliable non-failure message from UAS back to UAC which is - // correlated to that INVITE. For this specification, that is - // only the final 2xx response to that INVITE. That same exact - // answer MAY also be placed in any provisional responses sent - // prior to the answer. The UAC MUST treat the first session - // description it receives as the answer, and MUST ignore any - // session descriptions in subsequent responses to the initial - // INVITE. - // - // o If the initial offer is in the first reliable non-failure - // message from the UAS back to UAC, the answer MUST be in the - // acknowledgement for that message (in this specification, ACK - // for a 2xx response). - // - // o After having sent or received an answer to the first offer, the - // UAC MAY generate subsequent offers in requests based on rules - // specified for that method, but only if it has received answers - // to any previous offers, and has not sent any offers to which it - // hasn't gotten an answer. - // - // o Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - var _this = this; - // 5 The Offer/Answer Model and PRACK - // - // RFC 3261 describes guidelines for the sets of messages in which - // offers and answers [3] can appear. Based on those guidelines, this - // extension provides additional opportunities for offer/answer - // exchanges. - // If the INVITE contained an offer, the UAS MAY generate an answer in a - // reliable provisional response (assuming these are supported by the - // UAC). That results in the establishment of the session before - // completion of the call. Similarly, if a reliable provisional - // response is the first reliable message sent back to the UAC, and the - // INVITE did not contain an offer, one MUST appear in that reliable - // provisional response. - // If the UAC receives a reliable provisional response with an offer - // (this would occur if the UAC sent an INVITE without an offer, in - // which case the first reliable provisional response will contain the - // offer), it MUST generate an answer in the PRACK. If the UAC receives - // a reliable provisional response with an answer, it MAY generate an - // additional offer in the PRACK. If the UAS receives a PRACK with an - // offer, it MUST place the answer in the 2xx to the PRACK. - // Once an answer has been sent or received, the UA SHOULD establish the - // session based on the parameters of the offer and answer, even if the - // original INVITE itself has not been responded to. - // If the UAS had placed a session description in any reliable - // provisional response that is unacknowledged when the INVITE is - // accepted, the UAS MUST delay sending the 2xx until the provisional - // response is acknowledged. Otherwise, the reliability of the 1xx - // cannot be guaranteed, and reliability is needed for proper operation - // of the offer/answer exchange. - // All user agents that support this extension MUST support all - // offer/answer exchanges that are possible based on the rules in - // Section 13.2 of RFC 3261, based on the existence of INVITE and PRACK - // as requests, and 2xx and reliable 1xx as non-failure reliable - // responses. - // - // https://tools.ietf.org/html/rfc3262#section-5 - //// - // The Offer/Answer Model Implementation - // - // The offer/answer model is straight forward, but one MUST READ the specifications... - // - // 13.2.1 Creating the Initial INVITE (paragraph 8 in particular) - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // - // 5 The Offer/Answer Model and PRACK - // https://tools.ietf.org/html/rfc3262#section-5 - // - // Session Initiation Protocol (SIP) Usage of the Offer/Answer Model - // https://tools.ietf.org/html/rfc6337 - // - // *** IMPORTANT IMPLEMENTATION CHOICES *** - // - // TLDR... - // - // 1) Only one offer/answer exchange permitted during initial INVITE. - // 2) No "early media" if the initial offer is in an INVITE. - // - // - // 1) Initial Offer/Answer Restriction. - // - // Our implementation replaces the following bullet point... - // - // o After having sent or received an answer to the first offer, the - // UAC MAY generate subsequent offers in requests based on rules - // specified for that method, but only if it has received answers - // to any previous offers, and has not sent any offers to which it - // hasn't gotten an answer. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // - // ...with... - // - // o After having sent or received an answer to the first offer, the - // UAC MUST NOT generate subsequent offers in requests based on rules - // specified for that method. - // - // ...which in combination with this bullet point... - // - // o Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // - // ...ensures that EXACTLY ONE offer/answer exchange will occur - // during an initial out of dialog INVITE request made by our UAC. - // - // - // 2) Early Media Restriction. - // - // While our implementation adheres to the following bullet point... - // - // o If the initial offer is in an INVITE, the answer MUST be in a - // reliable non-failure message from UAS back to UAC which is - // correlated to that INVITE. For this specification, that is - // only the final 2xx response to that INVITE. That same exact - // answer MAY also be placed in any provisional responses sent - // prior to the answer. The UAC MUST treat the first session - // description it receives as the answer, and MUST ignore any - // session descriptions in subsequent responses to the initial - // INVITE. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // - // We have made the following implementation decision with regard to early media... - // - // o If the initial offer is in the INVITE, the answer from the - // UAS back to the UAC will establish a media session only - // only after the final 2xx response to that INVITE is received. - // - // The reason for this decision is rooted in a restriction currently - // inherent in WebRTC. Specifically, while a SIP INVITE request with an - // initial offer may fork resulting in more than one provisional answer, - // there is currently no easy/good way to to "fork" an offer generated - // by a peer connection. In particular, a WebRTC offer currently may only - // be matched with one answer and we have no good way to know which - // "provisional answer" is going to be the "final answer". So we have - // decided to punt and not create any "early media" sessions in this case. - // - // The upshot is that if you want "early media", you must not put the - // initial offer in the INVITE. Instead, force the UAS to provide the - // initial offer by sending an INVITE without an offer. In the WebRTC - // case this allows us to create a unique peer connection with a unique - // answer for every provisional offer with "early media" on all of them. - //// - //// - // ROADMAP: The Offer/Answer Model Implementation - // - // The "no early media if offer in INVITE" implementation is not a - // welcome one. The masses want it. The want it and they want it - // to work for WebRTC (so they want to have their cake and eat too). - // - // So while we currently cannot make the offer in INVITE+forking+webrtc - // case work, we decided to do the following... - // - // 1) modify SDH Factory to provide an initial offer without giving us the SDH, and then... - // 2) stick that offer in the initial INVITE, and when 183 with initial answer is received... - // 3) ask SDH Factory if it supports "earlyRemoteAnswer" - // a) if true, ask SDH Factory to createSDH(localOffer).then((sdh) => sdh.setDescription(remoteAnswer) - // b) if false, defer getting a SDH until 2xx response is received - // - // Our supplied WebRTC SDH will default to behavior 3b which works in forking environment (without) - // early media if initial offer is in the INVITE). We will, however, provide an "inviteWillNotFork" - // option which if set to "true" will have our supplied WebRTC SDH behave in the 3a manner. - // That will result in - // - early media working with initial offer in the INVITE, and... - // - if the INVITE forks, the session terminating with an ERROR that reads like - // "You set 'inviteWillNotFork' to true but the INVITE forked. You can't eat your cake, and have it too." - // - furthermore, we accept that users will report that error to us as "bug" regardless - // - // So, SDH Factory is going to end up with a new interface along the lines of... - // - // interface SessionDescriptionHandlerFactory { - // makeLocalOffer(): Promise; - // makeSessionDescriptionHandler( - // initialOffer: ContentTypeAndBody, offerType: "local" | "remote" - // ): Promise; - // supportsEarlyRemoteAnswer: boolean; - // supportsContentType(contentType: string): boolean; - // getDescription(description: ContentTypeAndBody): Promise - // setDescription(description: ContentTypeAndBody): Promise - // } - // - // We should be able to get rid of all the hasOffer/hasAnswer tracking code and otherwise code - // it up to the same interaction with the SDH Factory and SDH regardless of signaling scenario. - //// - // Send the INVITE request. - this.outgoingInviteRequest = this.ua.userAgentCore.invite(this.request, { - onAccept: function (inviteResponse) { return _this.onAccept(inviteResponse); }, - onProgress: function (inviteResponse) { return _this.onProgress(inviteResponse); }, - onRedirect: function (inviteResponse) { return _this.onRedirect(inviteResponse); }, - onReject: function (inviteResponse) { return _this.onReject(inviteResponse); }, - onTrying: function (inviteResponse) { return _this.onTrying(inviteResponse); } - }); - }; - InviteClientContext.prototype.ackAndBye = function (inviteResponse, session, statusCode, reasonPhrase) { - if (!this.ua.userAgentCore) { - throw new Error("Method requires user agent core."); - } - var extraHeaders = []; - if (statusCode) { - extraHeaders.push("Reason: " + Utils_1.Utils.getReasonHeaderValue(statusCode, reasonPhrase)); - } - var outgoingAckRequest = inviteResponse.ack(); - this.emit("ack", outgoingAckRequest.message); - var outgoingByeRequest = session.bye(undefined, { extraHeaders: extraHeaders }); - this.emit("bye", outgoingByeRequest.message); - }; - InviteClientContext.prototype.disposeEarlyMedia = function () { - if (!this.earlyMediaSessionDescriptionHandlers) { - throw new Error("Early media session description handlers undefined."); - } - this.earlyMediaSessionDescriptionHandlers.forEach(function (sessionDescriptionHandler) { - sessionDescriptionHandler.close(); - }); - }; - /** - * Handle final response to initial INVITE. - * @param inviteResponse 2xx response. - */ - InviteClientContext.prototype.onAccept = function (inviteResponse) { - var _this = this; - if (!this.earlyMediaSessionDescriptionHandlers) { - throw new Error("Early media session description handlers undefined."); - } - var response = inviteResponse.message; - var session = inviteResponse.session; - // Our transaction layer is "non-standard" in that it will only - // pass us a 2xx response once per branch, so there is no need to - // worry about dealing with 2xx retransmissions. However, we can - // and do still get 2xx responses for multiple branches (when an - // INVITE is forked) which may create multiple confirmed dialogs. - // Herein we are acking and sending a bye to any confirmed dialogs - // which arrive beyond the first one. This is the desired behavior - // for most applications (but certainly not all). - // If we already received a confirmed dialog, ack & bye this session. - if (this.session) { - this.ackAndBye(inviteResponse, session); - return; - } - // If the user requested cancellation, ack & bye this session. - if (this.isCanceled) { - this.ackAndBye(inviteResponse, session); - this.emit("bye", this.request); // FIXME: Ported this odd second "bye" emit - return; - } - // Ported behavior. - if (response.hasHeader("P-Asserted-Identity")) { - this.assertedIdentity = core_1.Grammar.nameAddrHeaderParse(response.getHeader("P-Asserted-Identity")); - } - // We have a confirmed dialog. - this.session = session; - this.session.delegate = { - onAck: function (ackRequest) { return _this.onAck(ackRequest); }, - onBye: function (byeRequest) { return _this.receiveRequest(byeRequest); }, - onInfo: function (infoRequest) { return _this.receiveRequest(infoRequest); }, - onInvite: function (inviteRequest) { return _this.receiveRequest(inviteRequest); }, - onNotify: function (notifyRequest) { return _this.receiveRequest(notifyRequest); }, - onPrack: function (prackRequest) { return _this.receiveRequest(prackRequest); }, - onRefer: function (referRequest) { return _this.receiveRequest(referRequest); } - }; - switch (session.signalingState) { - case core_1.SignalingState.Initial: - // INVITE without Offer, so MUST have Offer at this point, so invalid state. - this.ackAndBye(inviteResponse, session, 400, "Missing session description"); - this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - break; - case core_1.SignalingState.HaveLocalOffer: - // INVITE with Offer, so MUST have Answer at this point, so invalid state. - this.ackAndBye(inviteResponse, session, 400, "Missing session description"); - this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - break; - case core_1.SignalingState.HaveRemoteOffer: - // INVITE without Offer, received offer in 2xx, so MUST send Answer in ACK. - var sdh_1 = this.sessionDescriptionHandlerFactory(this, this.ua.configuration.sessionDescriptionHandlerFactoryOptions || {}); - this.sessionDescriptionHandler = sdh_1; - this.emit("SessionDescriptionHandler-created", this.sessionDescriptionHandler); - if (!sdh_1.hasDescription(response.getHeader("Content-Type") || "")) { - this.ackAndBye(inviteResponse, session, 400, "Missing session description"); - this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - break; - } - this.hasOffer = true; - sdh_1 - .setDescription(response.body, this.sessionDescriptionHandlerOptions, this.modifiers) - .then(function () { return sdh_1.getDescription(_this.sessionDescriptionHandlerOptions, _this.modifiers); }) - .then(function (description) { - if (_this.isCanceled || _this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return; - } - _this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; - _this.hasAnswer = true; - var body = { - contentDisposition: "session", contentType: description.contentType, content: description.body - }; - var ackRequest = inviteResponse.ack({ body: body }); - _this.emit("ack", ackRequest.message); - _this.accepted(response); - }) - .catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - _this.logger.warn("invalid description"); - _this.logger.warn(e.toString()); - // TODO: This message is inconsistent - _this.ackAndBye(inviteResponse, session, 488, "Invalid session description"); - _this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - } - else { - throw e; - } - }); - break; - case core_1.SignalingState.Stable: - // This session has completed an initial offer/answer exchange... - var options_1; - if (this.renderbody && this.rendertype) { - options_1 = { body: { contentDisposition: "render", contentType: this.rendertype, content: this.renderbody } }; - } - // If INVITE with Offer and we have been waiting till now to apply the answer. - if (this.hasOffer && !this.hasAnswer) { - if (!this.sessionDescriptionHandler) { - throw new Error("Session description handler undefined."); - } - var answer = session.answer; - if (!answer) { - throw new Error("Answer is undefined."); - } - this.sessionDescriptionHandler - .setDescription(answer.content, this.sessionDescriptionHandlerOptions, this.modifiers) - .then(function () { - _this.hasAnswer = true; - _this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; - var ackRequest = inviteResponse.ack(options_1); - _this.emit("ack", ackRequest.message); - _this.accepted(response); - }) - .catch(function (error) { - _this.logger.error(error); - _this.ackAndBye(inviteResponse, session, 488, "Not Acceptable Here"); - _this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - // FIME: DON'T EAT UNHANDLED ERRORS! - }); - } - else { - // Otherwise INVITE with or without Offer and we have already completed the initial exchange. - this.sessionDescriptionHandler = this.earlyMediaSessionDescriptionHandlers.get(session.id); - if (!this.sessionDescriptionHandler) { - throw new Error("Session description handler undefined."); - } - this.earlyMediaSessionDescriptionHandlers.delete(session.id); - this.hasOffer = true; - this.hasAnswer = true; - this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; - var ackRequest = inviteResponse.ack(); - this.emit("ack", ackRequest.message); - this.accepted(response); - } - break; - case core_1.SignalingState.Closed: - // Dialog has terminated. - break; - default: - throw new Error("Unknown session signaling state."); - } - this.disposeEarlyMedia(); - }; - /** - * Handle provisional response to initial INVITE. - * @param inviteResponse 1xx response. - */ - InviteClientContext.prototype.onProgress = function (inviteResponse) { - var _this = this; - // Ported - User requested cancellation. - if (this.isCanceled) { - return; - } - if (!this.outgoingInviteRequest) { - throw new Error("Outgoing INVITE request undefined."); - } - if (!this.earlyMediaSessionDescriptionHandlers) { - throw new Error("Early media session description handlers undefined."); - } - var response = inviteResponse.message; - var session = inviteResponse.session; - // Ported - Set status. - this.status = Enums_1.SessionStatus.STATUS_1XX_RECEIVED; - // Ported - Set assertedIdentity. - if (response.hasHeader("P-Asserted-Identity")) { - this.assertedIdentity = core_1.Grammar.nameAddrHeaderParse(response.getHeader("P-Asserted-Identity")); - } - // The provisional response MUST establish a dialog if one is not yet created. - // https://tools.ietf.org/html/rfc3262#section-4 - if (!session) { - // A response with a to tag MUST create a session (should never get here). - throw new Error("Session undefined."); - } - // If a provisional response is received for an initial request, and - // that response contains a Require header field containing the option - // tag 100rel, the response is to be sent reliably. If the response is - // a 100 (Trying) (as opposed to 101 to 199), this option tag MUST be - // ignored, and the procedures below MUST NOT be used. - // https://tools.ietf.org/html/rfc3262#section-4 - var requireHeader = response.getHeader("require"); - var rseqHeader = response.getHeader("rseq"); - var rseq = requireHeader && requireHeader.includes("100rel") && rseqHeader ? Number(rseqHeader) : undefined; - var responseReliable = !!rseq; - var extraHeaders = []; - if (responseReliable) { - extraHeaders.push("RAck: " + response.getHeader("rseq") + " " + response.getHeader("cseq")); - } - // INVITE without Offer and session still has no offer (and no answer). - if (session.signalingState === core_1.SignalingState.Initial) { - // Similarly, if a reliable provisional - // response is the first reliable message sent back to the UAC, and the - // INVITE did not contain an offer, one MUST appear in that reliable - // provisional response. - // https://tools.ietf.org/html/rfc3262#section-5 - if (responseReliable) { - this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."); - // FIXME: Known popular UA's currently end up here... - inviteResponse.prack({ extraHeaders: extraHeaders }); - } - this.emit("progress", response); - return; - } - // INVITE with Offer and session only has that initial local offer. - if (session.signalingState === core_1.SignalingState.HaveLocalOffer) { - if (responseReliable) { - inviteResponse.prack({ extraHeaders: extraHeaders }); - } - this.emit("progress", response); - return; - } - // INVITE without Offer and received initial offer in provisional response - if (session.signalingState === core_1.SignalingState.HaveRemoteOffer) { - // The initial offer MUST be in either an INVITE or, if not there, - // in the first reliable non-failure message from the UAS back to - // the UAC. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // According to Section 13.2.1 of [RFC3261], 'The first reliable - // non-failure message' must have an offer if there is no offer in the - // INVITE request. This means that the User Agent (UA) that receives - // the INVITE request without an offer must include an offer in the - // first reliable response with 100rel extension. If no reliable - // provisional response has been sent, the User Agent Server (UAS) must - // include an offer when sending 2xx response. - // https://tools.ietf.org/html/rfc6337#section-2.2 - if (!responseReliable) { - this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response."); - return; - } - // If the initial offer is in the first reliable non-failure - // message from the UAS back to UAC, the answer MUST be in the - // acknowledgement for that message - var sdh_2 = this.sessionDescriptionHandlerFactory(this, this.ua.configuration.sessionDescriptionHandlerFactoryOptions || {}); - this.emit("SessionDescriptionHandler-created", sdh_2); - this.earlyMediaSessionDescriptionHandlers.set(session.id, sdh_2); - sdh_2 - .setDescription(response.body, this.sessionDescriptionHandlerOptions, this.modifiers) - .then(function () { return sdh_2.getDescription(_this.sessionDescriptionHandlerOptions, _this.modifiers); }) - .then(function (description) { - var body = { - contentDisposition: "session", contentType: description.contentType, content: description.body - }; - inviteResponse.prack({ extraHeaders: extraHeaders, body: body }); - _this.status = Enums_1.SessionStatus.STATUS_EARLY_MEDIA; - _this.emit("progress", response); - }) - .catch(function (error) { - if (_this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return; - } - _this.failed(undefined, Constants_1.C.causes.WEBRTC_ERROR); - _this.terminated(undefined, Constants_1.C.causes.WEBRTC_ERROR); - }); - return; - } - // This session has completed an initial offer/answer exchange, so... - // - INVITE with SDP and this provisional response MAY be reliable - // - INVITE without SDP and this provisional response MAY be reliable - if (session.signalingState === core_1.SignalingState.Stable) { - if (responseReliable) { - inviteResponse.prack({ extraHeaders: extraHeaders }); - } - // Note: As documented, no early media if offer was in INVITE, so nothing to be done. - // FIXME: TODO: Add a flag/hack to allow early media in this case. There are people - // in non-forking environments (think straight to FreeSWITCH) who want - // early media on a 183. Not sure how to actually make it work, basically - // something like... - if (false) {} - this.emit("progress", response); - return; - } - }; - /** - * Handle final response to initial INVITE. - * @param inviteResponse 3xx response. - */ - InviteClientContext.prototype.onRedirect = function (inviteResponse) { - this.disposeEarlyMedia(); - var response = inviteResponse.message; - var statusCode = response.statusCode; - var cause = Utils_1.Utils.sipErrorCause(statusCode || 0); - this.rejected(response, cause); - this.failed(response, cause); - this.terminated(response, cause); - }; - /** - * Handle final response to initial INVITE. - * @param inviteResponse 4xx, 5xx, or 6xx response. - */ - InviteClientContext.prototype.onReject = function (inviteResponse) { - this.disposeEarlyMedia(); - var response = inviteResponse.message; - var statusCode = response.statusCode; - var cause = Utils_1.Utils.sipErrorCause(statusCode || 0); - this.rejected(response, cause); - this.failed(response, cause); - this.terminated(response, cause); - }; - /** - * Handle final response to initial INVITE. - * @param inviteResponse 100 response. - */ - InviteClientContext.prototype.onTrying = function (inviteResponse) { - this.received100 = true; - this.emit("progress", inviteResponse.message); - }; - return InviteClientContext; -}(Session)); -exports.InviteClientContext = InviteClientContext; - - -/***/ }), -/* 91 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var events_1 = __webpack_require__(30); -var Constants_1 = __webpack_require__(80); -var Enums_1 = __webpack_require__(82); -var Exceptions_1 = __webpack_require__(84); -var Utils_1 = __webpack_require__(83); -/** - * @class DTMF - * @param {SIP.Session} session - */ -var DTMF = /** @class */ (function (_super) { - tslib_1.__extends(DTMF, _super); - function DTMF(session, tone, options) { - if (options === void 0) { options = {}; } - var _this = _super.call(this) || this; - _this.C = { - MIN_DURATION: 70, - MAX_DURATION: 6000, - DEFAULT_DURATION: 100, - MIN_INTER_TONE_GAP: 50, - DEFAULT_INTER_TONE_GAP: 500 - }; - _this.type = Enums_1.TypeStrings.DTMF; - if (tone === undefined) { - throw new TypeError("Not enough arguments"); - } - _this.logger = session.ua.getLogger("sip.invitecontext.dtmf", session.id); - _this.owner = session; - // Check tone type - if (typeof tone === "string") { - tone = tone.toUpperCase(); - } - else if (typeof tone === "number") { - tone = tone.toString(); - } - else { - throw new TypeError("Invalid tone: " + tone); - } - // Check tone value - if (!tone.match(/^[0-9A-D#*]$/)) { - throw new TypeError("Invalid tone: " + tone); - } - else { - _this.tone = tone; - } - var duration = options.duration; - var interToneGap = options.interToneGap; - // Check duration - if (duration && !Utils_1.Utils.isDecimal(duration)) { - throw new TypeError("Invalid tone duration: " + duration); - } - else if (!duration) { - duration = _this.C.DEFAULT_DURATION; - } - else if (duration < _this.C.MIN_DURATION) { - _this.logger.warn("'duration' value is lower than the minimum allowed, setting it to " + - _this.C.MIN_DURATION + " milliseconds"); - duration = _this.C.MIN_DURATION; - } - else if (duration > _this.C.MAX_DURATION) { - _this.logger.warn("'duration' value is greater than the maximum allowed, setting it to " + - _this.C.MAX_DURATION + " milliseconds"); - duration = _this.C.MAX_DURATION; - } - else { - duration = Math.abs(duration); - } - _this.duration = duration; - // Check interToneGap - if (interToneGap && !Utils_1.Utils.isDecimal(interToneGap)) { - throw new TypeError("Invalid interToneGap: " + interToneGap); - } - else if (!interToneGap) { - interToneGap = _this.C.DEFAULT_INTER_TONE_GAP; - } - else if (interToneGap < _this.C.MIN_INTER_TONE_GAP) { - _this.logger.warn("'interToneGap' value is lower than the minimum allowed, setting it to " + - _this.C.MIN_INTER_TONE_GAP + " milliseconds"); - interToneGap = _this.C.MIN_INTER_TONE_GAP; - } - else { - interToneGap = Math.abs(interToneGap); - } - _this.interToneGap = interToneGap; - return _this; - } - DTMF.prototype.send = function (options) { - if (options === void 0) { options = {}; } - // Check RTCSession Status - if (this.owner.status !== Enums_1.SessionStatus.STATUS_CONFIRMED && - this.owner.status !== Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK) { - throw new Exceptions_1.Exceptions.InvalidStateError(this.owner.status); - } - // Get DTMF options - var extraHeaders = options.extraHeaders ? options.extraHeaders.slice() : []; - var body = { - contentType: "application/dtmf-relay", - body: "Signal= " + this.tone + "\r\nDuration= " + this.duration - }; - if (this.owner.session) { - var request = this.owner.session.info(undefined, { - extraHeaders: extraHeaders, - body: Utils_1.Utils.fromBodyObj(body) - }); - this.owner.emit("dtmf", request.message, this); - return; - } - }; - DTMF.prototype.init_incoming = function (request) { - request.accept(); - if (!this.tone || !this.duration) { - this.logger.warn("invalid INFO DTMF received, discarded"); - } - else { - this.owner.emit("dtmf", request.message, this); - } - }; - DTMF.prototype.receiveResponse = function (response) { - var statusCode = response && response.statusCode ? response.statusCode : 0; - switch (true) { - case /^1[0-9]{2}$/.test(statusCode.toString()): - // Ignore provisional responses. - break; - case /^2[0-9]{2}$/.test(statusCode.toString()): - this.emit("succeeded", { - originator: "remote", - response: response - }); - break; - default: - var cause = Utils_1.Utils.sipErrorCause(statusCode); - this.emit("failed", response, cause); - break; - } - }; - DTMF.prototype.onRequestTimeout = function () { - this.emit("failed", undefined, Constants_1.C.causes.REQUEST_TIMEOUT); - this.owner.onRequestTimeout(); - }; - DTMF.prototype.onTransportError = function () { - this.emit("failed", undefined, Constants_1.C.causes.CONNECTION_ERROR); - this.owner.onTransportError(); - }; - DTMF.prototype.onDialogError = function (response) { - this.emit("failed", response, Constants_1.C.causes.DIALOG_ERROR); - this.owner.onDialogError(response); - }; - return DTMF; -}(events_1.EventEmitter)); -exports.DTMF = DTMF; - - -/***/ }), -/* 92 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var events_1 = __webpack_require__(30); -var Constants_1 = __webpack_require__(80); -var core_1 = __webpack_require__(2); -var allowed_methods_1 = __webpack_require__(58); -var Enums_1 = __webpack_require__(82); -var Utils_1 = __webpack_require__(83); -/** - * While this class is named `Subscription`, it is closer to - * an implementation of a "subscriber" as defined in RFC 6665 - * "SIP-Specific Event Notifications". - * https://tools.ietf.org/html/rfc6665 - * @class Class creating a SIP Subscriber. - */ -var Subscription = /** @class */ (function (_super) { - tslib_1.__extends(Subscription, _super); - /** - * Constructor. - * @param ua User agent. - * @param target Subscription target. - * @param event Subscription event. - * @param options Options bucket. - */ - function Subscription(ua, target, event, options) { - if (options === void 0) { options = {}; } - var _this = _super.call(this) || this; - _this.data = {}; - _this.method = Constants_1.C.SUBSCRIBE; - _this.body = undefined; - // ClientContext interface - _this.type = Enums_1.TypeStrings.Subscription; - _this.ua = ua; - _this.logger = ua.getLogger("sip.subscription"); - if (options.body) { - _this.body = { - body: options.body, - contentType: options.contentType ? options.contentType : "application/sdp" - }; - } - // Target URI - var uri = ua.normalizeTarget(target); - if (!uri) { - throw new TypeError("Invalid target: " + target); - } - _this.uri = uri; - // Subscription event - _this.event = event; - // Subscription expires - if (options.expires === undefined) { - _this.expires = 3600; - } - else if (typeof options.expires !== "number") { // pre-typescript type guard - ua.logger.warn("Option \"expires\" must be a number. Using default of 3600."); - _this.expires = 3600; - } - else { - _this.expires = options.expires; - } - // Subscription extra headers - _this.extraHeaders = (options.extraHeaders || []).slice(); - // Subscription context. - _this.context = _this.initContext(); - _this.disposed = false; - // ClientContext interface - _this.request = _this.context.message; - if (!_this.request.from) { - throw new Error("From undefined."); - } - if (!_this.request.to) { - throw new Error("From undefined."); - } - _this.localIdentity = _this.request.from; - _this.remoteIdentity = _this.request.to; - // Add to UA's collection - _this.id = _this.request.callId + _this.request.from.parameters.tag + _this.event; - _this.ua.subscriptions[_this.id] = _this; - return _this; - } - /** - * Destructor. - */ - Subscription.prototype.dispose = function () { - if (this.disposed) { - return; - } - if (this.retryAfterTimer) { - clearTimeout(this.retryAfterTimer); - this.retryAfterTimer = undefined; - } - this.context.dispose(); - this.disposed = true; - // Remove from UA's collection - delete this.ua.subscriptions[this.id]; - }; - Subscription.prototype.on = function (name, callback) { - return _super.prototype.on.call(this, name, callback); - }; - Subscription.prototype.emit = function (event) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - return _super.prototype.emit.apply(this, [event].concat(args)); - }; - /** - * Gracefully terminate. - */ - Subscription.prototype.close = function () { - if (this.disposed) { - return; - } - this.dispose(); - switch (this.context.state) { - case core_1.SubscriptionState.Initial: - this.onTerminated(); - break; - case core_1.SubscriptionState.NotifyWait: - this.onTerminated(); - break; - case core_1.SubscriptionState.Pending: - this.unsubscribe(); - break; - case core_1.SubscriptionState.Active: - this.unsubscribe(); - break; - case core_1.SubscriptionState.Terminated: - this.onTerminated(); - break; - default: - break; - } - }; - /** - * Send a re-SUBSCRIBE request if there is an "active" subscription. - */ - Subscription.prototype.refresh = function () { - var _this = this; - switch (this.context.state) { - case core_1.SubscriptionState.Initial: - break; - case core_1.SubscriptionState.NotifyWait: - break; - case core_1.SubscriptionState.Pending: - break; - case core_1.SubscriptionState.Active: - if (this.subscription) { - var request = this.subscription.refresh(); - request.delegate = { - onAccept: (function (response) { return _this.onAccepted(response); }), - onRedirect: (function (response) { return _this.onFailed(response); }), - onReject: (function (response) { return _this.onFailed(response); }), - }; - } - break; - case core_1.SubscriptionState.Terminated: - break; - default: - break; - } - }; - /** - * Send an initial SUBSCRIBE request if no subscription. - * Send a re-SUBSCRIBE request if there is an "active" subscription. - */ - Subscription.prototype.subscribe = function () { - var _this = this; - switch (this.context.state) { - case core_1.SubscriptionState.Initial: - this.context.subscribe().then(function (result) { - if (result.success) { - if (result.success.subscription) { - _this.subscription = result.success.subscription; - _this.subscription.delegate = { - onNotify: function (request) { return _this.onNotify(request); }, - onRefresh: function (request) { return _this.onRefresh(request); }, - onTerminated: function () { return _this.close(); } - }; - } - _this.onNotify(result.success.request); - } - else if (result.failure) { - _this.onFailed(result.failure.response); - } - }); - break; - case core_1.SubscriptionState.NotifyWait: - break; - case core_1.SubscriptionState.Pending: - break; - case core_1.SubscriptionState.Active: - this.refresh(); - break; - case core_1.SubscriptionState.Terminated: - break; - default: - break; - } - return this; - }; - /** - * Send a re-SUBSCRIBE request if there is a "pending" or "active" subscription. - */ - Subscription.prototype.unsubscribe = function () { - this.dispose(); - switch (this.context.state) { - case core_1.SubscriptionState.Initial: - break; - case core_1.SubscriptionState.NotifyWait: - break; - case core_1.SubscriptionState.Pending: - if (this.subscription) { - this.subscription.unsubscribe(); - // responses intentionally ignored - } - break; - case core_1.SubscriptionState.Active: - if (this.subscription) { - this.subscription.unsubscribe(); - // responses intentionally ignored - } - break; - case core_1.SubscriptionState.Terminated: - break; - default: - break; - } - this.onTerminated(); - }; - Subscription.prototype.onAccepted = function (response) { - var statusCode = response.message.statusCode ? response.message.statusCode : 0; - var cause = Utils_1.Utils.getReasonPhrase(statusCode); - this.emit("accepted", response.message, cause); - }; - Subscription.prototype.onFailed = function (response) { - this.close(); - if (response) { - var statusCode = response.message.statusCode ? response.message.statusCode : 0; - var cause = Utils_1.Utils.getReasonPhrase(statusCode); - this.emit("failed", response.message, cause); - this.emit("rejected", response.message, cause); - } - }; - Subscription.prototype.onNotify = function (request) { - var _this = this; - request.accept(); // Send 200 response. - this.emit("notify", { request: request.message }); - // If we've set state to done, no further processing should take place - // and we are only interested in cleaning up after the appropriate NOTIFY. - if (this.disposed) { - return; - } - // If the "Subscription-State" value is "terminated", the subscriber - // MUST consider the subscription terminated. The "expires" parameter - // has no semantics for "terminated" -- notifiers SHOULD NOT include an - // "expires" parameter on a "Subscription-State" header field with a - // value of "terminated", and subscribers MUST ignore any such - // parameter, if present. If a reason code is present, the client - // should behave as described below. If no reason code or an unknown - // reason code is present, the client MAY attempt to re-subscribe at any - // time (unless a "retry-after" parameter is present, in which case the - // client SHOULD NOT attempt re-subscription until after the number of - // seconds specified by the "retry-after" parameter). The reason codes - // defined by this document are: - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - var subscriptionState = request.message.parseHeader("Subscription-State"); - if (subscriptionState && subscriptionState.state) { - switch (subscriptionState.state) { - case "terminated": - if (subscriptionState.reason) { - this.logger.log("Terminated subscription with reason " + subscriptionState.reason); - switch (subscriptionState.reason) { - case "deactivated": - case "timeout": - this.initContext(); - this.subscribe(); - return; - case "probation": - case "giveup": - this.initContext(); - if (subscriptionState.params && subscriptionState.params["retry-after"]) { - this.retryAfterTimer = setTimeout(function () { return _this.subscribe(); }, subscriptionState.params["retry-after"]); - } - else { - this.subscribe(); - } - return; - case "rejected": - case "noresource": - case "invariant": - break; - } - } - this.close(); - break; - default: - break; - } - } - }; - Subscription.prototype.onRefresh = function (request) { - var _this = this; - request.delegate = { - onAccept: function (response) { return _this.onAccepted(response); } - }; - }; - Subscription.prototype.onTerminated = function () { - this.emit("terminated"); - }; - Subscription.prototype.initContext = function () { - var _this = this; - var options = { - extraHeaders: this.extraHeaders, - body: this.body ? Utils_1.Utils.fromBodyObj(this.body) : undefined - }; - this.context = new SubscribeClientContext(this.ua.userAgentCore, this.uri, this.event, this.expires, options); - this.context.delegate = { - onAccept: (function (response) { return _this.onAccepted(response); }) - }; - return this.context; - }; - return Subscription; -}(events_1.EventEmitter)); -exports.Subscription = Subscription; -// tslint:disable-next-line:max-classes-per-file -var SubscribeClientContext = /** @class */ (function () { - function SubscribeClientContext(core, target, event, expires, options, delegate) { - this.core = core; - this.target = target; - this.event = event; - this.expires = expires; - this.subscribed = false; - this.logger = core.loggerFactory.getLogger("sip.subscription"); - this.delegate = delegate; - var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); - var extraHeaders = (options && options.extraHeaders || []).slice(); - extraHeaders.push(allowHeader); - extraHeaders.push("Event: " + this.event); - extraHeaders.push("Expires: " + this.expires); - extraHeaders.push("Contact: " + this.core.configuration.contact.toString()); - var body = options && options.body; - this.message = core.makeOutgoingRequestMessage(Constants_1.C.SUBSCRIBE, this.target, this.core.configuration.aor, this.target, {}, extraHeaders, body); - } - /** Destructor. */ - SubscribeClientContext.prototype.dispose = function () { - if (this.subscription) { - this.subscription.dispose(); - } - if (this.request) { - this.request.waitNotifyStop(); - this.request.dispose(); - } - }; - Object.defineProperty(SubscribeClientContext.prototype, "state", { - /** Subscription state. */ - get: function () { - if (this.subscription) { - return this.subscription.subscriptionState; - } - else if (this.subscribed) { - return core_1.SubscriptionState.NotifyWait; - } - else { - return core_1.SubscriptionState.Initial; - } - }, - enumerable: true, - configurable: true - }); - /** - * Establish subscription. - * @param options Options bucket. - */ - SubscribeClientContext.prototype.subscribe = function () { - var _this = this; - if (this.subscribed) { - return Promise.reject(new Error("Not in initial state. Did you call subscribe more than once?")); - } - this.subscribed = true; - return new Promise(function (resolve, reject) { - if (!_this.message) { - throw new Error("Message undefined."); - } - _this.request = _this.core.subscribe(_this.message, { - // This SUBSCRIBE request will be confirmed with a final response. - // 200-class responses indicate that the subscription has been accepted - // and that a NOTIFY request will be sent immediately. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - onAccept: function (response) { - if (_this.delegate && _this.delegate.onAccept) { - _this.delegate.onAccept(response); - } - }, - // Due to the potential for out-of-order messages, packet loss, and - // forking, the subscriber MUST be prepared to receive NOTIFY requests - // before the SUBSCRIBE transaction has completed. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.4 - onNotify: function (requestWithSubscription) { - _this.subscription = requestWithSubscription.subscription; - if (_this.subscription) { - _this.subscription.autoRefresh = true; - } - resolve({ success: requestWithSubscription }); - }, - // If this Timer N expires prior to the receipt of a NOTIFY request, - // the subscriber considers the subscription failed, and cleans up - // any state associated with the subscription attempt. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.4 - onNotifyTimeout: function () { - resolve({ failure: {} }); - }, - // This SUBSCRIBE request will be confirmed with a final response. - // Non-200-class final responses indicate that no subscription or new - // dialog usage has been created, and no subsequent NOTIFY request will - // be sent. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - onRedirect: function (response) { - resolve({ failure: { response: response } }); - }, - // This SUBSCRIBE request will be confirmed with a final response. - // Non-200-class final responses indicate that no subscription or new - // dialog usage has been created, and no subsequent NOTIFY request will - // be sent. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - onReject: function (response) { - resolve({ failure: { response: response } }); - } - }); - }); - }; - return SubscribeClientContext; -}()); - - -/***/ }), -/* 93 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var events_1 = __webpack_require__(30); -var ClientContext_1 = __webpack_require__(79); -var Constants_1 = __webpack_require__(80); -var core_1 = __webpack_require__(2); -var Enums_1 = __webpack_require__(82); -var Exceptions_1 = __webpack_require__(84); -var Parser_1 = __webpack_require__(85); -var PublishContext_1 = __webpack_require__(86); -var ReferContext_1 = __webpack_require__(87); -var RegisterContext_1 = __webpack_require__(89); -var ServerContext_1 = __webpack_require__(88); -var Session_1 = __webpack_require__(90); -var Subscription_1 = __webpack_require__(92); -var Utils_1 = __webpack_require__(83); -var SessionDescriptionHandler_1 = __webpack_require__(94); -var Transport_1 = __webpack_require__(103); -/** - * @class Class creating a SIP User Agent. - * @param {function returning SIP.sessionDescriptionHandler} [configuration.sessionDescriptionHandlerFactory] - * A function will be invoked by each of the UA's Sessions to build the sessionDescriptionHandler for that Session. - * If no (or a falsy) value is provided, each Session will use a default (WebRTC) sessionDescriptionHandler. - */ -var UA = /** @class */ (function (_super) { - tslib_1.__extends(UA, _super); - function UA(configuration) { - var _this = _super.call(this) || this; - /** Unload listener. */ - _this.unloadListener = (function () { _this.stop(); }); - _this.type = Enums_1.TypeStrings.UA; - _this.log = new core_1.LoggerFactory(); - _this.logger = _this.getLogger("sip.ua"); - _this.configuration = {}; - // User actions outside any session/dialog (MESSAGE) - _this.applicants = {}; - _this.data = {}; - _this.sessions = {}; - _this.subscriptions = {}; - _this.publishers = {}; - _this.status = Enums_1.UAStatus.STATUS_INIT; - /** - * Load configuration - * - * @throws {SIP.Exceptions.ConfigurationError} - * @throws {TypeError} - */ - if (configuration === undefined) { - configuration = {}; - } - else if (typeof configuration === "string" || configuration instanceof String) { - configuration = { - uri: configuration - }; - } - // Apply log configuration if present - if (configuration.log) { - _this.log.builtinEnabled = configuration.log.builtinEnabled; - if (configuration.log.hasOwnProperty("connector")) { - _this.log.connector = configuration.log.connector; - } - if (configuration.log.hasOwnProperty("level")) { - var level = configuration.log.level; - var normalized = void 0; - if (typeof level === "string") { - switch (level) { - case "error": - normalized = core_1.Levels.error; - break; - case "warn": - normalized = core_1.Levels.warn; - break; - case "log": - normalized = core_1.Levels.log; - break; - case "debug": - normalized = core_1.Levels.debug; - break; - default: - break; - } - } - else { - switch (level) { - case 0: - normalized = core_1.Levels.error; - break; - case 1: - normalized = core_1.Levels.warn; - break; - case 2: - normalized = core_1.Levels.log; - break; - case 3: - normalized = core_1.Levels.debug; - break; - default: - break; - } - } - // avoid setting level when invalid, use default level instead - if (normalized === undefined) { - _this.logger.error("Invalid \"level\" parameter value: " + JSON.stringify(level)); - } - else { - _this.log.level = normalized; - } - } - } - var deprecatedMessage = "The UA class has been deprecated and will no longer be available starting with SIP.js release 0.16.0. " + - "The UA has been replaced by the UserAgent class. Please update accordingly."; - _this.logger.warn(deprecatedMessage); - try { - _this.loadConfig(configuration); - } - catch (e) { - _this.status = Enums_1.UAStatus.STATUS_NOT_READY; - _this.error = UA.C.CONFIGURATION_ERROR; - throw e; - } - if (!_this.configuration.transportConstructor) { - throw new core_1.TransportError("Transport constructor not set"); - } - _this.transport = new _this.configuration.transportConstructor(_this.getLogger("sip.transport"), _this.configuration.transportOptions); - var userAgentCoreConfiguration = makeUserAgentCoreConfigurationFromUA(_this); - // The Replaces header contains information used to match an existing - // SIP dialog (call-id, to-tag, and from-tag). Upon receiving an INVITE - // with a Replaces header, the User Agent (UA) attempts to match this - // information with a confirmed or early dialog. - // https://tools.ietf.org/html/rfc3891#section-3 - var handleInviteWithReplacesHeader = function (context, request) { - if (_this.configuration.replaces !== Constants_1.C.supported.UNSUPPORTED) { - var replaces = request.parseHeader("replaces"); - if (replaces) { - var targetSession = _this.sessions[replaces.call_id + replaces.replaces_from_tag] || - _this.sessions[replaces.call_id + replaces.replaces_to_tag] || - undefined; - if (!targetSession) { - _this.userAgentCore.replyStateless(request, { statusCode: 481 }); - return; - } - if (targetSession.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - _this.userAgentCore.replyStateless(request, { statusCode: 603 }); - return; - } - var targetDialogId = replaces.call_id + replaces.replaces_to_tag + replaces.replaces_from_tag; - var targetDialog = _this.userAgentCore.dialogs.get(targetDialogId); - if (!targetDialog) { - _this.userAgentCore.replyStateless(request, { statusCode: 481 }); - return; - } - if (!targetDialog.early && replaces.early_only) { - _this.userAgentCore.replyStateless(request, { statusCode: 486 }); - return; - } - context.replacee = targetSession; - } - } - }; - var userAgentCoreDelegate = { - onInvite: function (incomingInviteRequest) { - // FIXME: Ported - 100 Trying send should be configurable. - // Only required if TU will not respond in 200ms. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - incomingInviteRequest.trying(); - incomingInviteRequest.delegate = { - onCancel: function (cancel) { - context.onCancel(cancel); - }, - onTransportError: function (error) { - context.onTransportError(); - } - }; - var context = new Session_1.InviteServerContext(_this, incomingInviteRequest); - // Ported - handling of out of dialog INVITE with Replaces. - handleInviteWithReplacesHeader(context, incomingInviteRequest.message); - // Ported - make the first call to progress automatically. - if (context.autoSendAnInitialProvisionalResponse) { - context.progress(); - } - _this.emit("invite", context); - }, - onMessage: function (incomingMessageRequest) { - // Ported - handling of out of dialog MESSAGE. - var serverContext = new ServerContext_1.ServerContext(_this, incomingMessageRequest); - serverContext.body = incomingMessageRequest.message.body; - serverContext.contentType = incomingMessageRequest.message.getHeader("Content-Type") || "text/plain"; - incomingMessageRequest.accept(); - _this.emit("message", serverContext); // TODO: Review. Why is a "ServerContext" emitted? What use it is? - }, - onNotify: function (incomingNotifyRequest) { - // DEPRECATED: Out of dialog NOTIFY is an obsolete usage. - // Ported - handling of out of dialog NOTIFY. - if (_this.configuration.allowLegacyNotifications && _this.listeners("notify").length > 0) { - incomingNotifyRequest.accept(); - _this.emit("notify", { request: incomingNotifyRequest.message }); - } - else { - incomingNotifyRequest.reject({ statusCode: 481 }); - } - }, - onRefer: function (incomingReferRequest) { - // Ported - handling of out of dialog REFER. - _this.logger.log("Received an out of dialog refer"); - if (!_this.configuration.allowOutOfDialogRefers) { - incomingReferRequest.reject({ statusCode: 405 }); - } - _this.logger.log("Allow out of dialog refers is enabled on the UA"); - var referContext = new ReferContext_1.ReferServerContext(_this, incomingReferRequest); - if (_this.listeners("outOfDialogReferRequested").length) { - _this.emit("outOfDialogReferRequested", referContext); - } - else { - _this.logger.log("No outOfDialogReferRequest listeners, automatically accepting and following the out of dialog refer"); - referContext.accept({ followRefer: true }); - } - }, - onSubscribe: function (incomingSubscribeRequest) { - _this.emit("subscribe", incomingSubscribeRequest); - }, - }; - _this.userAgentCore = new core_1.UserAgentCore(userAgentCoreConfiguration, userAgentCoreDelegate); - // Initialize registerContext - _this.registerContext = new RegisterContext_1.RegisterContext(_this, configuration.registerOptions); - _this.registerContext.on("failed", _this.emit.bind(_this, "registrationFailed")); - _this.registerContext.on("registered", _this.emit.bind(_this, "registered")); - _this.registerContext.on("unregistered", _this.emit.bind(_this, "unregistered")); - if (_this.configuration.autostart) { - _this.start(); - } - return _this; - } - // ================= - // High Level API - // ================= - UA.prototype.register = function (options) { - if (options === void 0) { options = {}; } - if (options.register) { - this.configuration.register = true; - } - this.registerContext.register(options); - return this; - }; - /** - * Unregister. - * - * @param {Boolean} [all] unregister all user bindings. - * - */ - UA.prototype.unregister = function (options) { - var _this = this; - this.configuration.register = false; - this.transport.afterConnected(function () { - _this.registerContext.unregister(options); - }); - return this; - }; - UA.prototype.isRegistered = function () { - return this.registerContext.registered; - }; - /** - * Make an outgoing call. - * - * @param {String} target - * @param {Object} views - * @param {Object} [options.media] gets passed to SIP.sessionDescriptionHandler.getDescription as mediaHint - * - * @throws {TypeError} - * - */ - UA.prototype.invite = function (target, options, modifiers) { - var _this = this; - var context = new Session_1.InviteClientContext(this, target, options, modifiers); - // Delay sending actual invite until the next 'tick' if we are already - // connected, so that API consumers can register to events fired by the - // the session. - this.transport.afterConnected(function () { - context.invite(); - _this.emit("inviteSent", context); - }); - return context; - }; - UA.prototype.subscribe = function (target, event, options) { - var sub = new Subscription_1.Subscription(this, target, event, options); - this.transport.afterConnected(function () { return sub.subscribe(); }); - return sub; - }; - /** - * Send PUBLISH Event State Publication (RFC3903) - * - * @param {String} target - * @param {String} event - * @param {String} body - * @param {Object} [options] - * - * @throws {SIP.Exceptions.MethodParameterError} - */ - UA.prototype.publish = function (target, event, body, options) { - var pub = new PublishContext_1.PublishContext(this, target, event, options); - this.transport.afterConnected(function () { - pub.publish(body); - }); - return pub; - }; - /** - * Send a message. - * - * @param {String} target - * @param {String} body - * @param {Object} [options] - * - * @throws {TypeError} - */ - UA.prototype.message = function (target, body, options) { - if (options === void 0) { options = {}; } - if (body === undefined) { - throw new TypeError("Not enough arguments"); - } - // There is no Message module, so it is okay that the UA handles defaults here. - options.contentType = options.contentType || "text/plain"; - options.body = body; - return this.request(Constants_1.C.MESSAGE, target, options); - }; - UA.prototype.request = function (method, target, options) { - var req = new ClientContext_1.ClientContext(this, method, target, options); - this.transport.afterConnected(function () { return req.send(); }); - return req; - }; - /** - * Gracefully close. - */ - UA.prototype.stop = function () { - this.logger.log("user requested closure..."); - if (this.status === Enums_1.UAStatus.STATUS_USER_CLOSED) { - this.logger.warn("UA already closed"); - return this; - } - // Close registerContext - this.logger.log("closing registerContext"); - this.registerContext.close(); - // Run terminate on every Session - for (var session in this.sessions) { - if (this.sessions[session]) { - this.logger.log("closing session " + session); - this.sessions[session].terminate(); - } - } - // Run unsubscribe on every Subscription - for (var subscription in this.subscriptions) { - if (this.subscriptions[subscription]) { - this.logger.log("unsubscribe " + subscription); - this.subscriptions[subscription].unsubscribe(); - } - } - // Run close on every Publisher - for (var publisher in this.publishers) { - if (this.publishers[publisher]) { - this.logger.log("unpublish " + publisher); - this.publishers[publisher].close(); - } - } - // Run close on every applicant - for (var applicant in this.applicants) { - if (this.applicants[applicant]) { - this.applicants[applicant].close(); - } - } - this.status = Enums_1.UAStatus.STATUS_USER_CLOSED; - // Disconnect the transport and reset user agent core - this.transport.disconnect(); - this.userAgentCore.reset(); - if (this.configuration.autostop) { - // Google Chrome Packaged Apps don't allow 'unload' listeners: unload is not available in packaged apps - var googleChromePackagedApp = typeof chrome !== "undefined" && chrome.app && chrome.app.runtime ? true : false; - if (typeof window !== "undefined" && - typeof window.removeEventListener === "function" && - !googleChromePackagedApp) { - window.removeEventListener("unload", this.unloadListener); - } - } - return this; - }; - /** - * Connect to the WS server if status = STATUS_INIT. - * Resume UA after being closed. - * - */ - UA.prototype.start = function () { - this.logger.log("user requested startup..."); - if (this.status === Enums_1.UAStatus.STATUS_INIT) { - this.status = Enums_1.UAStatus.STATUS_STARTING; - this.setTransportListeners(); - this.emit("transportCreated", this.transport); - this.transport.connect(); - } - else if (this.status === Enums_1.UAStatus.STATUS_USER_CLOSED) { - this.logger.log("resuming"); - this.status = Enums_1.UAStatus.STATUS_READY; - this.transport.connect(); - } - else if (this.status === Enums_1.UAStatus.STATUS_STARTING) { - this.logger.log("UA is in STARTING status, not opening new connection"); - } - else if (this.status === Enums_1.UAStatus.STATUS_READY) { - this.logger.log("UA is in READY status, not resuming"); - } - else { - this.logger.error("Connection is down. Auto-Recovery system is trying to connect"); - } - if (this.configuration.autostop) { - // Google Chrome Packaged Apps don't allow 'unload' listeners: unload is not available in packaged apps - var googleChromePackagedApp = typeof chrome !== "undefined" && chrome.app && chrome.app.runtime ? true : false; - if (typeof window !== "undefined" && - typeof window.addEventListener === "function" && - !googleChromePackagedApp) { - window.addEventListener("unload", this.unloadListener); - } - } - return this; - }; - /** - * Normalize a string into a valid SIP request URI - * - * @param {String} target - * - * @returns {SIP.URI|undefined} - */ - UA.prototype.normalizeTarget = function (target) { - return Utils_1.Utils.normalizeTarget(target, this.configuration.hostportParams); - }; - UA.prototype.getLogger = function (category, label) { - return this.log.getLogger(category, label); - }; - UA.prototype.getLoggerFactory = function () { - return this.log; - }; - UA.prototype.getSupportedResponseOptions = function () { - var optionTags = []; - if (this.contact.pubGruu || this.contact.tempGruu) { - optionTags.push("gruu"); - } - if (this.configuration.rel100 === Constants_1.C.supported.SUPPORTED) { - optionTags.push("100rel"); - } - if (this.configuration.replaces === Constants_1.C.supported.SUPPORTED) { - optionTags.push("replaces"); - } - optionTags.push("outbound"); - optionTags = optionTags.concat(this.configuration.extraSupported || []); - var allowUnregistered = this.configuration.hackAllowUnregisteredOptionTags || false; - var optionTagSet = {}; - optionTags = optionTags.filter(function (optionTag) { - var registered = Constants_1.C.OPTION_TAGS[optionTag]; - var unique = !optionTagSet[optionTag]; - optionTagSet[optionTag] = true; - return (registered || allowUnregistered) && unique; - }); - return optionTags; - }; - /** - * Get the session to which the request belongs to, if any. - * @param {SIP.IncomingRequest} request. - * @returns {SIP.OutgoingSession|SIP.IncomingSession|undefined} - */ - UA.prototype.findSession = function (request) { - return this.sessions[request.callId + request.fromTag] || - this.sessions[request.callId + request.toTag] || - undefined; - }; - UA.prototype.on = function (name, callback) { return _super.prototype.on.call(this, name, callback); }; - // ============================== - // Event Handlers - // ============================== - UA.prototype.onTransportError = function () { - if (this.status === Enums_1.UAStatus.STATUS_USER_CLOSED) { - return; - } - if (!this.error || this.error !== UA.C.NETWORK_ERROR) { - this.status = Enums_1.UAStatus.STATUS_NOT_READY; - this.error = UA.C.NETWORK_ERROR; - } - }; - /** - * Helper function. Sets transport listeners - */ - UA.prototype.setTransportListeners = function () { - var _this = this; - this.transport.on("connected", function () { return _this.onTransportConnected(); }); - this.transport.on("message", function (message) { return _this.onTransportReceiveMsg(message); }); - this.transport.on("transportError", function () { return _this.onTransportError(); }); - }; - /** - * Transport connection event. - * @event - * @param {SIP.Transport} transport. - */ - UA.prototype.onTransportConnected = function () { - var _this = this; - if (this.configuration.register) { - // In an effor to maintain behavior from when we "initialized" an - // authentication factory, this is in a Promise.then - Promise.resolve().then(function () { return _this.registerContext.register(); }); - } - }; - /** - * Handle SIP message received from the transport. - * @param messageString The message. - */ - UA.prototype.onTransportReceiveMsg = function (messageString) { - var _this = this; - var message = Parser_1.Parser.parseMessage(messageString, this.getLogger("sip.parser")); - if (!message) { - this.logger.warn("UA failed to parse incoming SIP message - discarding."); - return; - } - if (this.status === Enums_1.UAStatus.STATUS_USER_CLOSED && message instanceof core_1.IncomingRequestMessage) { - this.logger.warn("UA received message when status = USER_CLOSED - aborting"); - return; - } - // A valid SIP request formulated by a UAC MUST, at a minimum, contain - // the following header fields: To, From, CSeq, Call-ID, Max-Forwards, - // and Via; all of these header fields are mandatory in all SIP - // requests. - // https://tools.ietf.org/html/rfc3261#section-8.1.1 - var hasMinimumHeaders = function () { - var mandatoryHeaders = ["from", "to", "call_id", "cseq", "via"]; - for (var _i = 0, mandatoryHeaders_1 = mandatoryHeaders; _i < mandatoryHeaders_1.length; _i++) { - var header = mandatoryHeaders_1[_i]; - if (!message.hasHeader(header)) { - _this.logger.warn("Missing mandatory header field : " + header + "."); - return false; - } - } - return true; - }; - // Request Checks - if (message instanceof core_1.IncomingRequestMessage) { - // This is port of SanityCheck.minimumHeaders(). - if (!hasMinimumHeaders()) { - this.logger.warn("Request missing mandatory header field. Dropping."); - return; - } - // FIXME: This is non-standard and should be a configruable behavior (desirable regardless). - // Custom SIP.js check to reject request from ourself (this instance of SIP.js). - // This is port of SanityCheck.rfc3261_16_3_4(). - if (!message.toTag && message.callId.substr(0, 5) === this.configuration.sipjsId) { - this.userAgentCore.replyStateless(message, { statusCode: 482 }); - return; - } - // FIXME: This should be Transport check before we get here (Section 18). - // Custom SIP.js check to reject requests if body length wrong. - // This is port of SanityCheck.rfc3261_18_3_request(). - var len = Utils_1.Utils.str_utf8_length(message.body); - var contentLength = message.getHeader("content-length"); - if (contentLength && len < Number(contentLength)) { - this.userAgentCore.replyStateless(message, { statusCode: 400 }); - return; - } - } - // Reponse Checks - if (message instanceof core_1.IncomingResponseMessage) { - // This is port of SanityCheck.minimumHeaders(). - if (!hasMinimumHeaders()) { - this.logger.warn("Response missing mandatory header field. Dropping."); - return; - } - // Custom SIP.js check to drop responses if multiple Via headers. - // This is port of SanityCheck.rfc3261_8_1_3_3(). - if (message.getHeaders("via").length > 1) { - this.logger.warn("More than one Via header field present in the response. Dropping."); - return; - } - // FIXME: This should be Transport check before we get here (Section 18). - // Custom SIP.js check to drop responses if bad Via header. - // This is port of SanityCheck.rfc3261_18_1_2(). - if (message.via.host !== this.configuration.viaHost || message.via.port !== undefined) { - this.logger.warn("Via sent-by in the response does not match UA Via host value. Dropping."); - return; - } - // FIXME: This should be Transport check before we get here (Section 18). - // Custom SIP.js check to reject requests if body length wrong. - // This is port of SanityCheck.rfc3261_18_3_response(). - var len = Utils_1.Utils.str_utf8_length(message.body); - var contentLength = message.getHeader("content-length"); - if (contentLength && len < Number(contentLength)) { - this.logger.warn("Message body length is lower than the value in Content-Length header field. Dropping."); - return; - } - } - // Handle Request - if (message instanceof core_1.IncomingRequestMessage) { - this.userAgentCore.receiveIncomingRequestFromTransport(message); - return; - } - // Handle Response - if (message instanceof core_1.IncomingResponseMessage) { - this.userAgentCore.receiveIncomingResponseFromTransport(message); - return; - } - throw new Error("Invalid message type."); - }; - // ================= - // Utils - // ================= - UA.prototype.checkAuthenticationFactory = function (authenticationFactory) { - if (!(authenticationFactory instanceof Function)) { - return; - } - if (!authenticationFactory.initialize) { - authenticationFactory.initialize = function () { - return Promise.resolve(); - }; - } - return authenticationFactory; - }; - /** - * Configuration load. - * returns {void} - */ - UA.prototype.loadConfig = function (configuration) { - var _this = this; - // Settings and default values - var settings = { - /* Host address - * Value to be set in Via sent_by and host part of Contact FQDN - */ - viaHost: Utils_1.Utils.createRandomToken(12) + ".invalid", - uri: new core_1.URI("sip", "anonymous." + Utils_1.Utils.createRandomToken(6), "anonymous.invalid", undefined, undefined), - // Custom Configuration Settings - custom: {}, - // Display name - displayName: "", - // Password - password: undefined, - register: true, - // Registration parameters - registerOptions: {}, - // Transport related parameters - transportConstructor: Transport_1.Transport, - transportOptions: {}, - usePreloadedRoute: false, - // string to be inserted into User-Agent request header - userAgentString: Constants_1.C.USER_AGENT, - // Session parameters - noAnswerTimeout: 60, - // Hacks - hackViaTcp: false, - hackIpInContact: false, - hackWssInTransport: false, - hackAllowUnregisteredOptionTags: false, - // Session Description Handler Options - sessionDescriptionHandlerFactoryOptions: { - constraints: {}, - peerConnectionOptions: {} - }, - extraSupported: [], - contactName: Utils_1.Utils.createRandomToken(8), - contactTransport: "ws", - forceRport: false, - // autostarting - autostart: true, - autostop: true, - // Reliable Provisional Responses - rel100: Constants_1.C.supported.UNSUPPORTED, - // DTMF type: 'info' or 'rtp' (RFC 4733) - // RTP Payload Spec: https://tools.ietf.org/html/rfc4733 - // WebRTC Audio Spec: https://tools.ietf.org/html/rfc7874 - dtmfType: Constants_1.C.dtmfType.INFO, - // Replaces header (RFC 3891) - // http://tools.ietf.org/html/rfc3891 - replaces: Constants_1.C.supported.UNSUPPORTED, - sessionDescriptionHandlerFactory: SessionDescriptionHandler_1.SessionDescriptionHandler.defaultFactory, - authenticationFactory: this.checkAuthenticationFactory(function (ua) { - return new core_1.DigestAuthentication(ua.getLoggerFactory(), _this.configuration.authorizationUser, _this.configuration.password); - }), - allowLegacyNotifications: false, - allowOutOfDialogRefers: false, - experimentalFeatures: false - }; - var configCheck = this.getConfigurationCheck(); - // Check Mandatory parameters - for (var parameter in configCheck.mandatory) { - if (!configuration.hasOwnProperty(parameter)) { - throw new Exceptions_1.Exceptions.ConfigurationError(parameter); - } - else { - var value = configuration[parameter]; - var checkedValue = configCheck.mandatory[parameter](value); - if (checkedValue !== undefined) { - settings[parameter] = checkedValue; - } - else { - throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); - } - } - } - // Check Optional parameters - for (var parameter in configCheck.optional) { - if (configuration.hasOwnProperty(parameter)) { - var value = configuration[parameter]; - // If the parameter value is an empty array, but shouldn't be, apply its default value. - // If the parameter value is null, empty string, or undefined then apply its default value. - // If it's a number with NaN value then also apply its default value. - // NOTE: JS does not allow "value === NaN", the following does the work: - if ((value instanceof Array && value.length === 0) || - (value === null || value === "" || value === undefined) || - (typeof (value) === "number" && isNaN(value))) { - continue; - } - var checkedValue = configCheck.optional[parameter](value); - if (checkedValue !== undefined) { - settings[parameter] = checkedValue; - } - else { - throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); - } - } - } - // Post Configuration Process - // Allow passing 0 number as displayName. - if (settings.displayName === 0) { - settings.displayName = "0"; - } - // sipjsId instance parameter. Static random tag of length 5 - settings.sipjsId = Utils_1.Utils.createRandomToken(5); - // String containing settings.uri without scheme and user. - var hostportParams = settings.uri.clone(); - hostportParams.user = undefined; - settings.hostportParams = hostportParams.toRaw().replace(/^sip:/i, ""); - /* Check whether authorizationUser is explicitly defined. - * Take 'settings.uri.user' value if not. - */ - if (!settings.authorizationUser) { - settings.authorizationUser = settings.uri.user; - } - // User noAnswerTimeout - settings.noAnswerTimeout = settings.noAnswerTimeout * 1000; - // Via Host - if (settings.hackIpInContact) { - if (typeof settings.hackIpInContact === "boolean") { - var from = 1; - var to = 254; - var octet = Math.floor(Math.random() * (to - from + 1) + from); - // random Test-Net IP (http://tools.ietf.org/html/rfc5735) - settings.viaHost = "192.0.2." + octet; - } - else if (typeof settings.hackIpInContact === "string") { - settings.viaHost = settings.hackIpInContact; - } - } - // Contact transport parameter - if (settings.hackWssInTransport) { - settings.contactTransport = "wss"; - } - this.contact = { - pubGruu: undefined, - tempGruu: undefined, - uri: new core_1.URI("sip", settings.contactName, settings.viaHost, undefined, { transport: settings.contactTransport }), - toString: function (options) { - if (options === void 0) { options = {}; } - var anonymous = options.anonymous || false; - var outbound = options.outbound || false; - var contact = "<"; - if (anonymous) { - contact += (_this.contact.tempGruu || - ("sip:anonymous@anonymous.invalid;transport=" + settings.contactTransport)).toString(); - } - else { - contact += (_this.contact.pubGruu || _this.contact.uri).toString(); - } - if (outbound) { - contact += ";ob"; - } - contact += ">"; - return contact; - } - }; - var skeleton = {}; - // Fill the value of the configuration_skeleton - for (var parameter in settings) { - if (settings.hasOwnProperty(parameter)) { - skeleton[parameter] = settings[parameter]; - } - } - Object.assign(this.configuration, skeleton); - this.logger.log("configuration parameters after validation:"); - for (var parameter in settings) { - if (settings.hasOwnProperty(parameter)) { - switch (parameter) { - case "uri": - case "sessionDescriptionHandlerFactory": - this.logger.log("· " + parameter + ": " + settings[parameter]); - break; - case "password": - this.logger.log("· " + parameter + ": " + "NOT SHOWN"); - break; - case "transportConstructor": - this.logger.log("· " + parameter + ": " + settings[parameter].name); - break; - default: - this.logger.log("· " + parameter + ": " + JSON.stringify(settings[parameter])); - } - } - } - return; - }; - /** - * Configuration checker. - * @return {Boolean} - */ - UA.prototype.getConfigurationCheck = function () { - return { - mandatory: {}, - optional: { - uri: function (uri) { - if (!(/^sip:/i).test(uri)) { - uri = Constants_1.C.SIP + ":" + uri; - } - var parsed = core_1.Grammar.URIParse(uri); - if (!parsed || !parsed.user) { - return; - } - else { - return parsed; - } - }, - transportConstructor: function (transportConstructor) { - if (transportConstructor instanceof Function) { - return transportConstructor; - } - }, - transportOptions: function (transportOptions) { - if (typeof transportOptions === "object") { - return transportOptions; - } - }, - authorizationUser: function (authorizationUser) { - if (core_1.Grammar.parse('"' + authorizationUser + '"', "quoted_string") === -1) { - return; - } - else { - return authorizationUser; - } - }, - displayName: function (displayName) { - if (core_1.Grammar.parse('"' + displayName + '"', "displayName") === -1) { - return; - } - else { - return displayName; - } - }, - dtmfType: function (dtmfType) { - switch (dtmfType) { - case Constants_1.C.dtmfType.RTP: - return Constants_1.C.dtmfType.RTP; - case Constants_1.C.dtmfType.INFO: - // Fall through - default: - return Constants_1.C.dtmfType.INFO; - } - }, - hackViaTcp: function (hackViaTcp) { - if (typeof hackViaTcp === "boolean") { - return hackViaTcp; - } - }, - hackIpInContact: function (hackIpInContact) { - if (typeof hackIpInContact === "boolean") { - return hackIpInContact; - } - else if (typeof hackIpInContact === "string" && core_1.Grammar.parse(hackIpInContact, "host") !== -1) { - return hackIpInContact; - } - }, - hackWssInTransport: function (hackWssInTransport) { - if (typeof hackWssInTransport === "boolean") { - return hackWssInTransport; - } - }, - hackAllowUnregisteredOptionTags: function (hackAllowUnregisteredOptionTags) { - if (typeof hackAllowUnregisteredOptionTags === "boolean") { - return hackAllowUnregisteredOptionTags; - } - }, - contactTransport: function (contactTransport) { - if (typeof contactTransport === "string") { - return contactTransport; - } - }, - extraSupported: function (optionTags) { - if (!(optionTags instanceof Array)) { - return; - } - for (var _i = 0, optionTags_1 = optionTags; _i < optionTags_1.length; _i++) { - var tag = optionTags_1[_i]; - if (typeof tag !== "string") { - return; - } - } - return optionTags; - }, - forceRport: function (forceRport) { - if (typeof forceRport === "boolean") { - return forceRport; - } - }, - noAnswerTimeout: function (noAnswerTimeout) { - if (Utils_1.Utils.isDecimal(noAnswerTimeout)) { - var value = Number(noAnswerTimeout); - if (value > 0) { - return value; - } - } - }, - password: function (password) { - return String(password); - }, - rel100: function (rel100) { - if (rel100 === Constants_1.C.supported.REQUIRED) { - return Constants_1.C.supported.REQUIRED; - } - else if (rel100 === Constants_1.C.supported.SUPPORTED) { - return Constants_1.C.supported.SUPPORTED; - } - else { - return Constants_1.C.supported.UNSUPPORTED; - } - }, - replaces: function (replaces) { - if (replaces === Constants_1.C.supported.REQUIRED) { - return Constants_1.C.supported.REQUIRED; - } - else if (replaces === Constants_1.C.supported.SUPPORTED) { - return Constants_1.C.supported.SUPPORTED; - } - else { - return Constants_1.C.supported.UNSUPPORTED; - } - }, - register: function (register) { - if (typeof register === "boolean") { - return register; - } - }, - registerOptions: function (registerOptions) { - if (typeof registerOptions === "object") { - return registerOptions; - } - }, - usePreloadedRoute: function (usePreloadedRoute) { - if (typeof usePreloadedRoute === "boolean") { - return usePreloadedRoute; - } - }, - userAgentString: function (userAgentString) { - if (typeof userAgentString === "string") { - return userAgentString; - } - }, - autostart: function (autostart) { - if (typeof autostart === "boolean") { - return autostart; - } - }, - autostop: function (autostop) { - if (typeof autostop === "boolean") { - return autostop; - } - }, - sessionDescriptionHandlerFactory: function (sessionDescriptionHandlerFactory) { - if (sessionDescriptionHandlerFactory instanceof Function) { - return sessionDescriptionHandlerFactory; - } - }, - sessionDescriptionHandlerFactoryOptions: function (options) { - if (typeof options === "object") { - return options; - } - }, - authenticationFactory: this.checkAuthenticationFactory, - allowLegacyNotifications: function (allowLegacyNotifications) { - if (typeof allowLegacyNotifications === "boolean") { - return allowLegacyNotifications; - } - }, - custom: function (custom) { - if (typeof custom === "object") { - return custom; - } - }, - contactName: function (contactName) { - if (typeof contactName === "string") { - return contactName; - } - }, - experimentalFeatures: function (experimentalFeatures) { - if (typeof experimentalFeatures === "boolean") { - return experimentalFeatures; - } - }, - } - }; - }; - UA.C = { - // UA status codes - STATUS_INIT: 0, - STATUS_STARTING: 1, - STATUS_READY: 2, - STATUS_USER_CLOSED: 3, - STATUS_NOT_READY: 4, - // UA error codes - CONFIGURATION_ERROR: 1, - NETWORK_ERROR: 2, - ALLOWED_METHODS: [ - "ACK", - "CANCEL", - "INVITE", - "MESSAGE", - "BYE", - "OPTIONS", - "INFO", - "NOTIFY", - "REFER" - ], - ACCEPTED_BODY_TYPES: [ - "application/sdp", - "application/dtmf-relay" - ], - MAX_FORWARDS: 70, - TAG_LENGTH: 10 - }; - return UA; -}(events_1.EventEmitter)); -exports.UA = UA; -(function (UA) { - var DtmfType; - (function (DtmfType) { - DtmfType["RTP"] = "rtp"; - DtmfType["INFO"] = "info"; - })(DtmfType = UA.DtmfType || (UA.DtmfType = {})); -})(UA = exports.UA || (exports.UA = {})); -exports.UA = UA; -/** - * Factory function to generate configuration give a UA. - * @param ua UA - */ -function makeUserAgentCoreConfigurationFromUA(ua) { - // FIXME: Configuration URI is a bad mix of types currently. It also needs to exist. - if (!(ua.configuration.uri instanceof core_1.URI)) { - throw new Error("Configuration URI not instance of URI."); - } - var aor = ua.configuration.uri; - var contact = ua.contact; - var displayName = ua.configuration.displayName ? ua.configuration.displayName : ""; - var hackViaTcp = ua.configuration.hackViaTcp ? true : false; - var routeSet = ua.configuration.usePreloadedRoute && ua.transport.server && ua.transport.server.sipUri ? - [ua.transport.server.sipUri] : - []; - var sipjsId = ua.configuration.sipjsId || Utils_1.Utils.createRandomToken(5); - var supportedOptionTags = []; - supportedOptionTags.push("outbound"); // TODO: is this really supported? - if (ua.configuration.rel100 === Constants_1.C.supported.SUPPORTED) { - supportedOptionTags.push("100rel"); - } - if (ua.configuration.replaces === Constants_1.C.supported.SUPPORTED) { - supportedOptionTags.push("replaces"); - } - if (ua.configuration.extraSupported) { - supportedOptionTags.push.apply(supportedOptionTags, ua.configuration.extraSupported); - } - if (!ua.configuration.hackAllowUnregisteredOptionTags) { - supportedOptionTags = supportedOptionTags.filter(function (optionTag) { return Constants_1.C.OPTION_TAGS[optionTag]; }); - } - supportedOptionTags = Array.from(new Set(supportedOptionTags)); // array of unique values - var supportedOptionTagsResponse = ua.getSupportedResponseOptions(); - var userAgentHeaderFieldValue = ua.configuration.userAgentString || "sipjs"; - if (!(ua.configuration.viaHost)) { - throw new Error("Configuration via host undefined"); - } - var viaForceRport = ua.configuration.forceRport ? true : false; - var viaHost = ua.configuration.viaHost; - var configuration = { - aor: aor, - contact: contact, - displayName: displayName, - hackViaTcp: hackViaTcp, - loggerFactory: ua.getLoggerFactory(), - routeSet: routeSet, - sipjsId: sipjsId, - supportedOptionTags: supportedOptionTags, - supportedOptionTagsResponse: supportedOptionTagsResponse, - userAgentHeaderFieldValue: userAgentHeaderFieldValue, - viaForceRport: viaForceRport, - viaHost: viaHost, - authenticationFactory: function () { - if (ua.configuration.authenticationFactory) { - return ua.configuration.authenticationFactory(ua); - } - return undefined; - }, - transportAccessor: function () { return ua.transport; } - }; - return configuration; -} -exports.makeUserAgentCoreConfigurationFromUA = makeUserAgentCoreConfigurationFromUA; - - -/***/ }), -/* 94 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var events_1 = __webpack_require__(30); -var session_1 = __webpack_require__(95); -var Enums_1 = __webpack_require__(82); -var Exceptions_1 = __webpack_require__(84); -var Utils_1 = __webpack_require__(83); -var Modifiers = tslib_1.__importStar(__webpack_require__(101)); -var SessionDescriptionHandlerObserver_1 = __webpack_require__(102); -/* SessionDescriptionHandler - * @class PeerConnection helper Class. - * @param {SIP.Session} session - * @param {Object} [options] - */ -var SessionDescriptionHandler = /** @class */ (function (_super) { - tslib_1.__extends(SessionDescriptionHandler, _super); - function SessionDescriptionHandler(logger, observer, options) { - var _this = _super.call(this) || this; - _this.type = Enums_1.TypeStrings.SessionDescriptionHandler; - // TODO: Validate the options - _this.options = options || {}; - _this.logger = logger; - _this.observer = observer; - _this.dtmfSender = undefined; - _this.shouldAcquireMedia = true; - _this.CONTENT_TYPE = "application/sdp"; - _this.C = { - DIRECTION: { - NULL: null, - SENDRECV: "sendrecv", - SENDONLY: "sendonly", - RECVONLY: "recvonly", - INACTIVE: "inactive" - } - }; - _this.logger.log("SessionDescriptionHandlerOptions: " + JSON.stringify(_this.options)); - _this.direction = _this.C.DIRECTION.NULL; - _this.modifiers = _this.options.modifiers || []; - if (!Array.isArray(_this.modifiers)) { - _this.modifiers = [_this.modifiers]; - } - _this.iceGatheringTimeout = false; - _this.initPeerConnection(_this.options.peerConnectionOptions); - _this.constraints = _this.checkAndDefaultConstraints(_this.options.constraints); - return _this; - } - /** - * @param {SIP.Session} session - * @param {Object} [options] - */ - SessionDescriptionHandler.defaultFactory = function (session, options) { - var logger = (session instanceof session_1.Session) ? - session.userAgent.getLogger("sip.sessionDescriptionHandler", session.id) : - session.ua.getLogger("sip.invitecontext.sessionDescriptionHandler", session.id); - var observer = new SessionDescriptionHandlerObserver_1.SessionDescriptionHandlerObserver(session, options); - return new SessionDescriptionHandler(logger, observer, options); - }; - // Functions the sesssion can use - /** - * Destructor - */ - SessionDescriptionHandler.prototype.close = function () { - this.logger.log("closing PeerConnection"); - // have to check signalingState since this.close() gets called multiple times - if (this.peerConnection && this.peerConnection.signalingState !== "closed") { - if (this.peerConnection.getSenders) { - this.peerConnection.getSenders().forEach(function (sender) { - if (sender.track) { - sender.track.stop(); - } - }); - } - else { - this.logger.warn("Using getLocalStreams which is deprecated"); - this.peerConnection.getLocalStreams().forEach(function (stream) { - stream.getTracks().forEach(function (track) { - track.stop(); - }); - }); - } - if (this.peerConnection.getReceivers) { - this.peerConnection.getReceivers().forEach(function (receiver) { - if (receiver.track) { - receiver.track.stop(); - } - }); - } - else { - this.logger.warn("Using getRemoteStreams which is deprecated"); - this.peerConnection.getRemoteStreams().forEach(function (stream) { - stream.getTracks().forEach(function (track) { - track.stop(); - }); - }); - } - this.resetIceGatheringComplete(); - this.peerConnection.close(); - } - }; - /** - * Gets the local description from the underlying media implementation - * @param {Object} [options] Options object to be used by getDescription - * @param {MediaStreamConstraints} [options.constraints] MediaStreamConstraints - * https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints - * @param {Object} [options.peerConnectionOptions] If this is set it will recreate the peer - * connection with the new options - * @param {Array} [modifiers] Array with one time use description modifiers - * @returns {Promise} Promise that resolves with the local description to be used for the session - */ - SessionDescriptionHandler.prototype.getDescription = function (options, modifiers) { - var _this = this; - if (options === void 0) { options = {}; } - if (modifiers === void 0) { modifiers = []; } - if (options.peerConnectionOptions) { - this.initPeerConnection(options.peerConnectionOptions); - } - // Merge passed constraints with saved constraints and save - var newConstraints = Object.assign({}, this.constraints, options.constraints); - newConstraints = this.checkAndDefaultConstraints(newConstraints); - if (JSON.stringify(newConstraints) !== JSON.stringify(this.constraints)) { - this.constraints = newConstraints; - this.shouldAcquireMedia = true; - } - if (!Array.isArray(modifiers)) { - modifiers = [modifiers]; - } - modifiers = modifiers.concat(this.modifiers); - return Promise.resolve().then(function () { - if (_this.shouldAcquireMedia) { - return _this.acquire(_this.constraints).then(function () { - _this.shouldAcquireMedia = false; - }); - } - }).then(function () { return _this.createOfferOrAnswer(options.RTCOfferOptions, modifiers); }) - .then(function (description) { - if (description.sdp === undefined) { - throw new Exceptions_1.Exceptions.SessionDescriptionHandlerError("getDescription", undefined, "SDP undefined"); - } - _this.emit("getDescription", description); - return { - body: description.sdp, - contentType: _this.CONTENT_TYPE - }; - }); - }; - /** - * Check if the Session Description Handler can handle the Content-Type described by a SIP Message - * @param {String} contentType The content type that is in the SIP Message - * @returns {boolean} - */ - SessionDescriptionHandler.prototype.hasDescription = function (contentType) { - return contentType === this.CONTENT_TYPE; - }; - /** - * The modifier that should be used when the session would like to place the call on hold - * @param {String} [sdp] The description that will be modified - * @returns {Promise} Promise that resolves with modified SDP - */ - SessionDescriptionHandler.prototype.holdModifier = function (description) { - if (!description.sdp) { - return Promise.resolve(description); - } - if (!(/a=(sendrecv|sendonly|recvonly|inactive)/).test(description.sdp)) { - description.sdp = description.sdp.replace(/(m=[^\r]*\r\n)/g, "$1a=sendonly\r\n"); - } - else { - description.sdp = description.sdp.replace(/a=sendrecv\r\n/g, "a=sendonly\r\n"); - description.sdp = description.sdp.replace(/a=recvonly\r\n/g, "a=inactive\r\n"); - } - return Promise.resolve(description); - }; - /** - * Set the remote description to the underlying media implementation - * @param {String} sessionDescription The description provided by a SIP message to be set on the media implementation - * @param {Object} [options] Options object to be used by getDescription - * @param {MediaStreamConstraints} [options.constraints] MediaStreamConstraints - * https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints - * @param {Object} [options.peerConnectionOptions] If this is set it will recreate the peer - * connection with the new options - * @param {Array} [modifiers] Array with one time use description modifiers - * @returns {Promise} Promise that resolves once the description is set - */ - SessionDescriptionHandler.prototype.setDescription = function (sessionDescription, options, modifiers) { - var _this = this; - if (options === void 0) { options = {}; } - if (modifiers === void 0) { modifiers = []; } - if (options.peerConnectionOptions) { - this.initPeerConnection(options.peerConnectionOptions); - } - if (!Array.isArray(modifiers)) { - modifiers = [modifiers]; - } - modifiers = modifiers.concat(this.modifiers); - var description = { - type: this.hasOffer("local") ? "answer" : "offer", - sdp: sessionDescription - }; - return Promise.resolve().then(function () { - // Media should be acquired in getDescription unless we need to do it sooner for some reason (FF61+) - if (_this.shouldAcquireMedia && _this.options.alwaysAcquireMediaFirst) { - return _this.acquire(_this.constraints).then(function () { - _this.shouldAcquireMedia = false; - }); - } - }).then(function () { return Utils_1.Utils.reducePromises(modifiers, description); }) - .catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("setDescription", e, "The modifiers did not resolve successfully"); - _this.logger.error(error.message); - _this.emit("peerConnection-setRemoteDescriptionFailed", error); - throw error; - }).then(function (modifiedDescription) { - _this.emit("setDescription", modifiedDescription); - return _this.peerConnection.setRemoteDescription(modifiedDescription); - }).catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - // Check the original SDP for video, and ensure that we have want to do audio fallback - if ((/^m=video.+$/gm).test(sessionDescription) && !options.disableAudioFallback) { - // Do not try to audio fallback again - options.disableAudioFallback = true; - // Remove video first, then do the other modifiers - return _this.setDescription(sessionDescription, options, [Modifiers.stripVideo].concat(modifiers)); - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("setDescription", e); - if (error.error) { - _this.logger.error(error.error); - } - _this.emit("peerConnection-setRemoteDescriptionFailed", error); - throw error; - }).then(function () { - if (_this.peerConnection.getReceivers) { - _this.emit("setRemoteDescription", _this.peerConnection.getReceivers()); - } - else { - _this.emit("setRemoteDescription", _this.peerConnection.getRemoteStreams()); - } - _this.emit("confirmed", _this); - }); - }; - /** - * Send DTMF via RTP (RFC 4733) - * @param {String} tones A string containing DTMF digits - * @param {Object} [options] Options object to be used by sendDtmf - * @returns {boolean} true if DTMF send is successful, false otherwise - */ - SessionDescriptionHandler.prototype.sendDtmf = function (tones, options) { - if (options === void 0) { options = {}; } - if (!this.dtmfSender && this.hasBrowserGetSenderSupport()) { - var senders = this.peerConnection.getSenders(); - if (senders.length > 0) { - this.dtmfSender = senders[0].dtmf; - } - } - if (!this.dtmfSender && this.hasBrowserTrackSupport()) { - var streams = this.peerConnection.getLocalStreams(); - if (streams.length > 0) { - var audioTracks = streams[0].getAudioTracks(); - if (audioTracks.length > 0) { - this.dtmfSender = this.peerConnection.createDTMFSender(audioTracks[0]); - } - } - } - if (!this.dtmfSender) { - return false; - } - try { - this.dtmfSender.insertDTMF(tones, options.duration, options.interToneGap); - } - catch (e) { - if (e.type === "InvalidStateError" || e.type === "InvalidCharacterError") { - this.logger.error(e); - return false; - } - else { - throw e; - } - } - this.logger.log("DTMF sent via RTP: " + tones.toString()); - return true; - }; - /** - * Get the direction of the session description - * @returns {String} direction of the description - */ - SessionDescriptionHandler.prototype.getDirection = function () { - return this.direction; - }; - SessionDescriptionHandler.prototype.on = function (name, callback) { return _super.prototype.on.call(this, name, callback); }; - SessionDescriptionHandler.prototype.getMediaStream = function (constraints) { - return navigator.mediaDevices.getUserMedia(constraints); - }; - // Internal functions - SessionDescriptionHandler.prototype.createOfferOrAnswer = function (RTCOfferOptions, modifiers) { - var _this = this; - if (RTCOfferOptions === void 0) { RTCOfferOptions = {}; } - if (modifiers === void 0) { modifiers = []; } - var methodName = this.hasOffer("remote") ? "createAnswer" : "createOffer"; - var pc = this.peerConnection; - this.logger.log(methodName); - var method = this.hasOffer("remote") ? pc.createAnswer : pc.createOffer; - return method.apply(pc, RTCOfferOptions).catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer", e, "peerConnection-" + methodName + "Failed"); - _this.emit("peerConnection-" + methodName + "Failed", error); - throw error; - }).then(function (sdp) { - return Utils_1.Utils.reducePromises(modifiers, _this.createRTCSessionDescriptionInit(sdp)); - }).then(function (sdp) { - _this.resetIceGatheringComplete(); - _this.logger.log("Setting local sdp."); - _this.logger.log("sdp is " + sdp.sdp || false); - return pc.setLocalDescription(sdp); - }).catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer", e, "peerConnection-SetLocalDescriptionFailed"); - _this.emit("peerConnection-SetLocalDescriptionFailed", error); - throw error; - }).then(function () { return _this.waitForIceGatheringComplete(); }) - .then(function () { - if (!_this.peerConnection.localDescription) { - throw new Exceptions_1.Exceptions.SessionDescriptionHandlerError("Missing local description"); - } - var localDescription = _this.createRTCSessionDescriptionInit(_this.peerConnection.localDescription); - return Utils_1.Utils.reducePromises(modifiers, localDescription); - }).then(function (localDescription) { - _this.setDirection(localDescription.sdp || ""); - return localDescription; - }).catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer", e); - _this.logger.error(error.toString()); - throw error; - }); - }; - // Creates an RTCSessionDescriptionInit from an RTCSessionDescription - SessionDescriptionHandler.prototype.createRTCSessionDescriptionInit = function (RTCSessionDescription) { - return { - type: RTCSessionDescription.type, - sdp: RTCSessionDescription.sdp - }; - }; - SessionDescriptionHandler.prototype.addDefaultIceCheckingTimeout = function (peerConnectionOptions) { - if (peerConnectionOptions.iceCheckingTimeout === undefined) { - peerConnectionOptions.iceCheckingTimeout = 5000; - } - return peerConnectionOptions; - }; - SessionDescriptionHandler.prototype.addDefaultIceServers = function (rtcConfiguration) { - if (!rtcConfiguration.iceServers) { - rtcConfiguration.iceServers = [{ urls: "stun:stun.l.google.com:19302" }]; - } - return rtcConfiguration; - }; - SessionDescriptionHandler.prototype.checkAndDefaultConstraints = function (constraints) { - var defaultConstraints = { audio: true, video: !this.options.alwaysAcquireMediaFirst }; - constraints = constraints || defaultConstraints; - // Empty object check - if (Object.keys(constraints).length === 0 && constraints.constructor === Object) { - return defaultConstraints; - } - return constraints; - }; - SessionDescriptionHandler.prototype.hasBrowserTrackSupport = function () { - return Boolean(this.peerConnection.addTrack); - }; - SessionDescriptionHandler.prototype.hasBrowserGetSenderSupport = function () { - return Boolean(this.peerConnection.getSenders); - }; - SessionDescriptionHandler.prototype.initPeerConnection = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - options = this.addDefaultIceCheckingTimeout(options); - options.rtcConfiguration = options.rtcConfiguration || {}; - options.rtcConfiguration = this.addDefaultIceServers(options.rtcConfiguration); - this.logger.log("initPeerConnection"); - if (this.peerConnection) { - this.logger.log("Already have a peer connection for this session. Tearing down."); - this.resetIceGatheringComplete(); - this.peerConnection.close(); - } - this.peerConnection = new RTCPeerConnection(options.rtcConfiguration); - this.logger.log("New peer connection created"); - if ("ontrack" in this.peerConnection) { - this.peerConnection.addEventListener("track", function (e) { - _this.logger.log("track added"); - _this.observer.trackAdded(); - _this.emit("addTrack", e); - }); - } - else { - this.logger.warn("Using onaddstream which is deprecated"); - this.peerConnection.onaddstream = function (e) { - _this.logger.log("stream added"); - _this.emit("addStream", e); - }; - } - this.peerConnection.onicecandidate = function (e) { - _this.emit("iceCandidate", e); - if (e.candidate) { - _this.logger.log("ICE candidate received: " + - (e.candidate.candidate === null ? null : e.candidate.candidate.trim())); - } - else if (e.candidate === null) { - // indicates the end of candidate gathering - _this.logger.log("ICE candidate gathering complete"); - _this.triggerIceGatheringComplete(); - } - }; - this.peerConnection.onicegatheringstatechange = function () { - _this.logger.log("RTCIceGatheringState changed: " + _this.peerConnection.iceGatheringState); - switch (_this.peerConnection.iceGatheringState) { - case "gathering": - _this.emit("iceGathering", _this); - if (!_this.iceGatheringTimer && options.iceCheckingTimeout) { - _this.iceGatheringTimeout = false; - _this.iceGatheringTimer = setTimeout(function () { - _this.logger.log("RTCIceChecking Timeout Triggered after " + options.iceCheckingTimeout + " milliseconds"); - _this.iceGatheringTimeout = true; - _this.triggerIceGatheringComplete(); - }, options.iceCheckingTimeout); - } - break; - case "complete": - _this.triggerIceGatheringComplete(); - break; - } - }; - this.peerConnection.oniceconnectionstatechange = function () { - var stateEvent; - switch (_this.peerConnection.iceConnectionState) { - case "new": - stateEvent = "iceConnection"; - break; - case "checking": - stateEvent = "iceConnectionChecking"; - break; - case "connected": - stateEvent = "iceConnectionConnected"; - break; - case "completed": - stateEvent = "iceConnectionCompleted"; - break; - case "failed": - stateEvent = "iceConnectionFailed"; - break; - case "disconnected": - stateEvent = "iceConnectionDisconnected"; - break; - case "closed": - stateEvent = "iceConnectionClosed"; - break; - default: - _this.logger.warn("Unknown iceConnection state: " + _this.peerConnection.iceConnectionState); - return; - } - _this.logger.log("ICE Connection State changed to " + stateEvent); - _this.emit(stateEvent, _this); - }; - }; - SessionDescriptionHandler.prototype.acquire = function (constraints) { - var _this = this; - // Default audio & video to true - constraints = this.checkAndDefaultConstraints(constraints); - return new Promise(function (resolve, reject) { - /* - * Make the call asynchronous, so that ICCs have a chance - * to define callbacks to `userMediaRequest` - */ - _this.logger.log("acquiring local media"); - _this.emit("userMediaRequest", constraints); - if (constraints.audio || constraints.video) { - _this.getMediaStream(constraints).then(function (streams) { - _this.observer.trackAdded(); - _this.emit("userMedia", streams); - resolve(streams); - }).catch(function (e) { - _this.emit("userMediaFailed", e); - reject(e); - }); - } - else { - // Local streams were explicitly excluded. - resolve([]); - } - }).catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("acquire", e, "unable to acquire streams"); - _this.logger.error(error.message); - if (error.error) { - _this.logger.error(error.error); - } - throw error; - }).then(function (streams) { - _this.logger.log("acquired local media streams"); - // Remove old tracks - if (_this.peerConnection.removeTrack) { - _this.peerConnection.getSenders().forEach(function (sender) { - _this.peerConnection.removeTrack(sender); - }); - } - return streams; - }).catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("acquire", e, "error removing streams"); - _this.logger.error(error.message); - if (error.error) { - _this.logger.error(error.error); - } - throw error; - }).then(function (streams) { - var streamsArr = [].concat(streams); - streamsArr.forEach(function (stream) { - if (_this.peerConnection.addTrack) { - stream.getTracks().forEach(function (track) { - _this.peerConnection.addTrack(track, stream); - }); - } - else { - // Chrome 59 does not support addTrack - _this.peerConnection.addStream(stream); - } - }); - return Promise.resolve(); - }).catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("acquire", e, "error adding stream"); - _this.logger.error(error.message); - if (error.error) { - _this.logger.error(error.error); - } - throw error; - }); - }; - SessionDescriptionHandler.prototype.hasOffer = function (where) { - var offerState = "have-" + where + "-offer"; - return this.peerConnection.signalingState === offerState; - }; - // ICE gathering state handling - SessionDescriptionHandler.prototype.isIceGatheringComplete = function () { - return this.peerConnection.iceGatheringState === "complete" || this.iceGatheringTimeout; - }; - SessionDescriptionHandler.prototype.resetIceGatheringComplete = function () { - this.iceGatheringTimeout = false; - this.logger.log("resetIceGatheringComplete"); - if (this.iceGatheringTimer) { - clearTimeout(this.iceGatheringTimer); - this.iceGatheringTimer = undefined; - } - if (this.iceGatheringDeferred) { - this.iceGatheringDeferred.reject(); - this.iceGatheringDeferred = undefined; - } - }; - SessionDescriptionHandler.prototype.setDirection = function (sdp) { - var match = sdp.match(/a=(sendrecv|sendonly|recvonly|inactive)/); - if (match === null) { - this.direction = this.C.DIRECTION.NULL; - this.observer.directionChanged(); - return; - } - var direction = match[1]; - switch (direction) { - case this.C.DIRECTION.SENDRECV: - case this.C.DIRECTION.SENDONLY: - case this.C.DIRECTION.RECVONLY: - case this.C.DIRECTION.INACTIVE: - this.direction = direction; - break; - default: - this.direction = this.C.DIRECTION.NULL; - break; - } - this.observer.directionChanged(); - }; - SessionDescriptionHandler.prototype.triggerIceGatheringComplete = function () { - if (this.isIceGatheringComplete()) { - this.emit("iceGatheringComplete", this); - if (this.iceGatheringTimer) { - clearTimeout(this.iceGatheringTimer); - this.iceGatheringTimer = undefined; - } - if (this.iceGatheringDeferred) { - this.iceGatheringDeferred.resolve(); - this.iceGatheringDeferred = undefined; - } - } - }; - SessionDescriptionHandler.prototype.waitForIceGatheringComplete = function () { - this.logger.log("waitForIceGatheringComplete"); - if (this.isIceGatheringComplete()) { - this.logger.log("ICE is already complete. Return resolved."); - return Promise.resolve(); - } - else if (!this.iceGatheringDeferred) { - this.iceGatheringDeferred = Utils_1.Utils.defer(); - } - this.logger.log("ICE is not complete. Returning promise"); - return this.iceGatheringDeferred ? this.iceGatheringDeferred.promise : Promise.resolve(); - }; - return SessionDescriptionHandler; -}(events_1.EventEmitter)); -exports.SessionDescriptionHandler = SessionDescriptionHandler; - - -/***/ }), -/* 95 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var events_1 = __webpack_require__(30); -var Constants_1 = __webpack_require__(80); -var core_1 = __webpack_require__(2); -var allowed_methods_1 = __webpack_require__(58); -var Enums_1 = __webpack_require__(82); -var Exceptions_1 = __webpack_require__(84); -var Utils_1 = __webpack_require__(83); -var emitter_1 = __webpack_require__(96); -var info_1 = __webpack_require__(97); -var notification_1 = __webpack_require__(98); -var referral_1 = __webpack_require__(99); -var session_state_1 = __webpack_require__(100); -/** - * A session provides real time communication between one or more participants. - * @public - */ -var Session = /** @class */ (function (_super) { - tslib_1.__extends(Session, _super); - /** - * Constructor. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @internal - */ - function Session(userAgent, options) { - if (options === void 0) { options = {}; } - var _this = _super.call(this) || this; - // Property overlap with ClientContext & ServerContext Interfaces - /** @internal */ - _this.type = Enums_1.TypeStrings.Session; - /** @internal */ - _this.method = Constants_1.C.INVITE; - /** @internal */ - _this.localHold = false; - /** DEPRECATED: Session status */ - /** @internal */ - _this.status = Enums_1.SessionStatus.STATUS_NULL; - /** True if an error caused session termination. */ - /** @internal */ - _this.isFailed = false; - /** @internal */ - _this.rel100 = Constants_1.C.supported.UNSUPPORTED; - /** @internal */ - _this.expiresTimer = undefined; - /** @internal */ - _this.userNoAnswerTimer = undefined; - _this._state = session_state_1.SessionState.Initial; - _this._stateEventEmitter = new events_1.EventEmitter(); - _this.pendingReinvite = false; - _this.tones = undefined; - _this.userAgent = userAgent; - _this.delegate = options.delegate; - _this.logger = userAgent.getLogger("sip.session"); - _this.errorListener = _this.onTransportError.bind(_this); - if (userAgent.transport) { - userAgent.transport.on("transportError", _this.errorListener); - } - return _this; - } - /** - * @deprecated Legacy state transition. - * @internal - */ - Session.prototype.on = function (name, callback) { - return _super.prototype.on.call(this, name, callback); - }; - /** - * @deprecated Legacy state transition. - * @internal - */ - Session.prototype.emit = function (event) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - return _super.prototype.emit.apply(this, [event].concat(args)); - }; - Object.defineProperty(Session.prototype, "sessionDescriptionHandler", { - /** - * Session description handler. - */ - get: function () { - return this._sessionDescriptionHandler; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Session.prototype, "sessionDescriptionHandlerFactory", { - /** - * Session description handler factory. - */ - get: function () { - return this.userAgent.configuration.sessionDescriptionHandlerFactory; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Session.prototype, "state", { - /** - * Session state. - */ - get: function () { - return this._state; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Session.prototype, "stateChange", { - /** - * Session state change emitter. - */ - get: function () { - return emitter_1.makeEmitter(this._stateEventEmitter); - }, - enumerable: true, - configurable: true - }); - /** - * Renegotiate the session. Sends a re-INVITE. - * @param options - Options bucket. - */ - Session.prototype.invite = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - this.logger.log("Session.invite"); - if (this.state !== session_state_1.SessionState.Established) { - return Promise.reject(new Error("Invalid session state " + this.state)); - } - if (this.pendingReinvite) { - return Promise.reject(new Error("Reinvite in progress. Please wait until complete, then try again.")); - } - if (!this._sessionDescriptionHandler) { - throw new Error("Session description handler undefined."); - } - this.pendingReinvite = true; - var delegate = { - onAccept: function (response) { - // A re-INVITE transaction has an offer/answer [RFC3264] exchange - // associated with it. The UAC (User Agent Client) generating a given - // re-INVITE can act as the offerer or as the answerer. A UAC willing - // to act as the offerer includes an offer in the re-INVITE. The UAS - // (User Agent Server) then provides an answer in a response to the - // re-INVITE. A UAC willing to act as answerer does not include an - // offer in the re-INVITE. The UAS then provides an offer in a response - // to the re-INVITE becoming, thus, the offerer. - // https://tools.ietf.org/html/rfc6141#section-1 - var body = core_1.getBody(response.message); - if (!body) { - // No way to recover, so terminate session and mark as failed. - _this.logger.error("Received 2xx response to re-INVITE without a session description"); - _this.ackAndBye(response, 400, "Missing session description"); - _this.stateTransition(session_state_1.SessionState.Terminated); - _this.isFailed = true; - _this.pendingReinvite = false; - return; - } - if (options.withoutSdp) { - // INVITE without SDP - set remote offer and send an answer in the ACK - // FIXME: SDH options & SDH modifiers options are applied somewhat ambiguously - // This behavior was ported from legacy code and the issue punted down the road. - var answerOptions = { - sessionDescriptionHandlerOptions: options.sessionDescriptionHandlerOptions, - sessionDescriptionHandlerModifiers: options.sessionDescriptionHandlerModifiers - }; - _this.setOfferAndGetAnswer(body, answerOptions) - .then(function (answerBody) { - var request = response.ack({ body: answerBody }); - }) - .catch(function (error) { - // No way to recover, so terminate session and mark as failed. - _this.logger.error(error.message); - _this.logger.error("Failed to handle offer in 2xx response to re-INVITE"); - _this.ackAndBye(response, 488, "Bad Media Description"); - _this.stateTransition(session_state_1.SessionState.Terminated); - _this.isFailed = true; - }) - .then(function () { - _this.pendingReinvite = false; - if (options.requestDelegate && options.requestDelegate.onAccept) { - options.requestDelegate.onAccept(response); - } - }); - } - else { - // INVITE with SDP - set remote answer and send an ACK - // FIXME: SDH options & SDH modifiers options are applied somewhat ambiguously - // This behavior was ported from legacy code and the issue punted down the road. - var answerOptions = { - sessionDescriptionHandlerOptions: _this.sessionDescriptionHandlerOptions, - sessionDescriptionHandlerModifiers: _this.sessionDescriptionHandlerModifiers - }; - _this.setAnswer(body, answerOptions) - .then(function () { - var request = response.ack(); - }) - .catch(function (error) { - // No way to recover, so terminate session and mark as failed. - _this.logger.error(error.message); - _this.logger.error("Failed to handle answer in 2xx response to re-INVITE"); - _this.ackAndBye(response, 488, "Bad Media Description"); - _this.stateTransition(session_state_1.SessionState.Terminated); - _this.isFailed = true; - }) - .then(function () { - _this.pendingReinvite = false; - if (options.requestDelegate && options.requestDelegate.onAccept) { - options.requestDelegate.onAccept(response); - } - }); - } - }, - onProgress: function (response) { - return; - }, - onRedirect: function (response) { - return; - }, - onReject: function (response) { - _this.logger.warn("Received a non-2xx response to re-INVITE"); - _this.pendingReinvite = false; - if (options.withoutSdp) { - if (options.requestDelegate && options.requestDelegate.onReject) { - options.requestDelegate.onReject(response); - } - } - else { - _this.rollbackOffer() - .catch(function (error) { - // No way to recover, so terminate session and mark as failed. - _this.logger.error(error.message); - _this.logger.error("Failed to rollback offer on non-2xx response to re-INVITE"); - // Note that the ACK was already sent by the transaction, so just need to send BYE - if (!_this.dialog) { - throw new Error("Dialog undefined."); - } - var extraHeaders = []; - extraHeaders.push("Reason: " + Utils_1.Utils.getReasonHeaderValue(500, "Internal Server Error")); - var outgoingByeRequest = _this.dialog.bye(undefined, { extraHeaders: extraHeaders }); - _this.stateTransition(session_state_1.SessionState.Terminated); - _this.isFailed = true; - }) - .then(function () { - if (options.requestDelegate && options.requestDelegate.onReject) { - options.requestDelegate.onReject(response); - } - }); - } - }, - onTrying: function (response) { - return; - } - }; - var requestOptions = options.requestOptions || {}; - requestOptions.extraHeaders = (requestOptions.extraHeaders || []).slice(); - requestOptions.extraHeaders.push("Allow: " + allowed_methods_1.AllowedMethods.toString()); - requestOptions.extraHeaders.push("Contact: " + this.contact); - // Just send an INVITE with no sdp... - if (options.withoutSdp) { - if (!this.dialog) { - this.pendingReinvite = false; - return Promise.reject(new Error("Dialog undefined.")); - } - return Promise.resolve(this.dialog.invite(delegate, requestOptions)); - } - // Get an offer and send it in an INVITE - // FIXME: SDH options & SDH modifiers options are applied somewhat ambiguously - // This behavior was ported from legacy code and the issue punted down the road. - var offerOptions = { - sessionDescriptionHandlerOptions: options.sessionDescriptionHandlerOptions, - sessionDescriptionHandlerModifiers: options.sessionDescriptionHandlerModifiers - }; - return this.getOffer(offerOptions) - .then(function (offerBody) { - if (!_this.dialog) { - _this.pendingReinvite = false; - throw new Error("Dialog undefined."); - } - requestOptions.body = offerBody; - return _this.dialog.invite(delegate, requestOptions); - }) - .catch(function (error) { - _this.logger.error(error.message); - _this.logger.error("Failed to send re-INVITE"); - _this.pendingReinvite = false; - throw error; - }); - }; - /** - * TODO: This is awkward. - * Helper function - * @internal - */ - Session.prototype.byePending = function () { - this.stateTransition(session_state_1.SessionState.Terminating); - this.terminated(); - }; - /** - * TODO: This is awkward. - * Helper function - * @internal - */ - Session.prototype.byeSent = function (request) { - this.emit("bye", request.message); - this.stateTransition(session_state_1.SessionState.Terminated); - this.terminated(); - }; - /** - * Send BYE. - * @param delegate - Request delegate. - * @param options - Request options bucket. - * @internal - */ - Session.prototype.bye = function (delegate, options) { - var _this = this; - // Using core session dialog - if (!this.dialog) { - return Promise.reject(new Error("Session dialog undefined.")); - } - var dialog = this.dialog; - // The caller's UA MAY send a BYE for either confirmed or early dialogs, - // and the callee's UA MAY send a BYE on confirmed dialogs, but MUST NOT - // send a BYE on early dialogs. However, the callee's UA MUST NOT send a - // BYE on a confirmed dialog until it has received an ACK for its 2xx - // response or until the server transaction times out. - // https://tools.ietf.org/html/rfc3261#section-15 - switch (dialog.sessionState) { - case core_1.SessionState.Initial: - throw new Error("Invalid dialog state " + dialog.sessionState); - case core_1.SessionState.Early: // Implementation choice - not sending BYE for early dialogs. - throw new Error("Invalid dialog state " + dialog.sessionState); - case core_1.SessionState.AckWait: { // This state only occurs if we are the callee. - this.byePending(); - return new Promise(function (resolve, reject) { - dialog.delegate = { - // When ACK shows up, say BYE. - onAck: function () { - var request = dialog.bye(delegate, options); - _this.byeSent(request); - resolve(request); - }, - // Or the server transaction times out before the ACK arrives. - onAckTimeout: function () { - var request = dialog.bye(delegate, options); - _this.byeSent(request); - resolve(request); - } - }; - }); - } - case core_1.SessionState.Confirmed: { - var request = dialog.bye(delegate, options); - this.byeSent(request); - return Promise.resolve(request); - } - case core_1.SessionState.Terminated: - throw new Error("Invalid dialog state " + dialog.sessionState); - default: - throw new Error("Unrecognized state."); - } - }; - /** - * Send INFO. - * @param delegate - Request delegate. - * @param options - Request options bucket. - * @internal - */ - Session.prototype.info = function (delegate, options) { - // Using core session dialog - if (!this.dialog) { - return Promise.reject(new Error("Session dialog undefined.")); - } - return Promise.resolve(this.dialog.info(delegate, options)); - }; - /** - * Send REFER. - * @param delegate - Request delegate. - * @param options - Request options bucket. - * @internal - */ - Session.prototype.refer = function (referrer, delegate, options) { - // Using core session dialog - if (!this.dialog) { - return Promise.reject(new Error("Session dialog undefined.")); - } - // If the session has a referrer, it will receive any in-dialog NOTIFY requests. - this.referrer = referrer; - return Promise.resolve(this.dialog.refer(delegate, options)); - }; - /** - * @internal - */ - Session.prototype.close = function () { - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return; - } - this.logger.log("closing INVITE session " + this.id); - // 1st Step. Terminate media. - if (this._sessionDescriptionHandler) { - this._sessionDescriptionHandler.close(); - } - // 2nd Step. Terminate signaling. - // Clear session timers - if (this.expiresTimer) { - clearTimeout(this.expiresTimer); - } - if (this.userNoAnswerTimer) { - clearTimeout(this.userNoAnswerTimer); - } - this.status = Enums_1.SessionStatus.STATUS_TERMINATED; - if (this.userAgent.transport) { - this.userAgent.transport.removeListener("transportError", this.errorListener); - } - if (!this.id) { - throw new Error("Session id undefined."); - } - delete this.userAgent.sessions[this.id]; - return; - }; - /** - * @internal - */ - Session.prototype.onRequestTimeout = function () { - if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { - this.terminated(undefined, Constants_1.C.causes.REQUEST_TIMEOUT); - } - else if (this.status !== Enums_1.SessionStatus.STATUS_TERMINATED) { - this.failed(undefined, Constants_1.C.causes.REQUEST_TIMEOUT); - this.terminated(undefined, Constants_1.C.causes.REQUEST_TIMEOUT); - } - }; - /** - * @internal - */ - Session.prototype.onTransportError = function () { - if (this.status !== Enums_1.SessionStatus.STATUS_CONFIRMED && this.status !== Enums_1.SessionStatus.STATUS_TERMINATED) { - this.failed(undefined, Constants_1.C.causes.CONNECTION_ERROR); - } - }; - /** - * Send ACK and then BYE. There are unrecoverable errors which can occur - * while handling dialog forming and in-dialog INVITE responses and when - * they occur we ACK the response and terminate the session. - * @param inviteResponse - The response causing the error. - * @param statusCode - Status code for he reason phrase. - * @param reasonPhrase - Reason phrase for the BYE. - * @internal - */ - Session.prototype.ackAndBye = function (response, statusCode, reasonPhrase) { - var outgoingAckRequest = response.ack(); - var extraHeaders = []; - if (statusCode) { - extraHeaders.push("Reason: " + Utils_1.Utils.getReasonHeaderValue(statusCode, reasonPhrase)); - } - var outgoingByeRequest = response.session.bye(undefined, { extraHeaders: extraHeaders }); - this.emit("bye", outgoingByeRequest.message); - }; - /** - * Handle in dialog ACK request. - * @internal - */ - Session.prototype.onAckRequest = function (request) { - var _this = this; - this.logger.log("Session.onAckRequest"); - if (this.state !== session_state_1.SessionState.Initial && - this.state !== session_state_1.SessionState.Establishing && - this.state !== session_state_1.SessionState.Established && - this.state !== session_state_1.SessionState.Terminating) { - this.logger.error("ACK received while in state " + this.state + ", dropping request"); - return; - } - // FIXME: Review is this ever true? We're "Established" when dialog created in accept(). - if (this.state === session_state_1.SessionState.Initial || this.state === session_state_1.SessionState.Establishing) { - this.stateTransition(session_state_1.SessionState.Established); - } - var dialog = this.dialog; - if (!dialog) { - throw new Error("Dialog undefined."); - } - // Helper function. - var confirmSession = function () { - _this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; - _this.emit("confirmed", request.message); - }; - // If the ACK doesn't have an offer/answer, nothing to be done. - var body = core_1.getBody(request.message); - if (!body) { - confirmSession(); - return; - } - if (body.contentDisposition === "render") { - this.renderbody = body.content; - this.rendertype = body.contentType; - confirmSession(); - return; - } - if (body.contentDisposition !== "session") { - confirmSession(); - return; - } - var options = { - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers - }; - switch (dialog.signalingState) { - case core_1.SignalingState.Initial: - // State should never be reached as first reliable response must have answer/offer. - throw new Error("Invalid signaling state " + dialog.signalingState + "."); - case core_1.SignalingState.Stable: - // Receved answer. - this.setAnswer(body, options) - .then(function () { return confirmSession(); }) - .catch(function (error) { - // FIXME: TODO - need to do something to handle this error - _this.logger.error(error); - var extraHeaders = ["Reason: " + Utils_1.Utils.getReasonHeaderValue(488, "Bad Media Description")]; - _this.bye(undefined, { extraHeaders: extraHeaders }); - _this.failed(request.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - _this.terminated(request.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - throw error; - }); - return; - case core_1.SignalingState.HaveLocalOffer: - // State should never be reached as local offer would be answered by this ACK - throw new Error("Invalid signaling state " + dialog.signalingState + "."); - case core_1.SignalingState.HaveRemoteOffer: - // State should never be reached as remote offer would be answered in first reliable response. - throw new Error("Invalid signaling state " + dialog.signalingState + "."); - case core_1.SignalingState.Closed: - throw new Error("Invalid signaling state " + dialog.signalingState + "."); - default: - throw new Error("Invalid signaling state " + dialog.signalingState + "."); - } - }; - /** - * Handle in dialog BYE request. - * @internal - */ - Session.prototype.onByeRequest = function (request) { - this.logger.log("Session.onByeRequest"); - if (this.state !== session_state_1.SessionState.Established) { - this.logger.error("BYE received while in state " + this.state + ", dropping request"); - return; - } - request.accept(); - this.stateTransition(session_state_1.SessionState.Terminated); - if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { - this.emit("bye", request.message); - this.terminated(request.message, Constants_1.C.BYE); - } - }; - /** - * Handle in dialog INFO request. - * @internal - */ - Session.prototype.onInfoRequest = function (request) { - this.logger.log("Session.onInfoRequest"); - if (this.state !== session_state_1.SessionState.Established) { - this.logger.error("INFO received while in state " + this.state + ", dropping request"); - return; - } - if (this.delegate && this.delegate.onInfo) { - var info = new info_1.Info(request); - this.delegate.onInfo(info); - } - else { - request.accept(); - } - }; - /** - * Handle in dialog INVITE request. - * @internal - */ - Session.prototype.onInviteRequest = function (request) { - var _this = this; - this.logger.log("Session.onInviteRequest"); - if (this.state !== session_state_1.SessionState.Established) { - this.logger.error("INVITE received while in state " + this.state + ", dropping request"); - return; - } - // TODO: would be nice to have core track and set the Contact header, - // but currently the session which is setting it is holding onto it. - var extraHeaders = ["Contact: " + this.contact]; - // Check testing hooks - if (this.delegate && this.delegate.onReinviteTest) { - var test = this.delegate.onReinviteTest(); - if (test === "acceptWithoutDescription") { - request.accept({ statusCode: 200, extraHeaders: extraHeaders }); - return; - } - if (test === "reject488") { - request.reject({ statusCode: 488 }); - return; - } - } - // Handle P-Asserted-Identity - if (request.message.hasHeader("P-Asserted-Identity")) { - var header = request.message.getHeader("P-Asserted-Identity"); - if (!header) { - throw new Error("Header undefined."); - } - this.assertedIdentity = core_1.Grammar.nameAddrHeaderParse(header); - } - // FIXME: SDH options & SDH modifiers options are applied somewhat ambiguously - // This behavior was ported from legacy code and the issue punted down the road. - var options = { - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers - }; - this.generateResponseOfferAnswerInDialog(options) - .then(function (body) { - var outgoingResponse = request.accept({ statusCode: 200, extraHeaders: extraHeaders, body: body }); - if (_this.delegate && _this.delegate.onInvite) { - _this.delegate.onInvite(request.message, outgoingResponse.message, 200); - } - }) - .catch(function (error) { - _this.logger.error(error.message); - _this.logger.error("Failed to handle to re-INVITE request"); - if (!_this.dialog) { - throw new Error("Dialog undefined."); - } - _this.logger.error(_this.dialog.signalingState); - // If we don't have a local/remote offer... - if (_this.dialog.signalingState === core_1.SignalingState.Stable) { - var outgoingResponse = request.reject({ statusCode: 488 }); // Not Acceptable Here - if (_this.delegate && _this.delegate.onInvite) { - _this.delegate.onInvite(request.message, outgoingResponse.message, 488); - } - return; - } - // Otherwise rollback - _this.rollbackOffer() - .then(function () { - var outgoingResponse = request.reject({ statusCode: 488 }); // Not Acceptable Here - if (_this.delegate && _this.delegate.onInvite) { - _this.delegate.onInvite(request.message, outgoingResponse.message, 488); - } - }) - .catch(function (errorRollback) { - // No way to recover, so terminate session and mark as failed. - _this.logger.error(errorRollback.message); - _this.logger.error("Failed to rollback offer on re-INVITE request"); - var outgoingResponse = request.reject({ statusCode: 488 }); // Not Acceptable Here - var extraHeadersBye = []; - extraHeadersBye.push("Reason: " + Utils_1.Utils.getReasonHeaderValue(500, "Internal Server Error")); - if (!_this.dialog) { - throw new Error("Dialog undefined."); - } - var outgoingByeRequest = _this.dialog.bye(undefined, { extraHeaders: extraHeaders }); - _this.stateTransition(session_state_1.SessionState.Terminated); - _this.isFailed = true; - if (_this.delegate && _this.delegate.onInvite) { - _this.delegate.onInvite(request.message, outgoingResponse.message, 488); - } - }); - }); - }; - /** - * Handle in dialog NOTIFY request. - * @internal - */ - Session.prototype.onNotifyRequest = function (request) { - this.logger.log("Session.onNotifyRequest"); - if (this.state !== session_state_1.SessionState.Established) { - this.logger.error("NOTIFY received while in state " + this.state + ", dropping request"); - return; - } - // DEPRECATED BEGIN - // ReferClientContext is deprecated - // if ( - // this.referContext && - // this.referContext.type === TypeStrings.ReferClientContext && - // incomingRequest.message.hasHeader("event") && - // /^refer(;.*)?$/.test(incomingRequest.message.getHeader("event") as string) - // ) { - // this.referContext.receiveNotify(incomingRequest); - // return; - // } - // DEPRECATED END - // If this a NOTIFY associated with the progress of a REFER, - // look to delegate handling to the associated Referrer. - if (this.referrer && this.referrer.delegate && this.referrer.delegate.onNotify) { - var notification = new notification_1.Notification(request); - this.referrer.delegate.onNotify(notification); - return; - } - // Otherwise accept the NOTIFY. - if (this.delegate && this.delegate.onNotify) { - var notification = new notification_1.Notification(request); - this.delegate.onNotify(notification); - } - else { - request.accept(); - } - this.emit("notify", request.message); - }; - /** - * Handle in dialog PRACK request. - * @internal - */ - Session.prototype.onPrackRequest = function (request) { - this.logger.log("Session.onPrackRequest"); - if (this.state !== session_state_1.SessionState.Established) { - this.logger.error("PRACK received while in state " + this.state + ", dropping request"); - return; - } - throw new Error("Unimplemented."); - }; - /** - * Handle in dialog REFER request. - * @internal - */ - Session.prototype.onReferRequest = function (request) { - var _this = this; - this.logger.log("Session.onReferRequest"); - if (this.state !== session_state_1.SessionState.Established) { - this.logger.error("REFER received while in state " + this.state + ", dropping request"); - return; - } - if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { - // RFC 3515 2.4.1 - if (!request.message.hasHeader("refer-to")) { - this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting."); - request.reject(); - return; - } - // DEPRECATED BEGIN - // // ReferServerContext is deprecated - // if (this.listeners("referRequested").length) { - // const referContext = new ReferServerContext(this.ua, incomingRequest, this.dialog); - // this.emit("referRequested", referContext); - // return; - // } - // DEPRECATED END - var referral_2 = new referral_1.Referral(request, this); - if (this.delegate && this.delegate.onRefer) { - this.delegate.onRefer(referral_2); - } - else { - this.logger.log("No delegate available to handle REFER, automatically accepting and following."); - referral_2 - .accept() - .then(function () { return referral_2 - .makeInviter(_this.passedOptions) - .invite(); }) - .catch(function (error) { - // FIXME: logging and eating error... - _this.logger.error(error.message); - }); - } - } - }; - /** - * @deprecated Legacy state transition. - * @internal - */ - Session.prototype.connecting = function (request) { - this.emit("connecting", { request: request }); - }; - /** - * @deprecated Legacy state transition. - * @internal - */ - Session.prototype.failed = function (response, cause) { - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return; - } - this.emit("failed", response, cause); - }; - /** - * @deprecated Legacy state transition. - * @internal - */ - Session.prototype.rejected = function (response, cause) { - this.emit("rejected", response, cause); - }; - /** - * @deprecated Legacy state transition. - * @internal - */ - Session.prototype.terminated = function (message, cause) { - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return; - } - this.endTime = new Date(); - this.close(); - this.emit("terminated", message, cause); - }; - /** - * Generate an offer or answer for a response to an INVITE request. - * If a remote offer was provided in the request, set the remote - * description and get a local answer. If a remote offer was not - * provided, generates a local offer. - * @internal - */ - Session.prototype.generateResponseOfferAnswer = function (request, options) { - if (this.dialog) { - return this.generateResponseOfferAnswerInDialog(options); - } - var body = core_1.getBody(request.message); - if (!body || body.contentDisposition !== "session") { - return this.getOffer(options); - } - else { - return this.setOfferAndGetAnswer(body, options); - } - }; - /** - * Generate an offer or answer for a response to an INVITE request - * when a dialog (early or otherwise) has already been established. - * This method may NOT be called if a dialog has yet to be established. - * @internal - */ - Session.prototype.generateResponseOfferAnswerInDialog = function (options) { - if (!this.dialog) { - throw new Error("Dialog undefined."); - } - switch (this.dialog.signalingState) { - case core_1.SignalingState.Initial: - return this.getOffer(options); - case core_1.SignalingState.HaveLocalOffer: - // o Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - return Promise.resolve(undefined); - case core_1.SignalingState.HaveRemoteOffer: - if (!this.dialog.offer) { - throw new Error("Session offer undefined in signaling state " + this.dialog.signalingState + "."); - } - return this.setOfferAndGetAnswer(this.dialog.offer, options); - case core_1.SignalingState.Stable: - // o Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - if (this.state !== session_state_1.SessionState.Established) { - return Promise.resolve(undefined); - } - // In dialog INVITE without offer, get an offer for the response. - return this.getOffer(options); - case core_1.SignalingState.Closed: - throw new Error("Invalid signaling state " + this.dialog.signalingState + "."); - default: - throw new Error("Invalid signaling state " + this.dialog.signalingState + "."); - } - }; - /** - * Get local offer. - * @internal - */ - Session.prototype.getOffer = function (options) { - var sdh = this.setupSessionDescriptionHandler(); - var sdhOptions = options.sessionDescriptionHandlerOptions; - var sdhModifiers = options.sessionDescriptionHandlerModifiers; - return sdh.getDescription(sdhOptions, sdhModifiers) - .then(function (bodyAndContentType) { return Utils_1.Utils.fromBodyObj(bodyAndContentType); }) - .catch(function (error) { - throw (error instanceof Error ? error : new Error(error)); - }); - }; - /** - * Rollback local/remote offer. - * @internal - */ - Session.prototype.rollbackOffer = function () { - var sdh = this.setupSessionDescriptionHandler(); - if (!sdh.rollbackDescription) { - return Promise.resolve(); - } - return sdh.rollbackDescription() - .catch(function (error) { - throw (error instanceof Error ? error : new Error(error)); - }); - }; - /** - * Set remote answer. - * @internal - */ - Session.prototype.setAnswer = function (answer, options) { - var sdh = this.setupSessionDescriptionHandler(); - var sdhOptions = options.sessionDescriptionHandlerOptions; - var sdhModifiers = options.sessionDescriptionHandlerModifiers; - if (!sdh.hasDescription(answer.contentType)) { - return Promise.reject(new Exceptions_1.Exceptions.UnsupportedSessionDescriptionContentTypeError()); - } - return sdh.setDescription(answer.content, sdhOptions, sdhModifiers) - .catch(function (error) { - throw (error instanceof Error ? error : new Error(error)); - }); - }; - /** - * Set remote offer and get local answer. - * @internal - */ - Session.prototype.setOfferAndGetAnswer = function (offer, options) { - var sdh = this.setupSessionDescriptionHandler(); - var sdhOptions = options.sessionDescriptionHandlerOptions; - var sdhModifiers = options.sessionDescriptionHandlerModifiers; - if (!sdh.hasDescription(offer.contentType)) { - return Promise.reject(new Exceptions_1.Exceptions.UnsupportedSessionDescriptionContentTypeError()); - } - return sdh.setDescription(offer.content, sdhOptions, sdhModifiers) - .then(function () { return sdh.getDescription(sdhOptions, sdhModifiers); }) - .then(function (bodyAndContentType) { return Utils_1.Utils.fromBodyObj(bodyAndContentType); }) - .catch(function (error) { - throw (error instanceof Error ? error : new Error(error)); - }); - }; - /** - * SDH for confirmed dialog. - * @internal - */ - Session.prototype.setSessionDescriptionHandler = function (sdh) { - if (this._sessionDescriptionHandler) { - throw new Error("Sessionn description handler defined."); - } - this._sessionDescriptionHandler = sdh; - }; - /** - * SDH for confirmed dialog. - * @internal - */ - Session.prototype.setupSessionDescriptionHandler = function () { - if (this._sessionDescriptionHandler) { - return this._sessionDescriptionHandler; - } - this._sessionDescriptionHandler = - this.sessionDescriptionHandlerFactory(this, this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions); - this.emit("SessionDescriptionHandler-created", this._sessionDescriptionHandler); - return this._sessionDescriptionHandler; - }; - /** - * Transition session state. - * @internal - */ - Session.prototype.stateTransition = function (newState) { - var _this = this; - var invalidTransition = function () { - throw new Error("Invalid state transition from " + _this._state + " to " + newState); - }; - // Validate transition - switch (this._state) { - case session_state_1.SessionState.Initial: - if (newState !== session_state_1.SessionState.Establishing && - newState !== session_state_1.SessionState.Established && - newState !== session_state_1.SessionState.Terminating && - newState !== session_state_1.SessionState.Terminated) { - invalidTransition(); - } - break; - case session_state_1.SessionState.Establishing: - if (newState !== session_state_1.SessionState.Established && - newState !== session_state_1.SessionState.Terminating && - newState !== session_state_1.SessionState.Terminated) { - invalidTransition(); - } - break; - case session_state_1.SessionState.Established: - if (newState !== session_state_1.SessionState.Terminating && - newState !== session_state_1.SessionState.Terminated) { - invalidTransition(); - } - break; - case session_state_1.SessionState.Terminating: - if (newState !== session_state_1.SessionState.Terminated) { - invalidTransition(); - } - break; - case session_state_1.SessionState.Terminated: - invalidTransition(); - break; - default: - throw new Error("Unrecognized state."); - } - // Deprecated legacy ported behavior - if (newState === session_state_1.SessionState.Established) { - this.startTime = new Date(); - } - // Transition - this._state = newState; - this.logger.log("Session " + this.id + " transitioned to state " + this._state); - this._stateEventEmitter.emit("event", this._state); - }; - // DEPRECATED - /** @internal */ - Session.C = Enums_1.SessionStatus; - return Session; -}(events_1.EventEmitter)); -exports.Session = Session; - - -/***/ }), -/* 96 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * Creates an {@link Emitter}. - * @param eventEmitter - An event emitter. - * @param eventName - Event name. - * @internal - */ -function makeEmitter(eventEmitter, eventName) { - if (eventName === void 0) { eventName = "event"; } - return { - on: function (listener) { - eventEmitter.on(eventName, listener); - }, - off: function (listener) { - eventEmitter.removeListener(eventName, listener); - }, - once: function (listener) { - eventEmitter.once(eventName, listener); - } - }; -} -exports.makeEmitter = makeEmitter; - - -/***/ }), -/* 97 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * An exchange of information (incoming INFO). - * @public - */ -var Info = /** @class */ (function () { - /** @internal */ - function Info(incomingInfoRequest) { - this.incomingInfoRequest = incomingInfoRequest; - } - Object.defineProperty(Info.prototype, "request", { - /** Incoming MESSAGE request message. */ - get: function () { - return this.incomingInfoRequest.message; - }, - enumerable: true, - configurable: true - }); - /** Accept the request. */ - Info.prototype.accept = function (options) { - this.incomingInfoRequest.accept(options); - return Promise.resolve(); - }; - /** Reject the request. */ - Info.prototype.reject = function (options) { - this.incomingInfoRequest.reject(options); - return Promise.resolve(); - }; - return Info; -}()); -exports.Info = Info; - - -/***/ }), -/* 98 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * A notification of an event (incoming NOTIFY). - * @public - */ -var Notification = /** @class */ (function () { - /** @internal */ - function Notification(incomingNotifyRequest) { - this.incomingNotifyRequest = incomingNotifyRequest; - } - Object.defineProperty(Notification.prototype, "request", { - /** Incoming NOTIFY request message. */ - get: function () { - return this.incomingNotifyRequest.message; - }, - enumerable: true, - configurable: true - }); - /** Accept the request. */ - Notification.prototype.accept = function (options) { - this.incomingNotifyRequest.accept(options); - return Promise.resolve(); - }; - /** Reject the request. */ - Notification.prototype.reject = function (options) { - this.incomingNotifyRequest.reject(options); - return Promise.resolve(); - }; - return Notification; -}()); -exports.Notification = Notification; - - -/***/ }), -/* 99 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var core_1 = __webpack_require__(2); -/** - * A request to establish a {@link Session} elsewhere (incoming REFER). - * @public - */ -var Referral = /** @class */ (function () { - /** @internal */ - function Referral(incomingReferRequest, session) { - this.incomingReferRequest = incomingReferRequest; - this.session = session; - } - Object.defineProperty(Referral.prototype, "referTo", { - get: function () { - var referTo = this.incomingReferRequest.message.parseHeader("refer-to"); - if (!(referTo instanceof core_1.NameAddrHeader)) { - throw new Error("Failed to parse Refer-To header."); - } - return referTo; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Referral.prototype, "referredBy", { - get: function () { - return this.incomingReferRequest.message.getHeader("referred-by"); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Referral.prototype, "replaces", { - get: function () { - return this.referTo.uri.getHeader("replaces"); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Referral.prototype, "request", { - /** Incoming REFER request message. */ - get: function () { - return this.incomingReferRequest.message; - }, - enumerable: true, - configurable: true - }); - /** Accept the request. */ - Referral.prototype.accept = function (options) { - if (options === void 0) { options = { statusCode: 202 }; } - this.incomingReferRequest.accept(options); - return Promise.resolve(); - }; - /** Reject the request. */ - Referral.prototype.reject = function (options) { - this.incomingReferRequest.reject(options); - return Promise.resolve(); - }; - /** - * Creates an inviter which may be used to send an out of dialog INVITE request. - * - * @remarks - * This a helper method to create an Inviter which will execute the referral - * of the `Session` which was referred. The appropriate headers are set and - * the referred `Session` is linked to the new `Session`. Note that only a - * single instance of the `Inviter` will be created and returned (if called - * more than once a reference to the same `Inviter` will be returned every time). - * - * @param options - Options bucket. - * @param modifiers - Session description handler modifiers. - */ - Referral.prototype.makeInviter = function (options) { - if (this.inviter) { - return this.inviter; - } - var targetURI = this.referTo.uri.clone(); - targetURI.clearHeaders(); - options = options || {}; - var extraHeaders = (options.extraHeaders || []).slice(); - var replaces = this.replaces; - if (replaces) { - // decodeURIComponent is a holdover from 2c086eb4. Not sure that it is actually necessary - extraHeaders.push("Replaces: " + decodeURIComponent(replaces)); - } - var referredBy = this.referredBy; - if (referredBy) { - extraHeaders.push("Referred-By: " + referredBy); - } - options.extraHeaders = extraHeaders; - this.inviter = this.session.userAgent.makeInviter(targetURI, options); - this.inviter.referred = this.session; - this.session.referral = this.inviter; - return this.inviter; - }; - return Referral; -}()); -exports.Referral = Referral; - - -/***/ }), -/* 100 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * {@link Session} state. - * @remarks - * Valid state transitions: - * ``` - * 1. "initial" --> "establishing" (before INVITE sent on outgoing, before OK sent on incoming) - * 2. "initial" --> "established" (after ACK is sent on outgoing, after OK sent on incoming) - * 4. "initial" --> "terminating" - * 4. "initial" --> "terminated" - * 5. "establishing" --> "established" - * 6. "establishing" --> "terminating" - * 7. "establishing" --> "terminated" - * 8. "established" --> "terminating" - * 9. "established" --> "terminated" - * 10. "terminating" --> "terminated" - * ``` - * @public - */ -var SessionState; -(function (SessionState) { - SessionState["Initial"] = "Initial"; - SessionState["Establishing"] = "Establishing"; - SessionState["Established"] = "Established"; - SessionState["Terminating"] = "Terminating"; - SessionState["Terminated"] = "Terminated"; -})(SessionState = exports.SessionState || (exports.SessionState = {})); - - -/***/ }), -/* 101 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var stripPayload = function (sdp, payload) { - var mediaDescs = []; - var lines = sdp.split(/\r\n/); - var currentMediaDesc; - for (var i = 0; i < lines.length;) { - var line = lines[i]; - if (/^m=(?:audio|video)/.test(line)) { - currentMediaDesc = { - index: i, - stripped: [] - }; - mediaDescs.push(currentMediaDesc); - } - else if (currentMediaDesc) { - var rtpmap = /^a=rtpmap:(\d+) ([^/]+)\//.exec(line); - if (rtpmap && payload === rtpmap[2]) { - lines.splice(i, 1); - currentMediaDesc.stripped.push(rtpmap[1]); - continue; // Don't increment 'i' - } - } - i++; - } - for (var _i = 0, mediaDescs_1 = mediaDescs; _i < mediaDescs_1.length; _i++) { - var mediaDesc = mediaDescs_1[_i]; - var mline = lines[mediaDesc.index].split(" "); - // Ignore the first 3 parameters of the mline. The codec information is after that - for (var j = 3; j < mline.length;) { - if (mediaDesc.stripped.indexOf(mline[j]) !== -1) { - mline.splice(j, 1); - continue; - } - j++; - } - lines[mediaDesc.index] = mline.join(" "); - } - return lines.join("\r\n"); -}; -var stripMediaDescription = function (sdp, description) { - var descriptionRegExp = new RegExp("m=" + description + ".*$", "gm"); - var groupRegExp = new RegExp("^a=group:.*$", "gm"); - if (descriptionRegExp.test(sdp)) { - var midLineToRemove_1; - sdp = sdp.split(/^m=/gm).filter(function (section) { - if (section.substr(0, description.length) === description) { - midLineToRemove_1 = section.match(/^a=mid:.*$/gm); - if (midLineToRemove_1) { - var step = midLineToRemove_1[0].match(/:.+$/g); - if (step) { - midLineToRemove_1 = step[0].substr(1); - } - } - return false; - } - return true; - }).join("m="); - var groupLine = sdp.match(groupRegExp); - if (groupLine && groupLine.length === 1) { - var groupLinePortion = groupLine[0]; - var groupRegExpReplace = new RegExp("\ *" + midLineToRemove_1 + "[^\ ]*", "g"); - groupLinePortion = groupLinePortion.replace(groupRegExpReplace, ""); - sdp = sdp.split(groupRegExp).join(groupLinePortion); - } - } - return sdp; -}; -function stripTcpCandidates(description) { - description.sdp = (description.sdp || "").replace(/^a=candidate:\d+ \d+ tcp .*?\r\n/img, ""); - return Promise.resolve(description); -} -exports.stripTcpCandidates = stripTcpCandidates; -function stripTelephoneEvent(description) { - description.sdp = stripPayload(description.sdp || "", "telephone-event"); - return Promise.resolve(description); -} -exports.stripTelephoneEvent = stripTelephoneEvent; -function cleanJitsiSdpImageattr(description) { - description.sdp = (description.sdp || "").replace(/^(a=imageattr:.*?)(x|y)=\[0-/gm, "$1$2=[1:"); - return Promise.resolve(description); -} -exports.cleanJitsiSdpImageattr = cleanJitsiSdpImageattr; -function stripG722(description) { - description.sdp = stripPayload(description.sdp || "", "G722"); - return Promise.resolve(description); -} -exports.stripG722 = stripG722; -function stripRtpPayload(payload) { - return function (description) { - description.sdp = stripPayload(description.sdp || "", payload); - return Promise.resolve(description); - }; -} -exports.stripRtpPayload = stripRtpPayload; -function stripVideo(description) { - description.sdp = stripMediaDescription(description.sdp || "", "video"); - return Promise.resolve(description); -} -exports.stripVideo = stripVideo; -function addMidLines(description) { - var sdp = description.sdp || ""; - if (sdp.search(/^a=mid.*$/gm) === -1) { - var mlines_1 = sdp.match(/^m=.*$/gm); - var sdpArray_1 = sdp.split(/^m=.*$/gm); - if (mlines_1) { - mlines_1.forEach(function (elem, idx) { - mlines_1[idx] = elem + "\na=mid:" + idx; - }); - } - sdpArray_1.forEach(function (elem, idx) { - if (mlines_1 && mlines_1[idx]) { - sdpArray_1[idx] = elem + mlines_1[idx]; - } - }); - sdp = sdpArray_1.join(""); - description.sdp = sdp; - } - return Promise.resolve(description); -} -exports.addMidLines = addMidLines; - - -/***/ }), -/* 102 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var Enums_1 = __webpack_require__(82); -/* SessionDescriptionHandlerObserver - * @class SessionDescriptionHandler Observer Class. - * @param {SIP.Session} session - * @param {Object} [options] - */ -var SessionDescriptionHandlerObserver = /** @class */ (function () { - function SessionDescriptionHandlerObserver(session, options) { - this.type = Enums_1.TypeStrings.SessionDescriptionHandlerObserver; - this.session = session; - this.options = options; - } - SessionDescriptionHandlerObserver.prototype.trackAdded = function () { - this.session.emit("trackAdded"); - }; - SessionDescriptionHandlerObserver.prototype.directionChanged = function () { - this.session.emit("directionChanged"); - }; - return SessionDescriptionHandlerObserver; -}()); -exports.SessionDescriptionHandlerObserver = SessionDescriptionHandlerObserver; - - -/***/ }), -/* 103 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var core_1 = __webpack_require__(2); -var Enums_1 = __webpack_require__(82); -var Exceptions_1 = __webpack_require__(84); -var Utils_1 = __webpack_require__(83); -var TransportStatus; -(function (TransportStatus) { - TransportStatus[TransportStatus["STATUS_CONNECTING"] = 0] = "STATUS_CONNECTING"; - TransportStatus[TransportStatus["STATUS_OPEN"] = 1] = "STATUS_OPEN"; - TransportStatus[TransportStatus["STATUS_CLOSING"] = 2] = "STATUS_CLOSING"; - TransportStatus[TransportStatus["STATUS_CLOSED"] = 3] = "STATUS_CLOSED"; -})(TransportStatus = exports.TransportStatus || (exports.TransportStatus = {})); -/** - * Compute an amount of time in seconds to wait before sending another - * keep-alive. - * @returns {Number} - */ -var computeKeepAliveTimeout = function (upperBound) { - var lowerBound = upperBound * 0.8; - return 1000 * (Math.random() * (upperBound - lowerBound) + lowerBound); -}; -/** - * @class Transport - * @param {Object} options - */ -var Transport = /** @class */ (function (_super) { - tslib_1.__extends(Transport, _super); - function Transport(logger, options) { - if (options === void 0) { options = {}; } - var _this = _super.call(this, logger, options) || this; - _this.type = Enums_1.TypeStrings.Transport; - _this.reconnectionAttempts = 0; - _this.status = TransportStatus.STATUS_CONNECTING; - _this.configuration = _this.loadConfig(options); - _this.server = _this.configuration.wsServers[0]; - return _this; - } - /** - * @returns {Boolean} - */ - Transport.prototype.isConnected = function () { - return this.status === TransportStatus.STATUS_OPEN; - }; - /** - * Send a message. - * @param {SIP.OutgoingRequest|String} msg - * @param {Object} [options] - * @returns {Promise} - */ - Transport.prototype.sendPromise = function (msg, options) { - if (options === void 0) { options = {}; } - if (!this.statusAssert(TransportStatus.STATUS_OPEN, options.force)) { - this.onError("unable to send message - WebSocket not open"); - return Promise.reject(); - } - var message = msg.toString(); - if (this.ws) { - if (this.configuration.traceSip === true) { - this.logger.log("sending WebSocket message:\n\n" + message + "\n"); - } - this.ws.send(message); - return Promise.resolve({ msg: message }); - } - else { - this.onError("unable to send message - WebSocket does not exist"); - return Promise.reject(); - } - }; - /** - * Disconnect socket. - */ - Transport.prototype.disconnectPromise = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - if (this.disconnectionPromise) { // Already disconnecting. Just return this. - return this.disconnectionPromise; - } - options.code = options.code || 1000; - if (!this.statusTransition(TransportStatus.STATUS_CLOSING, options.force)) { - if (this.status === TransportStatus.STATUS_CLOSED) { // Websocket is already closed - return Promise.resolve({ overrideEvent: true }); - } - else if (this.connectionPromise) { // Websocket is connecting, cannot move to disconneting yet - return this.connectionPromise.then(function () { return Promise.reject("The websocket did not disconnect"); }) - .catch(function () { return Promise.resolve({ overrideEvent: true }); }); - } - else { - // Cannot move to disconnecting, but not in connecting state. - return Promise.reject("The websocket did not disconnect"); - } - } - this.emit("disconnecting"); - this.disconnectionPromise = new Promise(function (resolve, reject) { - _this.disconnectDeferredResolve = resolve; - if (_this.reconnectTimer) { - clearTimeout(_this.reconnectTimer); - _this.reconnectTimer = undefined; - } - if (_this.ws) { - _this.stopSendingKeepAlives(); - _this.logger.log("closing WebSocket " + _this.server.wsUri); - _this.ws.close(options.code, options.reason); - } - else { - reject("Attempted to disconnect but the websocket doesn't exist"); - } - }); - return this.disconnectionPromise; - }; - /** - * Connect socket. - */ - Transport.prototype.connectPromise = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - if (this.status === TransportStatus.STATUS_CLOSING && !options.force) { - return Promise.reject("WebSocket " + this.server.wsUri + " is closing"); - } - if (this.connectionPromise) { - return this.connectionPromise; - } - this.server = this.server || this.getNextWsServer(options.force); - this.connectionPromise = new Promise(function (resolve, reject) { - if ((_this.status === TransportStatus.STATUS_OPEN || _this.status === TransportStatus.STATUS_CLOSING) - && !options.force) { - _this.logger.warn("WebSocket " + _this.server.wsUri + " is already connected"); - reject("Failed status check - attempted to open a connection but already open/closing"); - return; - } - _this.connectDeferredResolve = resolve; - _this.connectDeferredReject = reject; - _this.status = TransportStatus.STATUS_CONNECTING; - _this.emit("connecting"); - _this.logger.log("connecting to WebSocket " + _this.server.wsUri); - _this.disposeWs(); - try { - _this.ws = new WebSocket(_this.server.wsUri, "sip"); - } - catch (e) { - _this.ws = null; - _this.statusTransition(TransportStatus.STATUS_CLOSED, true); - _this.onError("error connecting to WebSocket " + _this.server.wsUri + ":" + e); - reject("Failed to create a websocket"); - _this.connectDeferredResolve = undefined; - _this.connectDeferredReject = undefined; - return; - } - if (!_this.ws) { - reject("Unexpected instance websocket not set"); - _this.connectDeferredResolve = undefined; - _this.connectDeferredReject = undefined; - return; - } - _this.connectionTimeout = setTimeout(function () { - _this.statusTransition(TransportStatus.STATUS_CLOSED); - _this.logger.warn("took too long to connect - exceeded time set in configuration.connectionTimeout: " + - _this.configuration.connectionTimeout + "s"); - _this.emit("disconnected", { code: 1000 }); - _this.connectionPromise = undefined; - reject("Connection timeout"); - _this.connectDeferredResolve = undefined; - _this.connectDeferredReject = undefined; - var ws = _this.ws; - _this.disposeWs(); - ws.close(1000); - }, _this.configuration.connectionTimeout * 1000); - _this.boundOnOpen = _this.onOpen.bind(_this); - _this.boundOnMessage = _this.onMessage.bind(_this); - _this.boundOnClose = _this.onClose.bind(_this); - _this.boundOnError = _this.onWebsocketError.bind(_this); - _this.ws.addEventListener("open", _this.boundOnOpen); - _this.ws.addEventListener("message", _this.boundOnMessage); - _this.ws.addEventListener("close", _this.boundOnClose); - _this.ws.addEventListener("error", _this.boundOnError); - }); - return this.connectionPromise; - }; - /** - * @event - * @param {event} e - */ - Transport.prototype.onMessage = function (e) { - var data = e.data; - var finishedData; - // CRLF Keep Alive response from server. Clear our keep alive timeout. - if (/^(\r\n)+$/.test(data)) { - this.clearKeepAliveTimeout(); - if (this.configuration.traceSip === true) { - this.logger.log("received WebSocket message with CRLF Keep Alive response"); - } - return; - } - else if (!data) { - this.logger.warn("received empty message, message discarded"); - return; - } - else if (typeof data !== "string") { // WebSocket binary message. - try { - // the UInt8Data was here prior to types, and doesn't check - finishedData = String.fromCharCode.apply(null, new Uint8Array(data)); - } - catch (err) { - this.logger.warn("received WebSocket binary message failed to be converted into string, message discarded"); - return; - } - if (this.configuration.traceSip === true) { - this.logger.log("received WebSocket binary message:\n\n" + data + "\n"); - } - } - else { // WebSocket text message. - if (this.configuration.traceSip === true) { - this.logger.log("received WebSocket text message:\n\n" + data + "\n"); - } - finishedData = data; - } - this.emit("message", finishedData); - }; - // Transport Event Handlers - /** - * @event - * @param {event} e - */ - Transport.prototype.onOpen = function () { - if (this.status === TransportStatus.STATUS_CLOSED) { // Indicated that the transport thinks the ws is dead already - var ws = this.ws; - this.disposeWs(); - ws.close(1000); - return; - } - this.statusTransition(TransportStatus.STATUS_OPEN, true); - this.emit("connected"); - if (this.connectionTimeout) { - clearTimeout(this.connectionTimeout); - this.connectionTimeout = undefined; - } - this.logger.log("WebSocket " + this.server.wsUri + " connected"); - // Clear reconnectTimer since we are not disconnected - if (this.reconnectTimer !== undefined) { - clearTimeout(this.reconnectTimer); - this.reconnectTimer = undefined; - } - // Reset reconnectionAttempts - this.reconnectionAttempts = 0; - // Reset disconnection promise so we can disconnect from a fresh state - this.disconnectionPromise = undefined; - this.disconnectDeferredResolve = undefined; - // Start sending keep-alives - this.startSendingKeepAlives(); - if (this.connectDeferredResolve) { - this.connectDeferredResolve({ overrideEvent: true }); - this.connectDeferredResolve = undefined; - this.connectDeferredReject = undefined; - } - else { - this.logger.warn("Unexpected websocket.onOpen with no connectDeferredResolve"); - } - }; - /** - * @event - * @param {event} e - */ - Transport.prototype.onClose = function (e) { - this.logger.log("WebSocket disconnected (code: " + e.code + (e.reason ? "| reason: " + e.reason : "") + ")"); - if (this.status !== TransportStatus.STATUS_CLOSING) { - this.logger.warn("WebSocket closed without SIP.js requesting it"); - this.emit("transportError"); - } - this.stopSendingKeepAlives(); - // Clean up connection variables so we can connect again from a fresh state - if (this.connectionTimeout) { - clearTimeout(this.connectionTimeout); - } - if (this.connectDeferredReject) { - this.connectDeferredReject("Websocket Closed"); - } - this.connectionTimeout = undefined; - this.connectionPromise = undefined; - this.connectDeferredResolve = undefined; - this.connectDeferredReject = undefined; - // Check whether the user requested to close. - if (this.disconnectDeferredResolve) { - this.disconnectDeferredResolve({ overrideEvent: true }); - this.statusTransition(TransportStatus.STATUS_CLOSED); - this.disconnectDeferredResolve = undefined; - return; - } - this.statusTransition(TransportStatus.STATUS_CLOSED, true); - this.emit("disconnected", { code: e.code, reason: e.reason }); - this.disposeWs(); - this.reconnect(); - }; - /** - * Removes event listeners and clears the instance ws - */ - Transport.prototype.disposeWs = function () { - if (this.ws) { - this.ws.removeEventListener("open", this.boundOnOpen); - this.ws.removeEventListener("message", this.boundOnMessage); - this.ws.removeEventListener("close", this.boundOnClose); - this.ws.removeEventListener("error", this.boundOnError); - this.ws = undefined; - } - }; - /** - * @event - * @param {string} e - */ - Transport.prototype.onError = function (e) { - this.logger.warn("Transport error: " + e); - this.emit("transportError"); - }; - /** - * @event - * @private - */ - Transport.prototype.onWebsocketError = function () { - this.onError("The Websocket had an error"); - }; - /** - * Reconnection attempt logic. - */ - Transport.prototype.reconnect = function () { - var _this = this; - if (this.reconnectionAttempts > 0) { - this.logger.log("Reconnection attempt " + this.reconnectionAttempts + " failed"); - } - if (this.noAvailableServers()) { - this.logger.warn("attempted to get next ws server but there are no available ws servers left"); - this.logger.warn("no available ws servers left - going to closed state"); - this.statusTransition(TransportStatus.STATUS_CLOSED, true); - this.emit("closed"); - this.resetServerErrorStatus(); - return; - } - if (this.isConnected()) { - this.logger.warn("attempted to reconnect while connected - forcing disconnect"); - this.disconnect({ force: true }); - } - this.reconnectionAttempts += 1; - if (this.reconnectionAttempts > this.configuration.maxReconnectionAttempts) { - this.logger.warn("maximum reconnection attempts for WebSocket " + this.server.wsUri); - this.logger.log("transport " + this.server.wsUri + " failed | connection state set to 'error'"); - this.server.isError = true; - this.emit("transportError"); - if (!this.noAvailableServers()) { - this.server = this.getNextWsServer(); - } - // When there are no available servers, the reconnect function ends on the next recursive call - // after checking for no available servers again. - this.reconnectionAttempts = 0; - this.reconnect(); - } - else { - this.logger.log("trying to reconnect to WebSocket " + - this.server.wsUri + " (reconnection attempt " + this.reconnectionAttempts + ")"); - this.reconnectTimer = setTimeout(function () { - _this.connect(); - _this.reconnectTimer = undefined; - }, (this.reconnectionAttempts === 1) ? 0 : this.configuration.reconnectionTimeout * 1000); - } - }; - /** - * Resets the error state of all servers in the configuration - */ - Transport.prototype.resetServerErrorStatus = function () { - for (var _i = 0, _a = this.configuration.wsServers; _i < _a.length; _i++) { - var websocket = _a[_i]; - websocket.isError = false; - } - }; - /** - * Retrieve the next server to which connect. - * @param {Boolean} force allows bypass of server error status checking - * @returns {Object} WsServer - */ - Transport.prototype.getNextWsServer = function (force) { - if (force === void 0) { force = false; } - if (this.noAvailableServers()) { - this.logger.warn("attempted to get next ws server but there are no available ws servers left"); - throw new Error("Attempted to get next ws server, but there are no available ws servers left."); - } - // Order servers by weight - var candidates = []; - for (var _i = 0, _a = this.configuration.wsServers; _i < _a.length; _i++) { - var wsServer = _a[_i]; - if (wsServer.isError && !force) { - continue; - } - else if (candidates.length === 0) { - candidates.push(wsServer); - } - else if (wsServer.weight > candidates[0].weight) { - candidates = [wsServer]; - } - else if (wsServer.weight === candidates[0].weight) { - candidates.push(wsServer); - } - } - var idx = Math.floor(Math.random() * candidates.length); - return candidates[idx]; - }; - /** - * Checks all configuration servers, returns true if all of them have isError: true and false otherwise - * @returns {Boolean} - */ - Transport.prototype.noAvailableServers = function () { - for (var _i = 0, _a = this.configuration.wsServers; _i < _a.length; _i++) { - var server = _a[_i]; - if (!server.isError) { - return false; - } - } - return true; - }; - // ============================== - // KeepAlive Stuff - // ============================== - /** - * Send a keep-alive (a double-CRLF sequence). - * @returns {Boolean} - */ - Transport.prototype.sendKeepAlive = function () { - var _this = this; - if (this.keepAliveDebounceTimeout) { - // We already have an outstanding keep alive, do not send another. - return; - } - this.keepAliveDebounceTimeout = setTimeout(function () { - _this.emit("keepAliveDebounceTimeout"); - _this.clearKeepAliveTimeout(); - }, this.configuration.keepAliveDebounce * 1000); - return this.send("\r\n\r\n"); - }; - Transport.prototype.clearKeepAliveTimeout = function () { - if (this.keepAliveDebounceTimeout) { - clearTimeout(this.keepAliveDebounceTimeout); - } - this.keepAliveDebounceTimeout = undefined; - }; - /** - * Start sending keep-alives. - */ - Transport.prototype.startSendingKeepAlives = function () { - var _this = this; - if (this.configuration.keepAliveInterval && !this.keepAliveInterval) { - this.keepAliveInterval = setInterval(function () { - _this.sendKeepAlive(); - _this.startSendingKeepAlives(); - }, computeKeepAliveTimeout(this.configuration.keepAliveInterval)); - } - }; - /** - * Stop sending keep-alives. - */ - Transport.prototype.stopSendingKeepAlives = function () { - if (this.keepAliveInterval) { - clearInterval(this.keepAliveInterval); - } - if (this.keepAliveDebounceTimeout) { - clearTimeout(this.keepAliveDebounceTimeout); - } - this.keepAliveInterval = undefined; - this.keepAliveDebounceTimeout = undefined; - }; - // ============================== - // Status Stuff - // ============================== - /** - * Checks given status against instance current status. Returns true if they match - * @param {Number} status - * @param {Boolean} [force] - * @returns {Boolean} - */ - Transport.prototype.statusAssert = function (status, force) { - if (status === this.status) { - return true; - } - else { - if (force) { - this.logger.warn("Attempted to assert " + - Object.keys(TransportStatus)[this.status] + " as " + - Object.keys(TransportStatus)[status] + "- continuing with option: 'force'"); - return true; - } - else { - this.logger.warn("Tried to assert " + - Object.keys(TransportStatus)[status] + " but is currently " + - Object.keys(TransportStatus)[this.status]); - return false; - } - } - }; - /** - * Transitions the status. Checks for legal transition via assertion beforehand - * @param {Number} status - * @param {Boolean} [force] - * @returns {Boolean} - */ - Transport.prototype.statusTransition = function (status, force) { - if (force === void 0) { force = false; } - this.logger.log("Attempting to transition status from " + - Object.keys(TransportStatus)[this.status] + " to " + - Object.keys(TransportStatus)[status]); - if ((status === TransportStatus.STATUS_CONNECTING && this.statusAssert(TransportStatus.STATUS_CLOSED, force)) || - (status === TransportStatus.STATUS_OPEN && this.statusAssert(TransportStatus.STATUS_CONNECTING, force)) || - (status === TransportStatus.STATUS_CLOSING && this.statusAssert(TransportStatus.STATUS_OPEN, force)) || - (status === TransportStatus.STATUS_CLOSED)) { - this.status = status; - return true; - } - else { - this.logger.warn("Status transition failed - result: no-op - reason:" + - " either gave an nonexistent status or attempted illegal transition"); - return false; - } - }; - // ============================== - // Configuration Handling - // ============================== - /** - * Configuration load. - * returns {Configuration} - */ - Transport.prototype.loadConfig = function (configuration) { - var settings = { - wsServers: [{ - scheme: "WSS", - sipUri: "", - weight: 0, - wsUri: "wss://edge.sip.onsip.com", - isError: false - }], - connectionTimeout: 5, - maxReconnectionAttempts: 3, - reconnectionTimeout: 4, - keepAliveInterval: 0, - keepAliveDebounce: 10, - // Logging - traceSip: false - }; - var configCheck = this.getConfigurationCheck(); - // Check Mandatory parameters - for (var parameter in configCheck.mandatory) { - if (!configuration.hasOwnProperty(parameter)) { - throw new Exceptions_1.Exceptions.ConfigurationError(parameter); - } - else { - var value = configuration[parameter]; - var checkedValue = configCheck.mandatory[parameter](value); - if (checkedValue !== undefined) { - settings[parameter] = checkedValue; - } - else { - throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); - } - } - } - // Check Optional parameters - for (var parameter in configCheck.optional) { - if (configuration.hasOwnProperty(parameter)) { - var value = configuration[parameter]; - // If the parameter value is an empty array, but shouldn't be, apply its default value. - // If the parameter value is null, empty string, or undefined then apply its default value. - // If it's a number with NaN value then also apply its default value. - // NOTE: JS does not allow "value === NaN", the following does the work: - if ((value instanceof Array && value.length === 0) || - (value === null || value === "" || value === undefined) || - (typeof (value) === "number" && isNaN(value))) { - continue; - } - var checkedValue = configCheck.optional[parameter](value); - if (checkedValue !== undefined) { - settings[parameter] = checkedValue; - } - else { - throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); - } - } - } - var skeleton = {}; // Fill the value of the configuration_skeleton - for (var parameter in settings) { - if (settings.hasOwnProperty(parameter)) { - skeleton[parameter] = { - value: settings[parameter], - }; - } - } - var returnConfiguration = Object.defineProperties({}, skeleton); - this.logger.log("configuration parameters after validation:"); - for (var parameter in settings) { - if (settings.hasOwnProperty(parameter)) { - this.logger.log("· " + parameter + ": " + JSON.stringify(settings[parameter])); - } - } - return returnConfiguration; - }; - /** - * Configuration checker. - * @return {Boolean} - */ - Transport.prototype.getConfigurationCheck = function () { - return { - mandatory: {}, - optional: { - // Note: this function used to call 'this.logger.error' but calling 'this' with anything here is invalid - wsServers: function (wsServers) { - /* Allow defining wsServers parameter as: - * String: "host" - * Array of Strings: ["host1", "host2"] - * Array of Objects: [{wsUri:"host1", weight:1}, {wsUri:"host2", weight:0}] - * Array of Objects and Strings: [{wsUri:"host1"}, "host2"] - */ - if (typeof wsServers === "string") { - wsServers = [{ wsUri: wsServers }]; - } - else if (wsServers instanceof Array) { - for (var idx = 0; idx < wsServers.length; idx++) { - if (typeof wsServers[idx] === "string") { - wsServers[idx] = { wsUri: wsServers[idx] }; - } - } - } - else { - return; - } - if (wsServers.length === 0) { - return false; - } - for (var _i = 0, wsServers_1 = wsServers; _i < wsServers_1.length; _i++) { - var wsServer = wsServers_1[_i]; - if (!wsServer.wsUri) { - return; - } - if (wsServer.weight && !Number(wsServer.weight)) { - return; - } - var url = core_1.Grammar.parse(wsServer.wsUri, "absoluteURI"); - if (url === -1) { - return; - } - else if (["wss", "ws", "udp"].indexOf(url.scheme) < 0) { - return; - } - else { - wsServer.sipUri = ""; - if (!wsServer.weight) { - wsServer.weight = 0; - } - wsServer.isError = false; - wsServer.scheme = url.scheme.toUpperCase(); - } - } - return wsServers; - }, - keepAliveInterval: function (keepAliveInterval) { - if (Utils_1.Utils.isDecimal(keepAliveInterval)) { - var value = Number(keepAliveInterval); - if (value > 0) { - return value; - } - } - }, - keepAliveDebounce: function (keepAliveDebounce) { - if (Utils_1.Utils.isDecimal(keepAliveDebounce)) { - var value = Number(keepAliveDebounce); - if (value > 0) { - return value; - } - } - }, - traceSip: function (traceSip) { - if (typeof traceSip === "boolean") { - return traceSip; - } - }, - connectionTimeout: function (connectionTimeout) { - if (Utils_1.Utils.isDecimal(connectionTimeout)) { - var value = Number(connectionTimeout); - if (value > 0) { - return value; - } - } - }, - maxReconnectionAttempts: function (maxReconnectionAttempts) { - if (Utils_1.Utils.isDecimal(maxReconnectionAttempts)) { - var value = Number(maxReconnectionAttempts); - if (value >= 0) { - return value; - } - } - }, - reconnectionTimeout: function (reconnectionTimeout) { - if (Utils_1.Utils.isDecimal(reconnectionTimeout)) { - var value = Number(reconnectionTimeout); - if (value > 0) { - return value; - } - } - } - } - }; - }; - Transport.C = TransportStatus; - return Transport; -}(core_1.Transport)); -exports.Transport = Transport; - - -/***/ }), -/* 104 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var Modifiers = tslib_1.__importStar(__webpack_require__(101)); -exports.Modifiers = Modifiers; -var Simple_1 = __webpack_require__(105); -exports.Simple = Simple_1.Simple; -var SessionDescriptionHandler_1 = __webpack_require__(94); -exports.SessionDescriptionHandler = SessionDescriptionHandler_1.SessionDescriptionHandler; -var Transport_1 = __webpack_require__(103); -exports.Transport = Transport_1.Transport; - - -/***/ }), -/* 105 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var events_1 = __webpack_require__(30); -var UA_1 = __webpack_require__(93); -var Modifiers = tslib_1.__importStar(__webpack_require__(101)); -/* Simple - * @class Simple - */ -var SimpleStatus; -(function (SimpleStatus) { - SimpleStatus[SimpleStatus["STATUS_NULL"] = 0] = "STATUS_NULL"; - SimpleStatus[SimpleStatus["STATUS_NEW"] = 1] = "STATUS_NEW"; - SimpleStatus[SimpleStatus["STATUS_CONNECTING"] = 2] = "STATUS_CONNECTING"; - SimpleStatus[SimpleStatus["STATUS_CONNECTED"] = 3] = "STATUS_CONNECTED"; - SimpleStatus[SimpleStatus["STATUS_COMPLETED"] = 4] = "STATUS_COMPLETED"; -})(SimpleStatus = exports.SimpleStatus || (exports.SimpleStatus = {})); -var Simple = /** @class */ (function (_super) { - tslib_1.__extends(Simple, _super); - function Simple(options) { - var _this = _super.call(this) || this; - /* - * { - * media: { - * remote: { - * audio: , - * video: - * }, - * local: { - * video: - * } - * }, - * ua: { - * - * } - * } - */ - if (options.media.remote.video) { - _this.video = true; - } - else { - _this.video = false; - } - if (options.media.remote.audio) { - _this.audio = true; - } - else { - _this.audio = false; - } - if (!_this.audio && !_this.video) { - // Need to do at least audio or video - // Error - throw new Error("At least one remote audio or video element is required for Simple."); - } - _this.options = options; - // https://stackoverflow.com/questions/7944460/detect-safari-browser - var browserUa = navigator.userAgent.toLowerCase(); - var isSafari = false; - var isFirefox = false; - if (browserUa.indexOf("safari") > -1 && browserUa.indexOf("chrome") < 0) { - isSafari = true; - } - else if (browserUa.indexOf("firefox") > -1 && browserUa.indexOf("chrome") < 0) { - isFirefox = true; - } - var sessionDescriptionHandlerFactoryOptions = {}; - if (isSafari) { - sessionDescriptionHandlerFactoryOptions.modifiers = [Modifiers.stripG722]; - } - if (isFirefox) { - sessionDescriptionHandlerFactoryOptions.alwaysAcquireMediaFirst = true; - } - if (!_this.options.ua.uri) { - _this.anonymous = true; - } - else { - _this.anonymous = false; - } - _this.ua = new UA_1.UA({ - // User Configurable Options - uri: _this.options.ua.uri, - authorizationUser: _this.options.ua.authorizationUser, - password: _this.options.ua.password, - displayName: _this.options.ua.displayName, - // Undocumented "Advanced" Options - userAgentString: _this.options.ua.userAgentString, - // Fixed Options - register: true, - sessionDescriptionHandlerFactoryOptions: sessionDescriptionHandlerFactoryOptions, - transportOptions: { - traceSip: _this.options.ua.traceSip, - wsServers: _this.options.ua.wsServers - } - }); - _this.state = SimpleStatus.STATUS_NULL; - _this.logger = _this.ua.getLogger("sip.simple"); - _this.ua.on("registered", function () { - _this.emit("registered", _this.ua); - }); - _this.ua.on("unregistered", function () { - _this.emit("unregistered", _this.ua); - }); - _this.ua.on("registrationFailed", function () { - _this.emit("unregistered", _this.ua); - }); - _this.ua.on("invite", function (session) { - // If there is already an active session reject the incoming session - if (_this.state !== SimpleStatus.STATUS_NULL && _this.state !== SimpleStatus.STATUS_COMPLETED) { - _this.logger.warn("Rejecting incoming call. Simple only supports 1 call at a time"); - session.reject(); - return; - } - _this.session = session; - _this.setupSession(); - _this.emit("ringing", _this.session); - }); - _this.ua.on("message", function (message) { - _this.emit("message", message); - }); - return _this; - } - Simple.prototype.call = function (destination) { - if (!this.ua || !this.checkRegistration()) { - this.logger.warn("A registered UA is required for calling"); - return; - } - if (this.state !== SimpleStatus.STATUS_NULL && this.state !== SimpleStatus.STATUS_COMPLETED) { - this.logger.warn("Cannot make more than a single call with Simple"); - return; - } - // Safari hack, because you cannot call .play() from a non user action - if (this.options.media.remote.audio) { - this.options.media.remote.audio.autoplay = true; - } - if (this.options.media.remote.video) { - this.options.media.remote.video.autoplay = true; - } - if (this.options.media.local && this.options.media.local.video) { - this.options.media.local.video.autoplay = true; - this.options.media.local.video.volume = 0; - } - this.session = this.ua.invite(destination, { - sessionDescriptionHandlerOptions: { - constraints: { - audio: this.audio, - video: this.video - } - } - }); - this.setupSession(); - return this.session; - }; - Simple.prototype.answer = function () { - if (this.state !== SimpleStatus.STATUS_NEW && this.state !== SimpleStatus.STATUS_CONNECTING) { - this.logger.warn("No call to answer"); - return; - } - // Safari hack, because you cannot call .play() from a non user action - if (this.options.media.remote.audio) { - this.options.media.remote.audio.autoplay = true; - } - if (this.options.media.remote.video) { - this.options.media.remote.video.autoplay = true; - } - return this.session.accept({ - sessionDescriptionHandlerOptions: { - constraints: { - audio: this.audio, - video: this.video - } - } - }); - // emit call is active - }; - Simple.prototype.reject = function () { - if (this.state !== SimpleStatus.STATUS_NEW && this.state !== SimpleStatus.STATUS_CONNECTING) { - this.logger.warn("Call is already answered"); - return; - } - return this.session.reject(); - }; - Simple.prototype.hangup = function () { - if (this.state !== SimpleStatus.STATUS_CONNECTED && - this.state !== SimpleStatus.STATUS_CONNECTING && - this.state !== SimpleStatus.STATUS_NEW) { - this.logger.warn("No active call to hang up on"); - return; - } - if (this.state !== SimpleStatus.STATUS_CONNECTED) { - return this.session.cancel(); - } - else if (this.session) { - return this.session.bye(); - } - }; - Simple.prototype.hold = function () { - if (this.state !== SimpleStatus.STATUS_CONNECTED || !this.session || this.session.localHold) { - this.logger.warn("Cannot put call on hold"); - return; - } - this.mute(); - this.logger.log("Placing session on hold"); - return this.session.hold(); - }; - Simple.prototype.unhold = function () { - if (this.state !== SimpleStatus.STATUS_CONNECTED || !this.session || !this.session.localHold) { - this.logger.warn("Cannot unhold a call that is not on hold"); - return; - } - this.unmute(); - this.logger.log("Placing call off hold"); - return this.session.unhold(); - }; - Simple.prototype.mute = function () { - if (this.state !== SimpleStatus.STATUS_CONNECTED) { - this.logger.warn("An acitve call is required to mute audio"); - return; - } - this.logger.log("Muting Audio"); - this.toggleMute(true); - this.emit("mute", this); - }; - Simple.prototype.unmute = function () { - if (this.state !== SimpleStatus.STATUS_CONNECTED) { - this.logger.warn("An active call is required to unmute audio"); - return; - } - this.logger.log("Unmuting Audio"); - this.toggleMute(false); - this.emit("unmute", this); - }; - Simple.prototype.sendDTMF = function (tone) { - if (this.state !== SimpleStatus.STATUS_CONNECTED || !this.session) { - this.logger.warn("An active call is required to send a DTMF tone"); - return; - } - this.logger.log("Sending DTMF tone: " + tone); - this.session.dtmf(tone); - }; - Simple.prototype.message = function (destination, message) { - if (!this.ua || !this.checkRegistration()) { - this.logger.warn("A registered UA is required to send a message"); - return; - } - if (!destination || !message) { - this.logger.warn("A destination and message are required to send a message"); - return; - } - this.ua.message(destination, message); - }; - // Private Helpers - Simple.prototype.checkRegistration = function () { - return (this.anonymous || (this.ua && this.ua.isRegistered())); - }; - Simple.prototype.setupRemoteMedia = function () { - var _this = this; - if (!this.session) { - this.logger.warn("No session to set remote media on"); - return; - } - // If there is a video track, it will attach the video and audio to the same element - var pc = this.session.sessionDescriptionHandler.peerConnection; - var remoteStream; - if (pc.getReceivers) { - remoteStream = new MediaStream(); - pc.getReceivers().forEach(function (receiver) { - var track = receiver.track; - if (track) { - remoteStream.addTrack(track); - } - }); - } - else { - remoteStream = pc.getRemoteStreams()[0]; - } - if (this.video) { - this.options.media.remote.video.srcObject = remoteStream; - this.options.media.remote.video.play().catch(function () { - _this.logger.log("play was rejected"); - }); - } - else if (this.audio) { - this.options.media.remote.audio.srcObject = remoteStream; - this.options.media.remote.audio.play().catch(function () { - _this.logger.log("play was rejected"); - }); - } - }; - Simple.prototype.setupLocalMedia = function () { - if (!this.session) { - this.logger.warn("No session to set local media on"); - return; - } - if (this.video && this.options.media.local && this.options.media.local.video) { - var pc = this.session.sessionDescriptionHandler.peerConnection; - var localStream_1; - if (pc.getSenders) { - localStream_1 = new MediaStream(); - pc.getSenders().forEach(function (sender) { - var track = sender.track; - if (track && track.kind === "video") { - localStream_1.addTrack(track); - } - }); - } - else { - localStream_1 = pc.getLocalStreams()[0]; - } - this.options.media.local.video.srcObject = localStream_1; - this.options.media.local.video.volume = 0; - this.options.media.local.video.play(); - } - }; - Simple.prototype.cleanupMedia = function () { - if (this.video) { - this.options.media.remote.video.srcObject = null; - this.options.media.remote.video.pause(); - if (this.options.media.local && this.options.media.local.video) { - this.options.media.local.video.srcObject = null; - this.options.media.local.video.pause(); - } - } - if (this.audio) { - this.options.media.remote.audio.srcObject = null; - this.options.media.remote.audio.pause(); - } - }; - Simple.prototype.setupSession = function () { - var _this = this; - if (!this.session) { - this.logger.warn("No session to set up"); - return; - } - this.state = SimpleStatus.STATUS_NEW; - this.emit("new", this.session); - this.session.on("progress", function () { return _this.onProgress(); }); - this.session.on("accepted", function () { return _this.onAccepted(); }); - this.session.on("rejected", function () { return _this.onEnded(); }); - this.session.on("failed", function () { return _this.onFailed(); }); - this.session.on("terminated", function () { return _this.onEnded(); }); - }; - Simple.prototype.destroyMedia = function () { - if (this.session && this.session.sessionDescriptionHandler) { - this.session.sessionDescriptionHandler.close(); - } - }; - Simple.prototype.toggleMute = function (mute) { - if (!this.session) { - this.logger.warn("No session to toggle mute"); - return; - } - var pc = this.session.sessionDescriptionHandler.peerConnection; - if (pc.getSenders) { - pc.getSenders().forEach(function (sender) { - if (sender.track) { - sender.track.enabled = !mute; - } - }); - } - else { - pc.getLocalStreams().forEach(function (stream) { - stream.getAudioTracks().forEach(function (track) { - track.enabled = !mute; - }); - stream.getVideoTracks().forEach(function (track) { - track.enabled = !mute; - }); - }); - } - }; - Simple.prototype.onAccepted = function () { - var _this = this; - if (!this.session) { - this.logger.warn("No session for accepting"); - return; - } - this.state = SimpleStatus.STATUS_CONNECTED; - this.emit("connected", this.session); - this.setupLocalMedia(); - this.setupRemoteMedia(); - if (this.session.sessionDescriptionHandler) { - this.session.sessionDescriptionHandler.on("addTrack", function () { - _this.logger.log("A track has been added, triggering new remoteMedia setup"); - _this.setupRemoteMedia(); - }); - this.session.sessionDescriptionHandler.on("addStream", function () { - _this.logger.log("A stream has been added, trigger new remoteMedia setup"); - _this.setupRemoteMedia(); - }); - } - this.session.on("dtmf", function (request, dtmf) { - _this.emit("dtmf", dtmf.tone); - }); - this.session.on("bye", function () { return _this.onEnded(); }); - }; - Simple.prototype.onProgress = function () { - this.state = SimpleStatus.STATUS_CONNECTING; - this.emit("connecting", this.session); - }; - Simple.prototype.onFailed = function () { - this.onEnded(); - }; - Simple.prototype.onEnded = function () { - this.state = SimpleStatus.STATUS_COMPLETED; - this.emit("ended", this.session); - this.cleanupMedia(); - }; - Simple.C = SimpleStatus; - return Simple; -}(events_1.EventEmitter)); -exports.Simple = Simple; - - -/***/ }) -/******/ ]); -}); \ No newline at end of file diff --git a/dist/sip-0.15.5.min.js b/dist/sip-0.15.5.min.js deleted file mode 100644 index 8f48d4f07..000000000 --- a/dist/sip-0.15.5.min.js +++ /dev/null @@ -1 +0,0 @@ -!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.SIP=t():e.SIP=t()}(this,(function(){return function(e){var t={};function r(i){if(t[i])return t[i].exports;var n=t[i]={i:i,l:!1,exports:{}};return e[i].call(n.exports,n,n.exports,r),n.l=!0,n.exports}return r.m=e,r.c=t,r.d=function(e,t,i){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:i})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var i=Object.create(null);if(r.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var n in e)r.d(i,n,function(t){return e[t]}.bind(null,n));return i},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=109)}([function(e,t,r){"use strict";r.r(t),r.d(t,"__extends",(function(){return n})),r.d(t,"__assign",(function(){return s})),r.d(t,"__rest",(function(){return o})),r.d(t,"__decorate",(function(){return a})),r.d(t,"__param",(function(){return c})),r.d(t,"__metadata",(function(){return u})),r.d(t,"__awaiter",(function(){return d})),r.d(t,"__generator",(function(){return p})),r.d(t,"__exportStar",(function(){return h})),r.d(t,"__values",(function(){return l})),r.d(t,"__read",(function(){return g})),r.d(t,"__spread",(function(){return f})),r.d(t,"__spreadArrays",(function(){return m})),r.d(t,"__await",(function(){return v})),r.d(t,"__asyncGenerator",(function(){return S})),r.d(t,"__asyncDelegator",(function(){return T})),r.d(t,"__asyncValues",(function(){return y})),r.d(t,"__makeTemplateObject",(function(){return E})),r.d(t,"__importStar",(function(){return b})),r.d(t,"__importDefault",(function(){return C}));var i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};function n(e,t){function r(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var s=function(){return(s=Object.assign||function(e){for(var t,r=1,i=arguments.length;r=0;a--)(n=e[a])&&(o=(s<3?n(o):s>3?n(t,r,o):n(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o}function c(e,t){return function(r,i){t(r,i,e)}}function u(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function d(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){e.done?n(e.value):new r((function(t){t(e.value)})).then(o,a)}c((i=i.apply(e,t||[])).next())}))}function p(e,t){var r,i,n,s,o={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;o;)try{if(r=1,i&&(n=2&s[0]?i.return:s[0]?i.throw||((n=i.return)&&n.call(i),0):i.next)&&!(n=n.call(i,s[1])).done)return n;switch(i=0,n&&(s=[2&s[0],n.value]),s[0]){case 0:case 1:n=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,i=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!(n=(n=o.trys).length>0&&n[n.length-1])&&(6===s[0]||2===s[0])){o=0;continue}if(3===s[0]&&(!n||s[1]>n[0]&&s[1]=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}function g(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var i,n,s=r.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(i=s.next()).done;)o.push(i.value)}catch(e){n={error:e}}finally{try{i&&!i.done&&(r=s.return)&&r.call(s)}finally{if(n)throw n.error}}return o}function f(){for(var e=[],t=0;t1||a(e,t)}))})}function a(e,t){try{(r=n[e](t)).value instanceof v?Promise.resolve(r.value.v).then(c,u):d(s[0][2],r)}catch(e){d(s[0][3],e)}var r}function c(e){a("next",e)}function u(e){a("throw",e)}function d(e,t){e(t),s.shift(),s.length&&a(s[0][0],s[0][1])}}function T(e){var t,r;return t={},i("next"),i("throw",(function(e){throw e})),i("return"),t[Symbol.iterator]=function(){return this},t;function i(i,n){t[i]=e[i]?function(t){return(r=!r)?{value:v(e[i](t)),done:"return"===i}:n?n(t):t}:n}}function y(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=l(e),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(r){t[r]=e[r]&&function(t){return new Promise((function(i,n){(function(e,t,r,i){Promise.resolve(i).then((function(t){e({value:t,done:r})}),t)})(i,n,(t=e[r](t)).done,t.value)}))}}}function E(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}function b(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function C(e){return e&&e.__esModule?e:{default:e}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0);i.__exportStar(r(22),t),i.__exportStar(r(35),t),i.__exportStar(r(67),t),i.__exportStar(r(68),t),i.__exportStar(r(69),t),i.__exportStar(r(35),t),i.__exportStar(r(25),t),i.__exportStar(r(13),t),i.__exportStar(r(23),t)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0);i.__exportStar(r(55),t),i.__exportStar(r(57),t),i.__exportStar(r(59),t),i.__exportStar(r(29),t),i.__exportStar(r(19),t),i.__exportStar(r(32),t),i.__exportStar(r(33),t),i.__exportStar(r(20),t),i.__exportStar(r(34),t),i.__exportStar(r(62),t),i.__exportStar(r(21),t),i.__exportStar(r(30),t)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(2),n=r(1),s=function(){function e(e,t,r,i){this.transactionConstructor=e,this.core=t,this.message=r,this.delegate=i,this.challenged=!1,this.stale=!1,this.logger=this.loggerFactory.getLogger("sip.user-agent-client"),this.init()}return e.prototype.dispose=function(){this.transaction.dispose()},Object.defineProperty(e.prototype,"loggerFactory",{get:function(){return this.core.loggerFactory},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"transaction",{get:function(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction},enumerable:!0,configurable:!0}),e.prototype.cancel=function(t,r){var s=this;if(void 0===r&&(r={}),!this.transaction)throw new Error("Transaction undefined.");if(!this.message.to)throw new Error("To undefined.");if(!this.message.from)throw new Error("From undefined.");var o=this.core.makeOutgoingRequestMessage(i.C.CANCEL,this.message.ruri,this.message.from.uri,this.message.to.uri,{toTag:this.message.toTag,fromTag:this.message.fromTag,callId:this.message.callId,cseq:this.message.cseq},r.extraHeaders);if(o.branch=this.message.branch,this.message.headers.Route&&(o.headers.Route=this.message.headers.Route),t&&o.setHeader("Reason",t),this.transaction.state===n.TransactionState.Proceeding)new e(n.NonInviteClientTransaction,this.core,o);else this.transaction.once("stateChanged",(function(){if(s.transaction&&s.transaction.state===n.TransactionState.Proceeding)new e(n.NonInviteClientTransaction,s.core,o)}));return o},e.prototype.authenticationGuard=function(e){var t,r,i=e.statusCode;if(!i)throw new Error("Response status code undefined.");if(401!==i&&407!==i)return!0;if(401===i?(t=e.parseHeader("www-authenticate"),r="authorization"):(t=e.parseHeader("proxy-authenticate"),r="proxy-authorization"),!t)return this.logger.warn(i+" with wrong or missing challenge, cannot authenticate"),!0;if(this.challenged&&(this.stale||!0!==t.stale))return this.logger.warn(i+" apparently in authentication loop, cannot authenticate"),!0;if(!this.credentials&&(this.credentials=this.core.configuration.authenticationFactory(),!this.credentials))return this.logger.warn("Unable to obtain credentials, cannot authenticate"),!0;if(!this.credentials.authenticate(this.message,t))return!0;this.challenged=!0,t.stale&&(this.stale=!0);var n=this.message.cseq+=1;return this.message.setHeader("cseq",n+" "+this.message.method),this.message.setHeader(r,this.credentials.toString()),this.init(),!1},e.prototype.receiveResponse=function(e){if(this.authenticationGuard(e)){var t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e});break;case/^1[0-9]{2}$/.test(t):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e});break;case/^2[0-9]{2}$/.test(t):this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e});break;case/^3[0-9]{2}$/.test(t):this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e});break;case/^[4-6][0-9]{2}$/.test(t):this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e});break;default:throw new Error("Invalid status code "+t)}}},e.prototype.init=function(){var e=this,t={loggerFactory:this.loggerFactory,onRequestTimeout:function(){return e.onRequestTimeout()},onStateChange:function(t){t===n.TransactionState.Terminated&&(e.core.userAgentClients.delete(i),r===e._transaction&&e.dispose())},onTransportError:function(t){return e.onTransportError(t)},receiveResponse:function(t){return e.receiveResponse(t)}},r=new this.transactionConstructor(this.message,this.core.transport,t);this._transaction=r;var i=r.id+r.request.method;this.core.userAgentClients.set(i,this)},e.prototype.onRequestTimeout=function(){this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout.");var e=new i.IncomingResponseMessage;e.statusCode=408,e.reasonPhrase="Request Timeout",this.receiveResponse(e)},e.prototype.onTransportError=function(e){this.logger.error(e.message),this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable.");var t=new i.IncomingResponseMessage;t.statusCode=503,t.reasonPhrase="Service Unavailable",this.receiveResponse(t)},e}();t.UserAgentClient=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(16),n=r(2),s=r(10),o=r(1),a=function(){function e(e,t,r,i){this.transactionConstructor=e,this.core=t,this.message=r,this.delegate=i,this.logger=this.loggerFactory.getLogger("sip.user-agent-server"),this.toTag=r.toTag?r.toTag:s.newTag(),this.init()}return e.prototype.dispose=function(){this.transaction.dispose()},Object.defineProperty(e.prototype,"loggerFactory",{get:function(){return this.core.loggerFactory},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"transaction",{get:function(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction},enumerable:!0,configurable:!0}),e.prototype.accept=function(e){if(void 0===e&&(e={statusCode:200}),!this.acceptable)throw new i.TransactionStateError(this.message.method+" not acceptable in state "+this.transaction.state+".");var t=e.statusCode;if(t<200||t>299)throw new TypeError("Invalid statusCode: "+t);return this.reply(e)},e.prototype.progress=function(e){if(void 0===e&&(e={statusCode:180}),!this.progressable)throw new i.TransactionStateError(this.message.method+" not progressable in state "+this.transaction.state+".");var t=e.statusCode;if(t<101||t>199)throw new TypeError("Invalid statusCode: "+t);return this.reply(e)},e.prototype.redirect=function(e,t){if(void 0===t&&(t={statusCode:302}),!this.redirectable)throw new i.TransactionStateError(this.message.method+" not redirectable in state "+this.transaction.state+".");var r=t.statusCode;if(r<300||r>399)throw new TypeError("Invalid statusCode: "+r);var n=new Array;return e.forEach((function(e){return n.push("Contact: "+e.toString())})),t.extraHeaders=(t.extraHeaders||[]).concat(n),this.reply(t)},e.prototype.reject=function(e){if(void 0===e&&(e={statusCode:480}),!this.rejectable)throw new i.TransactionStateError(this.message.method+" not rejectable in state "+this.transaction.state+".");var t=e.statusCode;if(t<400||t>699)throw new TypeError("Invalid statusCode: "+t);return this.reply(e)},e.prototype.trying=function(e){if(!this.tryingable)throw new i.TransactionStateError(this.message.method+" not tryingable in state "+this.transaction.state+".");return this.reply({statusCode:100})},e.prototype.receiveCancel=function(e){this.delegate&&this.delegate.onCancel&&this.delegate.onCancel(e)},Object.defineProperty(e.prototype,"acceptable",{get:function(){if(this.transaction instanceof o.InviteServerTransaction)return this.transaction.state===o.TransactionState.Proceeding||this.transaction.state===o.TransactionState.Accepted;if(this.transaction instanceof o.NonInviteServerTransaction)return this.transaction.state===o.TransactionState.Trying||this.transaction.state===o.TransactionState.Proceeding;throw new Error("Unknown transaction type.")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"progressable",{get:function(){if(this.transaction instanceof o.InviteServerTransaction)return this.transaction.state===o.TransactionState.Proceeding;if(this.transaction instanceof o.NonInviteServerTransaction)return!1;throw new Error("Unknown transaction type.")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"redirectable",{get:function(){if(this.transaction instanceof o.InviteServerTransaction)return this.transaction.state===o.TransactionState.Proceeding;if(this.transaction instanceof o.NonInviteServerTransaction)return this.transaction.state===o.TransactionState.Trying||this.transaction.state===o.TransactionState.Proceeding;throw new Error("Unknown transaction type.")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rejectable",{get:function(){if(this.transaction instanceof o.InviteServerTransaction)return this.transaction.state===o.TransactionState.Proceeding;if(this.transaction instanceof o.NonInviteServerTransaction)return this.transaction.state===o.TransactionState.Trying||this.transaction.state===o.TransactionState.Proceeding;throw new Error("Unknown transaction type.")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"tryingable",{get:function(){if(this.transaction instanceof o.InviteServerTransaction)return this.transaction.state===o.TransactionState.Proceeding;if(this.transaction instanceof o.NonInviteServerTransaction)return this.transaction.state===o.TransactionState.Trying;throw new Error("Unknown transaction type.")},enumerable:!0,configurable:!0}),e.prototype.reply=function(e){e.toTag||100===e.statusCode||(e.toTag=this.toTag),e.userAgent=e.userAgent||this.core.configuration.userAgentHeaderFieldValue,e.supported=e.supported||this.core.configuration.supportedOptionTagsResponse;var t=n.constructOutgoingResponse(this.message,e);return this.transaction.receiveResponse(e.statusCode,t.message),t},e.prototype.init=function(){var e=this,t={loggerFactory:this.loggerFactory,onStateChange:function(t){t===o.TransactionState.Terminated&&(e.core.userAgentServers.delete(i),e.dispose())},onTransportError:function(t){e.logger.error(t.message),e.delegate&&e.delegate.onTransportError?e.delegate.onTransportError(t):e.logger.error("User agent server response transport error.")}},r=new this.transactionConstructor(this.message,this.core.transport,t);this._transaction=r;var i=r.id;this.core.userAgentServers.set(r.id,this)},e}();t.UserAgentServer=a},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0);i.__exportStar(r(17),t),i.__exportStar(r(16),t),i.__exportStar(r(71),t),i.__exportStar(r(2),t),i.__exportStar(r(15),t),i.__exportStar(r(27),t),i.__exportStar(r(1),t),i.__exportStar(r(73),t),i.__exportStar(r(50),t),i.__exportStar(r(6),t),i.__exportStar(r(86),t)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=500;t.Timers={T1:i,T2:4e3,T4:5e3,TIMER_B:32e3,TIMER_D:0,TIMER_F:32e3,TIMER_H:32e3,TIMER_I:0,TIMER_J:0,TIMER_K:0,TIMER_L:32e3,TIMER_M:32e3,TIMER_N:32e3,PROVISIONAL_RESPONSE_INTERVAL:6e4}},function(e,t,r){"use strict";var i,n="object"==typeof Reflect?Reflect:null,s=n&&"function"==typeof n.apply?n.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};i=n&&"function"==typeof n.ownKeys?n.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var o=Number.isNaN||function(e){return e!=e};function a(){a.init.call(this)}e.exports=a,a.EventEmitter=a,a.prototype._events=void 0,a.prototype._eventsCount=0,a.prototype._maxListeners=void 0;var c=10;function u(e){return void 0===e._maxListeners?a.defaultMaxListeners:e._maxListeners}function d(e,t,r,i){var n,s,o,a;if("function"!=typeof r)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof r);if(void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),s=e._events),o=s[t]),void 0===o)o=s[t]=r,++e._eventsCount;else if("function"==typeof o?o=s[t]=i?[r,o]:[o,r]:i?o.unshift(r):o.push(r),(n=u(e))>0&&o.length>n&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=o.length,a=c,console&&console.warn&&console.warn(a)}return e}function p(){for(var e=[],t=0;t0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=n[e];if(void 0===c)return!1;if("function"==typeof c)s(c,this,t);else{var u=c.length,d=f(c,u);for(r=0;r=0;s--)if(r[s]===t||r[s].listener===t){o=r[s].listener,n=s;break}if(n<0)return this;0===n?r.shift():function(e,t){for(;t+1=0;i--)this.removeListener(e,t[i]);return this},a.prototype.listeners=function(e){return l(this,e,!0)},a.prototype.rawListeners=function(e){return l(this,e,!1)},a.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):g.call(e,t)},a.prototype.listenerCount=g,a.prototype.eventNames=function(){return this._eventsCount>0?i(this._events):[]}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e){e[e.STATUS_EARLY=1]="STATUS_EARLY",e[e.STATUS_CONFIRMED=2]="STATUS_CONFIRMED"}(t.DialogStatus||(t.DialogStatus={})),function(e){e[e.STATUS_NULL=0]="STATUS_NULL",e[e.STATUS_INVITE_SENT=1]="STATUS_INVITE_SENT",e[e.STATUS_1XX_RECEIVED=2]="STATUS_1XX_RECEIVED",e[e.STATUS_INVITE_RECEIVED=3]="STATUS_INVITE_RECEIVED",e[e.STATUS_WAITING_FOR_ANSWER=4]="STATUS_WAITING_FOR_ANSWER",e[e.STATUS_ANSWERED=5]="STATUS_ANSWERED",e[e.STATUS_WAITING_FOR_PRACK=6]="STATUS_WAITING_FOR_PRACK",e[e.STATUS_WAITING_FOR_ACK=7]="STATUS_WAITING_FOR_ACK",e[e.STATUS_CANCELED=8]="STATUS_CANCELED",e[e.STATUS_TERMINATED=9]="STATUS_TERMINATED",e[e.STATUS_ANSWERED_WAITING_FOR_PRACK=10]="STATUS_ANSWERED_WAITING_FOR_PRACK",e[e.STATUS_EARLY_MEDIA=11]="STATUS_EARLY_MEDIA",e[e.STATUS_CONFIRMED=12]="STATUS_CONFIRMED"}(t.SessionStatus||(t.SessionStatus={})),function(e){e[e.ClientContext=0]="ClientContext",e[e.ConfigurationError=1]="ConfigurationError",e[e.Dialog=2]="Dialog",e[e.DigestAuthentication=3]="DigestAuthentication",e[e.DTMF=4]="DTMF",e[e.IncomingMessage=5]="IncomingMessage",e[e.IncomingRequest=6]="IncomingRequest",e[e.IncomingResponse=7]="IncomingResponse",e[e.InvalidStateError=8]="InvalidStateError",e[e.InviteClientContext=9]="InviteClientContext",e[e.InviteServerContext=10]="InviteServerContext",e[e.Logger=11]="Logger",e[e.LoggerFactory=12]="LoggerFactory",e[e.MethodParameterError=13]="MethodParameterError",e[e.NameAddrHeader=14]="NameAddrHeader",e[e.NotSupportedError=15]="NotSupportedError",e[e.OutgoingRequest=16]="OutgoingRequest",e[e.Parameters=17]="Parameters",e[e.PublishContext=18]="PublishContext",e[e.ReferClientContext=19]="ReferClientContext",e[e.ReferServerContext=20]="ReferServerContext",e[e.RegisterContext=21]="RegisterContext",e[e.RenegotiationError=22]="RenegotiationError",e[e.RequestSender=23]="RequestSender",e[e.ServerContext=24]="ServerContext",e[e.Session=25]="Session",e[e.SessionDescriptionHandler=26]="SessionDescriptionHandler",e[e.SessionDescriptionHandlerError=27]="SessionDescriptionHandlerError",e[e.SessionDescriptionHandlerObserver=28]="SessionDescriptionHandlerObserver",e[e.Subscription=29]="Subscription",e[e.Transport=30]="Transport",e[e.UA=31]="UA",e[e.URI=32]="URI"}(t.TypeStrings||(t.TypeStrings={})),function(e){e[e.STATUS_INIT=0]="STATUS_INIT",e[e.STATUS_STARTING=1]="STATUS_STARTING",e[e.STATUS_READY=2]="STATUS_READY",e[e.STATUS_USER_CLOSED=3]="STATUS_USER_CLOSED",e[e.STATUS_NOT_READY=4]="STATUS_NOT_READY"}(t.UAStatus||(t.UAStatus={}))},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(11),n=r(29),s=r(30);!function(e){e.defer=function(){var e={};return e.promise=new Promise((function(t,r){e.resolve=t,e.reject=r})),e},e.reducePromises=function(e,t){return e.reduce((function(e,t){return e=e.then(t)}),Promise.resolve(t))},e.str_utf8_length=function(e){return encodeURIComponent(e).replace(/%[A-F\d]{2}/g,"U").length},e.generateFakeSDP=function(e){if(e){var t=e.indexOf("o="),r=e.indexOf("\r\n",t);return"v=0\r\n"+e.slice(t,r)+"\r\ns=-\r\nt=0 0\r\nc=IN IP4 0.0.0.0"}},e.isDecimal=function(e){var t=parseInt(e,10);return!isNaN(t)&&parseFloat(e)===t},e.createRandomToken=function(e,t){void 0===t&&(t=32);for(var r="",i=0;i699)throw new TypeError("Invalid statusCode: "+t);if(t)return e.getReasonHeaderValue(t,r)},e.buildStatusLine=function(t,r){if(!t||t<100||t>699)throw new TypeError("Invalid statusCode: "+t);if(r&&"string"!=typeof r&&!(r instanceof String))throw new TypeError("Invalid reason: "+r);return"SIP/2.0 "+t+" "+(r=e.getReasonPhrase(t,r))+"\r\n"},e.fromBodyObj=function(e){var t=e.body,r=e.contentType;return{contentDisposition:function(e){return"application/sdp"===e?"session":"render"}(r),contentType:r,content:t}},e.toBodyObj=function(e){return{body:e.content,contentType:e.contentType}}}(t.Utils||(t.Utils={}))},function(e,t,r){"use strict";function i(e,t){void 0===t&&(t=32);for(var r="",i=0;i=this.headers[e].length)){var r=this.headers[e][t],s=r.raw;if(r.parsed)return r.parsed;var o=i.Grammar.parse(s,e.replace(/-/g,"_"));return-1===o?void this.headers[e].splice(t,1):(r.parsed=o,o)}},e.prototype.s=function(e,t){return void 0===t&&(t=0),this.parseHeader(e,t)},e.prototype.setHeader=function(e,t){this.headers[n.headerize(e)]=[{raw:t}]},e.prototype.toString=function(){return this.data},e}();t.IncomingMessage=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=function(e){function t(t,r,i){var n=e.call(this,i)||this;return n.uri=t,n._displayName=r,n}return i.__extends(t,e),Object.defineProperty(t.prototype,"friendlyName",{get:function(){return this.displayName||this.uri.aor},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"displayName",{get:function(){return this._displayName},set:function(e){this._displayName=e},enumerable:!0,configurable:!0}),t.prototype.clone=function(){return new t(this.uri.clone(),this._displayName,JSON.parse(JSON.stringify(this.parameters)))},t.prototype.toString=function(){var e=this.displayName||"0"===this.displayName?'"'+this.displayName+'" ':"";for(var t in e+="<"+this.uri.toString()+">",this.parameters)this.parameters.hasOwnProperty(t)&&(e+=";"+t,null!==this.parameters[t]&&(e+="="+this.parameters[t]));return e},t}(r(21).Parameters);t.NameAddrHeader=n},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e){for(var t in this.parameters={},e)e.hasOwnProperty(t)&&this.setParam(t,e[t])}return e.prototype.setParam=function(e,t){e&&(this.parameters[e.toLowerCase()]=null==t?null:t.toString())},e.prototype.getParam=function(e){if(e)return this.parameters[e.toLowerCase()]},e.prototype.hasParam=function(e){return!!e&&!!this.parameters.hasOwnProperty(e.toLowerCase())},e.prototype.deleteParam=function(e){if(e=e.toLowerCase(),this.parameters.hasOwnProperty(e)){var t=this.parameters[e];return delete this.parameters[e],t}},e.prototype.clearParams=function(){this.parameters={}},e}();t.Parameters=i},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=function(e){function t(r,i,n,s,o){var a=e.call(this,i,n,t.makeId(r),s,o)||this;a._request=r,a.user=n;var c=i.server&&i.server.scheme?i.server.scheme:void 0;return r.setViaHeader(a.id,c),a}return i.__extends(t,e),t.makeId=function(e){if("CANCEL"===e.method){if(!e.branch)throw new Error("Outgoing CANCEL request without a branch.");return e.branch}return"z9hG4bK"+Math.floor(1e7*Math.random())},Object.defineProperty(t.prototype,"request",{get:function(){return this._request},enumerable:!0,configurable:!0}),t.prototype.onRequestTimeout=function(){this.user.onRequestTimeout&&this.user.onRequestTimeout()},t}(r(23).Transaction);t.ClientTransaction=n},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(7),s=r(16),o=function(e){function t(t,r,i,n,s){var o=e.call(this)||this;return o._transport=t,o._user=r,o._id=i,o._state=n,o.logger=r.loggerFactory.getLogger(s,i),o.logger.debug("Constructing "+o.typeToString()+" with id "+o.id+"."),o}return i.__extends(t,e),t.prototype.dispose=function(){this.logger.debug("Destroyed "+this.typeToString()+" with id "+this.id+".")},Object.defineProperty(t.prototype,"id",{get:function(){return this._id},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"kind",{get:function(){throw new Error("Invalid kind.")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"state",{get:function(){return this._state},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"transport",{get:function(){return this._transport},enumerable:!0,configurable:!0}),t.prototype.on=function(t,r){return e.prototype.on.call(this,t,r)},t.prototype.logTransportError=function(e,t){this.logger.error(e.message),this.logger.error("Transport error occurred in "+this.typeToString()+" with id "+this.id+"."),this.logger.error(t)},t.prototype.send=function(e){var t=this;return this.transport.send(e).catch((function(e){var r;if(!(e instanceof s.TransportError))throw r=e&&"string"==typeof e.message?new s.TransportError(e.message):new s.TransportError,t.onTransportError(r),r;t.onTransportError(e)}))},t.prototype.setState=function(e){this.logger.debug('State change to "'+e+'" on '+this.typeToString()+" with id "+this.id+"."),this._state=e,this._user.onStateChange&&this._user.onStateChange(e),this.emit("stateChanged")},t.prototype.typeToString=function(){return"UnknownType"},t}(n.EventEmitter);t.Transaction=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=function(e){function t(t){var r=this.constructor,i=e.call(this,t)||this;return Object.setPrototypeOf(i,r.prototype),i}return i.__extends(t,e),t}(Error);t.Exception=n},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=function(e){function t(t,r,i,n,s){var o=e.call(this,r,i,t.viaBranch,n,s)||this;return o._request=t,o.user=i,o}return i.__extends(t,e),Object.defineProperty(t.prototype,"request",{get:function(){return this._request},enumerable:!0,configurable:!0}),t}(r(23).Transaction);t.ServerTransaction=n},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){var s=void 0!==t.userAgentCore?t.userAgentCore:t;return e.call(this,n.NonInviteServerTransaction,s,r,i)||this}return i.__extends(t,e),t}(r(4).UserAgentServer);t.NotifyUserAgentServer=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),r(0).__exportStar(r(70),t)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e){e[e.error=0]="error",e[e.warn=1]="warn",e[e.log=2]="log",e[e.debug=3]="debug"}(t.Levels||(t.Levels={}))},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0).__importStar(r(58));!function(e){e.parse=function(e,t){var r={startRule:t};try{i.parse(e,r)}catch(e){r.data=-1}return r.data},e.nameAddrHeaderParse=function(t){var r=e.parse(t,"Name_Addr_Header");return-1!==r?r:void 0},e.URIParse=function(t){var r=e.parse(t,"SIP_URI");return-1!==r?r:void 0}}(t.Grammar||(t.Grammar={}))},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=function(e){function t(t,r,i,n,s,o){var a=e.call(this,s)||this;if(a.headers={},!i)throw new TypeError('missing or invalid "host" parameter');for(var c in t=t||"sip",o)o.hasOwnProperty(c)&&a.setHeader(c,o[c]);return a.raw={scheme:t,user:r,host:i,port:n},a.normal={scheme:t.toLowerCase(),user:r,host:i.toLowerCase(),port:n},a}return i.__extends(t,e),Object.defineProperty(t.prototype,"scheme",{get:function(){return this.normal.scheme},set:function(e){this.raw.scheme=e,this.normal.scheme=e.toLowerCase()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"user",{get:function(){return this.normal.user},set:function(e){this.normal.user=this.raw.user=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"host",{get:function(){return this.normal.host},set:function(e){this.raw.host=e,this.normal.host=e.toLowerCase()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"aor",{get:function(){return this.normal.user+"@"+this.normal.host},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"port",{get:function(){return this.normal.port},set:function(e){this.normal.port=this.raw.port=e},enumerable:!0,configurable:!0}),t.prototype.setHeader=function(e,t){this.headers[this.headerize(e)]=t instanceof Array?t:[t]},t.prototype.getHeader=function(e){if(e)return this.headers[this.headerize(e)]},t.prototype.hasHeader=function(e){return!!e&&!!this.headers.hasOwnProperty(this.headerize(e))},t.prototype.deleteHeader=function(e){if(e=this.headerize(e),this.headers.hasOwnProperty(e)){var t=this.headers[e];return delete this.headers[e],t}},t.prototype.clearHeaders=function(){this.headers={}},t.prototype.clone=function(){return new t(this._raw.scheme,this._raw.user||"",this._raw.host,this._raw.port,JSON.parse(JSON.stringify(this.parameters)),JSON.parse(JSON.stringify(this.headers)))},t.prototype.toRaw=function(){return this._toString(this._raw)},t.prototype.toString=function(){return this._toString(this._normal)},Object.defineProperty(t.prototype,"_normal",{get:function(){return this.normal},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"_raw",{get:function(){return this.raw},enumerable:!0,configurable:!0}),t.prototype._toString=function(e){var t=e.scheme+":";for(var r in e.scheme.toLowerCase().match("^sips?$")||(t+="//"),e.user&&(t+=this.escapeUser(e.user)+"@"),t+=e.host,(e.port||0===e.port)&&(t+=":"+e.port),this.parameters)this.parameters.hasOwnProperty(r)&&(t+=";"+r,null!==this.parameters[r]&&(t+="="+this.parameters[r]));var i=[];for(var n in this.headers)if(this.headers.hasOwnProperty(n))for(var s in this.headers[n])this.headers[n].hasOwnProperty(s)&&i.push(n+"="+this.headers[n][s]);return i.length>0&&(t+="?"+i.join("&")),t},t.prototype.escapeUser=function(e){var t;try{t=decodeURIComponent(e)}catch(e){throw e}return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%2B/gi,"+").replace(/%3F/gi,"?").replace(/%2F/gi,"/")},t.prototype.headerize=function(e){for(var t={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},r=e.toLowerCase().replace(/_/g,"-").split("-"),i=r.length,n="",s=0;s699)throw new Error("Invalid status code "+r);switch(this.state){case o.TransactionState.Calling:if(r>=100&&r<=199)return this.stateTransition(o.TransactionState.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(r>=200&&r<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(o.TransactionState.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(r>=300&&r<=699)return this.stateTransition(o.TransactionState.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case o.TransactionState.Proceeding:if(r>=100&&r<=199)return void(this.user.receiveResponse&&this.user.receiveResponse(e));if(r>=200&&r<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(o.TransactionState.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(r>=300&&r<=699)return this.stateTransition(o.TransactionState.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case o.TransactionState.Accepted:if(r>=200&&r<=299){if(!this.ackRetransmissionCache.has(e.toTag))return this.ackRetransmissionCache.set(e.toTag,void 0),void(this.user.receiveResponse&&this.user.receiveResponse(e));var i=this.ackRetransmissionCache.get(e.toTag);return i?void this.send(i.toString()).catch((function(e){t.logTransportError(e,"Failed to send retransmission of ACK to 2xx response.")})):void 0}break;case o.TransactionState.Completed:if(r>=300&&r<=699)return void this.ack(e);break;case o.TransactionState.Terminated:break;default:throw new Error("Invalid state "+this.state)}var n="Received unexpected "+r+" response while in state "+this.state+".";this.logger.warn(n)},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(o.TransactionState.Terminated,!0)},t.prototype.typeToString=function(){return"INVITE client transaction"},t.prototype.ack=function(e){var t=this,r=this.request.ruri,i=this.request.callId,n=this.request.cseq,s=this.request.getHeader("from"),o=e.getHeader("to"),a=this.request.getHeader("via"),c=this.request.getHeader("route");if(!s)throw new Error("From undefined.");if(!o)throw new Error("To undefined.");if(!a)throw new Error("Via undefined.");var u="ACK "+r+" SIP/2.0\r\n";c&&(u+="Route: "+c+"\r\n"),u+="Via: "+a+"\r\n",u+="To: "+o+"\r\n",u+="From: "+s+"\r\n",u+="Call-ID: "+i+"\r\n",u+="CSeq: "+n+" ACK\r\n",u+="Max-Forwards: 70\r\n",u+="Content-Length: 0\r\n\r\n",this.send(u).catch((function(e){t.logTransportError(e,"Failed to send ACK to non-2xx response.")}))},t.prototype.stateTransition=function(e,t){var r=this;void 0===t&&(t=!1);var i=function(){throw new Error("Invalid state transition from "+r.state+" to "+e)};switch(e){case o.TransactionState.Calling:i();break;case o.TransactionState.Proceeding:this.state!==o.TransactionState.Calling&&i();break;case o.TransactionState.Accepted:case o.TransactionState.Completed:this.state!==o.TransactionState.Calling&&this.state!==o.TransactionState.Proceeding&&i();break;case o.TransactionState.Terminated:this.state!==o.TransactionState.Calling&&this.state!==o.TransactionState.Accepted&&this.state!==o.TransactionState.Completed&&(t||i());break;default:i()}this.B&&(clearTimeout(this.B),this.B=void 0),o.TransactionState.Proceeding,e===o.TransactionState.Completed&&(this.D=setTimeout((function(){return r.timer_D()}),n.Timers.TIMER_D)),e===o.TransactionState.Accepted&&(this.M=setTimeout((function(){return r.timer_M()}),n.Timers.TIMER_M)),e===o.TransactionState.Terminated&&this.dispose(),this.setState(e)},t.prototype.timer_A=function(){},t.prototype.timer_B=function(){this.logger.debug("Timer B expired for INVITE client transaction "+this.id+"."),this.state===o.TransactionState.Calling&&(this.onRequestTimeout(),this.stateTransition(o.TransactionState.Terminated))},t.prototype.timer_D=function(){this.logger.debug("Timer D expired for INVITE client transaction "+this.id+"."),this.state===o.TransactionState.Completed&&this.stateTransition(o.TransactionState.Terminated)},t.prototype.timer_M=function(){this.logger.debug("Timer M expired for INVITE client transaction "+this.id+"."),this.state===o.TransactionState.Accepted&&this.stateTransition(o.TransactionState.Terminated)},t}(s.ClientTransaction);t.InviteClientTransaction=a},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(2),s=r(1),o=function(e){function t(t,r,i){var o,a=t.createOutgoingRequestMessage(n.C.BYE,i);return o=e.call(this,s.NonInviteClientTransaction,t.userAgentCore,a,r)||this,t.dispose(),o}return i.__extends(t,e),t}(r(3).UserAgentClient);t.ByeUserAgentClient=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){return e.call(this,n.NonInviteServerTransaction,t.userAgentCore,r,i)||this}return i.__extends(t,e),t}(r(4).UserAgentServer);t.ByeUserAgentServer=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(2),s=r(1),o=function(e){function t(t,r,i){var o=t.createOutgoingRequestMessage(n.C.INFO,i);return e.call(this,s.NonInviteClientTransaction,t.userAgentCore,o,r)||this}return i.__extends(t,e),t}(r(3).UserAgentClient);t.InfoUserAgentClient=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){return e.call(this,n.NonInviteServerTransaction,t.userAgentCore,r,i)||this}return i.__extends(t,e),t}(r(4).UserAgentServer);t.InfoUserAgentServer=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(2),s=r(1),o=function(e){function t(t,r,i){var o=t.createOutgoingRequestMessage(n.C.NOTIFY,i);return e.call(this,s.NonInviteClientTransaction,t.userAgentCore,o,r)||this}return i.__extends(t,e),t}(r(3).UserAgentClient);t.NotifyUserAgentClient=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(2),s=r(1),o=function(e){function t(t,r,i){var o,a=t.createOutgoingRequestMessage(n.C.PRACK,i);return o=e.call(this,s.NonInviteClientTransaction,t.userAgentCore,a,r)||this,t.signalingStateTransition(a),o}return i.__extends(t,e),t}(r(3).UserAgentClient);t.PrackUserAgentClient=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){var s=e.call(this,n.NonInviteServerTransaction,t.userAgentCore,r,i)||this;return t.signalingStateTransition(r),s.dialog=t,s}return i.__extends(t,e),t.prototype.accept=function(t){return void 0===t&&(t={statusCode:200}),t.body&&this.dialog.signalingStateTransition(t.body),e.prototype.accept.call(this,t)},t}(r(4).UserAgentServer);t.PrackUserAgentServer=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(2),s=r(1),o=function(e){function t(t,r,i){var o=this,a=t.createOutgoingRequestMessage(n.C.INVITE,i);return(o=e.call(this,s.InviteClientTransaction,t.userAgentCore,a,r)||this).delegate=r,t.signalingStateTransition(a),t.reinviteUserAgentClient=o,o.dialog=t,o}return i.__extends(t,e),t.prototype.receiveResponse=function(e){var t=this,r=e.statusCode?e.statusCode.toString():"";if(!r)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(r):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e});break;case/^1[0-9]{2}$/.test(r):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:this.dialog,prack:function(e){throw new Error("Unimplemented.")}});break;case/^2[0-9]{2}$/.test(r):this.dialog.signalingStateTransition(e),this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e,session:this.dialog,ack:function(e){return t.dialog.ack(e)}});break;case/^3[0-9]{2}$/.test(r):this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentClient=void 0,this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e});break;case/^[4-6][0-9]{2}$/.test(r):this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentClient=void 0,this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e});break;default:throw new Error("Invalid status code "+r)}},t}(r(3).UserAgentClient);t.ReInviteUserAgentClient=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){var s=e.call(this,n.InviteServerTransaction,t.userAgentCore,r,i)||this;return t.reinviteUserAgentServer=s,s.dialog=t,s}return i.__extends(t,e),t.prototype.accept=function(t){void 0===t&&(t={statusCode:200}),t.extraHeaders=t.extraHeaders||[],t.extraHeaders=t.extraHeaders.concat(this.dialog.routeSet.map((function(e){return"Record-Route: "+e})));var r=e.prototype.accept.call(this,t),n=this.dialog,s=i.__assign({},r,{session:n});return t.body&&this.dialog.signalingStateTransition(t.body),this.dialog.reConfirm(),s},t.prototype.progress=function(t){void 0===t&&(t={statusCode:180});var r=e.prototype.progress.call(this,t),n=this.dialog,s=i.__assign({},r,{session:n});return t.body&&this.dialog.signalingStateTransition(t.body),s},t.prototype.redirect=function(e,t){throw void 0===t&&(t={statusCode:302}),this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,new Error("Unimplemented.")},t.prototype.reject=function(t){return void 0===t&&(t={statusCode:488}),this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,e.prototype.reject.call(this,t)},t}(r(4).UserAgentServer);t.ReInviteUserAgentServer=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(2),s=r(1),o=function(e){function t(t,r,i){var o=t.createOutgoingRequestMessage(n.C.REFER,i);return e.call(this,s.NonInviteClientTransaction,t.userAgentCore,o,r)||this}return i.__extends(t,e),t}(r(3).UserAgentClient);t.ReferUserAgentClient=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){var s=void 0!==t.userAgentCore?t.userAgentCore:t;return e.call(this,n.NonInviteServerTransaction,s,r,i)||this}return i.__extends(t,e),t}(r(4).UserAgentServer);t.ReferUserAgentServer=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(2),s=r(27),o=r(6),a=r(14),c=r(26),u=r(48),d=function(e){function t(t,r,i,n,s,o){var a=e.call(this,n,s)||this;return a.delegate=o,a._autoRefresh=!1,a._subscriptionEvent=t,a._subscriptionExpires=r,a._subscriptionExpiresInitial=r,a._subscriptionExpiresLastSet=Math.floor(Date.now()/1e3),a._subscriptionRefresh=void 0,a._subscriptionRefreshLastSet=void 0,a._subscriptionState=i,a.logger=n.loggerFactory.getLogger("sip.subscribe-dialog"),a.logger.log("SUBSCRIBE dialog "+a.id+" constructed"),a}return i.__extends(t,e),t.initialDialogStateForSubscription=function(e,t){var r=t.getHeaders("record-route"),i=t.parseHeader("contact");if(!i)throw new Error("Contact undefined.");if(!(i instanceof n.NameAddrHeader))throw new Error("Contact not instance of NameAddrHeader.");var s=i.uri,o=e.cseq,a=e.callId,c=e.fromTag,u=t.fromTag;if(!a)throw new Error("Call id undefined.");if(!c)throw new Error("From tag undefined.");if(!u)throw new Error("To tag undefined.");if(!e.from)throw new Error("From undefined.");if(!e.to)throw new Error("To undefined.");return{id:a+c+u,early:!1,callId:a,localTag:c,remoteTag:u,localSequenceNumber:o,remoteSequenceNumber:void 0,localURI:e.from.uri,remoteURI:e.to.uri,remoteTarget:s,routeSet:r,secure:!1}},t.prototype.dispose=function(){e.prototype.dispose.call(this),this.N&&(clearTimeout(this.N),this.N=void 0),this.refreshTimerClear(),this.logger.log("SUBSCRIBE dialog "+this.id+" destroyed")},Object.defineProperty(t.prototype,"autoRefresh",{get:function(){return this._autoRefresh},set:function(e){this._autoRefresh=!0,this.refreshTimerSet()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionEvent",{get:function(){return this._subscriptionEvent},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionExpires",{get:function(){var e=Math.floor(Date.now()/1e3)-this._subscriptionExpiresLastSet,t=this._subscriptionExpires-e;return Math.max(t,0)},set:function(e){if(e<0)throw new Error("Expires must be greater than or equal to zero.");if(this._subscriptionExpires=e,this._subscriptionExpiresLastSet=Math.floor(Date.now()/1e3),this.autoRefresh){var t=this.subscriptionRefresh;(void 0===t||t>=e)&&this.refreshTimerSet()}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionExpiresInitial",{get:function(){return this._subscriptionExpiresInitial},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionRefresh",{get:function(){if(void 0!==this._subscriptionRefresh&&void 0!==this._subscriptionRefreshLastSet){var e=Math.floor(Date.now()/1e3)-this._subscriptionRefreshLastSet,t=this._subscriptionRefresh-e;return Math.max(t,0)}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionState",{get:function(){return this._subscriptionState},enumerable:!0,configurable:!0}),t.prototype.receiveRequest=function(t){if(this.logger.log("SUBSCRIBE dialog "+this.id+" received "+t.method+" request"),this.sequenceGuard(t))switch(e.prototype.receiveRequest.call(this,t),t.method){case n.C.NOTIFY:this.onNotify(t);break;default:this.logger.log("SUBSCRIBE dialog "+this.id+" received unimplemented "+t.method+" request"),this.core.replyStateless(t,{statusCode:501})}else this.logger.log("SUBSCRIBE dialog "+this.id+" rejected out of order "+t.method+" request.")},t.prototype.refresh=function(){var e="Allow: "+a.AllowedMethods.toString(),t={};return t.extraHeaders=(t.extraHeaders||[]).slice(),t.extraHeaders.push(e),t.extraHeaders.push("Event: "+this.subscriptionEvent),t.extraHeaders.push("Expires: "+this.subscriptionExpiresInitial),t.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,t)},t.prototype.subscribe=function(e,t){var r=this;if(void 0===t&&(t={}),this.subscriptionState!==s.SubscriptionState.Pending&&this.subscriptionState!==s.SubscriptionState.Active)throw new Error("Invalid state "+this.subscriptionState+'. May only re-subscribe while in state "pending" or "active".');this.logger.log("SUBSCRIBE dialog "+this.id+" sending SUBSCRIBE request");var i=new u.ReSubscribeUserAgentClient(this,e,t);return this.N=setTimeout((function(){return r.timer_N()}),o.Timers.TIMER_N),i},t.prototype.terminate=function(){this.stateTransition(s.SubscriptionState.Terminated),this.onTerminated()},t.prototype.unsubscribe=function(){var e="Allow: "+a.AllowedMethods.toString(),t={};return t.extraHeaders=(t.extraHeaders||[]).slice(),t.extraHeaders.push(e),t.extraHeaders.push("Event: "+this.subscriptionEvent),t.extraHeaders.push("Expires: 0"),t.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,t)},t.prototype.onNotify=function(e){var t=e.parseHeader("Event").event;if(t&&t===this.subscriptionEvent){this.N&&(clearTimeout(this.N),this.N=void 0);var r=e.parseHeader("Subscription-State");if(r&&r.state){var i=r.state,n=r.expires?Math.max(r.expires,0):void 0;switch(i){case"pending":this.stateTransition(s.SubscriptionState.Pending,n);break;case"active":this.stateTransition(s.SubscriptionState.Active,n);break;case"terminated":this.stateTransition(s.SubscriptionState.Terminated,n);break;default:this.logger.warn("Unrecognized subscription state.")}var o=new c.NotifyUserAgentServer(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(o):o.accept()}else this.core.replyStateless(e,{statusCode:489})}else this.core.replyStateless(e,{statusCode:489})},t.prototype.onRefresh=function(e){this.delegate&&this.delegate.onRefresh&&this.delegate.onRefresh(e)},t.prototype.onTerminated=function(){this.delegate&&this.delegate.onTerminated&&this.delegate.onTerminated()},t.prototype.refreshTimerClear=function(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=void 0)},t.prototype.refreshTimerSet=function(){var e=this;if(this.refreshTimerClear(),this.autoRefresh&&this.subscriptionExpires>0){var t=900*this.subscriptionExpires;this._subscriptionRefresh=Math.floor(t/1e3),this._subscriptionRefreshLastSet=Math.floor(Date.now()/1e3),this.refreshTimer=setTimeout((function(){e.refreshTimer=void 0,e._subscriptionRefresh=void 0,e._subscriptionRefreshLastSet=void 0,e.onRefresh(e.refresh())}),t)}},t.prototype.stateTransition=function(e,t){var r=this,i=function(){r.logger.warn("Invalid subscription state transition from "+r.subscriptionState+" to "+e)};switch(e){case s.SubscriptionState.Initial:case s.SubscriptionState.NotifyWait:return void i();case s.SubscriptionState.Pending:if(this.subscriptionState!==s.SubscriptionState.NotifyWait&&this.subscriptionState!==s.SubscriptionState.Pending)return void i();break;case s.SubscriptionState.Active:case s.SubscriptionState.Terminated:if(this.subscriptionState!==s.SubscriptionState.NotifyWait&&this.subscriptionState!==s.SubscriptionState.Pending&&this.subscriptionState!==s.SubscriptionState.Active)return void i();break;default:return void i()}e===s.SubscriptionState.Pending&&t&&(this.subscriptionExpires=t),e===s.SubscriptionState.Active&&t&&(this.subscriptionExpires=t),e===s.SubscriptionState.Terminated&&this.dispose(),this._subscriptionState=e},t.prototype.timer_N=function(){this.subscriptionState!==s.SubscriptionState.Terminated&&(this.stateTransition(s.SubscriptionState.Terminated),this.onTerminated())},t}(r(18).Dialog);t.SubscriptionDialog=d},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(2),s=r(1),o=function(e){function t(t,r,i){var o=this,a=t.createOutgoingRequestMessage(n.C.SUBSCRIBE,i);return(o=e.call(this,s.NonInviteClientTransaction,t.userAgentCore,a,r)||this).dialog=t,o}return i.__extends(t,e),t.prototype.waitNotifyStop=function(){},t.prototype.receiveResponse=function(t){if(t.statusCode&&t.statusCode>=200&&t.statusCode<300){var r=t.getHeader("Expires");if(r){var i=Number(r);this.dialog.subscriptionExpires>i&&(this.dialog.subscriptionExpires=i)}else this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE")}if(t.statusCode&&t.statusCode>=400&&t.statusCode<700){[404,405,410,416,480,481,482,483,484,485,489,501,604].includes(t.statusCode)&&this.dialog.terminate()}e.prototype.receiveResponse.call(this,t)},t}(r(3).UserAgentClient);t.ReSubscribeUserAgentClient=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(28),n=function(){function e(e,t,r){this.logger=e,this.category=t,this.label=r}return e.prototype.error=function(e){this.genericLog(i.Levels.error,e)},e.prototype.warn=function(e){this.genericLog(i.Levels.warn,e)},e.prototype.log=function(e){this.genericLog(i.Levels.log,e)},e.prototype.debug=function(e){this.genericLog(i.Levels.debug,e)},e.prototype.genericLog=function(e,t){this.logger.genericLog(e,this.category,this.label,t)},e}();t.Logger=n},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0);i.__exportStar(r(36),t),i.__exportStar(r(37),t),i.__exportStar(r(75),t),i.__exportStar(r(38),t),i.__exportStar(r(39),t),i.__exportStar(r(76),t),i.__exportStar(r(77),t),i.__exportStar(r(78),t),i.__exportStar(r(79),t),i.__exportStar(r(40),t),i.__exportStar(r(26),t),i.__exportStar(r(80),t),i.__exportStar(r(41),t),i.__exportStar(r(42),t),i.__exportStar(r(43),t),i.__exportStar(r(44),t),i.__exportStar(r(48),t),i.__exportStar(r(81),t),i.__exportStar(r(45),t),i.__exportStar(r(46),t),i.__exportStar(r(82),t),i.__exportStar(r(83),t),i.__exportStar(r(84),t),i.__exportStar(r(85),t),i.__exportStar(r(3),t),i.__exportStar(r(4),t)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(7),s=r(11),o=r(5),a=r(8),c=r(9),u=function(e){function t(r,i,n,s){var o=e.call(this)||this;return o.data={},t.initializer(o,r,i,n,s),o}return i.__extends(t,e),t.initializer=function(e,t,r,i,n){if(e.type=a.TypeStrings.ClientContext,void 0===i)throw new TypeError("Not enough arguments");e.ua=t,e.logger=t.getLogger("sip.clientcontext"),e.method=r;var s=t.normalizeTarget(i);if(!s)throw new TypeError("Invalid target: "+i);var u=t.userAgentCore.configuration.aor;if(n&&n.params&&n.params.fromUri&&!(u="string"==typeof n.params.fromUri?o.Grammar.URIParse(n.params.fromUri):n.params.fromUri))throw new TypeError("Invalid from URI: "+n.params.fromUri);var d=s;if(n&&n.params&&n.params.toUri&&!(d="string"==typeof n.params.toUri?o.Grammar.URIParse(n.params.toUri):n.params.toUri))throw new TypeError("Invalid to URI: "+n.params.toUri);var p,h,l=((n=(n=Object.create(n||Object.prototype))||{}).extraHeaders||[]).slice(),g=n.params||{};n.body&&(p={body:n.body,contentType:n.contentType?n.contentType:"application/sdp"},e.body=p),p&&(h=c.Utils.fromBodyObj(p)),e.request=t.userAgentCore.makeOutgoingRequestMessage(r,s,u,d,g,l,h),e.request.from&&(e.localIdentity=e.request.from),e.request.to&&(e.remoteIdentity=e.request.to)},t.prototype.send=function(){var e=this;return this.ua.userAgentCore.request(this.request,{onAccept:function(t){return e.receiveResponse(t.message)},onProgress:function(t){return e.receiveResponse(t.message)},onRedirect:function(t){return e.receiveResponse(t.message)},onReject:function(t){return e.receiveResponse(t.message)},onTrying:function(t){return e.receiveResponse(t.message)}}),this},t.prototype.receiveResponse=function(e){var t=e.statusCode||0,r=c.Utils.getReasonPhrase(t);switch(!0){case/^1[0-9]{2}$/.test(t.toString()):this.emit("progress",e,r);break;case/^2[0-9]{2}$/.test(t.toString()):this.ua.applicants[this.toString()]&&delete this.ua.applicants[this.toString()],this.emit("accepted",e,r);break;default:this.ua.applicants[this.toString()]&&delete this.ua.applicants[this.toString()],this.emit("rejected",e,r),this.emit("failed",e,r)}},t.prototype.onRequestTimeout=function(){this.emit("failed",void 0,s.C.causes.REQUEST_TIMEOUT)},t.prototype.onTransportError=function(){this.emit("failed",void 0,s.C.causes.CONNECTION_ERROR)},t}(n.EventEmitter);t.ClientContext=u},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(7),s=r(11),o=r(5),a=r(14),c=r(8),u=r(12),d=r(9),p=r(53),h=r(92),l=r(54),g=r(93),f=r(31),m=function(e){function t(t,r){void 0===r&&(r={});var i=e.call(this)||this;return i.type=c.TypeStrings.Session,i.method=s.C.INVITE,i.localHold=!1,i.status=c.SessionStatus.STATUS_NULL,i.isFailed=!1,i.rel100=s.C.supported.UNSUPPORTED,i.expiresTimer=void 0,i.userNoAnswerTimer=void 0,i._state=f.SessionState.Initial,i._stateEventEmitter=new n.EventEmitter,i.pendingReinvite=!1,i.tones=void 0,i.userAgent=t,i.delegate=r.delegate,i.logger=t.getLogger("sip.session"),i.errorListener=i.onTransportError.bind(i),t.transport&&t.transport.on("transportError",i.errorListener),i}return i.__extends(t,e),t.prototype.on=function(t,r){return e.prototype.on.call(this,t,r)},t.prototype.emit=function(t){for(var r=[],i=1;i0){for(t=1,r=1;t",T(">",!1),"\\",T("\\",!1),"[",T("[",!1),"]",T("]",!1),"{",T("{",!1),"}",T("}",!1),function(){return"*"},function(){return"/"},function(){return"="},function(){return"("},function(){return")"},function(){return">"},function(){return"<"},function(){return","},function(){return";"},function(){return":"},function(){return'"'},/^[!-']/,y([["!","'"]],!1,!1),/^[*-[]/,y([["*","["]],!1,!1),/^[\]-~]/,y([["]","~"]],!1,!1),function(e){return e},/^[#-[]/,y([["#","["]],!1,!1),/^[\0-\t]/,y([["\0","\t"]],!1,!1),/^[\x0B-\f]/,y([["\v","\f"]],!1,!1),/^[\x0E-\x7F]/,y([["\x0e","\x7f"]],!1,!1),function(){(t=t||{data:{}}).data.uri=new s.URI(t.data.scheme,t.data.user,t.data.host,t.data.port),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port},function(){(t=t||{data:{}}).data.uri=new s.URI(t.data.scheme,t.data.user,t.data.host,t.data.port,t.data.uri_params,t.data.uri_headers),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port,delete t.data.uri_params,"SIP_URI"===t.startRule&&(t.data=t.data.uri)},"sips",T("sips",!0),"sip",T("sip",!0),function(e){(t=t||{data:{}}).data.scheme=e},function(){(t=t||{data:{}}).data.user=decodeURIComponent(v().slice(0,-1))},function(){(t=t||{data:{}}).data.password=v()},function(){return(t=t||{data:{}}).data.host=v(),t.data.host},function(){return(t=t||{data:{}}).data.host_type="domain",v()},/^[a-zA-Z0-9_\-]/,y([["a","z"],["A","Z"],["0","9"],"_","-"],!1,!1),/^[a-zA-Z0-9\-]/,y([["a","z"],["A","Z"],["0","9"],"-"],!1,!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",v()},"::",T("::",!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",v()},function(){return(t=t||{data:{}}).data.host_type="IPv4",v()},"25",T("25",!1),/^[0-5]/,y([["0","5"]],!1,!1),"2",T("2",!1),/^[0-4]/,y([["0","4"]],!1,!1),"1",T("1",!1),/^[1-9]/,y([["1","9"]],!1,!1),function(e){return t=t||{data:{}},e=parseInt(e.join("")),t.data.port=e,e},"transport=",T("transport=",!0),"udp",T("udp",!0),"tcp",T("tcp",!0),"sctp",T("sctp",!0),"tls",T("tls",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.transport=e.toLowerCase()},"user=",T("user=",!0),"phone",T("phone",!0),"ip",T("ip",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.user=e.toLowerCase()},"method=",T("method=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.method=e},"ttl=",T("ttl=",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.ttl=e},"maddr=",T("maddr=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.maddr=e},"lr",T("lr",!0),function(){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.lr=void 0},function(e,r){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),r=null===r?void 0:r[1],t.data.uri_params[e.toLowerCase()]=r},function(e,r){e=e.join("").toLowerCase(),r=r.join(""),(t=t||{data:{}}).data.uri_headers||(t.data.uri_headers={}),t.data.uri_headers[e]?t.data.uri_headers[e].push(r):t.data.uri_headers[e]=[r]},function(){"Refer_To"===(t=t||{data:{}}).startRule&&(t.data.uri=new s.URI(t.data.scheme,t.data.user,t.data.host,t.data.port,t.data.uri_params,t.data.uri_headers),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port,delete t.data.uri_params)},"//",T("//",!1),function(){(t=t||{data:{}}).data.scheme=v()},T("SIP",!0),function(){(t=t||{data:{}}).data.sip_version=v()},"INVITE",T("INVITE",!1),"ACK",T("ACK",!1),"VXACH",T("VXACH",!1),"OPTIONS",T("OPTIONS",!1),"BYE",T("BYE",!1),"CANCEL",T("CANCEL",!1),"REGISTER",T("REGISTER",!1),"SUBSCRIBE",T("SUBSCRIBE",!1),"NOTIFY",T("NOTIFY",!1),"REFER",T("REFER",!1),"PUBLISH",T("PUBLISH",!1),function(){return(t=t||{data:{}}).data.method=v(),t.data.method},function(e){(t=t||{data:{}}).data.status_code=parseInt(e.join(""))},function(){(t=t||{data:{}}).data.reason_phrase=v()},function(){(t=t||{data:{}}).data=v()},function(){var e,r;for(r=(t=t||{data:{}}).data.multi_header.length,e=0;e""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),_(";).# &;,"),_('2F""6F7G.} &2H""6H7I.q &2J""6J7K.e &2L""6L7M.Y &2N""6N7O.M &2P""6P7Q.A &2R""6R7S.5 &2T""6T7U.) &2V""6V7W'),_('%%2X""6X7Y/5#;#/,$;#/#$+#)(#\'#("\'#&\'#/"!&,)'),_('%%$;$0#*;$&/,#; /#$+")("\'#&\'#." &"/=#$;$/�#*;$&&&#/\'$8":Z" )("\'#&\'#'),_(';.." &"'),_("%$;'.# &;(0)*;'.# &;(&/?#28\"\"6879/0$;//'$8#:[# )(#'#(\"'#&'#"),_('%%$;2/�#*;2&&&#/g#$%$;.0#*;.&/,#;2/#$+")("\'#&\'#0=*%$;.0#*;.&/,#;2/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),_('4\\""5!7].# &;3'),_('4^""5!7_'),_('4`""5!7a'),_(';!.) &4b""5!7c'),_('%$;).\x95 &2F""6F7G.\x89 &2J""6J7K.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O/\x9e#0\x9b*;).\x95 &2F""6F7G.\x89 &2J""6J7K.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O&&&#/"!&,)'),_('%$;).\x89 &2F""6F7G.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O/\x92#0\x8f*;).\x89 &2F""6F7G.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O&&&#/"!&,)'),_('2T""6T7U.\xe3 &2V""6V7W.\xd7 &2f""6f7g.\xcb &2h""6h7i.\xbf &2:""6:7;.\xb3 &2D""6D7E.\xa7 &22""6273.\x9b &28""6879.\x8f &2j""6j7k.\x83 &;&.} &24""6475.q &2l""6l7m.e &2n""6n7o.Y &26""6677.M &2>""6>7?.A &2p""6p7q.5 &2r""6r7s.) &;\'.# &;('),_('%$;).\u012b &2F""6F7G.\u011f &2J""6J7K.\u0113 &2L""6L7M.\u0107 &2X""6X7Y.\xfb &2P""6P7Q.\xef &2H""6H7I.\xe3 &2@""6@7A.\xd7 &2d""6d7e.\xcb &2R""6R7S.\xbf &2N""6N7O.\xb3 &2T""6T7U.\xa7 &2V""6V7W.\x9b &2f""6f7g.\x8f &2h""6h7i.\x83 &28""6879.w &2j""6j7k.k &;&.e &24""6475.Y &2l""6l7m.M &2n""6n7o.A &26""6677.5 &2p""6p7q.) &2r""6r7s/\u0134#0\u0131*;).\u012b &2F""6F7G.\u011f &2J""6J7K.\u0113 &2L""6L7M.\u0107 &2X""6X7Y.\xfb &2P""6P7Q.\xef &2H""6H7I.\xe3 &2@""6@7A.\xd7 &2d""6d7e.\xcb &2R""6R7S.\xbf &2N""6N7O.\xb3 &2T""6T7U.\xa7 &2V""6V7W.\x9b &2f""6f7g.\x8f &2h""6h7i.\x83 &28""6879.w &2j""6j7k.k &;&.e &24""6475.Y &2l""6l7m.M &2n""6n7o.A &26""6677.5 &2p""6p7q.) &2r""6r7s&&&#/"!&,)'),_("%;//?#2P\"\"6P7Q/0$;//'$8#:t# )(#'#(\"'#&'#"),_("%;//?#24\"\"6475/0$;//'$8#:u# )(#'#(\"'#&'#"),_("%;//?#2>\"\"6>7?/0$;//'$8#:v# )(#'#(\"'#&'#"),_("%;//?#2T\"\"6T7U/0$;//'$8#:w# )(#'#(\"'#&'#"),_("%;//?#2V\"\"6V7W/0$;//'$8#:x# )(#'#(\"'#&'#"),_('%2h""6h7i/0#;//\'$8":y" )("\'#&\'#'),_('%;//6#2f""6f7g/\'$8":z" )("\'#&\'#'),_("%;//?#2D\"\"6D7E/0$;//'$8#:{# )(#'#(\"'#&'#"),_("%;//?#22\"\"6273/0$;//'$8#:|# )(#'#(\"'#&'#"),_("%;//?#28\"\"6879/0$;//'$8#:}# )(#'#(\"'#&'#"),_("%;//0#;&/'$8\":~\" )(\"'#&'#"),_("%;&/0#;//'$8\":~\" )(\"'#&'#"),_("%;=/T#$;G.) &;K.# &;F0/*;G.) &;K.# &;F&/,$;>/#$+#)(#'#(\"'#&'#"),_('4\x7f""5!7\x80.A &4\x81""5!7\x82.5 &4\x83""5!7\x84.) &;3.# &;.'),_("%%;//Q#;&/H$$;J.# &;K0)*;J.# &;K&/,$;&/#$+$)($'#(#'#(\"'#&'#/\"!&,)"),_("%;//]#;&/T$%$;J.# &;K0)*;J.# &;K&/\"!&,)/1$;&/($8$:\x85$!!)($'#(#'#(\"'#&'#"),_(';..G &2L""6L7M.; &4\x86""5!7\x87./ &4\x83""5!7\x84.# &;3'),_('%2j""6j7k/J#4\x88""5!7\x89.5 &4\x8a""5!7\x8b.) &4\x8c""5!7\x8d/#$+")("\'#&\'#'),_("%;N/M#28\"\"6879/>$;O.\" &\"/0$;S/'$8$:\x8e$ )($'#(#'#(\"'#&'#"),_("%;N/d#28\"\"6879/U$;O.\" &\"/G$;S/>$;_/5$;l.\" &\"/'$8&:\x8f& )(&'#(%'#($'#(#'#(\"'#&'#"),_('%3\x90""5$7\x91.) &3\x92""5#7\x93/\' 8!:\x94!! )'),_('%;P/]#%28""6879/,#;R/#$+")("\'#&\'#." &"/6$2:""6:7;/\'$8#:\x95# )(#\'#("\'#&\'#'),_("$;+.) &;-.# &;Q/2#0/*;+.) &;-.# &;Q&&&#"),_('2<""6<7=.q &2>""6>7?.e &2@""6@7A.Y &2B""6B7C.M &2D""6D7E.A &22""6273.5 &26""6677.) &24""6475'),_('%$;+._ &;-.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E0e*;+._ &;-.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E&/& 8!:\x96! )'),_('%;T/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),_("%;U.) &;\\.# &;X/& 8!:\x97! )"),_('%$%;V/2#2J""6J7K/#$+")("\'#&\'#0<*%;V/2#2J""6J7K/#$+")("\'#&\'#&/D#;W/;$2J""6J7K." &"/\'$8#:\x98# )(#\'#("\'#&\'#'),_('$4\x99""5!7\x9a/,#0)*4\x99""5!7\x9a&&&#'),_('%4$""5!7%/?#$4\x9b""5!7\x9c0)*4\x9b""5!7\x9c&/#$+")("\'#&\'#'),_('%2l""6l7m/?#;Y/6$2n""6n7o/\'$8#:\x9d# )(#\'#("\'#&\'#'),_('%%;Z/\xb3#28""6879/\xa4$;Z/\x9b$28""6879/\x8c$;Z/\x83$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+-)(-\'#(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u0790 &%2\x9e""6\x9e7\x9f/\xa4#;Z/\x9b$28""6879/\x8c$;Z/\x83$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+,)(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u06f9 &%2\x9e""6\x9e7\x9f/\x8c#;Z/\x83$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u067a &%2\x9e""6\x9e7\x9f/t#;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u0613 &%2\x9e""6\x9e7\x9f/\\#;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+&)(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u05c4 &%2\x9e""6\x9e7\x9f/D#;Z/;$28""6879/,$;[/#$+$)($\'#(#\'#("\'#&\'#.\u058d &%2\x9e""6\x9e7\x9f/,#;[/#$+")("\'#&\'#.\u056e &%2\x9e""6\x9e7\x9f/,#;Z/#$+")("\'#&\'#.\u054f &%;Z/\x9b#2\x9e""6\x9e7\x9f/\x8c$;Z/\x83$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$++)(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u04c7 &%;Z/\xaa#%28""6879/,#;Z/#$+")("\'#&\'#." &"/\x83$2\x9e""6\x9e7\x9f/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u0430 &%;Z/\xb9#%28""6879/,#;Z/#$+")("\'#&\'#." &"/\x92$%28""6879/,#;Z/#$+")("\'#&\'#." &"/k$2\x9e""6\x9e7\x9f/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+))()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u038a &%;Z/\xc8#%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xa1$%28""6879/,#;Z/#$+")("\'#&\'#." &"/z$%28""6879/,#;Z/#$+")("\'#&\'#." &"/S$2\x9e""6\x9e7\x9f/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u02d5 &%;Z/\xd7#%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xb0$%28""6879/,#;Z/#$+")("\'#&\'#." &"/\x89$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2\x9e""6\x9e7\x9f/,$;[/#$+\')(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u0211 &%;Z/\xfe#%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xd7$%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xb0$%28""6879/,#;Z/#$+")("\'#&\'#." &"/\x89$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2\x9e""6\x9e7\x9f/,$;Z/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u0126 &%;Z/\u011c#%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xf5$%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xce$%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xa7$%28""6879/,#;Z/#$+")("\'#&\'#." &"/\x80$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Y$%28""6879/,#;Z/#$+")("\'#&\'#." &"/2$2\x9e""6\x9e7\x9f/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#/& 8!:\xa0! )'),_('%;#/M#;#." &"/?$;#." &"/1$;#." &"/#$+$)($\'#(#\'#("\'#&\'#'),_("%;Z/;#28\"\"6879/,$;Z/#$+#)(#'#(\"'#&'#.# &;\\"),_("%;]/o#2J\"\"6J7K/`$;]/W$2J\"\"6J7K/H$;]/?$2J\"\"6J7K/0$;]/'$8':\xa1' )(''#(&'#(%'#($'#(#'#(\"'#&'#"),_('%2\xa2""6\xa27\xa3/2#4\xa4""5!7\xa5/#$+")("\'#&\'#.\x98 &%2\xa6""6\xa67\xa7/;#4\xa8""5!7\xa9/,$;!/#$+#)(#\'#("\'#&\'#.j &%2\xaa""6\xaa7\xab/5#;!/,$;!/#$+#)(#\'#("\'#&\'#.B &%4\xac""5!7\xad/,#;!/#$+")("\'#&\'#.# &;!'),_('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:\xae!! )'),_('$%22""6273/,#;`/#$+")("\'#&\'#0<*%22""6273/,#;`/#$+")("\'#&\'#&'),_(";a.A &;b.; &;c.5 &;d./ &;e.) &;f.# &;g"),_('%3\xaf""5*7\xb0/a#3\xb1""5#7\xb2.G &3\xb3""5#7\xb4.; &3\xb5""5$7\xb6./ &3\xb7""5#7\xb8.# &;6/($8":\xb9"! )("\'#&\'#'),_('%3\xba""5%7\xbb/I#3\xbc""5%7\xbd./ &3\xbe""5"7\xbf.# &;6/($8":\xc0"! )("\'#&\'#'),_('%3\xc1""5\'7\xc2/1#;\x90/($8":\xc3"! )("\'#&\'#'),_('%3\xc4""5$7\xc5/1#;\xf0/($8":\xc6"! )("\'#&\'#'),_('%3\xc7""5&7\xc8/1#;T/($8":\xc9"! )("\'#&\'#'),_('%3\xca""5"7\xcb/N#%2>""6>7?/,#;6/#$+")("\'#&\'#." &"/\'$8":\xcc" )("\'#&\'#'),_('%;h/P#%2>""6>7?/,#;i/#$+")("\'#&\'#." &"/)$8":\xcd""! )("\'#&\'#'),_('%$;j/�#*;j&&&#/"!&,)'),_('%$;j/�#*;j&&&#/"!&,)'),_(";k.) &;+.# &;-"),_('2l""6l7m.e &2n""6n7o.Y &24""6475.M &28""6879.A &2<""6<7=.5 &2@""6@7A.) &2B""6B7C'),_('%26""6677/n#;m/e$$%2<""6<7=/,#;m/#$+")("\'#&\'#0<*%2<""6<7=/,#;m/#$+")("\'#&\'#&/#$+#)(#\'#("\'#&\'#'),_('%;n/A#2>""6>7?/2$;o/)$8#:\xce#"" )(#\'#("\'#&\'#'),_("$;p.) &;+.# &;-/2#0/*;p.) &;+.# &;-&&&#"),_("$;p.) &;+.# &;-0/*;p.) &;+.# &;-&"),_('2l""6l7m.e &2n""6n7o.Y &24""6475.M &26""6677.A &28""6879.5 &2@""6@7A.) &2B""6B7C'),_(";\x91.# &;r"),_("%;\x90/G#;'/>$;s/5$;'/,$;\x84/#$+%)(%'#($'#(#'#(\"'#&'#"),_(";M.# &;t"),_("%;\x7f/E#28\"\"6879/6$;u.# &;x/'$8#:\xcf# )(#'#(\"'#&'#"),_('%;v.# &;w/J#%26""6677/,#;\x83/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),_('%2\xd0""6\xd07\xd1/:#;\x80/1$;w." &"/#$+#)(#\'#("\'#&\'#'),_('%24""6475/,#;{/#$+")("\'#&\'#'),_("%;z/3#$;y0#*;y&/#$+\")(\"'#&'#"),_(";*.) &;+.# &;-"),_(';+.\x8f &;-.\x89 &22""6273.} &26""6677.q &28""6879.e &2:""6:7;.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),_('%;|/e#$%24""6475/,#;|/#$+")("\'#&\'#0<*%24""6475/,#;|/#$+")("\'#&\'#&/#$+")("\'#&\'#'),_('%$;~0#*;~&/e#$%22""6273/,#;}/#$+")("\'#&\'#0<*%22""6273/,#;}/#$+")("\'#&\'#&/#$+")("\'#&\'#'),_("$;~0#*;~&"),_(';+.w &;-.q &28""6879.e &2:""6:7;.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),_('%%;"/\x87#$;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K0M*;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K&/#$+")("\'#&\'#/& 8!:\xd2! )'),_(";\x81.# &;\x82"),_('%%;O/2#2:""6:7;/#$+")("\'#&\'#." &"/,#;S/#$+")("\'#&\'#." &"'),_('$;+.\x83 &;-.} &2B""6B7C.q &2D""6D7E.e &22""6273.Y &28""6879.M &2:""6:7;.A &2<""6<7=.5 &2>""6>7?.) &2@""6@7A/\x8c#0\x89*;+.\x83 &;-.} &2B""6B7C.q &2D""6D7E.e &22""6273.Y &28""6879.M &2:""6:7;.A &2<""6<7=.5 &2>""6>7?.) &2@""6@7A&&&#'),_("$;y0#*;y&"),_('%3\x92""5#7\xd3/q#24""6475/b$$;!/�#*;!&&&#/L$2J""6J7K/=$$;!/�#*;!&&&#/\'$8%:\xd4% )(%\'#($\'#(#\'#("\'#&\'#'),_('2\xd5""6\xd57\xd6'),_('2\xd7""6\xd77\xd8'),_('2\xd9""6\xd97\xda'),_('2\xdb""6\xdb7\xdc'),_('2\xdd""6\xdd7\xde'),_('2\xdf""6\xdf7\xe0'),_('2\xe1""6\xe17\xe2'),_('2\xe3""6\xe37\xe4'),_('2\xe5""6\xe57\xe6'),_('2\xe7""6\xe77\xe8'),_('2\xe9""6\xe97\xea'),_("%;\x85.Y &;\x86.S &;\x88.M &;\x89.G &;\x8a.A &;\x8b.; &;\x8c.5 &;\x8f./ &;\x8d.) &;\x8e.# &;6/& 8!:\xeb! )"),_("%;\x84/G#;'/>$;\x92/5$;'/,$;\x94/#$+%)(%'#($'#(#'#(\"'#&'#"),_("%;\x93/' 8!:\xec!! )"),_("%;!/5#;!/,$;!/#$+#)(#'#(\"'#&'#"),_("%$;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(0G*;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(&/& 8!:\xed! )"),_("%;\xb6/Y#$%;A/,#;\xb6/#$+\")(\"'#&'#06*%;A/,#;\xb6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),_('%;9/N#%2:""6:7;/,#;9/#$+")("\'#&\'#." &"/\'$8":\xee" )("\'#&\'#'),_("%;:.c &%;\x98/Y#$%;A/,#;\x98/#$+\")(\"'#&'#06*%;A/,#;\x98/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/& 8!:\xef! )"),_("%;L.# &;\x99/]#$%;B/,#;\x9b/#$+\")(\"'#&'#06*%;B/,#;\x9b/#$+\")(\"'#&'#&/'$8\":\xf0\" )(\"'#&'#"),_("%;\x9a.\" &\"/>#;@/5$;M/,$;?/#$+$)($'#(#'#(\"'#&'#"),_("%%;6/Y#$%;./,#;6/#$+\")(\"'#&'#06*%;./,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#.# &;H/' 8!:\xf1!! )"),_(";\x9c.) &;\x9d.# &;\xa0"),_("%3\xf2\"\"5!7\xf3/:#;$;\xcf/5$;./,$;\x90/#$+%)(%'#($'#(#'#(\"'#&'#"),_("%$;!/�#*;!&&&#/' 8!:\u014b!! )"),_("%;\xd1/]#$%;A/,#;\xd1/#$+\")(\"'#&'#06*%;A/,#;\xd1/#$+\")(\"'#&'#&/'$8\":\u014c\" )(\"'#&'#"),_("%;\x99/]#$%;B/,#;\xa0/#$+\")(\"'#&'#06*%;B/,#;\xa0/#$+\")(\"'#&'#&/'$8\":\u014d\" )(\"'#&'#"),_('%;L.O &;\x99.I &%;@." &"/:#;t/1$;?." &"/#$+#)(#\'#("\'#&\'#/]#$%;B/,#;\xa0/#$+")("\'#&\'#06*%;B/,#;\xa0/#$+")("\'#&\'#&/\'$8":\u014e" )("\'#&\'#'),_("%;\xd4/]#$%;B/,#;\xd5/#$+\")(\"'#&'#06*%;B/,#;\xd5/#$+\")(\"'#&'#&/'$8\":\u014f\" )(\"'#&'#"),_("%;\x96/& 8!:\u0150! )"),_('%3\u0151""5(7\u0152/:#;$;6/5$;;/,$;\xec/#$+%)(%'#($'#(#'#(\"'#&'#"),_('%3\x92""5#7\xd3.# &;6/\' 8!:\u018b!! )'),_('%3\xb1""5#7\u018c.G &3\xb3""5#7\u018d.; &3\xb7""5#7\u018e./ &3\xb5""5$7\u018f.# &;6/\' 8!:\u0190!! )'),_('%;\xee/D#%;C/,#;\xef/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),_("%;U.) &;\\.# &;X/& 8!:\u0191! )"),_('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:\u0192!! )'),_('%%;!/?#;!." &"/1$;!." &"/#$+#)(#\'#("\'#&\'#/\' 8!:\u0193!! )'),_(";\xbe"),_('%;\x9e/^#$%;B/,#;\xf3/#$+")("\'#&\'#06*%;B/,#;\xf3/#$+")("\'#&\'#&/($8":\u0194"!!)("\'#&\'#'),_(";\xf4.# &;\xa0"),_('%2\u0195""6\u01957\u0196/L#;""6>7?'),_('%;\u0100/b#28""6879/S$;\xfb/J$%2\u01a3""6\u01a37\u01a4/,#;\xec/#$+")("\'#&\'#." &"/#$+$)($\'#(#\'#("\'#&\'#'),_('%3\u01a5""5%7\u01a6.) &3\u01a7""5$7\u01a8/\' 8!:\u01a1!! )'),_('%3\xb1""5#7\xb2.6 &3\xb3""5#7\xb4.* &$;+0#*;+&/\' 8!:\u01a9!! )'),_("%;\u0104/\x87#2F\"\"6F7G/x$;\u0103/o$2F\"\"6F7G/`$;\u0103/W$2F\"\"6F7G/H$;\u0103/?$2F\"\"6F7G/0$;\u0105/'$8):\u01aa) )()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#"),_("%;#/>#;#/5$;#/,$;#/#$+$)($'#(#'#(\"'#&'#"),_("%;\u0103/,#;\u0103/#$+\")(\"'#&'#"),_("%;\u0103/5#;\u0103/,$;\u0103/#$+#)(#'#(\"'#&'#"),_("%;q/T#$;m0#*;m&/D$%; /,#;\xf8/#$+\")(\"'#&'#.\" &\"/#$+#)(#'#(\"'#&'#"),_('%2\u01ab""6\u01ab7\u01ac.) &2\u01ad""6\u01ad7\u01ae/w#;0/n$;\u0108/e$$%;B/2#;\u0109.# &;\xa0/#$+")("\'#&\'#0<*%;B/2#;\u0109.# &;\xa0/#$+")("\'#&\'#&/#$+$)($\'#(#\'#("\'#&\'#'),_(";\x99.# &;L"),_("%2\u01af\"\"6\u01af7\u01b0/5#;g&&(g=p,f=[]),f.push(e))}function R(e,t,r){return new o(o.buildMessage(e,t),e,t,r)}function _(e){return e.split("").map((function(e){return e.charCodeAt(0)-32}))}if(t.data={},(r=function t(r){for(var n,s=d[r],o=0,a=[],c=s.length,l=[],g=[];;){for(;op?(c=o+3+s[o+1],o+=3):(c=o+3+s[o+1]+s[o+2],o+=3+s[o+1]);break;case 18:l.push(c),a.push(o+4+s[o+2]+s[o+3]),e.substr(p,u[s[o+1]].length)===u[s[o+1]]?(c=o+4+s[o+2],o+=4):(c=o+4+s[o+2]+s[o+3],o+=4+s[o+2]);break;case 19:l.push(c),a.push(o+4+s[o+2]+s[o+3]),e.substr(p,u[s[o+1]].length).toLowerCase()===u[s[o+1]]?(c=o+4+s[o+2],o+=4):(c=o+4+s[o+2]+s[o+3],o+=4+s[o+2]);break;case 20:l.push(c),a.push(o+4+s[o+2]+s[o+3]),u[s[o+1]].test(e.charAt(p))?(c=o+4+s[o+2],o+=4):(c=o+4+s[o+2]+s[o+3],o+=4+s[o+2]);break;case 21:g.push(e.substr(p,s[o+1])),p+=s[o+1],o+=2;break;case 22:g.push(u[s[o+1]]),p+=u[s[o+1]].length,o+=2;break;case 23:g.push(i),0===m&&C(u[s[o+1]]),o+=2;break;case 24:h=g[g.length-1-s[o+1]],o+=2;break;case 25:h=p,o++;break;case 26:n=s.slice(o+4,o+4+s[o+3]).map((function(e){return g[g.length-1-e]})),g.splice(g.length-s[o+2],s[o+2],u[s[o+1]].apply(null,n)),o+=4+s[o+3];break;case 27:g.push(t(s[o+1])),o+=2;break;case 28:m++,o++;break;case 29:m--,o++;break;default:throw new Error("Invalid opcode: "+s[o]+".")}if(!(l.length>0))break;c=l.pop(),o=a.pop()}return g[0]}(c))!==i&&p===e.length)return r;throw r!==i&&p-1)this.qop="auth";else{if(!(t.qop.indexOf("auth-int")>-1))return this.logger.warn("challenge without Digest qop different than 'auth' or 'auth-int', authentication aborted"),!1;this.qop="auth-int"}else this.qop=void 0;return this.method=e.method,this.uri=e.ruri,this.cnonce=n.createRandomToken(12),this.nc+=1,this.updateNcHex(),4294967296===this.nc&&(this.nc=1,this.ncHex="00000001"),this.calculateResponse(r),!0},e.prototype.toString=function(){var e=[];if(!this.response)throw new Error("response field does not exist, cannot generate Authorization header");return e.push("algorithm="+this.algorithm),e.push('username="'+this.username+'"'),e.push('realm="'+this.realm+'"'),e.push('nonce="'+this.nonce+'"'),e.push('uri="'+this.uri+'"'),e.push('response="'+this.response+'"'),this.opaque&&e.push('opaque="'+this.opaque+'"'),this.qop&&(e.push("qop="+this.qop),e.push('cnonce="'+this.cnonce+'"'),e.push("nc="+this.ncHex)),"Digest "+e.join(", ")},e.prototype.updateNcHex=function(){var e=Number(this.nc).toString(16);this.ncHex="00000000".substr(0,8-e.length)+e},e.prototype.calculateResponse=function(e){var t,r=i.default(this.username+":"+this.realm+":"+this.password);"auth"===this.qop?(t=i.default(this.method+":"+this.uri),this.response=i.default(r+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth:"+t)):"auth-int"===this.qop?(t=i.default(this.method+":"+this.uri+":"+i.default(e||"")),this.response=i.default(r+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth-int:"+t)):void 0===this.qop&&(t=i.default(this.method+":"+this.uri),this.response=i.default(r+":"+this.nonce+":"+t))},e}();t.DigestAuthentication=s},function(e,t,r){var i;e.exports=(i=r(61),function(e){var t=i,r=t.lib,n=r.WordArray,s=r.Hasher,o=t.algo,a=[];!function(){for(var t=0;t<64;t++)a[t]=4294967296*e.abs(e.sin(t+1))|0}();var c=o.MD5=s.extend({_doReset:function(){this._hash=new n.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(e,t){for(var r=0;r<16;r++){var i=t+r,n=e[i];e[i]=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8)}var s=this._hash.words,o=e[t+0],c=e[t+1],l=e[t+2],g=e[t+3],f=e[t+4],m=e[t+5],v=e[t+6],S=e[t+7],T=e[t+8],y=e[t+9],E=e[t+10],b=e[t+11],C=e[t+12],R=e[t+13],_=e[t+14],w=e[t+15],A=s[0],I=s[1],O=s[2],N=s[3];A=u(A,I,O,N,o,7,a[0]),N=u(N,A,I,O,c,12,a[1]),O=u(O,N,A,I,l,17,a[2]),I=u(I,O,N,A,g,22,a[3]),A=u(A,I,O,N,f,7,a[4]),N=u(N,A,I,O,m,12,a[5]),O=u(O,N,A,I,v,17,a[6]),I=u(I,O,N,A,S,22,a[7]),A=u(A,I,O,N,T,7,a[8]),N=u(N,A,I,O,y,12,a[9]),O=u(O,N,A,I,E,17,a[10]),I=u(I,O,N,A,b,22,a[11]),A=u(A,I,O,N,C,7,a[12]),N=u(N,A,I,O,R,12,a[13]),O=u(O,N,A,I,_,17,a[14]),A=d(A,I=u(I,O,N,A,w,22,a[15]),O,N,c,5,a[16]),N=d(N,A,I,O,v,9,a[17]),O=d(O,N,A,I,b,14,a[18]),I=d(I,O,N,A,o,20,a[19]),A=d(A,I,O,N,m,5,a[20]),N=d(N,A,I,O,E,9,a[21]),O=d(O,N,A,I,w,14,a[22]),I=d(I,O,N,A,f,20,a[23]),A=d(A,I,O,N,y,5,a[24]),N=d(N,A,I,O,_,9,a[25]),O=d(O,N,A,I,g,14,a[26]),I=d(I,O,N,A,T,20,a[27]),A=d(A,I,O,N,R,5,a[28]),N=d(N,A,I,O,l,9,a[29]),O=d(O,N,A,I,S,14,a[30]),A=p(A,I=d(I,O,N,A,C,20,a[31]),O,N,m,4,a[32]),N=p(N,A,I,O,T,11,a[33]),O=p(O,N,A,I,b,16,a[34]),I=p(I,O,N,A,_,23,a[35]),A=p(A,I,O,N,c,4,a[36]),N=p(N,A,I,O,f,11,a[37]),O=p(O,N,A,I,S,16,a[38]),I=p(I,O,N,A,E,23,a[39]),A=p(A,I,O,N,R,4,a[40]),N=p(N,A,I,O,o,11,a[41]),O=p(O,N,A,I,g,16,a[42]),I=p(I,O,N,A,v,23,a[43]),A=p(A,I,O,N,y,4,a[44]),N=p(N,A,I,O,C,11,a[45]),O=p(O,N,A,I,w,16,a[46]),A=h(A,I=p(I,O,N,A,l,23,a[47]),O,N,o,6,a[48]),N=h(N,A,I,O,S,10,a[49]),O=h(O,N,A,I,_,15,a[50]),I=h(I,O,N,A,m,21,a[51]),A=h(A,I,O,N,C,6,a[52]),N=h(N,A,I,O,g,10,a[53]),O=h(O,N,A,I,E,15,a[54]),I=h(I,O,N,A,c,21,a[55]),A=h(A,I,O,N,T,6,a[56]),N=h(N,A,I,O,w,10,a[57]),O=h(O,N,A,I,v,15,a[58]),I=h(I,O,N,A,R,21,a[59]),A=h(A,I,O,N,f,6,a[60]),N=h(N,A,I,O,b,10,a[61]),O=h(O,N,A,I,l,15,a[62]),I=h(I,O,N,A,y,21,a[63]),s[0]=s[0]+A|0,s[1]=s[1]+I|0,s[2]=s[2]+O|0,s[3]=s[3]+N|0},_doFinalize:function(){var t=this._data,r=t.words,i=8*this._nDataBytes,n=8*t.sigBytes;r[n>>>5]|=128<<24-n%32;var s=e.floor(i/4294967296),o=i;r[15+(n+64>>>9<<4)]=16711935&(s<<8|s>>>24)|4278255360&(s<<24|s>>>8),r[14+(n+64>>>9<<4)]=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8),t.sigBytes=4*(r.length+1),this._process();for(var a=this._hash,c=a.words,u=0;u<4;u++){var d=c[u];c[u]=16711935&(d<<8|d>>>24)|4278255360&(d<<24|d>>>8)}return a},clone:function(){var e=s.clone.call(this);return e._hash=this._hash.clone(),e}});function u(e,t,r,i,n,s,o){var a=e+(t&r|~t&i)+n+o;return(a<>>32-s)+t}function d(e,t,r,i,n,s,o){var a=e+(t&i|r&~i)+n+o;return(a<>>32-s)+t}function p(e,t,r,i,n,s,o){var a=e+(t^r^i)+n+o;return(a<>>32-s)+t}function h(e,t,r,i,n,s,o){var a=e+(r^(t|~i))+n+o;return(a<>>32-s)+t}t.MD5=s._createHelper(c),t.HmacMD5=s._createHmacHelper(c)}(Math),i.MD5)},function(e,t,r){var i;e.exports=(i=i||function(e,t){var r=Object.create||function(){function e(){}return function(t){var r;return e.prototype=t,r=new e,e.prototype=null,r}}(),i={},n=i.lib={},s=n.Base={extend:function(e){var t=r(this);return e&&t.mixIn(e),t.hasOwnProperty("init")&&this.init!==t.init||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},o=n.WordArray=s.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||c).stringify(this)},concat:function(e){var t=this.words,r=e.words,i=this.sigBytes,n=e.sigBytes;if(this.clamp(),i%4)for(var s=0;s>>2]>>>24-s%4*8&255;t[i+s>>>2]|=o<<24-(i+s)%4*8}else for(s=0;s>>2]=r[s>>>2];return this.sigBytes+=n,this},clamp:function(){var t=this.words,r=this.sigBytes;t[r>>>2]&=4294967295<<32-r%4*8,t.length=e.ceil(r/4)},clone:function(){var e=s.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var r,i=[],n=function(t){t=t;var r=987654321,i=4294967295;return function(){var n=((r=36969*(65535&r)+(r>>16)&i)<<16)+(t=18e3*(65535&t)+(t>>16)&i)&i;return n/=4294967296,(n+=.5)*(e.random()>.5?1:-1)}},s=0;s>>2]>>>24-n%4*8&255;i.push((s>>>4).toString(16)),i.push((15&s).toString(16))}return i.join("")},parse:function(e){for(var t=e.length,r=[],i=0;i>>3]|=parseInt(e.substr(i,2),16)<<24-i%8*4;return new o.init(r,t/2)}},u=a.Latin1={stringify:function(e){for(var t=e.words,r=e.sigBytes,i=[],n=0;n>>2]>>>24-n%4*8&255;i.push(String.fromCharCode(s))}return i.join("")},parse:function(e){for(var t=e.length,r=[],i=0;i>>2]|=(255&e.charCodeAt(i))<<24-i%4*8;return new o.init(r,t)}},d=a.Utf8={stringify:function(e){try{return decodeURIComponent(escape(u.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return u.parse(unescape(encodeURIComponent(e)))}},p=n.BufferedBlockAlgorithm=s.extend({reset:function(){this._data=new o.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=d.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var r=this._data,i=r.words,n=r.sigBytes,s=this.blockSize,a=n/(4*s),c=(a=t?e.ceil(a):e.max((0|a)-this._minBufferSize,0))*s,u=e.min(4*c,n);if(c){for(var d=0;d699)throw new TypeError("Invalid statusCode: "+t.statusCode);var n=t.reasonPhrase?t.reasonPhrase:i.getReasonPhrase(t.statusCode),s="SIP/2.0 "+t.statusCode+" "+n+r;t.statusCode>=100&&t.statusCode,t.statusCode;var o="From: "+e.getHeader("From")+r,a="Call-ID: "+e.callId+r,c="CSeq: "+e.cseq+" "+e.method+r,u=e.getHeaders("via").reduce((function(e,t){return e+"Via: "+t+r}),""),d="To: "+e.getHeader("to");if(t.statusCode>100&&!e.parseHeader("to").hasParam("tag")){var p=t.toTag;p||(p=i.newTag()),d+=";tag="+p}d+=r;var h="";t.supported&&(h="Supported: "+t.supported.join(", ")+r);var l="";t.userAgent&&(l="User-Agent: "+t.userAgent+r);var g="";return t.extraHeaders&&(g=t.extraHeaders.reduce((function(e,t){return e+t.trim()+r}),"")),s+=u,s+=o,s+=d,s+=c,s+=a,s+=h,s+=l,s+=g,t.body?(s+="Content-Type: "+t.body.contentType+r,s+="Content-Length: "+i.str_utf8_length(t.body.content)+r+r,s+=t.body.content):s+="Content-Length: 0\r\n\r\n",{message:s}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(2),s=r(15),o=r(6),a=r(1),c=r(36),u=r(37),d=r(38),p=r(39),h=r(40),l=r(26),g=r(41),f=r(42),m=r(43),v=r(44),S=r(45),T=r(46),y=function(e){function t(t,r,i,n){var o=e.call(this,r,i)||this;return o.initialTransaction=t,o._signalingState=s.SignalingState.Initial,o.ackWait=!1,o.delegate=n,t instanceof a.InviteServerTransaction&&(o.ackWait=!0),o.early||o.start2xxRetransmissionTimer(),o.signalingStateTransition(t.request),o.logger=r.loggerFactory.getLogger("sip.invite-dialog"),o.logger.log("INVITE dialog "+o.id+" constructed"),o}return i.__extends(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this),this._signalingState=s.SignalingState.Closed,this._offer=void 0,this._answer=void 0,this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.logger.log("INVITE dialog "+this.id+" destroyed")},Object.defineProperty(t.prototype,"sessionState",{get:function(){return this.early?s.SessionState.Early:this.ackWait?s.SessionState.AckWait:this._signalingState===s.SignalingState.Closed?s.SessionState.Terminated:s.SessionState.Confirmed},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"signalingState",{get:function(){return this._signalingState},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"offer",{get:function(){return this._offer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"answer",{get:function(){return this._answer},enumerable:!0,configurable:!0}),t.prototype.confirm=function(){this.early&&this.start2xxRetransmissionTimer(),e.prototype.confirm.call(this)},t.prototype.reConfirm=function(){this.reinviteUserAgentServer&&this.startReInvite2xxRetransmissionTimer()},t.prototype.ack=function(e){var t;if(void 0===e&&(e={}),this.logger.log("INVITE dialog "+this.id+" sending ACK request"),this.reinviteUserAgentClient){if(!(this.reinviteUserAgentClient.transaction instanceof a.InviteClientTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");t=this.reinviteUserAgentClient.transaction,this.reinviteUserAgentClient=void 0}else{if(!(this.initialTransaction instanceof a.InviteClientTransaction))throw new Error("Initial transaction not instance of InviteClientTransaction.");t=this.initialTransaction}e.cseq=t.request.cseq;var r=this.createOutgoingRequestMessage(n.C.ACK,e);return t.ackResponse(r),this.signalingStateTransition(r),{message:r}},t.prototype.bye=function(e,t){if(this.logger.log("INVITE dialog "+this.id+" sending BYE request"),this.initialTransaction instanceof a.InviteServerTransaction){if(this.early)throw new Error("UAS MUST NOT send a BYE on early dialogs.");if(this.ackWait&&this.initialTransaction.state!==a.TransactionState.Terminated)throw new Error("UAS MUST NOT send a BYE on a confirmed dialog until it has received an ACK for its 2xx response or until the server transaction times out.")}return new c.ByeUserAgentClient(this,e,t)},t.prototype.info=function(e,t){if(this.logger.log("INVITE dialog "+this.id+" sending INFO request"),this.early)throw new Error("Dialog not confirmed.");return new d.InfoUserAgentClient(this,e,t)},t.prototype.invite=function(e,t){if(this.logger.log("INVITE dialog "+this.id+" sending INVITE request"),this.early)throw new Error("Dialog not confirmed.");if(this.reinviteUserAgentClient)throw new Error("There is an ongoing re-INVITE client transaction.");if(this.reinviteUserAgentServer)throw new Error("There is an ongoing re-INVITE server transaction.");return new m.ReInviteUserAgentClient(this,e,t)},t.prototype.notify=function(e,t){if(this.logger.log("INVITE dialog "+this.id+" sending NOTIFY request"),this.early)throw new Error("Dialog not confirmed.");return new h.NotifyUserAgentClient(this,e,t)},t.prototype.prack=function(e,t){return this.logger.log("INVITE dialog "+this.id+" sending PRACK request"),new g.PrackUserAgentClient(this,e,t)},t.prototype.refer=function(e,t){if(this.logger.log("INVITE dialog "+this.id+" sending REFER request"),this.early)throw new Error("Dialog not confirmed.");return new S.ReferUserAgentClient(this,e,t)},t.prototype.receiveRequest=function(t){if(this.logger.log("INVITE dialog "+this.id+" received "+t.method+" request"),t.method===n.C.ACK){if(this.ackWait){if(this.initialTransaction instanceof a.InviteClientTransaction)return void this.logger.warn("INVITE dialog "+this.id+" received unexpected "+t.method+" request, dropping.");if(this.initialTransaction.request.cseq!==t.cseq)return void this.logger.warn("INVITE dialog "+this.id+" received unexpected "+t.method+" request, dropping.");this.ackWait=!1}else{if(!this.reinviteUserAgentServer)return void this.logger.warn("INVITE dialog "+this.id+" received unexpected "+t.method+" request, dropping.");if(this.reinviteUserAgentServer.transaction.request.cseq!==t.cseq)return void this.logger.warn("INVITE dialog "+this.id+" received unexpected "+t.method+" request, dropping.");this.reinviteUserAgentServer=void 0}return this.signalingStateTransition(t),void(this.delegate&&this.delegate.onAck&&this.delegate.onAck({message:t}))}if(this.sequenceGuard(t)){if(t.method===n.C.INVITE){if(this.reinviteUserAgentServer){var r=["Retry-After: "+(Math.floor(10*Math.random())+1)];return void this.core.replyStateless(t,{statusCode:500,extraHeaders:r})}if(this.reinviteUserAgentClient)return void this.core.replyStateless(t,{statusCode:491})}if(e.prototype.receiveRequest.call(this,t),t.method===n.C.INVITE){var i=t.parseHeader("contact");if(!i)throw new Error("Contact undefined.");if(!(i instanceof n.NameAddrHeader))throw new Error("Contact not instance of NameAddrHeader.");this.dialogState.remoteTarget=i.uri}switch(t.method){case n.C.BYE:var s=new u.ByeUserAgentServer(this,t);this.delegate&&this.delegate.onBye?this.delegate.onBye(s):s.accept(),this.dispose();break;case n.C.INFO:s=new p.InfoUserAgentServer(this,t);this.delegate&&this.delegate.onInfo?this.delegate.onInfo(s):s.reject({statusCode:469,extraHeaders:["Recv-Info :"]});break;case n.C.INVITE:s=new v.ReInviteUserAgentServer(this,t);this.signalingStateTransition(t),this.delegate&&this.delegate.onInvite?this.delegate.onInvite(s):s.reject({statusCode:488});break;case n.C.NOTIFY:s=new l.NotifyUserAgentServer(this,t);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(s):s.accept();break;case n.C.PRACK:s=new f.PrackUserAgentServer(this,t);this.delegate&&this.delegate.onPrack?this.delegate.onPrack(s):s.accept();break;case n.C.REFER:s=new T.ReferUserAgentServer(this,t);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(s):s.reject();break;default:this.logger.log("INVITE dialog "+this.id+" received unimplemented "+t.method+" request"),this.core.replyStateless(t,{statusCode:501})}}else this.logger.log("INVITE dialog "+this.id+" rejected out of order "+t.method+" request.")},t.prototype.reliableSequenceGuard=function(e){var t=e.statusCode;if(!t)throw new Error("Status code undefined");if(t>100&&t<200){var r=e.getHeader("require"),i=e.getHeader("rseq"),n=r&&r.includes("100rel")&&i?Number(i):void 0;if(n){if(this.rseq&&this.rseq+1!==n)return!1;this.rseq||(this.rseq=n)}}return!0},t.prototype.signalingStateRollback=function(){this._signalingState!==s.SignalingState.HaveLocalOffer&&this.signalingState!==s.SignalingState.HaveRemoteOffer||this._rollbackOffer&&this._rollbackAnswer&&(this._signalingState=s.SignalingState.Stable,this._offer=this._rollbackOffer,this._answer=this._rollbackAnswer)},t.prototype.signalingStateTransition=function(e){var t=n.getBody(e);if(t&&"session"===t.contentDisposition){if(this._signalingState===s.SignalingState.Stable&&(this._rollbackOffer=this._offer,this._rollbackAnswer=this._answer),e instanceof n.IncomingRequestMessage)switch(this._signalingState){case s.SignalingState.Initial:case s.SignalingState.Stable:this._signalingState=s.SignalingState.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case s.SignalingState.HaveLocalOffer:this._signalingState=s.SignalingState.Stable,this._answer=t;break;case s.SignalingState.HaveRemoteOffer:case s.SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof n.IncomingResponseMessage)switch(this._signalingState){case s.SignalingState.Initial:case s.SignalingState.Stable:this._signalingState=s.SignalingState.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case s.SignalingState.HaveLocalOffer:this._signalingState=s.SignalingState.Stable,this._answer=t;break;case s.SignalingState.HaveRemoteOffer:case s.SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof n.OutgoingRequestMessage)switch(this._signalingState){case s.SignalingState.Initial:case s.SignalingState.Stable:this._signalingState=s.SignalingState.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case s.SignalingState.HaveLocalOffer:break;case s.SignalingState.HaveRemoteOffer:this._signalingState=s.SignalingState.Stable,this._answer=t;break;case s.SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}if(n.isBody(e))switch(this._signalingState){case s.SignalingState.Initial:case s.SignalingState.Stable:this._signalingState=s.SignalingState.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case s.SignalingState.HaveLocalOffer:break;case s.SignalingState.HaveRemoteOffer:this._signalingState=s.SignalingState.Stable,this._answer=t;break;case s.SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}}},t.prototype.start2xxRetransmissionTimer=function(){var e=this;if(this.initialTransaction instanceof a.InviteServerTransaction){var t=this.initialTransaction,r=o.Timers.T1,i=function(){e.ackWait?(e.logger.log("No ACK for 2xx response received, attempting retransmission"),t.retransmitAcceptedResponse(),r=Math.min(2*r,o.Timers.T2),e.invite2xxTimer=setTimeout(i,r)):e.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(i,r);var n=function(){t.state===a.TransactionState.Terminated&&(t.removeListener("stateChanged",n),e.invite2xxTimer&&(clearTimeout(e.invite2xxTimer),e.invite2xxTimer=void 0),e.ackWait&&(e.delegate&&e.delegate.onAckTimeout?e.delegate.onAckTimeout():e.bye()))};t.addListener("stateChanged",n)}},t.prototype.startReInvite2xxRetransmissionTimer=function(){var e=this;if(this.reinviteUserAgentServer&&this.reinviteUserAgentServer.transaction instanceof a.InviteServerTransaction){var t=this.reinviteUserAgentServer.transaction,r=o.Timers.T1,i=function(){e.reinviteUserAgentServer?(e.logger.log("No ACK for 2xx response received, attempting retransmission"),t.retransmitAcceptedResponse(),r=Math.min(2*r,o.Timers.T2),e.invite2xxTimer=setTimeout(i,r)):e.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(i,r);var n=function(){t.state===a.TransactionState.Terminated&&(t.removeListener("stateChanged",n),e.invite2xxTimer&&(clearTimeout(e.invite2xxTimer),e.invite2xxTimer=void 0),e.reinviteUserAgentServer)};t.addListener("stateChanged",n)}},t}(r(18).Dialog);t.SessionDialog=y},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e){e.Initial="Initial",e.Early="Early",e.AckWait="AckWait",e.Confirmed="Confirmed",e.Terminated="Terminated"}(t.SessionState||(t.SessionState={})),function(e){e.Initial="Initial",e.HaveLocalOffer="HaveLocalOffer",e.HaveRemoteOffer="HaveRemoteOffer",e.Stable="Stable",e.Closed="Closed"}(t.SignalingState||(t.SignalingState={}))},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=function(e){function t(t){return e.call(this,t||"Transaction state error.")||this}return i.__extends(t,e),t}(r(24).Exception);t.TransactionStateError=n},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=function(e){function t(t){return e.call(this,t||"Unspecified transport error.")||this}return i.__extends(t,e),t}(r(24).Exception);t.TransportError=n},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(2),s=r(6),o=r(25),a=r(13),c=function(e){function t(t,r,i){return e.call(this,t,r,i,a.TransactionState.Proceeding,"sip.transaction.ist")||this}return i.__extends(t,e),t.prototype.dispose=function(){this.stopProgressExtensionTimer(),this.H&&(clearTimeout(this.H),this.H=void 0),this.I&&(clearTimeout(this.I),this.I=void 0),this.L&&(clearTimeout(this.L),this.L=void 0),e.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"kind",{get:function(){return"ist"},enumerable:!0,configurable:!0}),t.prototype.receiveRequest=function(e){var t=this;switch(this.state){case a.TransactionState.Proceeding:if(e.method===n.C.INVITE)return void(this.lastProvisionalResponse&&this.send(this.lastProvisionalResponse).catch((function(e){t.logTransportError(e,"Failed to send retransmission of provisional response.")})));break;case a.TransactionState.Accepted:if(e.method===n.C.INVITE)return;break;case a.TransactionState.Completed:if(e.method===n.C.INVITE){if(!this.lastFinalResponse)throw new Error("Last final response undefined.");return void this.send(this.lastFinalResponse).catch((function(e){t.logTransportError(e,"Failed to send retransmission of final response.")}))}if(e.method===n.C.ACK)return void this.stateTransition(a.TransactionState.Confirmed);break;case a.TransactionState.Confirmed:case a.TransactionState.Terminated:if(e.method===n.C.INVITE||e.method===n.C.ACK)return;break;default:throw new Error("Invalid state "+this.state)}var r="INVITE server transaction received unexpected "+e.method+" request while in state "+this.state+".";this.logger.warn(r)},t.prototype.receiveResponse=function(e,t){var r=this;if(e<100||e>699)throw new Error("Invalid status code "+e);switch(this.state){case a.TransactionState.Proceeding:if(e>=100&&e<=199)return this.lastProvisionalResponse=t,e>100&&this.startProgressExtensionTimer(),void this.send(t).catch((function(e){r.logTransportError(e,"Failed to send 1xx response.")}));if(e>=200&&e<=299)return this.lastFinalResponse=t,this.stateTransition(a.TransactionState.Accepted),void this.send(t).catch((function(e){r.logTransportError(e,"Failed to send 2xx response.")}));if(e>=300&&e<=699)return this.lastFinalResponse=t,this.stateTransition(a.TransactionState.Completed),void this.send(t).catch((function(e){r.logTransportError(e,"Failed to send non-2xx final response.")}));break;case a.TransactionState.Accepted:if(e>=200&&e<=299)return void this.send(t).catch((function(e){r.logTransportError(e,"Failed to send 2xx response.")}));break;case a.TransactionState.Completed:case a.TransactionState.Confirmed:case a.TransactionState.Terminated:break;default:throw new Error("Invalid state "+this.state)}var i="INVITE server transaction received unexpected "+e+" response from TU while in state "+this.state+".";throw this.logger.error(i),new Error(i)},t.prototype.retransmitAcceptedResponse=function(){var e=this;this.state===a.TransactionState.Accepted&&this.lastFinalResponse&&this.send(this.lastFinalResponse).catch((function(t){e.logTransportError(t,"Failed to send 2xx response.")}))},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e)},t.prototype.typeToString=function(){return"INVITE server transaction"},t.prototype.stateTransition=function(e){var t=this,r=function(){throw new Error("Invalid state transition from "+t.state+" to "+e)};switch(e){case a.TransactionState.Proceeding:r();break;case a.TransactionState.Accepted:case a.TransactionState.Completed:this.state!==a.TransactionState.Proceeding&&r();break;case a.TransactionState.Confirmed:this.state!==a.TransactionState.Completed&&r();break;case a.TransactionState.Terminated:this.state!==a.TransactionState.Accepted&&this.state!==a.TransactionState.Completed&&this.state!==a.TransactionState.Confirmed&&r();break;default:r()}this.stopProgressExtensionTimer(),e===a.TransactionState.Accepted&&(this.L=setTimeout((function(){return t.timer_L()}),s.Timers.TIMER_L)),e===a.TransactionState.Completed&&(this.H=setTimeout((function(){return t.timer_H()}),s.Timers.TIMER_H)),e===a.TransactionState.Confirmed&&(this.I=setTimeout((function(){return t.timer_I()}),s.Timers.TIMER_I)),e===a.TransactionState.Terminated&&this.dispose(),this.setState(e)},t.prototype.startProgressExtensionTimer=function(){var e=this;void 0===this.progressExtensionTimer&&(this.progressExtensionTimer=setInterval((function(){if(e.logger.debug("Progress extension timer expired for INVITE server transaction "+e.id+"."),!e.lastProvisionalResponse)throw new Error("Last provisional response undefined.");e.send(e.lastProvisionalResponse).catch((function(t){e.logTransportError(t,"Failed to send retransmission of provisional response.")}))}),s.Timers.PROVISIONAL_RESPONSE_INTERVAL))},t.prototype.stopProgressExtensionTimer=function(){void 0!==this.progressExtensionTimer&&(clearInterval(this.progressExtensionTimer),this.progressExtensionTimer=void 0)},t.prototype.timer_G=function(){},t.prototype.timer_H=function(){this.logger.debug("Timer H expired for INVITE server transaction "+this.id+"."),this.state===a.TransactionState.Completed&&(this.logger.warn("ACK to negative final response was never received, terminating transaction."),this.stateTransition(a.TransactionState.Terminated))},t.prototype.timer_I=function(){this.logger.debug("Timer I expired for INVITE server transaction "+this.id+"."),this.stateTransition(a.TransactionState.Terminated)},t.prototype.timer_L=function(){this.logger.debug("Timer L expired for INVITE server transaction "+this.id+"."),this.state===a.TransactionState.Accepted&&this.stateTransition(a.TransactionState.Terminated)},t}(o.ServerTransaction);t.InviteServerTransaction=c},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(6),s=r(22),o=r(13),a=function(e){function t(t,r,i){var s=e.call(this,t,r,i,o.TransactionState.Trying,"sip.transaction.nict")||this;return s.F=setTimeout((function(){return s.timer_F()}),n.Timers.TIMER_F),s.send(t.toString()).catch((function(e){s.logTransportError(e,"Failed to send initial outgoing request.")})),s}return i.__extends(t,e),t.prototype.dispose=function(){this.F&&(clearTimeout(this.F),this.F=void 0),this.K&&(clearTimeout(this.K),this.K=void 0),e.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"kind",{get:function(){return"nict"},enumerable:!0,configurable:!0}),t.prototype.receiveResponse=function(e){var t=e.statusCode;if(!t||t<100||t>699)throw new Error("Invalid status code "+t);switch(this.state){case o.TransactionState.Trying:if(t>=100&&t<=199)return this.stateTransition(o.TransactionState.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=699)return this.stateTransition(o.TransactionState.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case o.TransactionState.Proceeding:if(t>=100&&t<=199&&this.user.receiveResponse)return this.user.receiveResponse(e);if(t>=200&&t<=699)return this.stateTransition(o.TransactionState.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));case o.TransactionState.Completed:case o.TransactionState.Terminated:return;default:throw new Error("Invalid state "+this.state)}var r="Non-INVITE client transaction received unexpected "+t+" response while in state "+this.state+".";this.logger.warn(r)},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(o.TransactionState.Terminated,!0)},t.prototype.typeToString=function(){return"non-INVITE client transaction"},t.prototype.stateTransition=function(e,t){var r=this;void 0===t&&(t=!1);var i=function(){throw new Error("Invalid state transition from "+r.state+" to "+e)};switch(e){case o.TransactionState.Trying:i();break;case o.TransactionState.Proceeding:this.state!==o.TransactionState.Trying&&i();break;case o.TransactionState.Completed:this.state!==o.TransactionState.Trying&&this.state!==o.TransactionState.Proceeding&&i();break;case o.TransactionState.Terminated:this.state!==o.TransactionState.Trying&&this.state!==o.TransactionState.Proceeding&&this.state!==o.TransactionState.Completed&&(t||i());break;default:i()}e===o.TransactionState.Completed&&(this.F&&(clearTimeout(this.F),this.F=void 0),this.K=setTimeout((function(){return r.timer_K()}),n.Timers.TIMER_K)),e===o.TransactionState.Terminated&&this.dispose(),this.setState(e)},t.prototype.timer_F=function(){this.logger.debug("Timer F expired for non-INVITE client transaction "+this.id+"."),this.state!==o.TransactionState.Trying&&this.state!==o.TransactionState.Proceeding||(this.onRequestTimeout(),this.stateTransition(o.TransactionState.Terminated))},t.prototype.timer_K=function(){this.state===o.TransactionState.Completed&&this.stateTransition(o.TransactionState.Terminated)},t}(s.ClientTransaction);t.NonInviteClientTransaction=a},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(6),s=r(25),o=r(13),a=function(e){function t(t,r,i){return e.call(this,t,r,i,o.TransactionState.Trying,"sip.transaction.nist")||this}return i.__extends(t,e),t.prototype.dispose=function(){this.J&&(clearTimeout(this.J),this.J=void 0),e.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"kind",{get:function(){return"nist"},enumerable:!0,configurable:!0}),t.prototype.receiveRequest=function(e){var t=this;switch(this.state){case o.TransactionState.Trying:break;case o.TransactionState.Proceeding:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch((function(e){t.logTransportError(e,"Failed to send retransmission of provisional response.")}));break;case o.TransactionState.Completed:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch((function(e){t.logTransportError(e,"Failed to send retransmission of final response.")}));break;case o.TransactionState.Terminated:break;default:throw new Error("Invalid state "+this.state)}},t.prototype.receiveResponse=function(e,t){var r=this;if(e<100||e>699)throw new Error("Invalid status code "+e);if(e>100&&e<=199)throw new Error("Provisional response other than 100 not allowed.");switch(this.state){case o.TransactionState.Trying:if(this.lastResponse=t,e>=100&&e<200)return this.stateTransition(o.TransactionState.Proceeding),void this.send(t).catch((function(e){r.logTransportError(e,"Failed to send provisional response.")}));if(e>=200&&e<=699)return this.stateTransition(o.TransactionState.Completed),void this.send(t).catch((function(e){r.logTransportError(e,"Failed to send final response.")}));break;case o.TransactionState.Proceeding:if(this.lastResponse=t,e>=200&&e<=699)return this.stateTransition(o.TransactionState.Completed),void this.send(t).catch((function(e){r.logTransportError(e,"Failed to send final response.")}));break;case o.TransactionState.Completed:return;case o.TransactionState.Terminated:break;default:throw new Error("Invalid state "+this.state)}var i="Non-INVITE server transaction received unexpected "+e+" response from TU while in state "+this.state+".";throw this.logger.error(i),new Error(i)},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(o.TransactionState.Terminated,!0)},t.prototype.typeToString=function(){return"non-INVITE server transaction"},t.prototype.stateTransition=function(e,t){var r=this;void 0===t&&(t=!1);var i=function(){throw new Error("Invalid state transition from "+r.state+" to "+e)};switch(e){case o.TransactionState.Trying:i();break;case o.TransactionState.Proceeding:this.state!==o.TransactionState.Trying&&i();break;case o.TransactionState.Completed:this.state!==o.TransactionState.Trying&&this.state!==o.TransactionState.Proceeding&&i();break;case o.TransactionState.Terminated:this.state!==o.TransactionState.Proceeding&&this.state!==o.TransactionState.Completed&&(t||i());break;default:i()}e===o.TransactionState.Completed&&(this.J=setTimeout((function(){return r.timer_J()}),n.Timers.TIMER_J)),e===o.TransactionState.Terminated&&this.dispose(),this.setState(e)},t.prototype.timer_J=function(){this.logger.debug("Timer J expired for NON-INVITE server transaction "+this.id+"."),this.state===o.TransactionState.Completed&&this.stateTransition(o.TransactionState.Terminated)},t}(s.ServerTransaction);t.NonInviteServerTransaction=a},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e){e.Initial="Initial",e.NotifyWait="NotifyWait",e.Pending="Pending",e.Active="Active",e.Terminated="Terminated"}(t.SubscriptionState||(t.SubscriptionState={}))},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0);i.__exportStar(r(28),t),i.__exportStar(r(72),t),i.__exportStar(r(49),t)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(28),n=r(49),s=function(){function e(){this.builtinEnabled=!0,this._level=i.Levels.log,this.loggers={},this.logger=this.getLogger("sip:loggerfactory")}return Object.defineProperty(e.prototype,"level",{get:function(){return this._level},set:function(e){e>=0&&e<=3?this._level=e:e>3?this._level=3:i.Levels.hasOwnProperty(e)?this._level=e:this.logger.error("invalid 'level' parameter value: "+JSON.stringify(e))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"connector",{get:function(){return this._connector},set:function(e){e?"function"==typeof e?this._connector=e:this.logger.error("invalid 'connector' parameter value: "+JSON.stringify(e)):this._connector=void 0},enumerable:!0,configurable:!0}),e.prototype.getLogger=function(e,t){if(t&&3===this.level)return new n.Logger(this,e,t);if(this.loggers[e])return this.loggers[e];var r=new n.Logger(this,e);return this.loggers[e]=r,r},e.prototype.genericLog=function(e,t,r,n){this.level>=e&&this.builtinEnabled&&this.print(e,t,r,n),this.connector&&this.connector(i.Levels[e],t,r,n)},e.prototype.print=function(e,t,r,n){if("string"==typeof n){var s=[new Date,t];r&&s.push(r),n=s.concat(n).join(" | ")}switch(e){case i.Levels.error:console.error(n);break;case i.Levels.warn:console.warn(n);break;case i.Levels.log:console.log(n);break;case i.Levels.debug:console.debug(n)}},e}();t.LoggerFactory=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),r(0).__exportStar(r(74),t)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(2),s=r(1),o=r(50),a=r(14),c=["application/sdp","application/dtmf-relay"],u=function(){function e(e,t){void 0===t&&(t={}),this.userAgentClients=new Map,this.userAgentServers=new Map,this.configuration=e,this.delegate=t,this.dialogs=new Map,this.subscribers=new Map,this.logger=e.loggerFactory.getLogger("sip.user-agent-core")}return e.prototype.dispose=function(){this.reset()},e.prototype.reset=function(){this.dialogs.forEach((function(e){return e.dispose()})),this.dialogs.clear(),this.subscribers.forEach((function(e){return e.dispose()})),this.subscribers.clear(),this.userAgentClients.forEach((function(e){return e.dispose()})),this.userAgentClients.clear(),this.userAgentServers.forEach((function(e){return e.dispose()})),this.userAgentServers.clear()},Object.defineProperty(e.prototype,"loggerFactory",{get:function(){return this.configuration.loggerFactory},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"transport",{get:function(){var e=this.configuration.transportAccessor();if(!e)throw new Error("Transport undefined.");return e},enumerable:!0,configurable:!0}),e.prototype.invite=function(e,t){return new o.InviteUserAgentClient(this,e,t)},e.prototype.message=function(e,t){return new o.MessageUserAgentClient(this,e,t)},e.prototype.publish=function(e,t){return new o.PublishUserAgentClient(this,e,t)},e.prototype.register=function(e,t){return new o.RegisterUserAgentClient(this,e,t)},e.prototype.subscribe=function(e,t){return new o.SubscribeUserAgentClient(this,e,t)},e.prototype.request=function(e,t){return new o.UserAgentClient(s.NonInviteClientTransaction,this,e,t)},e.prototype.makeOutgoingRequestMessage=function(e,t,r,s,o,a,c){var u=this.configuration.sipjsId,d=this.configuration.displayName,p=this.configuration.viaForceRport,h=this.configuration.hackViaTcp,l=this.configuration.supportedOptionTags.slice();e===n.C.REGISTER&&l.push("path","gruu"),e===n.C.INVITE&&(this.configuration.contact.pubGruu||this.configuration.contact.tempGruu)&&l.push("gruu");var g={callIdPrefix:u,forceRport:p,fromDisplayName:d,hackViaTcp:h,optionTags:l,routeSet:this.configuration.routeSet,userAgentString:this.configuration.userAgentHeaderFieldValue,viaHost:this.configuration.viaHost},f=i.__assign({},g,o);return new n.OutgoingRequestMessage(e,t,r,s,f,a,c)},e.prototype.receiveIncomingRequestFromTransport=function(e){this.receiveRequestFromTransport(e)},e.prototype.receiveIncomingResponseFromTransport=function(e){this.receiveResponseFromTransport(e)},e.prototype.replyStateless=function(e,t){var r=this.configuration.userAgentHeaderFieldValue,s=this.configuration.supportedOptionTagsResponse;t=i.__assign({},t,{userAgent:r,supported:s});var o=n.constructOutgoingResponse(e,t);return this.transport.send(o.message),o},e.prototype.receiveRequestFromTransport=function(e){var t=e.viaBranch,r=this.userAgentServers.get(t);e.method===n.C.ACK&&r&&r.transaction.state===s.TransactionState.Accepted&&r instanceof o.InviteUserAgentServer?this.logger.warn("Discarding out of dialog ACK after 2xx response sent on transaction "+t+"."):e.method!==n.C.CANCEL?r?r.transaction.receiveRequest(e):this.receiveRequest(e):r?(this.replyStateless(e,{statusCode:200}),r.transaction instanceof s.InviteServerTransaction&&r.transaction.state===s.TransactionState.Proceeding&&r instanceof o.InviteUserAgentServer&&r.receiveCancel(e)):this.replyStateless(e,{statusCode:481})},e.prototype.receiveRequest=function(e){if(a.AllowedMethods.includes(e.method)){if(!e.ruri)throw new Error("Request-URI undefined.");if("sip"===e.ruri.scheme){var t=e.ruri,r=function(e){return!!e&&e.user===t.user};if(!r(this.configuration.aor)&&!(r(this.configuration.contact.uri)||r(this.configuration.contact.pubGruu)||r(this.configuration.contact.tempGruu)))return this.logger.warn("Request-URI does not point to us."),void(e.method!==n.C.ACK&&this.replyStateless(e,{statusCode:404}));if(e.method!==n.C.INVITE||e.hasHeader("Contact")){if(!e.toTag){var i=e.viaBranch;if(!this.userAgentServers.has(i))if(Array.from(this.userAgentServers.values()).some((function(t){return t.transaction.request.fromTag===e.fromTag&&t.transaction.request.callId===e.callId&&t.transaction.request.cseq===e.cseq})))return void this.replyStateless(e,{statusCode:482})}e.toTag?this.receiveInsideDialogRequest(e):this.receiveOutsideDialogRequest(e)}else this.replyStateless(e,{statusCode:400,reasonPhrase:"Missing Contact Header"})}else this.replyStateless(e,{statusCode:416})}else{var s="Allow: "+a.AllowedMethods.toString();this.replyStateless(e,{statusCode:405,extraHeaders:[s]})}},e.prototype.receiveInsideDialogRequest=function(e){if(e.method===n.C.NOTIFY){var t=e.parseHeader("Event");if(!t||!t.event)return void this.replyStateless(e,{statusCode:489});var r=e.callId+e.toTag+t.event,i=this.subscribers.get(r);if(i){var s=new o.NotifyUserAgentServer(this,e);return void i.onNotify(s)}}var u=e.callId+e.toTag+e.fromTag,d=this.dialogs.get(u);if(d){if(e.method===n.C.OPTIONS){var p="Allow: "+a.AllowedMethods.toString(),h="Accept: "+c.toString();return void this.replyStateless(e,{statusCode:200,extraHeaders:[p,h]})}d.receiveRequest(e)}else e.method!==n.C.ACK&&this.replyStateless(e,{statusCode:481})},e.prototype.receiveOutsideDialogRequest=function(e){switch(e.method){case n.C.ACK:break;case n.C.BYE:this.replyStateless(e,{statusCode:481});break;case n.C.CANCEL:throw new Error("Unexpected out of dialog request method "+e.method+".");case n.C.INFO:this.replyStateless(e,{statusCode:405});break;case n.C.INVITE:var t=new o.InviteUserAgentServer(this,e);this.delegate.onInvite?this.delegate.onInvite(t):t.reject();break;case n.C.MESSAGE:t=new o.MessageUserAgentServer(this,e);this.delegate.onMessage?this.delegate.onMessage(t):t.accept();break;case n.C.NOTIFY:t=new o.NotifyUserAgentServer(this,e);this.delegate.onNotify?this.delegate.onNotify(t):t.reject({statusCode:405});break;case n.C.OPTIONS:var r="Allow: "+a.AllowedMethods.toString(),i="Accept: "+c.toString();this.replyStateless(e,{statusCode:200,extraHeaders:[r,i]});break;case n.C.REFER:t=new o.ReferUserAgentServer(this,e);this.delegate.onRefer?this.delegate.onRefer(t):t.reject({statusCode:405});break;case n.C.REGISTER:t=new o.RegisterUserAgentServer(this,e);this.delegate.onRegister?this.delegate.onRegister(t):t.reject({statusCode:405});break;case n.C.SUBSCRIBE:t=new o.SubscribeUserAgentServer(this,e);this.delegate.onSubscribe?this.delegate.onSubscribe(t):t.reject({statusCode:480});break;default:throw new Error("Unexpected out of dialog request method "+e.method+".")}},e.prototype.receiveResponseFromTransport=function(e){if(e.getHeaders("via").length>1)this.logger.warn("More than one Via header field present in the response, dropping");else{var t=e.viaBranch+e.method,r=this.userAgentClients.get(t);r?r.transaction.receiveResponse(e):this.logger.warn("Discarding unmatched "+e.statusCode+" response to "+e.method+" "+t+".")}},e}();t.UserAgentCore=u},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){return e.call(this,n.NonInviteClientTransaction,t,r,i)||this}return i.__extends(t,e),t}(r(3).UserAgentClient);t.CancelUserAgentClient=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(17),s=r(15),o=r(1),a=function(e){function t(t,r,i){var n=e.call(this,o.InviteClientTransaction,t,r,i)||this;return n.confirmedDialogAcks=new Map,n.confirmedDialogs=new Map,n.earlyDialogs=new Map,n.delegate=i,n}return i.__extends(t,e),t.prototype.dispose=function(){this.earlyDialogs.forEach((function(e){return e.dispose()})),this.earlyDialogs.clear(),e.prototype.dispose.call(this)},t.prototype.receiveResponse=function(e){var t=this;if(this.authenticationGuard(e)){var r=e.statusCode?e.statusCode.toString():"";if(!r)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(r):return void(this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e}));case/^1[0-9]{2}$/.test(r):if(!e.toTag)return void this.logger.warn("Non-100 1xx INVITE response received without a to tag, dropping.");var i=n.Dialog.initialDialogStateForUserAgentClient(this.message,e),a=this.earlyDialogs.get(i.id);if(!a){if(!((d=this.transaction)instanceof o.InviteClientTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");a=new n.SessionDialog(d,this.core,i),this.earlyDialogs.set(a.id,a)}if(!a.reliableSequenceGuard(e))return void this.logger.warn("1xx INVITE reliable response received out of order, dropping.");a.signalingState!==s.SignalingState.Initial&&a.signalingState!==s.SignalingState.HaveLocalOffer||a.signalingStateTransition(e);var c=a;return void(this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:c,prack:function(e){return c.prack(void 0,e)}}));case/^2[0-9]{2}$/.test(r):i=n.Dialog.initialDialogStateForUserAgentClient(this.message,e);var u=this.confirmedDialogs.get(i.id);if(u){if(h=this.confirmedDialogAcks.get(i.id)){if(!((d=this.transaction)instanceof o.InviteClientTransaction))throw new Error("Client transaction not instance of InviteClientTransaction.");d.ackResponse(h.message)}return}if(u=this.earlyDialogs.get(i.id))u.confirm(),u.recomputeRouteSet(e),this.earlyDialogs.delete(u.id),this.confirmedDialogs.set(u.id,u);else{var d;if(!((d=this.transaction)instanceof o.InviteClientTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");u=new n.SessionDialog(d,this.core,i),this.confirmedDialogs.set(u.id,u)}u.signalingState!==s.SignalingState.Initial&&u.signalingState!==s.SignalingState.HaveLocalOffer||u.signalingStateTransition(e);var p=u;if(this.delegate&&this.delegate.onAccept)this.delegate.onAccept({message:e,session:p,ack:function(e){var r=p.ack(e);return t.confirmedDialogAcks.set(p.id,r),r}});else{var h=p.ack();this.confirmedDialogAcks.set(p.id,h)}return;case/^3[0-9]{2}$/.test(r):return this.earlyDialogs.forEach((function(e){return e.dispose()})),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e}));case/^[4-6][0-9]{2}$/.test(r):return this.earlyDialogs.forEach((function(e){return e.dispose()})),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e}));default:throw new Error("Invalid status code "+r)}throw new Error("Executing what should be an unreachable code path receiving "+r+" response.")}},t}(r(3).UserAgentClient);t.InviteUserAgentClient=a},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(17),s=r(16),o=r(15),a=r(1),c=r(14),u=function(e){function t(t,r,i){var n=e.call(this,a.InviteServerTransaction,t,r,i)||this;return n.core=t,n}return i.__extends(t,e),t.prototype.dispose=function(){this.earlyDialog&&this.earlyDialog.dispose(),e.prototype.dispose.call(this)},t.prototype.accept=function(t){if(void 0===t&&(t={statusCode:200}),!this.acceptable)throw new s.TransactionStateError(this.message.method+" not acceptable in state "+this.transaction.state+".");if(!this.confirmedDialog)if(this.earlyDialog)this.earlyDialog.confirm(),this.confirmedDialog=this.earlyDialog,this.earlyDialog=void 0;else{var r=this.transaction;if(!(r instanceof a.InviteServerTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");var u=n.Dialog.initialDialogStateForUserAgentServer(this.message,this.toTag);this.confirmedDialog=new n.SessionDialog(r,this.core,u)}var d=this.message.getHeaders("record-route").map((function(e){return"Record-Route: "+e})),p="Contact: "+this.core.configuration.contact.toString(),h="Allow: "+c.AllowedMethods.toString();if(!t.body)if(this.confirmedDialog.signalingState===o.SignalingState.Stable)t.body=this.confirmedDialog.answer;else if(this.confirmedDialog.signalingState===o.SignalingState.Initial||this.confirmedDialog.signalingState===o.SignalingState.HaveRemoteOffer)throw new Error("Response must have a body.");t.statusCode=t.statusCode||200,t.extraHeaders=t.extraHeaders||[],t.extraHeaders=t.extraHeaders.concat(d),t.extraHeaders.push(h),t.extraHeaders.push(p);var l=e.prototype.accept.call(this,t),g=this.confirmedDialog,f=i.__assign({},l,{session:g});return t.body&&this.confirmedDialog.signalingState!==o.SignalingState.Stable&&this.confirmedDialog.signalingStateTransition(t.body),f},t.prototype.progress=function(t){if(void 0===t&&(t={statusCode:180}),!this.progressable)throw new s.TransactionStateError(this.message.method+" not progressable in state "+this.transaction.state+".");if(!this.earlyDialog){var r=this.transaction;if(!(r instanceof a.InviteServerTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");var c=n.Dialog.initialDialogStateForUserAgentServer(this.message,this.toTag,!0);this.earlyDialog=new n.SessionDialog(r,this.core,c)}var u=this.message.getHeaders("record-route").map((function(e){return"Record-Route: "+e})),d="Contact: "+this.core.configuration.contact;t.extraHeaders=t.extraHeaders||[],t.extraHeaders=t.extraHeaders.concat(u),t.extraHeaders.push(d);var p=e.prototype.progress.call(this,t),h=this.earlyDialog,l=i.__assign({},p,{session:h});return t.body&&this.earlyDialog.signalingState!==o.SignalingState.Stable&&this.earlyDialog.signalingStateTransition(t.body),l},t.prototype.redirect=function(t,r){return void 0===r&&(r={statusCode:302}),e.prototype.redirect.call(this,t,r)},t.prototype.reject=function(t){return void 0===t&&(t={statusCode:486}),e.prototype.reject.call(this,t)},t}(r(4).UserAgentServer);t.InviteUserAgentServer=u},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){return e.call(this,n.NonInviteClientTransaction,t,r,i)||this}return i.__extends(t,e),t}(r(3).UserAgentClient);t.MessageUserAgentClient=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){var s=e.call(this,n.NonInviteServerTransaction,t,r,i)||this;return s.core=t,s}return i.__extends(t,e),t}(r(4).UserAgentServer);t.MessageUserAgentServer=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){return e.call(this,n.NonInviteClientTransaction,t,r,i)||this}return i.__extends(t,e),t}(r(3).UserAgentClient);t.PublishUserAgentClient=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){return e.call(this,n.NonInviteServerTransaction,t.userAgentCore,r,i)||this}return i.__extends(t,e),t}(r(4).UserAgentServer);t.ReSubscribeUserAgentServer=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){return e.call(this,n.NonInviteClientTransaction,t,r,i)||this}return i.__extends(t,e),t}(r(3).UserAgentClient);t.RegisterUserAgentClient=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){var s=e.call(this,n.NonInviteServerTransaction,t,r,i)||this;return s.core=t,s}return i.__extends(t,e),t}(r(4).UserAgentServer);t.RegisterUserAgentServer=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(47),s=r(27),o=r(6),a=r(1),c=function(e){function t(t,r,i){var n=this,o=r.getHeader("Event");if(!o)throw new Error("Event undefined");var c=r.getHeader("Expires");if(!c)throw new Error("Expires undefined");return(n=e.call(this,a.NonInviteClientTransaction,t,r,i)||this).delegate=i,n.subscriberId=r.callId+r.fromTag+o,n.subscriptionExpiresRequested=n.subscriptionExpires=Number(c),n.subscriptionEvent=o,n.subscriptionState=s.SubscriptionState.NotifyWait,n.waitNotifyStart(),n}return i.__extends(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this)},t.prototype.onNotify=function(e){var t=e.message.parseHeader("Event").event;if(!t||t!==this.subscriptionEvent)return this.logger.warn("Failed to parse event."),void e.reject({statusCode:489});var r=e.message.parseHeader("Subscription-State");if(!r||!r.state)return this.logger.warn("Failed to parse subscription state."),void e.reject({statusCode:489});var i=r.state;switch(i){case"pending":case"active":case"terminated":break;default:return this.logger.warn("Invalid subscription state "+i),void e.reject({statusCode:489})}if("terminated"!==i&&!e.message.parseHeader("contact"))return this.logger.warn("Failed to parse contact."),void e.reject({statusCode:489});if(this.dialog)throw new Error("Dialog already created. This implementation only supports install of single subscriptions.");switch(this.waitNotifyStop(),this.subscriptionExpires=r.expires?Math.min(this.subscriptionExpires,Math.max(r.expires,0)):this.subscriptionExpires,i){case"pending":this.subscriptionState=s.SubscriptionState.Pending;break;case"active":this.subscriptionState=s.SubscriptionState.Active;break;case"terminated":this.subscriptionState=s.SubscriptionState.Terminated;break;default:throw new Error("Unrecognized state "+i+".")}if(this.subscriptionState!==s.SubscriptionState.Terminated){var o=n.SubscriptionDialog.initialDialogStateForSubscription(this.message,e.message);this.dialog=new n.SubscriptionDialog(this.subscriptionEvent,this.subscriptionExpires,this.subscriptionState,this.core,o)}if(this.delegate&&this.delegate.onNotify){var a=e,c=this.dialog;this.delegate.onNotify({request:a,subscription:c})}else e.accept()},t.prototype.waitNotifyStart=function(){var e=this;this.N||(this.core.subscribers.set(this.subscriberId,this),this.N=setTimeout((function(){return e.timer_N()}),o.Timers.TIMER_N))},t.prototype.waitNotifyStop=function(){this.N&&(this.core.subscribers.delete(this.subscriberId),clearTimeout(this.N),this.N=void 0)},t.prototype.receiveResponse=function(t){if(this.authenticationGuard(t)){if(t.statusCode&&t.statusCode>=200&&t.statusCode<300){var r=t.getHeader("Expires");if(r){var i=Number(r);i>this.subscriptionExpiresRequested&&this.logger.warn("Expires header in a 200-class response to SUBSCRIBE with a higher value than the one in the request"),ithis.subscriptionExpires&&(this.dialog.subscriptionExpires=this.subscriptionExpires)}t.statusCode&&t.statusCode>=300&&t.statusCode<700&&this.waitNotifyStop(),e.prototype.receiveResponse.call(this,t)}},t.prototype.timer_N=function(){this.logger.warn("Timer N expired for SUBSCRIBE user agent client. Timed out waiting for NOTIFY."),this.waitNotifyStop(),this.delegate&&this.delegate.onNotifyTimeout&&this.delegate.onNotifyTimeout()},t}(r(3).UserAgentClient);t.SubscribeUserAgentClient=c},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){var s=e.call(this,n.NonInviteServerTransaction,t,r,i)||this;return s.core=t,s}return i.__extends(t,e),t}(r(4).UserAgentServer);t.SubscribeUserAgentServer=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=function(e){function t(t,r){var i=e.call(this)||this;return i.logger=t,i}return i.__extends(t,e),t.prototype.connect=function(e){var t=this;return void 0===e&&(e={}),this.connectPromise(e).then((function(e){e.overrideEvent||t.emit("connected")}))},t.prototype.send=function(e,t){var r=this;return void 0===t&&(t={}),this.sendPromise(e).then((function(e){e.overrideEvent||r.emit("messageSent",e.msg)}))},t.prototype.disconnect=function(e){var t=this;return void 0===e&&(e={}),this.disconnectPromise(e).then((function(e){e.overrideEvent||t.emit("disconnected")}))},t.prototype.afterConnected=function(e){this.isConnected()?e():this.once("connected",e)},t.prototype.waitForConnected=function(){var e=this;return console.warn("DEPRECATION WARNING Transport.waitForConnected(): use afterConnected() instead"),new Promise((function(t){e.afterConnected(t)}))},t}(r(7).EventEmitter);t.Transport=n},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=function(e,t){for(var r,i=[],n=e.split(/\r\n/),s=0;sn)throw new TypeError("Invalid statusCode: "+r);var p,h={statusCode:r,reasonPhrase:s,extraHeaders:a,body:u},l=r.toString();switch(!0){case/^100$/.test(l):p=this.incomingRequest.trying(h).message;break;case/^1[0-9]{2}$/.test(l):p=this.incomingRequest.progress(h).message;break;case/^2[0-9]{2}$/.test(l):p=this.incomingRequest.accept(h).message;break;case/^3[0-9]{2}$/.test(l):p=this.incomingRequest.redirect([],h).message;break;case/^[4-6][0-9]{2}$/.test(l):p=this.incomingRequest.reject(h).message;break;default:throw new Error("Invalid status code "+r)}return d.forEach((function(e){t.emit(e,p,s)})),this},t.prototype.onRequestTimeout=function(){this.emit("failed",void 0,s.C.causes.REQUEST_TIMEOUT)},t.prototype.onTransportError=function(){this.emit("failed",void 0,s.C.causes.CONNECTION_ERROR)},t}(n.EventEmitter);t.ServerContext=u},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(7),s=r(52),o=r(8),a=r(12),c=r(9),u=i.__importStar(r(87)),d=r(97),p=function(e){function t(t,r,i){var n=e.call(this)||this;return n.type=o.TypeStrings.SessionDescriptionHandler,n.options=i||{},n.logger=t,n.observer=r,n.dtmfSender=void 0,n.shouldAcquireMedia=!0,n.CONTENT_TYPE="application/sdp",n.C={DIRECTION:{NULL:null,SENDRECV:"sendrecv",SENDONLY:"sendonly",RECVONLY:"recvonly",INACTIVE:"inactive"}},n.logger.log("SessionDescriptionHandlerOptions: "+JSON.stringify(n.options)),n.direction=n.C.DIRECTION.NULL,n.modifiers=n.options.modifiers||[],Array.isArray(n.modifiers)||(n.modifiers=[n.modifiers]),n.iceGatheringTimeout=!1,n.initPeerConnection(n.options.peerConnectionOptions),n.constraints=n.checkAndDefaultConstraints(n.options.constraints),n}return i.__extends(t,e),t.defaultFactory=function(e,r){return new t(e instanceof s.Session?e.userAgent.getLogger("sip.sessionDescriptionHandler",e.id):e.ua.getLogger("sip.invitecontext.sessionDescriptionHandler",e.id),new d.SessionDescriptionHandlerObserver(e,r),r)},t.prototype.close=function(){this.logger.log("closing PeerConnection"),this.peerConnection&&"closed"!==this.peerConnection.signalingState&&(this.peerConnection.getSenders?this.peerConnection.getSenders().forEach((function(e){e.track&&e.track.stop()})):(this.logger.warn("Using getLocalStreams which is deprecated"),this.peerConnection.getLocalStreams().forEach((function(e){e.getTracks().forEach((function(e){e.stop()}))}))),this.peerConnection.getReceivers?this.peerConnection.getReceivers().forEach((function(e){e.track&&e.track.stop()})):(this.logger.warn("Using getRemoteStreams which is deprecated"),this.peerConnection.getRemoteStreams().forEach((function(e){e.getTracks().forEach((function(e){e.stop()}))}))),this.resetIceGatheringComplete(),this.peerConnection.close())},t.prototype.getDescription=function(e,t){var r=this;void 0===e&&(e={}),void 0===t&&(t=[]),e.peerConnectionOptions&&this.initPeerConnection(e.peerConnectionOptions);var i=Object.assign({},this.constraints,e.constraints);return i=this.checkAndDefaultConstraints(i),JSON.stringify(i)!==JSON.stringify(this.constraints)&&(this.constraints=i,this.shouldAcquireMedia=!0),Array.isArray(t)||(t=[t]),t=t.concat(this.modifiers),Promise.resolve().then((function(){if(r.shouldAcquireMedia)return r.acquire(r.constraints).then((function(){r.shouldAcquireMedia=!1}))})).then((function(){return r.createOfferOrAnswer(e.RTCOfferOptions,t)})).then((function(e){if(void 0===e.sdp)throw new a.Exceptions.SessionDescriptionHandlerError("getDescription",void 0,"SDP undefined");return r.emit("getDescription",e),{body:e.sdp,contentType:r.CONTENT_TYPE}}))},t.prototype.hasDescription=function(e){return e===this.CONTENT_TYPE},t.prototype.holdModifier=function(e){return e.sdp?(/a=(sendrecv|sendonly|recvonly|inactive)/.test(e.sdp)?(e.sdp=e.sdp.replace(/a=sendrecv\r\n/g,"a=sendonly\r\n"),e.sdp=e.sdp.replace(/a=recvonly\r\n/g,"a=inactive\r\n")):e.sdp=e.sdp.replace(/(m=[^\r]*\r\n)/g,"$1a=sendonly\r\n"),Promise.resolve(e)):Promise.resolve(e)},t.prototype.setDescription=function(e,t,r){var i=this;void 0===t&&(t={}),void 0===r&&(r=[]),t.peerConnectionOptions&&this.initPeerConnection(t.peerConnectionOptions),Array.isArray(r)||(r=[r]),r=r.concat(this.modifiers);var n={type:this.hasOffer("local")?"answer":"offer",sdp:e};return Promise.resolve().then((function(){if(i.shouldAcquireMedia&&i.options.alwaysAcquireMediaFirst)return i.acquire(i.constraints).then((function(){i.shouldAcquireMedia=!1}))})).then((function(){return c.Utils.reducePromises(r,n)})).catch((function(e){if(e.type===o.TypeStrings.SessionDescriptionHandlerError)throw e;var t=new a.Exceptions.SessionDescriptionHandlerError("setDescription",e,"The modifiers did not resolve successfully");throw i.logger.error(t.message),i.emit("peerConnection-setRemoteDescriptionFailed",t),t})).then((function(e){return i.emit("setDescription",e),i.peerConnection.setRemoteDescription(e)})).catch((function(n){if(n.type===o.TypeStrings.SessionDescriptionHandlerError)throw n;if(/^m=video.+$/gm.test(e)&&!t.disableAudioFallback)return t.disableAudioFallback=!0,i.setDescription(e,t,[u.stripVideo].concat(r));var s=new a.Exceptions.SessionDescriptionHandlerError("setDescription",n);throw s.error&&i.logger.error(s.error),i.emit("peerConnection-setRemoteDescriptionFailed",s),s})).then((function(){i.peerConnection.getReceivers?i.emit("setRemoteDescription",i.peerConnection.getReceivers()):i.emit("setRemoteDescription",i.peerConnection.getRemoteStreams()),i.emit("confirmed",i)}))},t.prototype.sendDtmf=function(e,t){if(void 0===t&&(t={}),!this.dtmfSender&&this.hasBrowserGetSenderSupport()){var r=this.peerConnection.getSenders();r.length>0&&(this.dtmfSender=r[0].dtmf)}if(!this.dtmfSender&&this.hasBrowserTrackSupport()){var i=this.peerConnection.getLocalStreams();if(i.length>0){var n=i[0].getAudioTracks();n.length>0&&(this.dtmfSender=this.peerConnection.createDTMFSender(n[0]))}}if(!this.dtmfSender)return!1;try{this.dtmfSender.insertDTMF(e,t.duration,t.interToneGap)}catch(e){if("InvalidStateError"===e.type||"InvalidCharacterError"===e.type)return this.logger.error(e),!1;throw e}return this.logger.log("DTMF sent via RTP: "+e.toString()),!0},t.prototype.getDirection=function(){return this.direction},t.prototype.on=function(t,r){return e.prototype.on.call(this,t,r)},t.prototype.getMediaStream=function(e){return navigator.mediaDevices.getUserMedia(e)},t.prototype.createOfferOrAnswer=function(e,t){var r=this;void 0===e&&(e={}),void 0===t&&(t=[]);var i=this.hasOffer("remote")?"createAnswer":"createOffer",n=this.peerConnection;return this.logger.log(i),(this.hasOffer("remote")?n.createAnswer:n.createOffer).apply(n,e).catch((function(e){if(e.type===o.TypeStrings.SessionDescriptionHandlerError)throw e;var t=new a.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer",e,"peerConnection-"+i+"Failed");throw r.emit("peerConnection-"+i+"Failed",t),t})).then((function(e){return c.Utils.reducePromises(t,r.createRTCSessionDescriptionInit(e))})).then((function(e){return r.resetIceGatheringComplete(),r.logger.log("Setting local sdp."),r.logger.log("sdp is "+e.sdp||!1),n.setLocalDescription(e)})).catch((function(e){if(e.type===o.TypeStrings.SessionDescriptionHandlerError)throw e;var t=new a.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer",e,"peerConnection-SetLocalDescriptionFailed");throw r.emit("peerConnection-SetLocalDescriptionFailed",t),t})).then((function(){return r.waitForIceGatheringComplete()})).then((function(){if(!r.peerConnection.localDescription)throw new a.Exceptions.SessionDescriptionHandlerError("Missing local description");var e=r.createRTCSessionDescriptionInit(r.peerConnection.localDescription);return c.Utils.reducePromises(t,e)})).then((function(e){return r.setDirection(e.sdp||""),e})).catch((function(e){if(e.type===o.TypeStrings.SessionDescriptionHandlerError)throw e;var t=new a.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer",e);throw r.logger.error(t.toString()),t}))},t.prototype.createRTCSessionDescriptionInit=function(e){return{type:e.type,sdp:e.sdp}},t.prototype.addDefaultIceCheckingTimeout=function(e){return void 0===e.iceCheckingTimeout&&(e.iceCheckingTimeout=5e3),e},t.prototype.addDefaultIceServers=function(e){return e.iceServers||(e.iceServers=[{urls:"stun:stun.l.google.com:19302"}]),e},t.prototype.checkAndDefaultConstraints=function(e){var t={audio:!0,video:!this.options.alwaysAcquireMediaFirst};return e=e||t,0===Object.keys(e).length&&e.constructor===Object?t:e},t.prototype.hasBrowserTrackSupport=function(){return Boolean(this.peerConnection.addTrack)},t.prototype.hasBrowserGetSenderSupport=function(){return Boolean(this.peerConnection.getSenders)},t.prototype.initPeerConnection=function(e){var t=this;void 0===e&&(e={}),(e=this.addDefaultIceCheckingTimeout(e)).rtcConfiguration=e.rtcConfiguration||{},e.rtcConfiguration=this.addDefaultIceServers(e.rtcConfiguration),this.logger.log("initPeerConnection"),this.peerConnection&&(this.logger.log("Already have a peer connection for this session. Tearing down."),this.resetIceGatheringComplete(),this.peerConnection.close()),this.peerConnection=new RTCPeerConnection(e.rtcConfiguration),this.logger.log("New peer connection created"),"ontrack"in this.peerConnection?this.peerConnection.addEventListener("track",(function(e){t.logger.log("track added"),t.observer.trackAdded(),t.emit("addTrack",e)})):(this.logger.warn("Using onaddstream which is deprecated"),this.peerConnection.onaddstream=function(e){t.logger.log("stream added"),t.emit("addStream",e)}),this.peerConnection.onicecandidate=function(e){t.emit("iceCandidate",e),e.candidate?t.logger.log("ICE candidate received: "+(null===e.candidate.candidate?null:e.candidate.candidate.trim())):null===e.candidate&&(t.logger.log("ICE candidate gathering complete"),t.triggerIceGatheringComplete())},this.peerConnection.onicegatheringstatechange=function(){switch(t.logger.log("RTCIceGatheringState changed: "+t.peerConnection.iceGatheringState),t.peerConnection.iceGatheringState){case"gathering":t.emit("iceGathering",t),!t.iceGatheringTimer&&e.iceCheckingTimeout&&(t.iceGatheringTimeout=!1,t.iceGatheringTimer=setTimeout((function(){t.logger.log("RTCIceChecking Timeout Triggered after "+e.iceCheckingTimeout+" milliseconds"),t.iceGatheringTimeout=!0,t.triggerIceGatheringComplete()}),e.iceCheckingTimeout));break;case"complete":t.triggerIceGatheringComplete()}},this.peerConnection.oniceconnectionstatechange=function(){var e;switch(t.peerConnection.iceConnectionState){case"new":e="iceConnection";break;case"checking":e="iceConnectionChecking";break;case"connected":e="iceConnectionConnected";break;case"completed":e="iceConnectionCompleted";break;case"failed":e="iceConnectionFailed";break;case"disconnected":e="iceConnectionDisconnected";break;case"closed":e="iceConnectionClosed";break;default:return void t.logger.warn("Unknown iceConnection state: "+t.peerConnection.iceConnectionState)}t.logger.log("ICE Connection State changed to "+e),t.emit(e,t)}},t.prototype.acquire=function(e){var t=this;return e=this.checkAndDefaultConstraints(e),new Promise((function(r,i){t.logger.log("acquiring local media"),t.emit("userMediaRequest",e),e.audio||e.video?t.getMediaStream(e).then((function(e){t.observer.trackAdded(),t.emit("userMedia",e),r(e)})).catch((function(e){t.emit("userMediaFailed",e),i(e)})):r([])})).catch((function(e){if(e.type===o.TypeStrings.SessionDescriptionHandlerError)throw e;var r=new a.Exceptions.SessionDescriptionHandlerError("acquire",e,"unable to acquire streams");throw t.logger.error(r.message),r.error&&t.logger.error(r.error),r})).then((function(e){return t.logger.log("acquired local media streams"),t.peerConnection.removeTrack&&t.peerConnection.getSenders().forEach((function(e){t.peerConnection.removeTrack(e)})),e})).catch((function(e){if(e.type===o.TypeStrings.SessionDescriptionHandlerError)throw e;var r=new a.Exceptions.SessionDescriptionHandlerError("acquire",e,"error removing streams");throw t.logger.error(r.message),r.error&&t.logger.error(r.error),r})).then((function(e){return[].concat(e).forEach((function(e){t.peerConnection.addTrack?e.getTracks().forEach((function(r){t.peerConnection.addTrack(r,e)})):t.peerConnection.addStream(e)})),Promise.resolve()})).catch((function(e){if(e.type===o.TypeStrings.SessionDescriptionHandlerError)throw e;var r=new a.Exceptions.SessionDescriptionHandlerError("acquire",e,"error adding stream");throw t.logger.error(r.message),r.error&&t.logger.error(r.error),r}))},t.prototype.hasOffer=function(e){var t="have-"+e+"-offer";return this.peerConnection.signalingState===t},t.prototype.isIceGatheringComplete=function(){return"complete"===this.peerConnection.iceGatheringState||this.iceGatheringTimeout},t.prototype.resetIceGatheringComplete=function(){this.iceGatheringTimeout=!1,this.logger.log("resetIceGatheringComplete"),this.iceGatheringTimer&&(clearTimeout(this.iceGatheringTimer),this.iceGatheringTimer=void 0),this.iceGatheringDeferred&&(this.iceGatheringDeferred.reject(),this.iceGatheringDeferred=void 0)},t.prototype.setDirection=function(e){var t=e.match(/a=(sendrecv|sendonly|recvonly|inactive)/);if(null===t)return this.direction=this.C.DIRECTION.NULL,void this.observer.directionChanged();var r=t[1];switch(r){case this.C.DIRECTION.SENDRECV:case this.C.DIRECTION.SENDONLY:case this.C.DIRECTION.RECVONLY:case this.C.DIRECTION.INACTIVE:this.direction=r;break;default:this.direction=this.C.DIRECTION.NULL}this.observer.directionChanged()},t.prototype.triggerIceGatheringComplete=function(){this.isIceGatheringComplete()&&(this.emit("iceGatheringComplete",this),this.iceGatheringTimer&&(clearTimeout(this.iceGatheringTimer),this.iceGatheringTimer=void 0),this.iceGatheringDeferred&&(this.iceGatheringDeferred.resolve(),this.iceGatheringDeferred=void 0))},t.prototype.waitForIceGatheringComplete=function(){return this.logger.log("waitForIceGatheringComplete"),this.isIceGatheringComplete()?(this.logger.log("ICE is already complete. Return resolved."),Promise.resolve()):(this.iceGatheringDeferred||(this.iceGatheringDeferred=c.Utils.defer()),this.logger.log("ICE is not complete. Returning promise"),this.iceGatheringDeferred?this.iceGatheringDeferred.promise:Promise.resolve())},t}(n.EventEmitter);t.SessionDescriptionHandler=p},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e){this.incomingInfoRequest=e}return Object.defineProperty(e.prototype,"request",{get:function(){return this.incomingInfoRequest.message},enumerable:!0,configurable:!0}),e.prototype.accept=function(e){return this.incomingInfoRequest.accept(e),Promise.resolve()},e.prototype.reject=function(e){return this.incomingInfoRequest.reject(e),Promise.resolve()},e}();t.Info=i},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(5),n=function(){function e(e,t){this.incomingReferRequest=e,this.session=t}return Object.defineProperty(e.prototype,"referTo",{get:function(){var e=this.incomingReferRequest.message.parseHeader("refer-to");if(!(e instanceof i.NameAddrHeader))throw new Error("Failed to parse Refer-To header.");return e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"referredBy",{get:function(){return this.incomingReferRequest.message.getHeader("referred-by")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"replaces",{get:function(){return this.referTo.uri.getHeader("replaces")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"request",{get:function(){return this.incomingReferRequest.message},enumerable:!0,configurable:!0}),e.prototype.accept=function(e){return void 0===e&&(e={statusCode:202}),this.incomingReferRequest.accept(e),Promise.resolve()},e.prototype.reject=function(e){return this.incomingReferRequest.reject(e),Promise.resolve()},e.prototype.makeInviter=function(e){if(this.inviter)return this.inviter;var t=this.referTo.uri.clone();t.clearHeaders();var r=((e=e||{}).extraHeaders||[]).slice(),i=this.replaces;i&&r.push("Replaces: "+decodeURIComponent(i));var n=this.referredBy;return n&&r.push("Referred-By: "+n),e.extraHeaders=r,this.inviter=this.session.userAgent.makeInviter(t,e),this.inviter.referred=this.session,this.session.referral=this.inviter,this.inviter},e}();t.Referral=n},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i,n=r(0),s=r(5),o=r(8),a=r(12),c=r(9);!function(e){e[e.STATUS_CONNECTING=0]="STATUS_CONNECTING",e[e.STATUS_OPEN=1]="STATUS_OPEN",e[e.STATUS_CLOSING=2]="STATUS_CLOSING",e[e.STATUS_CLOSED=3]="STATUS_CLOSED"}(i=t.TransportStatus||(t.TransportStatus={}));var u=function(e){function t(t,r){void 0===r&&(r={});var n=e.call(this,t,r)||this;return n.type=o.TypeStrings.Transport,n.reconnectionAttempts=0,n.status=i.STATUS_CONNECTING,n.configuration=n.loadConfig(r),n.server=n.configuration.wsServers[0],n}return n.__extends(t,e),t.prototype.isConnected=function(){return this.status===i.STATUS_OPEN},t.prototype.sendPromise=function(e,t){if(void 0===t&&(t={}),!this.statusAssert(i.STATUS_OPEN,t.force))return this.onError("unable to send message - WebSocket not open"),Promise.reject();var r=e.toString();return this.ws?(!0===this.configuration.traceSip&&this.logger.log("sending WebSocket message:\n\n"+r+"\n"),this.ws.send(r),Promise.resolve({msg:r})):(this.onError("unable to send message - WebSocket does not exist"),Promise.reject())},t.prototype.disconnectPromise=function(e){var t=this;return void 0===e&&(e={}),this.disconnectionPromise?this.disconnectionPromise:(e.code=e.code||1e3,this.statusTransition(i.STATUS_CLOSING,e.force)?(this.emit("disconnecting"),this.disconnectionPromise=new Promise((function(r,i){t.disconnectDeferredResolve=r,t.reconnectTimer&&(clearTimeout(t.reconnectTimer),t.reconnectTimer=void 0),t.ws?(t.stopSendingKeepAlives(),t.logger.log("closing WebSocket "+t.server.wsUri),t.ws.close(e.code,e.reason)):i("Attempted to disconnect but the websocket doesn't exist")})),this.disconnectionPromise):this.status===i.STATUS_CLOSED?Promise.resolve({overrideEvent:!0}):this.connectionPromise?this.connectionPromise.then((function(){return Promise.reject("The websocket did not disconnect")})).catch((function(){return Promise.resolve({overrideEvent:!0})})):Promise.reject("The websocket did not disconnect"))},t.prototype.connectPromise=function(e){var t=this;return void 0===e&&(e={}),this.status!==i.STATUS_CLOSING||e.force?this.connectionPromise?this.connectionPromise:(this.server=this.server||this.getNextWsServer(e.force),this.connectionPromise=new Promise((function(r,n){if((t.status===i.STATUS_OPEN||t.status===i.STATUS_CLOSING)&&!e.force)return t.logger.warn("WebSocket "+t.server.wsUri+" is already connected"),void n("Failed status check - attempted to open a connection but already open/closing");t.connectDeferredResolve=r,t.connectDeferredReject=n,t.status=i.STATUS_CONNECTING,t.emit("connecting"),t.logger.log("connecting to WebSocket "+t.server.wsUri),t.disposeWs();try{t.ws=new WebSocket(t.server.wsUri,"sip")}catch(e){return t.ws=null,t.statusTransition(i.STATUS_CLOSED,!0),t.onError("error connecting to WebSocket "+t.server.wsUri+":"+e),n("Failed to create a websocket"),t.connectDeferredResolve=void 0,void(t.connectDeferredReject=void 0)}if(!t.ws)return n("Unexpected instance websocket not set"),t.connectDeferredResolve=void 0,void(t.connectDeferredReject=void 0);t.connectionTimeout=setTimeout((function(){t.statusTransition(i.STATUS_CLOSED),t.logger.warn("took too long to connect - exceeded time set in configuration.connectionTimeout: "+t.configuration.connectionTimeout+"s"),t.emit("disconnected",{code:1e3}),t.connectionPromise=void 0,n("Connection timeout"),t.connectDeferredResolve=void 0,t.connectDeferredReject=void 0;var e=t.ws;t.disposeWs(),e.close(1e3)}),1e3*t.configuration.connectionTimeout),t.boundOnOpen=t.onOpen.bind(t),t.boundOnMessage=t.onMessage.bind(t),t.boundOnClose=t.onClose.bind(t),t.boundOnError=t.onWebsocketError.bind(t),t.ws.addEventListener("open",t.boundOnOpen),t.ws.addEventListener("message",t.boundOnMessage),t.ws.addEventListener("close",t.boundOnClose),t.ws.addEventListener("error",t.boundOnError)})),this.connectionPromise):Promise.reject("WebSocket "+this.server.wsUri+" is closing")},t.prototype.onMessage=function(e){var t,r=e.data;if(/^(\r\n)+$/.test(r))return this.clearKeepAliveTimeout(),void(!0===this.configuration.traceSip&&this.logger.log("received WebSocket message with CRLF Keep Alive response"));if(r){if("string"!=typeof r){try{t=String.fromCharCode.apply(null,new Uint8Array(r))}catch(e){return void this.logger.warn("received WebSocket binary message failed to be converted into string, message discarded")}!0===this.configuration.traceSip&&this.logger.log("received WebSocket binary message:\n\n"+r+"\n")}else!0===this.configuration.traceSip&&this.logger.log("received WebSocket text message:\n\n"+r+"\n"),t=r;this.emit("message",t)}else this.logger.warn("received empty message, message discarded")},t.prototype.onOpen=function(){if(this.status===i.STATUS_CLOSED){var e=this.ws;return this.disposeWs(),void e.close(1e3)}this.statusTransition(i.STATUS_OPEN,!0),this.emit("connected"),this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=void 0),this.logger.log("WebSocket "+this.server.wsUri+" connected"),void 0!==this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.reconnectionAttempts=0,this.disconnectionPromise=void 0,this.disconnectDeferredResolve=void 0,this.startSendingKeepAlives(),this.connectDeferredResolve?(this.connectDeferredResolve({overrideEvent:!0}),this.connectDeferredResolve=void 0,this.connectDeferredReject=void 0):this.logger.warn("Unexpected websocket.onOpen with no connectDeferredResolve")},t.prototype.onClose=function(e){if(this.logger.log("WebSocket disconnected (code: "+e.code+(e.reason?"| reason: "+e.reason:"")+")"),this.status!==i.STATUS_CLOSING&&(this.logger.warn("WebSocket closed without SIP.js requesting it"),this.emit("transportError")),this.stopSendingKeepAlives(),this.connectionTimeout&&clearTimeout(this.connectionTimeout),this.connectDeferredReject&&this.connectDeferredReject("Websocket Closed"),this.connectionTimeout=void 0,this.connectionPromise=void 0,this.connectDeferredResolve=void 0,this.connectDeferredReject=void 0,this.disconnectDeferredResolve)return this.disconnectDeferredResolve({overrideEvent:!0}),this.statusTransition(i.STATUS_CLOSED),void(this.disconnectDeferredResolve=void 0);this.statusTransition(i.STATUS_CLOSED,!0),this.emit("disconnected",{code:e.code,reason:e.reason}),this.disposeWs(),this.reconnect()},t.prototype.disposeWs=function(){this.ws&&(this.ws.removeEventListener("open",this.boundOnOpen),this.ws.removeEventListener("message",this.boundOnMessage),this.ws.removeEventListener("close",this.boundOnClose),this.ws.removeEventListener("error",this.boundOnError),this.ws=void 0)},t.prototype.onError=function(e){this.logger.warn("Transport error: "+e),this.emit("transportError")},t.prototype.onWebsocketError=function(){this.onError("The Websocket had an error")},t.prototype.reconnect=function(){var e=this;if(this.reconnectionAttempts>0&&this.logger.log("Reconnection attempt "+this.reconnectionAttempts+" failed"),this.noAvailableServers())return this.logger.warn("attempted to get next ws server but there are no available ws servers left"),this.logger.warn("no available ws servers left - going to closed state"),this.statusTransition(i.STATUS_CLOSED,!0),this.emit("closed"),void this.resetServerErrorStatus();this.isConnected()&&(this.logger.warn("attempted to reconnect while connected - forcing disconnect"),this.disconnect({force:!0})),this.reconnectionAttempts+=1,this.reconnectionAttempts>this.configuration.maxReconnectionAttempts?(this.logger.warn("maximum reconnection attempts for WebSocket "+this.server.wsUri),this.logger.log("transport "+this.server.wsUri+" failed | connection state set to 'error'"),this.server.isError=!0,this.emit("transportError"),this.noAvailableServers()||(this.server=this.getNextWsServer()),this.reconnectionAttempts=0,this.reconnect()):(this.logger.log("trying to reconnect to WebSocket "+this.server.wsUri+" (reconnection attempt "+this.reconnectionAttempts+")"),this.reconnectTimer=setTimeout((function(){e.connect(),e.reconnectTimer=void 0}),1===this.reconnectionAttempts?0:1e3*this.configuration.reconnectionTimeout))},t.prototype.resetServerErrorStatus=function(){for(var e=0,t=this.configuration.wsServers;et[0].weight?t=[n]:n.weight===t[0].weight&&t.push(n))}return t[Math.floor(Math.random()*t.length)]},t.prototype.noAvailableServers=function(){for(var e=0,t=this.configuration.wsServers;e",weight:0,wsUri:"wss://edge.sip.onsip.com",isError:!1}],connectionTimeout:5,maxReconnectionAttempts:3,reconnectionTimeout:4,keepAliveInterval:0,keepAliveDebounce:10,traceSip:!1},r=this.getConfigurationCheck();for(var i in r.mandatory){if(!e.hasOwnProperty(i))throw new a.Exceptions.ConfigurationError(i);var n=e[i];if(void 0===(s=r.mandatory[i](n)))throw new a.Exceptions.ConfigurationError(i,n);t[i]=s}for(var i in r.optional)if(e.hasOwnProperty(i)){var s;if((n=e[i])instanceof Array&&0===n.length||null===n||""===n||void 0===n||"number"==typeof n&&isNaN(n))continue;if(void 0===(s=r.optional[i](n)))throw new a.Exceptions.ConfigurationError(i,n);t[i]=s}var o={};for(var i in t)t.hasOwnProperty(i)&&(o[i]={value:t[i]});var c=Object.defineProperties({},o);for(var i in this.logger.log("configuration parameters after validation:"),t)t.hasOwnProperty(i)&&this.logger.log("\xb7 "+i+": "+JSON.stringify(t[i]));return c},t.prototype.getConfigurationCheck=function(){return{mandatory:{},optional:{wsServers:function(e){if("string"==typeof e)e=[{wsUri:e}];else{if(!(e instanceof Array))return;for(var t=0;t",n.weight||(n.weight=0),n.isError=!1,n.scheme=o.scheme.toUpperCase()}return e},keepAliveInterval:function(e){if(c.Utils.isDecimal(e)){var t=Number(e);if(t>0)return t}},keepAliveDebounce:function(e){if(c.Utils.isDecimal(e)){var t=Number(e);if(t>0)return t}},traceSip:function(e){if("boolean"==typeof e)return e},connectionTimeout:function(e){if(c.Utils.isDecimal(e)){var t=Number(e);if(t>0)return t}},maxReconnectionAttempts:function(e){if(c.Utils.isDecimal(e)){var t=Number(e);if(t>=0)return t}},reconnectionTimeout:function(e){if(c.Utils.isDecimal(e)){var t=Number(e);if(t>0)return t}}}}},t.C=i,t}(s.Transport);t.Transport=u},,function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(51),s=r(11),o=r(5),a=r(8),c=r(12),u=r(90),d=function(e){function t(t,r,i,n){void 0===n&&(n={});var o=this;if(void 0===t||void 0===r||void 0===i)throw new TypeError("Not enough arguments");return(o=e.call(this,t,s.C.REFER,r.remoteIdentity.uri.toString(),n)||this).type=a.TypeStrings.ReferClientContext,o.options=n,o.extraHeaders=(o.options.extraHeaders||[]).slice(),o.applicant=r,o.target=o.initReferTo(i),o.ua&&o.extraHeaders.push("Referred-By: <"+o.ua.configuration.uri+">"),o.extraHeaders.push("Contact: "+r.contact),o.extraHeaders.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),o.extraHeaders.push("Refer-To: "+o.target),o.errorListener=o.onTransportError.bind(o),t.transport&&t.transport.on("transportError",o.errorListener),o}return i.__extends(t,e),t.prototype.refer=function(e){var t=this;void 0===e&&(e={});var r=(this.extraHeaders||[]).slice();return e.extraHeaders&&r.concat(e.extraHeaders),this.applicant.sendRequest(s.C.REFER,{extraHeaders:this.extraHeaders,receiveResponse:function(r){var i=r&&r.statusCode?r.statusCode.toString():"";/^1[0-9]{2}$/.test(i)?t.emit("referRequestProgress",t):/^2[0-9]{2}$/.test(i)?t.emit("referRequestAccepted",t):/^[4-6][0-9]{2}$/.test(i)&&t.emit("referRequestRejected",t),e.receiveResponse&&e.receiveResponse(r)}}),this},t.prototype.receiveNotify=function(e){var t=e.message.hasHeader("Content-Type")?e.message.getHeader("Content-Type"):void 0;if(t&&-1!==t.search(/^message\/sipfrag/)){var r=o.Grammar.parse(e.message.body,"sipfrag");if(-1===r)return void e.reject({statusCode:489,reasonPhrase:"Bad Event"});switch(!0){case/^1[0-9]{2}$/.test(r.status_code):this.emit("referProgress",this);break;case/^2[0-9]{2}$/.test(r.status_code):this.emit("referAccepted",this),!this.options.activeAfterTransfer&&this.applicant.terminate&&this.applicant.terminate();break;default:this.emit("referRejected",this)}return e.accept(),void this.emit("notify",e.message)}e.reject({statusCode:489,reasonPhrase:"Bad Event"})},t.prototype.initReferTo=function(e){var t;if("string"==typeof e){var r=o.Grammar.parse(e,"Refer_To");t=r&&r.uri?r.uri:e;var i=this.ua.normalizeTarget(e);if(!i)throw new TypeError("Invalid target: "+e);t=i}else{if(!e.session)throw new Error("Session undefined.");var n=e.remoteIdentity.friendlyName,s=e.session.remoteTarget.toString(),a=e.session.callId,c=e.session.remoteTag,u=e.session.localTag;t='"'+n+'" <'+s+"?Replaces="+encodeURIComponent(a+";to-tag="+c+";from-tag="+u)+">"}return t},t}(n.ClientContext);t.ReferClientContext=d;var p=function(e){function t(t,r,i){var n=e.call(this,t,r)||this;return n.session=i,n.type=a.TypeStrings.ReferServerContext,n.ua=t,n.status=a.SessionStatus.STATUS_INVITE_RECEIVED,n.fromTag=n.request.fromTag,n.id=n.request.callId+n.fromTag,n.contact=n.ua.contact.toString(),n.logger=t.getLogger("sip.referservercontext",n.id),n.cseq=Math.floor(1e4*Math.random()),n.callId=n.request.callId,n.fromUri=n.request.to.uri,n.fromTag=n.request.to.parameters.tag,n.remoteTarget=n.request.headers.Contact[0].parsed.uri,n.toUri=n.request.from.uri,n.toTag=n.request.fromTag,n.routeSet=n.request.getHeaders("record-route"),n.request.hasHeader("refer-to")?(n.referTo=n.request.parseHeader("refer-to"),n.referredSession=n.ua.findSession(n.request),n.request.hasHeader("referred-by")&&(n.referredBy=n.request.getHeader("referred-by")),n.referTo.uri.hasHeader("replaces")&&(n.replaces=n.referTo.uri.getHeader("replaces")),n.errorListener=n.onTransportError.bind(n),t.transport&&t.transport.on("transportError",n.errorListener),n.status=a.SessionStatus.STATUS_WAITING_FOR_ANSWER,n):(n.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting refer."),n.reject(),n)}return i.__extends(t,e),t.prototype.progress=function(){if(this.status!==a.SessionStatus.STATUS_WAITING_FOR_ANSWER)throw new c.Exceptions.InvalidStateError(this.status);this.incomingRequest.trying()},t.prototype.reject=function(t){if(void 0===t&&(t={}),this.status===a.SessionStatus.STATUS_TERMINATED)throw new c.Exceptions.InvalidStateError(this.status);this.logger.log("Rejecting refer"),this.status=a.SessionStatus.STATUS_TERMINATED,e.prototype.reject.call(this,t),this.emit("referRequestRejected",this)},t.prototype.accept=function(e,t){var r=this;if(void 0===e&&(e={}),this.status!==a.SessionStatus.STATUS_WAITING_FOR_ANSWER)throw new c.Exceptions.InvalidStateError(this.status);if(this.status=a.SessionStatus.STATUS_ANSWERED,this.incomingRequest.accept({statusCode:202,reasonPhrase:"Accepted"}),this.emit("referRequestAccepted",this),e.followRefer){this.logger.log("Accepted refer, attempting to automatically follow it");var i=this.referTo.uri;if(!i.scheme||!i.scheme.match("^sips?$"))return this.logger.error("SIP.js can only automatically follow SIP refer target"),void this.reject();var n=e.inviteOptions||{},s=(n.extraHeaders||[]).slice();if(this.replaces&&s.push("Replaces: "+decodeURIComponent(this.replaces)),this.referredBy&&s.push("Referred-By: "+this.referredBy),n.extraHeaders=s,i.clearHeaders(),this.targetSession=this.ua.invite(i.toString(),n,t),this.emit("referInviteSent",this),this.targetSession){this.targetSession.once("progress",(function(e){var t=e.statusCode||100,i=e.reasonPhrase;r.sendNotify(("SIP/2.0 "+t+" "+i).trim()),r.emit("referProgress",r),r.referredSession&&r.referredSession.emit("referProgress",r)})),this.targetSession.once("accepted",(function(){r.logger.log("Successfully followed the refer"),r.sendNotify("SIP/2.0 200 OK"),r.emit("referAccepted",r),r.referredSession&&r.referredSession.emit("referAccepted",r)}));var o=function(e){if(r.status!==a.SessionStatus.STATUS_TERMINATED){if(r.logger.log("Refer was not successful. Resuming session"),e&&429===e.statusCode)return r.logger.log("Alerting referrer that identity is required."),void r.sendNotify("SIP/2.0 429 Provide Referrer Identity");r.sendNotify("SIP/2.0 603 Declined"),r.status=a.SessionStatus.STATUS_TERMINATED,r.emit("referRejected",r),r.referredSession&&r.referredSession.emit("referRejected")}};this.targetSession.once("rejected",o),this.targetSession.once("failed",o)}}else this.logger.log("Accepted refer, but did not automatically follow it"),this.sendNotify("SIP/2.0 200 OK"),this.emit("referAccepted",this),this.referredSession&&this.referredSession.emit("referAccepted",this)},t.prototype.sendNotify=function(e){if(this.status!==a.SessionStatus.STATUS_ANSWERED)throw new c.Exceptions.InvalidStateError(this.status);if(-1===o.Grammar.parse(e,"sipfrag"))throw new Error("sipfrag body is required to send notify for refer");var t={contentDisposition:"render",contentType:"message/sipfrag",content:e};if(this.session)this.session.notify(void 0,{extraHeaders:["Event: refer","Subscription-State: terminated"],body:t});else{var r=this.ua.userAgentCore.makeOutgoingRequestMessage(s.C.NOTIFY,this.remoteTarget,this.fromUri,this.toUri,{cseq:this.cseq+=1,callId:this.callId,fromTag:this.fromTag,toTag:this.toTag,routeSet:this.routeSet},["Event: refer","Subscription-State: terminated","Content-Type: message/sipfrag"],t),i=this.ua.transport;if(!i)throw new Error("Transport undefined.");var n={loggerFactory:this.ua.getLoggerFactory()};new o.NonInviteClientTransaction(r,i,n)}},t.prototype.on=function(t,r){return e.prototype.on.call(this,t,r)},t}(u.ServerContext);t.ReferServerContext=p},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(8),n=function(){function e(e,t){this.type=i.TypeStrings.SessionDescriptionHandlerObserver,this.session=e,this.options=t}return e.prototype.trackAdded=function(){this.session.emit("trackAdded")},e.prototype.directionChanged=function(){this.session.emit("directionChanged")},e}();t.SessionDescriptionHandlerObserver=n},,,function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(51),s=r(11),o=r(5),a=r(8),c=r(12),u=r(9),d=function(e){function t(t,r,i,n){void 0===n&&(n={});var o=this;if(n.extraHeaders=(n.extraHeaders||[]).slice(),n.contentType=n.contentType||"text/plain","number"!=typeof n.expires||n.expires%1!=0?n.expires=3600:n.expires=Number(n.expires),"boolean"!=typeof n.unpublishOnClose&&(n.unpublishOnClose=!0),null==r||""===r)throw new c.Exceptions.MethodParameterError("Publish","Target",r);if(void 0===(r=t.normalizeTarget(r)))throw new c.Exceptions.MethodParameterError("Publish","Target",r);if((o=e.call(this,t,s.C.PUBLISH,r,n)||this).type=a.TypeStrings.PublishContext,o.options=n,o.target=r,null==i||""===i)throw new c.Exceptions.MethodParameterError("Publish","Event",i);return o.event=i,o.logger=t.getLogger("sip.publish"),o.pubRequestExpires=o.options.expires,o}return i.__extends(t,e),t.prototype.publish=function(e){this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.options.body=e,this.pubRequestBody=this.options.body,0===this.pubRequestExpires&&(this.pubRequestExpires=this.options.expires,this.pubRequestEtag=void 0),this.ua.publishers[this.target.toString()+":"+this.event]||(this.ua.publishers[this.target.toString()+":"+this.event]=this),this.sendPublishRequest()},t.prototype.unpublish=function(){this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,this.pubRequestExpires=0,void 0!==this.pubRequestEtag&&this.sendPublishRequest()},t.prototype.close=function(){this.options.unpublishOnClose?this.unpublish():(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,this.pubRequestExpires=0,this.pubRequestEtag=void 0),this.ua.publishers[this.target.toString()+":"+this.event]&&delete this.ua.publishers[this.target.toString()+":"+this.event]},t.prototype.onRequestTimeout=function(){e.prototype.onRequestTimeout.call(this),this.emit("unpublished",void 0,s.C.causes.REQUEST_TIMEOUT)},t.prototype.onTransportError=function(){e.prototype.onTransportError.call(this),this.emit("unpublished",void 0,s.C.causes.CONNECTION_ERROR)},t.prototype.receiveResponse=function(e){var t=this,r=e.statusCode||0,i=u.Utils.getReasonPhrase(r);switch(!0){case/^1[0-9]{2}$/.test(r.toString()):this.emit("progress",e,i);break;case/^2[0-9]{2}$/.test(r.toString()):if(e.hasHeader("SIP-ETag")?this.pubRequestEtag=e.getHeader("SIP-ETag"):this.logger.warn("SIP-ETag header missing in a 200-class response to PUBLISH"),e.hasHeader("Expires")){var n=Number(e.getHeader("Expires"));"number"==typeof n&&n>=0&&n<=this.pubRequestExpires?this.pubRequestExpires=n:this.logger.warn("Bad Expires header in a 200-class response to PUBLISH")}else this.logger.warn("Expires header missing in a 200-class response to PUBLISH");0!==this.pubRequestExpires?(this.publishRefreshTimer=setTimeout((function(){return t.refreshRequest()}),900*this.pubRequestExpires),this.emit("published",e,i)):this.emit("unpublished",e,i);break;case/^412$/.test(r.toString()):void 0!==this.pubRequestEtag&&0!==this.pubRequestExpires?(this.logger.warn("412 response to PUBLISH, recovering"),this.pubRequestEtag=void 0,this.emit("progress",e,i),this.publish(this.options.body)):(this.logger.warn("412 response to PUBLISH, recovery failed"),this.pubRequestExpires=0,this.emit("failed",e,i),this.emit("unpublished",e,i));break;case/^423$/.test(r.toString()):if(0!==this.pubRequestExpires&&e.hasHeader("Min-Expires")){var s=Number(e.getHeader("Min-Expires"));"number"==typeof s||s>this.pubRequestExpires?(this.logger.warn("423 code in response to PUBLISH, adjusting the Expires value and trying to recover"),this.pubRequestExpires=s,this.emit("progress",e,i),this.publish(this.options.body)):(this.logger.warn("Bad 423 response Min-Expires header received for PUBLISH"),this.pubRequestExpires=0,this.emit("failed",e,i),this.emit("unpublished",e,i))}else this.logger.warn("423 response to PUBLISH, recovery failed"),this.pubRequestExpires=0,this.emit("failed",e,i),this.emit("unpublished",e,i);break;default:this.pubRequestExpires=0,this.emit("failed",e,i),this.emit("unpublished",e,i)}0===this.pubRequestExpires&&(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,this.pubRequestEtag=void 0)},t.prototype.send=function(){var e=this;return this.ua.userAgentCore.publish(this.request,{onAccept:function(t){return e.receiveResponse(t.message)},onProgress:function(t){return e.receiveResponse(t.message)},onRedirect:function(t){return e.receiveResponse(t.message)},onReject:function(t){return e.receiveResponse(t.message)},onTrying:function(t){return e.receiveResponse(t.message)}}),this},t.prototype.refreshRequest=function(){if(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,void 0===this.pubRequestEtag)throw new c.Exceptions.MethodParameterError("Publish","Body",void 0);if(0===this.pubRequestExpires)throw new c.Exceptions.MethodParameterError("Publish","Expire",this.pubRequestExpires);this.sendPublishRequest()},t.prototype.sendPublishRequest=function(){var e=Object.create(this.options||Object.prototype);e.extraHeaders=(this.options.extraHeaders||[]).slice(),e.extraHeaders.push("Event: "+this.event),e.extraHeaders.push("Expires: "+this.pubRequestExpires),void 0!==this.pubRequestEtag&&e.extraHeaders.push("SIP-If-Match: "+this.pubRequestEtag);var t=this.target instanceof o.URI?this.target:this.ua.normalizeTarget(this.target);if(!t)throw new Error("ruri undefined.");var r,i,n=this.options.params||{};void 0!==this.pubRequestBody&&(r={body:this.pubRequestBody,contentType:this.options.contentType}),r&&(i=u.Utils.fromBodyObj(r)),this.request=this.ua.userAgentCore.makeOutgoingRequestMessage(s.C.PUBLISH,t,n.fromUri?n.fromUri:this.ua.userAgentCore.configuration.aor,n.toUri?n.toUri:this.target,n,e.extraHeaders,i),this.send()},t}(n.ClientContext);t.PublishContext=d},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(51),s=r(11),o=r(5),a=r(8),c=r(12),u=r(9);function d(e){var t={expires:600,extraContactHeaderParams:[],instanceId:void 0,params:{},regId:void 0,registrar:void 0},r={mandatory:{},optional:{expires:function(e){if(u.Utils.isDecimal(e)){var t=Number(e);if(t>=0)return t}},extraContactHeaderParams:function(e){if(e instanceof Array)return e.filter((function(e){return"string"==typeof e}))},instanceId:function(e){if("string"==typeof e)return/^uuid:/i.test(e)&&(e=e.substr(5)),-1===o.Grammar.parse(e,"uuid")?void 0:e},params:function(e){if("object"==typeof e)return e},regId:function(e){if(u.Utils.isDecimal(e)){var t=Number(e);if(t>=0)return t}},registrar:function(e){if("string"==typeof e){/^sip:/i.test(e)||(e=s.C.SIP+":"+e);var t=o.Grammar.URIParse(e);return t?t.user?void 0:t:void 0}}}};for(var i in r.mandatory){if(!e.hasOwnProperty(i))throw new c.Exceptions.ConfigurationError(i);var n=e[i];if(void 0===(a=r.mandatory[i](n)))throw new c.Exceptions.ConfigurationError(i,n);t[i]=a}for(var i in r.optional)if(e.hasOwnProperty(i)){var a;if((n=e[i])instanceof Array&&0===n.length)continue;if(null===n||""===n||void 0===n||"number"==typeof n&&isNaN(n))continue;if(void 0===(a=r.optional[i](n)))throw new c.Exceptions.ConfigurationError(i,n);t[i]=a}return t}var p=function(e){function t(t,r){void 0===r&&(r={});var i=this,n=d(r);if(n.regId&&!n.instanceId?n.instanceId=u.Utils.newUUID():!n.regId&&n.instanceId&&(n.regId=1),n.params.toUri=n.params.toUri||t.configuration.uri,n.params.toDisplayName=n.params.toDisplayName||t.configuration.displayName,n.params.callId=n.params.callId||u.Utils.createRandomToken(22),n.params.cseq=n.params.cseq||Math.floor(1e4*Math.random()),!n.registrar){var o={};"object"==typeof t.configuration.uri?(o=t.configuration.uri.clone()).user=void 0:o=t.configuration.uri,n.registrar=o}for(var c in(i=e.call(this,t,s.C.REGISTER,n.registrar,n)||this).type=a.TypeStrings.RegisterContext,i.options=n,i.logger=t.getLogger("sip.registercontext"),i.logger.log("configuration parameters for RegisterContext after validation:"),n)n.hasOwnProperty(c)&&i.logger.log("\xb7 "+c+": "+JSON.stringify(n[c]));return i.expires=n.expires,i.contact=t.contact.toString(),i.registered=!1,t.transport.on("disconnected",(function(){return i.onTransportDisconnected()})),i}return i.__extends(t,e),t.prototype.register=function(e){var t=this;void 0===e&&(e={}),this.options=i.__assign({},this.options,e);var r=(this.options.extraHeaders||[]).slice();r.push("Contact: "+this.generateContactHeader(this.expires)),r.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),this.closeHeaders=this.options.closeWithHeaders?(this.options.extraHeaders||[]).slice():[],this.receiveResponse=function(e){if(e.cseq===t.request.cseq){void 0!==t.registrationTimer&&(clearTimeout(t.registrationTimer),t.registrationTimer=void 0);var r=(e.statusCode||0).toString();switch(!0){case/^1[0-9]{2}$/.test(r):t.emit("progress",e);break;case/^2[0-9]{2}$/.test(r):t.emit("accepted",e);var i=void 0;e.hasHeader("expires")&&(i=Number(e.getHeader("expires"))),void 0!==t.registrationExpiredTimer&&(clearTimeout(t.registrationExpiredTimer),t.registrationExpiredTimer=void 0);var n=e.getHeaders("contact").length;if(!n){t.logger.warn("no Contact header in response to REGISTER, response ignored");break}for(var a=void 0;n--;){if((a=e.parseHeader("contact",n)).uri.user===t.ua.contact.uri.user){i=a.getParam("expires");break}a=void 0}if(!a){t.logger.warn("no Contact header pointing to us, response ignored");break}void 0===i&&(i=t.expires),t.registrationTimer=setTimeout((function(){t.registrationTimer=void 0,t.register(t.options)}),1e3*i-3e3),t.registrationExpiredTimer=setTimeout((function(){t.logger.warn("registration expired"),t.registered&&t.unregistered(void 0,s.C.causes.EXPIRES)}),1e3*i),a.hasParam("temp-gruu")&&(t.ua.contact.tempGruu=o.Grammar.URIParse(a.getParam("temp-gruu").replace(/"/g,""))),a.hasParam("pub-gruu")&&(t.ua.contact.pubGruu=o.Grammar.URIParse(a.getParam("pub-gruu").replace(/"/g,""))),t.registered=!0,t.emit("registered",e||void 0);break;case/^423$/.test(r):e.hasHeader("min-expires")?(t.expires=Number(e.getHeader("min-expires")),t.register(t.options)):(t.logger.warn("423 response received for REGISTER without Min-Expires"),t.registrationFailure(e,s.C.causes.SIP_FAILURE_CODE));break;default:t.registrationFailure(e,u.Utils.sipErrorCause(e.statusCode||0))}}},this.onRequestTimeout=function(){t.registrationFailure(void 0,s.C.causes.REQUEST_TIMEOUT)},this.onTransportError=function(){t.registrationFailure(void 0,s.C.causes.CONNECTION_ERROR)},this.request.cseq++,this.request.setHeader("cseq",this.request.cseq+" REGISTER"),this.request.extraHeaders=r,this.send()},t.prototype.close=function(){var e={all:!1,extraHeaders:this.closeHeaders};this.registeredBefore=this.registered,this.registered&&this.unregister(e)},t.prototype.unregister=function(e){var t=this;void 0===e&&(e={}),this.registered||e.all||this.logger.warn("Already unregistered, but sending an unregister anyways.");var r=(e.extraHeaders||[]).slice();this.registered=!1,void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),e.all?(r.push("Contact: *"),r.push("Expires: 0")):r.push("Contact: "+this.generateContactHeader(0)),this.receiveResponse=function(e){var r=e&&e.statusCode?e.statusCode.toString():"";switch(!0){case/^1[0-9]{2}$/.test(r):t.emit("progress",e);break;case/^2[0-9]{2}$/.test(r):t.emit("accepted",e),void 0!==t.registrationExpiredTimer&&(clearTimeout(t.registrationExpiredTimer),t.registrationExpiredTimer=void 0),t.unregistered(e);break;default:t.unregistered(e,u.Utils.sipErrorCause(e.statusCode||0))}},this.onRequestTimeout=function(){},this.request.cseq++,this.request.setHeader("cseq",this.request.cseq+" REGISTER"),this.request.extraHeaders=r,this.send()},t.prototype.unregistered=function(e,t){this.registered=!1,this.emit("unregistered",e||void 0,t||void 0)},t.prototype.send=function(){var e=this;return this.ua.userAgentCore.register(this.request,{onAccept:function(t){return e.receiveResponse(t.message)},onProgress:function(t){return e.receiveResponse(t.message)},onRedirect:function(t){return e.receiveResponse(t.message)},onReject:function(t){return e.receiveResponse(t.message)},onTrying:function(t){return e.receiveResponse(t.message)}}),this},t.prototype.registrationFailure=function(e,t){this.emit("failed",e||void 0,t||void 0)},t.prototype.onTransportDisconnected=function(){this.registeredBefore=this.registered,void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),void 0!==this.registrationExpiredTimer&&(clearTimeout(this.registrationExpiredTimer),this.registrationExpiredTimer=void 0),this.registered&&this.unregistered(void 0,s.C.causes.CONNECTION_ERROR)},t.prototype.generateContactHeader=function(e){void 0===e&&(e=0);var t=this.contact;return this.options.regId&&this.options.instanceId&&(t+=";reg-id="+this.options.regId,t+=';+sip.instance=""'),this.options.extraContactHeaderParams&&this.options.extraContactHeaderParams.forEach((function(e){t+=";"+e})),t+=";expires="+e},t}(n.ClientContext);t.RegisterContext=p},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(7),s=r(51),o=r(11),a=r(5),c=r(8),u=r(12),d=r(96),p=r(90),h=r(110),l=r(9),g=function(e){function t(r){var i=e.call(this)||this;if(i.data={},i.type=c.TypeStrings.Session,!r)throw new u.Exceptions.SessionDescriptionHandlerError("A session description handler is required for the session to function");return i.status=t.C.STATUS_NULL,i.pendingReinvite=!1,i.sessionDescriptionHandlerFactory=r,i.hasOffer=!1,i.hasAnswer=!1,i.timers={ackTimer:void 0,expiresTimer:void 0,invite2xxTimer:void 0,userNoAnswerTimer:void 0,rel1xxTimer:void 0,prackTimer:void 0},i.startTime=void 0,i.endTime=void 0,i.tones=void 0,i.localHold=!1,i.earlySdp=void 0,i.rel100=o.C.supported.UNSUPPORTED,i}return i.__extends(t,e),t.prototype.dtmf=function(e,t){var r=this;if(void 0===t&&(t={}),this.status!==c.SessionStatus.STATUS_CONFIRMED&&this.status!==c.SessionStatus.STATUS_WAITING_FOR_ACK)throw new u.Exceptions.InvalidStateError(this.status);if(!e||!e.toString().match(/^[0-9A-D#*,]+$/i))throw new TypeError("Invalid tones: "+e);var i=function(){if(r.status!==c.SessionStatus.STATUS_TERMINATED&&r.tones&&0!==r.tones.length){var e,n=r.tones.shift();","===n.tone?e=2e3:(n.on("failed",(function(){r.tones=void 0})),n.send(t),e=n.duration+n.interToneGap),setTimeout(i,e)}else r.tones=void 0};e=e.toString();var n=this.ua.configuration.dtmfType;this.sessionDescriptionHandler&&n===o.C.dtmfType.RTP&&(this.sessionDescriptionHandler.sendDtmf(e,t)||(this.logger.warn("Attempt to use dtmfType 'RTP' has failed, falling back to INFO packet method"),n=o.C.dtmfType.INFO));if(n===o.C.dtmfType.INFO){for(var s=[],a=e.split("");a.length>0;)s.push(new h.DTMF(this,a.shift(),t));if(this.tones)return this.tones=this.tones.concat(s),this;this.tones=s,i()}return this},t.prototype.bye=function(e){if(void 0===e&&(e={}),this.status===c.SessionStatus.STATUS_TERMINATED)return this.logger.error("Error: Attempted to send BYE in a terminated session."),this;this.logger.log("terminating Session");var t=e.statusCode;if(t&&(t<200||t>=700))throw new TypeError("Invalid statusCode: "+t);return e.receiveResponse=function(){},this.sendRequest(o.C.BYE,e).terminated()},t.prototype.refer=function(e,t){if(void 0===t&&(t={}),this.status!==c.SessionStatus.STATUS_CONFIRMED)throw new u.Exceptions.InvalidStateError(this.status);return this.referContext=new d.ReferClientContext(this.ua,this,e,t),this.emit("referRequested",this.referContext),this.referContext.refer(t),this.referContext},t.prototype.sendRequest=function(e,t){if(void 0===t&&(t={}),!this.session)throw new Error("Session undefined.");var r;t.body&&(t.body=l.Utils.fromBodyObj(t.body));var i,n=t.receiveResponse;n&&(r={onAccept:function(e){return n(e.message)},onProgress:function(e){return n(e.message)},onRedirect:function(e){return n(e.message)},onReject:function(e){return n(e.message)},onTrying:function(e){return n(e.message)}});var s=t;switch(e){case o.C.BYE:i=this.session.bye(r,s);break;case o.C.INVITE:i=this.session.invite(r,s);break;case o.C.REFER:i=this.session.refer(r,s);break;default:throw new Error("Unexpected "+e+". Method not implemented by user agent core.")}return this.emit(e.toLowerCase(),i.message),this},t.prototype.close=function(){if(this.status===c.SessionStatus.STATUS_TERMINATED)return this;for(var e in this.logger.log("closing INVITE session "+this.id),this.sessionDescriptionHandler&&this.sessionDescriptionHandler.close(),this.timers)this.timers[e]&&clearTimeout(this.timers[e]);return this.status=c.SessionStatus.STATUS_TERMINATED,this.ua.transport&&this.ua.transport.removeListener("transportError",this.errorListener),delete this.ua.sessions[this.id],this},t.prototype.hold=function(e,t){if(void 0===e&&(e={}),void 0===t&&(t=[]),this.status!==c.SessionStatus.STATUS_WAITING_FOR_ACK&&this.status!==c.SessionStatus.STATUS_CONFIRMED)throw new u.Exceptions.InvalidStateError(this.status);this.localHold?this.logger.log("Session is already on hold, cannot put it on hold again"):(e.modifiers=t,this.sessionDescriptionHandler&&e.modifiers.push(this.sessionDescriptionHandler.holdModifier),this.localHold=!0,this.sendReinvite(e))},t.prototype.unhold=function(e,t){if(void 0===e&&(e={}),void 0===t&&(t=[]),this.status!==c.SessionStatus.STATUS_WAITING_FOR_ACK&&this.status!==c.SessionStatus.STATUS_CONFIRMED)throw new u.Exceptions.InvalidStateError(this.status);this.localHold?(e.modifiers=t,this.localHold=!1,this.sendReinvite(e)):this.logger.log("Session is not on hold, cannot unhold it")},t.prototype.reinvite=function(e,t){return void 0===e&&(e={}),void 0===t&&(t=[]),e.modifiers=t,this.sendReinvite(e)},t.prototype.terminate=function(e){return this},t.prototype.onTransportError=function(){this.status!==c.SessionStatus.STATUS_CONFIRMED&&this.status!==c.SessionStatus.STATUS_TERMINATED&&this.failed(void 0,o.C.causes.CONNECTION_ERROR)},t.prototype.onRequestTimeout=function(){this.status===c.SessionStatus.STATUS_CONFIRMED?this.terminated(void 0,o.C.causes.REQUEST_TIMEOUT):this.status!==c.SessionStatus.STATUS_TERMINATED&&(this.failed(void 0,o.C.causes.REQUEST_TIMEOUT),this.terminated(void 0,o.C.causes.REQUEST_TIMEOUT))},t.prototype.onDialogError=function(e){this.status===c.SessionStatus.STATUS_CONFIRMED?this.terminated(e,o.C.causes.DIALOG_ERROR):this.status!==c.SessionStatus.STATUS_TERMINATED&&(this.failed(e,o.C.causes.DIALOG_ERROR),this.terminated(e,o.C.causes.DIALOG_ERROR))},t.prototype.on=function(t,r){return e.prototype.on.call(this,t,r)},t.prototype.onAck=function(e){var t=this,r=function(){clearTimeout(t.timers.ackTimer),clearTimeout(t.timers.invite2xxTimer),t.status=c.SessionStatus.STATUS_CONFIRMED;var r=e.message.getHeader("Content-Disposition");r&&"render"===r.type&&(t.renderbody=e.message.body,t.rendertype=e.message.getHeader("Content-Type")),t.emit("confirmed",e.message)};this.status===c.SessionStatus.STATUS_WAITING_FOR_ACK&&(this.sessionDescriptionHandler&&this.sessionDescriptionHandler.hasDescription(e.message.getHeader("Content-Type")||"")?(this.hasAnswer=!0,this.sessionDescriptionHandler.setDescription(e.message.body,this.sessionDescriptionHandlerOptions,this.modifiers).catch((function(r){throw t.logger.warn(r),t.terminate({statusCode:"488",reasonPhrase:"Bad Media Description"}),t.failed(e.message,o.C.causes.BAD_MEDIA_DESCRIPTION),t.terminated(e.message,o.C.causes.BAD_MEDIA_DESCRIPTION),r})).then((function(){return r()}))):r())},t.prototype.receiveRequest=function(e){switch(e.message.method){case o.C.BYE:e.accept(),this.status===c.SessionStatus.STATUS_CONFIRMED&&(this.emit("bye",e.message),this.terminated(e.message,o.C.BYE));break;case o.C.INVITE:this.status===c.SessionStatus.STATUS_CONFIRMED&&(this.logger.log("re-INVITE received"),this.receiveReinvite(e));break;case o.C.INFO:if(this.status===c.SessionStatus.STATUS_CONFIRMED||this.status===c.SessionStatus.STATUS_WAITING_FOR_ACK){if(this.onInfo)return this.onInfo(e.message);var t=e.message.getHeader("content-type");if(t)if(t.match(/^application\/dtmf-relay/i)){if(e.message.body){var r=e.message.body.split("\r\n",2);if(2===r.length){var i=void 0,n=void 0,s=/^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/;s.test(r[0])&&(i=r[0].replace(s,"$2"));var a=/^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/;a.test(r[1])&&(n=parseInt(r[1].replace(a,"$2"),10)),i&&n&&new h.DTMF(this,i,{duration:n}).init_incoming(e)}}}else e.reject({statusCode:415,extraHeaders:["Accept: application/dtmf-relay"]})}break;case o.C.REFER:if(this.status===c.SessionStatus.STATUS_CONFIRMED)if(this.logger.log("REFER received"),this.referContext=new d.ReferServerContext(this.ua,e,this.session),this.listeners("referRequested").length)this.emit("referRequested",this.referContext);else{this.logger.log("No referRequested listeners, automatically accepting and following the refer");var u={followRefer:!0};this.passedOptions&&(u.inviteOptions=this.passedOptions),this.referContext.accept(u,this.modifiers)}break;case o.C.NOTIFY:if(this.referContext&&this.referContext.type===c.TypeStrings.ReferClientContext&&e.message.hasHeader("event")&&/^refer(;.*)?$/.test(e.message.getHeader("event")))return void this.referContext.receiveNotify(e);e.accept(),this.emit("notify",e.message)}},t.prototype.receiveReinvite=function(e){var t,r=this;if(this.emit("reinvite",this,e.message),e.message.hasHeader("P-Asserted-Identity")&&(this.assertedIdentity=a.Grammar.nameAddrHeaderParse(e.message.getHeader("P-Asserted-Identity"))),this.sessionDescriptionHandler){if("0"!==e.message.getHeader("Content-Length")||e.message.getHeader("Content-Type")){if(!this.sessionDescriptionHandler.hasDescription(e.message.getHeader("Content-Type")||""))return e.reject({statusCode:415}),void this.emit("reinviteFailed",this);t=this.sessionDescriptionHandler.setDescription(e.message.body,this.sessionDescriptionHandlerOptions,this.modifiers).then(this.sessionDescriptionHandler.getDescription.bind(this.sessionDescriptionHandler,this.sessionDescriptionHandlerOptions,this.modifiers))}else t=this.sessionDescriptionHandler.getDescription(this.sessionDescriptionHandlerOptions,this.modifiers);t.catch((function(t){var i;throw t.type===c.TypeStrings.SessionDescriptionHandlerError?i=500:t.type===c.TypeStrings.RenegotiationError?(r.emit("renegotiationError",t),r.logger.warn(t.toString()),i=488):(r.logger.error(t),i=488),e.reject({statusCode:i}),r.emit("reinviteFailed",r),t})).then((function(t){var i=["Contact: "+r.contact];e.accept({statusCode:200,extraHeaders:i,body:l.Utils.fromBodyObj(t)}),r.status=c.SessionStatus.STATUS_WAITING_FOR_ACK,r.emit("reinviteAccepted",r)}))}else this.logger.warn("No SessionDescriptionHandler to reinvite")},t.prototype.sendReinvite=function(e){var t=this;if(void 0===e&&(e={}),this.pendingReinvite)this.logger.warn("Reinvite in progress. Please wait until complete, then try again.");else if(this.sessionDescriptionHandler){this.pendingReinvite=!0,e.modifiers=e.modifiers||[];var r=(e.extraHeaders||[]).slice();r.push("Contact: "+this.contact),r.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),this.sessionDescriptionHandler.getDescription(e.sessionDescriptionHandlerOptions,e.modifiers).then((function(e){if(!t.session)throw new Error("Session undefined.");var i={onAccept:function(e){if(t.status!==c.SessionStatus.STATUS_TERMINATED)if(t.pendingReinvite){if(t.status=c.SessionStatus.STATUS_CONFIRMED,t.emit("ack",e.ack()),t.pendingReinvite=!1,clearTimeout(t.timers.invite2xxTimer),!t.sessionDescriptionHandler||!t.sessionDescriptionHandler.hasDescription(e.message.getHeader("Content-Type")||""))return t.logger.error("2XX response received to re-invite but did not have a description"),t.emit("reinviteFailed",t),void t.emit("renegotiationError",new u.Exceptions.RenegotiationError("2XX response received to re-invite but did not have a description"));t.sessionDescriptionHandler.setDescription(e.message.body,t.sessionDescriptionHandlerOptions,t.modifiers).catch((function(e){throw t.logger.error("Could not set the description in 2XX response"),t.logger.error(e),t.emit("reinviteFailed",t),t.emit("renegotiationError",e),t.sendRequest(o.C.BYE,{extraHeaders:["Reason: "+l.Utils.getReasonHeaderValue(488,"Not Acceptable Here")]}),t.terminated(void 0,o.C.causes.INCOMPATIBLE_SDP),e})).then((function(){t.emit("reinviteAccepted",t)}))}else t.logger.error("Received reinvite response, but have no pending reinvite");else t.logger.error("Received reinvite response, but in STATUS_TERMINATED")},onProgress:function(e){},onRedirect:function(e){t.pendingReinvite=!1,t.logger.log("Received a non 1XX or 2XX response to a re-invite"),t.emit("reinviteFailed",t),t.emit("renegotiationError",new u.Exceptions.RenegotiationError("Invalid response to a re-invite"))},onReject:function(e){t.pendingReinvite=!1,t.logger.log("Received a non 1XX or 2XX response to a re-invite"),t.emit("reinviteFailed",t),t.emit("renegotiationError",new u.Exceptions.RenegotiationError("Invalid response to a re-invite"))},onTrying:function(e){}},n={extraHeaders:r,body:l.Utils.fromBodyObj(e)};t.session.invite(i,n)})).catch((function(e){if(e.type===c.TypeStrings.RenegotiationError)throw t.pendingReinvite=!1,t.emit("renegotiationError",e),t.logger.warn("Renegotiation Error"),t.logger.warn(e.toString()),e;throw t.logger.error("sessionDescriptionHandler error"),t.logger.error(e),e}))}else this.logger.warn("No SessionDescriptionHandler, can't reinvite..")},t.prototype.failed=function(e,t){return this.status===c.SessionStatus.STATUS_TERMINATED?this:(this.emit("failed",e,t),this)},t.prototype.rejected=function(e,t){return this.emit("rejected",e,t),this},t.prototype.canceled=function(){return this.sessionDescriptionHandler&&this.sessionDescriptionHandler.close(),this.emit("cancel"),this},t.prototype.accepted=function(e,t){return e instanceof String||(t=l.Utils.getReasonPhrase(e&&e.statusCode||0,t)),this.startTime=new Date,this.replacee&&(this.replacee.emit("replaced",this),this.replacee.terminate()),this.emit("accepted",e,t),this},t.prototype.terminated=function(e,t){return this.status===c.SessionStatus.STATUS_TERMINATED?this:(this.endTime=new Date,this.close(),this.emit("terminated",e,t),this)},t.prototype.connecting=function(e){return this.emit("connecting",{request:e}),this},t.C=c.SessionStatus,t}(n.EventEmitter);t.Session=g;var f=function(e){function t(t,r){var i=this;if(!t.configuration.sessionDescriptionHandlerFactory)throw t.logger.warn("Can't build ISC without SDH Factory"),new Error("ISC Constructor Failed");(i=e.call(this,t.configuration.sessionDescriptionHandlerFactory)||this)._canceled=!1,i.rseq=Math.floor(1e4*Math.random()),i.incomingRequest=r;var n=r.message;p.ServerContext.initializer(i,t,r),i.type=c.TypeStrings.InviteServerContext;var s=n.parseHeader("Content-Disposition");s&&"render"===s.type&&(i.renderbody=n.body,i.rendertype=n.getHeader("Content-Type")),i.status=c.SessionStatus.STATUS_INVITE_RECEIVED,i.fromTag=n.fromTag,i.id=n.callId+i.fromTag,i.request=n,i.contact=i.ua.contact.toString(),i.logger=t.getLogger("sip.inviteservercontext",i.id),i.ua.sessions[i.id]=i;var a=function(e,t){n.hasHeader(e)&&n.getHeader(e).toLowerCase().indexOf("100rel")>=0&&(i.rel100=t)};if(a("require",o.C.supported.REQUIRED),a("supported",o.C.supported.SUPPORTED),i.request.toTag=r.toTag,i.status=c.SessionStatus.STATUS_WAITING_FOR_ANSWER,i.timers.userNoAnswerTimer=setTimeout((function(){r.reject({statusCode:408}),i.failed(n,o.C.causes.NO_ANSWER),i.terminated(n,o.C.causes.NO_ANSWER)}),i.ua.configuration.noAnswerTimeout||60),n.hasHeader("expires")){var u=1e3*Number(n.getHeader("expires")||0);i.timers.expiresTimer=setTimeout((function(){i.status===c.SessionStatus.STATUS_WAITING_FOR_ANSWER&&(r.reject({statusCode:487}),i.failed(n,o.C.causes.EXPIRES),i.terminated(n,o.C.causes.EXPIRES))}),u)}return i.errorListener=i.onTransportError.bind(i),t.transport&&t.transport.on("transportError",i.errorListener),i}return i.__extends(t,e),Object.defineProperty(t.prototype,"autoSendAnInitialProvisionalResponse",{get:function(){return this.rel100!==o.C.supported.REQUIRED},enumerable:!0,configurable:!0}),t.prototype.reply=function(e){return void 0===e&&(e={}),this},t.prototype.reject=function(e){var t=this;if(void 0===e&&(e={}),this.status===c.SessionStatus.STATUS_TERMINATED)throw new u.Exceptions.InvalidStateError(this.status);this.logger.log("rejecting RTCSession");var r=e.statusCode||480,i=l.Utils.getReasonPhrase(r,e.reasonPhrase),n=e.extraHeaders||[];if(r<300||r>699)throw new TypeError("Invalid statusCode: "+r);var s=e.body?a.fromBodyLegacy(e.body):void 0,o=r<400?this.incomingRequest.redirect([],{statusCode:r,reasonPhrase:i,extraHeaders:n,body:s}):this.incomingRequest.reject({statusCode:r,reasonPhrase:i,extraHeaders:n,body:s});return["rejected","failed"].forEach((function(e){t.emit(e,o.message,i)})),this.terminated()},t.prototype.accept=function(e){var t=this;return void 0===e&&(e={}),this._accept(e).then((function(e){var r=e.message,i=e.session;i.delegate={onAck:function(e){return t.onAck(e)},onAckTimeout:function(){return t.onAckTimeout()},onBye:function(e){return t.receiveRequest(e)},onInfo:function(e){return t.receiveRequest(e)},onInvite:function(e){return t.receiveRequest(e)},onNotify:function(e){return t.receiveRequest(e)},onPrack:function(e){return t.receiveRequest(e)},onRefer:function(e){return t.receiveRequest(e)}},t.session=i,t.status=c.SessionStatus.STATUS_WAITING_FOR_ACK,t.accepted(r,l.Utils.getReasonPhrase(200))})).catch((function(e){if(t.onContextError(e),!t._canceled)throw e})),this},t.prototype.progress=function(e){var t=this;void 0===e&&(e={});var r=e.statusCode||180;if(r<100||r>199)throw new TypeError("Invalid statusCode: "+r);if(this.status===c.SessionStatus.STATUS_TERMINATED)return this.logger.warn("Unexpected call for progress while terminated, ignoring"),this;if(this.status===c.SessionStatus.STATUS_ANSWERED)return this.logger.warn("Unexpected call for progress while answered, ignoring"),this;if(this.status===c.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK)return this.logger.warn("Unexpected call for progress while answered (waiting for prack), ignoring"),this;if(this.status===c.SessionStatus.STATUS_WAITING_FOR_PRACK)return this.logger.warn("Unexpected call for progress while waiting for prack, ignoring"),this;if(100===e.statusCode){try{this.incomingRequest.trying()}catch(e){if(this.onContextError(e),!this._canceled)throw e}return this}return this.rel100===o.C.supported.REQUIRED||this.rel100===o.C.supported.SUPPORTED&&e.rel100||this.rel100===o.C.supported.SUPPORTED&&this.ua.configuration.rel100===o.C.supported.REQUIRED?(this._reliableProgressWaitForPrack(e).catch((function(e){if(t.onContextError(e),!t._canceled)throw e})),this):(this._progress(e).catch((function(e){if(t.onContextError(e),!t._canceled)throw e})),this)},t.prototype.terminate=function(e){var t=this;if(void 0===e&&(e={}),!this.session)return this.reject(e),this;switch(this.session.sessionState){case a.SessionState.Initial:case a.SessionState.Early:return this.reject(e),this;case a.SessionState.AckWait:return this.session.delegate={onAck:function(){t.sendRequest(o.C.BYE,e)},onAckTimeout:function(){t.sendRequest(o.C.BYE,e)}},this.emit("bye",this.request),this.terminated(),this;case a.SessionState.Confirmed:return this.bye(e),this;case a.SessionState.Terminated:default:return this}},t.prototype.onCancel=function(e){this.status!==c.SessionStatus.STATUS_WAITING_FOR_ANSWER&&this.status!==c.SessionStatus.STATUS_WAITING_FOR_PRACK&&this.status!==c.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK&&this.status!==c.SessionStatus.STATUS_EARLY_MEDIA&&this.status!==c.SessionStatus.STATUS_ANSWERED||(this.status=c.SessionStatus.STATUS_CANCELED,this.incomingRequest.reject({statusCode:487}),this.canceled(),this.rejected(e,o.C.causes.CANCELED),this.failed(e,o.C.causes.CANCELED),this.terminated(e,o.C.causes.CANCELED))},t.prototype.receiveRequest=function(t){var r=this;switch(t.message.method){case o.C.PRACK:this.status===c.SessionStatus.STATUS_WAITING_FOR_PRACK||this.status===c.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK?this.hasAnswer?(clearTimeout(this.timers.rel1xxTimer),clearTimeout(this.timers.prackTimer),t.accept(),this.status===c.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK&&(this.status=c.SessionStatus.STATUS_EARLY_MEDIA,this.accept()),this.status=c.SessionStatus.STATUS_EARLY_MEDIA):(this.sessionDescriptionHandler=this.setupSessionDescriptionHandler(),this.emit("SessionDescriptionHandler-created",this.sessionDescriptionHandler),this.sessionDescriptionHandler.hasDescription(t.message.getHeader("Content-Type")||"")?(this.hasAnswer=!0,this.sessionDescriptionHandler.setDescription(t.message.body,this.sessionDescriptionHandlerOptions,this.modifiers).then((function(){clearTimeout(r.timers.rel1xxTimer),clearTimeout(r.timers.prackTimer),t.accept(),r.status===c.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK&&(r.status=c.SessionStatus.STATUS_EARLY_MEDIA,r.accept()),r.status=c.SessionStatus.STATUS_EARLY_MEDIA}),(function(e){r.logger.warn(e),r.terminate({statusCode:"488",reasonPhrase:"Bad Media Description"}),r.failed(t.message,o.C.causes.BAD_MEDIA_DESCRIPTION),r.terminated(t.message,o.C.causes.BAD_MEDIA_DESCRIPTION)}))):(this.terminate({statusCode:"488",reasonPhrase:"Bad Media Description"}),this.failed(t.message,o.C.causes.BAD_MEDIA_DESCRIPTION),this.terminated(t.message,o.C.causes.BAD_MEDIA_DESCRIPTION))):this.status===c.SessionStatus.STATUS_EARLY_MEDIA&&t.accept();break;default:e.prototype.receiveRequest.call(this,t)}},t.prototype.setupSessionDescriptionHandler=function(){return this.sessionDescriptionHandler?this.sessionDescriptionHandler:this.sessionDescriptionHandlerFactory(this,this.ua.configuration.sessionDescriptionHandlerFactoryOptions)},t.prototype.generateResponseOfferAnswer=function(e){if(!this.session){var t=a.getBody(this.incomingRequest.message);return t&&"session"===t.contentDisposition?this.setOfferAndGetAnswer(t,e):this.getOffer(e)}switch(this.session.signalingState){case a.SignalingState.Initial:return this.getOffer(e);case a.SignalingState.Stable:case a.SignalingState.HaveLocalOffer:return Promise.resolve(void 0);case a.SignalingState.HaveRemoteOffer:if(!this.session.offer)throw new Error("Session offer undefined");return this.setOfferAndGetAnswer(this.session.offer,e);case a.SignalingState.Closed:default:throw new Error("Invalid signaling state "+this.session.signalingState+".")}},t.prototype.handlePrackOfferAnswer=function(e,t){if(!this.session)throw new Error("Session undefined.");var r=a.getBody(e.message);if(!r||"session"!==r.contentDisposition)return Promise.resolve(void 0);switch(this.session.signalingState){case a.SignalingState.Initial:throw new Error("Invalid signaling state "+this.session.signalingState+".");case a.SignalingState.Stable:return this.setAnswer(r,t).then((function(){}));case a.SignalingState.HaveLocalOffer:throw new Error("Invalid signaling state "+this.session.signalingState+".");case a.SignalingState.HaveRemoteOffer:return this.setOfferAndGetAnswer(r,t);case a.SignalingState.Closed:default:throw new Error("Invalid signaling state "+this.session.signalingState+".")}},t.prototype.canceled=function(){return this._canceled=!0,e.prototype.canceled.call(this)},t.prototype.terminated=function(t,r){return this.prackNeverArrived(),e.prototype.terminated.call(this,t,r)},t.prototype._accept=function(e){var t=this;return void 0===e&&(e={}),this.onInfo=e.onInfo,this.status===c.SessionStatus.STATUS_WAITING_FOR_PRACK?(this.status=c.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK,this.waitForArrivalOfPrack().then((function(){t.status=c.SessionStatus.STATUS_ANSWERED,clearTimeout(t.timers.userNoAnswerTimer)})).then((function(){return t.generateResponseOfferAnswer(e)})).then((function(e){return t.incomingRequest.accept({statusCode:200,body:e})}))):this.status!==c.SessionStatus.STATUS_WAITING_FOR_ANSWER?Promise.reject(new u.Exceptions.InvalidStateError(this.status)):(this.status=c.SessionStatus.STATUS_ANSWERED,this.status=c.SessionStatus.STATUS_ANSWERED,clearTimeout(this.timers.userNoAnswerTimer),this.generateResponseOfferAnswer(e).then((function(e){return t.incomingRequest.accept({statusCode:200,body:e})})))},t.prototype._progress=function(e){void 0===e&&(e={});var t=e.statusCode||180,r=e.reasonPhrase,i=(e.extraHeaders||[]).slice(),n=e.body?a.fromBodyLegacy(e.body):void 0;if(183===t&&!n)return this._progressWithSDP(e);try{var s=this.incomingRequest.progress({statusCode:t,reasonPhrase:r,extraHeaders:i,body:n});return this.emit("progress",s.message,r),this.session=s.session,Promise.resolve(s)}catch(e){return Promise.reject(e)}},t.prototype._progressWithSDP=function(e){var t=this;void 0===e&&(e={});var r=e.statusCode||183,i=e.reasonPhrase,n=(e.extraHeaders||[]).slice();return this.generateResponseOfferAnswer(e).then((function(e){return t.incomingRequest.progress({statusCode:r,reasonPhrase:i,extraHeaders:n,body:e})})).then((function(e){return t.emit("progress",e.message,i),t.session=e.session,e}))},t.prototype._reliableProgress=function(e){var t=this;void 0===e&&(e={});var r=e.statusCode||183,i=e.reasonPhrase,n=(e.extraHeaders||[]).slice();return n.push("Require: 100rel"),n.push("RSeq: "+Math.floor(1e4*Math.random())),this.generateResponseOfferAnswer(e).then((function(e){return t.incomingRequest.progress({statusCode:r,reasonPhrase:i,extraHeaders:n,body:e})})).then((function(e){return t.emit("progress",e.message,i),t.session=e.session,e}))},t.prototype._reliableProgressWaitForPrack=function(e){var t=this;void 0===e&&(e={});var r,i=e.statusCode||183,n=e.reasonPhrase,s=(e.extraHeaders||[]).slice();return s.push("Require: 100rel"),s.push("RSeq: "+this.rseq++),this.status=c.SessionStatus.STATUS_WAITING_FOR_PRACK,new Promise((function(d,p){var h=!0;return t.generateResponseOfferAnswer(e).then((function(e){return r=e,t.incomingRequest.progress({statusCode:i,reasonPhrase:n,extraHeaders:s,body:r})})).then((function(l){var g,f;t.emit("progress",l.message,n),t.session=l.session,l.session.delegate={onPrack:function(r){g=r,clearTimeout(m),clearTimeout(T),h&&(h=!1,t.handlePrackOfferAnswer(g,e).then((function(e){try{f=g.accept({statusCode:200,body:e}),t.status===c.SessionStatus.STATUS_WAITING_FOR_PRACK&&(t.status=c.SessionStatus.STATUS_WAITING_FOR_ANSWER),t.prackArrived(),d({prackRequest:g,prackResponse:f,progressResponse:l})}catch(e){p(e)}})))}};var m=setTimeout((function(){if(h){h=!1,t.logger.warn("No PRACK received, rejecting INVITE."),clearTimeout(T);try{t.incomingRequest.reject({statusCode:504}),t.terminated(void 0,o.C.causes.NO_PRACK),p(new u.Exceptions.TerminatedSessionError)}catch(e){p(e)}}}),64*a.Timers.T1),v=function(){try{t.incomingRequest.progress({statusCode:i,reasonPhrase:n,extraHeaders:s,body:r})}catch(e){return h=!1,void p(e)}T=setTimeout(v,S*=2)},S=a.Timers.T1,T=setTimeout(v,S)}))}))},t.prototype.onAckTimeout=function(){if(this.status===c.SessionStatus.STATUS_WAITING_FOR_ACK){if(this.logger.log("no ACK received for an extended period of time, terminating the call"),!this.session)throw new Error("Session undefined.");this.session.bye(),this.terminated(void 0,o.C.causes.NO_ACK)}},t.prototype.onContextError=function(e){var t=480;e instanceof a.Exception?e instanceof u.Exceptions.SessionDescriptionHandlerError?(this.logger.error(e.message),e.error&&this.logger.error(e.error)):e instanceof u.Exceptions.TerminatedSessionError?this.logger.warn("Incoming session terminated while waiting for PRACK."):e instanceof u.Exceptions.UnsupportedSessionDescriptionContentTypeError?t=415:e instanceof a.Exception&&this.logger.error(e.message):e instanceof Error?this.logger.error(e.message):(this.logger.error("An error occurred in the session description handler."),this.logger.error(e));try{this.incomingRequest.reject({statusCode:t}),this.failed(this.incomingRequest.message,e.message),this.terminated(this.incomingRequest.message,e.message)}catch(e){return}},t.prototype.prackArrived=function(){this.waitingForPrackResolve&&this.waitingForPrackResolve(),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0},t.prototype.prackNeverArrived=function(){this.waitingForPrackReject&&this.waitingForPrackReject(new u.Exceptions.TerminatedSessionError),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0},t.prototype.waitForArrivalOfPrack=function(){var e=this;if(this.waitingForPrackPromise)throw new Error("Already waiting for PRACK");return this.waitingForPrackPromise=new Promise((function(t,r){e.waitingForPrackResolve=t,e.waitingForPrackReject=r})),this.waitingForPrackPromise},t.prototype.getOffer=function(e){return this.hasOffer=!0,this.getSessionDescriptionHandler().getDescription(e.sessionDescriptionHandlerOptions,e.modifiers).then((function(e){return l.Utils.fromBodyObj(e)}))},t.prototype.setAnswer=function(e,t){this.hasAnswer=!0;var r=this.getSessionDescriptionHandler();return r.hasDescription(e.contentType)?r.setDescription(e.content,t.sessionDescriptionHandlerOptions,t.modifiers):Promise.reject(new u.Exceptions.UnsupportedSessionDescriptionContentTypeError)},t.prototype.setOfferAndGetAnswer=function(e,t){this.hasOffer=!0,this.hasAnswer=!0;var r=this.getSessionDescriptionHandler();return r.hasDescription(e.contentType)?r.setDescription(e.content,t.sessionDescriptionHandlerOptions,t.modifiers).then((function(){return r.getDescription(t.sessionDescriptionHandlerOptions,t.modifiers)})).then((function(e){return l.Utils.fromBodyObj(e)})):Promise.reject(new u.Exceptions.UnsupportedSessionDescriptionContentTypeError)},t.prototype.getSessionDescriptionHandler=function(){var e=this.sessionDescriptionHandler=this.setupSessionDescriptionHandler();return this.emit("SessionDescriptionHandler-created",this.sessionDescriptionHandler),e},t}(g);t.InviteServerContext=f;var m=function(e){function t(t,r,i,n){void 0===i&&(i={}),void 0===n&&(n=[]);var a=this;if(!t.configuration.sessionDescriptionHandlerFactory)throw t.logger.warn("Can't build ISC without SDH Factory"),new Error("ICC Constructor Failed");i.params=i.params||{};var d=i.anonymous||!1,p=l.Utils.newTag();i.params.fromTag=p;var h=t.contact.toString({anonymous:d,outbound:d?!t.contact.tempGruu:!t.contact.pubGruu}),g=(i.extraHeaders||[]).slice();if(d&&t.configuration.uri&&(i.params.fromDisplayName="Anonymous",i.params.fromUri="sip:anonymous@anonymous.invalid",g.push("P-Preferred-Identity: "+t.configuration.uri.toString()),g.push("Privacy: id")),g.push("Contact: "+h),g.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),t.configuration.rel100===o.C.supported.REQUIRED&&g.push("Require: 100rel"),t.configuration.replaces===o.C.supported.REQUIRED&&g.push("Require: replaces"),i.extraHeaders=g,a=e.call(this,t.configuration.sessionDescriptionHandlerFactory)||this,s.ClientContext.initializer(a,t,o.C.INVITE,r,i),a.earlyMediaSessionDescriptionHandlers=new Map,a.type=c.TypeStrings.InviteClientContext,a.passedOptions=i,a.sessionDescriptionHandlerOptions=i.sessionDescriptionHandlerOptions||{},a.modifiers=n,a.inviteWithoutSdp=i.inviteWithoutSdp||!1,a.anonymous=i.anonymous||!1,a.renderbody=i.renderbody||void 0,a.rendertype=i.rendertype||"text/plain",a.fromTag=p,a.contact=h,a.status!==c.SessionStatus.STATUS_NULL)throw new u.Exceptions.InvalidStateError(a.status);return a.isCanceled=!1,a.received100=!1,a.method=o.C.INVITE,a.logger=t.getLogger("sip.inviteclientcontext"),t.applicants[a.toString()]=a,a.id=a.request.callId+a.fromTag,a.onInfo=i.onInfo,a.errorListener=a.onTransportError.bind(a),t.transport&&t.transport.on("transportError",a.errorListener),a}return i.__extends(t,e),t.prototype.receiveResponse=function(e){throw new Error("Unimplemented.")},t.prototype.send=function(){return this.sendInvite(),this},t.prototype.invite=function(){var e=this;return this.ua.sessions[this.id]=this,Promise.resolve().then((function(){e.isCanceled||e.status===c.SessionStatus.STATUS_TERMINATED||(e.inviteWithoutSdp?(e.renderbody&&e.rendertype&&(e.request.body={body:e.renderbody,contentType:e.rendertype}),e.status=c.SessionStatus.STATUS_INVITE_SENT,e.send()):(e.sessionDescriptionHandler=e.sessionDescriptionHandlerFactory(e,e.ua.configuration.sessionDescriptionHandlerFactoryOptions||{}),e.emit("SessionDescriptionHandler-created",e.sessionDescriptionHandler),e.sessionDescriptionHandler.getDescription(e.sessionDescriptionHandlerOptions,e.modifiers).then((function(t){e.isCanceled||e.status===c.SessionStatus.STATUS_TERMINATED||(e.hasOffer=!0,e.request.body=t,e.status=c.SessionStatus.STATUS_INVITE_SENT,e.send())}),(function(t){t.type===c.TypeStrings.SessionDescriptionHandlerError&&(e.logger.log(t.message),t.error&&e.logger.log(t.error)),e.status!==c.SessionStatus.STATUS_TERMINATED&&(e.failed(void 0,o.C.causes.WEBRTC_ERROR),e.terminated(void 0,o.C.causes.WEBRTC_ERROR))}))))})),this},t.prototype.cancel=function(e){if(void 0===e&&(e={}),this.status===c.SessionStatus.STATUS_TERMINATED||this.status===c.SessionStatus.STATUS_CONFIRMED)throw new u.Exceptions.InvalidStateError(this.status);if(this.isCanceled)throw new u.Exceptions.InvalidStateError(c.SessionStatus.STATUS_CANCELED);this.isCanceled=!0,this.logger.log("Canceling session");var t=l.Utils.getCancelReason(e.statusCode,e.reasonPhrase);return e.extraHeaders=(e.extraHeaders||[]).slice(),this.outgoingInviteRequest&&(this.logger.warn("Canceling session before it was created"),this.outgoingInviteRequest.cancel(t,e)),this.canceled()},t.prototype.terminate=function(e){return this.status===c.SessionStatus.STATUS_TERMINATED?this:(this.status===c.SessionStatus.STATUS_WAITING_FOR_ACK||this.status===c.SessionStatus.STATUS_CONFIRMED?this.bye(e):this.cancel(e),this)},t.prototype.sendInvite=function(){var e=this;this.outgoingInviteRequest=this.ua.userAgentCore.invite(this.request,{onAccept:function(t){return e.onAccept(t)},onProgress:function(t){return e.onProgress(t)},onRedirect:function(t){return e.onRedirect(t)},onReject:function(t){return e.onReject(t)},onTrying:function(t){return e.onTrying(t)}})},t.prototype.ackAndBye=function(e,t,r,i){if(!this.ua.userAgentCore)throw new Error("Method requires user agent core.");var n=[];r&&n.push("Reason: "+l.Utils.getReasonHeaderValue(r,i));var s=e.ack();this.emit("ack",s.message);var o=t.bye(void 0,{extraHeaders:n});this.emit("bye",o.message)},t.prototype.disposeEarlyMedia=function(){if(!this.earlyMediaSessionDescriptionHandlers)throw new Error("Early media session description handlers undefined.");this.earlyMediaSessionDescriptionHandlers.forEach((function(e){e.close()}))},t.prototype.onAccept=function(e){var t=this;if(!this.earlyMediaSessionDescriptionHandlers)throw new Error("Early media session description handlers undefined.");var r=e.message,i=e.session;if(this.session)this.ackAndBye(e,i);else{if(this.isCanceled)return this.ackAndBye(e,i),void this.emit("bye",this.request);switch(r.hasHeader("P-Asserted-Identity")&&(this.assertedIdentity=a.Grammar.nameAddrHeaderParse(r.getHeader("P-Asserted-Identity"))),this.session=i,this.session.delegate={onAck:function(e){return t.onAck(e)},onBye:function(e){return t.receiveRequest(e)},onInfo:function(e){return t.receiveRequest(e)},onInvite:function(e){return t.receiveRequest(e)},onNotify:function(e){return t.receiveRequest(e)},onPrack:function(e){return t.receiveRequest(e)},onRefer:function(e){return t.receiveRequest(e)}},i.signalingState){case a.SignalingState.Initial:case a.SignalingState.HaveLocalOffer:this.ackAndBye(e,i,400,"Missing session description"),this.failed(r,o.C.causes.BAD_MEDIA_DESCRIPTION);break;case a.SignalingState.HaveRemoteOffer:var n=this.sessionDescriptionHandlerFactory(this,this.ua.configuration.sessionDescriptionHandlerFactoryOptions||{});if(this.sessionDescriptionHandler=n,this.emit("SessionDescriptionHandler-created",this.sessionDescriptionHandler),!n.hasDescription(r.getHeader("Content-Type")||"")){this.ackAndBye(e,i,400,"Missing session description"),this.failed(r,o.C.causes.BAD_MEDIA_DESCRIPTION);break}this.hasOffer=!0,n.setDescription(r.body,this.sessionDescriptionHandlerOptions,this.modifiers).then((function(){return n.getDescription(t.sessionDescriptionHandlerOptions,t.modifiers)})).then((function(i){if(!t.isCanceled&&t.status!==c.SessionStatus.STATUS_TERMINATED){t.status=c.SessionStatus.STATUS_CONFIRMED,t.hasAnswer=!0;var n={contentDisposition:"session",contentType:i.contentType,content:i.body},s=e.ack({body:n});t.emit("ack",s.message),t.accepted(r)}})).catch((function(n){if(n.type!==c.TypeStrings.SessionDescriptionHandlerError)throw n;t.logger.warn("invalid description"),t.logger.warn(n.toString()),t.ackAndBye(e,i,488,"Invalid session description"),t.failed(r,o.C.causes.BAD_MEDIA_DESCRIPTION)}));break;case a.SignalingState.Stable:var s;if(this.renderbody&&this.rendertype&&(s={body:{contentDisposition:"render",contentType:this.rendertype,content:this.renderbody}}),this.hasOffer&&!this.hasAnswer){if(!this.sessionDescriptionHandler)throw new Error("Session description handler undefined.");var u=i.answer;if(!u)throw new Error("Answer is undefined.");this.sessionDescriptionHandler.setDescription(u.content,this.sessionDescriptionHandlerOptions,this.modifiers).then((function(){t.hasAnswer=!0,t.status=c.SessionStatus.STATUS_CONFIRMED;var i=e.ack(s);t.emit("ack",i.message),t.accepted(r)})).catch((function(n){t.logger.error(n),t.ackAndBye(e,i,488,"Not Acceptable Here"),t.failed(r,o.C.causes.BAD_MEDIA_DESCRIPTION)}))}else{if(this.sessionDescriptionHandler=this.earlyMediaSessionDescriptionHandlers.get(i.id),!this.sessionDescriptionHandler)throw new Error("Session description handler undefined.");this.earlyMediaSessionDescriptionHandlers.delete(i.id),this.hasOffer=!0,this.hasAnswer=!0,this.status=c.SessionStatus.STATUS_CONFIRMED;var d=e.ack();this.emit("ack",d.message),this.accepted(r)}break;case a.SignalingState.Closed:break;default:throw new Error("Unknown session signaling state.")}this.disposeEarlyMedia()}},t.prototype.onProgress=function(e){var t=this;if(!this.isCanceled){if(!this.outgoingInviteRequest)throw new Error("Outgoing INVITE request undefined.");if(!this.earlyMediaSessionDescriptionHandlers)throw new Error("Early media session description handlers undefined.");var r=e.message,i=e.session;if(this.status=c.SessionStatus.STATUS_1XX_RECEIVED,r.hasHeader("P-Asserted-Identity")&&(this.assertedIdentity=a.Grammar.nameAddrHeaderParse(r.getHeader("P-Asserted-Identity"))),!i)throw new Error("Session undefined.");var n=r.getHeader("require"),s=r.getHeader("rseq"),u=!!(n&&n.includes("100rel")&&s?Number(s):void 0),d=[];if(u&&d.push("RAck: "+r.getHeader("rseq")+" "+r.getHeader("cseq")),i.signalingState===a.SignalingState.Initial)return u&&(this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."),e.prack({extraHeaders:d})),void this.emit("progress",r);if(i.signalingState===a.SignalingState.HaveLocalOffer)return u&&e.prack({extraHeaders:d}),void this.emit("progress",r);if(i.signalingState===a.SignalingState.HaveRemoteOffer){if(!u)return void this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response.");var p=this.sessionDescriptionHandlerFactory(this,this.ua.configuration.sessionDescriptionHandlerFactoryOptions||{});return this.emit("SessionDescriptionHandler-created",p),this.earlyMediaSessionDescriptionHandlers.set(i.id,p),void p.setDescription(r.body,this.sessionDescriptionHandlerOptions,this.modifiers).then((function(){return p.getDescription(t.sessionDescriptionHandlerOptions,t.modifiers)})).then((function(i){var n={contentDisposition:"session",contentType:i.contentType,content:i.body};e.prack({extraHeaders:d,body:n}),t.status=c.SessionStatus.STATUS_EARLY_MEDIA,t.emit("progress",r)})).catch((function(e){t.status!==c.SessionStatus.STATUS_TERMINATED&&(t.failed(void 0,o.C.causes.WEBRTC_ERROR),t.terminated(void 0,o.C.causes.WEBRTC_ERROR))}))}return i.signalingState===a.SignalingState.Stable?(u&&e.prack({extraHeaders:d}),void this.emit("progress",r)):void 0}},t.prototype.onRedirect=function(e){this.disposeEarlyMedia();var t=e.message,r=t.statusCode,i=l.Utils.sipErrorCause(r||0);this.rejected(t,i),this.failed(t,i),this.terminated(t,i)},t.prototype.onReject=function(e){this.disposeEarlyMedia();var t=e.message,r=t.statusCode,i=l.Utils.sipErrorCause(r||0);this.rejected(t,i),this.failed(t,i),this.terminated(t,i)},t.prototype.onTrying=function(e){this.received100=!0,this.emit("progress",e.message)},t}(g);t.InviteClientContext=m},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(7),s=r(11),o=r(5),a=r(14),c=r(8),u=r(9),d=function(e){function t(t,r,i,n){void 0===n&&(n={});var o=e.call(this)||this;o.data={},o.method=s.C.SUBSCRIBE,o.body=void 0,o.type=c.TypeStrings.Subscription,o.ua=t,o.logger=t.getLogger("sip.subscription"),n.body&&(o.body={body:n.body,contentType:n.contentType?n.contentType:"application/sdp"});var a=t.normalizeTarget(r);if(!a)throw new TypeError("Invalid target: "+r);if(o.uri=a,o.event=i,void 0===n.expires?o.expires=3600:"number"!=typeof n.expires?(t.logger.warn('Option "expires" must be a number. Using default of 3600.'),o.expires=3600):o.expires=n.expires,o.extraHeaders=(n.extraHeaders||[]).slice(),o.context=o.initContext(),o.disposed=!1,o.request=o.context.message,!o.request.from)throw new Error("From undefined.");if(!o.request.to)throw new Error("From undefined.");return o.localIdentity=o.request.from,o.remoteIdentity=o.request.to,o.id=o.request.callId+o.request.from.parameters.tag+o.event,o.ua.subscriptions[o.id]=o,o}return i.__extends(t,e),t.prototype.dispose=function(){this.disposed||(this.retryAfterTimer&&(clearTimeout(this.retryAfterTimer),this.retryAfterTimer=void 0),this.context.dispose(),this.disposed=!0,delete this.ua.subscriptions[this.id])},t.prototype.on=function(t,r){return e.prototype.on.call(this,t,r)},t.prototype.emit=function(t){for(var r=[],i=1;i0?(e.accept(),i.emit("notify",{request:e.message})):e.reject({statusCode:481})},onRefer:function(e){i.logger.log("Received an out of dialog refer"),i.configuration.allowOutOfDialogRefers||e.reject({statusCode:405}),i.logger.log("Allow out of dialog refers is enabled on the UA");var t=new h.ReferServerContext(i,e);i.listeners("outOfDialogReferRequested").length?i.emit("outOfDialogReferRequested",t):(i.logger.log("No outOfDialogReferRequest listeners, automatically accepting and following the out of dialog refer"),t.accept({followRefer:!0}))},onSubscribe:function(e){i.emit("subscribe",e)}};return i.userAgentCore=new a.UserAgentCore(u,d),i.registerContext=new l.RegisterContext(i,r.registerOptions),i.registerContext.on("failed",i.emit.bind(i,"registrationFailed")),i.registerContext.on("registered",i.emit.bind(i,"registered")),i.registerContext.on("unregistered",i.emit.bind(i,"unregistered")),i.configuration.autostart&&i.start(),i}return i.__extends(t,e),t.prototype.register=function(e){return void 0===e&&(e={}),e.register&&(this.configuration.register=!0),this.registerContext.register(e),this},t.prototype.unregister=function(e){var t=this;return this.configuration.register=!1,this.transport.afterConnected((function(){t.registerContext.unregister(e)})),this},t.prototype.isRegistered=function(){return this.registerContext.registered},t.prototype.invite=function(e,t,r){var i=this,n=new f.InviteClientContext(this,e,t,r);return this.transport.afterConnected((function(){n.invite(),i.emit("inviteSent",n)})),n},t.prototype.subscribe=function(e,t,r){var i=new m.Subscription(this,e,t,r);return this.transport.afterConnected((function(){return i.subscribe()})),i},t.prototype.publish=function(e,t,r,i){var n=new p.PublishContext(this,e,t,i);return this.transport.afterConnected((function(){n.publish(r)})),n},t.prototype.message=function(e,t,r){if(void 0===r&&(r={}),void 0===t)throw new TypeError("Not enough arguments");return r.contentType=r.contentType||"text/plain",r.body=t,this.request(o.C.MESSAGE,e,r)},t.prototype.request=function(e,t,r){var i=new s.ClientContext(this,e,t,r);return this.transport.afterConnected((function(){return i.send()})),i},t.prototype.stop=function(){if(this.logger.log("user requested closure..."),this.status===c.UAStatus.STATUS_USER_CLOSED)return this.logger.warn("UA already closed"),this;for(var e in this.logger.log("closing registerContext"),this.registerContext.close(),this.sessions)this.sessions[e]&&(this.logger.log("closing session "+e),this.sessions[e].terminate());for(var t in this.subscriptions)this.subscriptions[t]&&(this.logger.log("unsubscribe "+t),this.subscriptions[t].unsubscribe());for(var r in this.publishers)this.publishers[r]&&(this.logger.log("unpublish "+r),this.publishers[r].close());for(var i in this.applicants)this.applicants[i]&&this.applicants[i].close();if(this.status=c.UAStatus.STATUS_USER_CLOSED,this.transport.disconnect(),this.userAgentCore.reset(),this.configuration.autostop){var n=!("undefined"==typeof chrome||!chrome.app||!chrome.app.runtime);"undefined"==typeof window||"function"!=typeof window.removeEventListener||n||window.removeEventListener("unload",this.unloadListener)}return this},t.prototype.start=function(){if(this.logger.log("user requested startup..."),this.status===c.UAStatus.STATUS_INIT?(this.status=c.UAStatus.STATUS_STARTING,this.setTransportListeners(),this.emit("transportCreated",this.transport),this.transport.connect()):this.status===c.UAStatus.STATUS_USER_CLOSED?(this.logger.log("resuming"),this.status=c.UAStatus.STATUS_READY,this.transport.connect()):this.status===c.UAStatus.STATUS_STARTING?this.logger.log("UA is in STARTING status, not opening new connection"):this.status===c.UAStatus.STATUS_READY?this.logger.log("UA is in READY status, not resuming"):this.logger.error("Connection is down. Auto-Recovery system is trying to connect"),this.configuration.autostop){var e=!("undefined"==typeof chrome||!chrome.app||!chrome.app.runtime);"undefined"==typeof window||"function"!=typeof window.addEventListener||e||window.addEventListener("unload",this.unloadListener)}return this},t.prototype.normalizeTarget=function(e){return v.Utils.normalizeTarget(e,this.configuration.hostportParams)},t.prototype.getLogger=function(e,t){return this.log.getLogger(e,t)},t.prototype.getLoggerFactory=function(){return this.log},t.prototype.getSupportedResponseOptions=function(){var e=[];(this.contact.pubGruu||this.contact.tempGruu)&&e.push("gruu"),this.configuration.rel100===o.C.supported.SUPPORTED&&e.push("100rel"),this.configuration.replaces===o.C.supported.SUPPORTED&&e.push("replaces"),e.push("outbound"),e=e.concat(this.configuration.extraSupported||[]);var t=this.configuration.hackAllowUnregisteredOptionTags||!1,r={};return e=e.filter((function(e){var i=o.C.OPTION_TAGS[e],n=!r[e];return r[e]=!0,(i||t)&&n}))},t.prototype.findSession=function(e){return this.sessions[e.callId+e.fromTag]||this.sessions[e.callId+e.toTag]||void 0},t.prototype.on=function(t,r){return e.prototype.on.call(this,t,r)},t.prototype.onTransportError=function(){this.status!==c.UAStatus.STATUS_USER_CLOSED&&(this.error&&this.error===t.C.NETWORK_ERROR||(this.status=c.UAStatus.STATUS_NOT_READY,this.error=t.C.NETWORK_ERROR))},t.prototype.setTransportListeners=function(){var e=this;this.transport.on("connected",(function(){return e.onTransportConnected()})),this.transport.on("message",(function(t){return e.onTransportReceiveMsg(t)})),this.transport.on("transportError",(function(){return e.onTransportError()}))},t.prototype.onTransportConnected=function(){var e=this;this.configuration.register&&Promise.resolve().then((function(){return e.registerContext.register()}))},t.prototype.onTransportReceiveMsg=function(e){var t=this,r=d.Parser.parseMessage(e,this.getLogger("sip.parser"));if(r)if(this.status===c.UAStatus.STATUS_USER_CLOSED&&r instanceof a.IncomingRequestMessage)this.logger.warn("UA received message when status = USER_CLOSED - aborting");else{var i=function(){for(var e=0,i=["from","to","call_id","cseq","via"];e1)return void this.logger.warn("More than one Via header field present in the response. Dropping.");if(r.via.host!==this.configuration.viaHost||void 0!==r.via.port)return void this.logger.warn("Via sent-by in the response does not match UA Via host value. Dropping.");var s;n=v.Utils.str_utf8_length(r.body);if((s=r.getHeader("content-length"))&&n"}};var h={};for(var n in r)r.hasOwnProperty(n)&&(h[n]=r[n]);for(var n in Object.assign(this.configuration,h),this.logger.log("configuration parameters after validation:"),r)if(r.hasOwnProperty(n))switch(n){case"uri":case"sessionDescriptionHandlerFactory":this.logger.log("\xb7 "+n+": "+r[n]);break;case"password":this.logger.log("\xb7 "+n+": NOT SHOWN");break;case"transportConstructor":this.logger.log("\xb7 "+n+": "+r[n].name);break;default:this.logger.log("\xb7 "+n+": "+JSON.stringify(r[n]))}},t.prototype.getConfigurationCheck=function(){return{mandatory:{},optional:{uri:function(e){/^sip:/i.test(e)||(e=o.C.SIP+":"+e);var t=a.Grammar.URIParse(e);return t&&t.user?t:void 0},transportConstructor:function(e){if(e instanceof Function)return e},transportOptions:function(e){if("object"==typeof e)return e},authorizationUser:function(e){return-1===a.Grammar.parse('"'+e+'"',"quoted_string")?void 0:e},displayName:function(e){return-1===a.Grammar.parse('"'+e+'"',"displayName")?void 0:e},dtmfType:function(e){switch(e){case o.C.dtmfType.RTP:return o.C.dtmfType.RTP;case o.C.dtmfType.INFO:default:return o.C.dtmfType.INFO}},hackViaTcp:function(e){if("boolean"==typeof e)return e},hackIpInContact:function(e){return"boolean"==typeof e?e:"string"==typeof e&&-1!==a.Grammar.parse(e,"host")?e:void 0},hackWssInTransport:function(e){if("boolean"==typeof e)return e},hackAllowUnregisteredOptionTags:function(e){if("boolean"==typeof e)return e},contactTransport:function(e){if("string"==typeof e)return e},extraSupported:function(e){if(e instanceof Array){for(var t=0,r=e;t0)return t}},password:function(e){return String(e)},rel100:function(e){return e===o.C.supported.REQUIRED?o.C.supported.REQUIRED:e===o.C.supported.SUPPORTED?o.C.supported.SUPPORTED:o.C.supported.UNSUPPORTED},replaces:function(e){return e===o.C.supported.REQUIRED?o.C.supported.REQUIRED:e===o.C.supported.SUPPORTED?o.C.supported.SUPPORTED:o.C.supported.UNSUPPORTED},register:function(e){if("boolean"==typeof e)return e},registerOptions:function(e){if("object"==typeof e)return e},usePreloadedRoute:function(e){if("boolean"==typeof e)return e},userAgentString:function(e){if("string"==typeof e)return e},autostart:function(e){if("boolean"==typeof e)return e},autostop:function(e){if("boolean"==typeof e)return e},sessionDescriptionHandlerFactory:function(e){if(e instanceof Function)return e},sessionDescriptionHandlerFactoryOptions:function(e){if("object"==typeof e)return e},authenticationFactory:this.checkAuthenticationFactory,allowLegacyNotifications:function(e){if("boolean"==typeof e)return e},custom:function(e){if("object"==typeof e)return e},contactName:function(e){if("string"==typeof e)return e},experimentalFeatures:function(e){if("boolean"==typeof e)return e}}}},t.C={STATUS_INIT:0,STATUS_STARTING:1,STATUS_READY:2,STATUS_USER_CLOSED:3,STATUS_NOT_READY:4,CONFIGURATION_ERROR:1,NETWORK_ERROR:2,ALLOWED_METHODS:["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"],ACCEPTED_BODY_TYPES:["application/sdp","application/dtmf-relay"],MAX_FORWARDS:70,TAG_LENGTH:10},t}(n.EventEmitter);function E(e){if(!(e.configuration.uri instanceof a.URI))throw new Error("Configuration URI not instance of URI.");var t=e.configuration.uri,r=e.contact,i=e.configuration.displayName?e.configuration.displayName:"",n=!!e.configuration.hackViaTcp,s=e.configuration.usePreloadedRoute&&e.transport.server&&e.transport.server.sipUri?[e.transport.server.sipUri]:[],c=e.configuration.sipjsId||v.Utils.createRandomToken(5),u=[];u.push("outbound"),e.configuration.rel100===o.C.supported.SUPPORTED&&u.push("100rel"),e.configuration.replaces===o.C.supported.SUPPORTED&&u.push("replaces"),e.configuration.extraSupported&&u.push.apply(u,e.configuration.extraSupported),e.configuration.hackAllowUnregisteredOptionTags||(u=u.filter((function(e){return o.C.OPTION_TAGS[e]}))),u=Array.from(new Set(u));var d=e.getSupportedResponseOptions(),p=e.configuration.userAgentString||"sipjs";if(!e.configuration.viaHost)throw new Error("Configuration via host undefined");var h=!!e.configuration.forceRport,l=e.configuration.viaHost;return{aor:t,contact:r,displayName:i,hackViaTcp:n,loggerFactory:e.getLoggerFactory(),routeSet:s,sipjsId:c,supportedOptionTags:u,supportedOptionTagsResponse:d,userAgentHeaderFieldValue:p,viaForceRport:h,viaHost:l,authenticationFactory:function(){if(e.configuration.authenticationFactory)return e.configuration.authenticationFactory(e)},transportAccessor:function(){return e.transport}}}t.UA=y,function(e){!function(e){e.RTP="rtp",e.INFO="info"}(e.DtmfType||(e.DtmfType={}))}(y=t.UA||(t.UA={})),t.UA=y,t.makeUserAgentCoreConfigurationFromUA=E},,,,,function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(5);t.DigestAuthentication=n.DigestAuthentication,t.Grammar=n.Grammar,t.IncomingRequest=n.IncomingRequestMessage,t.IncomingResponse=n.IncomingResponseMessage,t.LoggerFactory=n.LoggerFactory,t.NameAddrHeader=n.NameAddrHeader,t.OutgoingRequest=n.OutgoingRequestMessage,t.Timers=n.Timers,t.Transport=n.Transport,t.URI=n.URI;var s=r(51);t.ClientContext=s.ClientContext;var o=r(11);t.C=o.C;var a=r(8);t.DialogStatus=a.DialogStatus,t.SessionStatus=a.SessionStatus,t.TypeStrings=a.TypeStrings,t.UAStatus=a.UAStatus;var c=r(12);t.Exceptions=c.Exceptions;var u=r(89);t.Parser=u.Parser;var d=r(100);t.PublishContext=d.PublishContext;var p=r(96);t.ReferClientContext=p.ReferClientContext,t.ReferServerContext=p.ReferServerContext;var h=r(101);t.RegisterContext=h.RegisterContext;var l=r(90);t.ServerContext=l.ServerContext;var g=r(102);t.InviteClientContext=g.InviteClientContext,t.InviteServerContext=g.InviteServerContext,t.Session=g.Session;var f=r(103);t.Subscription=f.Subscription;var m=r(1),v={InviteClientTransaction:m.InviteClientTransaction,InviteServerTransaction:m.InviteServerTransaction,NonInviteClientTransaction:m.NonInviteClientTransaction,NonInviteServerTransaction:m.NonInviteServerTransaction};t.Transactions=v;var S=r(104);t.makeUserAgentCoreConfigurationFromUA=S.makeUserAgentCoreConfigurationFromUA,t.UA=S.UA;var T=r(9);t.Utils=T.Utils;var y=i.__importStar(r(111));t.Web=y;var E=o.C.version;t.version=E;t.name="sip.js";var b=i.__importStar(r(5));t.Core=b},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(7),s=r(11),o=r(8),a=r(12),c=r(9),u=function(e){function t(t,r,i){void 0===i&&(i={});var n=e.call(this)||this;if(n.C={MIN_DURATION:70,MAX_DURATION:6e3,DEFAULT_DURATION:100,MIN_INTER_TONE_GAP:50,DEFAULT_INTER_TONE_GAP:500},n.type=o.TypeStrings.DTMF,void 0===r)throw new TypeError("Not enough arguments");if(n.logger=t.ua.getLogger("sip.invitecontext.dtmf",t.id),n.owner=t,"string"==typeof r)r=r.toUpperCase();else{if("number"!=typeof r)throw new TypeError("Invalid tone: "+r);r=r.toString()}if(!r.match(/^[0-9A-D#*]$/))throw new TypeError("Invalid tone: "+r);n.tone=r;var s=i.duration,a=i.interToneGap;if(s&&!c.Utils.isDecimal(s))throw new TypeError("Invalid tone duration: "+s);if(s?sn.C.MAX_DURATION?(n.logger.warn("'duration' value is greater than the maximum allowed, setting it to "+n.C.MAX_DURATION+" milliseconds"),s=n.C.MAX_DURATION):s=Math.abs(s):s=n.C.DEFAULT_DURATION,n.duration=s,a&&!c.Utils.isDecimal(a))throw new TypeError("Invalid interToneGap: "+a);return a?a-1&&n.indexOf("chrome")<0?s=!0:n.indexOf("firefox")>-1&&n.indexOf("chrome")<0&&(c=!0);var u={};return s&&(u.modifiers=[a.stripG722]),c&&(u.alwaysAcquireMediaFirst=!0),r.options.ua.uri?r.anonymous=!1:r.anonymous=!0,r.ua=new o.UA({uri:r.options.ua.uri,authorizationUser:r.options.ua.authorizationUser,password:r.options.ua.password,displayName:r.options.ua.displayName,userAgentString:r.options.ua.userAgentString,register:!0,sessionDescriptionHandlerFactoryOptions:u,transportOptions:{traceSip:r.options.ua.traceSip,wsServers:r.options.ua.wsServers}}),r.state=i.STATUS_NULL,r.logger=r.ua.getLogger("sip.simple"),r.ua.on("registered",(function(){r.emit("registered",r.ua)})),r.ua.on("unregistered",(function(){r.emit("unregistered",r.ua)})),r.ua.on("registrationFailed",(function(){r.emit("unregistered",r.ua)})),r.ua.on("invite",(function(e){if(r.state!==i.STATUS_NULL&&r.state!==i.STATUS_COMPLETED)return r.logger.warn("Rejecting incoming call. Simple only supports 1 call at a time"),void e.reject();r.session=e,r.setupSession(),r.emit("ringing",r.session)})),r.ua.on("message",(function(e){r.emit("message",e)})),r}return n.__extends(t,e),t.prototype.call=function(e){if(this.ua&&this.checkRegistration()){if(this.state===i.STATUS_NULL||this.state===i.STATUS_COMPLETED)return this.options.media.remote.audio&&(this.options.media.remote.audio.autoplay=!0),this.options.media.remote.video&&(this.options.media.remote.video.autoplay=!0),this.options.media.local&&this.options.media.local.video&&(this.options.media.local.video.autoplay=!0,this.options.media.local.video.volume=0),this.session=this.ua.invite(e,{sessionDescriptionHandlerOptions:{constraints:{audio:this.audio,video:this.video}}}),this.setupSession(),this.session;this.logger.warn("Cannot make more than a single call with Simple")}else this.logger.warn("A registered UA is required for calling")},t.prototype.answer=function(){if(this.state===i.STATUS_NEW||this.state===i.STATUS_CONNECTING)return this.options.media.remote.audio&&(this.options.media.remote.audio.autoplay=!0),this.options.media.remote.video&&(this.options.media.remote.video.autoplay=!0),this.session.accept({sessionDescriptionHandlerOptions:{constraints:{audio:this.audio,video:this.video}}});this.logger.warn("No call to answer")},t.prototype.reject=function(){if(this.state===i.STATUS_NEW||this.state===i.STATUS_CONNECTING)return this.session.reject();this.logger.warn("Call is already answered")},t.prototype.hangup=function(){if(this.state===i.STATUS_CONNECTED||this.state===i.STATUS_CONNECTING||this.state===i.STATUS_NEW)return this.state!==i.STATUS_CONNECTED?this.session.cancel():this.session?this.session.bye():void 0;this.logger.warn("No active call to hang up on")},t.prototype.hold=function(){if(this.state===i.STATUS_CONNECTED&&this.session&&!this.session.localHold)return this.mute(),this.logger.log("Placing session on hold"),this.session.hold();this.logger.warn("Cannot put call on hold")},t.prototype.unhold=function(){if(this.state===i.STATUS_CONNECTED&&this.session&&this.session.localHold)return this.unmute(),this.logger.log("Placing call off hold"),this.session.unhold();this.logger.warn("Cannot unhold a call that is not on hold")},t.prototype.mute=function(){this.state===i.STATUS_CONNECTED?(this.logger.log("Muting Audio"),this.toggleMute(!0),this.emit("mute",this)):this.logger.warn("An acitve call is required to mute audio")},t.prototype.unmute=function(){this.state===i.STATUS_CONNECTED?(this.logger.log("Unmuting Audio"),this.toggleMute(!1),this.emit("unmute",this)):this.logger.warn("An active call is required to unmute audio")},t.prototype.sendDTMF=function(e){this.state===i.STATUS_CONNECTED&&this.session?(this.logger.log("Sending DTMF tone: "+e),this.session.dtmf(e)):this.logger.warn("An active call is required to send a DTMF tone")},t.prototype.message=function(e,t){this.ua&&this.checkRegistration()?e&&t?this.ua.message(e,t):this.logger.warn("A destination and message are required to send a message"):this.logger.warn("A registered UA is required to send a message")},t.prototype.checkRegistration=function(){return this.anonymous||this.ua&&this.ua.isRegistered()},t.prototype.setupRemoteMedia=function(){var e=this;if(this.session){var t,r=this.session.sessionDescriptionHandler.peerConnection;r.getReceivers?(t=new MediaStream,r.getReceivers().forEach((function(e){var r=e.track;r&&t.addTrack(r)}))):t=r.getRemoteStreams()[0],this.video?(this.options.media.remote.video.srcObject=t,this.options.media.remote.video.play().catch((function(){e.logger.log("play was rejected")}))):this.audio&&(this.options.media.remote.audio.srcObject=t,this.options.media.remote.audio.play().catch((function(){e.logger.log("play was rejected")})))}else this.logger.warn("No session to set remote media on")},t.prototype.setupLocalMedia=function(){if(this.session){if(this.video&&this.options.media.local&&this.options.media.local.video){var e,t=this.session.sessionDescriptionHandler.peerConnection;t.getSenders?(e=new MediaStream,t.getSenders().forEach((function(t){var r=t.track;r&&"video"===r.kind&&e.addTrack(r)}))):e=t.getLocalStreams()[0],this.options.media.local.video.srcObject=e,this.options.media.local.video.volume=0,this.options.media.local.video.play()}}else this.logger.warn("No session to set local media on")},t.prototype.cleanupMedia=function(){this.video&&(this.options.media.remote.video.srcObject=null,this.options.media.remote.video.pause(),this.options.media.local&&this.options.media.local.video&&(this.options.media.local.video.srcObject=null,this.options.media.local.video.pause())),this.audio&&(this.options.media.remote.audio.srcObject=null,this.options.media.remote.audio.pause())},t.prototype.setupSession=function(){var e=this;this.session?(this.state=i.STATUS_NEW,this.emit("new",this.session),this.session.on("progress",(function(){return e.onProgress()})),this.session.on("accepted",(function(){return e.onAccepted()})),this.session.on("rejected",(function(){return e.onEnded()})),this.session.on("failed",(function(){return e.onFailed()})),this.session.on("terminated",(function(){return e.onEnded()}))):this.logger.warn("No session to set up")},t.prototype.destroyMedia=function(){this.session&&this.session.sessionDescriptionHandler&&this.session.sessionDescriptionHandler.close()},t.prototype.toggleMute=function(e){if(this.session){var t=this.session.sessionDescriptionHandler.peerConnection;t.getSenders?t.getSenders().forEach((function(t){t.track&&(t.track.enabled=!e)})):t.getLocalStreams().forEach((function(t){t.getAudioTracks().forEach((function(t){t.enabled=!e})),t.getVideoTracks().forEach((function(t){t.enabled=!e}))}))}else this.logger.warn("No session to toggle mute")},t.prototype.onAccepted=function(){var e=this;this.session?(this.state=i.STATUS_CONNECTED,this.emit("connected",this.session),this.setupLocalMedia(),this.setupRemoteMedia(),this.session.sessionDescriptionHandler&&(this.session.sessionDescriptionHandler.on("addTrack",(function(){e.logger.log("A track has been added, triggering new remoteMedia setup"),e.setupRemoteMedia()})),this.session.sessionDescriptionHandler.on("addStream",(function(){e.logger.log("A stream has been added, trigger new remoteMedia setup"),e.setupRemoteMedia()}))),this.session.on("dtmf",(function(t,r){e.emit("dtmf",r.tone)})),this.session.on("bye",(function(){return e.onEnded()}))):this.logger.warn("No session for accepting")},t.prototype.onProgress=function(){this.state=i.STATUS_CONNECTING,this.emit("connecting",this.session)},t.prototype.onFailed=function(){this.onEnded()},t.prototype.onEnded=function(){this.state=i.STATUS_COMPLETED,this.emit("ended",this.session),this.cleanupMedia()},t.C=i,t}(s.EventEmitter);t.Simple=c}])})); \ No newline at end of file diff --git a/dist/sip-api.js b/dist/sip-api.js deleted file mode 100644 index b07a2ea6c..000000000 --- a/dist/sip-api.js +++ /dev/null @@ -1,20215 +0,0 @@ -/*! - * - * SIP version 0.15.5 - * Copyright (c) 2014-2019 Junction Networks, Inc - * Homepage: https://sipjs.com - * License: https://sipjs.com/license/ - * - * - * ~~~SIP.js contains substantial portions of JsSIP under the following license~~~ - * Homepage: http://jssip.net - * Copyright (c) 2012-2013 José Luis Millán - Versatica - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * ~~~ end JsSIP license ~~~ - * - * - * - * - */ -(function webpackUniversalModuleDefinition(root, factory) { - if(typeof exports === 'object' && typeof module === 'object') - module.exports = factory(); - else if(typeof define === 'function' && define.amd) - define([], factory); - else if(typeof exports === 'object') - exports["SIP"] = factory(); - else - root["SIP"] = factory(); -})(this, function() { -return /******/ (function(modules) { // webpackBootstrap -/******/ // The module cache -/******/ var installedModules = {}; -/******/ -/******/ // The require function -/******/ function __webpack_require__(moduleId) { -/******/ -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) { -/******/ return installedModules[moduleId].exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ i: moduleId, -/******/ l: false, -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); -/******/ -/******/ // Flag the module as loaded -/******/ module.l = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/******/ -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; -/******/ -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; -/******/ -/******/ // define getter function for harmony exports -/******/ __webpack_require__.d = function(exports, name, getter) { -/******/ if(!__webpack_require__.o(exports, name)) { -/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); -/******/ } -/******/ }; -/******/ -/******/ // define __esModule on exports -/******/ __webpack_require__.r = function(exports) { -/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { -/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); -/******/ } -/******/ Object.defineProperty(exports, '__esModule', { value: true }); -/******/ }; -/******/ -/******/ // create a fake namespace object -/******/ // mode & 1: value is a module id, require it -/******/ // mode & 2: merge all properties of value into the ns -/******/ // mode & 4: return value when already ns object -/******/ // mode & 8|1: behave like require -/******/ __webpack_require__.t = function(value, mode) { -/******/ if(mode & 1) value = __webpack_require__(value); -/******/ if(mode & 8) return value; -/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; -/******/ var ns = Object.create(null); -/******/ __webpack_require__.r(ns); -/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); -/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); -/******/ return ns; -/******/ }; -/******/ -/******/ // getDefaultExport function for compatibility with non-harmony modules -/******/ __webpack_require__.n = function(module) { -/******/ var getter = module && module.__esModule ? -/******/ function getDefault() { return module['default']; } : -/******/ function getModuleExports() { return module; }; -/******/ __webpack_require__.d(getter, 'a', getter); -/******/ return getter; -/******/ }; -/******/ -/******/ // Object.prototype.hasOwnProperty.call -/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; -/******/ -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = ""; -/******/ -/******/ -/******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = 106); -/******/ }) -/************************************************************************/ -/******/ ([ -/* 0 */, -/* 1 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__extends", function() { return __extends; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__assign", function() { return __assign; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__rest", function() { return __rest; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__decorate", function() { return __decorate; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__param", function() { return __param; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__metadata", function() { return __metadata; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__awaiter", function() { return __awaiter; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__generator", function() { return __generator; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__exportStar", function() { return __exportStar; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__values", function() { return __values; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__read", function() { return __read; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__spread", function() { return __spread; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__spreadArrays", function() { return __spreadArrays; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__await", function() { return __await; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncGenerator", function() { return __asyncGenerator; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncDelegator", function() { return __asyncDelegator; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncValues", function() { return __asyncValues; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__makeTemplateObject", function() { return __makeTemplateObject; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__importStar", function() { return __importStar; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__importDefault", function() { return __importDefault; }); -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ -/* global Reflect, Promise */ - -var extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); -}; - -function __extends(d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -} - -var __assign = function() { - __assign = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - } - return __assign.apply(this, arguments); -} - -function __rest(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; -} - -function __decorate(decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -} - -function __param(paramIndex, decorator) { - return function (target, key) { decorator(target, key, paramIndex); } -} - -function __metadata(metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); -} - -function __awaiter(thisArg, _arguments, P, generator) { - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -} - -function __generator(thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -} - -function __exportStar(m, exports) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; -} - -function __values(o) { - var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; - if (m) return m.call(o); - return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; -} - -function __read(o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; -} - -function __spread() { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read(arguments[i])); - return ar; -} - -function __spreadArrays() { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) - for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) - r[k] = a[j]; - return r; -}; - -function __await(v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); -} - -function __asyncGenerator(thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function fulfill(value) { resume("next", value); } - function reject(value) { resume("throw", value); } - function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } -} - -function __asyncDelegator(o) { - var i, p; - return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } -} - -function __asyncValues(o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } -} - -function __makeTemplateObject(cooked, raw) { - if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } - return cooked; -}; - -function __importStar(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result.default = mod; - return result; -} - -function __importDefault(mod) { - return (mod && mod.__esModule) ? mod : { default: mod }; -} - - -/***/ }), -/* 2 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -/** - * A core library implementing low level SIP protocol elements. - * @packageDocumentation - */ -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -// Directories -tslib_1.__exportStar(__webpack_require__(3), exports); -tslib_1.__exportStar(__webpack_require__(31), exports); -tslib_1.__exportStar(__webpack_require__(60), exports); -tslib_1.__exportStar(__webpack_require__(5), exports); -tslib_1.__exportStar(__webpack_require__(24), exports); -tslib_1.__exportStar(__webpack_require__(56), exports); -tslib_1.__exportStar(__webpack_require__(27), exports); -tslib_1.__exportStar(__webpack_require__(64), exports); -tslib_1.__exportStar(__webpack_require__(66), exports); -// Files -tslib_1.__exportStar(__webpack_require__(26), exports); -tslib_1.__exportStar(__webpack_require__(78), exports); - - -/***/ }), -/* 3 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -tslib_1.__exportStar(__webpack_require__(4), exports); -tslib_1.__exportStar(__webpack_require__(23), exports); -tslib_1.__exportStar(__webpack_require__(55), exports); - - -/***/ }), -/* 4 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var messages_1 = __webpack_require__(5); -/** - * Dialog. - * @remarks - * A key concept for a user agent is that of a dialog. A dialog - * represents a peer-to-peer SIP relationship between two user agents - * that persists for some time. The dialog facilitates sequencing of - * messages between the user agents and proper routing of requests - * between both of them. The dialog represents a context in which to - * interpret SIP messages. - * https://tools.ietf.org/html/rfc3261#section-12 - * @public - */ -var Dialog = /** @class */ (function () { - /** - * Dialog constructor. - * @param core - User agent core. - * @param dialogState - Initial dialog state. - */ - function Dialog(core, dialogState) { - this.core = core; - this.dialogState = dialogState; - this.core.dialogs.set(this.id, this); - } - /** - * When a UAC receives a response that establishes a dialog, it - * constructs the state of the dialog. This state MUST be maintained - * for the duration of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.1.2 - * @param outgoingRequestMessage - Outgoing request message for dialog. - * @param incomingResponseMessage - Incoming response message creating dialog. - */ - Dialog.initialDialogStateForUserAgentClient = function (outgoingRequestMessage, incomingResponseMessage) { - // If the request was sent over TLS, and the Request-URI contained a - // SIPS URI, the "secure" flag is set to TRUE. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - var secure = false; // FIXME: Currently no support for TLS. - // The route set MUST be set to the list of URIs in the Record-Route - // header field from the response, taken in reverse order and preserving - // all URI parameters. If no Record-Route header field is present in - // the response, the route set MUST be set to the empty set. This route - // set, even if empty, overrides any pre-existing route set for future - // requests in this dialog. The remote target MUST be set to the URI - // from the Contact header field of the response. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - var routeSet = incomingResponseMessage.getHeaders("record-route").reverse(); - var contact = incomingResponseMessage.parseHeader("contact"); - if (!contact) { // TODO: Review to make sure this will never happen - throw new Error("Contact undefined."); - } - if (!(contact instanceof messages_1.NameAddrHeader)) { - throw new Error("Contact not instance of NameAddrHeader."); - } - var remoteTarget = contact.uri; - // The local sequence number MUST be set to the value of the sequence - // number in the CSeq header field of the request. The remote sequence - // number MUST be empty (it is established when the remote UA sends a - // request within the dialog). The call identifier component of the - // dialog ID MUST be set to the value of the Call-ID in the request. - // The local tag component of the dialog ID MUST be set to the tag in - // the From field in the request, and the remote tag component of the - // dialog ID MUST be set to the tag in the To field of the response. A - // UAC MUST be prepared to receive a response without a tag in the To - // field, in which case the tag is considered to have a value of null. - // - // This is to maintain backwards compatibility with RFC 2543, which - // did not mandate To tags. - // - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - var localSequenceNumber = outgoingRequestMessage.cseq; - var remoteSequenceNumber = undefined; - var callId = outgoingRequestMessage.callId; - var localTag = outgoingRequestMessage.fromTag; - var remoteTag = incomingResponseMessage.toTag; - if (!callId) { // TODO: Review to make sure this will never happen - throw new Error("Call id undefined."); - } - if (!localTag) { // TODO: Review to make sure this will never happen - throw new Error("From tag undefined."); - } - if (!remoteTag) { // TODO: Review to make sure this will never happen - throw new Error("To tag undefined."); // FIXME: No backwards compatibility with RFC 2543 - } - // The remote URI MUST be set to the URI in the To field, and the local - // URI MUST be set to the URI in the From field. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - if (!outgoingRequestMessage.from) { // TODO: Review to make sure this will never happen - throw new Error("From undefined."); - } - if (!outgoingRequestMessage.to) { // TODO: Review to make sure this will never happen - throw new Error("To undefined."); - } - var localURI = outgoingRequestMessage.from.uri; - var remoteURI = outgoingRequestMessage.to.uri; - // A dialog can also be in the "early" state, which occurs when it is - // created with a provisional response, and then transition to the - // "confirmed" state when a 2xx final response arrives. - // https://tools.ietf.org/html/rfc3261#section-12 - if (!incomingResponseMessage.statusCode) { - throw new Error("Incoming response status code undefined."); - } - var early = incomingResponseMessage.statusCode < 200 ? true : false; - var dialogState = { - id: callId + localTag + remoteTag, - early: early, - callId: callId, - localTag: localTag, - remoteTag: remoteTag, - localSequenceNumber: localSequenceNumber, - remoteSequenceNumber: remoteSequenceNumber, - localURI: localURI, - remoteURI: remoteURI, - remoteTarget: remoteTarget, - routeSet: routeSet, - secure: secure - }; - return dialogState; - }; - /** - * The UAS then constructs the state of the dialog. This state MUST be - * maintained for the duration of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.1.1 - * @param incomingRequestMessage - Incoming request message creating dialog. - * @param toTag - Tag in the To field in the response to the incoming request. - */ - Dialog.initialDialogStateForUserAgentServer = function (incomingRequestMessage, toTag, early) { - if (early === void 0) { early = false; } - // If the request arrived over TLS, and the Request-URI contained a SIPS - // URI, the "secure" flag is set to TRUE. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - var secure = false; // FIXME: Currently no support for TLS. - // The route set MUST be set to the list of URIs in the Record-Route - // header field from the request, taken in order and preserving all URI - // parameters. If no Record-Route header field is present in the - // request, the route set MUST be set to the empty set. This route set, - // even if empty, overrides any pre-existing route set for future - // requests in this dialog. The remote target MUST be set to the URI - // from the Contact header field of the request. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - var routeSet = incomingRequestMessage.getHeaders("record-route"); - var contact = incomingRequestMessage.parseHeader("contact"); - if (!contact) { // TODO: Review to make sure this will never happen - throw new Error("Contact undefined."); - } - if (!(contact instanceof messages_1.NameAddrHeader)) { - throw new Error("Contact not instance of NameAddrHeader."); - } - var remoteTarget = contact.uri; - // The remote sequence number MUST be set to the value of the sequence - // number in the CSeq header field of the request. The local sequence - // number MUST be empty. The call identifier component of the dialog ID - // MUST be set to the value of the Call-ID in the request. The local - // tag component of the dialog ID MUST be set to the tag in the To field - // in the response to the request (which always includes a tag), and the - // remote tag component of the dialog ID MUST be set to the tag from the - // From field in the request. A UAS MUST be prepared to receive a - // request without a tag in the From field, in which case the tag is - // considered to have a value of null. - // - // This is to maintain backwards compatibility with RFC 2543, which - // did not mandate From tags. - // - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - var remoteSequenceNumber = incomingRequestMessage.cseq; - var localSequenceNumber = undefined; - var callId = incomingRequestMessage.callId; - var localTag = toTag; - var remoteTag = incomingRequestMessage.fromTag; - // The remote URI MUST be set to the URI in the From field, and the - // local URI MUST be set to the URI in the To field. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - var remoteURI = incomingRequestMessage.from.uri; - var localURI = incomingRequestMessage.to.uri; - var dialogState = { - id: callId + localTag + remoteTag, - early: early, - callId: callId, - localTag: localTag, - remoteTag: remoteTag, - localSequenceNumber: localSequenceNumber, - remoteSequenceNumber: remoteSequenceNumber, - localURI: localURI, - remoteURI: remoteURI, - remoteTarget: remoteTarget, - routeSet: routeSet, - secure: secure - }; - return dialogState; - }; - /** Destructor. */ - Dialog.prototype.dispose = function () { - this.core.dialogs.delete(this.id); - }; - Object.defineProperty(Dialog.prototype, "id", { - /** - * A dialog is identified at each UA with a dialog ID, which consists of - * a Call-ID value, a local tag and a remote tag. The dialog ID at each - * UA involved in the dialog is not the same. Specifically, the local - * tag at one UA is identical to the remote tag at the peer UA. The - * tags are opaque tokens that facilitate the generation of unique - * dialog IDs. - * https://tools.ietf.org/html/rfc3261#section-12 - */ - get: function () { - return this.dialogState.id; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "early", { - /** - * A dialog can also be in the "early" state, which occurs when it is - * created with a provisional response, and then it transition to the - * "confirmed" state when a 2xx final response received or is sent. - * - * Note: RFC 3261 is concise on when a dialog is "confirmed", but it - * can be a point of confusion if an INVITE dialog is "confirmed" after - * a 2xx is sent or after receiving the ACK for the 2xx response. - * With careful reading it can be inferred a dialog is always is - * "confirmed" when the 2xx is sent (regardless of type of dialog). - * However a INVITE dialog does have additional considerations - * when it is confirmed but an ACK has not yet been received (in - * particular with regard to a callee sending BYE requests). - */ - get: function () { - return this.dialogState.early; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "callId", { - /** Call identifier component of the dialog id. */ - get: function () { - return this.dialogState.callId; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "localTag", { - /** Local tag component of the dialog id. */ - get: function () { - return this.dialogState.localTag; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "remoteTag", { - /** Remote tag component of the dialog id. */ - get: function () { - return this.dialogState.remoteTag; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "localSequenceNumber", { - /** Local sequence number (used to order requests from the UA to its peer). */ - get: function () { - return this.dialogState.localSequenceNumber; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "remoteSequenceNumber", { - /** Remote sequence number (used to order requests from its peer to the UA). */ - get: function () { - return this.dialogState.remoteSequenceNumber; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "localURI", { - /** Local URI. */ - get: function () { - return this.dialogState.localURI; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "remoteURI", { - /** Remote URI. */ - get: function () { - return this.dialogState.remoteURI; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "remoteTarget", { - /** Remote target. */ - get: function () { - return this.dialogState.remoteTarget; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "routeSet", { - /** - * Route set, which is an ordered list of URIs. The route set is the - * list of servers that need to be traversed to send a request to the peer. - */ - get: function () { - return this.dialogState.routeSet; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "secure", { - /** - * If the request was sent over TLS, and the Request-URI contained - * a SIPS URI, the "secure" flag is set to true. *NOT IMPLEMENTED* - */ - get: function () { - return this.dialogState.secure; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "userAgentCore", { - /** The user agent core servicing this dialog. */ - get: function () { - return this.core; - }, - enumerable: true, - configurable: true - }); - /** Confirm the dialog. Only matters if dialog is currently early. */ - Dialog.prototype.confirm = function () { - this.dialogState.early = false; - }; - /** - * Requests sent within a dialog, as any other requests, are atomic. If - * a particular request is accepted by the UAS, all the state changes - * associated with it are performed. If the request is rejected, none - * of the state changes are performed. - * - * Note that some requests, such as INVITEs, affect several pieces of - * state. - * - * https://tools.ietf.org/html/rfc3261#section-12.2.2 - * @param message - Incoming request message within this dialog. - */ - Dialog.prototype.receiveRequest = function (message) { - // ACK guard. - // By convention, the handling of ACKs is the responsibility - // the particular dialog implementation. For example, see SessionDialog. - // Furthermore, ACKs have same sequence number as the associated INVITE. - if (message.method === messages_1.C.ACK) { - return; - } - // If the remote sequence number was not empty, but the sequence number - // of the request is lower than the remote sequence number, the request - // is out of order and MUST be rejected with a 500 (Server Internal - // Error) response. If the remote sequence number was not empty, and - // the sequence number of the request is greater than the remote - // sequence number, the request is in order. It is possible for the - // CSeq sequence number to be higher than the remote sequence number by - // more than one. This is not an error condition, and a UAS SHOULD be - // prepared to receive and process requests with CSeq values more than - // one higher than the previous received request. The UAS MUST then set - // the remote sequence number to the value of the sequence number in the - // CSeq header field value in the request. - // - // If a proxy challenges a request generated by the UAC, the UAC has - // to resubmit the request with credentials. The resubmitted request - // will have a new CSeq number. The UAS will never see the first - // request, and thus, it will notice a gap in the CSeq number space. - // Such a gap does not represent any error condition. - // - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (this.remoteSequenceNumber) { - if (message.cseq <= this.remoteSequenceNumber) { - throw new Error("Out of sequence in dialog request. Did you forget to call sequenceGuard()?"); - } - this.dialogState.remoteSequenceNumber = message.cseq; - } - // If the remote sequence number is empty, it MUST be set to the value - // of the sequence number in the CSeq header field value in the request. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (!this.remoteSequenceNumber) { - this.dialogState.remoteSequenceNumber = message.cseq; - } - // When a UAS receives a target refresh request, it MUST replace the - // dialog's remote target URI with the URI from the Contact header field - // in that request, if present. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - // Note: "target refresh request" processing delegated to sub-class. - }; - /** - * If the dialog identifier in the 2xx response matches the dialog - * identifier of an existing dialog, the dialog MUST be transitioned to - * the "confirmed" state, and the route set for the dialog MUST be - * recomputed based on the 2xx response using the procedures of Section - * 12.2.1.2. Otherwise, a new dialog in the "confirmed" state MUST be - * constructed using the procedures of Section 12.1.2. - * - * Note that the only piece of state that is recomputed is the route - * set. Other pieces of state such as the highest sequence numbers - * (remote and local) sent within the dialog are not recomputed. The - * route set only is recomputed for backwards compatibility. RFC - * 2543 did not mandate mirroring of the Record-Route header field in - * a 1xx, only 2xx. However, we cannot update the entire state of - * the dialog, since mid-dialog requests may have been sent within - * the early dialog, modifying the sequence numbers, for example. - * - * https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - */ - Dialog.prototype.recomputeRouteSet = function (message) { - this.dialogState.routeSet = message.getHeaders("record-route").reverse(); - }; - /** - * A request within a dialog is constructed by using many of the - * components of the state stored as part of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - * @param method - Outgoing request method. - */ - Dialog.prototype.createOutgoingRequestMessage = function (method, options) { - // The URI in the To field of the request MUST be set to the remote URI - // from the dialog state. The tag in the To header field of the request - // MUST be set to the remote tag of the dialog ID. The From URI of the - // request MUST be set to the local URI from the dialog state. The tag - // in the From header field of the request MUST be set to the local tag - // of the dialog ID. If the value of the remote or local tags is null, - // the tag parameter MUST be omitted from the To or From header fields, - // respectively. - // - // Usage of the URI from the To and From fields in the original - // request within subsequent requests is done for backwards - // compatibility with RFC 2543, which used the URI for dialog - // identification. In this specification, only the tags are used for - // dialog identification. It is expected that mandatory reflection - // of the original To and From URI in mid-dialog requests will be - // deprecated in a subsequent revision of this specification. - // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - var toUri = this.remoteURI; - var toTag = this.remoteTag; - var fromUri = this.localURI; - var fromTag = this.localTag; - // The Call-ID of the request MUST be set to the Call-ID of the dialog. - // Requests within a dialog MUST contain strictly monotonically - // increasing and contiguous CSeq sequence numbers (increasing-by-one) - // in each direction (excepting ACK and CANCEL of course, whose numbers - // equal the requests being acknowledged or cancelled). Therefore, if - // the local sequence number is not empty, the value of the local - // sequence number MUST be incremented by one, and this value MUST be - // placed into the CSeq header field. If the local sequence number is - // empty, an initial value MUST be chosen using the guidelines of - // Section 8.1.1.5. The method field in the CSeq header field value - // MUST match the method of the request. - // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - var callId = this.callId; - var cseq; - if (options && options.cseq) { - cseq = options.cseq; - } - else if (!this.dialogState.localSequenceNumber) { - cseq = this.dialogState.localSequenceNumber = 1; // https://tools.ietf.org/html/rfc3261#section-8.1.1.5 - } - else { - cseq = this.dialogState.localSequenceNumber += 1; - } - // The UAC uses the remote target and route set to build the Request-URI - // and Route header field of the request. - // - // If the route set is empty, the UAC MUST place the remote target URI - // into the Request-URI. The UAC MUST NOT add a Route header field to - // the request. - // - // If the route set is not empty, and the first URI in the route set - // contains the lr parameter (see Section 19.1.1), the UAC MUST place - // the remote target URI into the Request-URI and MUST include a Route - // header field containing the route set values in order, including all - // parameters. - // - // If the route set is not empty, and its first URI does not contain the - // lr parameter, the UAC MUST place the first URI from the route set - // into the Request-URI, stripping any parameters that are not allowed - // in a Request-URI. The UAC MUST add a Route header field containing - // the remainder of the route set values in order, including all - // parameters. The UAC MUST then place the remote target URI into the - // Route header field as the last value. - // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - // The lr parameter, when present, indicates that the element - // responsible for this resource implements the routing mechanisms - // specified in this document. This parameter will be used in the - // URIs proxies place into Record-Route header field values, and - // may appear in the URIs in a pre-existing route set. - // - // This parameter is used to achieve backwards compatibility with - // systems implementing the strict-routing mechanisms of RFC 2543 - // and the rfc2543bis drafts up to bis-05. An element preparing - // to send a request based on a URI not containing this parameter - // can assume the receiving element implements strict-routing and - // reformat the message to preserve the information in the - // Request-URI. - // https://tools.ietf.org/html/rfc3261#section-19.1.1 - // NOTE: Not backwards compatible with RFC 2543 (no support for strict-routing). - var ruri = this.remoteTarget; - var routeSet = this.routeSet; - var extraHeaders = options && options.extraHeaders; - var body = options && options.body; - // The relative order of header fields with different field names is not - // significant. However, it is RECOMMENDED that header fields which are - // needed for proxy processing (Via, Route, Record-Route, Proxy-Require, - // Max-Forwards, and Proxy-Authorization, for example) appear towards - // the top of the message to facilitate rapid parsing. - // https://tools.ietf.org/html/rfc3261#section-7.3.1 - var message = this.userAgentCore.makeOutgoingRequestMessage(method, ruri, fromUri, toUri, { - callId: callId, - cseq: cseq, - fromTag: fromTag, - toTag: toTag, - routeSet: routeSet - }, extraHeaders, body); - return message; - }; - /** - * If the remote sequence number was not empty, but the sequence number - * of the request is lower than the remote sequence number, the request - * is out of order and MUST be rejected with a 500 (Server Internal - * Error) response. - * https://tools.ietf.org/html/rfc3261#section-12.2.2 - * @param request - Incoming request to guard. - * @returns True if the program execution is to continue in the branch in question. - * Otherwise a 500 Server Internal Error was stateless sent and request processing must stop. - */ - Dialog.prototype.sequenceGuard = function (message) { - // ACK guard. - // By convention, handling of unexpected ACKs is responsibility - // the particular dialog implementation. For example, see SessionDialog. - // Furthermore, we cannot reply to an "out of sequence" ACK. - if (message.method === messages_1.C.ACK) { - return true; - } - // Note: We are rejecting on "less than or equal to" the remote - // sequence number (excepting ACK whose numbers equal the requests - // being acknowledged or cancelled), which is the correct thing to - // do in our case. The only time a request with the same sequence number - // will show up here if is a) it is a very late retransmission of a - // request we already handled or b) it is a different request with the - // same sequence number which would be violation of the standard. - // Request retransmissions are absorbed by the transaction layer, - // so any request with a duplicate sequence number getting here - // would have to be a retransmission after the transaction terminated - // or a broken request (with unique via branch value). - // Requests within a dialog MUST contain strictly monotonically - // increasing and contiguous CSeq sequence numbers (increasing-by-one) - // in each direction (excepting ACK and CANCEL of course, whose numbers - // equal the requests being acknowledged or cancelled). Therefore, if - // the local sequence number is not empty, the value of the local - // sequence number MUST be incremented by one, and this value MUST be - // placed into the CSeq header field. - // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - if (this.remoteSequenceNumber && message.cseq <= this.remoteSequenceNumber) { - this.core.replyStateless(message, { statusCode: 500 }); - return false; - } - return true; - }; - return Dialog; -}()); -exports.Dialog = Dialog; - - -/***/ }), -/* 5 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -// Directories -tslib_1.__exportStar(__webpack_require__(6), exports); -// Files -tslib_1.__exportStar(__webpack_require__(8), exports); -tslib_1.__exportStar(__webpack_require__(19), exports); -tslib_1.__exportStar(__webpack_require__(11), exports); -tslib_1.__exportStar(__webpack_require__(10), exports); -tslib_1.__exportStar(__webpack_require__(9), exports); -tslib_1.__exportStar(__webpack_require__(17), exports); -tslib_1.__exportStar(__webpack_require__(13), exports); -tslib_1.__exportStar(__webpack_require__(18), exports); -tslib_1.__exportStar(__webpack_require__(22), exports); -tslib_1.__exportStar(__webpack_require__(14), exports); -tslib_1.__exportStar(__webpack_require__(15), exports); - - -/***/ }), -/* 6 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -tslib_1.__exportStar(__webpack_require__(7), exports); - - -/***/ }), -/* 7 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * SIP Methods - * @internal - */ -var C; -(function (C) { - C.ACK = "ACK"; - C.BYE = "BYE"; - C.CANCEL = "CANCEL"; - C.INFO = "INFO"; - C.INVITE = "INVITE"; - C.MESSAGE = "MESSAGE"; - C.NOTIFY = "NOTIFY"; - C.OPTIONS = "OPTIONS"; - C.REGISTER = "REGISTER"; - C.UPDATE = "UPDATE"; - C.SUBSCRIBE = "SUBSCRIBE"; - C.PUBLISH = "PUBLISH"; - C.REFER = "REFER"; - C.PRACK = "PRACK"; -})(C = exports.C || (exports.C = {})); - - -/***/ }), -/* 8 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var incoming_request_message_1 = __webpack_require__(9); -var incoming_response_message_1 = __webpack_require__(17); -var outgoing_request_message_1 = __webpack_require__(18); -/** - * Create a Body given a legacy body type. - * @param bodyLegacy - Body Object - * @internal - */ -function fromBodyLegacy(bodyLegacy) { - var content = (typeof bodyLegacy === "string") ? bodyLegacy : bodyLegacy.body; - var contentType = (typeof bodyLegacy === "string") ? "application/sdp" : bodyLegacy.contentType; - var contentDisposition = contentTypeToContentDisposition(contentType); - var body = { contentDisposition: contentDisposition, contentType: contentType, content: content }; - return body; -} -exports.fromBodyLegacy = fromBodyLegacy; -/** - * Given a message, get a normalized body. - * The content disposition is inferred if not set. - * @param message - The message. - * @internal - */ -function getBody(message) { - var contentDisposition; - var contentType; - var content; - // We're in UAS role, receiving incoming request - if (message instanceof incoming_request_message_1.IncomingRequestMessage) { - if (message.body) { - // FIXME: Parsing needs typing - var parse = message.parseHeader("Content-Disposition"); - contentDisposition = parse ? parse.type : undefined; - contentType = message.parseHeader("Content-Type"); - content = message.body; - } - } - // We're in UAC role, receiving incoming response - if (message instanceof incoming_response_message_1.IncomingResponseMessage) { - if (message.body) { - // FIXME: Parsing needs typing - var parse = message.parseHeader("Content-Disposition"); - contentDisposition = parse ? parse.type : undefined; - contentType = message.parseHeader("Content-Type"); - content = message.body; - } - } - // We're in UAC role, sending outgoing request - if (message instanceof outgoing_request_message_1.OutgoingRequestMessage) { - if (message.body) { - contentDisposition = message.getHeader("Content-Disposition"); - contentType = message.getHeader("Content-Type"); - if (typeof message.body === "string") { - // FIXME: OutgoingRequest should not allow a "string" body without a "Content-Type" header. - if (!contentType) { - throw new Error("Header content type header does not equal body content type."); - } - content = message.body; - } - else { - // FIXME: OutgoingRequest should not allow the "Content-Type" header not to match th body content type - if (contentType && contentType !== message.body.contentType) { - throw new Error("Header content type header does not equal body content type."); - } - contentType = message.body.contentType; - content = message.body.body; - } - } - } - // We're in UAS role, sending outgoing response - if (isBody(message)) { - contentDisposition = message.contentDisposition; - contentType = message.contentType; - content = message.content; - } - // No content, no body. - if (!content) { - return undefined; - } - if (contentType && !contentDisposition) { - contentDisposition = contentTypeToContentDisposition(contentType); - } - if (!contentDisposition) { - throw new Error("Content disposition undefined."); - } - if (!contentType) { - throw new Error("Content type undefined."); - } - return { - contentDisposition: contentDisposition, - contentType: contentType, - content: content - }; -} -exports.getBody = getBody; -/** - * User-Defined Type Guard for Body. - * @param body - Body to check. - * @internal - */ -function isBody(body) { - return body && - typeof body.content === "string" && - typeof body.contentType === "string" && - body.contentDisposition === undefined ? true : typeof body.contentDisposition === "string"; -} -exports.isBody = isBody; -// If the Content-Disposition header field is missing, bodies of -// Content-Type application/sdp imply the disposition "session", while -// other content types imply "render". -// https://tools.ietf.org/html/rfc3261#section-13.2.1 -function contentTypeToContentDisposition(contentType) { - if (contentType === "application/sdp") { - return "session"; - } - else { - return "render"; - } -} - - -/***/ }), -/* 9 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var incoming_message_1 = __webpack_require__(10); -/** - * Incoming request message. - * @public - */ -var IncomingRequestMessage = /** @class */ (function (_super) { - tslib_1.__extends(IncomingRequestMessage, _super); - function IncomingRequestMessage() { - return _super.call(this) || this; - } - return IncomingRequestMessage; -}(incoming_message_1.IncomingMessage)); -exports.IncomingRequestMessage = IncomingRequestMessage; - - -/***/ }), -/* 10 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var grammar_1 = __webpack_require__(11); -var utils_1 = __webpack_require__(16); -/** - * Incoming message. - * @public - */ -var IncomingMessage = /** @class */ (function () { - function IncomingMessage() { - this.headers = {}; - } - /** - * Insert a header of the given name and value into the last position of the - * header array. - * @param name - header name - * @param value - header value - */ - IncomingMessage.prototype.addHeader = function (name, value) { - var header = { raw: value }; - name = utils_1.headerize(name); - if (this.headers[name]) { - this.headers[name].push(header); - } - else { - this.headers[name] = [header]; - } - }; - /** - * Get the value of the given header name at the given position. - * @param name - header name - * @returns Returns the specified header, undefined if header doesn't exist. - */ - IncomingMessage.prototype.getHeader = function (name) { - var header = this.headers[utils_1.headerize(name)]; - if (header) { - if (header[0]) { - return header[0].raw; - } - } - else { - return; - } - }; - /** - * Get the header/s of the given name. - * @param name - header name - * @returns Array - with all the headers of the specified name. - */ - IncomingMessage.prototype.getHeaders = function (name) { - var header = this.headers[utils_1.headerize(name)]; - var result = []; - if (!header) { - return []; - } - for (var _i = 0, header_1 = header; _i < header_1.length; _i++) { - var headerPart = header_1[_i]; - result.push(headerPart.raw); - } - return result; - }; - /** - * Verify the existence of the given header. - * @param name - header name - * @returns true if header with given name exists, false otherwise - */ - IncomingMessage.prototype.hasHeader = function (name) { - return !!this.headers[utils_1.headerize(name)]; - }; - /** - * Parse the given header on the given index. - * @param name - header name - * @param idx - header index - * @returns Parsed header object, undefined if the - * header is not present or in case of a parsing error. - */ - IncomingMessage.prototype.parseHeader = function (name, idx) { - if (idx === void 0) { idx = 0; } - name = utils_1.headerize(name); - if (!this.headers[name]) { - // this.logger.log("header '" + name + "' not present"); - return; - } - else if (idx >= this.headers[name].length) { - // this.logger.log("not so many '" + name + "' headers present"); - return; - } - var header = this.headers[name][idx]; - var value = header.raw; - if (header.parsed) { - return header.parsed; - } - // substitute '-' by '_' for grammar rule matching. - var parsed = grammar_1.Grammar.parse(value, name.replace(/-/g, "_")); - if (parsed === -1) { - this.headers[name].splice(idx, 1); // delete from headers - // this.logger.warn('error parsing "' + name + '" header field with value "' + value + '"'); - return; - } - else { - header.parsed = parsed; - return parsed; - } - }; - /** - * Message Header attribute selector. Alias of parseHeader. - * @param name - header name - * @param idx - header index - * @returns Parsed header object, undefined if the - * header is not present or in case of a parsing error. - * - * @example - * message.s('via',3).port - */ - IncomingMessage.prototype.s = function (name, idx) { - if (idx === void 0) { idx = 0; } - return this.parseHeader(name, idx); - }; - /** - * Replace the value of the given header by the value. - * @param name - header name - * @param value - header value - */ - IncomingMessage.prototype.setHeader = function (name, value) { - this.headers[utils_1.headerize(name)] = [{ raw: value }]; - }; - IncomingMessage.prototype.toString = function () { - return this.data; - }; - return IncomingMessage; -}()); -exports.IncomingMessage = IncomingMessage; - - -/***/ }), -/* 11 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var pegGrammar = tslib_1.__importStar(__webpack_require__(12)); -/** - * Grammar. - * @internal - */ -var Grammar; -(function (Grammar) { - /** - * Parse. - * @param input - - * @param startRule - - */ - function parse(input, startRule) { - var options = { startRule: startRule }; - try { - pegGrammar.parse(input, options); - } - catch (e) { - options.data = -1; - } - return options.data; - } - Grammar.parse = parse; - /** - * Parse the given string and returns a SIP.NameAddrHeader instance or undefined if - * it is an invalid NameAddrHeader. - * @param name_addr_header - - */ - function nameAddrHeaderParse(nameAddrHeader) { - var parsedNameAddrHeader = Grammar.parse(nameAddrHeader, "Name_Addr_Header"); - return parsedNameAddrHeader !== -1 ? parsedNameAddrHeader : undefined; - } - Grammar.nameAddrHeaderParse = nameAddrHeaderParse; - /** - * Parse the given string and returns a SIP.URI instance or undefined if - * it is an invalid URI. - * @param uri - - */ - function URIParse(uri) { - var parsedUri = Grammar.parse(uri, "SIP_URI"); - return parsedUri !== -1 ? parsedUri : undefined; - } - Grammar.URIParse = URIParse; -})(Grammar = exports.Grammar || (exports.Grammar = {})); - - -/***/ }), -/* 12 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// tslint:disable:interface-name -// tslint:disable: trailing-comma -// tslint:disable: object-literal-sort-keys -// tslint:disable: max-line-length -// tslint:disable: only-arrow-functions -// tslint:disable: one-variable-per-declaration -// tslint:disable: no-consecutive-blank-lines -// tslint:disable: align -// tslint:disable: radix -// tslint:disable: quotemark -// tslint:disable: semicolon -// tslint:disable: object-literal-shorthand -// tslint:disable: variable-name -// tslint:disable: no-var-keyword -// tslint:disable: whitespace -// tslint:disable: curly -// tslint:disable: prefer-const -// tslint:disable: object-literal-key-quotes -// tslint:disable: no-string-literal -// tslint:disable: one-line -// tslint:disable: no-unused-expression -// tslint:disable: space-before-function-paren -// tslint:disable: arrow-return-shorthand -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -// Generated by PEG.js v. 0.10.0 (ts-pegjs plugin v. 0.2.6 ) -// -// https://pegjs.org/ https://github.com/metadevpro/ts-pegjs -var name_addr_header_1 = __webpack_require__(13); -var uri_1 = __webpack_require__(15); -var SyntaxError = /** @class */ (function (_super) { - tslib_1.__extends(SyntaxError, _super); - function SyntaxError(message, expected, found, location) { - var _this = _super.call(this) || this; - _this.message = message; - _this.expected = expected; - _this.found = found; - _this.location = location; - _this.name = "SyntaxError"; - if (typeof Error.captureStackTrace === "function") { - Error.captureStackTrace(_this, SyntaxError); - } - return _this; - } - SyntaxError.buildMessage = function (expected, found) { - function hex(ch) { - return ch.charCodeAt(0).toString(16).toUpperCase(); - } - function literalEscape(s) { - return s - .replace(/\\/g, "\\\\") - .replace(/"/g, "\\\"") - .replace(/\0/g, "\\0") - .replace(/\t/g, "\\t") - .replace(/\n/g, "\\n") - .replace(/\r/g, "\\r") - .replace(/[\x00-\x0F]/g, function (ch) { return "\\x0" + hex(ch); }) - .replace(/[\x10-\x1F\x7F-\x9F]/g, function (ch) { return "\\x" + hex(ch); }); - } - function classEscape(s) { - return s - .replace(/\\/g, "\\\\") - .replace(/\]/g, "\\]") - .replace(/\^/g, "\\^") - .replace(/-/g, "\\-") - .replace(/\0/g, "\\0") - .replace(/\t/g, "\\t") - .replace(/\n/g, "\\n") - .replace(/\r/g, "\\r") - .replace(/[\x00-\x0F]/g, function (ch) { return "\\x0" + hex(ch); }) - .replace(/[\x10-\x1F\x7F-\x9F]/g, function (ch) { return "\\x" + hex(ch); }); - } - function describeExpectation(expectation) { - switch (expectation.type) { - case "literal": - return "\"" + literalEscape(expectation.text) + "\""; - case "class": - var escapedParts = expectation.parts.map(function (part) { - return Array.isArray(part) - ? classEscape(part[0]) + "-" + classEscape(part[1]) - : classEscape(part); - }); - return "[" + (expectation.inverted ? "^" : "") + escapedParts + "]"; - case "any": - return "any character"; - case "end": - return "end of input"; - case "other": - return expectation.description; - } - } - function describeExpected(expected1) { - var descriptions = expected1.map(describeExpectation); - var i; - var j; - descriptions.sort(); - if (descriptions.length > 0) { - for (i = 1, j = 1; i < descriptions.length; i++) { - if (descriptions[i - 1] !== descriptions[i]) { - descriptions[j] = descriptions[i]; - j++; - } - } - descriptions.length = j; - } - switch (descriptions.length) { - case 1: - return descriptions[0]; - case 2: - return descriptions[0] + " or " + descriptions[1]; - default: - return descriptions.slice(0, -1).join(", ") - + ", or " - + descriptions[descriptions.length - 1]; - } - } - function describeFound(found1) { - return found1 ? "\"" + literalEscape(found1) + "\"" : "end of input"; - } - return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found."; - }; - return SyntaxError; -}(Error)); -exports.SyntaxError = SyntaxError; -function peg$parse(input, options) { - options = options !== undefined ? options : {}; - var peg$FAILED = {}; - var peg$startRuleIndices = { Contact: 119, Name_Addr_Header: 156, Record_Route: 176, Request_Response: 81, SIP_URI: 45, Subscription_State: 186, Supported: 191, Require: 182, Via: 194, absoluteURI: 84, Call_ID: 118, Content_Disposition: 130, Content_Length: 135, Content_Type: 136, CSeq: 146, displayName: 122, Event: 149, From: 151, host: 52, Max_Forwards: 154, Min_SE: 213, Proxy_Authenticate: 157, quoted_string: 40, Refer_To: 178, Replaces: 179, Session_Expires: 210, stun_URI: 217, To: 192, turn_URI: 223, uuid: 226, WWW_Authenticate: 209, challenge: 158, sipfrag: 230, Referred_By: 231 }; - var peg$startRuleIndex = 119; - var peg$consts = [ - "\r\n", - peg$literalExpectation("\r\n", false), - /^[0-9]/, - peg$classExpectation([["0", "9"]], false, false), - /^[a-zA-Z]/, - peg$classExpectation([["a", "z"], ["A", "Z"]], false, false), - /^[0-9a-fA-F]/, - peg$classExpectation([["0", "9"], ["a", "f"], ["A", "F"]], false, false), - /^[\0-\xFF]/, - peg$classExpectation([["\0", "\xFF"]], false, false), - /^["]/, - peg$classExpectation(["\""], false, false), - " ", - peg$literalExpectation(" ", false), - "\t", - peg$literalExpectation("\t", false), - /^[a-zA-Z0-9]/, - peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"]], false, false), - ";", - peg$literalExpectation(";", false), - "/", - peg$literalExpectation("/", false), - "?", - peg$literalExpectation("?", false), - ":", - peg$literalExpectation(":", false), - "@", - peg$literalExpectation("@", false), - "&", - peg$literalExpectation("&", false), - "=", - peg$literalExpectation("=", false), - "+", - peg$literalExpectation("+", false), - "$", - peg$literalExpectation("$", false), - ",", - peg$literalExpectation(",", false), - "-", - peg$literalExpectation("-", false), - "_", - peg$literalExpectation("_", false), - ".", - peg$literalExpectation(".", false), - "!", - peg$literalExpectation("!", false), - "~", - peg$literalExpectation("~", false), - "*", - peg$literalExpectation("*", false), - "'", - peg$literalExpectation("'", false), - "(", - peg$literalExpectation("(", false), - ")", - peg$literalExpectation(")", false), - "%", - peg$literalExpectation("%", false), - function () { return " "; }, - function () { return ':'; }, - /^[!-~]/, - peg$classExpectation([["!", "~"]], false, false), - /^[\x80-\uFFFF]/, - peg$classExpectation([["\x80", "\uFFFF"]], false, false), - /^[\x80-\xBF]/, - peg$classExpectation([["\x80", "\xBF"]], false, false), - /^[a-f]/, - peg$classExpectation([["a", "f"]], false, false), - "`", - peg$literalExpectation("`", false), - "<", - peg$literalExpectation("<", false), - ">", - peg$literalExpectation(">", false), - "\\", - peg$literalExpectation("\\", false), - "[", - peg$literalExpectation("[", false), - "]", - peg$literalExpectation("]", false), - "{", - peg$literalExpectation("{", false), - "}", - peg$literalExpectation("}", false), - function () { return "*"; }, - function () { return "/"; }, - function () { return "="; }, - function () { return "("; }, - function () { return ")"; }, - function () { return ">"; }, - function () { return "<"; }, - function () { return ","; }, - function () { return ";"; }, - function () { return ":"; }, - function () { return "\""; }, - /^[!-']/, - peg$classExpectation([["!", "'"]], false, false), - /^[*-[]/, - peg$classExpectation([["*", "["]], false, false), - /^[\]-~]/, - peg$classExpectation([["]", "~"]], false, false), - function (contents) { - return contents; - }, - /^[#-[]/, - peg$classExpectation([["#", "["]], false, false), - /^[\0-\t]/, - peg$classExpectation([["\0", "\t"]], false, false), - /^[\x0B-\f]/, - peg$classExpectation([["\x0B", "\f"]], false, false), - /^[\x0E-\x7F]/, - peg$classExpectation([["\x0E", "\x7F"]], false, false), - function () { - options = options || { data: {} }; - options.data.uri = new uri_1.URI(options.data.scheme, options.data.user, options.data.host, options.data.port); - delete options.data.scheme; - delete options.data.user; - delete options.data.host; - delete options.data.host_type; - delete options.data.port; - }, - function () { - options = options || { data: {} }; - options.data.uri = new uri_1.URI(options.data.scheme, options.data.user, options.data.host, options.data.port, options.data.uri_params, options.data.uri_headers); - delete options.data.scheme; - delete options.data.user; - delete options.data.host; - delete options.data.host_type; - delete options.data.port; - delete options.data.uri_params; - if (options.startRule === 'SIP_URI') { - options.data = options.data.uri; - } - }, - "sips", - peg$literalExpectation("sips", true), - "sip", - peg$literalExpectation("sip", true), - function (uri_scheme) { - options = options || { data: {} }; - options.data.scheme = uri_scheme; - }, - function () { - options = options || { data: {} }; - options.data.user = decodeURIComponent(text().slice(0, -1)); - }, - function () { - options = options || { data: {} }; - options.data.password = text(); - }, - function () { - options = options || { data: {} }; - options.data.host = text(); - return options.data.host; - }, - function () { - options = options || { data: {} }; - options.data.host_type = 'domain'; - return text(); - }, - /^[a-zA-Z0-9_\-]/, - peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"], "_", "-"], false, false), - /^[a-zA-Z0-9\-]/, - peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"], "-"], false, false), - function () { - options = options || { data: {} }; - options.data.host_type = 'IPv6'; - return text(); - }, - "::", - peg$literalExpectation("::", false), - function () { - options = options || { data: {} }; - options.data.host_type = 'IPv6'; - return text(); - }, - function () { - options = options || { data: {} }; - options.data.host_type = 'IPv4'; - return text(); - }, - "25", - peg$literalExpectation("25", false), - /^[0-5]/, - peg$classExpectation([["0", "5"]], false, false), - "2", - peg$literalExpectation("2", false), - /^[0-4]/, - peg$classExpectation([["0", "4"]], false, false), - "1", - peg$literalExpectation("1", false), - /^[1-9]/, - peg$classExpectation([["1", "9"]], false, false), - function (port) { - options = options || { data: {} }; - port = parseInt(port.join('')); - options.data.port = port; - return port; - }, - "transport=", - peg$literalExpectation("transport=", true), - "udp", - peg$literalExpectation("udp", true), - "tcp", - peg$literalExpectation("tcp", true), - "sctp", - peg$literalExpectation("sctp", true), - "tls", - peg$literalExpectation("tls", true), - function (transport) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['transport'] = transport.toLowerCase(); - }, - "user=", - peg$literalExpectation("user=", true), - "phone", - peg$literalExpectation("phone", true), - "ip", - peg$literalExpectation("ip", true), - function (user) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['user'] = user.toLowerCase(); - }, - "method=", - peg$literalExpectation("method=", true), - function (method) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['method'] = method; - }, - "ttl=", - peg$literalExpectation("ttl=", true), - function (ttl) { - options = options || { data: {} }; - if (!options.data.params) - options.data.params = {}; - options.data.params['ttl'] = ttl; - }, - "maddr=", - peg$literalExpectation("maddr=", true), - function (maddr) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['maddr'] = maddr; - }, - "lr", - peg$literalExpectation("lr", true), - function () { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['lr'] = undefined; - }, - function (param, value) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - if (value === null) { - value = undefined; - } - else { - value = value[1]; - } - options.data.uri_params[param.toLowerCase()] = value; - }, - function (hname, hvalue) { - hname = hname.join('').toLowerCase(); - hvalue = hvalue.join(''); - options = options || { data: {} }; - if (!options.data.uri_headers) - options.data.uri_headers = {}; - if (!options.data.uri_headers[hname]) { - options.data.uri_headers[hname] = [hvalue]; - } - else { - options.data.uri_headers[hname].push(hvalue); - } - }, - function () { - options = options || { data: {} }; - // lots of tests fail if this isn't guarded... - if (options.startRule === 'Refer_To') { - options.data.uri = new uri_1.URI(options.data.scheme, options.data.user, options.data.host, options.data.port, options.data.uri_params, options.data.uri_headers); - delete options.data.scheme; - delete options.data.user; - delete options.data.host; - delete options.data.host_type; - delete options.data.port; - delete options.data.uri_params; - } - }, - "//", - peg$literalExpectation("//", false), - function () { - options = options || { data: {} }; - options.data.scheme = text(); - }, - peg$literalExpectation("SIP", true), - function () { - options = options || { data: {} }; - options.data.sip_version = text(); - }, - "INVITE", - peg$literalExpectation("INVITE", false), - "ACK", - peg$literalExpectation("ACK", false), - "VXACH", - peg$literalExpectation("VXACH", false), - "OPTIONS", - peg$literalExpectation("OPTIONS", false), - "BYE", - peg$literalExpectation("BYE", false), - "CANCEL", - peg$literalExpectation("CANCEL", false), - "REGISTER", - peg$literalExpectation("REGISTER", false), - "SUBSCRIBE", - peg$literalExpectation("SUBSCRIBE", false), - "NOTIFY", - peg$literalExpectation("NOTIFY", false), - "REFER", - peg$literalExpectation("REFER", false), - "PUBLISH", - peg$literalExpectation("PUBLISH", false), - function () { - options = options || { data: {} }; - options.data.method = text(); - return options.data.method; - }, - function (status_code) { - options = options || { data: {} }; - options.data.status_code = parseInt(status_code.join('')); - }, - function () { - options = options || { data: {} }; - options.data.reason_phrase = text(); - }, - function () { - options = options || { data: {} }; - options.data = text(); - }, - function () { - var idx, length; - options = options || { data: {} }; - length = options.data.multi_header.length; - for (idx = 0; idx < length; idx++) { - if (options.data.multi_header[idx].parsed === null) { - options.data = null; - break; - } - } - if (options.data !== null) { - options.data = options.data.multi_header; - } - else { - options.data = -1; - } - }, - function () { - var header; - options = options || { data: {} }; - if (!options.data.multi_header) - options.data.multi_header = []; - try { - header = new name_addr_header_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); - delete options.data.uri; - delete options.data.displayName; - delete options.data.params; - } - catch (e) { - header = null; - } - options.data.multi_header.push({ 'position': peg$currPos, - 'offset': location().start.offset, - 'parsed': header - }); - }, - function (displayName) { - displayName = text().trim(); - if (displayName[0] === '\"') { - displayName = displayName.substring(1, displayName.length - 1); - } - options = options || { data: {} }; - options.data.displayName = displayName; - }, - "q", - peg$literalExpectation("q", true), - function (q) { - options = options || { data: {} }; - if (!options.data.params) - options.data.params = {}; - options.data.params['q'] = q; - }, - "expires", - peg$literalExpectation("expires", true), - function (expires) { - options = options || { data: {} }; - if (!options.data.params) - options.data.params = {}; - options.data.params['expires'] = expires; - }, - function (delta_seconds) { - return parseInt(delta_seconds.join('')); - }, - "0", - peg$literalExpectation("0", false), - function () { - return parseFloat(text()); - }, - function (param, value) { - options = options || { data: {} }; - if (!options.data.params) - options.data.params = {}; - if (value === null) { - value = undefined; - } - else { - value = value[1]; - } - options.data.params[param.toLowerCase()] = value; - }, - "render", - peg$literalExpectation("render", true), - "session", - peg$literalExpectation("session", true), - "icon", - peg$literalExpectation("icon", true), - "alert", - peg$literalExpectation("alert", true), - function () { - options = options || { data: {} }; - if (options.startRule === 'Content_Disposition') { - options.data.type = text().toLowerCase(); - } - }, - "handling", - peg$literalExpectation("handling", true), - "optional", - peg$literalExpectation("optional", true), - "required", - peg$literalExpectation("required", true), - function (length) { - options = options || { data: {} }; - options.data = parseInt(length.join('')); - }, - function () { - options = options || { data: {} }; - options.data = text(); - }, - "text", - peg$literalExpectation("text", true), - "image", - peg$literalExpectation("image", true), - "audio", - peg$literalExpectation("audio", true), - "video", - peg$literalExpectation("video", true), - "application", - peg$literalExpectation("application", true), - "message", - peg$literalExpectation("message", true), - "multipart", - peg$literalExpectation("multipart", true), - "x-", - peg$literalExpectation("x-", true), - function (cseq_value) { - options = options || { data: {} }; - options.data.value = parseInt(cseq_value.join('')); - }, - function (expires) { options = options || { data: {} }; options.data = expires; }, - function (event_type) { - options = options || { data: {} }; - options.data.event = event_type.toLowerCase(); - }, - function () { - options = options || { data: {} }; - var tag = options.data.tag; - options.data = new name_addr_header_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); - if (tag) { - options.data.setParam('tag', tag); - } - }, - "tag", - peg$literalExpectation("tag", true), - function (tag) { options = options || { data: {} }; options.data.tag = tag; }, - function (forwards) { - options = options || { data: {} }; - options.data = parseInt(forwards.join('')); - }, - function (min_expires) { options = options || { data: {} }; options.data = min_expires; }, - function () { - options = options || { data: {} }; - options.data = new name_addr_header_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); - }, - "digest", - peg$literalExpectation("Digest", true), - "realm", - peg$literalExpectation("realm", true), - function (realm) { options = options || { data: {} }; options.data.realm = realm; }, - "domain", - peg$literalExpectation("domain", true), - "nonce", - peg$literalExpectation("nonce", true), - function (nonce) { options = options || { data: {} }; options.data.nonce = nonce; }, - "opaque", - peg$literalExpectation("opaque", true), - function (opaque) { options = options || { data: {} }; options.data.opaque = opaque; }, - "stale", - peg$literalExpectation("stale", true), - "true", - peg$literalExpectation("true", true), - function () { options = options || { data: {} }; options.data.stale = true; }, - "false", - peg$literalExpectation("false", true), - function () { options = options || { data: {} }; options.data.stale = false; }, - "algorithm", - peg$literalExpectation("algorithm", true), - "md5", - peg$literalExpectation("MD5", true), - "md5-sess", - peg$literalExpectation("MD5-sess", true), - function (algorithm) { - options = options || { data: {} }; - options.data.algorithm = algorithm.toUpperCase(); - }, - "qop", - peg$literalExpectation("qop", true), - "auth-int", - peg$literalExpectation("auth-int", true), - "auth", - peg$literalExpectation("auth", true), - function (qop_value) { - options = options || { data: {} }; - options.data.qop || (options.data.qop = []); - options.data.qop.push(qop_value.toLowerCase()); - }, - function (rack_value) { - options = options || { data: {} }; - options.data.value = parseInt(rack_value.join('')); - }, - function () { - var idx, length; - options = options || { data: {} }; - length = options.data.multi_header.length; - for (idx = 0; idx < length; idx++) { - if (options.data.multi_header[idx].parsed === null) { - options.data = null; - break; - } - } - if (options.data !== null) { - options.data = options.data.multi_header; - } - else { - options.data = -1; - } - }, - function () { - var header; - options = options || { data: {} }; - if (!options.data.multi_header) - options.data.multi_header = []; - try { - header = new name_addr_header_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); - delete options.data.uri; - delete options.data.displayName; - delete options.data.params; - } - catch (e) { - header = null; - } - options.data.multi_header.push({ 'position': peg$currPos, - 'offset': location().start.offset, - 'parsed': header - }); - }, - function () { - options = options || { data: {} }; - options.data = new name_addr_header_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); - }, - function () { - options = options || { data: {} }; - if (!(options.data.replaces_from_tag && options.data.replaces_to_tag)) { - options.data = -1; - } - }, - function () { - options = options || { data: {} }; - options.data = { - call_id: options.data - }; - }, - "from-tag", - peg$literalExpectation("from-tag", true), - function (from_tag) { - options = options || { data: {} }; - options.data.replaces_from_tag = from_tag; - }, - "to-tag", - peg$literalExpectation("to-tag", true), - function (to_tag) { - options = options || { data: {} }; - options.data.replaces_to_tag = to_tag; - }, - "early-only", - peg$literalExpectation("early-only", true), - function () { - options = options || { data: {} }; - options.data.early_only = true; - }, - function (head, r) { return r; }, - function (head, tail) { return list(head, tail); }, - function (value) { - options = options || { data: {} }; - if (options.startRule === 'Require') { - options.data = value || []; - } - }, - function (rseq_value) { - options = options || { data: {} }; - options.data.value = parseInt(rseq_value.join('')); - }, - "active", - peg$literalExpectation("active", true), - "pending", - peg$literalExpectation("pending", true), - "terminated", - peg$literalExpectation("terminated", true), - function () { - options = options || { data: {} }; - options.data.state = text(); - }, - "reason", - peg$literalExpectation("reason", true), - function (reason) { - options = options || { data: {} }; - if (typeof reason !== 'undefined') - options.data.reason = reason; - }, - function (expires) { - options = options || { data: {} }; - if (typeof expires !== 'undefined') - options.data.expires = expires; - }, - "retry_after", - peg$literalExpectation("retry_after", true), - function (retry_after) { - options = options || { data: {} }; - if (typeof retry_after !== 'undefined') - options.data.retry_after = retry_after; - }, - "deactivated", - peg$literalExpectation("deactivated", true), - "probation", - peg$literalExpectation("probation", true), - "rejected", - peg$literalExpectation("rejected", true), - "timeout", - peg$literalExpectation("timeout", true), - "giveup", - peg$literalExpectation("giveup", true), - "noresource", - peg$literalExpectation("noresource", true), - "invariant", - peg$literalExpectation("invariant", true), - function (value) { - options = options || { data: {} }; - if (options.startRule === 'Supported') { - options.data = value || []; - } - }, - function () { - options = options || { data: {} }; - var tag = options.data.tag; - options.data = new name_addr_header_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); - if (tag) { - options.data.setParam('tag', tag); - } - }, - "ttl", - peg$literalExpectation("ttl", true), - function (via_ttl_value) { - options = options || { data: {} }; - options.data.ttl = via_ttl_value; - }, - "maddr", - peg$literalExpectation("maddr", true), - function (via_maddr) { - options = options || { data: {} }; - options.data.maddr = via_maddr; - }, - "received", - peg$literalExpectation("received", true), - function (via_received) { - options = options || { data: {} }; - options.data.received = via_received; - }, - "branch", - peg$literalExpectation("branch", true), - function (via_branch) { - options = options || { data: {} }; - options.data.branch = via_branch; - }, - "rport", - peg$literalExpectation("rport", true), - function (response_port) { - options = options || { data: {} }; - if (typeof response_port !== 'undefined') - options.data.rport = response_port.join(''); - }, - function (via_protocol) { - options = options || { data: {} }; - options.data.protocol = via_protocol; - }, - peg$literalExpectation("UDP", true), - peg$literalExpectation("TCP", true), - peg$literalExpectation("TLS", true), - peg$literalExpectation("SCTP", true), - function (via_transport) { - options = options || { data: {} }; - options.data.transport = via_transport; - }, - function () { - options = options || { data: {} }; - options.data.host = text(); - }, - function (via_sent_by_port) { - options = options || { data: {} }; - options.data.port = parseInt(via_sent_by_port.join('')); - }, - function (ttl) { - return parseInt(ttl.join('')); - }, - function (deltaSeconds) { - options = options || { data: {} }; - if (options.startRule === 'Session_Expires') { - options.data.deltaSeconds = deltaSeconds; - } - }, - "refresher", - peg$literalExpectation("refresher", false), - "uas", - peg$literalExpectation("uas", false), - "uac", - peg$literalExpectation("uac", false), - function (endpoint) { - options = options || { data: {} }; - if (options.startRule === 'Session_Expires') { - options.data.refresher = endpoint; - } - }, - function (deltaSeconds) { - options = options || { data: {} }; - if (options.startRule === 'Min_SE') { - options.data = deltaSeconds; - } - }, - "stuns", - peg$literalExpectation("stuns", true), - "stun", - peg$literalExpectation("stun", true), - function (scheme) { - options = options || { data: {} }; - options.data.scheme = scheme; - }, - function (host) { - options = options || { data: {} }; - options.data.host = host; - }, - "?transport=", - peg$literalExpectation("?transport=", false), - "turns", - peg$literalExpectation("turns", true), - "turn", - peg$literalExpectation("turn", true), - function (transport) { - options = options || { data: {} }; - options.data.transport = transport; - }, - function () { - options = options || { data: {} }; - options.data = text(); - }, - "Referred-By", - peg$literalExpectation("Referred-By", false), - "b", - peg$literalExpectation("b", false), - "cid", - peg$literalExpectation("cid", false) - ]; - var peg$bytecode = [ - peg$decode("2 \"\"6 7!"), - peg$decode("4\"\"\"5!7#"), - peg$decode("4$\"\"5!7%"), - peg$decode("4&\"\"5!7'"), - peg$decode(";'.# &;("), - peg$decode("4(\"\"5!7)"), - peg$decode("4*\"\"5!7+"), - peg$decode("2,\"\"6,7-"), - peg$decode("2.\"\"6.7/"), - peg$decode("40\"\"5!71"), - peg$decode("22\"\"6273.\x89 &24\"\"6475.} &26\"\"6677.q &28\"\"6879.e &2:\"\"6:7;.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E"), - peg$decode(";).# &;,"), - peg$decode("2F\"\"6F7G.} &2H\"\"6H7I.q &2J\"\"6J7K.e &2L\"\"6L7M.Y &2N\"\"6N7O.M &2P\"\"6P7Q.A &2R\"\"6R7S.5 &2T\"\"6T7U.) &2V\"\"6V7W"), - peg$decode("%%2X\"\"6X7Y/5#;#/,$;#/#$+#)(#'#(\"'#&'#/\"!&,)"), - peg$decode("%%$;$0#*;$&/,#; /#$+\")(\"'#&'#.\" &\"/=#$;$/�#*;$&&&#/'$8\":Z\" )(\"'#&'#"), - peg$decode(";..\" &\""), - peg$decode("%$;'.# &;(0)*;'.# &;(&/?#28\"\"6879/0$;//'$8#:[# )(#'#(\"'#&'#"), - peg$decode("%%$;2/�#*;2&&&#/g#$%$;.0#*;.&/,#;2/#$+\")(\"'#&'#0=*%$;.0#*;.&/,#;2/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/\"!&,)"), - peg$decode("4\\\"\"5!7].# &;3"), - peg$decode("4^\"\"5!7_"), - peg$decode("4`\"\"5!7a"), - peg$decode(";!.) &4b\"\"5!7c"), - peg$decode("%$;).\x95 &2F\"\"6F7G.\x89 &2J\"\"6J7K.} &2L\"\"6L7M.q &2X\"\"6X7Y.e &2P\"\"6P7Q.Y &2H\"\"6H7I.M &2@\"\"6@7A.A &2d\"\"6d7e.5 &2R\"\"6R7S.) &2N\"\"6N7O/\x9E#0\x9B*;).\x95 &2F\"\"6F7G.\x89 &2J\"\"6J7K.} &2L\"\"6L7M.q &2X\"\"6X7Y.e &2P\"\"6P7Q.Y &2H\"\"6H7I.M &2@\"\"6@7A.A &2d\"\"6d7e.5 &2R\"\"6R7S.) &2N\"\"6N7O&&&#/\"!&,)"), - peg$decode("%$;).\x89 &2F\"\"6F7G.} &2L\"\"6L7M.q &2X\"\"6X7Y.e &2P\"\"6P7Q.Y &2H\"\"6H7I.M &2@\"\"6@7A.A &2d\"\"6d7e.5 &2R\"\"6R7S.) &2N\"\"6N7O/\x92#0\x8F*;).\x89 &2F\"\"6F7G.} &2L\"\"6L7M.q &2X\"\"6X7Y.e &2P\"\"6P7Q.Y &2H\"\"6H7I.M &2@\"\"6@7A.A &2d\"\"6d7e.5 &2R\"\"6R7S.) &2N\"\"6N7O&&&#/\"!&,)"), - peg$decode("2T\"\"6T7U.\xE3 &2V\"\"6V7W.\xD7 &2f\"\"6f7g.\xCB &2h\"\"6h7i.\xBF &2:\"\"6:7;.\xB3 &2D\"\"6D7E.\xA7 &22\"\"6273.\x9B &28\"\"6879.\x8F &2j\"\"6j7k.\x83 &;&.} &24\"\"6475.q &2l\"\"6l7m.e &2n\"\"6n7o.Y &26\"\"6677.M &2>\"\"6>7?.A &2p\"\"6p7q.5 &2r\"\"6r7s.) &;'.# &;("), - peg$decode("%$;).\u012B &2F\"\"6F7G.\u011F &2J\"\"6J7K.\u0113 &2L\"\"6L7M.\u0107 &2X\"\"6X7Y.\xFB &2P\"\"6P7Q.\xEF &2H\"\"6H7I.\xE3 &2@\"\"6@7A.\xD7 &2d\"\"6d7e.\xCB &2R\"\"6R7S.\xBF &2N\"\"6N7O.\xB3 &2T\"\"6T7U.\xA7 &2V\"\"6V7W.\x9B &2f\"\"6f7g.\x8F &2h\"\"6h7i.\x83 &28\"\"6879.w &2j\"\"6j7k.k &;&.e &24\"\"6475.Y &2l\"\"6l7m.M &2n\"\"6n7o.A &26\"\"6677.5 &2p\"\"6p7q.) &2r\"\"6r7s/\u0134#0\u0131*;).\u012B &2F\"\"6F7G.\u011F &2J\"\"6J7K.\u0113 &2L\"\"6L7M.\u0107 &2X\"\"6X7Y.\xFB &2P\"\"6P7Q.\xEF &2H\"\"6H7I.\xE3 &2@\"\"6@7A.\xD7 &2d\"\"6d7e.\xCB &2R\"\"6R7S.\xBF &2N\"\"6N7O.\xB3 &2T\"\"6T7U.\xA7 &2V\"\"6V7W.\x9B &2f\"\"6f7g.\x8F &2h\"\"6h7i.\x83 &28\"\"6879.w &2j\"\"6j7k.k &;&.e &24\"\"6475.Y &2l\"\"6l7m.M &2n\"\"6n7o.A &26\"\"6677.5 &2p\"\"6p7q.) &2r\"\"6r7s&&&#/\"!&,)"), - peg$decode("%;//?#2P\"\"6P7Q/0$;//'$8#:t# )(#'#(\"'#&'#"), - peg$decode("%;//?#24\"\"6475/0$;//'$8#:u# )(#'#(\"'#&'#"), - peg$decode("%;//?#2>\"\"6>7?/0$;//'$8#:v# )(#'#(\"'#&'#"), - peg$decode("%;//?#2T\"\"6T7U/0$;//'$8#:w# )(#'#(\"'#&'#"), - peg$decode("%;//?#2V\"\"6V7W/0$;//'$8#:x# )(#'#(\"'#&'#"), - peg$decode("%2h\"\"6h7i/0#;//'$8\":y\" )(\"'#&'#"), - peg$decode("%;//6#2f\"\"6f7g/'$8\":z\" )(\"'#&'#"), - peg$decode("%;//?#2D\"\"6D7E/0$;//'$8#:{# )(#'#(\"'#&'#"), - peg$decode("%;//?#22\"\"6273/0$;//'$8#:|# )(#'#(\"'#&'#"), - peg$decode("%;//?#28\"\"6879/0$;//'$8#:}# )(#'#(\"'#&'#"), - peg$decode("%;//0#;&/'$8\":~\" )(\"'#&'#"), - peg$decode("%;&/0#;//'$8\":~\" )(\"'#&'#"), - peg$decode("%;=/T#$;G.) &;K.# &;F0/*;G.) &;K.# &;F&/,$;>/#$+#)(#'#(\"'#&'#"), - peg$decode("4\x7F\"\"5!7\x80.A &4\x81\"\"5!7\x82.5 &4\x83\"\"5!7\x84.) &;3.# &;."), - peg$decode("%%;//Q#;&/H$$;J.# &;K0)*;J.# &;K&/,$;&/#$+$)($'#(#'#(\"'#&'#/\"!&,)"), - peg$decode("%;//]#;&/T$%$;J.# &;K0)*;J.# &;K&/\"!&,)/1$;&/($8$:\x85$!!)($'#(#'#(\"'#&'#"), - peg$decode(";..G &2L\"\"6L7M.; &4\x86\"\"5!7\x87./ &4\x83\"\"5!7\x84.# &;3"), - peg$decode("%2j\"\"6j7k/J#4\x88\"\"5!7\x89.5 &4\x8A\"\"5!7\x8B.) &4\x8C\"\"5!7\x8D/#$+\")(\"'#&'#"), - peg$decode("%;N/M#28\"\"6879/>$;O.\" &\"/0$;S/'$8$:\x8E$ )($'#(#'#(\"'#&'#"), - peg$decode("%;N/d#28\"\"6879/U$;O.\" &\"/G$;S/>$;_/5$;l.\" &\"/'$8&:\x8F& )(&'#(%'#($'#(#'#(\"'#&'#"), - peg$decode("%3\x90\"\"5$7\x91.) &3\x92\"\"5#7\x93/' 8!:\x94!! )"), - peg$decode("%;P/]#%28\"\"6879/,#;R/#$+\")(\"'#&'#.\" &\"/6$2:\"\"6:7;/'$8#:\x95# )(#'#(\"'#&'#"), - peg$decode("$;+.) &;-.# &;Q/2#0/*;+.) &;-.# &;Q&&&#"), - peg$decode("2<\"\"6<7=.q &2>\"\"6>7?.e &2@\"\"6@7A.Y &2B\"\"6B7C.M &2D\"\"6D7E.A &22\"\"6273.5 &26\"\"6677.) &24\"\"6475"), - peg$decode("%$;+._ &;-.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E0e*;+._ &;-.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E&/& 8!:\x96! )"), - peg$decode("%;T/J#%28\"\"6879/,#;^/#$+\")(\"'#&'#.\" &\"/#$+\")(\"'#&'#"), - peg$decode("%;U.) &;\\.# &;X/& 8!:\x97! )"), - peg$decode("%$%;V/2#2J\"\"6J7K/#$+\")(\"'#&'#0<*%;V/2#2J\"\"6J7K/#$+\")(\"'#&'#&/D#;W/;$2J\"\"6J7K.\" &\"/'$8#:\x98# )(#'#(\"'#&'#"), - peg$decode("$4\x99\"\"5!7\x9A/,#0)*4\x99\"\"5!7\x9A&&&#"), - peg$decode("%4$\"\"5!7%/?#$4\x9B\"\"5!7\x9C0)*4\x9B\"\"5!7\x9C&/#$+\")(\"'#&'#"), - peg$decode("%2l\"\"6l7m/?#;Y/6$2n\"\"6n7o/'$8#:\x9D# )(#'#(\"'#&'#"), - peg$decode("%%;Z/\xB3#28\"\"6879/\xA4$;Z/\x9B$28\"\"6879/\x8C$;Z/\x83$28\"\"6879/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+-)(-'#(,'#(+'#(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0790 &%2\x9E\"\"6\x9E7\x9F/\xA4#;Z/\x9B$28\"\"6879/\x8C$;Z/\x83$28\"\"6879/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+,)(,'#(+'#(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u06F9 &%2\x9E\"\"6\x9E7\x9F/\x8C#;Z/\x83$28\"\"6879/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+*)(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u067A &%2\x9E\"\"6\x9E7\x9F/t#;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+()(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0613 &%2\x9E\"\"6\x9E7\x9F/\\#;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+&)(&'#(%'#($'#(#'#(\"'#&'#.\u05C4 &%2\x9E\"\"6\x9E7\x9F/D#;Z/;$28\"\"6879/,$;[/#$+$)($'#(#'#(\"'#&'#.\u058D &%2\x9E\"\"6\x9E7\x9F/,#;[/#$+\")(\"'#&'#.\u056E &%2\x9E\"\"6\x9E7\x9F/,#;Z/#$+\")(\"'#&'#.\u054F &%;Z/\x9B#2\x9E\"\"6\x9E7\x9F/\x8C$;Z/\x83$28\"\"6879/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$++)(+'#(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u04C7 &%;Z/\xAA#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x83$2\x9E\"\"6\x9E7\x9F/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+*)(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0430 &%;Z/\xB9#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x92$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/k$2\x9E\"\"6\x9E7\x9F/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+))()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u038A &%;Z/\xC8#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xA1$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/z$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/S$2\x9E\"\"6\x9E7\x9F/D$;Z/;$28\"\"6879/,$;[/#$+()(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u02D5 &%;Z/\xD7#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xB0$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x89$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/b$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/;$2\x9E\"\"6\x9E7\x9F/,$;[/#$+')(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0211 &%;Z/\xFE#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xD7$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xB0$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x89$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/b$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/;$2\x9E\"\"6\x9E7\x9F/,$;Z/#$+()(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0126 &%;Z/\u011C#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xF5$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xCE$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xA7$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x80$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/Y$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/2$2\x9E\"\"6\x9E7\x9F/#$+()(('#(''#(&'#(%'#($'#(#'#(\"'#&'#/& 8!:\xA0! )"), - peg$decode("%;#/M#;#.\" &\"/?$;#.\" &\"/1$;#.\" &\"/#$+$)($'#(#'#(\"'#&'#"), - peg$decode("%;Z/;#28\"\"6879/,$;Z/#$+#)(#'#(\"'#&'#.# &;\\"), - peg$decode("%;]/o#2J\"\"6J7K/`$;]/W$2J\"\"6J7K/H$;]/?$2J\"\"6J7K/0$;]/'$8':\xA1' )(''#(&'#(%'#($'#(#'#(\"'#&'#"), - peg$decode("%2\xA2\"\"6\xA27\xA3/2#4\xA4\"\"5!7\xA5/#$+\")(\"'#&'#.\x98 &%2\xA6\"\"6\xA67\xA7/;#4\xA8\"\"5!7\xA9/,$;!/#$+#)(#'#(\"'#&'#.j &%2\xAA\"\"6\xAA7\xAB/5#;!/,$;!/#$+#)(#'#(\"'#&'#.B &%4\xAC\"\"5!7\xAD/,#;!/#$+\")(\"'#&'#.# &;!"), - peg$decode("%%;!.\" &\"/[#;!.\" &\"/M$;!.\" &\"/?$;!.\" &\"/1$;!.\" &\"/#$+%)(%'#($'#(#'#(\"'#&'#/' 8!:\xAE!! )"), - peg$decode("$%22\"\"6273/,#;`/#$+\")(\"'#&'#0<*%22\"\"6273/,#;`/#$+\")(\"'#&'#&"), - peg$decode(";a.A &;b.; &;c.5 &;d./ &;e.) &;f.# &;g"), - peg$decode("%3\xAF\"\"5*7\xB0/a#3\xB1\"\"5#7\xB2.G &3\xB3\"\"5#7\xB4.; &3\xB5\"\"5$7\xB6./ &3\xB7\"\"5#7\xB8.# &;6/($8\":\xB9\"! )(\"'#&'#"), - peg$decode("%3\xBA\"\"5%7\xBB/I#3\xBC\"\"5%7\xBD./ &3\xBE\"\"5\"7\xBF.# &;6/($8\":\xC0\"! )(\"'#&'#"), - peg$decode("%3\xC1\"\"5'7\xC2/1#;\x90/($8\":\xC3\"! )(\"'#&'#"), - peg$decode("%3\xC4\"\"5$7\xC5/1#;\xF0/($8\":\xC6\"! )(\"'#&'#"), - peg$decode("%3\xC7\"\"5&7\xC8/1#;T/($8\":\xC9\"! )(\"'#&'#"), - peg$decode("%3\xCA\"\"5\"7\xCB/N#%2>\"\"6>7?/,#;6/#$+\")(\"'#&'#.\" &\"/'$8\":\xCC\" )(\"'#&'#"), - peg$decode("%;h/P#%2>\"\"6>7?/,#;i/#$+\")(\"'#&'#.\" &\"/)$8\":\xCD\"\"! )(\"'#&'#"), - peg$decode("%$;j/�#*;j&&&#/\"!&,)"), - peg$decode("%$;j/�#*;j&&&#/\"!&,)"), - peg$decode(";k.) &;+.# &;-"), - peg$decode("2l\"\"6l7m.e &2n\"\"6n7o.Y &24\"\"6475.M &28\"\"6879.A &2<\"\"6<7=.5 &2@\"\"6@7A.) &2B\"\"6B7C"), - peg$decode("%26\"\"6677/n#;m/e$$%2<\"\"6<7=/,#;m/#$+\")(\"'#&'#0<*%2<\"\"6<7=/,#;m/#$+\")(\"'#&'#&/#$+#)(#'#(\"'#&'#"), - peg$decode("%;n/A#2>\"\"6>7?/2$;o/)$8#:\xCE#\"\" )(#'#(\"'#&'#"), - peg$decode("$;p.) &;+.# &;-/2#0/*;p.) &;+.# &;-&&&#"), - peg$decode("$;p.) &;+.# &;-0/*;p.) &;+.# &;-&"), - peg$decode("2l\"\"6l7m.e &2n\"\"6n7o.Y &24\"\"6475.M &26\"\"6677.A &28\"\"6879.5 &2@\"\"6@7A.) &2B\"\"6B7C"), - peg$decode(";\x91.# &;r"), - peg$decode("%;\x90/G#;'/>$;s/5$;'/,$;\x84/#$+%)(%'#($'#(#'#(\"'#&'#"), - peg$decode(";M.# &;t"), - peg$decode("%;\x7F/E#28\"\"6879/6$;u.# &;x/'$8#:\xCF# )(#'#(\"'#&'#"), - peg$decode("%;v.# &;w/J#%26\"\"6677/,#;\x83/#$+\")(\"'#&'#.\" &\"/#$+\")(\"'#&'#"), - peg$decode("%2\xD0\"\"6\xD07\xD1/:#;\x80/1$;w.\" &\"/#$+#)(#'#(\"'#&'#"), - peg$decode("%24\"\"6475/,#;{/#$+\")(\"'#&'#"), - peg$decode("%;z/3#$;y0#*;y&/#$+\")(\"'#&'#"), - peg$decode(";*.) &;+.# &;-"), - peg$decode(";+.\x8F &;-.\x89 &22\"\"6273.} &26\"\"6677.q &28\"\"6879.e &2:\"\"6:7;.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E"), - peg$decode("%;|/e#$%24\"\"6475/,#;|/#$+\")(\"'#&'#0<*%24\"\"6475/,#;|/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"), - peg$decode("%$;~0#*;~&/e#$%22\"\"6273/,#;}/#$+\")(\"'#&'#0<*%22\"\"6273/,#;}/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"), - peg$decode("$;~0#*;~&"), - peg$decode(";+.w &;-.q &28\"\"6879.e &2:\"\"6:7;.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E"), - peg$decode("%%;\"/\x87#$;\".G &;!.A &2@\"\"6@7A.5 &2F\"\"6F7G.) &2J\"\"6J7K0M*;\".G &;!.A &2@\"\"6@7A.5 &2F\"\"6F7G.) &2J\"\"6J7K&/#$+\")(\"'#&'#/& 8!:\xD2! )"), - peg$decode(";\x81.# &;\x82"), - peg$decode("%%;O/2#2:\"\"6:7;/#$+\")(\"'#&'#.\" &\"/,#;S/#$+\")(\"'#&'#.\" &\""), - peg$decode("$;+.\x83 &;-.} &2B\"\"6B7C.q &2D\"\"6D7E.e &22\"\"6273.Y &28\"\"6879.M &2:\"\"6:7;.A &2<\"\"6<7=.5 &2>\"\"6>7?.) &2@\"\"6@7A/\x8C#0\x89*;+.\x83 &;-.} &2B\"\"6B7C.q &2D\"\"6D7E.e &22\"\"6273.Y &28\"\"6879.M &2:\"\"6:7;.A &2<\"\"6<7=.5 &2>\"\"6>7?.) &2@\"\"6@7A&&&#"), - peg$decode("$;y0#*;y&"), - peg$decode("%3\x92\"\"5#7\xD3/q#24\"\"6475/b$$;!/�#*;!&&&#/L$2J\"\"6J7K/=$$;!/�#*;!&&&#/'$8%:\xD4% )(%'#($'#(#'#(\"'#&'#"), - peg$decode("2\xD5\"\"6\xD57\xD6"), - peg$decode("2\xD7\"\"6\xD77\xD8"), - peg$decode("2\xD9\"\"6\xD97\xDA"), - peg$decode("2\xDB\"\"6\xDB7\xDC"), - peg$decode("2\xDD\"\"6\xDD7\xDE"), - peg$decode("2\xDF\"\"6\xDF7\xE0"), - peg$decode("2\xE1\"\"6\xE17\xE2"), - peg$decode("2\xE3\"\"6\xE37\xE4"), - peg$decode("2\xE5\"\"6\xE57\xE6"), - peg$decode("2\xE7\"\"6\xE77\xE8"), - peg$decode("2\xE9\"\"6\xE97\xEA"), - peg$decode("%;\x85.Y &;\x86.S &;\x88.M &;\x89.G &;\x8A.A &;\x8B.; &;\x8C.5 &;\x8F./ &;\x8D.) &;\x8E.# &;6/& 8!:\xEB! )"), - peg$decode("%;\x84/G#;'/>$;\x92/5$;'/,$;\x94/#$+%)(%'#($'#(#'#(\"'#&'#"), - peg$decode("%;\x93/' 8!:\xEC!! )"), - peg$decode("%;!/5#;!/,$;!/#$+#)(#'#(\"'#&'#"), - peg$decode("%$;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(0G*;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(&/& 8!:\xED! )"), - peg$decode("%;\xB6/Y#$%;A/,#;\xB6/#$+\")(\"'#&'#06*%;A/,#;\xB6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"), - peg$decode("%;9/N#%2:\"\"6:7;/,#;9/#$+\")(\"'#&'#.\" &\"/'$8\":\xEE\" )(\"'#&'#"), - peg$decode("%;:.c &%;\x98/Y#$%;A/,#;\x98/#$+\")(\"'#&'#06*%;A/,#;\x98/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/& 8!:\xEF! )"), - peg$decode("%;L.# &;\x99/]#$%;B/,#;\x9B/#$+\")(\"'#&'#06*%;B/,#;\x9B/#$+\")(\"'#&'#&/'$8\":\xF0\" )(\"'#&'#"), - peg$decode("%;\x9A.\" &\"/>#;@/5$;M/,$;?/#$+$)($'#(#'#(\"'#&'#"), - peg$decode("%%;6/Y#$%;./,#;6/#$+\")(\"'#&'#06*%;./,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#.# &;H/' 8!:\xF1!! )"), - peg$decode(";\x9C.) &;\x9D.# &;\xA0"), - peg$decode("%3\xF2\"\"5!7\xF3/:#;$;\xCF/5$;./,$;\x90/#$+%)(%'#($'#(#'#(\"'#&'#"), - peg$decode("%$;!/�#*;!&&&#/' 8!:\u014B!! )"), - peg$decode("%;\xD1/]#$%;A/,#;\xD1/#$+\")(\"'#&'#06*%;A/,#;\xD1/#$+\")(\"'#&'#&/'$8\":\u014C\" )(\"'#&'#"), - peg$decode("%;\x99/]#$%;B/,#;\xA0/#$+\")(\"'#&'#06*%;B/,#;\xA0/#$+\")(\"'#&'#&/'$8\":\u014D\" )(\"'#&'#"), - peg$decode("%;L.O &;\x99.I &%;@.\" &\"/:#;t/1$;?.\" &\"/#$+#)(#'#(\"'#&'#/]#$%;B/,#;\xA0/#$+\")(\"'#&'#06*%;B/,#;\xA0/#$+\")(\"'#&'#&/'$8\":\u014E\" )(\"'#&'#"), - peg$decode("%;\xD4/]#$%;B/,#;\xD5/#$+\")(\"'#&'#06*%;B/,#;\xD5/#$+\")(\"'#&'#&/'$8\":\u014F\" )(\"'#&'#"), - peg$decode("%;\x96/& 8!:\u0150! )"), - peg$decode("%3\u0151\"\"5(7\u0152/:#;$;6/5$;;/,$;\xEC/#$+%)(%'#($'#(#'#(\"'#&'#"), - peg$decode("%3\x92\"\"5#7\xD3.# &;6/' 8!:\u018B!! )"), - peg$decode("%3\xB1\"\"5#7\u018C.G &3\xB3\"\"5#7\u018D.; &3\xB7\"\"5#7\u018E./ &3\xB5\"\"5$7\u018F.# &;6/' 8!:\u0190!! )"), - peg$decode("%;\xEE/D#%;C/,#;\xEF/#$+\")(\"'#&'#.\" &\"/#$+\")(\"'#&'#"), - peg$decode("%;U.) &;\\.# &;X/& 8!:\u0191! )"), - peg$decode("%%;!.\" &\"/[#;!.\" &\"/M$;!.\" &\"/?$;!.\" &\"/1$;!.\" &\"/#$+%)(%'#($'#(#'#(\"'#&'#/' 8!:\u0192!! )"), - peg$decode("%%;!/?#;!.\" &\"/1$;!.\" &\"/#$+#)(#'#(\"'#&'#/' 8!:\u0193!! )"), - peg$decode(";\xBE"), - peg$decode("%;\x9E/^#$%;B/,#;\xF3/#$+\")(\"'#&'#06*%;B/,#;\xF3/#$+\")(\"'#&'#&/($8\":\u0194\"!!)(\"'#&'#"), - peg$decode(";\xF4.# &;\xA0"), - peg$decode("%2\u0195\"\"6\u01957\u0196/L#;\"\"6>7?"), - peg$decode("%;\u0100/b#28\"\"6879/S$;\xFB/J$%2\u01A3\"\"6\u01A37\u01A4/,#;\xEC/#$+\")(\"'#&'#.\" &\"/#$+$)($'#(#'#(\"'#&'#"), - peg$decode("%3\u01A5\"\"5%7\u01A6.) &3\u01A7\"\"5$7\u01A8/' 8!:\u01A1!! )"), - peg$decode("%3\xB1\"\"5#7\xB2.6 &3\xB3\"\"5#7\xB4.* &$;+0#*;+&/' 8!:\u01A9!! )"), - peg$decode("%;\u0104/\x87#2F\"\"6F7G/x$;\u0103/o$2F\"\"6F7G/`$;\u0103/W$2F\"\"6F7G/H$;\u0103/?$2F\"\"6F7G/0$;\u0105/'$8):\u01AA) )()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#"), - peg$decode("%;#/>#;#/5$;#/,$;#/#$+$)($'#(#'#(\"'#&'#"), - peg$decode("%;\u0103/,#;\u0103/#$+\")(\"'#&'#"), - peg$decode("%;\u0103/5#;\u0103/,$;\u0103/#$+#)(#'#(\"'#&'#"), - peg$decode("%;q/T#$;m0#*;m&/D$%; /,#;\xF8/#$+\")(\"'#&'#.\" &\"/#$+#)(#'#(\"'#&'#"), - peg$decode("%2\u01AB\"\"6\u01AB7\u01AC.) &2\u01AD\"\"6\u01AD7\u01AE/w#;0/n$;\u0108/e$$%;B/2#;\u0109.# &;\xA0/#$+\")(\"'#&'#0<*%;B/2#;\u0109.# &;\xA0/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"), - peg$decode(";\x99.# &;L"), - peg$decode("%2\u01AF\"\"6\u01AF7\u01B0/5#; peg$maxFailPos) { - peg$maxFailPos = peg$currPos; - peg$maxFailExpected = []; - } - peg$maxFailExpected.push(expected1); - } - function peg$buildSimpleError(message, location1) { - return new SyntaxError(message, [], "", location1); - } - function peg$buildStructuredError(expected1, found, location1) { - return new SyntaxError(SyntaxError.buildMessage(expected1, found), expected1, found, location1); - } - function peg$decode(s) { - return s.split("").map(function (ch) { return ch.charCodeAt(0) - 32; }); - } - function peg$parseRule(index) { - var bc = peg$bytecode[index]; - var ip = 0; - var ips = []; - var end = bc.length; - var ends = []; - var stack = []; - var params; - while (true) { - while (ip < end) { - switch (bc[ip]) { - case 0: - stack.push(peg$consts[bc[ip + 1]]); - ip += 2; - break; - case 1: - stack.push(undefined); - ip++; - break; - case 2: - stack.push(null); - ip++; - break; - case 3: - stack.push(peg$FAILED); - ip++; - break; - case 4: - stack.push([]); - ip++; - break; - case 5: - stack.push(peg$currPos); - ip++; - break; - case 6: - stack.pop(); - ip++; - break; - case 7: - peg$currPos = stack.pop(); - ip++; - break; - case 8: - stack.length -= bc[ip + 1]; - ip += 2; - break; - case 9: - stack.splice(-2, 1); - ip++; - break; - case 10: - stack[stack.length - 2].push(stack.pop()); - ip++; - break; - case 11: - stack.push(stack.splice(stack.length - bc[ip + 1], bc[ip + 1])); - ip += 2; - break; - case 12: - stack.push(input.substring(stack.pop(), peg$currPos)); - ip++; - break; - case 13: - ends.push(end); - ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); - if (stack[stack.length - 1]) { - end = ip + 3 + bc[ip + 1]; - ip += 3; - } - else { - end = ip + 3 + bc[ip + 1] + bc[ip + 2]; - ip += 3 + bc[ip + 1]; - } - break; - case 14: - ends.push(end); - ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); - if (stack[stack.length - 1] === peg$FAILED) { - end = ip + 3 + bc[ip + 1]; - ip += 3; - } - else { - end = ip + 3 + bc[ip + 1] + bc[ip + 2]; - ip += 3 + bc[ip + 1]; - } - break; - case 15: - ends.push(end); - ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); - if (stack[stack.length - 1] !== peg$FAILED) { - end = ip + 3 + bc[ip + 1]; - ip += 3; - } - else { - end = ip + 3 + bc[ip + 1] + bc[ip + 2]; - ip += 3 + bc[ip + 1]; - } - break; - case 16: - if (stack[stack.length - 1] !== peg$FAILED) { - ends.push(end); - ips.push(ip); - end = ip + 2 + bc[ip + 1]; - ip += 2; - } - else { - ip += 2 + bc[ip + 1]; - } - break; - case 17: - ends.push(end); - ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); - if (input.length > peg$currPos) { - end = ip + 3 + bc[ip + 1]; - ip += 3; - } - else { - end = ip + 3 + bc[ip + 1] + bc[ip + 2]; - ip += 3 + bc[ip + 1]; - } - break; - case 18: - ends.push(end); - ips.push(ip + 4 + bc[ip + 2] + bc[ip + 3]); - if (input.substr(peg$currPos, peg$consts[bc[ip + 1]].length) === peg$consts[bc[ip + 1]]) { - end = ip + 4 + bc[ip + 2]; - ip += 4; - } - else { - end = ip + 4 + bc[ip + 2] + bc[ip + 3]; - ip += 4 + bc[ip + 2]; - } - break; - case 19: - ends.push(end); - ips.push(ip + 4 + bc[ip + 2] + bc[ip + 3]); - if (input.substr(peg$currPos, peg$consts[bc[ip + 1]].length).toLowerCase() === peg$consts[bc[ip + 1]]) { - end = ip + 4 + bc[ip + 2]; - ip += 4; - } - else { - end = ip + 4 + bc[ip + 2] + bc[ip + 3]; - ip += 4 + bc[ip + 2]; - } - break; - case 20: - ends.push(end); - ips.push(ip + 4 + bc[ip + 2] + bc[ip + 3]); - if (peg$consts[bc[ip + 1]].test(input.charAt(peg$currPos))) { - end = ip + 4 + bc[ip + 2]; - ip += 4; - } - else { - end = ip + 4 + bc[ip + 2] + bc[ip + 3]; - ip += 4 + bc[ip + 2]; - } - break; - case 21: - stack.push(input.substr(peg$currPos, bc[ip + 1])); - peg$currPos += bc[ip + 1]; - ip += 2; - break; - case 22: - stack.push(peg$consts[bc[ip + 1]]); - peg$currPos += peg$consts[bc[ip + 1]].length; - ip += 2; - break; - case 23: - stack.push(peg$FAILED); - if (peg$silentFails === 0) { - peg$fail(peg$consts[bc[ip + 1]]); - } - ip += 2; - break; - case 24: - peg$savedPos = stack[stack.length - 1 - bc[ip + 1]]; - ip += 2; - break; - case 25: - peg$savedPos = peg$currPos; - ip++; - break; - case 26: - params = bc.slice(ip + 4, ip + 4 + bc[ip + 3]) - .map(function (p) { return stack[stack.length - 1 - p]; }); - stack.splice(stack.length - bc[ip + 2], bc[ip + 2], peg$consts[bc[ip + 1]].apply(null, params)); - ip += 4 + bc[ip + 3]; - break; - case 27: - stack.push(peg$parseRule(bc[ip + 1])); - ip += 2; - break; - case 28: - peg$silentFails++; - ip++; - break; - case 29: - peg$silentFails--; - ip++; - break; - default: - throw new Error("Invalid opcode: " + bc[ip] + "."); - } - } - if (ends.length > 0) { - end = ends.pop(); - ip = ips.pop(); - } - else { - break; - } - } - return stack[0]; - } - options.data = {}; // Object to which header attributes will be assigned during parsing - function list(head, tail) { - return [head].concat(tail); - } - peg$result = peg$parseRule(peg$startRuleIndex); - if (peg$result !== peg$FAILED && peg$currPos === input.length) { - return peg$result; - } - else { - if (peg$result !== peg$FAILED && peg$currPos < input.length) { - peg$fail(peg$endExpectation()); - } - throw peg$buildStructuredError(peg$maxFailExpected, peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, peg$maxFailPos < input.length - ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) - : peg$computeLocation(peg$maxFailPos, peg$maxFailPos)); - } -} -exports.parse = peg$parse; - - -/***/ }), -/* 13 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var parameters_1 = __webpack_require__(14); -/** - * Name Address SIP header. - * @public - */ -var NameAddrHeader = /** @class */ (function (_super) { - tslib_1.__extends(NameAddrHeader, _super); - /** - * Constructor - * @param uri - - * @param displayName - - * @param parameters - - */ - function NameAddrHeader(uri, displayName, parameters) { - var _this = _super.call(this, parameters) || this; - _this.uri = uri; - _this._displayName = displayName; - return _this; - } - Object.defineProperty(NameAddrHeader.prototype, "friendlyName", { - get: function () { - return this.displayName || this.uri.aor; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(NameAddrHeader.prototype, "displayName", { - get: function () { return this._displayName; }, - set: function (value) { - this._displayName = value; - }, - enumerable: true, - configurable: true - }); - NameAddrHeader.prototype.clone = function () { - return new NameAddrHeader(this.uri.clone(), this._displayName, JSON.parse(JSON.stringify(this.parameters))); - }; - NameAddrHeader.prototype.toString = function () { - var body = (this.displayName || this.displayName === "0") ? '"' + this.displayName + '" ' : ""; - body += "<" + this.uri.toString() + ">"; - for (var parameter in this.parameters) { - if (this.parameters.hasOwnProperty(parameter)) { - body += ";" + parameter; - if (this.parameters[parameter] !== null) { - body += "=" + this.parameters[parameter]; - } - } - } - return body; - }; - return NameAddrHeader; -}(parameters_1.Parameters)); -exports.NameAddrHeader = NameAddrHeader; - - -/***/ }), -/* 14 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * @internal - */ -var Parameters = /** @class */ (function () { - function Parameters(parameters) { - this.parameters = {}; - for (var param in parameters) { - if (parameters.hasOwnProperty(param)) { - this.setParam(param, parameters[param]); - } - } - } - Parameters.prototype.setParam = function (key, value) { - if (key) { - this.parameters[key.toLowerCase()] = (typeof value === "undefined" || value === null) ? null : value.toString(); - } - }; - Parameters.prototype.getParam = function (key) { - if (key) { - return this.parameters[key.toLowerCase()]; - } - }; - Parameters.prototype.hasParam = function (key) { - if (key) { - return !!this.parameters.hasOwnProperty(key.toLowerCase()); - } - return false; - }; - Parameters.prototype.deleteParam = function (parameter) { - parameter = parameter.toLowerCase(); - if (this.parameters.hasOwnProperty(parameter)) { - var value = this.parameters[parameter]; - delete this.parameters[parameter]; - return value; - } - }; - Parameters.prototype.clearParams = function () { - this.parameters = {}; - }; - return Parameters; -}()); -exports.Parameters = Parameters; - - -/***/ }), -/* 15 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var parameters_1 = __webpack_require__(14); -/** - * URI. - * @public - */ -var URI = /** @class */ (function (_super) { - tslib_1.__extends(URI, _super); - /** - * Constructor - * @param scheme - - * @param user - - * @param host - - * @param port - - * @param parameters - - * @param headers - - */ - function URI(scheme, user, host, port, parameters, headers) { - var _this = _super.call(this, parameters) || this; - _this.headers = {}; - // Checks - if (!host) { - throw new TypeError('missing or invalid "host" parameter'); - } - // Initialize parameters - scheme = scheme || "sip"; - for (var header in headers) { - if (headers.hasOwnProperty(header)) { - _this.setHeader(header, headers[header]); - } - } - // Raw URI - _this.raw = { - scheme: scheme, - user: user, - host: host, - port: port - }; - // Normalized URI - _this.normal = { - scheme: scheme.toLowerCase(), - user: user, - host: host.toLowerCase(), - port: port - }; - return _this; - } - Object.defineProperty(URI.prototype, "scheme", { - get: function () { return this.normal.scheme; }, - set: function (value) { - this.raw.scheme = value; - this.normal.scheme = value.toLowerCase(); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(URI.prototype, "user", { - get: function () { return this.normal.user; }, - set: function (value) { - this.normal.user = this.raw.user = value; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(URI.prototype, "host", { - get: function () { return this.normal.host; }, - set: function (value) { - this.raw.host = value; - this.normal.host = value.toLowerCase(); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(URI.prototype, "aor", { - get: function () { return this.normal.user + "@" + this.normal.host; }, - enumerable: true, - configurable: true - }); - Object.defineProperty(URI.prototype, "port", { - get: function () { return this.normal.port; }, - set: function (value) { - this.normal.port = this.raw.port = value === 0 ? value : value; - }, - enumerable: true, - configurable: true - }); - URI.prototype.setHeader = function (name, value) { - this.headers[this.headerize(name)] = (value instanceof Array) ? value : [value]; - }; - URI.prototype.getHeader = function (name) { - if (name) { - return this.headers[this.headerize(name)]; - } - }; - URI.prototype.hasHeader = function (name) { - return !!name && !!this.headers.hasOwnProperty(this.headerize(name)); - }; - URI.prototype.deleteHeader = function (header) { - header = this.headerize(header); - if (this.headers.hasOwnProperty(header)) { - var value = this.headers[header]; - delete this.headers[header]; - return value; - } - }; - URI.prototype.clearHeaders = function () { - this.headers = {}; - }; - URI.prototype.clone = function () { - return new URI(this._raw.scheme, this._raw.user || "", this._raw.host, this._raw.port, JSON.parse(JSON.stringify(this.parameters)), JSON.parse(JSON.stringify(this.headers))); - }; - URI.prototype.toRaw = function () { - return this._toString(this._raw); - }; - URI.prototype.toString = function () { - return this._toString(this._normal); - }; - Object.defineProperty(URI.prototype, "_normal", { - get: function () { return this.normal; }, - enumerable: true, - configurable: true - }); - Object.defineProperty(URI.prototype, "_raw", { - get: function () { return this.raw; }, - enumerable: true, - configurable: true - }); - URI.prototype._toString = function (uri) { - var uriString = uri.scheme + ":"; - // add slashes if it's not a sip(s) URI - if (!uri.scheme.toLowerCase().match("^sips?$")) { - uriString += "//"; - } - if (uri.user) { - uriString += this.escapeUser(uri.user) + "@"; - } - uriString += uri.host; - if (uri.port || uri.port === 0) { - uriString += ":" + uri.port; - } - for (var parameter in this.parameters) { - if (this.parameters.hasOwnProperty(parameter)) { - uriString += ";" + parameter; - if (this.parameters[parameter] !== null) { - uriString += "=" + this.parameters[parameter]; - } - } - } - var headers = []; - for (var header in this.headers) { - if (this.headers.hasOwnProperty(header)) { - for (var idx in this.headers[header]) { - if (this.headers[header].hasOwnProperty(idx)) { - headers.push(header + "=" + this.headers[header][idx]); - } - } - } - } - if (headers.length > 0) { - uriString += "?" + headers.join("&"); - } - return uriString; - }; - /* - * Hex-escape a SIP URI user. - * @private - * @param {String} user - */ - URI.prototype.escapeUser = function (user) { - var decodedUser; - // FIXME: This is called by toString above which should never throw, but - // decodeURIComponent can throw and I've seen one case in production where - // it did throw resulting in a cascading failure. This class should be - // fixed so that decodeURIComponent is not called at this point (in toString). - // The user should be decoded when the URI is constructor or some other - // place where we can catch the error before the URI is created or somesuch. - try { - decodedUser = decodeURIComponent(user); - } - catch (error) { - throw error; - } - // Don't hex-escape ':' (%3A), '+' (%2B), '?' (%3F"), '/' (%2F). - return encodeURIComponent(decodedUser) - .replace(/%3A/ig, ":") - .replace(/%2B/ig, "+") - .replace(/%3F/ig, "?") - .replace(/%2F/ig, "/"); - }; - URI.prototype.headerize = function (str) { - var exceptions = { - "Call-Id": "Call-ID", - "Cseq": "CSeq", - "Min-Se": "Min-SE", - "Rack": "RAck", - "Rseq": "RSeq", - "Www-Authenticate": "WWW-Authenticate", - }; - var name = str.toLowerCase().replace(/_/g, "-").split("-"); - var parts = name.length; - var hname = ""; - for (var part = 0; part < parts; part++) { - if (part !== 0) { - hname += "-"; - } - hname += name[part].charAt(0).toUpperCase() + name[part].substring(1); - } - if (exceptions[hname]) { - hname = exceptions[hname]; - } - return hname; - }; - return URI; -}(parameters_1.Parameters)); -exports.URI = URI; - - -/***/ }), -/* 16 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * @param size - - * @param base - - * @internal - */ -function createRandomToken(size, base) { - if (base === void 0) { base = 32; } - var token = ""; - for (var i = 0; i < size; i++) { - var r = Math.floor(Math.random() * base); - token += r.toString(base); - } - return token; -} -exports.createRandomToken = createRandomToken; -/** - * @internal - */ -function getReasonPhrase(code) { - return REASON_PHRASE[code] || ""; -} -exports.getReasonPhrase = getReasonPhrase; -/** - * @internal - */ -function newTag() { - return createRandomToken(10); -} -exports.newTag = newTag; -/** - * @param str - - * @internal - */ -function headerize(str) { - var exceptions = { - "Call-Id": "Call-ID", - "Cseq": "CSeq", - "Min-Se": "Min-SE", - "Rack": "RAck", - "Rseq": "RSeq", - "Www-Authenticate": "WWW-Authenticate", - }; - var name = str.toLowerCase().replace(/_/g, "-").split("-"); - var parts = name.length; - var hname = ""; - for (var part = 0; part < parts; part++) { - if (part !== 0) { - hname += "-"; - } - hname += name[part].charAt(0).toUpperCase() + name[part].substring(1); - } - if (exceptions[hname]) { - hname = exceptions[hname]; - } - return hname; -} -exports.headerize = headerize; -/** - * @param str - - * @internal - */ -function str_utf8_length(str) { - return encodeURIComponent(str).replace(/%[A-F\d]{2}/g, "U").length; -} -exports.str_utf8_length = str_utf8_length; -/** - * SIP Response Reasons - * DOC: http://www.iana.org/assignments/sip-parameters - * @internal - */ -var REASON_PHRASE = { - 100: "Trying", - 180: "Ringing", - 181: "Call Is Being Forwarded", - 182: "Queued", - 183: "Session Progress", - 199: "Early Dialog Terminated", - 200: "OK", - 202: "Accepted", - 204: "No Notification", - 300: "Multiple Choices", - 301: "Moved Permanently", - 302: "Moved Temporarily", - 305: "Use Proxy", - 380: "Alternative Service", - 400: "Bad Request", - 401: "Unauthorized", - 402: "Payment Required", - 403: "Forbidden", - 404: "Not Found", - 405: "Method Not Allowed", - 406: "Not Acceptable", - 407: "Proxy Authentication Required", - 408: "Request Timeout", - 410: "Gone", - 412: "Conditional Request Failed", - 413: "Request Entity Too Large", - 414: "Request-URI Too Long", - 415: "Unsupported Media Type", - 416: "Unsupported URI Scheme", - 417: "Unknown Resource-Priority", - 420: "Bad Extension", - 421: "Extension Required", - 422: "Session Interval Too Small", - 423: "Interval Too Brief", - 428: "Use Identity Header", - 429: "Provide Referrer Identity", - 430: "Flow Failed", - 433: "Anonymity Disallowed", - 436: "Bad Identity-Info", - 437: "Unsupported Certificate", - 438: "Invalid Identity Header", - 439: "First Hop Lacks Outbound Support", - 440: "Max-Breadth Exceeded", - 469: "Bad Info Package", - 470: "Consent Needed", - 478: "Unresolvable Destination", - 480: "Temporarily Unavailable", - 481: "Call/Transaction Does Not Exist", - 482: "Loop Detected", - 483: "Too Many Hops", - 484: "Address Incomplete", - 485: "Ambiguous", - 486: "Busy Here", - 487: "Request Terminated", - 488: "Not Acceptable Here", - 489: "Bad Event", - 491: "Request Pending", - 493: "Undecipherable", - 494: "Security Agreement Required", - 500: "Internal Server Error", - 501: "Not Implemented", - 502: "Bad Gateway", - 503: "Service Unavailable", - 504: "Server Time-out", - 505: "Version Not Supported", - 513: "Message Too Large", - 580: "Precondition Failure", - 600: "Busy Everywhere", - 603: "Decline", - 604: "Does Not Exist Anywhere", - 606: "Not Acceptable" -}; - - -/***/ }), -/* 17 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var incoming_message_1 = __webpack_require__(10); -/** - * Incoming response message. - * @public - */ -var IncomingResponseMessage = /** @class */ (function (_super) { - tslib_1.__extends(IncomingResponseMessage, _super); - function IncomingResponseMessage() { - return _super.call(this) || this; - } - return IncomingResponseMessage; -}(incoming_message_1.IncomingMessage)); -exports.IncomingResponseMessage = IncomingResponseMessage; - - -/***/ }), -/* 18 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var name_addr_header_1 = __webpack_require__(13); -var utils_1 = __webpack_require__(16); -/** - * Outgoing SIP request message. - * @public - */ -var OutgoingRequestMessage = /** @class */ (function () { - function OutgoingRequestMessage(method, ruri, fromURI, toURI, options, extraHeaders, body) { - this.headers = {}; - this.extraHeaders = []; - this.options = OutgoingRequestMessage.getDefaultOptions(); - // Options - merge a deep copy - if (options) { - this.options = tslib_1.__assign({}, this.options, options); - if (this.options.optionTags && this.options.optionTags.length) { - this.options.optionTags = this.options.optionTags.slice(); - } - if (this.options.routeSet && this.options.routeSet.length) { - this.options.routeSet = this.options.routeSet.slice(); - } - } - // Extra headers - deep copy - if (extraHeaders && extraHeaders.length) { - this.extraHeaders = extraHeaders.slice(); - } - // Body - deep copy - if (body) { - // TODO: internal representation should be Body - // this.body = { ...body }; - this.body = { - body: body.content, - contentType: body.contentType - }; - } - // Method - this.method = method; - // RURI - this.ruri = ruri.clone(); - // From - this.fromURI = fromURI.clone(); - this.fromTag = this.options.fromTag ? this.options.fromTag : utils_1.newTag(); - this.from = OutgoingRequestMessage.makeNameAddrHeader(this.fromURI, this.options.fromDisplayName, this.fromTag); - // To - this.toURI = toURI.clone(); - this.toTag = this.options.toTag; - this.to = OutgoingRequestMessage.makeNameAddrHeader(this.toURI, this.options.toDisplayName, this.toTag); - // Call-ID - this.callId = this.options.callId ? this.options.callId : this.options.callIdPrefix + utils_1.createRandomToken(15); - // CSeq - this.cseq = this.options.cseq; - // The relative order of header fields with different field names is not - // significant. However, it is RECOMMENDED that header fields which are - // needed for proxy processing (Via, Route, Record-Route, Proxy-Require, - // Max-Forwards, and Proxy-Authorization, for example) appear towards - // the top of the message to facilitate rapid parsing. - // https://tools.ietf.org/html/rfc3261#section-7.3.1 - this.setHeader("route", this.options.routeSet); - this.setHeader("via", ""); - this.setHeader("to", this.to.toString()); - this.setHeader("from", this.from.toString()); - this.setHeader("cseq", this.cseq + " " + this.method); - this.setHeader("call-id", this.callId); - this.setHeader("max-forwards", "70"); - } - /** Get a copy of the default options. */ - OutgoingRequestMessage.getDefaultOptions = function () { - return { - callId: "", - callIdPrefix: "", - cseq: 1, - toDisplayName: "", - toTag: "", - fromDisplayName: "", - fromTag: "", - forceRport: false, - hackViaTcp: false, - optionTags: ["outbound"], - routeSet: [], - userAgentString: "sip.js", - viaHost: "" - }; - }; - OutgoingRequestMessage.makeNameAddrHeader = function (uri, displayName, tag) { - var parameters = {}; - if (tag) { - parameters.tag = tag; - } - return new name_addr_header_1.NameAddrHeader(uri, displayName, parameters); - }; - /** - * Get the value of the given header name at the given position. - * @param name - header name - * @returns Returns the specified header, undefined if header doesn't exist. - */ - OutgoingRequestMessage.prototype.getHeader = function (name) { - var header = this.headers[utils_1.headerize(name)]; - if (header) { - if (header[0]) { - return header[0]; - } - } - else { - var regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); - for (var _i = 0, _a = this.extraHeaders; _i < _a.length; _i++) { - var exHeader = _a[_i]; - if (regexp.test(exHeader)) { - return exHeader.substring(exHeader.indexOf(":") + 1).trim(); - } - } - } - return; - }; - /** - * Get the header/s of the given name. - * @param name - header name - * @returns Array with all the headers of the specified name. - */ - OutgoingRequestMessage.prototype.getHeaders = function (name) { - var result = []; - var headerArray = this.headers[utils_1.headerize(name)]; - if (headerArray) { - for (var _i = 0, headerArray_1 = headerArray; _i < headerArray_1.length; _i++) { - var headerPart = headerArray_1[_i]; - result.push(headerPart); - } - } - else { - var regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); - for (var _a = 0, _b = this.extraHeaders; _a < _b.length; _a++) { - var exHeader = _b[_a]; - if (regexp.test(exHeader)) { - result.push(exHeader.substring(exHeader.indexOf(":") + 1).trim()); - } - } - } - return result; - }; - /** - * Verify the existence of the given header. - * @param name - header name - * @returns true if header with given name exists, false otherwise - */ - OutgoingRequestMessage.prototype.hasHeader = function (name) { - if (this.headers[utils_1.headerize(name)]) { - return true; - } - else { - var regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); - for (var _i = 0, _a = this.extraHeaders; _i < _a.length; _i++) { - var extraHeader = _a[_i]; - if (regexp.test(extraHeader)) { - return true; - } - } - } - return false; - }; - /** - * Replace the the given header by the given value. - * @param name - header name - * @param value - header value - */ - OutgoingRequestMessage.prototype.setHeader = function (name, value) { - this.headers[utils_1.headerize(name)] = (value instanceof Array) ? value : [value]; - }; - /** - * The Via header field indicates the transport used for the transaction - * and identifies the location where the response is to be sent. A Via - * header field value is added only after the transport that will be - * used to reach the next hop has been selected (which may involve the - * usage of the procedures in [4]). - * - * When the UAC creates a request, it MUST insert a Via into that - * request. The protocol name and protocol version in the header field - * MUST be SIP and 2.0, respectively. The Via header field value MUST - * contain a branch parameter. This parameter is used to identify the - * transaction created by that request. This parameter is used by both - * the client and the server. - * https://tools.ietf.org/html/rfc3261#section-8.1.1.7 - * @param branchParameter - The branch parameter. - * @param scheme - The scheme. - */ - OutgoingRequestMessage.prototype.setViaHeader = function (branch, scheme) { - if (scheme === void 0) { scheme = "WSS"; } - // FIXME: Hack - if (this.options.hackViaTcp) { - scheme = "TCP"; - } - var via = "SIP/2.0/" + scheme; - via += " " + this.options.viaHost + ";branch=" + branch; - if (this.options.forceRport) { - via += ";rport"; - } - this.setHeader("via", via); - this.branch = branch; - }; - OutgoingRequestMessage.prototype.toString = function () { - var msg = ""; - msg += this.method + " " + this.ruri.toRaw() + " SIP/2.0\r\n"; - for (var header in this.headers) { - if (this.headers[header]) { - for (var _i = 0, _a = this.headers[header]; _i < _a.length; _i++) { - var headerPart = _a[_i]; - msg += header + ": " + headerPart + "\r\n"; - } - } - } - for (var _b = 0, _c = this.extraHeaders; _b < _c.length; _b++) { - var header = _c[_b]; - msg += header.trim() + "\r\n"; - } - msg += "Supported: " + this.options.optionTags.join(", ") + "\r\n"; - msg += "User-Agent: " + this.options.userAgentString + "\r\n"; - if (this.body) { - if (typeof this.body === "string") { - msg += "Content-Length: " + utils_1.str_utf8_length(this.body) + "\r\n\r\n"; - msg += this.body; - } - else { - if (this.body.body && this.body.contentType) { - msg += "Content-Type: " + this.body.contentType + "\r\n"; - msg += "Content-Length: " + utils_1.str_utf8_length(this.body.body) + "\r\n\r\n"; - msg += this.body.body; - } - else { - msg += "Content-Length: " + 0 + "\r\n\r\n"; - } - } - } - else { - msg += "Content-Length: " + 0 + "\r\n\r\n"; - } - return msg; - }; - return OutgoingRequestMessage; -}()); -exports.OutgoingRequestMessage = OutgoingRequestMessage; - - -/***/ }), -/* 19 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var md5_1 = tslib_1.__importDefault(__webpack_require__(20)); -var utils_1 = __webpack_require__(16); -/** - * Digest Authentication. - * @internal - */ -var DigestAuthentication = /** @class */ (function () { - /** - * Constructor. - * @param loggerFactory - LoggerFactory. - * @param username - Username. - * @param password - Password. - */ - function DigestAuthentication(loggerFactory, username, password) { - this.logger = loggerFactory.getLogger("sipjs.digestauthentication"); - this.username = username; - this.password = password; - this.nc = 0; - this.ncHex = "00000000"; - } - /** - * Performs Digest authentication given a SIP request and the challenge - * received in a response to that request. - * @param request - - * @param challenge - - * @returns true if credentials were successfully generated, false otherwise. - */ - DigestAuthentication.prototype.authenticate = function (request, challenge, body) { - // Inspect and validate the challenge. - this.algorithm = challenge.algorithm; - this.realm = challenge.realm; - this.nonce = challenge.nonce; - this.opaque = challenge.opaque; - this.stale = challenge.stale; - if (this.algorithm) { - if (this.algorithm !== "MD5") { - this.logger.warn("challenge with Digest algorithm different than 'MD5', authentication aborted"); - return false; - } - } - else { - this.algorithm = "MD5"; - } - if (!this.realm) { - this.logger.warn("challenge without Digest realm, authentication aborted"); - return false; - } - if (!this.nonce) { - this.logger.warn("challenge without Digest nonce, authentication aborted"); - return false; - } - // 'qop' can contain a list of values (Array). Let's choose just one. - if (challenge.qop) { - if (challenge.qop.indexOf("auth") > -1) { - this.qop = "auth"; - } - else if (challenge.qop.indexOf("auth-int") > -1) { - this.qop = "auth-int"; - } - else { - // Otherwise 'qop' is present but does not contain 'auth' or 'auth-int', so abort here. - this.logger.warn("challenge without Digest qop different than 'auth' or 'auth-int', authentication aborted"); - return false; - } - } - else { - this.qop = undefined; - } - // Fill other attributes. - this.method = request.method; - this.uri = request.ruri; - this.cnonce = utils_1.createRandomToken(12); - this.nc += 1; - this.updateNcHex(); - // nc-value = 8LHEX. Max value = 'FFFFFFFF'. - if (this.nc === 4294967296) { - this.nc = 1; - this.ncHex = "00000001"; - } - // Calculate the Digest "response" value. - this.calculateResponse(body); - return true; - }; - /** - * Return the Proxy-Authorization or WWW-Authorization header value. - */ - DigestAuthentication.prototype.toString = function () { - var authParams = []; - if (!this.response) { - throw new Error("response field does not exist, cannot generate Authorization header"); - } - authParams.push("algorithm=" + this.algorithm); - authParams.push('username="' + this.username + '"'); - authParams.push('realm="' + this.realm + '"'); - authParams.push('nonce="' + this.nonce + '"'); - authParams.push('uri="' + this.uri + '"'); - authParams.push('response="' + this.response + '"'); - if (this.opaque) { - authParams.push('opaque="' + this.opaque + '"'); - } - if (this.qop) { - authParams.push("qop=" + this.qop); - authParams.push('cnonce="' + this.cnonce + '"'); - authParams.push("nc=" + this.ncHex); - } - return "Digest " + authParams.join(", "); - }; - /** - * Generate the 'nc' value as required by Digest in this.ncHex by reading this.nc. - */ - DigestAuthentication.prototype.updateNcHex = function () { - var hex = Number(this.nc).toString(16); - this.ncHex = "00000000".substr(0, 8 - hex.length) + hex; - }; - /** - * Generate Digest 'response' value. - */ - DigestAuthentication.prototype.calculateResponse = function (body) { - var ha2; - // HA1 = MD5(A1) = MD5(username:realm:password) - var ha1 = md5_1.default(this.username + ":" + this.realm + ":" + this.password); - if (this.qop === "auth") { - // HA2 = MD5(A2) = MD5(method:digestURI) - ha2 = md5_1.default(this.method + ":" + this.uri); - // response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2) - this.response = md5_1.default(ha1 + ":" + this.nonce + ":" + this.ncHex + ":" + this.cnonce + ":auth:" + ha2); - } - else if (this.qop === "auth-int") { - // HA2 = MD5(A2) = MD5(method:digestURI:MD5(entityBody)) - ha2 = md5_1.default(this.method + ":" + this.uri + ":" + md5_1.default(body ? body : "")); - // response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2) - this.response = md5_1.default(ha1 + ":" + this.nonce + ":" + this.ncHex + ":" + this.cnonce + ":auth-int:" + ha2); - } - else if (this.qop === undefined) { - // HA2 = MD5(A2) = MD5(method:digestURI) - ha2 = md5_1.default(this.method + ":" + this.uri); - // response = MD5(HA1:nonce:HA2) - this.response = md5_1.default(ha1 + ":" + this.nonce + ":" + ha2); - } - }; - return DigestAuthentication; -}()); -exports.DigestAuthentication = DigestAuthentication; - - -/***/ }), -/* 20 */ -/***/ (function(module, exports, __webpack_require__) { - -;(function (root, factory) { - if (true) { - // CommonJS - module.exports = exports = factory(__webpack_require__(21)); - } - else {} -}(this, function (CryptoJS) { - - (function (Math) { - // Shortcuts - var C = CryptoJS; - var C_lib = C.lib; - var WordArray = C_lib.WordArray; - var Hasher = C_lib.Hasher; - var C_algo = C.algo; - - // Constants table - var T = []; - - // Compute constants - (function () { - for (var i = 0; i < 64; i++) { - T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0; - } - }()); - - /** - * MD5 hash algorithm. - */ - var MD5 = C_algo.MD5 = Hasher.extend({ - _doReset: function () { - this._hash = new WordArray.init([ - 0x67452301, 0xefcdab89, - 0x98badcfe, 0x10325476 - ]); - }, - - _doProcessBlock: function (M, offset) { - // Swap endian - for (var i = 0; i < 16; i++) { - // Shortcuts - var offset_i = offset + i; - var M_offset_i = M[offset_i]; - - M[offset_i] = ( - (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | - (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) - ); - } - - // Shortcuts - var H = this._hash.words; - - var M_offset_0 = M[offset + 0]; - var M_offset_1 = M[offset + 1]; - var M_offset_2 = M[offset + 2]; - var M_offset_3 = M[offset + 3]; - var M_offset_4 = M[offset + 4]; - var M_offset_5 = M[offset + 5]; - var M_offset_6 = M[offset + 6]; - var M_offset_7 = M[offset + 7]; - var M_offset_8 = M[offset + 8]; - var M_offset_9 = M[offset + 9]; - var M_offset_10 = M[offset + 10]; - var M_offset_11 = M[offset + 11]; - var M_offset_12 = M[offset + 12]; - var M_offset_13 = M[offset + 13]; - var M_offset_14 = M[offset + 14]; - var M_offset_15 = M[offset + 15]; - - // Working varialbes - var a = H[0]; - var b = H[1]; - var c = H[2]; - var d = H[3]; - - // Computation - a = FF(a, b, c, d, M_offset_0, 7, T[0]); - d = FF(d, a, b, c, M_offset_1, 12, T[1]); - c = FF(c, d, a, b, M_offset_2, 17, T[2]); - b = FF(b, c, d, a, M_offset_3, 22, T[3]); - a = FF(a, b, c, d, M_offset_4, 7, T[4]); - d = FF(d, a, b, c, M_offset_5, 12, T[5]); - c = FF(c, d, a, b, M_offset_6, 17, T[6]); - b = FF(b, c, d, a, M_offset_7, 22, T[7]); - a = FF(a, b, c, d, M_offset_8, 7, T[8]); - d = FF(d, a, b, c, M_offset_9, 12, T[9]); - c = FF(c, d, a, b, M_offset_10, 17, T[10]); - b = FF(b, c, d, a, M_offset_11, 22, T[11]); - a = FF(a, b, c, d, M_offset_12, 7, T[12]); - d = FF(d, a, b, c, M_offset_13, 12, T[13]); - c = FF(c, d, a, b, M_offset_14, 17, T[14]); - b = FF(b, c, d, a, M_offset_15, 22, T[15]); - - a = GG(a, b, c, d, M_offset_1, 5, T[16]); - d = GG(d, a, b, c, M_offset_6, 9, T[17]); - c = GG(c, d, a, b, M_offset_11, 14, T[18]); - b = GG(b, c, d, a, M_offset_0, 20, T[19]); - a = GG(a, b, c, d, M_offset_5, 5, T[20]); - d = GG(d, a, b, c, M_offset_10, 9, T[21]); - c = GG(c, d, a, b, M_offset_15, 14, T[22]); - b = GG(b, c, d, a, M_offset_4, 20, T[23]); - a = GG(a, b, c, d, M_offset_9, 5, T[24]); - d = GG(d, a, b, c, M_offset_14, 9, T[25]); - c = GG(c, d, a, b, M_offset_3, 14, T[26]); - b = GG(b, c, d, a, M_offset_8, 20, T[27]); - a = GG(a, b, c, d, M_offset_13, 5, T[28]); - d = GG(d, a, b, c, M_offset_2, 9, T[29]); - c = GG(c, d, a, b, M_offset_7, 14, T[30]); - b = GG(b, c, d, a, M_offset_12, 20, T[31]); - - a = HH(a, b, c, d, M_offset_5, 4, T[32]); - d = HH(d, a, b, c, M_offset_8, 11, T[33]); - c = HH(c, d, a, b, M_offset_11, 16, T[34]); - b = HH(b, c, d, a, M_offset_14, 23, T[35]); - a = HH(a, b, c, d, M_offset_1, 4, T[36]); - d = HH(d, a, b, c, M_offset_4, 11, T[37]); - c = HH(c, d, a, b, M_offset_7, 16, T[38]); - b = HH(b, c, d, a, M_offset_10, 23, T[39]); - a = HH(a, b, c, d, M_offset_13, 4, T[40]); - d = HH(d, a, b, c, M_offset_0, 11, T[41]); - c = HH(c, d, a, b, M_offset_3, 16, T[42]); - b = HH(b, c, d, a, M_offset_6, 23, T[43]); - a = HH(a, b, c, d, M_offset_9, 4, T[44]); - d = HH(d, a, b, c, M_offset_12, 11, T[45]); - c = HH(c, d, a, b, M_offset_15, 16, T[46]); - b = HH(b, c, d, a, M_offset_2, 23, T[47]); - - a = II(a, b, c, d, M_offset_0, 6, T[48]); - d = II(d, a, b, c, M_offset_7, 10, T[49]); - c = II(c, d, a, b, M_offset_14, 15, T[50]); - b = II(b, c, d, a, M_offset_5, 21, T[51]); - a = II(a, b, c, d, M_offset_12, 6, T[52]); - d = II(d, a, b, c, M_offset_3, 10, T[53]); - c = II(c, d, a, b, M_offset_10, 15, T[54]); - b = II(b, c, d, a, M_offset_1, 21, T[55]); - a = II(a, b, c, d, M_offset_8, 6, T[56]); - d = II(d, a, b, c, M_offset_15, 10, T[57]); - c = II(c, d, a, b, M_offset_6, 15, T[58]); - b = II(b, c, d, a, M_offset_13, 21, T[59]); - a = II(a, b, c, d, M_offset_4, 6, T[60]); - d = II(d, a, b, c, M_offset_11, 10, T[61]); - c = II(c, d, a, b, M_offset_2, 15, T[62]); - b = II(b, c, d, a, M_offset_9, 21, T[63]); - - // Intermediate hash value - H[0] = (H[0] + a) | 0; - H[1] = (H[1] + b) | 0; - H[2] = (H[2] + c) | 0; - H[3] = (H[3] + d) | 0; - }, - - _doFinalize: function () { - // Shortcuts - var data = this._data; - var dataWords = data.words; - - var nBitsTotal = this._nDataBytes * 8; - var nBitsLeft = data.sigBytes * 8; - - // Add padding - dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); - - var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000); - var nBitsTotalL = nBitsTotal; - dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = ( - (((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) | - (((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00) - ); - dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( - (((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) | - (((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00) - ); - - data.sigBytes = (dataWords.length + 1) * 4; - - // Hash final blocks - this._process(); - - // Shortcuts - var hash = this._hash; - var H = hash.words; - - // Swap endian - for (var i = 0; i < 4; i++) { - // Shortcut - var H_i = H[i]; - - H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | - (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); - } - - // Return final computed hash - return hash; - }, - - clone: function () { - var clone = Hasher.clone.call(this); - clone._hash = this._hash.clone(); - - return clone; - } - }); - - function FF(a, b, c, d, x, s, t) { - var n = a + ((b & c) | (~b & d)) + x + t; - return ((n << s) | (n >>> (32 - s))) + b; - } - - function GG(a, b, c, d, x, s, t) { - var n = a + ((b & d) | (c & ~d)) + x + t; - return ((n << s) | (n >>> (32 - s))) + b; - } - - function HH(a, b, c, d, x, s, t) { - var n = a + (b ^ c ^ d) + x + t; - return ((n << s) | (n >>> (32 - s))) + b; - } - - function II(a, b, c, d, x, s, t) { - var n = a + (c ^ (b | ~d)) + x + t; - return ((n << s) | (n >>> (32 - s))) + b; - } - - /** - * Shortcut function to the hasher's object interface. - * - * @param {WordArray|string} message The message to hash. - * - * @return {WordArray} The hash. - * - * @static - * - * @example - * - * var hash = CryptoJS.MD5('message'); - * var hash = CryptoJS.MD5(wordArray); - */ - C.MD5 = Hasher._createHelper(MD5); - - /** - * Shortcut function to the HMAC's object interface. - * - * @param {WordArray|string} message The message to hash. - * @param {WordArray|string} key The secret key. - * - * @return {WordArray} The HMAC. - * - * @static - * - * @example - * - * var hmac = CryptoJS.HmacMD5(message, key); - */ - C.HmacMD5 = Hasher._createHmacHelper(MD5); - }(Math)); - - - return CryptoJS.MD5; - -})); - -/***/ }), -/* 21 */ -/***/ (function(module, exports, __webpack_require__) { - -;(function (root, factory) { - if (true) { - // CommonJS - module.exports = exports = factory(); - } - else {} -}(this, function () { - - /** - * CryptoJS core components. - */ - var CryptoJS = CryptoJS || (function (Math, undefined) { - /* - * Local polyfil of Object.create - */ - var create = Object.create || (function () { - function F() {}; - - return function (obj) { - var subtype; - - F.prototype = obj; - - subtype = new F(); - - F.prototype = null; - - return subtype; - }; - }()) - - /** - * CryptoJS namespace. - */ - var C = {}; - - /** - * Library namespace. - */ - var C_lib = C.lib = {}; - - /** - * Base object for prototypal inheritance. - */ - var Base = C_lib.Base = (function () { - - - return { - /** - * Creates a new object that inherits from this object. - * - * @param {Object} overrides Properties to copy into the new object. - * - * @return {Object} The new object. - * - * @static - * - * @example - * - * var MyType = CryptoJS.lib.Base.extend({ - * field: 'value', - * - * method: function () { - * } - * }); - */ - extend: function (overrides) { - // Spawn - var subtype = create(this); - - // Augment - if (overrides) { - subtype.mixIn(overrides); - } - - // Create default initializer - if (!subtype.hasOwnProperty('init') || this.init === subtype.init) { - subtype.init = function () { - subtype.$super.init.apply(this, arguments); - }; - } - - // Initializer's prototype is the subtype object - subtype.init.prototype = subtype; - - // Reference supertype - subtype.$super = this; - - return subtype; - }, - - /** - * Extends this object and runs the init method. - * Arguments to create() will be passed to init(). - * - * @return {Object} The new object. - * - * @static - * - * @example - * - * var instance = MyType.create(); - */ - create: function () { - var instance = this.extend(); - instance.init.apply(instance, arguments); - - return instance; - }, - - /** - * Initializes a newly created object. - * Override this method to add some logic when your objects are created. - * - * @example - * - * var MyType = CryptoJS.lib.Base.extend({ - * init: function () { - * // ... - * } - * }); - */ - init: function () { - }, - - /** - * Copies properties into this object. - * - * @param {Object} properties The properties to mix in. - * - * @example - * - * MyType.mixIn({ - * field: 'value' - * }); - */ - mixIn: function (properties) { - for (var propertyName in properties) { - if (properties.hasOwnProperty(propertyName)) { - this[propertyName] = properties[propertyName]; - } - } - - // IE won't copy toString using the loop above - if (properties.hasOwnProperty('toString')) { - this.toString = properties.toString; - } - }, - - /** - * Creates a copy of this object. - * - * @return {Object} The clone. - * - * @example - * - * var clone = instance.clone(); - */ - clone: function () { - return this.init.prototype.extend(this); - } - }; - }()); - - /** - * An array of 32-bit words. - * - * @property {Array} words The array of 32-bit words. - * @property {number} sigBytes The number of significant bytes in this word array. - */ - var WordArray = C_lib.WordArray = Base.extend({ - /** - * Initializes a newly created word array. - * - * @param {Array} words (Optional) An array of 32-bit words. - * @param {number} sigBytes (Optional) The number of significant bytes in the words. - * - * @example - * - * var wordArray = CryptoJS.lib.WordArray.create(); - * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); - * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); - */ - init: function (words, sigBytes) { - words = this.words = words || []; - - if (sigBytes != undefined) { - this.sigBytes = sigBytes; - } else { - this.sigBytes = words.length * 4; - } - }, - - /** - * Converts this word array to a string. - * - * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex - * - * @return {string} The stringified word array. - * - * @example - * - * var string = wordArray + ''; - * var string = wordArray.toString(); - * var string = wordArray.toString(CryptoJS.enc.Utf8); - */ - toString: function (encoder) { - return (encoder || Hex).stringify(this); - }, - - /** - * Concatenates a word array to this word array. - * - * @param {WordArray} wordArray The word array to append. - * - * @return {WordArray} This word array. - * - * @example - * - * wordArray1.concat(wordArray2); - */ - concat: function (wordArray) { - // Shortcuts - var thisWords = this.words; - var thatWords = wordArray.words; - var thisSigBytes = this.sigBytes; - var thatSigBytes = wordArray.sigBytes; - - // Clamp excess bits - this.clamp(); - - // Concat - if (thisSigBytes % 4) { - // Copy one byte at a time - for (var i = 0; i < thatSigBytes; i++) { - var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; - thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); - } - } else { - // Copy one word at a time - for (var i = 0; i < thatSigBytes; i += 4) { - thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2]; - } - } - this.sigBytes += thatSigBytes; - - // Chainable - return this; - }, - - /** - * Removes insignificant bits. - * - * @example - * - * wordArray.clamp(); - */ - clamp: function () { - // Shortcuts - var words = this.words; - var sigBytes = this.sigBytes; - - // Clamp - words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); - words.length = Math.ceil(sigBytes / 4); - }, - - /** - * Creates a copy of this word array. - * - * @return {WordArray} The clone. - * - * @example - * - * var clone = wordArray.clone(); - */ - clone: function () { - var clone = Base.clone.call(this); - clone.words = this.words.slice(0); - - return clone; - }, - - /** - * Creates a word array filled with random bytes. - * - * @param {number} nBytes The number of random bytes to generate. - * - * @return {WordArray} The random word array. - * - * @static - * - * @example - * - * var wordArray = CryptoJS.lib.WordArray.random(16); - */ - random: function (nBytes) { - var words = []; - - var r = (function (m_w) { - var m_w = m_w; - var m_z = 0x3ade68b1; - var mask = 0xffffffff; - - return function () { - m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask; - m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask; - var result = ((m_z << 0x10) + m_w) & mask; - result /= 0x100000000; - result += 0.5; - return result * (Math.random() > .5 ? 1 : -1); - } - }); - - for (var i = 0, rcache; i < nBytes; i += 4) { - var _r = r((rcache || Math.random()) * 0x100000000); - - rcache = _r() * 0x3ade67b7; - words.push((_r() * 0x100000000) | 0); - } - - return new WordArray.init(words, nBytes); - } - }); - - /** - * Encoder namespace. - */ - var C_enc = C.enc = {}; - - /** - * Hex encoding strategy. - */ - var Hex = C_enc.Hex = { - /** - * Converts a word array to a hex string. - * - * @param {WordArray} wordArray The word array. - * - * @return {string} The hex string. - * - * @static - * - * @example - * - * var hexString = CryptoJS.enc.Hex.stringify(wordArray); - */ - stringify: function (wordArray) { - // Shortcuts - var words = wordArray.words; - var sigBytes = wordArray.sigBytes; - - // Convert - var hexChars = []; - for (var i = 0; i < sigBytes; i++) { - var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; - hexChars.push((bite >>> 4).toString(16)); - hexChars.push((bite & 0x0f).toString(16)); - } - - return hexChars.join(''); - }, - - /** - * Converts a hex string to a word array. - * - * @param {string} hexStr The hex string. - * - * @return {WordArray} The word array. - * - * @static - * - * @example - * - * var wordArray = CryptoJS.enc.Hex.parse(hexString); - */ - parse: function (hexStr) { - // Shortcut - var hexStrLength = hexStr.length; - - // Convert - var words = []; - for (var i = 0; i < hexStrLength; i += 2) { - words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); - } - - return new WordArray.init(words, hexStrLength / 2); - } - }; - - /** - * Latin1 encoding strategy. - */ - var Latin1 = C_enc.Latin1 = { - /** - * Converts a word array to a Latin1 string. - * - * @param {WordArray} wordArray The word array. - * - * @return {string} The Latin1 string. - * - * @static - * - * @example - * - * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); - */ - stringify: function (wordArray) { - // Shortcuts - var words = wordArray.words; - var sigBytes = wordArray.sigBytes; - - // Convert - var latin1Chars = []; - for (var i = 0; i < sigBytes; i++) { - var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; - latin1Chars.push(String.fromCharCode(bite)); - } - - return latin1Chars.join(''); - }, - - /** - * Converts a Latin1 string to a word array. - * - * @param {string} latin1Str The Latin1 string. - * - * @return {WordArray} The word array. - * - * @static - * - * @example - * - * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); - */ - parse: function (latin1Str) { - // Shortcut - var latin1StrLength = latin1Str.length; - - // Convert - var words = []; - for (var i = 0; i < latin1StrLength; i++) { - words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); - } - - return new WordArray.init(words, latin1StrLength); - } - }; - - /** - * UTF-8 encoding strategy. - */ - var Utf8 = C_enc.Utf8 = { - /** - * Converts a word array to a UTF-8 string. - * - * @param {WordArray} wordArray The word array. - * - * @return {string} The UTF-8 string. - * - * @static - * - * @example - * - * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); - */ - stringify: function (wordArray) { - try { - return decodeURIComponent(escape(Latin1.stringify(wordArray))); - } catch (e) { - throw new Error('Malformed UTF-8 data'); - } - }, - - /** - * Converts a UTF-8 string to a word array. - * - * @param {string} utf8Str The UTF-8 string. - * - * @return {WordArray} The word array. - * - * @static - * - * @example - * - * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); - */ - parse: function (utf8Str) { - return Latin1.parse(unescape(encodeURIComponent(utf8Str))); - } - }; - - /** - * Abstract buffered block algorithm template. - * - * The property blockSize must be implemented in a concrete subtype. - * - * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 - */ - var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ - /** - * Resets this block algorithm's data buffer to its initial state. - * - * @example - * - * bufferedBlockAlgorithm.reset(); - */ - reset: function () { - // Initial values - this._data = new WordArray.init(); - this._nDataBytes = 0; - }, - - /** - * Adds new data to this block algorithm's buffer. - * - * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. - * - * @example - * - * bufferedBlockAlgorithm._append('data'); - * bufferedBlockAlgorithm._append(wordArray); - */ - _append: function (data) { - // Convert string to WordArray, else assume WordArray already - if (typeof data == 'string') { - data = Utf8.parse(data); - } - - // Append - this._data.concat(data); - this._nDataBytes += data.sigBytes; - }, - - /** - * Processes available data blocks. - * - * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. - * - * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. - * - * @return {WordArray} The processed data. - * - * @example - * - * var processedData = bufferedBlockAlgorithm._process(); - * var processedData = bufferedBlockAlgorithm._process(!!'flush'); - */ - _process: function (doFlush) { - // Shortcuts - var data = this._data; - var dataWords = data.words; - var dataSigBytes = data.sigBytes; - var blockSize = this.blockSize; - var blockSizeBytes = blockSize * 4; - - // Count blocks ready - var nBlocksReady = dataSigBytes / blockSizeBytes; - if (doFlush) { - // Round up to include partial blocks - nBlocksReady = Math.ceil(nBlocksReady); - } else { - // Round down to include only full blocks, - // less the number of blocks that must remain in the buffer - nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); - } - - // Count words ready - var nWordsReady = nBlocksReady * blockSize; - - // Count bytes ready - var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); - - // Process blocks - if (nWordsReady) { - for (var offset = 0; offset < nWordsReady; offset += blockSize) { - // Perform concrete-algorithm logic - this._doProcessBlock(dataWords, offset); - } - - // Remove processed words - var processedWords = dataWords.splice(0, nWordsReady); - data.sigBytes -= nBytesReady; - } - - // Return processed words - return new WordArray.init(processedWords, nBytesReady); - }, - - /** - * Creates a copy of this object. - * - * @return {Object} The clone. - * - * @example - * - * var clone = bufferedBlockAlgorithm.clone(); - */ - clone: function () { - var clone = Base.clone.call(this); - clone._data = this._data.clone(); - - return clone; - }, - - _minBufferSize: 0 - }); - - /** - * Abstract hasher template. - * - * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) - */ - var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ - /** - * Configuration options. - */ - cfg: Base.extend(), - - /** - * Initializes a newly created hasher. - * - * @param {Object} cfg (Optional) The configuration options to use for this hash computation. - * - * @example - * - * var hasher = CryptoJS.algo.SHA256.create(); - */ - init: function (cfg) { - // Apply config defaults - this.cfg = this.cfg.extend(cfg); - - // Set initial values - this.reset(); - }, - - /** - * Resets this hasher to its initial state. - * - * @example - * - * hasher.reset(); - */ - reset: function () { - // Reset data buffer - BufferedBlockAlgorithm.reset.call(this); - - // Perform concrete-hasher logic - this._doReset(); - }, - - /** - * Updates this hasher with a message. - * - * @param {WordArray|string} messageUpdate The message to append. - * - * @return {Hasher} This hasher. - * - * @example - * - * hasher.update('message'); - * hasher.update(wordArray); - */ - update: function (messageUpdate) { - // Append - this._append(messageUpdate); - - // Update the hash - this._process(); - - // Chainable - return this; - }, - - /** - * Finalizes the hash computation. - * Note that the finalize operation is effectively a destructive, read-once operation. - * - * @param {WordArray|string} messageUpdate (Optional) A final message update. - * - * @return {WordArray} The hash. - * - * @example - * - * var hash = hasher.finalize(); - * var hash = hasher.finalize('message'); - * var hash = hasher.finalize(wordArray); - */ - finalize: function (messageUpdate) { - // Final message update - if (messageUpdate) { - this._append(messageUpdate); - } - - // Perform concrete-hasher logic - var hash = this._doFinalize(); - - return hash; - }, - - blockSize: 512/32, - - /** - * Creates a shortcut function to a hasher's object interface. - * - * @param {Hasher} hasher The hasher to create a helper for. - * - * @return {Function} The shortcut function. - * - * @static - * - * @example - * - * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); - */ - _createHelper: function (hasher) { - return function (message, cfg) { - return new hasher.init(cfg).finalize(message); - }; - }, - - /** - * Creates a shortcut function to the HMAC's object interface. - * - * @param {Hasher} hasher The hasher to use in this HMAC helper. - * - * @return {Function} The shortcut function. - * - * @static - * - * @example - * - * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); - */ - _createHmacHelper: function (hasher) { - return function (message, key) { - return new C_algo.HMAC.init(hasher, key).finalize(message); - }; - } - }); - - /** - * Algorithm namespace. - */ - var C_algo = C.algo = {}; - - return C; - }(Math)); - - - return CryptoJS; - -})); - -/***/ }), -/* 22 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var utils_1 = __webpack_require__(16); -/** - * When a UAS wishes to construct a response to a request, it follows - * the general procedures detailed in the following subsections. - * Additional behaviors specific to the response code in question, which - * are not detailed in this section, may also be required. - * https://tools.ietf.org/html/rfc3261#section-8.2.6 - * @internal - */ -function constructOutgoingResponse(message, options) { - var CRLF = "\r\n"; - if (options.statusCode < 100 || options.statusCode > 699) { - throw new TypeError("Invalid statusCode: " + options.statusCode); - } - var reasonPhrase = options.reasonPhrase ? options.reasonPhrase : utils_1.getReasonPhrase(options.statusCode); - // SIP responses are distinguished from requests by having a Status-Line - // as their start-line. A Status-Line consists of the protocol version - // followed by a numeric Status-Code and its associated textual phrase, - // with each element separated by a single SP character. - // https://tools.ietf.org/html/rfc3261#section-7.2 - var response = "SIP/2.0 " + options.statusCode + " " + reasonPhrase + CRLF; - // One largely non-method-specific guideline for the generation of - // responses is that UASs SHOULD NOT issue a provisional response for a - // non-INVITE request. Rather, UASs SHOULD generate a final response to - // a non-INVITE request as soon as possible. - // https://tools.ietf.org/html/rfc3261#section-8.2.6.1 - if (options.statusCode >= 100 && options.statusCode < 200) { - // TODO - } - // When a 100 (Trying) response is generated, any Timestamp header field - // present in the request MUST be copied into this 100 (Trying) - // response. If there is a delay in generating the response, the UAS - // SHOULD add a delay value into the Timestamp value in the response. - // This value MUST contain the difference between the time of sending of - // the response and receipt of the request, measured in seconds. - // https://tools.ietf.org/html/rfc3261#section-8.2.6.1 - if (options.statusCode === 100) { - // TODO - } - // The From field of the response MUST equal the From header field of - // the request. The Call-ID header field of the response MUST equal the - // Call-ID header field of the request. The CSeq header field of the - // response MUST equal the CSeq field of the request. The Via header - // field values in the response MUST equal the Via header field values - // in the request and MUST maintain the same ordering. - // https://tools.ietf.org/html/rfc3261#section-8.2.6.2 - var fromHeader = "From: " + message.getHeader("From") + CRLF; - var callIdHeader = "Call-ID: " + message.callId + CRLF; - var cSeqHeader = "CSeq: " + message.cseq + " " + message.method + CRLF; - var viaHeaders = message.getHeaders("via").reduce(function (previous, current) { - return previous + "Via: " + current + CRLF; - }, ""); - // If a request contained a To tag in the request, the To header field - // in the response MUST equal that of the request. However, if the To - // header field in the request did not contain a tag, the URI in the To - // header field in the response MUST equal the URI in the To header - // field; additionally, the UAS MUST add a tag to the To header field in - // the response (with the exception of the 100 (Trying) response, in - // which a tag MAY be present). This serves to identify the UAS that is - // responding, possibly resulting in a component of a dialog ID. The - // same tag MUST be used for all responses to that request, both final - // and provisional (again excepting the 100 (Trying)). - // https://tools.ietf.org/html/rfc3261#section-8.2.6.2 - var toHeader = "To: " + message.getHeader("to"); - if (options.statusCode > 100 && !message.parseHeader("to").hasParam("tag")) { - var toTag = options.toTag; - if (!toTag) { - // Stateless UAS Behavior... - // o To header tags MUST be generated for responses in a stateless - // manner - in a manner that will generate the same tag for the - // same request consistently. For information on tag construction - // see Section 19.3. - // https://tools.ietf.org/html/rfc3261#section-8.2.7 - toTag = utils_1.newTag(); // FIXME: newTag() currently generates random tags - } - toHeader += ";tag=" + toTag; - } - toHeader += CRLF; - // FIXME: TODO: needs review... moved to InviteUserAgentServer (as it is specific to that) - // let recordRouteHeaders = ""; - // if (request.method === C.INVITE && statusCode > 100 && statusCode <= 200) { - // recordRouteHeaders = request.getHeaders("record-route").reduce((previous, current) => { - // return previous + "Record-Route: " + current + CRLF; - // }, ""); - // } - // FIXME: TODO: needs review... - var supportedHeader = ""; - if (options.supported) { - supportedHeader = "Supported: " + options.supported.join(", ") + CRLF; - } - // FIXME: TODO: needs review... - var userAgentHeader = ""; - if (options.userAgent) { - userAgentHeader = "User-Agent: " + options.userAgent + CRLF; - } - var extensionHeaders = ""; - if (options.extraHeaders) { - extensionHeaders = options.extraHeaders.reduce(function (previous, current) { - return previous + current.trim() + CRLF; - }, ""); - } - // The relative order of header fields with different field names is not - // significant. However, it is RECOMMENDED that header fields which are - // needed for proxy processing (Via, Route, Record-Route, Proxy-Require, - // Max-Forwards, and Proxy-Authorization, for example) appear towards - // the top of the message to facilitate rapid parsing. - // https://tools.ietf.org/html/rfc3261#section-7.3.1 - // response += recordRouteHeaders; - response += viaHeaders; - response += fromHeader; - response += toHeader; - response += cSeqHeader; - response += callIdHeader; - response += supportedHeader; - response += userAgentHeader; - response += extensionHeaders; - if (options.body) { - response += "Content-Type: " + options.body.contentType + CRLF; - response += "Content-Length: " + utils_1.str_utf8_length(options.body.content) + CRLF + CRLF; - response += options.body.content; - } - else { - response += "Content-Length: " + 0 + CRLF + CRLF; - } - return { message: response }; -} -exports.constructOutgoingResponse = constructOutgoingResponse; - - -/***/ }), -/* 23 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var session_1 = __webpack_require__(24); -var timers_1 = __webpack_require__(26); -var transactions_1 = __webpack_require__(27); -var bye_user_agent_client_1 = __webpack_require__(41); -var bye_user_agent_server_1 = __webpack_require__(43); -var info_user_agent_client_1 = __webpack_require__(45); -var info_user_agent_server_1 = __webpack_require__(46); -var notify_user_agent_client_1 = __webpack_require__(47); -var notify_user_agent_server_1 = __webpack_require__(48); -var prack_user_agent_client_1 = __webpack_require__(49); -var prack_user_agent_server_1 = __webpack_require__(50); -var re_invite_user_agent_client_1 = __webpack_require__(51); -var re_invite_user_agent_server_1 = __webpack_require__(52); -var refer_user_agent_client_1 = __webpack_require__(53); -var refer_user_agent_server_1 = __webpack_require__(54); -var dialog_1 = __webpack_require__(4); -/** - * Session Dialog. - * @public - */ -var SessionDialog = /** @class */ (function (_super) { - tslib_1.__extends(SessionDialog, _super); - function SessionDialog(initialTransaction, core, state, delegate) { - var _this = _super.call(this, core, state) || this; - _this.initialTransaction = initialTransaction; - /** The state of the offer/answer exchange. */ - _this._signalingState = session_1.SignalingState.Initial; - /** True if waiting for an ACK to the initial transaction 2xx (UAS only). */ - _this.ackWait = false; - _this.delegate = delegate; - if (initialTransaction instanceof transactions_1.InviteServerTransaction) { - // If we're created by an invite server transaction, we're - // going to be waiting for an ACK if are to be confirmed. - _this.ackWait = true; - } - // If we're confirmed upon creation start the retransmitting whatever - // the 2xx final response was that confirmed us into existence. - if (!_this.early) { - _this.start2xxRetransmissionTimer(); - } - _this.signalingStateTransition(initialTransaction.request); - _this.logger = core.loggerFactory.getLogger("sip.invite-dialog"); - _this.logger.log("INVITE dialog " + _this.id + " constructed"); - return _this; - } - SessionDialog.prototype.dispose = function () { - _super.prototype.dispose.call(this); - this._signalingState = session_1.SignalingState.Closed; - this._offer = undefined; - this._answer = undefined; - if (this.invite2xxTimer) { - clearTimeout(this.invite2xxTimer); - this.invite2xxTimer = undefined; - } - // The UAS MUST still respond to any pending requests received for that - // dialog. It is RECOMMENDED that a 487 (Request Terminated) response - // be generated to those pending requests. - // https://tools.ietf.org/html/rfc3261#section-15.1.2 - // TODO: - // this.userAgentServers.forEach((uas) => uas.reply(487)); - this.logger.log("INVITE dialog " + this.id + " destroyed"); - }; - Object.defineProperty(SessionDialog.prototype, "sessionState", { - // FIXME: Need real state machine - get: function () { - if (this.early) { - return session_1.SessionState.Early; - } - else if (this.ackWait) { - return session_1.SessionState.AckWait; - } - else if (this._signalingState === session_1.SignalingState.Closed) { - return session_1.SessionState.Terminated; - } - else { - return session_1.SessionState.Confirmed; - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SessionDialog.prototype, "signalingState", { - /** The state of the offer/answer exchange. */ - get: function () { - return this._signalingState; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SessionDialog.prototype, "offer", { - /** The current offer. Undefined unless signaling state HaveLocalOffer, HaveRemoteOffer, of Stable. */ - get: function () { - return this._offer; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SessionDialog.prototype, "answer", { - /** The current answer. Undefined unless signaling state Stable. */ - get: function () { - return this._answer; - }, - enumerable: true, - configurable: true - }); - /** Confirm the dialog. Only matters if dialog is currently early. */ - SessionDialog.prototype.confirm = function () { - // When we're confirmed start the retransmitting whatever - // the 2xx final response that may have confirmed us. - if (this.early) { - this.start2xxRetransmissionTimer(); - } - _super.prototype.confirm.call(this); - }; - /** Re-confirm the dialog. Only matters if handling re-INVITE request. */ - SessionDialog.prototype.reConfirm = function () { - // When we're confirmed start the retransmitting whatever - // the 2xx final response that may have confirmed us. - if (this.reinviteUserAgentServer) { - this.startReInvite2xxRetransmissionTimer(); - } - }; - /** - * The UAC core MUST generate an ACK request for each 2xx received from - * the transaction layer. The header fields of the ACK are constructed - * in the same way as for any request sent within a dialog (see Section - * 12) with the exception of the CSeq and the header fields related to - * authentication. The sequence number of the CSeq header field MUST be - * the same as the INVITE being acknowledged, but the CSeq method MUST - * be ACK. The ACK MUST contain the same credentials as the INVITE. If - * the 2xx contains an offer (based on the rules above), the ACK MUST - * carry an answer in its body. If the offer in the 2xx response is not - * acceptable, the UAC core MUST generate a valid answer in the ACK and - * then send a BYE immediately. - * https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - * @param options - ACK options bucket. - */ - SessionDialog.prototype.ack = function (options) { - if (options === void 0) { options = {}; } - this.logger.log("INVITE dialog " + this.id + " sending ACK request"); - var transaction; - if (this.reinviteUserAgentClient) { - // We're sending ACK for a re-INVITE - if (!(this.reinviteUserAgentClient.transaction instanceof transactions_1.InviteClientTransaction)) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - transaction = this.reinviteUserAgentClient.transaction; - this.reinviteUserAgentClient = undefined; - } - else { - // We're sending ACK for the initial INVITE - if (!(this.initialTransaction instanceof transactions_1.InviteClientTransaction)) { - throw new Error("Initial transaction not instance of InviteClientTransaction."); - } - transaction = this.initialTransaction; - } - options.cseq = transaction.request.cseq; // ACK cseq is INVITE cseq - var message = this.createOutgoingRequestMessage(messages_1.C.ACK, options); - transaction.ackResponse(message); // See InviteClientTransaction for details. - this.signalingStateTransition(message); - return { message: message }; - }; - /** - * Terminating a Session - * - * This section describes the procedures for terminating a session - * established by SIP. The state of the session and the state of the - * dialog are very closely related. When a session is initiated with an - * INVITE, each 1xx or 2xx response from a distinct UAS creates a - * dialog, and if that response completes the offer/answer exchange, it - * also creates a session. As a result, each session is "associated" - * with a single dialog - the one which resulted in its creation. If an - * initial INVITE generates a non-2xx final response, that terminates - * all sessions (if any) and all dialogs (if any) that were created - * through responses to the request. By virtue of completing the - * transaction, a non-2xx final response also prevents further sessions - * from being created as a result of the INVITE. The BYE request is - * used to terminate a specific session or attempted session. In this - * case, the specific session is the one with the peer UA on the other - * side of the dialog. When a BYE is received on a dialog, any session - * associated with that dialog SHOULD terminate. A UA MUST NOT send a - * BYE outside of a dialog. The caller's UA MAY send a BYE for either - * confirmed or early dialogs, and the callee's UA MAY send a BYE on - * confirmed dialogs, but MUST NOT send a BYE on early dialogs. - * - * However, the callee's UA MUST NOT send a BYE on a confirmed dialog - * until it has received an ACK for its 2xx response or until the server - * transaction times out. If no SIP extensions have defined other - * application layer states associated with the dialog, the BYE also - * terminates the dialog. - * - * https://tools.ietf.org/html/rfc3261#section-15 - * FIXME: Make these proper Exceptions... - * @param options - BYE options bucket. - * @returns - * Throws `Error` if callee's UA attempts a BYE on an early dialog. - * Throws `Error` if callee's UA attempts a BYE on a confirmed dialog - * while it's waiting on the ACK for its 2xx response. - */ - SessionDialog.prototype.bye = function (delegate, options) { - this.logger.log("INVITE dialog " + this.id + " sending BYE request"); - // The caller's UA MAY send a BYE for either - // confirmed or early dialogs, and the callee's UA MAY send a BYE on - // confirmed dialogs, but MUST NOT send a BYE on early dialogs. - // - // However, the callee's UA MUST NOT send a BYE on a confirmed dialog - // until it has received an ACK for its 2xx response or until the server - // transaction times out. - // https://tools.ietf.org/html/rfc3261#section-15 - if (this.initialTransaction instanceof transactions_1.InviteServerTransaction) { - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("UAS MUST NOT send a BYE on early dialogs."); - } - if (this.ackWait && this.initialTransaction.state !== transactions_1.TransactionState.Terminated) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("UAS MUST NOT send a BYE on a confirmed dialog " + - "until it has received an ACK for its 2xx response " + - "or until the server transaction times out."); - } - } - // A BYE request is constructed as would any other request within a - // dialog, as described in Section 12. - // - // Once the BYE is constructed, the UAC core creates a new non-INVITE - // client transaction, and passes it the BYE request. The UAC MUST - // consider the session terminated (and therefore stop sending or - // listening for media) as soon as the BYE request is passed to the - // client transaction. If the response for the BYE is a 481 - // (Call/Transaction Does Not Exist) or a 408 (Request Timeout) or no - // response at all is received for the BYE (that is, a timeout is - // returned by the client transaction), the UAC MUST consider the - // session and the dialog terminated. - // https://tools.ietf.org/html/rfc3261#section-15.1.1 - return new bye_user_agent_client_1.ByeUserAgentClient(this, delegate, options); - }; - /** - * An INFO request can be associated with an Info Package (see - * Section 5), or associated with a legacy INFO usage (see Section 2). - * - * The construction of the INFO request is the same as any other - * non-target refresh request within an existing invite dialog usage as - * described in Section 12.2 of RFC 3261. - * https://tools.ietf.org/html/rfc6086#section-4.2.1 - * @param options - Options bucket. - */ - SessionDialog.prototype.info = function (delegate, options) { - this.logger.log("INVITE dialog " + this.id + " sending INFO request"); - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("Dialog not confirmed."); - } - return new info_user_agent_client_1.InfoUserAgentClient(this, delegate, options); - }; - /** - * Modifying an Existing Session - * - * A successful INVITE request (see Section 13) establishes both a - * dialog between two user agents and a session using the offer-answer - * model. Section 12 explains how to modify an existing dialog using a - * target refresh request (for example, changing the remote target URI - * of the dialog). This section describes how to modify the actual - * session. This modification can involve changing addresses or ports, - * adding a media stream, deleting a media stream, and so on. This is - * accomplished by sending a new INVITE request within the same dialog - * that established the session. An INVITE request sent within an - * existing dialog is known as a re-INVITE. - * - * Note that a single re-INVITE can modify the dialog and the - * parameters of the session at the same time. - * - * Either the caller or callee can modify an existing session. - * https://tools.ietf.org/html/rfc3261#section-14 - * @param options - Options bucket - */ - SessionDialog.prototype.invite = function (delegate, options) { - this.logger.log("INVITE dialog " + this.id + " sending INVITE request"); - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("Dialog not confirmed."); - } - // Note that a UAC MUST NOT initiate a new INVITE transaction within a - // dialog while another INVITE transaction is in progress in either - // direction. - // - // 1. If there is an ongoing INVITE client transaction, the TU MUST - // wait until the transaction reaches the completed or terminated - // state before initiating the new INVITE. - // - // 2. If there is an ongoing INVITE server transaction, the TU MUST - // wait until the transaction reaches the confirmed or terminated - // state before initiating the new INVITE. - // - // However, a UA MAY initiate a regular transaction while an INVITE - // transaction is in progress. A UA MAY also initiate an INVITE - // transaction while a regular transaction is in progress. - // https://tools.ietf.org/html/rfc3261#section-14.1 - if (this.reinviteUserAgentClient) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("There is an ongoing re-INVITE client transaction."); - } - if (this.reinviteUserAgentServer) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("There is an ongoing re-INVITE server transaction."); - } - return new re_invite_user_agent_client_1.ReInviteUserAgentClient(this, delegate, options); - }; - /** - * The NOTIFY mechanism defined in [2] MUST be used to inform the agent - * sending the REFER of the status of the reference. - * https://tools.ietf.org/html/rfc3515#section-2.4.4 - * @param options - Options bucket. - */ - SessionDialog.prototype.notify = function (delegate, options) { - this.logger.log("INVITE dialog " + this.id + " sending NOTIFY request"); - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("Dialog not confirmed."); - } - return new notify_user_agent_client_1.NotifyUserAgentClient(this, delegate, options); - }; - /** - * Assuming the response is to be transmitted reliably, the UAC MUST - * create a new request with method PRACK. This request is sent within - * the dialog associated with the provisional response (indeed, the - * provisional response may have created the dialog). PRACK requests - * MAY contain bodies, which are interpreted according to their type and - * disposition. - * https://tools.ietf.org/html/rfc3262#section-4 - * @param options - Options bucket. - */ - SessionDialog.prototype.prack = function (delegate, options) { - this.logger.log("INVITE dialog " + this.id + " sending PRACK request"); - return new prack_user_agent_client_1.PrackUserAgentClient(this, delegate, options); - }; - /** - * REFER is a SIP request and is constructed as defined in [1]. A REFER - * request MUST contain exactly one Refer-To header field value. - * https://tools.ietf.org/html/rfc3515#section-2.4.1 - * @param options - Options bucket. - */ - SessionDialog.prototype.refer = function (delegate, options) { - this.logger.log("INVITE dialog " + this.id + " sending REFER request"); - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("Dialog not confirmed."); - } - // FIXME: TODO: Validate Refer-To header field value. - return new refer_user_agent_client_1.ReferUserAgentClient(this, delegate, options); - }; - /** - * Requests sent within a dialog, as any other requests, are atomic. If - * a particular request is accepted by the UAS, all the state changes - * associated with it are performed. If the request is rejected, none - * of the state changes are performed. - * https://tools.ietf.org/html/rfc3261#section-12.2.2 - * @param message - Incoming request message within this dialog. - */ - SessionDialog.prototype.receiveRequest = function (message) { - this.logger.log("INVITE dialog " + this.id + " received " + message.method + " request"); - // Response retransmissions cease when an ACK request for the - // response is received. This is independent of whatever transport - // protocols are used to send the response. - // https://tools.ietf.org/html/rfc6026#section-8.1 - if (message.method === messages_1.C.ACK) { - // If ackWait is true, then this is the ACK to the initial INVITE, - // otherwise this is an ACK to an in dialog INVITE. In either case, - // guard to make sure the sequence number of the ACK matches the INVITE. - if (this.ackWait) { - if (this.initialTransaction instanceof transactions_1.InviteClientTransaction) { - this.logger.warn("INVITE dialog " + this.id + " received unexpected " + message.method + " request, dropping."); - return; - } - if (this.initialTransaction.request.cseq !== message.cseq) { - this.logger.warn("INVITE dialog " + this.id + " received unexpected " + message.method + " request, dropping."); - return; - } - // Update before the delegate has a chance to handle the - // message as delegate may callback into this dialog. - this.ackWait = false; - } - else { - if (!this.reinviteUserAgentServer) { - this.logger.warn("INVITE dialog " + this.id + " received unexpected " + message.method + " request, dropping."); - return; - } - if (this.reinviteUserAgentServer.transaction.request.cseq !== message.cseq) { - this.logger.warn("INVITE dialog " + this.id + " received unexpected " + message.method + " request, dropping."); - return; - } - this.reinviteUserAgentServer = undefined; - } - this.signalingStateTransition(message); - if (this.delegate && this.delegate.onAck) { - this.delegate.onAck({ message: message }); - } - return; - } - // Request within a dialog out of sequence guard. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (!this.sequenceGuard(message)) { - this.logger.log("INVITE dialog " + this.id + " rejected out of order " + message.method + " request."); - return; - } - if (message.method === messages_1.C.INVITE) { - // A UAS that receives a second INVITE before it sends the final - // response to a first INVITE with a lower CSeq sequence number on the - // same dialog MUST return a 500 (Server Internal Error) response to the - // second INVITE and MUST include a Retry-After header field with a - // randomly chosen value of between 0 and 10 seconds. - // https://tools.ietf.org/html/rfc3261#section-14.2 - if (this.reinviteUserAgentServer) { - // https://tools.ietf.org/html/rfc3261#section-20.33 - var retryAfter = Math.floor((Math.random() * 10)) + 1; - var extraHeaders = ["Retry-After: " + retryAfter]; - this.core.replyStateless(message, { statusCode: 500, extraHeaders: extraHeaders }); - return; - } - // A UAS that receives an INVITE on a dialog while an INVITE it had sent - // on that dialog is in progress MUST return a 491 (Request Pending) - // response to the received INVITE. - // https://tools.ietf.org/html/rfc3261#section-14.2 - if (this.reinviteUserAgentClient) { - this.core.replyStateless(message, { statusCode: 491 }); - return; - } - } - // Request within a dialog common processing. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - _super.prototype.receiveRequest.call(this, message); - // Requests within a dialog MAY contain Record-Route and Contact header - // fields. However, these requests do not cause the dialog's route set - // to be modified, although they may modify the remote target URI. - // Specifically, requests that are not target refresh requests do not - // modify the dialog's remote target URI, and requests that are target - // refresh requests do. For dialogs that have been established with an - // INVITE, the only target refresh request defined is re-INVITE (see - // Section 14). Other extensions may define different target refresh - // requests for dialogs established in other ways. - // - // Note that an ACK is NOT a target refresh request. - // - // Target refresh requests only update the dialog's remote target URI, - // and not the route set formed from the Record-Route. Updating the - // latter would introduce severe backwards compatibility problems with - // RFC 2543-compliant systems. - // https://tools.ietf.org/html/rfc3261#section-15 - if (message.method === messages_1.C.INVITE) { - // FIXME: parser needs to be typed... - var contact = message.parseHeader("contact"); - if (!contact) { // TODO: Review to make sure this will never happen - throw new Error("Contact undefined."); - } - if (!(contact instanceof messages_1.NameAddrHeader)) { - throw new Error("Contact not instance of NameAddrHeader."); - } - this.dialogState.remoteTarget = contact.uri; - } - // Switch on method and then delegate. - switch (message.method) { - case messages_1.C.BYE: - // A UAS core receiving a BYE request for an existing dialog MUST follow - // the procedures of Section 12.2.2 to process the request. Once done, - // the UAS SHOULD terminate the session (and therefore stop sending and - // listening for media). The only case where it can elect not to are - // multicast sessions, where participation is possible even if the other - // participant in the dialog has terminated its involvement in the - // session. Whether or not it ends its participation on the session, - // the UAS core MUST generate a 2xx response to the BYE, and MUST pass - // that to the server transaction for transmission. - // - // The UAS MUST still respond to any pending requests received for that - // dialog. It is RECOMMENDED that a 487 (Request Terminated) response - // be generated to those pending requests. - // https://tools.ietf.org/html/rfc3261#section-15.1.2 - { - var uas = new bye_user_agent_server_1.ByeUserAgentServer(this, message); - this.delegate && this.delegate.onBye ? - this.delegate.onBye(uas) : - uas.accept(); - this.dispose(); - } - break; - case messages_1.C.INFO: - // If a UA receives an INFO request associated with an Info Package that - // the UA has not indicated willingness to receive, the UA MUST send a - // 469 (Bad Info Package) response (see Section 11.6), which contains a - // Recv-Info header field with Info Packages for which the UA is willing - // to receive INFO requests. - { - var uas = new info_user_agent_server_1.InfoUserAgentServer(this, message); - this.delegate && this.delegate.onInfo ? - this.delegate.onInfo(uas) : - uas.reject({ - statusCode: 469, - extraHeaders: ["Recv-Info :"] - }); - } - break; - case messages_1.C.INVITE: - // If the new session description is not acceptable, the UAS can reject - // it by returning a 488 (Not Acceptable Here) response for the re- - // INVITE. This response SHOULD include a Warning header field. - // https://tools.ietf.org/html/rfc3261#section-14.2 - { - var uas = new re_invite_user_agent_server_1.ReInviteUserAgentServer(this, message); - this.signalingStateTransition(message); - this.delegate && this.delegate.onInvite ? - this.delegate.onInvite(uas) : - uas.reject({ statusCode: 488 }); // TODO: Warning header field. - } - break; - case messages_1.C.NOTIFY: - // https://tools.ietf.org/html/rfc3515#section-2.4.4 - { - var uas = new notify_user_agent_server_1.NotifyUserAgentServer(this, message); - this.delegate && this.delegate.onNotify ? - this.delegate.onNotify(uas) : - uas.accept(); - } - break; - case messages_1.C.PRACK: - // https://tools.ietf.org/html/rfc3262#section-4 - { - var uas = new prack_user_agent_server_1.PrackUserAgentServer(this, message); - this.delegate && this.delegate.onPrack ? - this.delegate.onPrack(uas) : - uas.accept(); - } - break; - case messages_1.C.REFER: - // https://tools.ietf.org/html/rfc3515#section-2.4.2 - { - var uas = new refer_user_agent_server_1.ReferUserAgentServer(this, message); - this.delegate && this.delegate.onRefer ? - this.delegate.onRefer(uas) : - uas.reject(); - } - break; - default: - { - this.logger.log("INVITE dialog " + this.id + " received unimplemented " + message.method + " request"); - this.core.replyStateless(message, { statusCode: 501 }); - } - break; - } - }; - SessionDialog.prototype.reliableSequenceGuard = function (message) { - var statusCode = message.statusCode; - if (!statusCode) { - throw new Error("Status code undefined"); - } - if (statusCode > 100 && statusCode < 200) { - // If a provisional response is received for an initial request, and - // that response contains a Require header field containing the option - // tag 100rel, the response is to be sent reliably. If the response is - // a 100 (Trying) (as opposed to 101 to 199), this option tag MUST be - // ignored, and the procedures below MUST NOT be used. - // https://tools.ietf.org/html/rfc3262#section-4 - var requireHeader = message.getHeader("require"); - var rseqHeader = message.getHeader("rseq"); - var rseq = requireHeader && requireHeader.includes("100rel") && rseqHeader ? Number(rseqHeader) : undefined; - if (rseq) { - // Handling of subsequent reliable provisional responses for the same - // initial request follows the same rules as above, with the following - // difference: reliable provisional responses are guaranteed to be in - // order. As a result, if the UAC receives another reliable provisional - // response to the same request, and its RSeq value is not one higher - // than the value of the sequence number, that response MUST NOT be - // acknowledged with a PRACK, and MUST NOT be processed further by the - // UAC. An implementation MAY discard the response, or MAY cache the - // response in the hopes of receiving the missing responses. - // https://tools.ietf.org/html/rfc3262#section-4 - if (this.rseq && this.rseq + 1 !== rseq) { - return false; - } - // Once a reliable provisional response is received, retransmissions of - // that response MUST be discarded. A response is a retransmission when - // its dialog ID, CSeq, and RSeq match the original response. The UAC - // MUST maintain a sequence number that indicates the most recently - // received in-order reliable provisional response for the initial - // request. This sequence number MUST be maintained until a final - // response is received for the initial request. Its value MUST be - // initialized to the RSeq header field in the first reliable - // provisional response received for the initial request. - // https://tools.ietf.org/html/rfc3262#section-4 - if (!this.rseq) { - this.rseq = rseq; - } - } - } - return true; - }; - /** - * If not in a stable signaling state, rollback to prior stable signaling state. - */ - SessionDialog.prototype.signalingStateRollback = function () { - if (this._signalingState === session_1.SignalingState.HaveLocalOffer || - this.signalingState === session_1.SignalingState.HaveRemoteOffer) { - if (this._rollbackOffer && this._rollbackAnswer) { - this._signalingState = session_1.SignalingState.Stable; - this._offer = this._rollbackOffer; - this._answer = this._rollbackAnswer; - } - } - }; - /** - * Update the signaling state of the dialog. - * @param message - The message to base the update off of. - */ - SessionDialog.prototype.signalingStateTransition = function (message) { - var body = messages_1.getBody(message); - // No body, no session. No, woman, no cry. - if (!body || body.contentDisposition !== "session") { - return; - } - // We've got an existing offer and answer which we may wish to rollback to - if (this._signalingState === session_1.SignalingState.Stable) { - this._rollbackOffer = this._offer; - this._rollbackAnswer = this._answer; - } - // We're in UAS role, receiving incoming request with session description - if (message instanceof messages_1.IncomingRequestMessage) { - switch (this._signalingState) { - case session_1.SignalingState.Initial: - case session_1.SignalingState.Stable: - this._signalingState = session_1.SignalingState.HaveRemoteOffer; - this._offer = body; - this._answer = undefined; - break; - case session_1.SignalingState.HaveLocalOffer: - this._signalingState = session_1.SignalingState.Stable; - this._answer = body; - break; - case session_1.SignalingState.HaveRemoteOffer: - // You cannot make a new offer while one is in progress. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // FIXME: What to do here? - break; - case session_1.SignalingState.Closed: - break; - default: - throw new Error("Unexpected signaling state."); - } - } - // We're in UAC role, receiving incoming response with session description - if (message instanceof messages_1.IncomingResponseMessage) { - switch (this._signalingState) { - case session_1.SignalingState.Initial: - case session_1.SignalingState.Stable: - this._signalingState = session_1.SignalingState.HaveRemoteOffer; - this._offer = body; - this._answer = undefined; - break; - case session_1.SignalingState.HaveLocalOffer: - this._signalingState = session_1.SignalingState.Stable; - this._answer = body; - break; - case session_1.SignalingState.HaveRemoteOffer: - // You cannot make a new offer while one is in progress. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // FIXME: What to do here? - break; - case session_1.SignalingState.Closed: - break; - default: - throw new Error("Unexpected signaling state."); - } - } - // We're in UAC role, sending outgoing request with session description - if (message instanceof messages_1.OutgoingRequestMessage) { - switch (this._signalingState) { - case session_1.SignalingState.Initial: - case session_1.SignalingState.Stable: - this._signalingState = session_1.SignalingState.HaveLocalOffer; - this._offer = body; - this._answer = undefined; - break; - case session_1.SignalingState.HaveLocalOffer: - // You cannot make a new offer while one is in progress. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // FIXME: What to do here? - break; - case session_1.SignalingState.HaveRemoteOffer: - this._signalingState = session_1.SignalingState.Stable; - this._answer = body; - break; - case session_1.SignalingState.Closed: - break; - default: - throw new Error("Unexpected signaling state."); - } - } - // We're in UAS role, sending outgoing response with session description - if (messages_1.isBody(message)) { - switch (this._signalingState) { - case session_1.SignalingState.Initial: - case session_1.SignalingState.Stable: - this._signalingState = session_1.SignalingState.HaveLocalOffer; - this._offer = body; - this._answer = undefined; - break; - case session_1.SignalingState.HaveLocalOffer: - // You cannot make a new offer while one is in progress. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // FIXME: What to do here? - break; - case session_1.SignalingState.HaveRemoteOffer: - this._signalingState = session_1.SignalingState.Stable; - this._answer = body; - break; - case session_1.SignalingState.Closed: - break; - default: - throw new Error("Unexpected signaling state."); - } - } - }; - SessionDialog.prototype.start2xxRetransmissionTimer = function () { - var _this = this; - if (this.initialTransaction instanceof transactions_1.InviteServerTransaction) { - var transaction_1 = this.initialTransaction; - // Once the response has been constructed, it is passed to the INVITE - // server transaction. In order to ensure reliable end-to-end - // transport of the response, it is necessary to periodically pass - // the response directly to the transport until the ACK arrives. The - // 2xx response is passed to the transport with an interval that - // starts at T1 seconds and doubles for each retransmission until it - // reaches T2 seconds (T1 and T2 are defined in Section 17). - // Response retransmissions cease when an ACK request for the - // response is received. This is independent of whatever transport - // protocols are used to send the response. - // https://tools.ietf.org/html/rfc6026#section-8.1 - var timeout_1 = timers_1.Timers.T1; - var retransmission_1 = function () { - if (!_this.ackWait) { - _this.invite2xxTimer = undefined; - return; - } - _this.logger.log("No ACK for 2xx response received, attempting retransmission"); - transaction_1.retransmitAcceptedResponse(); - timeout_1 = Math.min(timeout_1 * 2, timers_1.Timers.T2); - _this.invite2xxTimer = setTimeout(retransmission_1, timeout_1); - }; - this.invite2xxTimer = setTimeout(retransmission_1, timeout_1); - // If the server retransmits the 2xx response for 64*T1 seconds without - // receiving an ACK, the dialog is confirmed, but the session SHOULD be - // terminated. This is accomplished with a BYE, as described in Section 15. - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - var stateChanged_1 = function () { - if (transaction_1.state === transactions_1.TransactionState.Terminated) { - transaction_1.removeListener("stateChanged", stateChanged_1); - if (_this.invite2xxTimer) { - clearTimeout(_this.invite2xxTimer); - _this.invite2xxTimer = undefined; - } - if (_this.ackWait) { - if (_this.delegate && _this.delegate.onAckTimeout) { - _this.delegate.onAckTimeout(); - } - else { - _this.bye(); - } - } - } - }; - transaction_1.addListener("stateChanged", stateChanged_1); - } - }; - // FIXME: Refactor - SessionDialog.prototype.startReInvite2xxRetransmissionTimer = function () { - var _this = this; - if (this.reinviteUserAgentServer && this.reinviteUserAgentServer.transaction instanceof transactions_1.InviteServerTransaction) { - var transaction_2 = this.reinviteUserAgentServer.transaction; - // Once the response has been constructed, it is passed to the INVITE - // server transaction. In order to ensure reliable end-to-end - // transport of the response, it is necessary to periodically pass - // the response directly to the transport until the ACK arrives. The - // 2xx response is passed to the transport with an interval that - // starts at T1 seconds and doubles for each retransmission until it - // reaches T2 seconds (T1 and T2 are defined in Section 17). - // Response retransmissions cease when an ACK request for the - // response is received. This is independent of whatever transport - // protocols are used to send the response. - // https://tools.ietf.org/html/rfc6026#section-8.1 - var timeout_2 = timers_1.Timers.T1; - var retransmission_2 = function () { - if (!_this.reinviteUserAgentServer) { - _this.invite2xxTimer = undefined; - return; - } - _this.logger.log("No ACK for 2xx response received, attempting retransmission"); - transaction_2.retransmitAcceptedResponse(); - timeout_2 = Math.min(timeout_2 * 2, timers_1.Timers.T2); - _this.invite2xxTimer = setTimeout(retransmission_2, timeout_2); - }; - this.invite2xxTimer = setTimeout(retransmission_2, timeout_2); - // If the server retransmits the 2xx response for 64*T1 seconds without - // receiving an ACK, the dialog is confirmed, but the session SHOULD be - // terminated. This is accomplished with a BYE, as described in Section 15. - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - var stateChanged_2 = function () { - if (transaction_2.state === transactions_1.TransactionState.Terminated) { - transaction_2.removeListener("stateChanged", stateChanged_2); - if (_this.invite2xxTimer) { - clearTimeout(_this.invite2xxTimer); - _this.invite2xxTimer = undefined; - } - if (_this.reinviteUserAgentServer) { - // FIXME: TODO: What to do here - } - } - }; - transaction_2.addListener("stateChanged", stateChanged_2); - } - }; - return SessionDialog; -}(dialog_1.Dialog)); -exports.SessionDialog = SessionDialog; - - -/***/ }), -/* 24 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -tslib_1.__exportStar(__webpack_require__(25), exports); - - -/***/ }), -/* 25 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * Session state. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-13 - * @public - */ -var SessionState; -(function (SessionState) { - SessionState["Initial"] = "Initial"; - SessionState["Early"] = "Early"; - SessionState["AckWait"] = "AckWait"; - SessionState["Confirmed"] = "Confirmed"; - SessionState["Terminated"] = "Terminated"; -})(SessionState = exports.SessionState || (exports.SessionState = {})); -/** - * Offer/Answer state. - * @remarks - * ```txt - * Offer Answer RFC Ini Est Early - * ------------------------------------------------------------------- - * 1. INVITE Req. 2xx INVITE Resp. RFC 3261 Y Y N - * 2. 2xx INVITE Resp. ACK Req. RFC 3261 Y Y N - * 3. INVITE Req. 1xx-rel INVITE Resp. RFC 3262 Y Y N - * 4. 1xx-rel INVITE Resp. PRACK Req. RFC 3262 Y Y N - * 5. PRACK Req. 200 PRACK Resp. RFC 3262 N Y Y - * 6. UPDATE Req. 2xx UPDATE Resp. RFC 3311 N Y Y - * - * Table 1: Summary of SIP Usage of the Offer/Answer Model - * ``` - * https://tools.ietf.org/html/rfc6337#section-2.2 - * @public - */ -var SignalingState; -(function (SignalingState) { - SignalingState["Initial"] = "Initial"; - SignalingState["HaveLocalOffer"] = "HaveLocalOffer"; - SignalingState["HaveRemoteOffer"] = "HaveRemoteOffer"; - SignalingState["Stable"] = "Stable"; - SignalingState["Closed"] = "Closed"; -})(SignalingState = exports.SignalingState || (exports.SignalingState = {})); - - -/***/ }), -/* 26 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var T1 = 500; -var T2 = 4000; -var T4 = 5000; -/** - * Timers. - * @public - */ -exports.Timers = { - T1: T1, - T2: T2, - T4: T4, - TIMER_B: 64 * T1, - TIMER_D: 0 * T1, - TIMER_F: 64 * T1, - TIMER_H: 64 * T1, - TIMER_I: 0 * T4, - TIMER_J: 0 * T1, - TIMER_K: 0 * T4, - TIMER_L: 64 * T1, - TIMER_M: 64 * T1, - TIMER_N: 64 * T1, - PROVISIONAL_RESPONSE_INTERVAL: 60000 // See RFC 3261 Section 13.3.1.1 -}; - - -/***/ }), -/* 27 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -tslib_1.__exportStar(__webpack_require__(28), exports); -tslib_1.__exportStar(__webpack_require__(35), exports); -tslib_1.__exportStar(__webpack_require__(37), exports); -tslib_1.__exportStar(__webpack_require__(39), exports); -tslib_1.__exportStar(__webpack_require__(40), exports); -tslib_1.__exportStar(__webpack_require__(35), exports); -tslib_1.__exportStar(__webpack_require__(38), exports); -tslib_1.__exportStar(__webpack_require__(36), exports); -tslib_1.__exportStar(__webpack_require__(29), exports); - - -/***/ }), -/* 28 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transaction_1 = __webpack_require__(29); -/** - * Client Transaction. - * @remarks - * The client transaction provides its functionality through the - * maintenance of a state machine. - * - * The TU communicates with the client transaction through a simple - * interface. When the TU wishes to initiate a new transaction, it - * creates a client transaction and passes it the SIP request to send - * and an IP address, port, and transport to which to send it. The - * client transaction begins execution of its state machine. Valid - * responses are passed up to the TU from the client transaction. - * https://tools.ietf.org/html/rfc3261#section-17.1 - * @public - */ -var ClientTransaction = /** @class */ (function (_super) { - tslib_1.__extends(ClientTransaction, _super); - function ClientTransaction(_request, transport, user, state, loggerCategory) { - var _this = _super.call(this, transport, user, ClientTransaction.makeId(_request), state, loggerCategory) || this; - _this._request = _request; - _this.user = user; - // The Via header field indicates the transport used for the transaction - // and identifies the location where the response is to be sent. A Via - // header field value is added only after the transport that will be - // used to reach the next hop has been selected (which may involve the - // usage of the procedures in [4]). - // https://tools.ietf.org/html/rfc3261#section-8.1.1.7 - // FIXME: Transport's server property is not typed (as of writing this). - var scheme = transport.server && transport.server.scheme ? transport.server.scheme : undefined; - _request.setViaHeader(_this.id, scheme); - return _this; - } - ClientTransaction.makeId = function (request) { - if (request.method === "CANCEL") { - if (!request.branch) { - throw new Error("Outgoing CANCEL request without a branch."); - } - return request.branch; - } - else { - return "z9hG4bK" + Math.floor(Math.random() * 10000000); - } - }; - Object.defineProperty(ClientTransaction.prototype, "request", { - /** The outgoing request the transaction handling. */ - get: function () { - return this._request; - }, - enumerable: true, - configurable: true - }); - /** - * A 408 to non-INVITE will always arrive too late to be useful ([3]), - * The client already has full knowledge of the timeout. The only - * information this message would convey is whether or not the server - * believed the transaction timed out. However, with the current design - * of the NIT, a client cannot do anything with this knowledge. Thus, - * the 408 is simply wasting network resources and contributes to the - * response bombardment illustrated in [3]. - * https://tools.ietf.org/html/rfc4320#section-4.1 - */ - ClientTransaction.prototype.onRequestTimeout = function () { - if (this.user.onRequestTimeout) { - this.user.onRequestTimeout(); - } - }; - return ClientTransaction; -}(transaction_1.Transaction)); -exports.ClientTransaction = ClientTransaction; - - -/***/ }), -/* 29 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var events_1 = __webpack_require__(30); -var exceptions_1 = __webpack_require__(31); -/** - * Transaction. - * @remarks - * SIP is a transactional protocol: interactions between components take - * place in a series of independent message exchanges. Specifically, a - * SIP transaction consists of a single request and any responses to - * that request, which include zero or more provisional responses and - * one or more final responses. In the case of a transaction where the - * request was an INVITE (known as an INVITE transaction), the - * transaction also includes the ACK only if the final response was not - * a 2xx response. If the response was a 2xx, the ACK is not considered - * part of the transaction. - * https://tools.ietf.org/html/rfc3261#section-17 - * @public - */ -var Transaction = /** @class */ (function (_super) { - tslib_1.__extends(Transaction, _super); - function Transaction(_transport, _user, _id, _state, loggerCategory) { - var _this = _super.call(this) || this; - _this._transport = _transport; - _this._user = _user; - _this._id = _id; - _this._state = _state; - _this.logger = _user.loggerFactory.getLogger(loggerCategory, _id); - _this.logger.debug("Constructing " + _this.typeToString() + " with id " + _this.id + "."); - return _this; - } - /** - * Destructor. - * Once the transaction is in the "terminated" state, it is destroyed - * immediately and there is no need to call `dispose`. However, if a - * transaction needs to be ended prematurely, the transaction user may - * do so by calling this method (for example, perhaps the UA is shutting down). - * No state transition will occur upon calling this method, all outstanding - * transmission timers will be cancelled, and use of the transaction after - * calling `dispose` is undefined. - */ - Transaction.prototype.dispose = function () { - this.logger.debug("Destroyed " + this.typeToString() + " with id " + this.id + "."); - }; - Object.defineProperty(Transaction.prototype, "id", { - /** Transaction id. */ - get: function () { - return this._id; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Transaction.prototype, "kind", { - /** Transaction kind. Deprecated. */ - get: function () { - throw new Error("Invalid kind."); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Transaction.prototype, "state", { - /** Transaction state. */ - get: function () { - return this._state; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Transaction.prototype, "transport", { - /** Transaction transport. */ - get: function () { - return this._transport; - }, - enumerable: true, - configurable: true - }); - Transaction.prototype.on = function (name, callback) { return _super.prototype.on.call(this, name, callback); }; - Transaction.prototype.logTransportError = function (error, message) { - this.logger.error(error.message); - this.logger.error("Transport error occurred in " + this.typeToString() + " with id " + this.id + "."); - this.logger.error(message); - }; - /** - * Pass message to transport for transmission. If transport fails, - * the transaction user is notified by callback to onTransportError(). - * @returns - * Rejects with `TransportError` if transport fails. - */ - Transaction.prototype.send = function (message) { - var _this = this; - return this.transport.send(message).catch(function (error) { - // FIXME: Transport is not, yet, typed and it is not clear - // yet what send() may or may not send our way. So for now, - // make sure we convert it to a TransportError if need be. - if (error instanceof exceptions_1.TransportError) { - _this.onTransportError(error); - return; - } - var transportError; - if (error && typeof error.message === "string") { - transportError = new exceptions_1.TransportError(error.message); - } - else { - transportError = new exceptions_1.TransportError(); - } - _this.onTransportError(transportError); - throw transportError; - }); - }; - Transaction.prototype.setState = function (state) { - this.logger.debug("State change to \"" + state + "\" on " + this.typeToString() + " with id " + this.id + "."); - this._state = state; - if (this._user.onStateChange) { - this._user.onStateChange(state); - } - this.emit("stateChanged"); - }; - Transaction.prototype.typeToString = function () { - return "UnknownType"; - }; - return Transaction; -}(events_1.EventEmitter)); -exports.Transaction = Transaction; - - -/***/ }), -/* 30 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - -var R = typeof Reflect === 'object' ? Reflect : null -var ReflectApply = R && typeof R.apply === 'function' - ? R.apply - : function ReflectApply(target, receiver, args) { - return Function.prototype.apply.call(target, receiver, args); - } - -var ReflectOwnKeys -if (R && typeof R.ownKeys === 'function') { - ReflectOwnKeys = R.ownKeys -} else if (Object.getOwnPropertySymbols) { - ReflectOwnKeys = function ReflectOwnKeys(target) { - return Object.getOwnPropertyNames(target) - .concat(Object.getOwnPropertySymbols(target)); - }; -} else { - ReflectOwnKeys = function ReflectOwnKeys(target) { - return Object.getOwnPropertyNames(target); - }; -} - -function ProcessEmitWarning(warning) { - if (console && console.warn) console.warn(warning); -} - -var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { - return value !== value; -} - -function EventEmitter() { - EventEmitter.init.call(this); -} -module.exports = EventEmitter; - -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; - -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._eventsCount = 0; -EventEmitter.prototype._maxListeners = undefined; - -// By default EventEmitters will print a warning if more than 10 listeners are -// added to it. This is a useful default which helps finding memory leaks. -var defaultMaxListeners = 10; - -Object.defineProperty(EventEmitter, 'defaultMaxListeners', { - enumerable: true, - get: function() { - return defaultMaxListeners; - }, - set: function(arg) { - if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { - throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); - } - defaultMaxListeners = arg; - } -}); - -EventEmitter.init = function() { - - if (this._events === undefined || - this._events === Object.getPrototypeOf(this)._events) { - this._events = Object.create(null); - this._eventsCount = 0; - } - - this._maxListeners = this._maxListeners || undefined; -}; - -// Obviously not all Emitters should be limited to 10. This function allows -// that to be increased. Set to zero for unlimited. -EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { - if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { - throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); - } - this._maxListeners = n; - return this; -}; - -function $getMaxListeners(that) { - if (that._maxListeners === undefined) - return EventEmitter.defaultMaxListeners; - return that._maxListeners; -} - -EventEmitter.prototype.getMaxListeners = function getMaxListeners() { - return $getMaxListeners(this); -}; - -EventEmitter.prototype.emit = function emit(type) { - var args = []; - for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); - var doError = (type === 'error'); - - var events = this._events; - if (events !== undefined) - doError = (doError && events.error === undefined); - else if (!doError) - return false; - - // If there is no 'error' event listener then throw. - if (doError) { - var er; - if (args.length > 0) - er = args[0]; - if (er instanceof Error) { - // Note: The comments on the `throw` lines are intentional, they show - // up in Node's output if this results in an unhandled exception. - throw er; // Unhandled 'error' event - } - // At least give some kind of context to the user - var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); - err.context = er; - throw err; // Unhandled 'error' event - } - - var handler = events[type]; - - if (handler === undefined) - return false; - - if (typeof handler === 'function') { - ReflectApply(handler, this, args); - } else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - ReflectApply(listeners[i], this, args); - } - - return true; -}; - -function _addListener(target, type, listener, prepend) { - var m; - var events; - var existing; - - if (typeof listener !== 'function') { - throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); - } - - events = target._events; - if (events === undefined) { - events = target._events = Object.create(null); - target._eventsCount = 0; - } else { - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (events.newListener !== undefined) { - target.emit('newListener', type, - listener.listener ? listener.listener : listener); - - // Re-assign `events` because a newListener handler could have caused the - // this._events to be assigned to a new object - events = target._events; - } - existing = events[type]; - } - - if (existing === undefined) { - // Optimize the case of one listener. Don't need the extra array object. - existing = events[type] = listener; - ++target._eventsCount; - } else { - if (typeof existing === 'function') { - // Adding the second element, need to change to array. - existing = events[type] = - prepend ? [listener, existing] : [existing, listener]; - // If we've already got an array, just append. - } else if (prepend) { - existing.unshift(listener); - } else { - existing.push(listener); - } - - // Check for listener leak - m = $getMaxListeners(target); - if (m > 0 && existing.length > m && !existing.warned) { - existing.warned = true; - // No error code for this since it is a Warning - // eslint-disable-next-line no-restricted-syntax - var w = new Error('Possible EventEmitter memory leak detected. ' + - existing.length + ' ' + String(type) + ' listeners ' + - 'added. Use emitter.setMaxListeners() to ' + - 'increase limit'); - w.name = 'MaxListenersExceededWarning'; - w.emitter = target; - w.type = type; - w.count = existing.length; - ProcessEmitWarning(w); - } - } - - return target; -} - -EventEmitter.prototype.addListener = function addListener(type, listener) { - return _addListener(this, type, listener, false); -}; - -EventEmitter.prototype.on = EventEmitter.prototype.addListener; - -EventEmitter.prototype.prependListener = - function prependListener(type, listener) { - return _addListener(this, type, listener, true); - }; - -function onceWrapper() { - var args = []; - for (var i = 0; i < arguments.length; i++) args.push(arguments[i]); - if (!this.fired) { - this.target.removeListener(this.type, this.wrapFn); - this.fired = true; - ReflectApply(this.listener, this.target, args); - } -} - -function _onceWrap(target, type, listener) { - var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; - var wrapped = onceWrapper.bind(state); - wrapped.listener = listener; - state.wrapFn = wrapped; - return wrapped; -} - -EventEmitter.prototype.once = function once(type, listener) { - if (typeof listener !== 'function') { - throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); - } - this.on(type, _onceWrap(this, type, listener)); - return this; -}; - -EventEmitter.prototype.prependOnceListener = - function prependOnceListener(type, listener) { - if (typeof listener !== 'function') { - throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); - } - this.prependListener(type, _onceWrap(this, type, listener)); - return this; - }; - -// Emits a 'removeListener' event if and only if the listener was removed. -EventEmitter.prototype.removeListener = - function removeListener(type, listener) { - var list, events, position, i, originalListener; - - if (typeof listener !== 'function') { - throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); - } - - events = this._events; - if (events === undefined) - return this; - - list = events[type]; - if (list === undefined) - return this; - - if (list === listener || list.listener === listener) { - if (--this._eventsCount === 0) - this._events = Object.create(null); - else { - delete events[type]; - if (events.removeListener) - this.emit('removeListener', type, list.listener || listener); - } - } else if (typeof list !== 'function') { - position = -1; - - for (i = list.length - 1; i >= 0; i--) { - if (list[i] === listener || list[i].listener === listener) { - originalListener = list[i].listener; - position = i; - break; - } - } - - if (position < 0) - return this; - - if (position === 0) - list.shift(); - else { - spliceOne(list, position); - } - - if (list.length === 1) - events[type] = list[0]; - - if (events.removeListener !== undefined) - this.emit('removeListener', type, originalListener || listener); - } - - return this; - }; - -EventEmitter.prototype.off = EventEmitter.prototype.removeListener; - -EventEmitter.prototype.removeAllListeners = - function removeAllListeners(type) { - var listeners, events, i; - - events = this._events; - if (events === undefined) - return this; - - // not listening for removeListener, no need to emit - if (events.removeListener === undefined) { - if (arguments.length === 0) { - this._events = Object.create(null); - this._eventsCount = 0; - } else if (events[type] !== undefined) { - if (--this._eventsCount === 0) - this._events = Object.create(null); - else - delete events[type]; - } - return this; - } - - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - var keys = Object.keys(events); - var key; - for (i = 0; i < keys.length; ++i) { - key = keys[i]; - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = Object.create(null); - this._eventsCount = 0; - return this; - } - - listeners = events[type]; - - if (typeof listeners === 'function') { - this.removeListener(type, listeners); - } else if (listeners !== undefined) { - // LIFO order - for (i = listeners.length - 1; i >= 0; i--) { - this.removeListener(type, listeners[i]); - } - } - - return this; - }; - -function _listeners(target, type, unwrap) { - var events = target._events; - - if (events === undefined) - return []; - - var evlistener = events[type]; - if (evlistener === undefined) - return []; - - if (typeof evlistener === 'function') - return unwrap ? [evlistener.listener || evlistener] : [evlistener]; - - return unwrap ? - unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); -} - -EventEmitter.prototype.listeners = function listeners(type) { - return _listeners(this, type, true); -}; - -EventEmitter.prototype.rawListeners = function rawListeners(type) { - return _listeners(this, type, false); -}; - -EventEmitter.listenerCount = function(emitter, type) { - if (typeof emitter.listenerCount === 'function') { - return emitter.listenerCount(type); - } else { - return listenerCount.call(emitter, type); - } -}; - -EventEmitter.prototype.listenerCount = listenerCount; -function listenerCount(type) { - var events = this._events; - - if (events !== undefined) { - var evlistener = events[type]; - - if (typeof evlistener === 'function') { - return 1; - } else if (evlistener !== undefined) { - return evlistener.length; - } - } - - return 0; -} - -EventEmitter.prototype.eventNames = function eventNames() { - return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; -}; - -function arrayClone(arr, n) { - var copy = new Array(n); - for (var i = 0; i < n; ++i) - copy[i] = arr[i]; - return copy; -} - -function spliceOne(list, index) { - for (; index + 1 < list.length; index++) - list[index] = list[index + 1]; - list.pop(); -} - -function unwrapListeners(arr) { - var ret = new Array(arr.length); - for (var i = 0; i < ret.length; ++i) { - ret[i] = arr[i].listener || arr[i]; - } - return ret; -} - - -/***/ }), -/* 31 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -tslib_1.__exportStar(__webpack_require__(32), exports); -tslib_1.__exportStar(__webpack_require__(33), exports); -tslib_1.__exportStar(__webpack_require__(34), exports); - - -/***/ }), -/* 32 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -/** - * An Exception is considered a condition that a reasonable application may wish to catch. - * An Error indicates serious problems that a reasonable application should not try to catch. - * @public - */ -var Exception = /** @class */ (function (_super) { - tslib_1.__extends(Exception, _super); - function Exception(message) { - var _newTarget = this.constructor; - var _this = _super.call(this, message) || this; - Object.setPrototypeOf(_this, _newTarget.prototype); // restore prototype chain - return _this; - } - return Exception; -}(Error)); -exports.Exception = Exception; - - -/***/ }), -/* 33 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var exception_1 = __webpack_require__(32); -/** - * Indicates that the operation could not be completed given the current transaction state. - * @public - */ -var TransactionStateError = /** @class */ (function (_super) { - tslib_1.__extends(TransactionStateError, _super); - function TransactionStateError(message) { - return _super.call(this, message ? message : "Transaction state error.") || this; - } - return TransactionStateError; -}(exception_1.Exception)); -exports.TransactionStateError = TransactionStateError; - - -/***/ }), -/* 34 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var exception_1 = __webpack_require__(32); -/** - * Transport error. - * @public - */ -var TransportError = /** @class */ (function (_super) { - tslib_1.__extends(TransportError, _super); - function TransportError(message) { - return _super.call(this, message ? message : "Unspecified transport error.") || this; - } - return TransportError; -}(exception_1.Exception)); -exports.TransportError = TransportError; - - -/***/ }), -/* 35 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var timers_1 = __webpack_require__(26); -var client_transaction_1 = __webpack_require__(28); -var transaction_state_1 = __webpack_require__(36); -/** - * INVITE Client Transaction. - * @remarks - * The INVITE transaction consists of a three-way handshake. The client - * transaction sends an INVITE, the server transaction sends responses, - * and the client transaction sends an ACK. - * https://tools.ietf.org/html/rfc3261#section-17.1.1 - * @public - */ -var InviteClientTransaction = /** @class */ (function (_super) { - tslib_1.__extends(InviteClientTransaction, _super); - /** - * Constructor. - * Upon construction, the outgoing request's Via header is updated by calling `setViaHeader`. - * Then `toString` is called on the outgoing request and the message is sent via the transport. - * After construction the transaction will be in the "calling" state and the transaction id - * will equal the branch parameter set in the Via header of the outgoing request. - * https://tools.ietf.org/html/rfc3261#section-17.1.1 - * @param request - The outgoing INVITE request. - * @param transport - The transport. - * @param user - The transaction user. - */ - function InviteClientTransaction(request, transport, user) { - var _this = _super.call(this, request, transport, user, transaction_state_1.TransactionState.Calling, "sip.transaction.ict") || this; - /** - * Map of 2xx to-tag to ACK. - * If value is not undefined, value is the ACK which was sent. - * If key exists but value is undefined, a 2xx was received but the ACK not yet sent. - * Otherwise, a 2xx was not (yet) received for this transaction. - */ - _this.ackRetransmissionCache = new Map(); - // FIXME: Timer A for unreliable transport not implemented - // - // If an unreliable transport is being used, the client transaction - // MUST start timer A with a value of T1. If a reliable transport is being used, - // the client transaction SHOULD NOT start timer A (Timer A controls request retransmissions). - // For any transport, the client transaction MUST start timer B with a value - // of 64*T1 seconds (Timer B controls transaction timeouts). - // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - // - // While not spelled out in the RFC, Timer B is the maximum amount of time that a sender - // will wait for an INVITE message to be acknowledged (a SIP response message is received). - // So Timer B should be cleared when the transaction state proceeds from "Calling". - _this.B = setTimeout(function () { return _this.timer_B(); }, timers_1.Timers.TIMER_B); - _this.send(request.toString()).catch(function (error) { - _this.logTransportError(error, "Failed to send initial outgoing request."); - }); - return _this; - } - /** - * Destructor. - */ - InviteClientTransaction.prototype.dispose = function () { - if (this.B) { - clearTimeout(this.B); - this.B = undefined; - } - if (this.D) { - clearTimeout(this.D); - this.D = undefined; - } - if (this.M) { - clearTimeout(this.M); - this.M = undefined; - } - _super.prototype.dispose.call(this); - }; - Object.defineProperty(InviteClientTransaction.prototype, "kind", { - /** Transaction kind. Deprecated. */ - get: function () { - return "ict"; - }, - enumerable: true, - configurable: true - }); - /** - * ACK a 2xx final response. - * - * The transaction includes the ACK only if the final response was not a 2xx response (the - * transaction will generate and send the ACK to the transport automagically). If the - * final response was a 2xx, the ACK is not considered part of the transaction (the - * transaction user needs to generate and send the ACK). - * - * This library is not strictly RFC compliant with regard to ACK handling for 2xx final - * responses. Specifically, retransmissions of ACKs to a 2xx final responses is handled - * by the transaction layer (instead of the UAC core). The "standard" approach is for - * the UAC core to receive all 2xx responses and manage sending ACK retransmissions to - * the transport directly. Herein the transaction layer manages sending ACKs to 2xx responses - * and any retransmissions of those ACKs as needed. - * - * @param ack - The outgoing ACK request. - */ - InviteClientTransaction.prototype.ackResponse = function (ack) { - var _this = this; - var toTag = ack.toTag; - if (!toTag) { - throw new Error("To tag undefined."); - } - var id = "z9hG4bK" + Math.floor(Math.random() * 10000000); - // FIXME: Transport's server property is not typed (as of writing this). - var scheme = this.transport.server && this.transport.server.scheme ? this.transport.server.scheme : undefined; - ack.setViaHeader(id, scheme); - this.ackRetransmissionCache.set(toTag, ack); // Add to ACK retransmission cache - this.send(ack.toString()).catch(function (error) { - _this.logTransportError(error, "Failed to send ACK to 2xx response."); - }); - }; - /** - * Handler for incoming responses from the transport which match this transaction. - * @param response - The incoming response. - */ - InviteClientTransaction.prototype.receiveResponse = function (response) { - var _this = this; - var statusCode = response.statusCode; - if (!statusCode || statusCode < 100 || statusCode > 699) { - throw new Error("Invalid status code " + statusCode); - } - switch (this.state) { - case transaction_state_1.TransactionState.Calling: - // If the client transaction receives a provisional response while in - // the "Calling" state, it transitions to the "Proceeding" state. In the - // "Proceeding" state, the client transaction SHOULD NOT retransmit the - // request any longer. Furthermore, the provisional response MUST be - // passed to the TU. Any further provisional responses MUST be passed - // up to the TU while in the "Proceeding" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - if (statusCode >= 100 && statusCode <= 199) { - this.stateTransition(transaction_state_1.TransactionState.Proceeding); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // When a 2xx response is received while in either the "Calling" or - // "Proceeding" states, the client transaction MUST transition to - // the "Accepted" state... The 2xx response MUST be passed up to the TU. - // The client transaction MUST NOT generate an ACK to the 2xx response -- its - // handling is delegated to the TU. A UAC core will send an ACK to - // the 2xx response using a new transaction. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 200 && statusCode <= 299) { - this.ackRetransmissionCache.set(response.toTag, undefined); // Prime the ACK cache - this.stateTransition(transaction_state_1.TransactionState.Accepted); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // When in either the "Calling" or "Proceeding" states, reception of - // a response with status code from 300-699 MUST cause the client - // transaction to transition to "Completed". The client transaction - // MUST pass the received response up to the TU, and the client - // transaction MUST generate an ACK request, even if the transport is - // reliable (guidelines for constructing the ACK from the response - // are given in Section 17.1.1.3), and then pass the ACK to the - // transport layer for transmission. The ACK MUST be sent to the - // same address, port, and transport to which the original request was sent. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 300 && statusCode <= 699) { - this.stateTransition(transaction_state_1.TransactionState.Completed); - this.ack(response); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - break; - case transaction_state_1.TransactionState.Proceeding: - // In the "Proceeding" state, the client transaction SHOULD NOT retransmit the - // request any longer. Furthermore, the provisional response MUST be - // passed to the TU. Any further provisional responses MUST be passed - // up to the TU while in the "Proceeding" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - if (statusCode >= 100 && statusCode <= 199) { - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // When a 2xx response is received while in either the "Calling" or "Proceeding" states, - // the client transaction MUST transition to the "Accepted" state... - // The 2xx response MUST be passed up to the TU. The client - // transaction MUST NOT generate an ACK to the 2xx response -- its - // handling is delegated to the TU. A UAC core will send an ACK to - // the 2xx response using a new transaction. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 200 && statusCode <= 299) { - this.ackRetransmissionCache.set(response.toTag, undefined); // Prime the ACK cache - this.stateTransition(transaction_state_1.TransactionState.Accepted); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // When in either the "Calling" or "Proceeding" states, reception of - // a response with status code from 300-699 MUST cause the client - // transaction to transition to "Completed". The client transaction - // MUST pass the received response up to the TU, and the client - // transaction MUST generate an ACK request, even if the transport is - // reliable (guidelines for constructing the ACK from the response - // are given in Section 17.1.1.3), and then pass the ACK to the - // transport layer for transmission. The ACK MUST be sent to the - // same address, port, and transport to which the original request was sent. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 300 && statusCode <= 699) { - this.stateTransition(transaction_state_1.TransactionState.Completed); - this.ack(response); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - break; - case transaction_state_1.TransactionState.Accepted: - // The purpose of the "Accepted" state is to allow the client - // transaction to continue to exist to receive, and pass to the TU, - // any retransmissions of the 2xx response and any additional 2xx - // responses from other branches of the INVITE if it forked - // downstream. Timer M reflects the amount of time that the - // transaction user will wait for such messages. - // - // Any 2xx responses that match this client transaction and that are - // received while in the "Accepted" state MUST be passed up to the - // TU. The client transaction MUST NOT generate an ACK to the 2xx - // response. The client transaction takes no further action. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 200 && statusCode <= 299) { - // NOTE: This implementation herein is intentionally not RFC compliant. - // While the first 2xx response for a given branch is passed up to the TU, - // retransmissions of 2xx responses are absorbed and the ACK associated - // with the original response is resent. This approach is taken because - // our current transaction users are not currently in a good position to - // deal with 2xx retransmission. This SHOULD NOT cause any compliance issues - ;) - // - // If we don't have a cache hit, pass the response to the TU. - if (!this.ackRetransmissionCache.has(response.toTag)) { - this.ackRetransmissionCache.set(response.toTag, undefined); // Prime the ACK cache - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // If we have a cache hit, try pulling the ACK from cache and retransmitting it. - var ack = this.ackRetransmissionCache.get(response.toTag); - if (ack) { - this.send(ack.toString()).catch(function (error) { - _this.logTransportError(error, "Failed to send retransmission of ACK to 2xx response."); - }); - return; - } - // If an ACK was not found in cache then we have received a retransmitted 2xx - // response before the TU responded to the original response (we don't have an ACK yet). - // So discard this response under the assumption that the TU will eventually - // get us a ACK for the original response. - return; - } - break; - case transaction_state_1.TransactionState.Completed: - // Any retransmissions of a response with status code 300-699 that - // are received while in the "Completed" state MUST cause the ACK to - // be re-passed to the transport layer for retransmission, but the - // newly received response MUST NOT be passed up to the TU. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 300 && statusCode <= 699) { - this.ack(response); - return; - } - break; - case transaction_state_1.TransactionState.Terminated: - break; - default: - throw new Error("Invalid state " + this.state); - } - // Any response received that does not match an existing client - // transaction state machine is simply dropped. (Implementations are, - // of course, free to log or do other implementation-specific things - // with such responses, but the implementer should be sure to consider - // the impact of large numbers of malicious stray responses.) - // https://tools.ietf.org/html/rfc6026#section-7.2 - var message = "Received unexpected " + statusCode + " response while in state " + this.state + "."; - this.logger.warn(message); - return; - }; - /** - * The client transaction SHOULD inform the TU that a transport failure - * has occurred, and the client transaction SHOULD transition directly - * to the "Terminated" state. The TU will handle the failover - * mechanisms described in [4]. - * https://tools.ietf.org/html/rfc3261#section-17.1.4 - * @param error - The error. - */ - InviteClientTransaction.prototype.onTransportError = function (error) { - if (this.user.onTransportError) { - this.user.onTransportError(error); - } - this.stateTransition(transaction_state_1.TransactionState.Terminated, true); - }; - /** For logging. */ - InviteClientTransaction.prototype.typeToString = function () { - return "INVITE client transaction"; - }; - InviteClientTransaction.prototype.ack = function (response) { - var _this = this; - // The ACK request constructed by the client transaction MUST contain - // values for the Call-ID, From, and Request-URI that are equal to the - // values of those header fields in the request passed to the transport - // by the client transaction (call this the "original request"). The To - // header field in the ACK MUST equal the To header field in the - // response being acknowledged, and therefore will usually differ from - // the To header field in the original request by the addition of the - // tag parameter. The ACK MUST contain a single Via header field, and - // this MUST be equal to the top Via header field of the original - // request. The CSeq header field in the ACK MUST contain the same - // value for the sequence number as was present in the original request, - // but the method parameter MUST be equal to "ACK". - // - // If the INVITE request whose response is being acknowledged had Route - // header fields, those header fields MUST appear in the ACK. This is - // to ensure that the ACK can be routed properly through any downstream - // stateless proxies. - // https://tools.ietf.org/html/rfc3261#section-17.1.1.3 - var ruri = this.request.ruri; - var callId = this.request.callId; - var cseq = this.request.cseq; - var from = this.request.getHeader("from"); - var to = response.getHeader("to"); - var via = this.request.getHeader("via"); - var route = this.request.getHeader("route"); - if (!from) { - throw new Error("From undefined."); - } - if (!to) { - throw new Error("To undefined."); - } - if (!via) { - throw new Error("Via undefined."); - } - var ack = "ACK " + ruri + " SIP/2.0\r\n"; - if (route) { - ack += "Route: " + route + "\r\n"; - } - ack += "Via: " + via + "\r\n"; - ack += "To: " + to + "\r\n"; - ack += "From: " + from + "\r\n"; - ack += "Call-ID: " + callId + "\r\n"; - ack += "CSeq: " + cseq + " ACK\r\n"; - ack += "Max-Forwards: 70\r\n"; - ack += "Content-Length: 0\r\n\r\n"; - // TOOO: "User-Agent" header - this.send(ack).catch(function (error) { - _this.logTransportError(error, "Failed to send ACK to non-2xx response."); - }); - return; - }; - /** - * Execute a state transition. - * @param newState - New state. - */ - InviteClientTransaction.prototype.stateTransition = function (newState, dueToTransportError) { - var _this = this; - if (dueToTransportError === void 0) { dueToTransportError = false; } - // Assert valid state transitions. - var invalidStateTransition = function () { - throw new Error("Invalid state transition from " + _this.state + " to " + newState); - }; - switch (newState) { - case transaction_state_1.TransactionState.Calling: - invalidStateTransition(); - break; - case transaction_state_1.TransactionState.Proceeding: - if (this.state !== transaction_state_1.TransactionState.Calling) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Accepted: - case transaction_state_1.TransactionState.Completed: - if (this.state !== transaction_state_1.TransactionState.Calling && - this.state !== transaction_state_1.TransactionState.Proceeding) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Terminated: - if (this.state !== transaction_state_1.TransactionState.Calling && - this.state !== transaction_state_1.TransactionState.Accepted && - this.state !== transaction_state_1.TransactionState.Completed) { - if (!dueToTransportError) { - invalidStateTransition(); - } - } - break; - default: - invalidStateTransition(); - } - // While not spelled out in the RFC, Timer B is the maximum amount of time that a sender - // will wait for an INVITE message to be acknowledged (a SIP response message is received). - // So Timer B should be cleared when the transaction state proceeds from "Calling". - if (this.B) { - clearTimeout(this.B); - this.B = undefined; - } - if (newState === transaction_state_1.TransactionState.Proceeding) { - // Timers have no effect on "Proceeding" state. - // In the "Proceeding" state, the client transaction - // SHOULD NOT retransmit the request any longer. - // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - } - // The client transaction MUST start Timer D when it enters the "Completed" state - // for any reason, with a value of at least 32 seconds for unreliable transports, - // and a value of zero seconds for reliable transports. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (newState === transaction_state_1.TransactionState.Completed) { - this.D = setTimeout(function () { return _this.timer_D(); }, timers_1.Timers.TIMER_D); - } - // The client transaction MUST transition to the "Accepted" state, - // and Timer M MUST be started with a value of 64*T1. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (newState === transaction_state_1.TransactionState.Accepted) { - this.M = setTimeout(function () { return _this.timer_M(); }, timers_1.Timers.TIMER_M); - } - // Once the transaction is in the "Terminated" state, it MUST be destroyed immediately. - // https://tools.ietf.org/html/rfc6026#section-8.7 - if (newState === transaction_state_1.TransactionState.Terminated) { - this.dispose(); - } - // Update state. - this.setState(newState); - }; - /** - * When timer A fires, the client transaction MUST retransmit the - * request by passing it to the transport layer, and MUST reset the - * timer with a value of 2*T1. - * When timer A fires 2*T1 seconds later, the request MUST be - * retransmitted again (assuming the client transaction is still in this - * state). This process MUST continue so that the request is - * retransmitted with intervals that double after each transmission. - * These retransmissions SHOULD only be done while the client - * transaction is in the "Calling" state. - * https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - */ - InviteClientTransaction.prototype.timer_A = function () { - // TODO - }; - /** - * If the client transaction is still in the "Calling" state when timer - * B fires, the client transaction SHOULD inform the TU that a timeout - * has occurred. The client transaction MUST NOT generate an ACK. - * https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - */ - InviteClientTransaction.prototype.timer_B = function () { - this.logger.debug("Timer B expired for INVITE client transaction " + this.id + "."); - if (this.state === transaction_state_1.TransactionState.Calling) { - this.onRequestTimeout(); - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - /** - * If Timer D fires while the client transaction is in the "Completed" state, - * the client transaction MUST move to the "Terminated" state. - * https://tools.ietf.org/html/rfc6026#section-8.4 - */ - InviteClientTransaction.prototype.timer_D = function () { - this.logger.debug("Timer D expired for INVITE client transaction " + this.id + "."); - if (this.state === transaction_state_1.TransactionState.Completed) { - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - /** - * If Timer M fires while the client transaction is in the "Accepted" - * state, the client transaction MUST move to the "Terminated" state. - * https://tools.ietf.org/html/rfc6026#section-8.4 - */ - InviteClientTransaction.prototype.timer_M = function () { - this.logger.debug("Timer M expired for INVITE client transaction " + this.id + "."); - if (this.state === transaction_state_1.TransactionState.Accepted) { - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - return InviteClientTransaction; -}(client_transaction_1.ClientTransaction)); -exports.InviteClientTransaction = InviteClientTransaction; - - -/***/ }), -/* 36 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * Transaction state. - * @public - */ -var TransactionState; -(function (TransactionState) { - TransactionState["Accepted"] = "Accepted"; - TransactionState["Calling"] = "Calling"; - TransactionState["Completed"] = "Completed"; - TransactionState["Confirmed"] = "Confirmed"; - TransactionState["Proceeding"] = "Proceeding"; - TransactionState["Terminated"] = "Terminated"; - TransactionState["Trying"] = "Trying"; -})(TransactionState = exports.TransactionState || (exports.TransactionState = {})); - - -/***/ }), -/* 37 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var timers_1 = __webpack_require__(26); -var server_transaction_1 = __webpack_require__(38); -var transaction_state_1 = __webpack_require__(36); -/** - * INVITE Server Transaction. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - * @public - */ -var InviteServerTransaction = /** @class */ (function (_super) { - tslib_1.__extends(InviteServerTransaction, _super); - /** - * Constructor. - * Upon construction, a "100 Trying" reply will be immediately sent. - * After construction the transaction will be in the "proceeding" state and the transaction - * `id` will equal the branch parameter set in the Via header of the incoming request. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - * @param request - Incoming INVITE request from the transport. - * @param transport - The transport. - * @param user - The transaction user. - */ - function InviteServerTransaction(request, transport, user) { - return _super.call(this, request, transport, user, transaction_state_1.TransactionState.Proceeding, "sip.transaction.ist") || this; - } - /** - * Destructor. - */ - InviteServerTransaction.prototype.dispose = function () { - this.stopProgressExtensionTimer(); - if (this.H) { - clearTimeout(this.H); - this.H = undefined; - } - if (this.I) { - clearTimeout(this.I); - this.I = undefined; - } - if (this.L) { - clearTimeout(this.L); - this.L = undefined; - } - _super.prototype.dispose.call(this); - }; - Object.defineProperty(InviteServerTransaction.prototype, "kind", { - /** Transaction kind. Deprecated. */ - get: function () { - return "ist"; - }, - enumerable: true, - configurable: true - }); - /** - * Receive requests from transport matching this transaction. - * @param request - Request matching this transaction. - */ - InviteServerTransaction.prototype.receiveRequest = function (request) { - var _this = this; - switch (this.state) { - case transaction_state_1.TransactionState.Proceeding: - // If a request retransmission is received while in the "Proceeding" state, the most - // recent provisional response that was received from the TU MUST be passed to the - // transport layer for retransmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (request.method === messages_1.C.INVITE) { - if (this.lastProvisionalResponse) { - this.send(this.lastProvisionalResponse).catch(function (error) { - _this.logTransportError(error, "Failed to send retransmission of provisional response."); - }); - } - return; - } - break; - case transaction_state_1.TransactionState.Accepted: - // While in the "Accepted" state, any retransmissions of the INVITE - // received will match this transaction state machine and will be - // absorbed by the machine without changing its state. These - // retransmissions are not passed onto the TU. - // https://tools.ietf.org/html/rfc6026#section-7.1 - if (request.method === messages_1.C.INVITE) { - return; - } - break; - case transaction_state_1.TransactionState.Completed: - // Furthermore, while in the "Completed" state, if a request retransmission is - // received, the server SHOULD pass the response to the transport for retransmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (request.method === messages_1.C.INVITE) { - if (!this.lastFinalResponse) { - throw new Error("Last final response undefined."); - } - this.send(this.lastFinalResponse).catch(function (error) { - _this.logTransportError(error, "Failed to send retransmission of final response."); - }); - return; - } - // If an ACK is received while the server transaction is in the "Completed" state, - // the server transaction MUST transition to the "Confirmed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (request.method === messages_1.C.ACK) { - this.stateTransition(transaction_state_1.TransactionState.Confirmed); - return; - } - break; - case transaction_state_1.TransactionState.Confirmed: - // The purpose of the "Confirmed" state is to absorb any additional ACK messages that arrive, - // triggered from retransmissions of the final response. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (request.method === messages_1.C.INVITE || request.method === messages_1.C.ACK) { - return; - } - break; - case transaction_state_1.TransactionState.Terminated: - // For good measure absorb any additional messages that arrive (should not happen). - if (request.method === messages_1.C.INVITE || request.method === messages_1.C.ACK) { - return; - } - break; - default: - throw new Error("Invalid state " + this.state); - } - var message = "INVITE server transaction received unexpected " + request.method + " request while in state " + this.state + "."; - this.logger.warn(message); - return; - }; - /** - * Receive responses from TU for this transaction. - * @param statusCode - Status code of response. - * @param response - Response. - */ - InviteServerTransaction.prototype.receiveResponse = function (statusCode, response) { - var _this = this; - if (statusCode < 100 || statusCode > 699) { - throw new Error("Invalid status code " + statusCode); - } - switch (this.state) { - case transaction_state_1.TransactionState.Proceeding: - // The TU passes any number of provisional responses to the server - // transaction. So long as the server transaction is in the - // "Proceeding" state, each of these MUST be passed to the transport - // layer for transmission. They are not sent reliably by the - // transaction layer (they are not retransmitted by it) and do not cause - // a change in the state of the server transaction. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (statusCode >= 100 && statusCode <= 199) { - this.lastProvisionalResponse = response; - // Start the progress extension timer only for a non-100 provisional response. - if (statusCode > 100) { - this.startProgressExtensionTimer(); // FIXME: remove - } - this.send(response).catch(function (error) { - _this.logTransportError(error, "Failed to send 1xx response."); - }); - return; - } - // If, while in the "Proceeding" state, the TU passes a 2xx response - // to the server transaction, the server transaction MUST pass this - // response to the transport layer for transmission. It is not - // retransmitted by the server transaction; retransmissions of 2xx - // responses are handled by the TU. The server transaction MUST then - // transition to the "Accepted" state. - // https://tools.ietf.org/html/rfc6026#section-8.5 - if (statusCode >= 200 && statusCode <= 299) { - this.lastFinalResponse = response; - this.stateTransition(transaction_state_1.TransactionState.Accepted); - this.send(response).catch(function (error) { - _this.logTransportError(error, "Failed to send 2xx response."); - }); - return; - } - // While in the "Proceeding" state, if the TU passes a response with - // status code from 300 to 699 to the server transaction, the response - // MUST be passed to the transport layer for transmission, and the state - // machine MUST enter the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (statusCode >= 300 && statusCode <= 699) { - this.lastFinalResponse = response; - this.stateTransition(transaction_state_1.TransactionState.Completed); - this.send(response).catch(function (error) { - _this.logTransportError(error, "Failed to send non-2xx final response."); - }); - return; - } - break; - case transaction_state_1.TransactionState.Accepted: - // While in the "Accepted" state, if the TU passes a 2xx response, - // the server transaction MUST pass the response to the transport layer for transmission. - // https://tools.ietf.org/html/rfc6026#section-8.7 - if (statusCode >= 200 && statusCode <= 299) { - this.send(response).catch(function (error) { - _this.logTransportError(error, "Failed to send 2xx response."); - }); - return; - } - break; - case transaction_state_1.TransactionState.Completed: - break; - case transaction_state_1.TransactionState.Confirmed: - break; - case transaction_state_1.TransactionState.Terminated: - break; - default: - throw new Error("Invalid state " + this.state); - } - var message = "INVITE server transaction received unexpected " + statusCode + " response from TU while in state " + this.state + "."; - this.logger.error(message); - throw new Error(message); - }; - /** - * Retransmit the last 2xx response. This is a noop if not in the "accepted" state. - */ - InviteServerTransaction.prototype.retransmitAcceptedResponse = function () { - var _this = this; - if (this.state === transaction_state_1.TransactionState.Accepted && this.lastFinalResponse) { - this.send(this.lastFinalResponse).catch(function (error) { - _this.logTransportError(error, "Failed to send 2xx response."); - }); - } - }; - /** - * First, the procedures in [4] are followed, which attempt to deliver the response to a backup. - * If those should all fail, based on the definition of failure in [4], the server transaction SHOULD - * inform the TU that a failure has occurred, and MUST remain in the current state. - * https://tools.ietf.org/html/rfc6026#section-8.8 - */ - InviteServerTransaction.prototype.onTransportError = function (error) { - if (this.user.onTransportError) { - this.user.onTransportError(error); - } - }; - /** For logging. */ - InviteServerTransaction.prototype.typeToString = function () { - return "INVITE server transaction"; - }; - /** - * Execute a state transition. - * @param newState - New state. - */ - InviteServerTransaction.prototype.stateTransition = function (newState) { - var _this = this; - // Assert valid state transitions. - var invalidStateTransition = function () { - throw new Error("Invalid state transition from " + _this.state + " to " + newState); - }; - switch (newState) { - case transaction_state_1.TransactionState.Proceeding: - invalidStateTransition(); - break; - case transaction_state_1.TransactionState.Accepted: - case transaction_state_1.TransactionState.Completed: - if (this.state !== transaction_state_1.TransactionState.Proceeding) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Confirmed: - if (this.state !== transaction_state_1.TransactionState.Completed) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Terminated: - if (this.state !== transaction_state_1.TransactionState.Accepted && - this.state !== transaction_state_1.TransactionState.Completed && - this.state !== transaction_state_1.TransactionState.Confirmed) { - invalidStateTransition(); - } - break; - default: - invalidStateTransition(); - } - // On any state transition, stop resending provisonal responses - this.stopProgressExtensionTimer(); - // The purpose of the "Accepted" state is to absorb retransmissions of an accepted INVITE request. - // Any such retransmissions are absorbed entirely within the server transaction. - // They are not passed up to the TU since any downstream UAS cores that accepted the request have - // taken responsibility for reliability and will already retransmit their 2xx responses if necessary. - // https://tools.ietf.org/html/rfc6026#section-8.7 - if (newState === transaction_state_1.TransactionState.Accepted) { - this.L = setTimeout(function () { return _this.timer_L(); }, timers_1.Timers.TIMER_L); - } - // When the "Completed" state is entered, timer H MUST be set to fire in 64*T1 seconds for all transports. - // Timer H determines when the server transaction abandons retransmitting the response. - // If an ACK is received while the server transaction is in the "Completed" state, - // the server transaction MUST transition to the "Confirmed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (newState === transaction_state_1.TransactionState.Completed) { - // FIXME: Missing timer G for unreliable transports. - this.H = setTimeout(function () { return _this.timer_H(); }, timers_1.Timers.TIMER_H); - } - // The purpose of the "Confirmed" state is to absorb any additional ACK messages that arrive, - // triggered from retransmissions of the final response. When this state is entered, timer I - // is set to fire in T4 seconds for unreliable transports, and zero seconds for reliable - // transports. Once timer I fires, the server MUST transition to the "Terminated" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (newState === transaction_state_1.TransactionState.Confirmed) { - // FIXME: This timer is not getting set correctly for unreliable transports. - this.I = setTimeout(function () { return _this.timer_I(); }, timers_1.Timers.TIMER_I); - } - // Once the transaction is in the "Terminated" state, it MUST be destroyed immediately. - // https://tools.ietf.org/html/rfc6026#section-8.7 - if (newState === transaction_state_1.TransactionState.Terminated) { - this.dispose(); - } - // Update state. - this.setState(newState); - }; - /** - * FIXME: UAS Provisional Retransmission Timer. See RFC 3261 Section 13.3.1.1 - * This is in the wrong place. This is not a transaction level thing. It's a UAS level thing. - */ - InviteServerTransaction.prototype.startProgressExtensionTimer = function () { - var _this = this; - // Start the progress extension timer only for the first non-100 provisional response. - if (this.progressExtensionTimer === undefined) { - this.progressExtensionTimer = setInterval(function () { - _this.logger.debug("Progress extension timer expired for INVITE server transaction " + _this.id + "."); - if (!_this.lastProvisionalResponse) { - throw new Error("Last provisional response undefined."); - } - _this.send(_this.lastProvisionalResponse).catch(function (error) { - _this.logTransportError(error, "Failed to send retransmission of provisional response."); - }); - }, timers_1.Timers.PROVISIONAL_RESPONSE_INTERVAL); - } - }; - /** - * FIXME: UAS Provisional Retransmission Timer id. See RFC 3261 Section 13.3.1.1 - * This is in the wrong place. This is not a transaction level thing. It's a UAS level thing. - */ - InviteServerTransaction.prototype.stopProgressExtensionTimer = function () { - if (this.progressExtensionTimer !== undefined) { - clearInterval(this.progressExtensionTimer); - this.progressExtensionTimer = undefined; - } - }; - /** - * While in the "Proceeding" state, if the TU passes a response with status code - * from 300 to 699 to the server transaction, the response MUST be passed to the - * transport layer for transmission, and the state machine MUST enter the "Completed" state. - * For unreliable transports, timer G is set to fire in T1 seconds, and is not set to fire for - * reliable transports. If timer G fires, the response is passed to the transport layer once - * more for retransmission, and timer G is set to fire in MIN(2*T1, T2) seconds. From then on, - * when timer G fires, the response is passed to the transport again for transmission, and - * timer G is reset with a value that doubles, unless that value exceeds T2, in which case - * it is reset with the value of T2. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - */ - InviteServerTransaction.prototype.timer_G = function () { - // TODO - }; - /** - * If timer H fires while in the "Completed" state, it implies that the ACK was never received. - * In this case, the server transaction MUST transition to the "Terminated" state, and MUST - * indicate to the TU that a transaction failure has occurred. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - */ - InviteServerTransaction.prototype.timer_H = function () { - this.logger.debug("Timer H expired for INVITE server transaction " + this.id + "."); - if (this.state === transaction_state_1.TransactionState.Completed) { - this.logger.warn("ACK to negative final response was never received, terminating transaction."); - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - /** - * Once timer I fires, the server MUST transition to the "Terminated" state. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - */ - InviteServerTransaction.prototype.timer_I = function () { - this.logger.debug("Timer I expired for INVITE server transaction " + this.id + "."); - this.stateTransition(transaction_state_1.TransactionState.Terminated); - }; - /** - * When Timer L fires and the state machine is in the "Accepted" state, the machine MUST - * transition to the "Terminated" state. Once the transaction is in the "Terminated" state, - * it MUST be destroyed immediately. Timer L reflects the amount of time the server - * transaction could receive 2xx responses for retransmission from the - * TU while it is waiting to receive an ACK. - * https://tools.ietf.org/html/rfc6026#section-7.1 - * https://tools.ietf.org/html/rfc6026#section-8.7 - */ - InviteServerTransaction.prototype.timer_L = function () { - this.logger.debug("Timer L expired for INVITE server transaction " + this.id + "."); - if (this.state === transaction_state_1.TransactionState.Accepted) { - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - return InviteServerTransaction; -}(server_transaction_1.ServerTransaction)); -exports.InviteServerTransaction = InviteServerTransaction; - - -/***/ }), -/* 38 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transaction_1 = __webpack_require__(29); -/** - * Server Transaction. - * @remarks - * The server transaction is responsible for the delivery of requests to - * the TU and the reliable transmission of responses. It accomplishes - * this through a state machine. Server transactions are created by the - * core when a request is received, and transaction handling is desired - * for that request (this is not always the case). - * https://tools.ietf.org/html/rfc3261#section-17.2 - * @public - */ -var ServerTransaction = /** @class */ (function (_super) { - tslib_1.__extends(ServerTransaction, _super); - function ServerTransaction(_request, transport, user, state, loggerCategory) { - var _this = _super.call(this, transport, user, _request.viaBranch, state, loggerCategory) || this; - _this._request = _request; - _this.user = user; - return _this; - } - Object.defineProperty(ServerTransaction.prototype, "request", { - /** The incoming request the transaction handling. */ - get: function () { - return this._request; - }, - enumerable: true, - configurable: true - }); - return ServerTransaction; -}(transaction_1.Transaction)); -exports.ServerTransaction = ServerTransaction; - - -/***/ }), -/* 39 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var timers_1 = __webpack_require__(26); -var client_transaction_1 = __webpack_require__(28); -var transaction_state_1 = __webpack_require__(36); -/** - * Non-INVITE Client Transaction. - * @remarks - * Non-INVITE transactions do not make use of ACK. - * They are simple request-response interactions. - * https://tools.ietf.org/html/rfc3261#section-17.1.2 - * @public - */ -var NonInviteClientTransaction = /** @class */ (function (_super) { - tslib_1.__extends(NonInviteClientTransaction, _super); - /** - * Constructor - * Upon construction, the outgoing request's Via header is updated by calling `setViaHeader`. - * Then `toString` is called on the outgoing request and the message is sent via the transport. - * After construction the transaction will be in the "calling" state and the transaction id - * will equal the branch parameter set in the Via header of the outgoing request. - * https://tools.ietf.org/html/rfc3261#section-17.1.2 - * @param request - The outgoing Non-INVITE request. - * @param transport - The transport. - * @param user - The transaction user. - */ - function NonInviteClientTransaction(request, transport, user) { - var _this = _super.call(this, request, transport, user, transaction_state_1.TransactionState.Trying, "sip.transaction.nict") || this; - // FIXME: Timer E for unreliable transports not implemented. - // - // The "Trying" state is entered when the TU initiates a new client - // transaction with a request. When entering this state, the client - // transaction SHOULD set timer F to fire in 64*T1 seconds. The request - // MUST be passed to the transport layer for transmission. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - _this.F = setTimeout(function () { return _this.timer_F(); }, timers_1.Timers.TIMER_F); - _this.send(request.toString()).catch(function (error) { - _this.logTransportError(error, "Failed to send initial outgoing request."); - }); - return _this; - } - /** - * Destructor. - */ - NonInviteClientTransaction.prototype.dispose = function () { - if (this.F) { - clearTimeout(this.F); - this.F = undefined; - } - if (this.K) { - clearTimeout(this.K); - this.K = undefined; - } - _super.prototype.dispose.call(this); - }; - Object.defineProperty(NonInviteClientTransaction.prototype, "kind", { - /** Transaction kind. Deprecated. */ - get: function () { - return "nict"; - }, - enumerable: true, - configurable: true - }); - /** - * Handler for incoming responses from the transport which match this transaction. - * @param response - The incoming response. - */ - NonInviteClientTransaction.prototype.receiveResponse = function (response) { - var statusCode = response.statusCode; - if (!statusCode || statusCode < 100 || statusCode > 699) { - throw new Error("Invalid status code " + statusCode); - } - switch (this.state) { - case transaction_state_1.TransactionState.Trying: - // If a provisional response is received while in the "Trying" state, the - // response MUST be passed to the TU, and then the client transaction - // SHOULD move to the "Proceeding" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (statusCode >= 100 && statusCode <= 199) { - this.stateTransition(transaction_state_1.TransactionState.Proceeding); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // If a final response (status codes 200-699) is received while in the - // "Trying" state, the response MUST be passed to the TU, and the - // client transaction MUST transition to the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (statusCode >= 200 && statusCode <= 699) { - this.stateTransition(transaction_state_1.TransactionState.Completed); - if (statusCode === 408) { - this.onRequestTimeout(); - return; - } - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - break; - case transaction_state_1.TransactionState.Proceeding: - // If a provisional response is received while in the "Proceeding" state, - // the response MUST be passed to the TU. (From Figure 6) - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (statusCode >= 100 && statusCode <= 199) { - if (this.user.receiveResponse) { - return this.user.receiveResponse(response); - } - } - // If a final response (status codes 200-699) is received while in the - // "Proceeding" state, the response MUST be passed to the TU, and the - // client transaction MUST transition to the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (statusCode >= 200 && statusCode <= 699) { - this.stateTransition(transaction_state_1.TransactionState.Completed); - if (statusCode === 408) { - this.onRequestTimeout(); - return; - } - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - case transaction_state_1.TransactionState.Completed: - // The "Completed" state exists to buffer any additional response - // retransmissions that may be received (which is why the client - // transaction remains there only for unreliable transports). - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - return; - case transaction_state_1.TransactionState.Terminated: - // For good measure just absorb additional response retransmissions. - return; - default: - throw new Error("Invalid state " + this.state); - } - var message = "Non-INVITE client transaction received unexpected " + statusCode + " response while in state " + this.state + "."; - this.logger.warn(message); - return; - }; - /** - * The client transaction SHOULD inform the TU that a transport failure has occurred, - * and the client transaction SHOULD transition directly to the "Terminated" state. - * The TU will handle the failover mechanisms described in [4]. - * https://tools.ietf.org/html/rfc3261#section-17.1.4 - * @param error - Trasnsport error - */ - NonInviteClientTransaction.prototype.onTransportError = function (error) { - if (this.user.onTransportError) { - this.user.onTransportError(error); - } - this.stateTransition(transaction_state_1.TransactionState.Terminated, true); - }; - /** For logging. */ - NonInviteClientTransaction.prototype.typeToString = function () { - return "non-INVITE client transaction"; - }; - /** - * Execute a state transition. - * @param newState - New state. - */ - NonInviteClientTransaction.prototype.stateTransition = function (newState, dueToTransportError) { - var _this = this; - if (dueToTransportError === void 0) { dueToTransportError = false; } - // Assert valid state transitions. - var invalidStateTransition = function () { - throw new Error("Invalid state transition from " + _this.state + " to " + newState); - }; - switch (newState) { - case transaction_state_1.TransactionState.Trying: - invalidStateTransition(); - break; - case transaction_state_1.TransactionState.Proceeding: - if (this.state !== transaction_state_1.TransactionState.Trying) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Completed: - if (this.state !== transaction_state_1.TransactionState.Trying && - this.state !== transaction_state_1.TransactionState.Proceeding) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Terminated: - if (this.state !== transaction_state_1.TransactionState.Trying && - this.state !== transaction_state_1.TransactionState.Proceeding && - this.state !== transaction_state_1.TransactionState.Completed) { - if (!dueToTransportError) { - invalidStateTransition(); - } - } - break; - default: - invalidStateTransition(); - } - // Once the client transaction enters the "Completed" state, it MUST set - // Timer K to fire in T4 seconds for unreliable transports, and zero - // seconds for reliable transports The "Completed" state exists to - // buffer any additional response retransmissions that may be received - // (which is why the client transaction remains there only for unreliable transports). - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (newState === transaction_state_1.TransactionState.Completed) { - if (this.F) { - clearTimeout(this.F); - this.F = undefined; - } - this.K = setTimeout(function () { return _this.timer_K(); }, timers_1.Timers.TIMER_K); - } - // Once the transaction is in the terminated state, it MUST be destroyed immediately. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (newState === transaction_state_1.TransactionState.Terminated) { - this.dispose(); - } - // Update state. - this.setState(newState); - }; - /** - * If Timer F fires while the client transaction is still in the - * "Trying" state, the client transaction SHOULD inform the TU about the - * timeout, and then it SHOULD enter the "Terminated" state. - * If timer F fires while in the "Proceeding" state, the TU MUST be informed of - * a timeout, and the client transaction MUST transition to the terminated state. - * https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - */ - NonInviteClientTransaction.prototype.timer_F = function () { - this.logger.debug("Timer F expired for non-INVITE client transaction " + this.id + "."); - if (this.state === transaction_state_1.TransactionState.Trying || this.state === transaction_state_1.TransactionState.Proceeding) { - this.onRequestTimeout(); - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - /** - * If Timer K fires while in this (COMPLETED) state, the client transaction - * MUST transition to the "Terminated" state. - * https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - */ - NonInviteClientTransaction.prototype.timer_K = function () { - if (this.state === transaction_state_1.TransactionState.Completed) { - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - return NonInviteClientTransaction; -}(client_transaction_1.ClientTransaction)); -exports.NonInviteClientTransaction = NonInviteClientTransaction; - - -/***/ }), -/* 40 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var timers_1 = __webpack_require__(26); -var server_transaction_1 = __webpack_require__(38); -var transaction_state_1 = __webpack_require__(36); -/** - * Non-INVITE Server Transaction. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-17.2.2 - * @public - */ -var NonInviteServerTransaction = /** @class */ (function (_super) { - tslib_1.__extends(NonInviteServerTransaction, _super); - /** - * Constructor. - * After construction the transaction will be in the "trying": state and the transaction - * `id` will equal the branch parameter set in the Via header of the incoming request. - * https://tools.ietf.org/html/rfc3261#section-17.2.2 - * @param request - Incoming Non-INVITE request from the transport. - * @param transport - The transport. - * @param user - The transaction user. - */ - function NonInviteServerTransaction(request, transport, user) { - return _super.call(this, request, transport, user, transaction_state_1.TransactionState.Trying, "sip.transaction.nist") || this; - } - /** - * Destructor. - */ - NonInviteServerTransaction.prototype.dispose = function () { - if (this.J) { - clearTimeout(this.J); - this.J = undefined; - } - _super.prototype.dispose.call(this); - }; - Object.defineProperty(NonInviteServerTransaction.prototype, "kind", { - /** Transaction kind. Deprecated. */ - get: function () { - return "nist"; - }, - enumerable: true, - configurable: true - }); - /** - * Receive requests from transport matching this transaction. - * @param request - Request matching this transaction. - */ - NonInviteServerTransaction.prototype.receiveRequest = function (request) { - var _this = this; - switch (this.state) { - case transaction_state_1.TransactionState.Trying: - // Once in the "Trying" state, any further request retransmissions are discarded. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - break; - case transaction_state_1.TransactionState.Proceeding: - // If a retransmission of the request is received while in the "Proceeding" state, - // the most recently sent provisional response MUST be passed to the transport layer for retransmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - if (!this.lastResponse) { - throw new Error("Last response undefined."); - } - this.send(this.lastResponse).catch(function (error) { - _this.logTransportError(error, "Failed to send retransmission of provisional response."); - }); - break; - case transaction_state_1.TransactionState.Completed: - // While in the "Completed" state, the server transaction MUST pass the final response to the transport - // layer for retransmission whenever a retransmission of the request is received. Any other final responses - // passed by the TU to the server transaction MUST be discarded while in the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - if (!this.lastResponse) { - throw new Error("Last response undefined."); - } - this.send(this.lastResponse).catch(function (error) { - _this.logTransportError(error, "Failed to send retransmission of final response."); - }); - break; - case transaction_state_1.TransactionState.Terminated: - break; - default: - throw new Error("Invalid state " + this.state); - } - }; - /** - * Receive responses from TU for this transaction. - * @param statusCode - Status code of repsonse. 101-199 not allowed per RFC 4320. - * @param response - Response to send. - */ - NonInviteServerTransaction.prototype.receiveResponse = function (statusCode, response) { - var _this = this; - if (statusCode < 100 || statusCode > 699) { - throw new Error("Invalid status code " + statusCode); - } - // An SIP element MUST NOT send any provisional response with a - // Status-Code other than 100 to a non-INVITE request. - // An SIP element MUST NOT respond to a non-INVITE request with a - // Status-Code of 100 over any unreliable transport, such as UDP, - // before the amount of time it takes a client transaction's Timer E to be reset to T2. - // An SIP element MAY respond to a non-INVITE request with a - // Status-Code of 100 over a reliable transport at any time. - // https://tools.ietf.org/html/rfc4320#section-4.1 - if (statusCode > 100 && statusCode <= 199) { - throw new Error("Provisional response other than 100 not allowed."); - } - switch (this.state) { - case transaction_state_1.TransactionState.Trying: - // While in the "Trying" state, if the TU passes a provisional response - // to the server transaction, the server transaction MUST enter the "Proceeding" state. - // The response MUST be passed to the transport layer for transmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - this.lastResponse = response; - if (statusCode >= 100 && statusCode < 200) { - this.stateTransition(transaction_state_1.TransactionState.Proceeding); - this.send(response).catch(function (error) { - _this.logTransportError(error, "Failed to send provisional response."); - }); - return; - } - if (statusCode >= 200 && statusCode <= 699) { - this.stateTransition(transaction_state_1.TransactionState.Completed); - this.send(response).catch(function (error) { - _this.logTransportError(error, "Failed to send final response."); - }); - return; - } - break; - case transaction_state_1.TransactionState.Proceeding: - // Any further provisional responses that are received from the TU while - // in the "Proceeding" state MUST be passed to the transport layer for transmission. - // If the TU passes a final response (status codes 200-699) to the server while in - // the "Proceeding" state, the transaction MUST enter the "Completed" state, and - // the response MUST be passed to the transport layer for transmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - this.lastResponse = response; - if (statusCode >= 200 && statusCode <= 699) { - this.stateTransition(transaction_state_1.TransactionState.Completed); - this.send(response).catch(function (error) { - _this.logTransportError(error, "Failed to send final response."); - }); - return; - } - break; - case transaction_state_1.TransactionState.Completed: - // Any other final responses passed by the TU to the server - // transaction MUST be discarded while in the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - return; - case transaction_state_1.TransactionState.Terminated: - break; - default: - throw new Error("Invalid state " + this.state); - } - var message = "Non-INVITE server transaction received unexpected " + statusCode + " response from TU while in state " + this.state + "."; - this.logger.error(message); - throw new Error(message); - }; - /** - * First, the procedures in [4] are followed, which attempt to deliver the response to a backup. - * If those should all fail, based on the definition of failure in [4], the server transaction SHOULD - * inform the TU that a failure has occurred, and SHOULD transition to the terminated state. - * https://tools.ietf.org/html/rfc3261#section-17.2.4 - */ - NonInviteServerTransaction.prototype.onTransportError = function (error) { - if (this.user.onTransportError) { - this.user.onTransportError(error); - } - this.stateTransition(transaction_state_1.TransactionState.Terminated, true); - }; - /** For logging. */ - NonInviteServerTransaction.prototype.typeToString = function () { - return "non-INVITE server transaction"; - }; - NonInviteServerTransaction.prototype.stateTransition = function (newState, dueToTransportError) { - var _this = this; - if (dueToTransportError === void 0) { dueToTransportError = false; } - // Assert valid state transitions. - var invalidStateTransition = function () { - throw new Error("Invalid state transition from " + _this.state + " to " + newState); - }; - switch (newState) { - case transaction_state_1.TransactionState.Trying: - invalidStateTransition(); - break; - case transaction_state_1.TransactionState.Proceeding: - if (this.state !== transaction_state_1.TransactionState.Trying) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Completed: - if (this.state !== transaction_state_1.TransactionState.Trying && this.state !== transaction_state_1.TransactionState.Proceeding) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Terminated: - if (this.state !== transaction_state_1.TransactionState.Proceeding && this.state !== transaction_state_1.TransactionState.Completed) { - if (!dueToTransportError) { - invalidStateTransition(); - } - } - break; - default: - invalidStateTransition(); - } - // When the server transaction enters the "Completed" state, it MUST set Timer J to fire - // in 64*T1 seconds for unreliable transports, and zero seconds for reliable transports. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - if (newState === transaction_state_1.TransactionState.Completed) { - this.J = setTimeout(function () { return _this.timer_J(); }, timers_1.Timers.TIMER_J); - } - // The server transaction MUST be destroyed the instant it enters the "Terminated" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - if (newState === transaction_state_1.TransactionState.Terminated) { - this.dispose(); - } - this.setState(newState); - }; - /** - * The server transaction remains in this state until Timer J fires, - * at which point it MUST transition to the "Terminated" state. - * https://tools.ietf.org/html/rfc3261#section-17.2.2 - */ - NonInviteServerTransaction.prototype.timer_J = function () { - this.logger.debug("Timer J expired for NON-INVITE server transaction " + this.id + "."); - if (this.state === transaction_state_1.TransactionState.Completed) { - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - return NonInviteServerTransaction; -}(server_transaction_1.ServerTransaction)); -exports.NonInviteServerTransaction = NonInviteServerTransaction; - - -/***/ }), -/* 41 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * BYE UAC. - * @public - */ -var ByeUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(ByeUserAgentClient, _super); - function ByeUserAgentClient(dialog, delegate, options) { - var _this = this; - var message = dialog.createOutgoingRequestMessage(messages_1.C.BYE, options); - _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; - dialog.dispose(); - return _this; - } - return ByeUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.ByeUserAgentClient = ByeUserAgentClient; - - -/***/ }), -/* 42 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var messages_1 = __webpack_require__(5); -var transactions_1 = __webpack_require__(27); -/** - * User Agent Client (UAC). - * @remarks - * A user agent client is a logical entity - * that creates a new request, and then uses the client - * transaction state machinery to send it. The role of UAC lasts - * only for the duration of that transaction. In other words, if - * a piece of software initiates a request, it acts as a UAC for - * the duration of that transaction. If it receives a request - * later, it assumes the role of a user agent server for the - * processing of that transaction. - * https://tools.ietf.org/html/rfc3261#section-6 - * @public - */ -var UserAgentClient = /** @class */ (function () { - function UserAgentClient(transactionConstructor, core, message, delegate) { - this.transactionConstructor = transactionConstructor; - this.core = core; - this.message = message; - this.delegate = delegate; - this.challenged = false; - this.stale = false; - this.logger = this.loggerFactory.getLogger("sip.user-agent-client"); - this.init(); - } - UserAgentClient.prototype.dispose = function () { - this.transaction.dispose(); - }; - Object.defineProperty(UserAgentClient.prototype, "loggerFactory", { - get: function () { - return this.core.loggerFactory; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(UserAgentClient.prototype, "transaction", { - /** The transaction associated with this request. */ - get: function () { - if (!this._transaction) { - throw new Error("Transaction undefined."); - } - return this._transaction; - }, - enumerable: true, - configurable: true - }); - /** - * Since requests other than INVITE are responded to immediately, sending a - * CANCEL for a non-INVITE request would always create a race condition. - * A CANCEL request SHOULD NOT be sent to cancel a request other than INVITE. - * https://tools.ietf.org/html/rfc3261#section-9.1 - * @param options - Cancel options bucket. - */ - UserAgentClient.prototype.cancel = function (reason, options) { - var _this = this; - if (options === void 0) { options = {}; } - if (!this.transaction) { - throw new Error("Transaction undefined."); - } - if (!this.message.to) { - throw new Error("To undefined."); - } - if (!this.message.from) { - throw new Error("From undefined."); - } - // The following procedures are used to construct a CANCEL request. The - // Request-URI, Call-ID, To, the numeric part of CSeq, and From header - // fields in the CANCEL request MUST be identical to those in the - // request being cancelled, including tags. A CANCEL constructed by a - // client MUST have only a single Via header field value matching the - // top Via value in the request being cancelled. Using the same values - // for these header fields allows the CANCEL to be matched with the - // request it cancels (Section 9.2 indicates how such matching occurs). - // However, the method part of the CSeq header field MUST have a value - // of CANCEL. This allows it to be identified and processed as a - // transaction in its own right (See Section 17). - // https://tools.ietf.org/html/rfc3261#section-9.1 - var message = this.core.makeOutgoingRequestMessage(messages_1.C.CANCEL, this.message.ruri, this.message.from.uri, this.message.to.uri, { - toTag: this.message.toTag, - fromTag: this.message.fromTag, - callId: this.message.callId, - cseq: this.message.cseq - }, options.extraHeaders); - // TODO: Revisit this. - // The CANCEL needs to use the same branch parameter so that - // it matches the INVITE transaction, but this is a hacky way to do this. - // Or at the very least not well documented. If the the branch parameter - // is set on the outgoing request, the transaction will use it. - // Otherwise the transaction will make a new one. - message.branch = this.message.branch; - if (this.message.headers.Route) { - message.headers.Route = this.message.headers.Route; - } - if (reason) { - message.setHeader("Reason", reason); - } - // If no provisional response has been received, the CANCEL request MUST - // NOT be sent; rather, the client MUST wait for the arrival of a - // provisional response before sending the request. If the original - // request has generated a final response, the CANCEL SHOULD NOT be - // sent, as it is an effective no-op, since CANCEL has no effect on - // requests that have already generated a final response. - // https://tools.ietf.org/html/rfc3261#section-9.1 - if (this.transaction.state === transactions_1.TransactionState.Proceeding) { - var uac = new UserAgentClient(transactions_1.NonInviteClientTransaction, this.core, message); - } - else { - this.transaction.once("stateChanged", function () { - if (_this.transaction && _this.transaction.state === transactions_1.TransactionState.Proceeding) { - var uac = new UserAgentClient(transactions_1.NonInviteClientTransaction, _this.core, message); - } - }); - } - return message; - }; - /** - * If a 401 (Unauthorized) or 407 (Proxy Authentication Required) - * response is received, the UAC SHOULD follow the authorization - * procedures of Section 22.2 and Section 22.3 to retry the request with - * credentials. - * https://tools.ietf.org/html/rfc3261#section-8.1.3.5 - * 22 Usage of HTTP Authentication - * https://tools.ietf.org/html/rfc3261#section-22 - * 22.1 Framework - * https://tools.ietf.org/html/rfc3261#section-22.1 - * 22.2 User-to-User Authentication - * https://tools.ietf.org/html/rfc3261#section-22.2 - * 22.3 Proxy-to-User Authentication - * https://tools.ietf.org/html/rfc3261#section-22.3 - * - * FIXME: This "guard for and retry the request with credentials" - * implementation is not complete and at best minimally passable. - * @param response - The incoming response to guard. - * @returns True if the program execution is to continue in the branch in question. - * Otherwise the request is retried with credentials and current request processing must stop. - */ - UserAgentClient.prototype.authenticationGuard = function (message) { - var statusCode = message.statusCode; - if (!statusCode) { - throw new Error("Response status code undefined."); - } - // If a 401 (Unauthorized) or 407 (Proxy Authentication Required) - // response is received, the UAC SHOULD follow the authorization - // procedures of Section 22.2 and Section 22.3 to retry the request with - // credentials. - // https://tools.ietf.org/html/rfc3261#section-8.1.3.5 - if (statusCode !== 401 && statusCode !== 407) { - return true; - } - // Get and parse the appropriate WWW-Authenticate or Proxy-Authenticate header. - var challenge; - var authorizationHeaderName; - if (statusCode === 401) { - challenge = message.parseHeader("www-authenticate"); - authorizationHeaderName = "authorization"; - } - else { - challenge = message.parseHeader("proxy-authenticate"); - authorizationHeaderName = "proxy-authorization"; - } - // Verify it seems a valid challenge. - if (!challenge) { - this.logger.warn(statusCode + " with wrong or missing challenge, cannot authenticate"); - return true; - } - // Avoid infinite authentications. - if (this.challenged && (this.stale || challenge.stale !== true)) { - this.logger.warn(statusCode + " apparently in authentication loop, cannot authenticate"); - return true; - } - // Get credentials. - if (!this.credentials) { - this.credentials = this.core.configuration.authenticationFactory(); - if (!this.credentials) { - this.logger.warn("Unable to obtain credentials, cannot authenticate"); - return true; - } - } - // Verify that the challenge is really valid. - if (!this.credentials.authenticate(this.message, challenge)) { - return true; - } - this.challenged = true; - if (challenge.stale) { - this.stale = true; - } - var cseq = this.message.cseq += 1; - this.message.setHeader("cseq", cseq + " " + this.message.method); - this.message.setHeader(authorizationHeaderName, this.credentials.toString()); - // Calling init (again) will swap out our existing client transaction with a new one. - // FIXME: HACK: An assumption is being made here that there is nothing that needs to - // be cleaned up beyond the client transaction which is being replaced. For example, - // it is assumed that no early dialogs have been created. - this.init(); - return false; - }; - /** - * Receive a response from the transaction layer. - * @param message - Incoming response message. - */ - UserAgentClient.prototype.receiveResponse = function (message) { - if (!this.authenticationGuard(message)) { - return; - } - var statusCode = message.statusCode ? message.statusCode.toString() : ""; - if (!statusCode) { - throw new Error("Response status code undefined."); - } - switch (true) { - case /^100$/.test(statusCode): - if (this.delegate && this.delegate.onTrying) { - this.delegate.onTrying({ message: message }); - } - break; - case /^1[0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onProgress) { - this.delegate.onProgress({ message: message }); - } - break; - case /^2[0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onAccept) { - this.delegate.onAccept({ message: message }); - } - break; - case /^3[0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onRedirect) { - this.delegate.onRedirect({ message: message }); - } - break; - case /^[4-6][0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onReject) { - this.delegate.onReject({ message: message }); - } - break; - default: - throw new Error("Invalid status code " + statusCode); - } - }; - UserAgentClient.prototype.init = function () { - var _this = this; - // We are the transaction user. - var user = { - loggerFactory: this.loggerFactory, - onRequestTimeout: function () { return _this.onRequestTimeout(); }, - onStateChange: function (newState) { - if (newState === transactions_1.TransactionState.Terminated) { - // Remove the terminated transaction from the core. - _this.core.userAgentClients.delete(userAgentClientId); - // FIXME: HACK: Our transaction may have been swapped out with a new one - // post authentication (see above), so make sure to only to dispose of - // ourselves if this terminating transaction is our current transaction. - if (transaction === _this._transaction) { - _this.dispose(); - } - } - }, - onTransportError: function (error) { return _this.onTransportError(error); }, - receiveResponse: function (message) { return _this.receiveResponse(message); } - }; - // Create a new transaction with us as the user. - var transaction = new this.transactionConstructor(this.message, this.core.transport, user); - this._transaction = transaction; - // Add the new transaction to the core. - var userAgentClientId = transaction.id + transaction.request.method; - this.core.userAgentClients.set(userAgentClientId, this); - }; - /** - * 8.1.3.1 Transaction Layer Errors - * In some cases, the response returned by the transaction layer will - * not be a SIP message, but rather a transaction layer error. When a - * timeout error is received from the transaction layer, it MUST be - * treated as if a 408 (Request Timeout) status code has been received. - * If a fatal transport error is reported by the transport layer - * (generally, due to fatal ICMP errors in UDP or connection failures in - * TCP), the condition MUST be treated as a 503 (Service Unavailable) - * status code. - * https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - */ - UserAgentClient.prototype.onRequestTimeout = function () { - this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout."); - var message = new messages_1.IncomingResponseMessage(); - message.statusCode = 408; - message.reasonPhrase = "Request Timeout"; - this.receiveResponse(message); - return; - }; - /** - * 8.1.3.1 Transaction Layer Errors - * In some cases, the response returned by the transaction layer will - * not be a SIP message, but rather a transaction layer error. When a - * timeout error is received from the transaction layer, it MUST be - * treated as if a 408 (Request Timeout) status code has been received. - * If a fatal transport error is reported by the transport layer - * (generally, due to fatal ICMP errors in UDP or connection failures in - * TCP), the condition MUST be treated as a 503 (Service Unavailable) - * status code. - * https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - */ - UserAgentClient.prototype.onTransportError = function (error) { - this.logger.error(error.message); - this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable."); - var message = new messages_1.IncomingResponseMessage(); - message.statusCode = 503; - message.reasonPhrase = "Service Unavailable"; - this.receiveResponse(message); - }; - return UserAgentClient; -}()); -exports.UserAgentClient = UserAgentClient; - - -/***/ }), -/* 43 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * BYE UAS. - * @public - */ -var ByeUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(ByeUserAgentServer, _super); - function ByeUserAgentServer(dialog, message, delegate) { - return _super.call(this, transactions_1.NonInviteServerTransaction, dialog.userAgentCore, message, delegate) || this; - } - return ByeUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.ByeUserAgentServer = ByeUserAgentServer; - - -/***/ }), -/* 44 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var exceptions_1 = __webpack_require__(31); -var messages_1 = __webpack_require__(5); -var utils_1 = __webpack_require__(16); -var transactions_1 = __webpack_require__(27); -/** - * User Agent Server (UAS). - * @remarks - * A user agent server is a logical entity - * that generates a response to a SIP request. The response - * accepts, rejects, or redirects the request. This role lasts - * only for the duration of that transaction. In other words, if - * a piece of software responds to a request, it acts as a UAS for - * the duration of that transaction. If it generates a request - * later, it assumes the role of a user agent client for the - * processing of that transaction. - * https://tools.ietf.org/html/rfc3261#section-6 - * @public - */ -var UserAgentServer = /** @class */ (function () { - function UserAgentServer(transactionConstructor, core, message, delegate) { - this.transactionConstructor = transactionConstructor; - this.core = core; - this.message = message; - this.delegate = delegate; - this.logger = this.loggerFactory.getLogger("sip.user-agent-server"); - this.toTag = message.toTag ? message.toTag : utils_1.newTag(); - this.init(); - } - UserAgentServer.prototype.dispose = function () { - this.transaction.dispose(); - }; - Object.defineProperty(UserAgentServer.prototype, "loggerFactory", { - get: function () { - return this.core.loggerFactory; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(UserAgentServer.prototype, "transaction", { - /** The transaction associated with this request. */ - get: function () { - if (!this._transaction) { - throw new Error("Transaction undefined."); - } - return this._transaction; - }, - enumerable: true, - configurable: true - }); - UserAgentServer.prototype.accept = function (options) { - if (options === void 0) { options = { statusCode: 200 }; } - if (!this.acceptable) { - throw new exceptions_1.TransactionStateError(this.message.method + " not acceptable in state " + this.transaction.state + "."); - } - var statusCode = options.statusCode; - if (statusCode < 200 || statusCode > 299) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - var response = this.reply(options); - return response; - }; - UserAgentServer.prototype.progress = function (options) { - if (options === void 0) { options = { statusCode: 180 }; } - if (!this.progressable) { - throw new exceptions_1.TransactionStateError(this.message.method + " not progressable in state " + this.transaction.state + "."); - } - var statusCode = options.statusCode; - if (statusCode < 101 || statusCode > 199) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - var response = this.reply(options); - return response; - }; - UserAgentServer.prototype.redirect = function (contacts, options) { - if (options === void 0) { options = { statusCode: 302 }; } - if (!this.redirectable) { - throw new exceptions_1.TransactionStateError(this.message.method + " not redirectable in state " + this.transaction.state + "."); - } - var statusCode = options.statusCode; - if (statusCode < 300 || statusCode > 399) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - var contactHeaders = new Array(); - contacts.forEach(function (contact) { return contactHeaders.push("Contact: " + contact.toString()); }); - options.extraHeaders = (options.extraHeaders || []).concat(contactHeaders); - var response = this.reply(options); - return response; - }; - UserAgentServer.prototype.reject = function (options) { - if (options === void 0) { options = { statusCode: 480 }; } - if (!this.rejectable) { - throw new exceptions_1.TransactionStateError(this.message.method + " not rejectable in state " + this.transaction.state + "."); - } - var statusCode = options.statusCode; - if (statusCode < 400 || statusCode > 699) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - var response = this.reply(options); - return response; - }; - UserAgentServer.prototype.trying = function (options) { - if (!this.tryingable) { - throw new exceptions_1.TransactionStateError(this.message.method + " not tryingable in state " + this.transaction.state + "."); - } - var response = this.reply({ statusCode: 100 }); - return response; - }; - /** - * If the UAS did not find a matching transaction for the CANCEL - * according to the procedure above, it SHOULD respond to the CANCEL - * with a 481 (Call Leg/Transaction Does Not Exist). If the transaction - * for the original request still exists, the behavior of the UAS on - * receiving a CANCEL request depends on whether it has already sent a - * final response for the original request. If it has, the CANCEL - * request has no effect on the processing of the original request, no - * effect on any session state, and no effect on the responses generated - * for the original request. If the UAS has not issued a final response - * for the original request, its behavior depends on the method of the - * original request. If the original request was an INVITE, the UAS - * SHOULD immediately respond to the INVITE with a 487 (Request - * Terminated). A CANCEL request has no impact on the processing of - * transactions with any other method defined in this specification. - * https://tools.ietf.org/html/rfc3261#section-9.2 - * @param request - Incoming CANCEL request. - */ - UserAgentServer.prototype.receiveCancel = function (message) { - // Note: Currently CANCEL is being handled as a special case. - // No UAS is created to handle the CANCEL and the response to - // it CANCEL is being handled statelessly by the user agent core. - // As such, there is currently no way to externally impact the - // response to the a CANCEL request. - if (this.delegate && this.delegate.onCancel) { - this.delegate.onCancel(message); - } - }; - Object.defineProperty(UserAgentServer.prototype, "acceptable", { - get: function () { - if (this.transaction instanceof transactions_1.InviteServerTransaction) { - return (this.transaction.state === transactions_1.TransactionState.Proceeding || - this.transaction.state === transactions_1.TransactionState.Accepted); - } - if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { - return (this.transaction.state === transactions_1.TransactionState.Trying || - this.transaction.state === transactions_1.TransactionState.Proceeding); - } - throw new Error("Unknown transaction type."); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(UserAgentServer.prototype, "progressable", { - get: function () { - if (this.transaction instanceof transactions_1.InviteServerTransaction) { - return this.transaction.state === transactions_1.TransactionState.Proceeding; - } - if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { - return false; // https://tools.ietf.org/html/rfc4320#section-4.1 - } - throw new Error("Unknown transaction type."); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(UserAgentServer.prototype, "redirectable", { - get: function () { - if (this.transaction instanceof transactions_1.InviteServerTransaction) { - return this.transaction.state === transactions_1.TransactionState.Proceeding; - } - if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { - return (this.transaction.state === transactions_1.TransactionState.Trying || - this.transaction.state === transactions_1.TransactionState.Proceeding); - } - throw new Error("Unknown transaction type."); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(UserAgentServer.prototype, "rejectable", { - get: function () { - if (this.transaction instanceof transactions_1.InviteServerTransaction) { - return this.transaction.state === transactions_1.TransactionState.Proceeding; - } - if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { - return (this.transaction.state === transactions_1.TransactionState.Trying || - this.transaction.state === transactions_1.TransactionState.Proceeding); - } - throw new Error("Unknown transaction type."); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(UserAgentServer.prototype, "tryingable", { - get: function () { - if (this.transaction instanceof transactions_1.InviteServerTransaction) { - return this.transaction.state === transactions_1.TransactionState.Proceeding; - } - if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { - return this.transaction.state === transactions_1.TransactionState.Trying; - } - throw new Error("Unknown transaction type."); - }, - enumerable: true, - configurable: true - }); - /** - * When a UAS wishes to construct a response to a request, it follows - * the general procedures detailed in the following subsections. - * Additional behaviors specific to the response code in question, which - * are not detailed in this section, may also be required. - * - * Once all procedures associated with the creation of a response have - * been completed, the UAS hands the response back to the server - * transaction from which it received the request. - * https://tools.ietf.org/html/rfc3261#section-8.2.6 - * @param statusCode - Status code to reply with. - * @param options - Reply options bucket. - */ - UserAgentServer.prototype.reply = function (options) { - if (!options.toTag && options.statusCode !== 100) { - options.toTag = this.toTag; - } - options.userAgent = options.userAgent || this.core.configuration.userAgentHeaderFieldValue; - options.supported = options.supported || this.core.configuration.supportedOptionTagsResponse; - var response = messages_1.constructOutgoingResponse(this.message, options); - this.transaction.receiveResponse(options.statusCode, response.message); - return response; - }; - UserAgentServer.prototype.init = function () { - var _this = this; - // We are the transaction user. - var user = { - loggerFactory: this.loggerFactory, - onStateChange: function (newState) { - if (newState === transactions_1.TransactionState.Terminated) { - // Remove the terminated transaction from the core. - _this.core.userAgentServers.delete(userAgentServerId); - _this.dispose(); - } - }, - onTransportError: function (error) { - _this.logger.error(error.message); - if (_this.delegate && _this.delegate.onTransportError) { - _this.delegate.onTransportError(error); - } - else { - _this.logger.error("User agent server response transport error."); - } - } - }; - // Create a new transaction with us as the user. - var transaction = new this.transactionConstructor(this.message, this.core.transport, user); - this._transaction = transaction; - // Add the new transaction to the core. - var userAgentServerId = transaction.id; - this.core.userAgentServers.set(transaction.id, this); - }; - return UserAgentServer; -}()); -exports.UserAgentServer = UserAgentServer; - - -/***/ }), -/* 45 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * INFO UAC. - * @public - */ -var InfoUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(InfoUserAgentClient, _super); - function InfoUserAgentClient(dialog, delegate, options) { - var _this = this; - var message = dialog.createOutgoingRequestMessage(messages_1.C.INFO, options); - _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; - return _this; - } - return InfoUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.InfoUserAgentClient = InfoUserAgentClient; - - -/***/ }), -/* 46 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * INFO UAS. - * @public - */ -var InfoUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(InfoUserAgentServer, _super); - function InfoUserAgentServer(dialog, message, delegate) { - return _super.call(this, transactions_1.NonInviteServerTransaction, dialog.userAgentCore, message, delegate) || this; - } - return InfoUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.InfoUserAgentServer = InfoUserAgentServer; - - -/***/ }), -/* 47 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * NOTIFY UAS. - * @public - */ -var NotifyUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(NotifyUserAgentClient, _super); - function NotifyUserAgentClient(dialog, delegate, options) { - var _this = this; - var message = dialog.createOutgoingRequestMessage(messages_1.C.NOTIFY, options); - _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; - return _this; - } - return NotifyUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.NotifyUserAgentClient = NotifyUserAgentClient; - - -/***/ }), -/* 48 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * NOTIFY UAS. - * @public - */ -var NotifyUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(NotifyUserAgentServer, _super); - /** - * NOTIFY UAS constructor. - * @param dialogOrCore - Dialog for in dialog NOTIFY, UserAgentCore for out of dialog NOTIFY (deprecated). - * @param message - Incoming NOTIFY request message. - */ - function NotifyUserAgentServer(dialogOrCore, message, delegate) { - var _this = this; - var userAgentCore = instanceOfDialog(dialogOrCore) ? - dialogOrCore.userAgentCore : - dialogOrCore; - _this = _super.call(this, transactions_1.NonInviteServerTransaction, userAgentCore, message, delegate) || this; - return _this; - } - return NotifyUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.NotifyUserAgentServer = NotifyUserAgentServer; -function instanceOfDialog(object) { - return object.userAgentCore !== undefined; -} - - -/***/ }), -/* 49 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * PRACK UAC. - * @public - */ -var PrackUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(PrackUserAgentClient, _super); - function PrackUserAgentClient(dialog, delegate, options) { - var _this = this; - var message = dialog.createOutgoingRequestMessage(messages_1.C.PRACK, options); - _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; - dialog.signalingStateTransition(message); - return _this; - } - return PrackUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.PrackUserAgentClient = PrackUserAgentClient; - - -/***/ }), -/* 50 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * PRACK UAS. - * @public - */ -var PrackUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(PrackUserAgentServer, _super); - function PrackUserAgentServer(dialog, message, delegate) { - var _this = _super.call(this, transactions_1.NonInviteServerTransaction, dialog.userAgentCore, message, delegate) || this; - // Update dialog signaling state with offer/answer in body - dialog.signalingStateTransition(message); - _this.dialog = dialog; - return _this; - } - /** - * Update the dialog signaling state on a 2xx response. - * @param options - Options bucket. - */ - PrackUserAgentServer.prototype.accept = function (options) { - if (options === void 0) { options = { statusCode: 200 }; } - if (options.body) { - // Update dialog signaling state with offer/answer in body - this.dialog.signalingStateTransition(options.body); - } - return _super.prototype.accept.call(this, options); - }; - return PrackUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.PrackUserAgentServer = PrackUserAgentServer; - - -/***/ }), -/* 51 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * Re-INVITE UAC. - * @remarks - * 14 Modifying an Existing Session - * https://tools.ietf.org/html/rfc3261#section-14 - * 14.1 UAC Behavior - * https://tools.ietf.org/html/rfc3261#section-14.1 - * @public - */ -var ReInviteUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(ReInviteUserAgentClient, _super); - function ReInviteUserAgentClient(dialog, delegate, options) { - var _this = this; - var message = dialog.createOutgoingRequestMessage(messages_1.C.INVITE, options); - _this = _super.call(this, transactions_1.InviteClientTransaction, dialog.userAgentCore, message, delegate) || this; - _this.delegate = delegate; - dialog.signalingStateTransition(message); - // FIXME: TODO: next line obviously needs to be improved... - dialog.reinviteUserAgentClient = _this; // let the dialog know re-invite request sent - _this.dialog = dialog; - return _this; - } - ReInviteUserAgentClient.prototype.receiveResponse = function (message) { - var _this = this; - var statusCode = message.statusCode ? message.statusCode.toString() : ""; - if (!statusCode) { - throw new Error("Response status code undefined."); - } - switch (true) { - case /^100$/.test(statusCode): - if (this.delegate && this.delegate.onTrying) { - this.delegate.onTrying({ message: message }); - } - break; - case /^1[0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onProgress) { - this.delegate.onProgress({ - message: message, - session: this.dialog, - prack: function (options) { - throw new Error("Unimplemented."); - } - }); - } - break; - case /^2[0-9]{2}$/.test(statusCode): - // Update dialog signaling state with offer/answer in body - this.dialog.signalingStateTransition(message); - if (this.delegate && this.delegate.onAccept) { - this.delegate.onAccept({ - message: message, - session: this.dialog, - ack: function (options) { - var outgoingAckRequest = _this.dialog.ack(options); - return outgoingAckRequest; - } - }); - } - break; - case /^3[0-9]{2}$/.test(statusCode): - this.dialog.signalingStateRollback(); - this.dialog.reinviteUserAgentClient = undefined; // ACK was handled by transaction - if (this.delegate && this.delegate.onRedirect) { - this.delegate.onRedirect({ message: message }); - } - break; - case /^[4-6][0-9]{2}$/.test(statusCode): - this.dialog.signalingStateRollback(); - this.dialog.reinviteUserAgentClient = undefined; // ACK was handled by transaction - if (this.delegate && this.delegate.onReject) { - this.delegate.onReject({ message: message }); - } - else { - // If a UA receives a non-2xx final response to a re-INVITE, the session - // parameters MUST remain unchanged, as if no re-INVITE had been issued. - // Note that, as stated in Section 12.2.1.2, if the non-2xx final - // response is a 481 (Call/Transaction Does Not Exist), or a 408 - // (Request Timeout), or no response at all is received for the re- - // INVITE (that is, a timeout is returned by the INVITE client - // transaction), the UAC will terminate the dialog. - // - // If a UAC receives a 491 response to a re-INVITE, it SHOULD start a - // timer with a value T chosen as follows: - // - // 1. If the UAC is the owner of the Call-ID of the dialog ID - // (meaning it generated the value), T has a randomly chosen value - // between 2.1 and 4 seconds in units of 10 ms. - // - // 2. If the UAC is not the owner of the Call-ID of the dialog ID, T - // has a randomly chosen value of between 0 and 2 seconds in units - // of 10 ms. - // - // When the timer fires, the UAC SHOULD attempt the re-INVITE once more, - // if it still desires for that session modification to take place. For - // example, if the call was already hung up with a BYE, the re-INVITE - // would not take place. - // https://tools.ietf.org/html/rfc3261#section-14.1 - // FIXME: TODO: The above. - } - break; - default: - throw new Error("Invalid status code " + statusCode); - } - }; - return ReInviteUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.ReInviteUserAgentClient = ReInviteUserAgentClient; - - -/***/ }), -/* 52 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * Re-INVITE UAS. - * @remarks - * 14 Modifying an Existing Session - * https://tools.ietf.org/html/rfc3261#section-14 - * 14.2 UAS Behavior - * https://tools.ietf.org/html/rfc3261#section-14.2 - * @public - */ -var ReInviteUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(ReInviteUserAgentServer, _super); - function ReInviteUserAgentServer(dialog, message, delegate) { - var _this = _super.call(this, transactions_1.InviteServerTransaction, dialog.userAgentCore, message, delegate) || this; - dialog.reinviteUserAgentServer = _this; - _this.dialog = dialog; - return _this; - } - /** - * Update the dialog signaling state on a 2xx response. - * @param options - Options bucket. - */ - ReInviteUserAgentServer.prototype.accept = function (options) { - if (options === void 0) { options = { statusCode: 200 }; } - // FIXME: The next two lines SHOULD go away, but I suppose it's technically harmless... - // These are here because some versions of SIP.js prior to 0.13.8 set the route set - // of all in dialog ACKs based on the Record-Route headers in the associated 2xx - // response. While this worked for dialog forming 2xx responses, it was technically - // broken for re-INVITE ACKS as it only worked if the UAS populated the Record-Route - // headers in the re-INVITE 2xx response (which is not required and a waste of bandwidth - // as the should be ignored if present in re-INVITE ACKS) and the UAS populated - // the Record-Route headers with the correct values (would be weird not too, but...). - // Anyway, for now the technically useless Record-Route headers are being added - // to maintain "backwards compatibility" with the older broken versions of SIP.js. - options.extraHeaders = options.extraHeaders || []; - options.extraHeaders = options.extraHeaders.concat(this.dialog.routeSet.map(function (route) { return "Record-Route: " + route; })); - // Send and return the response - var response = _super.prototype.accept.call(this, options); - var session = this.dialog; - var result = tslib_1.__assign({}, response, { session: session }); - if (options.body) { - // Update dialog signaling state with offer/answer in body - this.dialog.signalingStateTransition(options.body); - } - // Update dialog - this.dialog.reConfirm(); - return result; - }; - /** - * Update the dialog signaling state on a 1xx response. - * @param options - Progress options bucket. - */ - ReInviteUserAgentServer.prototype.progress = function (options) { - if (options === void 0) { options = { statusCode: 180 }; } - // Send and return the response - var response = _super.prototype.progress.call(this, options); - var session = this.dialog; - var result = tslib_1.__assign({}, response, { session: session }); - // Update dialog signaling state - if (options.body) { - this.dialog.signalingStateTransition(options.body); - } - return result; - }; - /** - * TODO: Not Yet Supported - * @param contacts - Contacts to redirect to. - * @param options - Redirect options bucket. - */ - ReInviteUserAgentServer.prototype.redirect = function (contacts, options) { - if (options === void 0) { options = { statusCode: 302 }; } - this.dialog.signalingStateRollback(); - this.dialog.reinviteUserAgentServer = undefined; // ACK will be handled by transaction - throw new Error("Unimplemented."); - }; - /** - * 3.1 Background on Re-INVITE Handling by UASs - * An error response to a re-INVITE has the following semantics. As - * specified in Section 12.2.2 of RFC 3261 [RFC3261], if a re-INVITE is - * rejected, no state changes are performed. - * https://tools.ietf.org/html/rfc6141#section-3.1 - * @param options - Reject options bucket. - */ - ReInviteUserAgentServer.prototype.reject = function (options) { - if (options === void 0) { options = { statusCode: 488 }; } - this.dialog.signalingStateRollback(); - this.dialog.reinviteUserAgentServer = undefined; // ACK will be handled by transaction - return _super.prototype.reject.call(this, options); - }; - return ReInviteUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.ReInviteUserAgentServer = ReInviteUserAgentServer; - - -/***/ }), -/* 53 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * REFER UAC. - * @public - */ -var ReferUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(ReferUserAgentClient, _super); - function ReferUserAgentClient(dialog, delegate, options) { - var _this = this; - var message = dialog.createOutgoingRequestMessage(messages_1.C.REFER, options); - _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; - return _this; - } - return ReferUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.ReferUserAgentClient = ReferUserAgentClient; - - -/***/ }), -/* 54 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * REFER UAS. - * @public - */ -var ReferUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(ReferUserAgentServer, _super); - /** - * REFER UAS constructor. - * @param dialogOrCore - Dialog for in dialog REFER, UserAgentCore for out of dialog REFER. - * @param message - Incoming REFER request message. - */ - function ReferUserAgentServer(dialogOrCore, message, delegate) { - var _this = this; - var userAgentCore = instanceOfSessionDialog(dialogOrCore) ? - dialogOrCore.userAgentCore : - dialogOrCore; - _this = _super.call(this, transactions_1.NonInviteServerTransaction, userAgentCore, message, delegate) || this; - return _this; - } - return ReferUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.ReferUserAgentServer = ReferUserAgentServer; -function instanceOfSessionDialog(object) { - return object.userAgentCore !== undefined; -} - - -/***/ }), -/* 55 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var subscription_1 = __webpack_require__(56); -var timers_1 = __webpack_require__(26); -var allowed_methods_1 = __webpack_require__(58); -var notify_user_agent_server_1 = __webpack_require__(48); -var re_subscribe_user_agent_client_1 = __webpack_require__(59); -var dialog_1 = __webpack_require__(4); -/** - * Subscription Dialog. - * @remarks - * SIP-Specific Event Notification - * - * Abstract - * - * This document describes an extension to the Session Initiation - * Protocol (SIP) defined by RFC 3261. The purpose of this extension is - * to provide an extensible framework by which SIP nodes can request - * notification from remote nodes indicating that certain events have - * occurred. - * - * Note that the event notification mechanisms defined herein are NOT - * intended to be a general-purpose infrastructure for all classes of - * event subscription and notification. - * - * This document represents a backwards-compatible improvement on the - * original mechanism described by RFC 3265, taking into account several - * years of implementation experience. Accordingly, this document - * obsoletes RFC 3265. This document also updates RFC 4660 slightly to - * accommodate some small changes to the mechanism that were discussed - * in that document. - * - * https://tools.ietf.org/html/rfc6665 - * @public - */ -var SubscriptionDialog = /** @class */ (function (_super) { - tslib_1.__extends(SubscriptionDialog, _super); - function SubscriptionDialog(subscriptionEvent, subscriptionExpires, subscriptionState, core, state, delegate) { - var _this = _super.call(this, core, state) || this; - _this.delegate = delegate; - _this._autoRefresh = false; - _this._subscriptionEvent = subscriptionEvent; - _this._subscriptionExpires = subscriptionExpires; - _this._subscriptionExpiresInitial = subscriptionExpires; - _this._subscriptionExpiresLastSet = Math.floor(Date.now() / 1000); - _this._subscriptionRefresh = undefined; - _this._subscriptionRefreshLastSet = undefined; - _this._subscriptionState = subscriptionState; - _this.logger = core.loggerFactory.getLogger("sip.subscribe-dialog"); - _this.logger.log("SUBSCRIBE dialog " + _this.id + " constructed"); - return _this; - } - /** - * When a UAC receives a response that establishes a dialog, it - * constructs the state of the dialog. This state MUST be maintained - * for the duration of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.1.2 - * @param outgoingRequestMessage - Outgoing request message for dialog. - * @param incomingResponseMessage - Incoming response message creating dialog. - */ - SubscriptionDialog.initialDialogStateForSubscription = function (outgoingSubscribeRequestMessage, incomingNotifyRequestMessage) { - // If the request was sent over TLS, and the Request-URI contained a - // SIPS URI, the "secure" flag is set to TRUE. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - var secure = false; // FIXME: Currently no support for TLS. - // The route set MUST be set to the list of URIs in the Record-Route - // header field from the response, taken in reverse order and preserving - // all URI parameters. If no Record-Route header field is present in - // the response, the route set MUST be set to the empty set. This route - // set, even if empty, overrides any pre-existing route set for future - // requests in this dialog. The remote target MUST be set to the URI - // from the Contact header field of the response. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - var routeSet = incomingNotifyRequestMessage.getHeaders("record-route"); - var contact = incomingNotifyRequestMessage.parseHeader("contact"); - if (!contact) { // TODO: Review to make sure this will never happen - throw new Error("Contact undefined."); - } - if (!(contact instanceof messages_1.NameAddrHeader)) { - throw new Error("Contact not instance of NameAddrHeader."); - } - var remoteTarget = contact.uri; - // The local sequence number MUST be set to the value of the sequence - // number in the CSeq header field of the request. The remote sequence - // number MUST be empty (it is established when the remote UA sends a - // request within the dialog). The call identifier component of the - // dialog ID MUST be set to the value of the Call-ID in the request. - // The local tag component of the dialog ID MUST be set to the tag in - // the From field in the request, and the remote tag component of the - // dialog ID MUST be set to the tag in the To field of the response. A - // UAC MUST be prepared to receive a response without a tag in the To - // field, in which case the tag is considered to have a value of null. - // - // This is to maintain backwards compatibility with RFC 2543, which - // did not mandate To tags. - // - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - var localSequenceNumber = outgoingSubscribeRequestMessage.cseq; - var remoteSequenceNumber = undefined; - var callId = outgoingSubscribeRequestMessage.callId; - var localTag = outgoingSubscribeRequestMessage.fromTag; - var remoteTag = incomingNotifyRequestMessage.fromTag; - if (!callId) { // TODO: Review to make sure this will never happen - throw new Error("Call id undefined."); - } - if (!localTag) { // TODO: Review to make sure this will never happen - throw new Error("From tag undefined."); - } - if (!remoteTag) { // TODO: Review to make sure this will never happen - throw new Error("To tag undefined."); // FIXME: No backwards compatibility with RFC 2543 - } - // The remote URI MUST be set to the URI in the To field, and the local - // URI MUST be set to the URI in the From field. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - if (!outgoingSubscribeRequestMessage.from) { // TODO: Review to make sure this will never happen - throw new Error("From undefined."); - } - if (!outgoingSubscribeRequestMessage.to) { // TODO: Review to make sure this will never happen - throw new Error("To undefined."); - } - var localURI = outgoingSubscribeRequestMessage.from.uri; - var remoteURI = outgoingSubscribeRequestMessage.to.uri; - // A dialog can also be in the "early" state, which occurs when it is - // created with a provisional response, and then transition to the - // "confirmed" state when a 2xx final response arrives. - // https://tools.ietf.org/html/rfc3261#section-12 - var early = false; - var dialogState = { - id: callId + localTag + remoteTag, - early: early, - callId: callId, - localTag: localTag, - remoteTag: remoteTag, - localSequenceNumber: localSequenceNumber, - remoteSequenceNumber: remoteSequenceNumber, - localURI: localURI, - remoteURI: remoteURI, - remoteTarget: remoteTarget, - routeSet: routeSet, - secure: secure - }; - return dialogState; - }; - SubscriptionDialog.prototype.dispose = function () { - _super.prototype.dispose.call(this); - if (this.N) { - clearTimeout(this.N); - this.N = undefined; - } - this.refreshTimerClear(); - this.logger.log("SUBSCRIBE dialog " + this.id + " destroyed"); - }; - Object.defineProperty(SubscriptionDialog.prototype, "autoRefresh", { - get: function () { - return this._autoRefresh; - }, - set: function (autoRefresh) { - this._autoRefresh = true; - this.refreshTimerSet(); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SubscriptionDialog.prototype, "subscriptionEvent", { - get: function () { - return this._subscriptionEvent; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SubscriptionDialog.prototype, "subscriptionExpires", { - /** Number of seconds until subscription expires. */ - get: function () { - var secondsSinceLastSet = Math.floor(Date.now() / 1000) - this._subscriptionExpiresLastSet; - var secondsUntilExpires = this._subscriptionExpires - secondsSinceLastSet; - return Math.max(secondsUntilExpires, 0); - }, - set: function (expires) { - if (expires < 0) { - throw new Error("Expires must be greater than or equal to zero."); - } - this._subscriptionExpires = expires; - this._subscriptionExpiresLastSet = Math.floor(Date.now() / 1000); - if (this.autoRefresh) { - var refresh = this.subscriptionRefresh; - if (refresh === undefined || refresh >= expires) { - this.refreshTimerSet(); - } - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SubscriptionDialog.prototype, "subscriptionExpiresInitial", { - get: function () { - return this._subscriptionExpiresInitial; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SubscriptionDialog.prototype, "subscriptionRefresh", { - /** Number of seconds until subscription auto refresh. */ - get: function () { - if (this._subscriptionRefresh === undefined || this._subscriptionRefreshLastSet === undefined) { - return undefined; - } - var secondsSinceLastSet = Math.floor(Date.now() / 1000) - this._subscriptionRefreshLastSet; - var secondsUntilExpires = this._subscriptionRefresh - secondsSinceLastSet; - return Math.max(secondsUntilExpires, 0); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SubscriptionDialog.prototype, "subscriptionState", { - get: function () { - return this._subscriptionState; - }, - enumerable: true, - configurable: true - }); - /** - * Receive in dialog request message from transport. - * @param message - The incoming request message. - */ - SubscriptionDialog.prototype.receiveRequest = function (message) { - this.logger.log("SUBSCRIBE dialog " + this.id + " received " + message.method + " request"); - // Request within a dialog out of sequence guard. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (!this.sequenceGuard(message)) { - this.logger.log("SUBSCRIBE dialog " + this.id + " rejected out of order " + message.method + " request."); - return; - } - // Request within a dialog common processing. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - _super.prototype.receiveRequest.call(this, message); - // Switch on method and then delegate. - switch (message.method) { - case messages_1.C.NOTIFY: - this.onNotify(message); - break; - default: - this.logger.log("SUBSCRIBE dialog " + this.id + " received unimplemented " + message.method + " request"); - this.core.replyStateless(message, { statusCode: 501 }); - break; - } - }; - /** - * 4.1.2.2. Refreshing of Subscriptions - * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - */ - SubscriptionDialog.prototype.refresh = function () { - var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); - var options = {}; - options.extraHeaders = (options.extraHeaders || []).slice(); - options.extraHeaders.push(allowHeader); - options.extraHeaders.push("Event: " + this.subscriptionEvent); - options.extraHeaders.push("Expires: " + this.subscriptionExpiresInitial); - options.extraHeaders.push("Contact: " + this.core.configuration.contact.toString()); - return this.subscribe(undefined, options); - }; - /** - * 4.1.2.2. Refreshing of Subscriptions - * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - * @param delegate - Delegate to handle responses. - * @param options - Options bucket. - */ - SubscriptionDialog.prototype.subscribe = function (delegate, options) { - var _this = this; - if (options === void 0) { options = {}; } - if (this.subscriptionState !== subscription_1.SubscriptionState.Pending && this.subscriptionState !== subscription_1.SubscriptionState.Active) { - // FIXME: This needs to be a proper exception - throw new Error("Invalid state " + this.subscriptionState + ". May only re-subscribe while in state \"pending\" or \"active\"."); - } - this.logger.log("SUBSCRIBE dialog " + this.id + " sending SUBSCRIBE request"); - var uac = new re_subscribe_user_agent_client_1.ReSubscribeUserAgentClient(this, delegate, options); - // When refreshing a subscription, a subscriber starts Timer N, set to - // 64*T1, when it sends the SUBSCRIBE request. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - this.N = setTimeout(function () { return _this.timer_N(); }, timers_1.Timers.TIMER_N); - return uac; - }; - /** - * 4.4.1. Dialog Creation and Termination - * A subscription is destroyed after a notifier sends a NOTIFY request - * with a "Subscription-State" of "terminated", or in certain error - * situations described elsewhere in this document. - * https://tools.ietf.org/html/rfc6665#section-4.4.1 - */ - SubscriptionDialog.prototype.terminate = function () { - this.stateTransition(subscription_1.SubscriptionState.Terminated); - this.onTerminated(); - }; - /** - * 4.1.2.3. Unsubscribing - * https://tools.ietf.org/html/rfc6665#section-4.1.2.3 - */ - SubscriptionDialog.prototype.unsubscribe = function () { - var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); - var options = {}; - options.extraHeaders = (options.extraHeaders || []).slice(); - options.extraHeaders.push(allowHeader); - options.extraHeaders.push("Event: " + this.subscriptionEvent); - options.extraHeaders.push("Expires: 0"); - options.extraHeaders.push("Contact: " + this.core.configuration.contact.toString()); - return this.subscribe(undefined, options); - }; - /** - * Handle in dialog NOTIFY requests. - * This does not include the first NOTIFY which created the dialog. - * @param message - The incoming NOTIFY request message. - */ - SubscriptionDialog.prototype.onNotify = function (message) { - // If, for some reason, the event package designated in the "Event" - // header field of the NOTIFY request is not supported, the subscriber - // will respond with a 489 (Bad Event) response. - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - var event = message.parseHeader("Event").event; - if (!event || event !== this.subscriptionEvent) { - this.core.replyStateless(message, { statusCode: 489 }); - return; - } - // In the state diagram, "Re-subscription times out" means that an - // attempt to refresh or update the subscription using a new SUBSCRIBE - // request does not result in a NOTIFY request before the corresponding - // Timer N expires. - // https://tools.ietf.org/html/rfc6665#section-4.1.2 - if (this.N) { - clearTimeout(this.N); - this.N = undefined; - } - // NOTIFY requests MUST contain "Subscription-State" header fields that - // indicate the status of the subscription. - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - var subscriptionState = message.parseHeader("Subscription-State"); - if (!subscriptionState || !subscriptionState.state) { - this.core.replyStateless(message, { statusCode: 489 }); - return; - } - var state = subscriptionState.state; - var expires = subscriptionState.expires ? Math.max(subscriptionState.expires, 0) : undefined; - // Update our state and expiration. - switch (state) { - case "pending": - this.stateTransition(subscription_1.SubscriptionState.Pending, expires); - break; - case "active": - this.stateTransition(subscription_1.SubscriptionState.Active, expires); - break; - case "terminated": - this.stateTransition(subscription_1.SubscriptionState.Terminated, expires); - break; - default: - this.logger.warn("Unrecognized subscription state."); - break; - } - // Delegate remainder of NOTIFY handling. - var uas = new notify_user_agent_server_1.NotifyUserAgentServer(this, message); - if (this.delegate && this.delegate.onNotify) { - this.delegate.onNotify(uas); - } - else { - uas.accept(); - } - }; - SubscriptionDialog.prototype.onRefresh = function (request) { - if (this.delegate && this.delegate.onRefresh) { - this.delegate.onRefresh(request); - } - }; - SubscriptionDialog.prototype.onTerminated = function () { - if (this.delegate && this.delegate.onTerminated) { - this.delegate.onTerminated(); - } - }; - SubscriptionDialog.prototype.refreshTimerClear = function () { - if (this.refreshTimer) { - clearTimeout(this.refreshTimer); - this.refreshTimer = undefined; - } - }; - SubscriptionDialog.prototype.refreshTimerSet = function () { - var _this = this; - this.refreshTimerClear(); - if (this.autoRefresh && this.subscriptionExpires > 0) { - var refresh = this.subscriptionExpires * 900; - this._subscriptionRefresh = Math.floor(refresh / 1000); - this._subscriptionRefreshLastSet = Math.floor(Date.now() / 1000); - this.refreshTimer = setTimeout(function () { - _this.refreshTimer = undefined; - _this._subscriptionRefresh = undefined; - _this._subscriptionRefreshLastSet = undefined; - _this.onRefresh(_this.refresh()); - }, refresh); - } - }; - SubscriptionDialog.prototype.stateTransition = function (newState, newExpires) { - var _this = this; - // Assert valid state transitions. - var invalidStateTransition = function () { - _this.logger.warn("Invalid subscription state transition from " + _this.subscriptionState + " to " + newState); - }; - switch (newState) { - case subscription_1.SubscriptionState.Initial: - invalidStateTransition(); - return; - case subscription_1.SubscriptionState.NotifyWait: - invalidStateTransition(); - return; - case subscription_1.SubscriptionState.Pending: - if (this.subscriptionState !== subscription_1.SubscriptionState.NotifyWait && - this.subscriptionState !== subscription_1.SubscriptionState.Pending) { - invalidStateTransition(); - return; - } - break; - case subscription_1.SubscriptionState.Active: - if (this.subscriptionState !== subscription_1.SubscriptionState.NotifyWait && - this.subscriptionState !== subscription_1.SubscriptionState.Pending && - this.subscriptionState !== subscription_1.SubscriptionState.Active) { - invalidStateTransition(); - return; - } - break; - case subscription_1.SubscriptionState.Terminated: - if (this.subscriptionState !== subscription_1.SubscriptionState.NotifyWait && - this.subscriptionState !== subscription_1.SubscriptionState.Pending && - this.subscriptionState !== subscription_1.SubscriptionState.Active) { - invalidStateTransition(); - return; - } - break; - default: - invalidStateTransition(); - return; - } - // If the "Subscription-State" value is "pending", the subscription has - // been received by the notifier, but there is insufficient policy - // information to grant or deny the subscription yet. If the header - // field also contains an "expires" parameter, the subscriber SHOULD - // take it as the authoritative subscription duration and adjust - // accordingly. No further action is necessary on the part of the - // subscriber. The "retry-after" and "reason" parameters have no - // semantics for "pending". - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - if (newState === subscription_1.SubscriptionState.Pending) { - if (newExpires) { - this.subscriptionExpires = newExpires; - } - } - // If the "Subscription-State" header field value is "active", it means - // that the subscription has been accepted and (in general) has been - // authorized. If the header field also contains an "expires" - // parameter, the subscriber SHOULD take it as the authoritative - // subscription duration and adjust accordingly. The "retry-after" and - // "reason" parameters have no semantics for "active". - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - if (newState === subscription_1.SubscriptionState.Active) { - if (newExpires) { - this.subscriptionExpires = newExpires; - } - } - // If the "Subscription-State" value is "terminated", the subscriber - // MUST consider the subscription terminated. The "expires" parameter - // has no semantics for "terminated" -- notifiers SHOULD NOT include an - // "expires" parameter on a "Subscription-State" header field with a - // value of "terminated", and subscribers MUST ignore any such - // parameter, if present. - if (newState === subscription_1.SubscriptionState.Terminated) { - this.dispose(); - } - this._subscriptionState = newState; - }; - /** - * When refreshing a subscription, a subscriber starts Timer N, set to - * 64*T1, when it sends the SUBSCRIBE request. If this Timer N expires - * prior to the receipt of a NOTIFY request, the subscriber considers - * the subscription terminated. If the subscriber receives a success - * response to the SUBSCRIBE request that indicates that no NOTIFY - * request will be generated -- such as the 204 response defined for use - * with the optional extension described in [RFC5839] -- then it MUST - * cancel Timer N. - * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - */ - SubscriptionDialog.prototype.timer_N = function () { - if (this.subscriptionState !== subscription_1.SubscriptionState.Terminated) { - this.stateTransition(subscription_1.SubscriptionState.Terminated); - this.onTerminated(); - } - }; - return SubscriptionDialog; -}(dialog_1.Dialog)); -exports.SubscriptionDialog = SubscriptionDialog; - - -/***/ }), -/* 56 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -tslib_1.__exportStar(__webpack_require__(57), exports); - - -/***/ }), -/* 57 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * Subscription state. - * @remarks - * https://tools.ietf.org/html/rfc6665#section-4.1.2 - * @public - */ -var SubscriptionState; -(function (SubscriptionState) { - SubscriptionState["Initial"] = "Initial"; - SubscriptionState["NotifyWait"] = "NotifyWait"; - SubscriptionState["Pending"] = "Pending"; - SubscriptionState["Active"] = "Active"; - SubscriptionState["Terminated"] = "Terminated"; -})(SubscriptionState = exports.SubscriptionState || (exports.SubscriptionState = {})); - - -/***/ }), -/* 58 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var messages_1 = __webpack_require__(5); -/** - * FIXME: TODO: Should be configurable/variable. - */ -exports.AllowedMethods = [ - messages_1.C.ACK, - messages_1.C.BYE, - messages_1.C.CANCEL, - messages_1.C.INFO, - messages_1.C.INVITE, - messages_1.C.MESSAGE, - messages_1.C.NOTIFY, - messages_1.C.OPTIONS, - messages_1.C.PRACK, - messages_1.C.REFER, - messages_1.C.REGISTER, - messages_1.C.SUBSCRIBE -]; - - -/***/ }), -/* 59 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * Re-SUBSCRIBE UAC. - * @public - */ -var ReSubscribeUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(ReSubscribeUserAgentClient, _super); - function ReSubscribeUserAgentClient(dialog, delegate, options) { - var _this = this; - var message = dialog.createOutgoingRequestMessage(messages_1.C.SUBSCRIBE, options); - _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; - _this.dialog = dialog; - return _this; - } - ReSubscribeUserAgentClient.prototype.waitNotifyStop = function () { - // TODO: Placeholder. Not utilized currently. - return; - }; - /** - * Receive a response from the transaction layer. - * @param message - Incoming response message. - */ - ReSubscribeUserAgentClient.prototype.receiveResponse = function (message) { - if (message.statusCode && message.statusCode >= 200 && message.statusCode < 300) { - // The "Expires" header field in a 200-class response to SUBSCRIBE - // request indicates the actual duration for which the subscription will - // remain active (unless refreshed). The received value might be - // smaller than the value indicated in the SUBSCRIBE request but cannot - // be larger; see Section 4.2.1 for details. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - var expires = message.getHeader("Expires"); - if (!expires) { - this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE"); - } - else { - var subscriptionExpiresReceived = Number(expires); - if (this.dialog.subscriptionExpires > subscriptionExpiresReceived) { - this.dialog.subscriptionExpires = subscriptionExpiresReceived; - } - } - } - if (message.statusCode && message.statusCode >= 400 && message.statusCode < 700) { - // If a SUBSCRIBE request to refresh a subscription receives a 404, 405, - // 410, 416, 480-485, 489, 501, or 604 response, the subscriber MUST - // consider the subscription terminated. (See [RFC5057] for further - // details and notes about the effect of error codes on dialogs and - // usages within dialog, such as subscriptions). If the subscriber - // wishes to re-subscribe to the state, he does so by composing an - // unrelated initial SUBSCRIBE request with a freshly generated Call-ID - // and a new, unique "From" tag (see Section 4.1.2.1). - // https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - var errorCodes = [404, 405, 410, 416, 480, 481, 482, 483, 484, 485, 489, 501, 604]; - if (errorCodes.includes(message.statusCode)) { - this.dialog.terminate(); - } - // If a SUBSCRIBE request to refresh a subscription fails with any error - // code other than those listed above, the original subscription is - // still considered valid for the duration of the most recently known - // "Expires" value as negotiated by the most recent successful SUBSCRIBE - // transaction, or as communicated by a NOTIFY request in its - // "Subscription-State" header field "expires" parameter. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - } - _super.prototype.receiveResponse.call(this, message); - }; - return ReSubscribeUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.ReSubscribeUserAgentClient = ReSubscribeUserAgentClient; - - -/***/ }), -/* 60 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -tslib_1.__exportStar(__webpack_require__(61), exports); -tslib_1.__exportStar(__webpack_require__(62), exports); -tslib_1.__exportStar(__webpack_require__(63), exports); - - -/***/ }), -/* 61 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * Log levels. - * @public - */ -var Levels; -(function (Levels) { - Levels[Levels["error"] = 0] = "error"; - Levels[Levels["warn"] = 1] = "warn"; - Levels[Levels["log"] = 2] = "log"; - Levels[Levels["debug"] = 3] = "debug"; -})(Levels = exports.Levels || (exports.Levels = {})); - - -/***/ }), -/* 62 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var levels_1 = __webpack_require__(61); -var logger_1 = __webpack_require__(63); -/** - * Logger. - * @public - */ -var LoggerFactory = /** @class */ (function () { - function LoggerFactory() { - this.builtinEnabled = true; - this._level = levels_1.Levels.log; - this.loggers = {}; - this.logger = this.getLogger("sip:loggerfactory"); - } - Object.defineProperty(LoggerFactory.prototype, "level", { - get: function () { return this._level; }, - set: function (newLevel) { - if (newLevel >= 0 && newLevel <= 3) { - this._level = newLevel; - } - else if (newLevel > 3) { - this._level = 3; - } - else if (levels_1.Levels.hasOwnProperty(newLevel)) { - this._level = newLevel; - } - else { - this.logger.error("invalid 'level' parameter value: " + JSON.stringify(newLevel)); - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(LoggerFactory.prototype, "connector", { - get: function () { - return this._connector; - }, - set: function (value) { - if (!value) { - this._connector = undefined; - } - else if (typeof value === "function") { - this._connector = value; - } - else { - this.logger.error("invalid 'connector' parameter value: " + JSON.stringify(value)); - } - }, - enumerable: true, - configurable: true - }); - LoggerFactory.prototype.getLogger = function (category, label) { - if (label && this.level === 3) { - return new logger_1.Logger(this, category, label); - } - else if (this.loggers[category]) { - return this.loggers[category]; - } - else { - var logger = new logger_1.Logger(this, category); - this.loggers[category] = logger; - return logger; - } - }; - LoggerFactory.prototype.genericLog = function (levelToLog, category, label, content) { - if (this.level >= levelToLog) { - if (this.builtinEnabled) { - this.print(levelToLog, category, label, content); - } - } - if (this.connector) { - this.connector(levels_1.Levels[levelToLog], category, label, content); - } - }; - LoggerFactory.prototype.print = function (levelToLog, category, label, content) { - if (typeof content === "string") { - var prefix = [new Date(), category]; - if (label) { - prefix.push(label); - } - content = prefix.concat(content).join(" | "); - } - switch (levelToLog) { - case levels_1.Levels.error: - // tslint:disable-next-line:no-console - console.error(content); - break; - case levels_1.Levels.warn: - // tslint:disable-next-line:no-console - console.warn(content); - break; - case levels_1.Levels.log: - // tslint:disable-next-line:no-console - console.log(content); - break; - case levels_1.Levels.debug: - // tslint:disable-next-line:no-console - console.debug(content); - break; - default: - break; - } - }; - return LoggerFactory; -}()); -exports.LoggerFactory = LoggerFactory; - - -/***/ }), -/* 63 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var levels_1 = __webpack_require__(61); -/** - * Logger. - * @public - */ -var Logger = /** @class */ (function () { - function Logger(logger, category, label) { - this.logger = logger; - this.category = category; - this.label = label; - } - Logger.prototype.error = function (content) { this.genericLog(levels_1.Levels.error, content); }; - Logger.prototype.warn = function (content) { this.genericLog(levels_1.Levels.warn, content); }; - Logger.prototype.log = function (content) { this.genericLog(levels_1.Levels.log, content); }; - Logger.prototype.debug = function (content) { this.genericLog(levels_1.Levels.debug, content); }; - Logger.prototype.genericLog = function (level, content) { - this.logger.genericLog(level, this.category, this.label, content); - }; - return Logger; -}()); -exports.Logger = Logger; - - -/***/ }), -/* 64 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -tslib_1.__exportStar(__webpack_require__(65), exports); - - -/***/ }), -/* 65 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var transactions_1 = __webpack_require__(27); -var user_agents_1 = __webpack_require__(66); -var allowed_methods_1 = __webpack_require__(58); -/** - * This is ported from UA.C.ACCEPTED_BODY_TYPES. - * FIXME: TODO: Should be configurable/variable. - */ -var acceptedBodyTypes = [ - "application/sdp", - "application/dtmf-relay" -]; -/** - * User Agent Core. - * @remarks - * Core designates the functions specific to a particular type - * of SIP entity, i.e., specific to either a stateful or stateless - * proxy, a user agent or registrar. All cores, except those for - * the stateless proxy, are transaction users. - * https://tools.ietf.org/html/rfc3261#section-6 - * - * UAC Core: The set of processing functions required of a UAC that - * reside above the transaction and transport layers. - * https://tools.ietf.org/html/rfc3261#section-6 - * - * UAS Core: The set of processing functions required at a UAS that - * resides above the transaction and transport layers. - * https://tools.ietf.org/html/rfc3261#section-6 - * @public - */ -var UserAgentCore = /** @class */ (function () { - /** - * Constructor. - * @param configuration - Configuration. - * @param delegate - Delegate. - */ - function UserAgentCore(configuration, delegate) { - if (delegate === void 0) { delegate = {}; } - /** UACs. */ - this.userAgentClients = new Map(); - /** UASs. */ - this.userAgentServers = new Map(); - this.configuration = configuration; - this.delegate = delegate; - this.dialogs = new Map(); - this.subscribers = new Map(); - this.logger = configuration.loggerFactory.getLogger("sip.user-agent-core"); - } - /** Destructor. */ - UserAgentCore.prototype.dispose = function () { - this.reset(); - }; - /** Reset. */ - UserAgentCore.prototype.reset = function () { - this.dialogs.forEach(function (dialog) { return dialog.dispose(); }); - this.dialogs.clear(); - this.subscribers.forEach(function (subscriber) { return subscriber.dispose(); }); - this.subscribers.clear(); - this.userAgentClients.forEach(function (uac) { return uac.dispose(); }); - this.userAgentClients.clear(); - this.userAgentServers.forEach(function (uac) { return uac.dispose(); }); - this.userAgentServers.clear(); - }; - Object.defineProperty(UserAgentCore.prototype, "loggerFactory", { - /** Logger factory. */ - get: function () { - return this.configuration.loggerFactory; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(UserAgentCore.prototype, "transport", { - /** Transport. */ - get: function () { - var transport = this.configuration.transportAccessor(); - if (!transport) { - throw new Error("Transport undefined."); - } - return transport; - }, - enumerable: true, - configurable: true - }); - /** - * Send INVITE. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - UserAgentCore.prototype.invite = function (request, delegate) { - return new user_agents_1.InviteUserAgentClient(this, request, delegate); - }; - /** - * Send MESSAGE. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - UserAgentCore.prototype.message = function (request, delegate) { - return new user_agents_1.MessageUserAgentClient(this, request, delegate); - }; - /** - * Send PUBLISH. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - UserAgentCore.prototype.publish = function (request, delegate) { - return new user_agents_1.PublishUserAgentClient(this, request, delegate); - }; - /** - * Send REGISTER. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - UserAgentCore.prototype.register = function (request, delegate) { - return new user_agents_1.RegisterUserAgentClient(this, request, delegate); - }; - /** - * Send SUBSCRIBE. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - UserAgentCore.prototype.subscribe = function (request, delegate) { - return new user_agents_1.SubscribeUserAgentClient(this, request, delegate); - }; - /** - * Send a request. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - UserAgentCore.prototype.request = function (request, delegate) { - return new user_agents_1.UserAgentClient(transactions_1.NonInviteClientTransaction, this, request, delegate); - }; - /** - * Outgoing request message factory function. - * @param method - Method. - * @param requestURI - Request-URI. - * @param fromURI - From URI. - * @param toURI - To URI. - * @param options - Request options. - * @param extraHeaders - Extra headers to add. - * @param body - Message body. - */ - UserAgentCore.prototype.makeOutgoingRequestMessage = function (method, requestURI, fromURI, toURI, options, extraHeaders, body) { - // default values from user agent configuration - var callIdPrefix = this.configuration.sipjsId; - var fromDisplayName = this.configuration.displayName; - var forceRport = this.configuration.viaForceRport; - var hackViaTcp = this.configuration.hackViaTcp; - var optionTags = this.configuration.supportedOptionTags.slice(); - if (method === messages_1.C.REGISTER) { - optionTags.push("path", "gruu"); - } - if (method === messages_1.C.INVITE && (this.configuration.contact.pubGruu || this.configuration.contact.tempGruu)) { - optionTags.push("gruu"); - } - var routeSet = this.configuration.routeSet; - var userAgentString = this.configuration.userAgentHeaderFieldValue; - var viaHost = this.configuration.viaHost; - var defaultOptions = { - callIdPrefix: callIdPrefix, - forceRport: forceRport, - fromDisplayName: fromDisplayName, - hackViaTcp: hackViaTcp, - optionTags: optionTags, - routeSet: routeSet, - userAgentString: userAgentString, - viaHost: viaHost, - }; - // merge provided options with default options - var requestOptions = tslib_1.__assign({}, defaultOptions, options); - return new messages_1.OutgoingRequestMessage(method, requestURI, fromURI, toURI, requestOptions, extraHeaders, body); - }; - /** - * Handle an incoming request message from the transport. - * @param message - Incoming request message from transport layer. - */ - UserAgentCore.prototype.receiveIncomingRequestFromTransport = function (message) { - this.receiveRequestFromTransport(message); - }; - /** - * Handle an incoming response message from the transport. - * @param message - Incoming response message from transport layer. - */ - UserAgentCore.prototype.receiveIncomingResponseFromTransport = function (message) { - this.receiveResponseFromTransport(message); - }; - /** - * A stateless UAS is a UAS that does not maintain transaction state. - * It replies to requests normally, but discards any state that would - * ordinarily be retained by a UAS after a response has been sent. If a - * stateless UAS receives a retransmission of a request, it regenerates - * the response and re-sends it, just as if it were replying to the first - * instance of the request. A UAS cannot be stateless unless the request - * processing for that method would always result in the same response - * if the requests are identical. This rules out stateless registrars, - * for example. Stateless UASs do not use a transaction layer; they - * receive requests directly from the transport layer and send responses - * directly to the transport layer. - * https://tools.ietf.org/html/rfc3261#section-8.2.7 - * @param message - Incoming request message to reply to. - * @param statusCode - Status code to reply with. - */ - UserAgentCore.prototype.replyStateless = function (message, options) { - var userAgent = this.configuration.userAgentHeaderFieldValue; - var supported = this.configuration.supportedOptionTagsResponse; - options = tslib_1.__assign({}, options, { userAgent: userAgent, supported: supported }); - var response = messages_1.constructOutgoingResponse(message, options); - this.transport.send(response.message); - return response; - }; - /** - * In Section 18.2.1, replace the last paragraph with: - * - * Next, the server transport attempts to match the request to a - * server transaction. It does so using the matching rules described - * in Section 17.2.3. If a matching server transaction is found, the - * request is passed to that transaction for processing. If no match - * is found, the request is passed to the core, which may decide to - * construct a new server transaction for that request. - * https://tools.ietf.org/html/rfc6026#section-8.10 - * @param message - Incoming request message from transport layer. - */ - UserAgentCore.prototype.receiveRequestFromTransport = function (message) { - // When a request is received from the network by the server, it has to - // be matched to an existing transaction. This is accomplished in the - // following manner. - // - // The branch parameter in the topmost Via header field of the request - // is examined. If it is present and begins with the magic cookie - // "z9hG4bK", the request was generated by a client transaction - // compliant to this specification. Therefore, the branch parameter - // will be unique across all transactions sent by that client. The - // request matches a transaction if: - // - // 1. the branch parameter in the request is equal to the one in the - // top Via header field of the request that created the - // transaction, and - // - // 2. the sent-by value in the top Via of the request is equal to the - // one in the request that created the transaction, and - // - // 3. the method of the request matches the one that created the - // transaction, except for ACK, where the method of the request - // that created the transaction is INVITE. - // - // This matching rule applies to both INVITE and non-INVITE transactions - // alike. - // - // The sent-by value is used as part of the matching process because - // there could be accidental or malicious duplication of branch - // parameters from different clients. - // https://tools.ietf.org/html/rfc3261#section-17.2.3 - var transactionId = message.viaBranch; // FIXME: Currently only using rule 1... - var uas = this.userAgentServers.get(transactionId); - // When receiving an ACK that matches an existing INVITE server - // transaction and that does not contain a branch parameter containing - // the magic cookie defined in RFC 3261, the matching transaction MUST - // be checked to see if it is in the "Accepted" state. If it is, then - // the ACK must be passed directly to the transaction user instead of - // being absorbed by the transaction state machine. This is necessary - // as requests from RFC 2543 clients will not include a unique branch - // parameter, and the mechanisms for calculating the transaction ID from - // such a request will be the same for both INVITE and ACKs. - // https://tools.ietf.org/html/rfc6026#section-6 - // Any ACKs received from the network while in the "Accepted" state MUST be - // passed directly to the TU and not absorbed. - // https://tools.ietf.org/html/rfc6026#section-7.1 - if (message.method === messages_1.C.ACK) { - if (uas && uas.transaction.state === transactions_1.TransactionState.Accepted) { - if (uas instanceof user_agents_1.InviteUserAgentServer) { - // These are ACKs matching an INVITE server transaction. - // These should never happen with RFC 3261 compliant user agents - // (would be a broken ACK to negative final response or something) - // but is apparently how RFC 2543 user agents do things. - // We are not currently supporting this case. - // NOTE: Not backwards compatible with RFC 2543 (no support for strict-routing). - this.logger.warn("Discarding out of dialog ACK after 2xx response sent on transaction " + transactionId + "."); - return; - } - } - } - // The CANCEL method requests that the TU at the server side cancel a - // pending transaction. The TU determines the transaction to be - // cancelled by taking the CANCEL request, and then assuming that the - // request method is anything but CANCEL or ACK and applying the - // transaction matching procedures of Section 17.2.3. The matching - // transaction is the one to be cancelled. - // https://tools.ietf.org/html/rfc3261#section-9.2 - if (message.method === messages_1.C.CANCEL) { - if (uas) { - // Regardless of the method of the original request, as long as the - // CANCEL matched an existing transaction, the UAS answers the CANCEL - // request itself with a 200 (OK) response. - // https://tools.ietf.org/html/rfc3261#section-9.2 - this.replyStateless(message, { statusCode: 200 }); - // If the transaction for the original request still exists, the behavior - // of the UAS on receiving a CANCEL request depends on whether it has already - // sent a final response for the original request. If it has, the CANCEL - // request has no effect on the processing of the original request, no - // effect on any session state, and no effect on the responses generated - // for the original request. If the UAS has not issued a final response - // for the original request, its behavior depends on the method of the - // original request. If the original request was an INVITE, the UAS - // SHOULD immediately respond to the INVITE with a 487 (Request - // Terminated). - // https://tools.ietf.org/html/rfc3261#section-9.2 - if (uas.transaction instanceof transactions_1.InviteServerTransaction && - uas.transaction.state === transactions_1.TransactionState.Proceeding) { - if (uas instanceof user_agents_1.InviteUserAgentServer) { - uas.receiveCancel(message); - } - // A CANCEL request has no impact on the processing of - // transactions with any other method defined in this specification. - // https://tools.ietf.org/html/rfc3261#section-9.2 - } - } - else { - // If the UAS did not find a matching transaction for the CANCEL - // according to the procedure above, it SHOULD respond to the CANCEL - // with a 481 (Call Leg/Transaction Does Not Exist). - // https://tools.ietf.org/html/rfc3261#section-9.2 - this.replyStateless(message, { statusCode: 481 }); - } - return; - } - // If a matching server transaction is found, the request is passed to that - // transaction for processing. - // https://tools.ietf.org/html/rfc6026#section-8.10 - if (uas) { - uas.transaction.receiveRequest(message); - return; - } - // If no match is found, the request is passed to the core, which may decide to - // construct a new server transaction for that request. - // https://tools.ietf.org/html/rfc6026#section-8.10 - this.receiveRequest(message); - return; - }; - /** - * UAC and UAS procedures depend strongly on two factors. First, based - * on whether the request or response is inside or outside of a dialog, - * and second, based on the method of a request. Dialogs are discussed - * thoroughly in Section 12; they represent a peer-to-peer relationship - * between user agents and are established by specific SIP methods, such - * as INVITE. - * @param message - Incoming request message. - */ - UserAgentCore.prototype.receiveRequest = function (message) { - // 8.2 UAS Behavior - // UASs SHOULD process the requests in the order of the steps that - // follow in this section (that is, starting with authentication, then - // inspecting the method, the header fields, and so on throughout the - // remainder of this section). - // https://tools.ietf.org/html/rfc3261#section-8.2 - // 8.2.1 Method Inspection - // Once a request is authenticated (or authentication is skipped), the - // UAS MUST inspect the method of the request. If the UAS recognizes - // but does not support the method of a request, it MUST generate a 405 - // (Method Not Allowed) response. Procedures for generating responses - // are described in Section 8.2.6. The UAS MUST also add an Allow - // header field to the 405 (Method Not Allowed) response. The Allow - // header field MUST list the set of methods supported by the UAS - // generating the message. - // https://tools.ietf.org/html/rfc3261#section-8.2.1 - if (!allowed_methods_1.AllowedMethods.includes(message.method)) { - var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); - this.replyStateless(message, { - statusCode: 405, - extraHeaders: [allowHeader] - }); - return; - } - // 8.2.2 Header Inspection - // https://tools.ietf.org/html/rfc3261#section-8.2.2 - if (!message.ruri) { // FIXME: A request message should always have an ruri - throw new Error("Request-URI undefined."); - } - // 8.2.2.1 To and Request-URI - // If the Request-URI uses a scheme not supported by the UAS, it SHOULD - // reject the request with a 416 (Unsupported URI Scheme) response. - // https://tools.ietf.org/html/rfc3261#section-8.2.2.1 - if (message.ruri.scheme !== "sip") { - this.replyStateless(message, { statusCode: 416 }); - return; - } - // 8.2.2.1 To and Request-URI - // If the Request-URI does not identify an address that the - // UAS is willing to accept requests for, it SHOULD reject - // the request with a 404 (Not Found) response. - // https://tools.ietf.org/html/rfc3261#section-8.2.2.1 - var ruri = message.ruri; - var ruriMatches = function (uri) { - return !!uri && uri.user === ruri.user; - }; - if (!ruriMatches(this.configuration.aor) && - !(ruriMatches(this.configuration.contact.uri) || - ruriMatches(this.configuration.contact.pubGruu) || - ruriMatches(this.configuration.contact.tempGruu))) { - this.logger.warn("Request-URI does not point to us."); - if (message.method !== messages_1.C.ACK) { - this.replyStateless(message, { statusCode: 404 }); - } - return; - } - // 8.2.2.1 To and Request-URI - // Other potential sources of received Request-URIs include - // the Contact header fields of requests and responses sent by the UA - // that establish or refresh dialogs. - // https://tools.ietf.org/html/rfc3261#section-8.2.2.1 - if (message.method === messages_1.C.INVITE) { - if (!message.hasHeader("Contact")) { - this.replyStateless(message, { - statusCode: 400, - reasonPhrase: "Missing Contact Header" - }); - return; - } - } - // 8.2.2.2 Merged Requests - // If the request has no tag in the To header field, the UAS core MUST - // check the request against ongoing transactions. If the From tag, - // Call-ID, and CSeq exactly match those associated with an ongoing - // transaction, but the request does not match that transaction (based - // on the matching rules in Section 17.2.3), the UAS core SHOULD - // generate a 482 (Loop Detected) response and pass it to the server - // transaction. - // - // The same request has arrived at the UAS more than once, following - // different paths, most likely due to forking. The UAS processes - // the first such request received and responds with a 482 (Loop - // Detected) to the rest of them. - // https://tools.ietf.org/html/rfc3261#section-8.2.2.2 - if (!message.toTag) { - var transactionId = message.viaBranch; - if (!this.userAgentServers.has(transactionId)) { - var mergedRequest = Array.from(this.userAgentServers.values()) - .some(function (uas) { - return uas.transaction.request.fromTag === message.fromTag && - uas.transaction.request.callId === message.callId && - uas.transaction.request.cseq === message.cseq; - }); - if (mergedRequest) { - this.replyStateless(message, { statusCode: 482 }); - return; - } - } - } - // 8.2.2.3 Require - // https://tools.ietf.org/html/rfc3261#section-8.2.2.3 - // TODO - // 8.2.3 Content Processing - // https://tools.ietf.org/html/rfc3261#section-8.2.3 - // TODO - // 8.2.4 Applying Extensions - // https://tools.ietf.org/html/rfc3261#section-8.2.4 - // TODO - // 8.2.5 Processing the Request - // Assuming all of the checks in the previous subsections are passed, - // the UAS processing becomes method-specific. - // https://tools.ietf.org/html/rfc3261#section-8.2.5 - // The UAS will receive the request from the transaction layer. If the - // request has a tag in the To header field, the UAS core computes the - // dialog identifier corresponding to the request and compares it with - // existing dialogs. If there is a match, this is a mid-dialog request. - // In that case, the UAS first applies the same processing rules for - // requests outside of a dialog, discussed in Section 8.2. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (message.toTag) { - this.receiveInsideDialogRequest(message); - } - else { - this.receiveOutsideDialogRequest(message); - } - return; - }; - /** - * Once a dialog has been established between two UAs, either of them - * MAY initiate new transactions as needed within the dialog. The UA - * sending the request will take the UAC role for the transaction. The - * UA receiving the request will take the UAS role. Note that these may - * be different roles than the UAs held during the transaction that - * established the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.2 - * @param message - Incoming request message. - */ - UserAgentCore.prototype.receiveInsideDialogRequest = function (message) { - // NOTIFY requests are matched to such SUBSCRIBE requests if they - // contain the same "Call-ID", a "To" header field "tag" parameter that - // matches the "From" header field "tag" parameter of the SUBSCRIBE - // request, and the same "Event" header field. Rules for comparisons of - // the "Event" header fields are described in Section 8.2.1. - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - if (message.method === messages_1.C.NOTIFY) { - var event_1 = message.parseHeader("Event"); - if (!event_1 || !event_1.event) { - this.replyStateless(message, { statusCode: 489 }); - return; - } - // FIXME: Subscriber id should also matching on event id. - var subscriberId = message.callId + message.toTag + event_1.event; - var subscriber = this.subscribers.get(subscriberId); - if (subscriber) { - var uas = new user_agents_1.NotifyUserAgentServer(this, message); - subscriber.onNotify(uas); - return; - } - } - // Requests sent within a dialog, as any other requests, are atomic. If - // a particular request is accepted by the UAS, all the state changes - // associated with it are performed. If the request is rejected, none - // of the state changes are performed. - // - // Note that some requests, such as INVITEs, affect several pieces of - // state. - // - // The UAS will receive the request from the transaction layer. If the - // request has a tag in the To header field, the UAS core computes the - // dialog identifier corresponding to the request and compares it with - // existing dialogs. If there is a match, this is a mid-dialog request. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - var dialogId = message.callId + message.toTag + message.fromTag; - var dialog = this.dialogs.get(dialogId); - if (dialog) { - // [Sip-implementors] Reg. SIP reinvite, UPDATE and OPTIONS - // You got the question right. - // - // And you got the right answer too. :-) - // - // Thanks, - // Paul - // - // Robert Sparks wrote: - // > So I've lost track of the question during the musing. - // > - // > I _think_ the fundamental question being asked is this: - // > - // > Is an endpoint required to reject (with a 481) an OPTIONS request that - // > arrives with at to-tag but does not match any existing dialog state. - // > (Assuming some earlier requirement hasn't forced another error code). Or - // > is it OK if it just sends - // > a 200 OK anyhow. - // > - // > My take on the collection of specs is that its _not_ ok for it to send - // > the 200 OK anyhow and that it is required to send - // > the 481. I base this primarily on these sentences from 11.2 in 3261: - // > - // > The response to an OPTIONS is constructed using the standard rules - // > for a SIP response as discussed in Section 8.2.6. The response code - // > chosen MUST be the same that would have been chosen had the request - // > been an INVITE. - // > - // > Did I miss the point of the question? - // > - // > On May 15, 2008, at 12:48 PM, Paul Kyzivat wrote: - // > - // >> [Including Robert in hopes of getting his insight on this.] - // https://lists.cs.columbia.edu/pipermail/sip-implementors/2008-May/019178.html - // - // Requests that do not change in any way the state of a dialog may be - // received within a dialog (for example, an OPTIONS request). They are - // processed as if they had been received outside the dialog. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (message.method === messages_1.C.OPTIONS) { - var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); - var acceptHeader = "Accept: " + acceptedBodyTypes.toString(); - this.replyStateless(message, { - statusCode: 200, - extraHeaders: [allowHeader, acceptHeader] - }); - return; - } - // Pass the incoming request to the dialog for further handling. - dialog.receiveRequest(message); - return; - } - // The most important behaviors of a stateless UAS are the following: - // ... - // o A stateless UAS MUST ignore ACK requests. - // ... - // https://tools.ietf.org/html/rfc3261#section-8.2.7 - if (message.method === messages_1.C.ACK) { - // If a final response to an INVITE was sent statelessly, - // the corresponding ACK: - // - will not match an existing transaction - // - may have tag in the To header field - // - not not match any existing dialogs - // Absorb unmatched ACKs. - return; - } - // If the request has a tag in the To header field, but the dialog - // identifier does not match any existing dialogs, the UAS may have - // crashed and restarted, or it may have received a request for a - // different (possibly failed) UAS (the UASs can construct the To tags - // so that a UAS can identify that the tag was for a UAS for which it is - // providing recovery). Another possibility is that the incoming - // request has been simply mis-routed. Based on the To tag, the UAS MAY - // either accept or reject the request. Accepting the request for - // acceptable To tags provides robustness, so that dialogs can persist - // even through crashes. UAs wishing to support this capability must - // take into consideration some issues such as choosing monotonically - // increasing CSeq sequence numbers even across reboots, reconstructing - // the route set, and accepting out-of-range RTP timestamps and sequence - // numbers. - // - // If the UAS wishes to reject the request because it does not wish to - // recreate the dialog, it MUST respond to the request with a 481 - // (Call/Transaction Does Not Exist) status code and pass that to the - // server transaction. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - this.replyStateless(message, { statusCode: 481 }); - return; - }; - /** - * Assuming all of the checks in the previous subsections are passed, - * the UAS processing becomes method-specific. - * https://tools.ietf.org/html/rfc3261#section-8.2.5 - * @param message - Incoming request message. - */ - UserAgentCore.prototype.receiveOutsideDialogRequest = function (message) { - switch (message.method) { - case messages_1.C.ACK: - // Absorb stray out of dialog ACKs - break; - case messages_1.C.BYE: - // If the BYE does not match an existing dialog, the UAS core SHOULD - // generate a 481 (Call/Transaction Does Not Exist) response and pass - // that to the server transaction. This rule means that a BYE sent - // without tags by a UAC will be rejected. - // https://tools.ietf.org/html/rfc3261#section-15.1.2 - this.replyStateless(message, { statusCode: 481 }); - break; - case messages_1.C.CANCEL: - throw new Error("Unexpected out of dialog request method " + message.method + "."); - break; - case messages_1.C.INFO: - // Use of the INFO method does not constitute a separate dialog usage. - // INFO messages are always part of, and share the fate of, an invite - // dialog usage [RFC5057]. INFO messages cannot be sent as part of - // other dialog usages, or outside an existing dialog. - // https://tools.ietf.org/html/rfc6086#section-1 - this.replyStateless(message, { statusCode: 405 }); // Should never happen - break; - case messages_1.C.INVITE: - // https://tools.ietf.org/html/rfc3261#section-13.3.1 - { - var uas = new user_agents_1.InviteUserAgentServer(this, message); - this.delegate.onInvite ? - this.delegate.onInvite(uas) : - uas.reject(); - } - break; - case messages_1.C.MESSAGE: - // MESSAGE requests are discouraged inside a dialog. Implementations - // are restricted from creating a usage for the purpose of carrying a - // sequence of MESSAGE requests (though some implementations use it that - // way, against the standard recommendation). - // https://tools.ietf.org/html/rfc5057#section-5.3 - { - var uas = new user_agents_1.MessageUserAgentServer(this, message); - this.delegate.onMessage ? - this.delegate.onMessage(uas) : - uas.accept(); - } - break; - case messages_1.C.NOTIFY: - // Obsoleted by: RFC 6665 - // If any non-SUBSCRIBE mechanisms are defined to create subscriptions, - // it is the responsibility of the parties defining those mechanisms to - // ensure that correlation of a NOTIFY message to the corresponding - // subscription is possible. Designers of such mechanisms are also - // warned to make a distinction between sending a NOTIFY message to a - // subscriber who is aware of the subscription, and sending a NOTIFY - // message to an unsuspecting node. The latter behavior is invalid, and - // MUST receive a "481 Subscription does not exist" response (unless - // some other 400- or 500-class error code is more applicable), as - // described in section 3.2.4. In other words, knowledge of a - // subscription must exist in both the subscriber and the notifier to be - // valid, even if installed via a non-SUBSCRIBE mechanism. - // https://tools.ietf.org/html/rfc3265#section-3.2 - // - // NOTIFY requests are sent to inform subscribers of changes in state to - // which the subscriber has a subscription. Subscriptions are created - // using the SUBSCRIBE method. In legacy implementations, it is - // possible that other means of subscription creation have been used. - // However, this specification does not allow the creation of - // subscriptions except through SUBSCRIBE requests and (for backwards- - // compatibility) REFER requests [RFC3515]. - // https://tools.ietf.org/html/rfc6665#section-3.2 - { - var uas = new user_agents_1.NotifyUserAgentServer(this, message); - this.delegate.onNotify ? - this.delegate.onNotify(uas) : - uas.reject({ statusCode: 405 }); - } - break; - case messages_1.C.OPTIONS: - // https://tools.ietf.org/html/rfc3261#section-11.2 - { - var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); - var acceptHeader = "Accept: " + acceptedBodyTypes.toString(); - this.replyStateless(message, { - statusCode: 200, - extraHeaders: [allowHeader, acceptHeader] - }); - } - break; - case messages_1.C.REFER: - // https://tools.ietf.org/html/rfc3515#section-2.4.2 - { - var uas = new user_agents_1.ReferUserAgentServer(this, message); - this.delegate.onRefer ? - this.delegate.onRefer(uas) : - uas.reject({ statusCode: 405 }); - } - break; - case messages_1.C.REGISTER: - // https://tools.ietf.org/html/rfc3261#section-10.3 - { - var uas = new user_agents_1.RegisterUserAgentServer(this, message); - this.delegate.onRegister ? - this.delegate.onRegister(uas) : - uas.reject({ statusCode: 405 }); - } - break; - case messages_1.C.SUBSCRIBE: - // https://tools.ietf.org/html/rfc6665#section-4.2 - { - var uas = new user_agents_1.SubscribeUserAgentServer(this, message); - this.delegate.onSubscribe ? - this.delegate.onSubscribe(uas) : - uas.reject({ statusCode: 480 }); - } - break; - default: - throw new Error("Unexpected out of dialog request method " + message.method + "."); - } - return; - }; - /** - * Responses are first processed by the transport layer and then passed - * up to the transaction layer. The transaction layer performs its - * processing and then passes the response up to the TU. The majority - * of response processing in the TU is method specific. However, there - * are some general behaviors independent of the method. - * https://tools.ietf.org/html/rfc3261#section-8.1.3 - * @param message - Incoming response message from transport layer. - */ - UserAgentCore.prototype.receiveResponseFromTransport = function (message) { - // 8.1.3.1 Transaction Layer Errors - // https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - // Handled by transaction layer callbacks. - // 8.1.3.2 Unrecognized Responses - // https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - // TODO - // 8.1.3.3 Vias - // https://tools.ietf.org/html/rfc3261#section-8.1.3.3 - if (message.getHeaders("via").length > 1) { - this.logger.warn("More than one Via header field present in the response, dropping"); - return; - } - // 8.1.3.4 Processing 3xx Responses - // https://tools.ietf.org/html/rfc3261#section-8.1.3.4 - // TODO - // 8.1.3.5 Processing 4xx Responses - // https://tools.ietf.org/html/rfc3261#section-8.1.3.5 - // TODO - // When the transport layer in the client receives a response, it has to - // determine which client transaction will handle the response, so that - // the processing of Sections 17.1.1 and 17.1.2 can take place. The - // branch parameter in the top Via header field is used for this - // purpose. A response matches a client transaction under two - // conditions: - // - // 1. If the response has the same value of the branch parameter in - // the top Via header field as the branch parameter in the top - // Via header field of the request that created the transaction. - // - // 2. If the method parameter in the CSeq header field matches the - // method of the request that created the transaction. The - // method is needed since a CANCEL request constitutes a - // different transaction, but shares the same value of the branch - // parameter. - // https://tools.ietf.org/html/rfc3261#section-17.1.3 - var userAgentClientId = message.viaBranch + message.method; - var userAgentClient = this.userAgentClients.get(userAgentClientId); - // The client transport uses the matching procedures of Section - // 17.1.3 to attempt to match the response to an existing - // transaction. If there is a match, the response MUST be passed to - // that transaction. Otherwise, any element other than a stateless - // proxy MUST silently discard the response. - // https://tools.ietf.org/html/rfc6026#section-8.9 - if (userAgentClient) { - userAgentClient.transaction.receiveResponse(message); - } - else { - this.logger.warn("Discarding unmatched " + message.statusCode + " response to " + message.method + " " + userAgentClientId + "."); - } - }; - return UserAgentCore; -}()); -exports.UserAgentCore = UserAgentCore; - - -/***/ }), -/* 66 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -tslib_1.__exportStar(__webpack_require__(41), exports); -tslib_1.__exportStar(__webpack_require__(43), exports); -tslib_1.__exportStar(__webpack_require__(67), exports); -tslib_1.__exportStar(__webpack_require__(45), exports); -tslib_1.__exportStar(__webpack_require__(46), exports); -tslib_1.__exportStar(__webpack_require__(68), exports); -tslib_1.__exportStar(__webpack_require__(69), exports); -tslib_1.__exportStar(__webpack_require__(70), exports); -tslib_1.__exportStar(__webpack_require__(71), exports); -tslib_1.__exportStar(__webpack_require__(47), exports); -tslib_1.__exportStar(__webpack_require__(48), exports); -tslib_1.__exportStar(__webpack_require__(72), exports); -tslib_1.__exportStar(__webpack_require__(49), exports); -tslib_1.__exportStar(__webpack_require__(50), exports); -tslib_1.__exportStar(__webpack_require__(51), exports); -tslib_1.__exportStar(__webpack_require__(52), exports); -tslib_1.__exportStar(__webpack_require__(59), exports); -tslib_1.__exportStar(__webpack_require__(73), exports); -tslib_1.__exportStar(__webpack_require__(53), exports); -tslib_1.__exportStar(__webpack_require__(54), exports); -tslib_1.__exportStar(__webpack_require__(74), exports); -tslib_1.__exportStar(__webpack_require__(75), exports); -tslib_1.__exportStar(__webpack_require__(76), exports); -tslib_1.__exportStar(__webpack_require__(77), exports); -tslib_1.__exportStar(__webpack_require__(42), exports); -tslib_1.__exportStar(__webpack_require__(44), exports); - - -/***/ }), -/* 67 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * CANCEL UAC. - * @public - */ -var CancelUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(CancelUserAgentClient, _super); - function CancelUserAgentClient(core, message, delegate) { - return _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; - } - return CancelUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.CancelUserAgentClient = CancelUserAgentClient; - - -/***/ }), -/* 68 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var dialogs_1 = __webpack_require__(3); -var session_1 = __webpack_require__(24); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * INVITE UAC. - * @remarks - * 13 Initiating a Session - * https://tools.ietf.org/html/rfc3261#section-13 - * 13.1 Overview - * https://tools.ietf.org/html/rfc3261#section-13.1 - * 13.2 UAC Processing - * https://tools.ietf.org/html/rfc3261#section-13.2 - * @public - */ -var InviteUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(InviteUserAgentClient, _super); - function InviteUserAgentClient(core, message, delegate) { - var _this = _super.call(this, transactions_1.InviteClientTransaction, core, message, delegate) || this; - _this.confirmedDialogAcks = new Map(); - _this.confirmedDialogs = new Map(); - _this.earlyDialogs = new Map(); - _this.delegate = delegate; - return _this; - } - InviteUserAgentClient.prototype.dispose = function () { - // The UAC core considers the INVITE transaction completed 64*T1 seconds - // after the reception of the first 2xx response. At this point all the - // early dialogs that have not transitioned to established dialogs are - // terminated. Once the INVITE transaction is considered completed by - // the UAC core, no more new 2xx responses are expected to arrive. - // - // If, after acknowledging any 2xx response to an INVITE, the UAC does - // not want to continue with that dialog, then the UAC MUST terminate - // the dialog by sending a BYE request as described in Section 15. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - this.earlyDialogs.forEach(function (earlyDialog) { return earlyDialog.dispose(); }); - this.earlyDialogs.clear(); - _super.prototype.dispose.call(this); - }; - /** - * Once the INVITE has been passed to the INVITE client transaction, the - * UAC waits for responses for the INVITE. - * https://tools.ietf.org/html/rfc3261#section-13.2.2 - * @param incomingResponse - Incoming response to INVITE request. - */ - InviteUserAgentClient.prototype.receiveResponse = function (message) { - var _this = this; - if (!this.authenticationGuard(message)) { - return; - } - var statusCode = message.statusCode ? message.statusCode.toString() : ""; - if (!statusCode) { - throw new Error("Response status code undefined."); - } - switch (true) { - case /^100$/.test(statusCode): - if (this.delegate && this.delegate.onTrying) { - this.delegate.onTrying({ message: message }); - } - return; - case /^1[0-9]{2}$/.test(statusCode): - // Zero, one or multiple provisional responses may arrive before one or - // more final responses are received. Provisional responses for an - // INVITE request can create "early dialogs". If a provisional response - // has a tag in the To field, and if the dialog ID of the response does - // not match an existing dialog, one is constructed using the procedures - // defined in Section 12.1.2. - // - // The early dialog will only be needed if the UAC needs to send a - // request to its peer within the dialog before the initial INVITE - // transaction completes. Header fields present in a provisional - // response are applicable as long as the dialog is in the early state - // (for example, an Allow header field in a provisional response - // contains the methods that can be used in the dialog while this is in - // the early state). - // https://tools.ietf.org/html/rfc3261#section-13.2.2.1 - { - // Provisional without to tag, no dialog to create. - if (!message.toTag) { - this.logger.warn("Non-100 1xx INVITE response received without a to tag, dropping."); - return; - } - // Compute dialog state. - var dialogState = dialogs_1.Dialog.initialDialogStateForUserAgentClient(this.message, message); - // Have existing early dialog or create a new one. - var earlyDialog = this.earlyDialogs.get(dialogState.id); - if (!earlyDialog) { - var transaction = this.transaction; - if (!(transaction instanceof transactions_1.InviteClientTransaction)) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - earlyDialog = new dialogs_1.SessionDialog(transaction, this.core, dialogState); - this.earlyDialogs.set(earlyDialog.id, earlyDialog); - } - // Guard against out of order reliable provisional responses. - // Note that this is where the rseq tracking is done. - if (!earlyDialog.reliableSequenceGuard(message)) { - this.logger.warn("1xx INVITE reliable response received out of order, dropping."); - return; - } - // If the initial offer is in an INVITE, the answer MUST be in a - // reliable non-failure message from UAS back to UAC which is - // correlated to that INVITE. For this specification, that is - // only the final 2xx response to that INVITE. That same exact - // answer MAY also be placed in any provisional responses sent - // prior to the answer. The UAC MUST treat the first session - // description it receives as the answer, and MUST ignore any - // session descriptions in subsequent responses to the initial - // INVITE. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - if (earlyDialog.signalingState === session_1.SignalingState.Initial || - earlyDialog.signalingState === session_1.SignalingState.HaveLocalOffer) { - earlyDialog.signalingStateTransition(message); - } - // Pass response to delegate. - var session_2 = earlyDialog; - if (this.delegate && this.delegate.onProgress) { - this.delegate.onProgress({ - message: message, - session: session_2, - prack: function (options) { - var outgoingPrackRequest = session_2.prack(undefined, options); - return outgoingPrackRequest; - } - }); - } - } - return; - case /^2[0-9]{2}$/.test(statusCode): - // Multiple 2xx responses may arrive at the UAC for a single INVITE - // request due to a forking proxy. Each response is distinguished by - // the tag parameter in the To header field, and each represents a - // distinct dialog, with a distinct dialog identifier. - // - // If the dialog identifier in the 2xx response matches the dialog - // identifier of an existing dialog, the dialog MUST be transitioned to - // the "confirmed" state, and the route set for the dialog MUST be - // recomputed based on the 2xx response using the procedures of Section - // 12.2.1.2. Otherwise, a new dialog in the "confirmed" state MUST be - // constructed using the procedures of Section 12.1.2. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - { - // Compute dialog state. - var dialogState = dialogs_1.Dialog.initialDialogStateForUserAgentClient(this.message, message); - // NOTE: Currently our transaction layer is caching the 2xx ACKs and - // handling retransmissions of the ACK which is an approach which is - // not to spec. In any event, this block is intended to provide a to - // spec implementation of ACK retransmissions, but it should not be - // hit currently. - var dialog = this.confirmedDialogs.get(dialogState.id); - if (dialog) { - // Once the ACK has been constructed, the procedures of [4] are used to - // determine the destination address, port and transport. However, the - // request is passed to the transport layer directly for transmission, - // rather than a client transaction. This is because the UAC core - // handles retransmissions of the ACK, not the transaction layer. The - // ACK MUST be passed to the client transport every time a - // retransmission of the 2xx final response that triggered the ACK - // arrives. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - var outgoingAckRequest = this.confirmedDialogAcks.get(dialogState.id); - if (outgoingAckRequest) { - var transaction = this.transaction; - if (!(transaction instanceof transactions_1.InviteClientTransaction)) { - throw new Error("Client transaction not instance of InviteClientTransaction."); - } - transaction.ackResponse(outgoingAckRequest.message); - } - else { - // If still waiting for an ACK, drop the retransmission of the 2xx final response. - } - return; - } - // If the dialog identifier in the 2xx response matches the dialog - // identifier of an existing dialog, the dialog MUST be transitioned to - // the "confirmed" state, and the route set for the dialog MUST be - // recomputed based on the 2xx response using the procedures of Section - // 12.2.1.2. Otherwise, a new dialog in the "confirmed" state MUST be - // constructed using the procedures of Section 12.1.2. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - dialog = this.earlyDialogs.get(dialogState.id); - if (dialog) { - dialog.confirm(); - dialog.recomputeRouteSet(message); - this.earlyDialogs.delete(dialog.id); - this.confirmedDialogs.set(dialog.id, dialog); - } - else { - var transaction = this.transaction; - if (!(transaction instanceof transactions_1.InviteClientTransaction)) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - dialog = new dialogs_1.SessionDialog(transaction, this.core, dialogState); - this.confirmedDialogs.set(dialog.id, dialog); - } - // If the initial offer is in an INVITE, the answer MUST be in a - // reliable non-failure message from UAS back to UAC which is - // correlated to that INVITE. For this specification, that is - // only the final 2xx response to that INVITE. That same exact - // answer MAY also be placed in any provisional responses sent - // prior to the answer. The UAC MUST treat the first session - // description it receives as the answer, and MUST ignore any - // session descriptions in subsequent responses to the initial - // INVITE. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - if (dialog.signalingState === session_1.SignalingState.Initial || - dialog.signalingState === session_1.SignalingState.HaveLocalOffer) { - dialog.signalingStateTransition(message); - } - // Session Initiated! :) - var session_3 = dialog; - // The UAC core MUST generate an ACK request for each 2xx received from - // the transaction layer. The header fields of the ACK are constructed - // in the same way as for any request sent within a dialog (see Section - // 12) with the exception of the CSeq and the header fields related to - // authentication. The sequence number of the CSeq header field MUST be - // the same as the INVITE being acknowledged, but the CSeq method MUST - // be ACK. The ACK MUST contain the same credentials as the INVITE. If - // the 2xx contains an offer (based on the rules above), the ACK MUST - // carry an answer in its body. If the offer in the 2xx response is not - // acceptable, the UAC core MUST generate a valid answer in the ACK and - // then send a BYE immediately. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - if (this.delegate && this.delegate.onAccept) { - this.delegate.onAccept({ - message: message, - session: session_3, - ack: function (options) { - var outgoingAckRequest = session_3.ack(options); - _this.confirmedDialogAcks.set(session_3.id, outgoingAckRequest); - return outgoingAckRequest; - } - }); - } - else { - var outgoingAckRequest = session_3.ack(); - this.confirmedDialogAcks.set(session_3.id, outgoingAckRequest); - } - } - return; - case /^3[0-9]{2}$/.test(statusCode): - // 12.3 Termination of a Dialog - // - // Independent of the method, if a request outside of a dialog generates - // a non-2xx final response, any early dialogs created through - // provisional responses to that request are terminated. The mechanism - // for terminating confirmed dialogs is method specific. In this - // specification, the BYE method terminates a session and the dialog - // associated with it. See Section 15 for details. - // https://tools.ietf.org/html/rfc3261#section-12.3 - // All early dialogs are considered terminated upon reception of the - // non-2xx final response. - // - // After having received the non-2xx final response the UAC core - // considers the INVITE transaction completed. The INVITE client - // transaction handles the generation of ACKs for the response (see - // Section 17). - // https://tools.ietf.org/html/rfc3261#section-13.2.2.3 - this.earlyDialogs.forEach(function (earlyDialog) { return earlyDialog.dispose(); }); - this.earlyDialogs.clear(); - // A 3xx response may contain one or more Contact header field values - // providing new addresses where the callee might be reachable. - // Depending on the status code of the 3xx response (see Section 21.3), - // the UAC MAY choose to try those new addresses. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.2 - if (this.delegate && this.delegate.onRedirect) { - this.delegate.onRedirect({ message: message }); - } - return; - case /^[4-6][0-9]{2}$/.test(statusCode): - // 12.3 Termination of a Dialog - // - // Independent of the method, if a request outside of a dialog generates - // a non-2xx final response, any early dialogs created through - // provisional responses to that request are terminated. The mechanism - // for terminating confirmed dialogs is method specific. In this - // specification, the BYE method terminates a session and the dialog - // associated with it. See Section 15 for details. - // https://tools.ietf.org/html/rfc3261#section-12.3 - // All early dialogs are considered terminated upon reception of the - // non-2xx final response. - // - // After having received the non-2xx final response the UAC core - // considers the INVITE transaction completed. The INVITE client - // transaction handles the generation of ACKs for the response (see - // Section 17). - // https://tools.ietf.org/html/rfc3261#section-13.2.2.3 - this.earlyDialogs.forEach(function (earlyDialog) { return earlyDialog.dispose(); }); - this.earlyDialogs.clear(); - // A single non-2xx final response may be received for the INVITE. 4xx, - // 5xx and 6xx responses may contain a Contact header field value - // indicating the location where additional information about the error - // can be found. Subsequent final responses (which would only arrive - // under error conditions) MUST be ignored. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.3 - if (this.delegate && this.delegate.onReject) { - this.delegate.onReject({ message: message }); - } - return; - default: - throw new Error("Invalid status code " + statusCode); - } - throw new Error("Executing what should be an unreachable code path receiving " + statusCode + " response."); - }; - return InviteUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.InviteUserAgentClient = InviteUserAgentClient; - - -/***/ }), -/* 69 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var dialogs_1 = __webpack_require__(3); -var exceptions_1 = __webpack_require__(31); -var session_1 = __webpack_require__(24); -var transactions_1 = __webpack_require__(27); -var allowed_methods_1 = __webpack_require__(58); -var user_agent_server_1 = __webpack_require__(44); -/** - * INVITE UAS. - * @remarks - * 13 Initiating a Session - * https://tools.ietf.org/html/rfc3261#section-13 - * 13.1 Overview - * https://tools.ietf.org/html/rfc3261#section-13.1 - * 13.3 UAS Processing - * https://tools.ietf.org/html/rfc3261#section-13.3 - * @public - */ -var InviteUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(InviteUserAgentServer, _super); - function InviteUserAgentServer(core, message, delegate) { - var _this = _super.call(this, transactions_1.InviteServerTransaction, core, message, delegate) || this; - _this.core = core; - return _this; - } - InviteUserAgentServer.prototype.dispose = function () { - if (this.earlyDialog) { - this.earlyDialog.dispose(); - } - _super.prototype.dispose.call(this); - }; - /** - * 13.3.1.4 The INVITE is Accepted - * The UAS core generates a 2xx response. This response establishes a - * dialog, and therefore follows the procedures of Section 12.1.1 in - * addition to those of Section 8.2.6. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - * @param options - Accept options bucket. - */ - InviteUserAgentServer.prototype.accept = function (options) { - if (options === void 0) { options = { statusCode: 200 }; } - if (!this.acceptable) { - throw new exceptions_1.TransactionStateError(this.message.method + " not acceptable in state " + this.transaction.state + "."); - } - // This response establishes a dialog... - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - if (!this.confirmedDialog) { - if (this.earlyDialog) { - this.earlyDialog.confirm(); - this.confirmedDialog = this.earlyDialog; - this.earlyDialog = undefined; - } - else { - var transaction = this.transaction; - if (!(transaction instanceof transactions_1.InviteServerTransaction)) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - var state = dialogs_1.Dialog.initialDialogStateForUserAgentServer(this.message, this.toTag); - this.confirmedDialog = new dialogs_1.SessionDialog(transaction, this.core, state); - } - } - // When a UAS responds to a request with a response that establishes a - // dialog (such as a 2xx to INVITE), the UAS MUST copy all Record-Route - // header field values from the request into the response (including the - // URIs, URI parameters, and any Record-Route header field parameters, - // whether they are known or unknown to the UAS) and MUST maintain the - // order of those values. The UAS MUST add a Contact header field to - // the response. The Contact header field contains an address where the - // UAS would like to be contacted for subsequent requests in the dialog - // (which includes the ACK for a 2xx response in the case of an INVITE). - // Generally, the host portion of this URI is the IP address or FQDN of - // the host. The URI provided in the Contact header field MUST be a SIP - // or SIPS URI. If the request that initiated the dialog contained a - // SIPS URI in the Request-URI or in the top Record-Route header field - // value, if there was any, or the Contact header field if there was no - // Record-Route header field, the Contact header field in the response - // MUST be a SIPS URI. The URI SHOULD have global scope (that is, the - // same URI can be used in messages outside this dialog). The same way, - // the scope of the URI in the Contact header field of the INVITE is not - // limited to this dialog either. It can therefore be used in messages - // to the UAC even outside this dialog. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - var recordRouteHeader = this.message - .getHeaders("record-route") - .map(function (header) { return "Record-Route: " + header; }); - var contactHeader = "Contact: " + this.core.configuration.contact.toString(); - // A 2xx response to an INVITE SHOULD contain the Allow header field and - // the Supported header field, and MAY contain the Accept header field. - // Including these header fields allows the UAC to determine the - // features and extensions supported by the UAS for the duration of the - // call, without probing. - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - // FIXME: TODO: This should not be hard coded. - var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); - // FIXME: TODO: Supported header (see reply()) - // FIXME: TODO: Accept header - // If the INVITE request contained an offer, and the UAS had not yet - // sent an answer, the 2xx MUST contain an answer. If the INVITE did - // not contain an offer, the 2xx MUST contain an offer if the UAS had - // not yet sent an offer. - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - if (!options.body) { - if (this.confirmedDialog.signalingState === session_1.SignalingState.Stable) { - options.body = this.confirmedDialog.answer; // resend the answer sent in provisional response - } - else if (this.confirmedDialog.signalingState === session_1.SignalingState.Initial || - this.confirmedDialog.signalingState === session_1.SignalingState.HaveRemoteOffer) { - throw new Error("Response must have a body."); - } - } - options.statusCode = options.statusCode || 200; - options.extraHeaders = options.extraHeaders || []; - options.extraHeaders = options.extraHeaders.concat(recordRouteHeader); - options.extraHeaders.push(allowHeader); - options.extraHeaders.push(contactHeader); - var response = _super.prototype.accept.call(this, options); - var session = this.confirmedDialog; - var result = tslib_1.__assign({}, response, { session: session }); - // Update dialog signaling state - if (options.body) { - // Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - if (this.confirmedDialog.signalingState !== session_1.SignalingState.Stable) { - this.confirmedDialog.signalingStateTransition(options.body); - } - } - return result; - }; - /** - * 13.3.1.1 Progress - * If the UAS is not able to answer the invitation immediately, it can - * choose to indicate some kind of progress to the UAC (for example, an - * indication that a phone is ringing). This is accomplished with a - * provisional response between 101 and 199. These provisional - * responses establish early dialogs and therefore follow the procedures - * of Section 12.1.1 in addition to those of Section 8.2.6. A UAS MAY - * send as many provisional responses as it likes. Each of these MUST - * indicate the same dialog ID. However, these will not be delivered - * reliably. - * - * If the UAS desires an extended period of time to answer the INVITE, - * it will need to ask for an "extension" in order to prevent proxies - * from canceling the transaction. A proxy has the option of canceling - * a transaction when there is a gap of 3 minutes between responses in a - * transaction. To prevent cancellation, the UAS MUST send a non-100 - * provisional response at every minute, to handle the possibility of - * lost provisional responses. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.1 - * @param options - Progress options bucket. - */ - InviteUserAgentServer.prototype.progress = function (options) { - if (options === void 0) { options = { statusCode: 180 }; } - if (!this.progressable) { - throw new exceptions_1.TransactionStateError(this.message.method + " not progressable in state " + this.transaction.state + "."); - } - // This response establishes a dialog... - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - if (!this.earlyDialog) { - var transaction = this.transaction; - if (!(transaction instanceof transactions_1.InviteServerTransaction)) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - var state = dialogs_1.Dialog.initialDialogStateForUserAgentServer(this.message, this.toTag, true); - this.earlyDialog = new dialogs_1.SessionDialog(transaction, this.core, state); - } - // When a UAS responds to a request with a response that establishes a - // dialog (such as a 2xx to INVITE), the UAS MUST copy all Record-Route - // header field values from the request into the response (including the - // URIs, URI parameters, and any Record-Route header field parameters, - // whether they are known or unknown to the UAS) and MUST maintain the - // order of those values. The UAS MUST add a Contact header field to - // the response. The Contact header field contains an address where the - // UAS would like to be contacted for subsequent requests in the dialog - // (which includes the ACK for a 2xx response in the case of an INVITE). - // Generally, the host portion of this URI is the IP address or FQDN of - // the host. The URI provided in the Contact header field MUST be a SIP - // or SIPS URI. If the request that initiated the dialog contained a - // SIPS URI in the Request-URI or in the top Record-Route header field - // value, if there was any, or the Contact header field if there was no - // Record-Route header field, the Contact header field in the response - // MUST be a SIPS URI. The URI SHOULD have global scope (that is, the - // same URI can be used in messages outside this dialog). The same way, - // the scope of the URI in the Contact header field of the INVITE is not - // limited to this dialog either. It can therefore be used in messages - // to the UAC even outside this dialog. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - var recordRouteHeader = this.message - .getHeaders("record-route") - .map(function (header) { return "Record-Route: " + header; }); - var contactHeader = "Contact: " + this.core.configuration.contact; - options.extraHeaders = options.extraHeaders || []; - options.extraHeaders = options.extraHeaders.concat(recordRouteHeader); - options.extraHeaders.push(contactHeader); - var response = _super.prototype.progress.call(this, options); - var session = this.earlyDialog; - var result = tslib_1.__assign({}, response, { session: session }); - // Update dialog signaling state - if (options.body) { - // Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - if (this.earlyDialog.signalingState !== session_1.SignalingState.Stable) { - this.earlyDialog.signalingStateTransition(options.body); - } - } - return result; - }; - /** - * 13.3.1.2 The INVITE is Redirected - * If the UAS decides to redirect the call, a 3xx response is sent. A - * 300 (Multiple Choices), 301 (Moved Permanently) or 302 (Moved - * Temporarily) response SHOULD contain a Contact header field - * containing one or more URIs of new addresses to be tried. The - * response is passed to the INVITE server transaction, which will deal - * with its retransmissions. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.2 - * @param contacts - Contacts to redirect to. - * @param options - Redirect options bucket. - */ - InviteUserAgentServer.prototype.redirect = function (contacts, options) { - if (options === void 0) { options = { statusCode: 302 }; } - return _super.prototype.redirect.call(this, contacts, options); - }; - /** - * 13.3.1.3 The INVITE is Rejected - * A common scenario occurs when the callee is currently not willing or - * able to take additional calls at this end system. A 486 (Busy Here) - * SHOULD be returned in such a scenario. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.3 - * @param options - Reject options bucket. - */ - InviteUserAgentServer.prototype.reject = function (options) { - if (options === void 0) { options = { statusCode: 486 }; } - return _super.prototype.reject.call(this, options); - }; - return InviteUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.InviteUserAgentServer = InviteUserAgentServer; - - -/***/ }), -/* 70 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * MESSAGE UAS. - * @public - */ -var MessageUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(MessageUserAgentClient, _super); - function MessageUserAgentClient(core, message, delegate) { - return _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; - } - return MessageUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.MessageUserAgentClient = MessageUserAgentClient; - - -/***/ }), -/* 71 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * MESSAGE UAS. - * @public - */ -var MessageUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(MessageUserAgentServer, _super); - function MessageUserAgentServer(core, message, delegate) { - var _this = _super.call(this, transactions_1.NonInviteServerTransaction, core, message, delegate) || this; - _this.core = core; - return _this; - } - return MessageUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.MessageUserAgentServer = MessageUserAgentServer; - - -/***/ }), -/* 72 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * PUBLISH UAC. - * @public - */ -var PublishUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(PublishUserAgentClient, _super); - function PublishUserAgentClient(core, message, delegate) { - return _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; - } - return PublishUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.PublishUserAgentClient = PublishUserAgentClient; - - -/***/ }), -/* 73 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * Re-SUBSCRIBE UAS. - * @public - */ -var ReSubscribeUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(ReSubscribeUserAgentServer, _super); - function ReSubscribeUserAgentServer(dialog, message, delegate) { - return _super.call(this, transactions_1.NonInviteServerTransaction, dialog.userAgentCore, message, delegate) || this; - } - return ReSubscribeUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.ReSubscribeUserAgentServer = ReSubscribeUserAgentServer; - - -/***/ }), -/* 74 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * REGISTER UAC. - * @public - */ -var RegisterUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(RegisterUserAgentClient, _super); - function RegisterUserAgentClient(core, message, delegate) { - return _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; - } - return RegisterUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.RegisterUserAgentClient = RegisterUserAgentClient; - - -/***/ }), -/* 75 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * REGISTER UAS. - * @public - */ -var RegisterUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(RegisterUserAgentServer, _super); - function RegisterUserAgentServer(core, message, delegate) { - var _this = _super.call(this, transactions_1.NonInviteServerTransaction, core, message, delegate) || this; - _this.core = core; - return _this; - } - return RegisterUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.RegisterUserAgentServer = RegisterUserAgentServer; - - -/***/ }), -/* 76 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var subscription_dialog_1 = __webpack_require__(55); -var subscription_1 = __webpack_require__(56); -var timers_1 = __webpack_require__(26); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * SUBSCRIBE UAC. - * @remarks - * 4.1. Subscriber Behavior - * https://tools.ietf.org/html/rfc6665#section-4.1 - * - * User agent client for installation of a single subscription per SUBSCRIBE request. - * TODO: Support for installation of multiple subscriptions on forked SUBSCRIBE reqeuests. - * @public - */ -var SubscribeUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(SubscribeUserAgentClient, _super); - function SubscribeUserAgentClient(core, message, delegate) { - var _this = this; - // Get event from request message. - var event = message.getHeader("Event"); - if (!event) { - throw new Error("Event undefined"); - } - // Get expires from reqeust message. - var expires = message.getHeader("Expires"); - if (!expires) { - throw new Error("Expires undefined"); - } - _this = _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; - _this.delegate = delegate; - // FIXME: Subscriber id should also be matching on event id. - _this.subscriberId = message.callId + message.fromTag + event; - _this.subscriptionExpiresRequested = _this.subscriptionExpires = Number(expires); - _this.subscriptionEvent = event; - _this.subscriptionState = subscription_1.SubscriptionState.NotifyWait; - // Start waiting for a NOTIFY we can use to create a subscription. - _this.waitNotifyStart(); - return _this; - } - /** - * Destructor. - * Note that Timer N may live on waiting for an initial NOTIFY and - * the delegate may still receive that NOTIFY. If you don't want - * that behavior then either clear the delegate so the delegate - * doesn't get called (a 200 will be sent in response to the NOTIFY) - * or call `waitNotifyStop` which will clear Timer N and remove this - * UAC from the core (a 481 will be sent in response to the NOTIFY). - */ - SubscribeUserAgentClient.prototype.dispose = function () { - _super.prototype.dispose.call(this); - }; - /** - * Handle out of dialog NOTIFY assoicated with SUBSCRIBE request. - * This is the first NOTIFY received after the SUBSCRIBE request. - * @param uas - User agent server handling the subscription creating NOTIFY. - */ - SubscribeUserAgentClient.prototype.onNotify = function (uas) { - // NOTIFY requests are matched to such SUBSCRIBE requests if they - // contain the same "Call-ID", a "To" header field "tag" parameter that - // matches the "From" header field "tag" parameter of the SUBSCRIBE - // request, and the same "Event" header field. Rules for comparisons of - // the "Event" header fields are described in Section 8.2.1. - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - var event = uas.message.parseHeader("Event").event; - if (!event || event !== this.subscriptionEvent) { - this.logger.warn("Failed to parse event."); - uas.reject({ statusCode: 489 }); - return; - } - // NOTIFY requests MUST contain "Subscription-State" header fields that - // indicate the status of the subscription. - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - var subscriptionState = uas.message.parseHeader("Subscription-State"); - if (!subscriptionState || !subscriptionState.state) { - this.logger.warn("Failed to parse subscription state."); - uas.reject({ statusCode: 489 }); - return; - } - // Validate subscription state. - var state = subscriptionState.state; - switch (state) { - case "pending": - break; - case "active": - break; - case "terminated": - break; - default: - this.logger.warn("Invalid subscription state " + state); - uas.reject({ statusCode: 489 }); - return; - } - // Dialogs usages are created upon completion of a NOTIFY transaction - // for a new subscription, unless the NOTIFY request contains a - // "Subscription-State" of "terminated." - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - if (state !== "terminated") { - // The Contact header field MUST be present and contain exactly one SIP - // or SIPS URI in any request that can result in the establishment of a - // dialog. - // https://tools.ietf.org/html/rfc3261#section-8.1.1.8 - var contact = uas.message.parseHeader("contact"); - if (!contact) { - this.logger.warn("Failed to parse contact."); - uas.reject({ statusCode: 489 }); - return; - } - } - // In accordance with the rules for proxying non-INVITE requests as - // defined in [RFC3261], successful SUBSCRIBE requests will receive only - // one 200-class response; however, due to forking, the subscription may - // have been accepted by multiple nodes. The subscriber MUST therefore - // be prepared to receive NOTIFY requests with "From:" tags that differ - // from the "To:" tag received in the SUBSCRIBE 200-class response. - // - // If multiple NOTIFY requests are received in different dialogs in - // response to a single SUBSCRIBE request, each dialog represents a - // different destination to which the SUBSCRIBE request was forked. - // Subscriber handling in such situations varies by event package; see - // Section 5.4.9 for details. - // https://tools.ietf.org/html/rfc6665#section-4.1.4 - // Each event package MUST specify whether forked SUBSCRIBE requests are - // allowed to install multiple subscriptions. - // - // If such behavior is not allowed, the first potential dialog- - // establishing message will create a dialog. All subsequent NOTIFY - // requests that correspond to the SUBSCRIBE request (i.e., have - // matching "To", "From", "Call-ID", and "Event" header fields, as well - // as "From" header field "tag" parameter and "Event" header field "id" - // parameter) but that do not match the dialog would be rejected with a - // 481 response. Note that the 200-class response to the SUBSCRIBE - // request can arrive after a matching NOTIFY request has been received; - // such responses might not correlate to the same dialog established by - // the NOTIFY request. Except as required to complete the SUBSCRIBE - // transaction, such non-matching 200-class responses are ignored. - // - // If installing of multiple subscriptions by way of a single forked - // SUBSCRIBE request is allowed, the subscriber establishes a new dialog - // towards each notifier by returning a 200-class response to each - // NOTIFY request. Each dialog is then handled as its own entity and is - // refreshed independently of the other dialogs. - // - // In the case that multiple subscriptions are allowed, the event - // package MUST specify whether merging of the notifications to form a - // single state is required, and how such merging is to be performed. - // Note that it is possible that some event packages may be defined in - // such a way that each dialog is tied to a mutually exclusive state - // that is unaffected by the other dialogs; this MUST be clearly stated - // if it is the case. - // https://tools.ietf.org/html/rfc6665#section-5.4.9 - // *** NOTE: This implementation is only for event packages which - // do not allow forked requests to install muliple subscriptions. - // As such and in accordance with the specificaiton, we stop waiting - // and any future NOTIFY requests will be rejected with a 481. - if (this.dialog) { - throw new Error("Dialog already created. This implementation only supports install of single subscriptions."); - } - this.waitNotifyStop(); - // Update expires. - this.subscriptionExpires = - subscriptionState.expires ? - Math.min(this.subscriptionExpires, Math.max(subscriptionState.expires, 0)) : - this.subscriptionExpires; - // Update subscriptoin state. - switch (state) { - case "pending": - this.subscriptionState = subscription_1.SubscriptionState.Pending; - break; - case "active": - this.subscriptionState = subscription_1.SubscriptionState.Active; - break; - case "terminated": - this.subscriptionState = subscription_1.SubscriptionState.Terminated; - break; - default: - throw new Error("Unrecognized state " + state + "."); - } - // Dialogs usages are created upon completion of a NOTIFY transaction - // for a new subscription, unless the NOTIFY request contains a - // "Subscription-State" of "terminated." - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - if (this.subscriptionState !== subscription_1.SubscriptionState.Terminated) { - // Because the dialog usage is established by the NOTIFY request, the - // route set at the subscriber is taken from the NOTIFY request itself, - // as opposed to the route set present in the 200-class response to the - // SUBSCRIBE request. - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - var dialogState = subscription_dialog_1.SubscriptionDialog.initialDialogStateForSubscription(this.message, uas.message); - // Subscription Initiated! :) - this.dialog = new subscription_dialog_1.SubscriptionDialog(this.subscriptionEvent, this.subscriptionExpires, this.subscriptionState, this.core, dialogState); - } - // Delegate. - if (this.delegate && this.delegate.onNotify) { - var request = uas; - var subscription = this.dialog; - this.delegate.onNotify({ request: request, subscription: subscription }); - } - else { - uas.accept(); - } - }; - SubscribeUserAgentClient.prototype.waitNotifyStart = function () { - var _this = this; - if (!this.N) { - // Add ourselves to the core's subscriber map. - // This allows the core to route out of dialog NOTIFY messages to us. - this.core.subscribers.set(this.subscriberId, this); - this.N = setTimeout(function () { return _this.timer_N(); }, timers_1.Timers.TIMER_N); - } - }; - SubscribeUserAgentClient.prototype.waitNotifyStop = function () { - if (this.N) { - // Remove ourselves to the core's subscriber map. - // Any future out of dialog NOTIFY messages will be rejected with a 481. - this.core.subscribers.delete(this.subscriberId); - clearTimeout(this.N); - this.N = undefined; - } - }; - /** - * Receive a response from the transaction layer. - * @param message - Incoming response message. - */ - SubscribeUserAgentClient.prototype.receiveResponse = function (message) { - if (!this.authenticationGuard(message)) { - return; - } - if (message.statusCode && message.statusCode >= 200 && message.statusCode < 300) { - // The "Expires" header field in a 200-class response to SUBSCRIBE - // request indicates the actual duration for which the subscription will - // remain active (unless refreshed). The received value might be - // smaller than the value indicated in the SUBSCRIBE request but cannot - // be larger; see Section 4.2.1 for details. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - // The "Expires" values present in SUBSCRIBE 200-class responses behave - // in the same way as they do in REGISTER responses: the server MAY - // shorten the interval but MUST NOT lengthen it. - // - // If the duration specified in a SUBSCRIBE request is unacceptably - // short, the notifier may be able to send a 423 response, as - // described earlier in this section. - // - // 200-class responses to SUBSCRIBE requests will not generally contain - // any useful information beyond subscription duration; their primary - // purpose is to serve as a reliability mechanism. State information - // will be communicated via a subsequent NOTIFY request from the - // notifier. - // https://tools.ietf.org/html/rfc6665#section-4.2.1.1 - var expires = message.getHeader("Expires"); - if (!expires) { - this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE"); - } - else { - var subscriptionExpiresReceived = Number(expires); - if (subscriptionExpiresReceived > this.subscriptionExpiresRequested) { - this.logger.warn("Expires header in a 200-class response to SUBSCRIBE with a higher value than the one in the request"); - } - if (subscriptionExpiresReceived < this.subscriptionExpires) { - this.subscriptionExpires = subscriptionExpiresReceived; - } - } - // If a NOTIFY arrived before 200-class response a dialog may have been created. - // Updated the dialogs expiration only if this indicates earlier expiration. - if (this.dialog) { - if (this.dialog.subscriptionExpires > this.subscriptionExpires) { - this.dialog.subscriptionExpires = this.subscriptionExpires; - } - } - } - if (message.statusCode && message.statusCode >= 300 && message.statusCode < 700) { - this.waitNotifyStop(); // No NOTIFY will be sent after a negative final response. - } - _super.prototype.receiveResponse.call(this, message); - }; - /** - * To ensure that subscribers do not wait indefinitely for a - * subscription to be established, a subscriber starts a Timer N, set to - * 64*T1, when it sends a SUBSCRIBE request. If this Timer N expires - * prior to the receipt of a NOTIFY request, the subscriber considers - * the subscription failed, and cleans up any state associated with the - * subscription attempt. - * https://tools.ietf.org/html/rfc6665#section-4.1.2.4 - */ - SubscribeUserAgentClient.prototype.timer_N = function () { - this.logger.warn("Timer N expired for SUBSCRIBE user agent client. Timed out waiting for NOTIFY."); - this.waitNotifyStop(); - if (this.delegate && this.delegate.onNotifyTimeout) { - this.delegate.onNotifyTimeout(); - } - }; - return SubscribeUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.SubscribeUserAgentClient = SubscribeUserAgentClient; - - -/***/ }), -/* 77 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * SUBSCRIBE UAS. - * @public - */ -var SubscribeUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(SubscribeUserAgentServer, _super); - function SubscribeUserAgentServer(core, message, delegate) { - var _this = _super.call(this, transactions_1.NonInviteServerTransaction, core, message, delegate) || this; - _this.core = core; - return _this; - } - return SubscribeUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.SubscribeUserAgentServer = SubscribeUserAgentServer; - - -/***/ }), -/* 78 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var events_1 = __webpack_require__(30); -/** - * Transport. - * @remarks - * Abstract transport layer base class. - * @public - */ -var Transport = /** @class */ (function (_super) { - tslib_1.__extends(Transport, _super); - /** - * Constructor - * @param logger - Logger. - * @param options - Options bucket. - */ - function Transport(logger, options) { - var _this = _super.call(this) || this; - _this.logger = logger; - return _this; - } - /** - * Returns the promise designated by the child layer then emits a connected event. - * Automatically emits an event upon resolution, unless overrideEvent is set. If you - * override the event in this fashion, you should emit it in your implementation of connectPromise - * @param options - Options bucket. - */ - Transport.prototype.connect = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - return this.connectPromise(options).then(function (data) { - if (!data.overrideEvent) { - _this.emit("connected"); - } - }); - }; - /** - * Sends a message then emits a 'messageSent' event. Automatically emits an - * event upon resolution, unless data.overrideEvent is set. If you override - * the event in this fashion, you should emit it in your implementation of sendPromise - * @param msg - Message. - * @param options - Options bucket. - */ - Transport.prototype.send = function (msg, options) { - var _this = this; - if (options === void 0) { options = {}; } - return this.sendPromise(msg).then(function (data) { - if (!data.overrideEvent) { - _this.emit("messageSent", data.msg); - } - }); - }; - /** - * Returns the promise designated by the child layer then emits a - * disconnected event. Automatically emits an event upon resolution, - * unless overrideEvent is set. If you override the event in this fashion, - * you should emit it in your implementation of disconnectPromise - * @param options - Options bucket - */ - Transport.prototype.disconnect = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - return this.disconnectPromise(options).then(function (data) { - if (!data.overrideEvent) { - _this.emit("disconnected"); - } - }); - }; - Transport.prototype.afterConnected = function (callback) { - if (this.isConnected()) { - callback(); - } - else { - this.once("connected", callback); - } - }; - /** - * Returns a promise which resolves once the UA is connected. DEPRECATION WARNING: just use afterConnected() - */ - Transport.prototype.waitForConnected = function () { - var _this = this; - // tslint:disable-next-line:no-console - console.warn("DEPRECATION WARNING Transport.waitForConnected(): use afterConnected() instead"); - return new Promise(function (resolve) { - _this.afterConnected(resolve); - }); - }; - return Transport; -}(events_1.EventEmitter)); -exports.Transport = Transport; - - -/***/ }), -/* 79 */, -/* 80 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var version_1 = __webpack_require__(81); -var C; -(function (C) { - C.version = version_1.LIBRARY_VERSION; - C.USER_AGENT = "SIP.js/" + version_1.LIBRARY_VERSION; - // SIP scheme - C.SIP = "sip"; - C.SIPS = "sips"; - // End and Failure causes - var causes; - (function (causes) { - // Generic error causes - causes["CONNECTION_ERROR"] = "Connection Error"; - causes["INTERNAL_ERROR"] = "Internal Error"; - causes["REQUEST_TIMEOUT"] = "Request Timeout"; - causes["SIP_FAILURE_CODE"] = "SIP Failure Code"; - // SIP error causes - causes["ADDRESS_INCOMPLETE"] = "Address Incomplete"; - causes["AUTHENTICATION_ERROR"] = "Authentication Error"; - causes["BUSY"] = "Busy"; - causes["DIALOG_ERROR"] = "Dialog Error"; - causes["INCOMPATIBLE_SDP"] = "Incompatible SDP"; - causes["NOT_FOUND"] = "Not Found"; - causes["REDIRECTED"] = "Redirected"; - causes["REJECTED"] = "Rejected"; - causes["UNAVAILABLE"] = "Unavailable"; - // Session error causes - causes["BAD_MEDIA_DESCRIPTION"] = "Bad Media Description"; - causes["CANCELED"] = "Canceled"; - causes["EXPIRES"] = "Expires"; - causes["NO_ACK"] = "No ACK"; - causes["NO_ANSWER"] = "No Answer"; - causes["NO_PRACK"] = "No PRACK"; - causes["RTP_TIMEOUT"] = "RTP Timeout"; - causes["USER_DENIED_MEDIA_ACCESS"] = "User Denied Media Access"; - causes["WEBRTC_ERROR"] = "WebRTC Error"; - causes["WEBRTC_NOT_SUPPORTED"] = "WebRTC Not Supported"; - })(causes = C.causes || (C.causes = {})); - var supported; - (function (supported) { - supported["REQUIRED"] = "required"; - supported["SUPPORTED"] = "supported"; - supported["UNSUPPORTED"] = "none"; - })(supported = C.supported || (C.supported = {})); - C.SIP_ERROR_CAUSES = { - ADDRESS_INCOMPLETE: [484], - AUTHENTICATION_ERROR: [401, 407], - BUSY: [486, 600], - INCOMPATIBLE_SDP: [488, 606], - NOT_FOUND: [404, 604], - REDIRECTED: [300, 301, 302, 305, 380], - REJECTED: [403, 603], - UNAVAILABLE: [480, 410, 408, 430] - }; - // SIP Methods - C.ACK = "ACK"; - C.BYE = "BYE"; - C.CANCEL = "CANCEL"; - C.INFO = "INFO"; - C.INVITE = "INVITE"; - C.MESSAGE = "MESSAGE"; - C.NOTIFY = "NOTIFY"; - C.OPTIONS = "OPTIONS"; - C.REGISTER = "REGISTER"; - C.UPDATE = "UPDATE"; - C.SUBSCRIBE = "SUBSCRIBE"; - C.PUBLISH = "PUBLISH"; - C.REFER = "REFER"; - C.PRACK = "PRACK"; - /* SIP Response Reasons - * DOC: http://www.iana.org/assignments/sip-parameters - * Copied from https://github.com/versatica/OverSIP/blob/master/lib/oversip/sip/constants.rb#L7 - */ - C.REASON_PHRASE = { - 100: "Trying", - 180: "Ringing", - 181: "Call Is Being Forwarded", - 182: "Queued", - 183: "Session Progress", - 199: "Early Dialog Terminated", - 200: "OK", - 202: "Accepted", - 204: "No Notification", - 300: "Multiple Choices", - 301: "Moved Permanently", - 302: "Moved Temporarily", - 305: "Use Proxy", - 380: "Alternative Service", - 400: "Bad Request", - 401: "Unauthorized", - 402: "Payment Required", - 403: "Forbidden", - 404: "Not Found", - 405: "Method Not Allowed", - 406: "Not Acceptable", - 407: "Proxy Authentication Required", - 408: "Request Timeout", - 410: "Gone", - 412: "Conditional Request Failed", - 413: "Request Entity Too Large", - 414: "Request-URI Too Long", - 415: "Unsupported Media Type", - 416: "Unsupported URI Scheme", - 417: "Unknown Resource-Priority", - 420: "Bad Extension", - 421: "Extension Required", - 422: "Session Interval Too Small", - 423: "Interval Too Brief", - 428: "Use Identity Header", - 429: "Provide Referrer Identity", - 430: "Flow Failed", - 433: "Anonymity Disallowed", - 436: "Bad Identity-Info", - 437: "Unsupported Certificate", - 438: "Invalid Identity Header", - 439: "First Hop Lacks Outbound Support", - 440: "Max-Breadth Exceeded", - 469: "Bad Info Package", - 470: "Consent Needed", - 478: "Unresolvable Destination", - 480: "Temporarily Unavailable", - 481: "Call/Transaction Does Not Exist", - 482: "Loop Detected", - 483: "Too Many Hops", - 484: "Address Incomplete", - 485: "Ambiguous", - 486: "Busy Here", - 487: "Request Terminated", - 488: "Not Acceptable Here", - 489: "Bad Event", - 491: "Request Pending", - 493: "Undecipherable", - 494: "Security Agreement Required", - 500: "Internal Server Error", - 501: "Not Implemented", - 502: "Bad Gateway", - 503: "Service Unavailable", - 504: "Server Time-out", - 505: "Version Not Supported", - 513: "Message Too Large", - 580: "Precondition Failure", - 600: "Busy Everywhere", - 603: "Decline", - 604: "Does Not Exist Anywhere", - 606: "Not Acceptable" - }; - /* SIP Option Tags - * DOC: http://www.iana.org/assignments/sip-parameters/sip-parameters.xhtml#sip-parameters-4 - */ - C.OPTION_TAGS = { - "100rel": true, - "199": true, - "answermode": true, - "early-session": true, - "eventlist": true, - "explicitsub": true, - "from-change": true, - "geolocation-http": true, - "geolocation-sip": true, - "gin": true, - "gruu": true, - "histinfo": true, - "ice": true, - "join": true, - "multiple-refer": true, - "norefersub": true, - "nosub": true, - "outbound": true, - "path": true, - "policy": true, - "precondition": true, - "pref": true, - "privacy": true, - "recipient-list-invite": true, - "recipient-list-message": true, - "recipient-list-subscribe": true, - "replaces": true, - "resource-priority": true, - "sdp-anat": true, - "sec-agree": true, - "tdialog": true, - "timer": true, - "uui": true // RFC 7433 - }; - var dtmfType; - (function (dtmfType) { - dtmfType["INFO"] = "info"; - dtmfType["RTP"] = "rtp"; - })(dtmfType = C.dtmfType || (C.dtmfType = {})); -})(C = exports.C || (exports.C = {})); - - -/***/ }), -/* 81 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.LIBRARY_VERSION = "0.15.5"; - - -/***/ }), -/* 82 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// enums can't really be declared, so they are set here. -// pulled out of individual files to avoid circular dependencies -Object.defineProperty(exports, "__esModule", { value: true }); -var DialogStatus; -(function (DialogStatus) { - DialogStatus[DialogStatus["STATUS_EARLY"] = 1] = "STATUS_EARLY"; - DialogStatus[DialogStatus["STATUS_CONFIRMED"] = 2] = "STATUS_CONFIRMED"; -})(DialogStatus = exports.DialogStatus || (exports.DialogStatus = {})); -var SessionStatus; -(function (SessionStatus) { - // Session states - SessionStatus[SessionStatus["STATUS_NULL"] = 0] = "STATUS_NULL"; - SessionStatus[SessionStatus["STATUS_INVITE_SENT"] = 1] = "STATUS_INVITE_SENT"; - SessionStatus[SessionStatus["STATUS_1XX_RECEIVED"] = 2] = "STATUS_1XX_RECEIVED"; - SessionStatus[SessionStatus["STATUS_INVITE_RECEIVED"] = 3] = "STATUS_INVITE_RECEIVED"; - SessionStatus[SessionStatus["STATUS_WAITING_FOR_ANSWER"] = 4] = "STATUS_WAITING_FOR_ANSWER"; - SessionStatus[SessionStatus["STATUS_ANSWERED"] = 5] = "STATUS_ANSWERED"; - SessionStatus[SessionStatus["STATUS_WAITING_FOR_PRACK"] = 6] = "STATUS_WAITING_FOR_PRACK"; - SessionStatus[SessionStatus["STATUS_WAITING_FOR_ACK"] = 7] = "STATUS_WAITING_FOR_ACK"; - SessionStatus[SessionStatus["STATUS_CANCELED"] = 8] = "STATUS_CANCELED"; - SessionStatus[SessionStatus["STATUS_TERMINATED"] = 9] = "STATUS_TERMINATED"; - SessionStatus[SessionStatus["STATUS_ANSWERED_WAITING_FOR_PRACK"] = 10] = "STATUS_ANSWERED_WAITING_FOR_PRACK"; - SessionStatus[SessionStatus["STATUS_EARLY_MEDIA"] = 11] = "STATUS_EARLY_MEDIA"; - SessionStatus[SessionStatus["STATUS_CONFIRMED"] = 12] = "STATUS_CONFIRMED"; -})(SessionStatus = exports.SessionStatus || (exports.SessionStatus = {})); -var TypeStrings; -(function (TypeStrings) { - TypeStrings[TypeStrings["ClientContext"] = 0] = "ClientContext"; - TypeStrings[TypeStrings["ConfigurationError"] = 1] = "ConfigurationError"; - TypeStrings[TypeStrings["Dialog"] = 2] = "Dialog"; - TypeStrings[TypeStrings["DigestAuthentication"] = 3] = "DigestAuthentication"; - TypeStrings[TypeStrings["DTMF"] = 4] = "DTMF"; - TypeStrings[TypeStrings["IncomingMessage"] = 5] = "IncomingMessage"; - TypeStrings[TypeStrings["IncomingRequest"] = 6] = "IncomingRequest"; - TypeStrings[TypeStrings["IncomingResponse"] = 7] = "IncomingResponse"; - TypeStrings[TypeStrings["InvalidStateError"] = 8] = "InvalidStateError"; - TypeStrings[TypeStrings["InviteClientContext"] = 9] = "InviteClientContext"; - TypeStrings[TypeStrings["InviteServerContext"] = 10] = "InviteServerContext"; - TypeStrings[TypeStrings["Logger"] = 11] = "Logger"; - TypeStrings[TypeStrings["LoggerFactory"] = 12] = "LoggerFactory"; - TypeStrings[TypeStrings["MethodParameterError"] = 13] = "MethodParameterError"; - TypeStrings[TypeStrings["NameAddrHeader"] = 14] = "NameAddrHeader"; - TypeStrings[TypeStrings["NotSupportedError"] = 15] = "NotSupportedError"; - TypeStrings[TypeStrings["OutgoingRequest"] = 16] = "OutgoingRequest"; - TypeStrings[TypeStrings["Parameters"] = 17] = "Parameters"; - TypeStrings[TypeStrings["PublishContext"] = 18] = "PublishContext"; - TypeStrings[TypeStrings["ReferClientContext"] = 19] = "ReferClientContext"; - TypeStrings[TypeStrings["ReferServerContext"] = 20] = "ReferServerContext"; - TypeStrings[TypeStrings["RegisterContext"] = 21] = "RegisterContext"; - TypeStrings[TypeStrings["RenegotiationError"] = 22] = "RenegotiationError"; - TypeStrings[TypeStrings["RequestSender"] = 23] = "RequestSender"; - TypeStrings[TypeStrings["ServerContext"] = 24] = "ServerContext"; - TypeStrings[TypeStrings["Session"] = 25] = "Session"; - TypeStrings[TypeStrings["SessionDescriptionHandler"] = 26] = "SessionDescriptionHandler"; - TypeStrings[TypeStrings["SessionDescriptionHandlerError"] = 27] = "SessionDescriptionHandlerError"; - TypeStrings[TypeStrings["SessionDescriptionHandlerObserver"] = 28] = "SessionDescriptionHandlerObserver"; - TypeStrings[TypeStrings["Subscription"] = 29] = "Subscription"; - TypeStrings[TypeStrings["Transport"] = 30] = "Transport"; - TypeStrings[TypeStrings["UA"] = 31] = "UA"; - TypeStrings[TypeStrings["URI"] = 32] = "URI"; -})(TypeStrings = exports.TypeStrings || (exports.TypeStrings = {})); -// UA status codes -var UAStatus; -(function (UAStatus) { - UAStatus[UAStatus["STATUS_INIT"] = 0] = "STATUS_INIT"; - UAStatus[UAStatus["STATUS_STARTING"] = 1] = "STATUS_STARTING"; - UAStatus[UAStatus["STATUS_READY"] = 2] = "STATUS_READY"; - UAStatus[UAStatus["STATUS_USER_CLOSED"] = 3] = "STATUS_USER_CLOSED"; - UAStatus[UAStatus["STATUS_NOT_READY"] = 4] = "STATUS_NOT_READY"; -})(UAStatus = exports.UAStatus || (exports.UAStatus = {})); - - -/***/ }), -/* 83 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var Constants_1 = __webpack_require__(80); -var grammar_1 = __webpack_require__(11); -var uri_1 = __webpack_require__(15); -var Utils; -(function (Utils) { - function defer() { - var deferred = {}; - deferred.promise = new Promise(function (resolve, reject) { - deferred.resolve = resolve; - deferred.reject = reject; - }); - return deferred; - } - Utils.defer = defer; - function reducePromises(arr, val) { - return arr.reduce(function (acc, fn) { - acc = acc.then(fn); - return acc; - }, Promise.resolve(val)); - } - Utils.reducePromises = reducePromises; - function str_utf8_length(str) { - return encodeURIComponent(str).replace(/%[A-F\d]{2}/g, "U").length; - } - Utils.str_utf8_length = str_utf8_length; - function generateFakeSDP(body) { - if (!body) { - return; - } - var start = body.indexOf("o="); - var end = body.indexOf("\r\n", start); - return "v=0\r\n" + body.slice(start, end) + "\r\ns=-\r\nt=0 0\r\nc=IN IP4 0.0.0.0"; - } - Utils.generateFakeSDP = generateFakeSDP; - function isDecimal(num) { - var numAsNum = parseInt(num, 10); - return !isNaN(numAsNum) && (parseFloat(num) === numAsNum); - } - Utils.isDecimal = isDecimal; - function createRandomToken(size, base) { - if (base === void 0) { base = 32; } - var token = ""; - for (var i = 0; i < size; i++) { - var r = Math.floor(Math.random() * base); - token += r.toString(base); - } - return token; - } - Utils.createRandomToken = createRandomToken; - function newTag() { - // used to use the constant in UA - return Utils.createRandomToken(10); - } - Utils.newTag = newTag; - // http://stackoverflow.com/users/109538/broofa - function newUUID() { - var UUID = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) { - var r = Math.floor(Math.random() * 16); - var v = c === "x" ? r : (r % 4 + 8); - return v.toString(16); - }); - return UUID; - } - Utils.newUUID = newUUID; - /* - * Normalize SIP URI. - * NOTE: It does not allow a SIP URI without username. - * Accepts 'sip', 'sips' and 'tel' URIs and convert them into 'sip'. - * Detects the domain part (if given) and properly hex-escapes the user portion. - * If the user portion has only 'tel' number symbols the user portion is clean of 'tel' visual separators. - * @private - * @param {String} target - * @param {String} [domain] - */ - function normalizeTarget(target, domain) { - // If no target is given then raise an error. - if (!target) { - return; - // If a SIP.URI instance is given then return it. - } - else if (target instanceof uri_1.URI) { - return target; - // If a string is given split it by '@': - // - Last fragment is the desired domain. - // - Otherwise append the given domain argument. - } - else if (typeof target === "string") { - var targetArray = target.split("@"); - var targetUser = void 0; - var targetDomain = void 0; - switch (targetArray.length) { - case 1: - if (!domain) { - return; - } - targetUser = target; - targetDomain = domain; - break; - case 2: - targetUser = targetArray[0]; - targetDomain = targetArray[1]; - break; - default: - targetUser = targetArray.slice(0, targetArray.length - 1).join("@"); - targetDomain = targetArray[targetArray.length - 1]; - } - // Remove the URI scheme (if present). - targetUser = targetUser.replace(/^(sips?|tel):/i, ""); - // Remove 'tel' visual separators if the user portion just contains 'tel' number symbols. - if (/^[\-\.\(\)]*\+?[0-9\-\.\(\)]+$/.test(targetUser)) { - targetUser = targetUser.replace(/[\-\.\(\)]/g, ""); - } - // Build the complete SIP URI. - target = Constants_1.C.SIP + ":" + Utils.escapeUser(targetUser) + "@" + targetDomain; - // Finally parse the resulting URI. - return grammar_1.Grammar.URIParse(target); - } - else { - return; - } - } - Utils.normalizeTarget = normalizeTarget; - /* - * Hex-escape a SIP URI user. - * @private - * @param {String} user - */ - function escapeUser(user) { - // Don't hex-escape ':' (%3A), '+' (%2B), '?' (%3F"), '/' (%2F). - return encodeURIComponent(decodeURIComponent(user)) - .replace(/%3A/ig, ":") - .replace(/%2B/ig, "+") - .replace(/%3F/ig, "?") - .replace(/%2F/ig, "/"); - } - Utils.escapeUser = escapeUser; - function headerize(str) { - var exceptions = { - "Call-Id": "Call-ID", - "Cseq": "CSeq", - "Min-Se": "Min-SE", - "Rack": "RAck", - "Rseq": "RSeq", - "Www-Authenticate": "WWW-Authenticate", - }; - var name = str.toLowerCase().replace(/_/g, "-").split("-"); - var parts = name.length; - var hname = ""; - for (var part = 0; part < parts; part++) { - if (part !== 0) { - hname += "-"; - } - hname += name[part].charAt(0).toUpperCase() + name[part].substring(1); - } - if (exceptions[hname]) { - hname = exceptions[hname]; - } - return hname; - } - Utils.headerize = headerize; - function sipErrorCause(statusCode) { - for (var cause in Constants_1.C.SIP_ERROR_CAUSES) { - if (Constants_1.C.SIP_ERROR_CAUSES[cause].indexOf(statusCode) !== -1) { - return Constants_1.C.causes[cause]; - } - } - return Constants_1.C.causes.SIP_FAILURE_CODE; - } - Utils.sipErrorCause = sipErrorCause; - function getReasonPhrase(code, specific) { - return specific || Constants_1.C.REASON_PHRASE[code] || ""; - } - Utils.getReasonPhrase = getReasonPhrase; - function getReasonHeaderValue(code, reason) { - reason = Utils.getReasonPhrase(code, reason); - return "SIP;cause=" + code + ';text="' + reason + '"'; - } - Utils.getReasonHeaderValue = getReasonHeaderValue; - function getCancelReason(code, reason) { - if (code && code < 200 || code > 699) { - throw new TypeError("Invalid statusCode: " + code); - } - else if (code) { - return Utils.getReasonHeaderValue(code, reason); - } - } - Utils.getCancelReason = getCancelReason; - function buildStatusLine(code, reason) { - // Validate code and reason values - if (!code || (code < 100 || code > 699)) { - throw new TypeError("Invalid statusCode: " + code); - } - else if (reason && typeof reason !== "string" && !(reason instanceof String)) { - throw new TypeError("Invalid reason: " + reason); - } - reason = Utils.getReasonPhrase(code, reason); - return "SIP/2.0 " + code + " " + reason + "\r\n"; - } - Utils.buildStatusLine = buildStatusLine; - /** - * Create a Body given a BodyObj. - * @param bodyObj Body Object - */ - function fromBodyObj(bodyObj) { - var content = bodyObj.body; - var contentType = bodyObj.contentType; - var contentDisposition = contentTypeToContentDisposition(contentType); - var body = { contentDisposition: contentDisposition, contentType: contentType, content: content }; - return body; - } - Utils.fromBodyObj = fromBodyObj; - /** - * Create a BodyObj given a Body. - * @param bodyObj Body Object - */ - function toBodyObj(body) { - var bodyObj = { - body: body.content, - contentType: body.contentType - }; - return bodyObj; - } - Utils.toBodyObj = toBodyObj; - // If the Content-Disposition header field is missing, bodies of - // Content-Type application/sdp imply the disposition "session", while - // other content types imply "render". - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - function contentTypeToContentDisposition(contentType) { - if (contentType === "application/sdp") { - return "session"; - } - else { - return "render"; - } - } -})(Utils = exports.Utils || (exports.Utils = {})); - - -/***/ }), -/* 84 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var core_1 = __webpack_require__(2); -var Enums_1 = __webpack_require__(82); -// tslint:disable:max-classes-per-file -var Exceptions; -(function (Exceptions) { - /** - * Indicates the session description handler has closed. - * Occurs when getDescription() or setDescription() are called after close() has been called. - * Occurs when close() is called while getDescription() or setDescription() are in progress. - */ - var ClosedSessionDescriptionHandlerError = /** @class */ (function (_super) { - tslib_1.__extends(ClosedSessionDescriptionHandlerError, _super); - function ClosedSessionDescriptionHandlerError() { - return _super.call(this, "The session description handler has closed.") || this; - } - return ClosedSessionDescriptionHandlerError; - }(core_1.Exception)); - Exceptions.ClosedSessionDescriptionHandlerError = ClosedSessionDescriptionHandlerError; - /** - * Indicates the session terminated before the action completed. - */ - var TerminatedSessionError = /** @class */ (function (_super) { - tslib_1.__extends(TerminatedSessionError, _super); - function TerminatedSessionError() { - return _super.call(this, "The session has terminated.") || this; - } - return TerminatedSessionError; - }(core_1.Exception)); - Exceptions.TerminatedSessionError = TerminatedSessionError; - /** - * Unsupported session description content type. - */ - var UnsupportedSessionDescriptionContentTypeError = /** @class */ (function (_super) { - tslib_1.__extends(UnsupportedSessionDescriptionContentTypeError, _super); - function UnsupportedSessionDescriptionContentTypeError(message) { - return _super.call(this, message ? message : "Unsupported session description content type.") || this; - } - return UnsupportedSessionDescriptionContentTypeError; - }(core_1.Exception)); - Exceptions.UnsupportedSessionDescriptionContentTypeError = UnsupportedSessionDescriptionContentTypeError; -})(Exceptions = exports.Exceptions || (exports.Exceptions = {})); -/** - * DEPRECATED: The original implementation of exceptions in this library attempted to - * deal with the lack of type checking in JavaScript by adding a "type" attribute - * to objects and using that to discriminate. On top of that it layered allcoated - * "code" numbers and constant "name" strings. All of that is unnecessary when using - * TypeScript, inheriting from Error and properly setting up the prototype chain... - */ -var LegacyException = /** @class */ (function (_super) { - tslib_1.__extends(LegacyException, _super); - function LegacyException(code, name, message) { - var _this = _super.call(this, message) || this; - _this.code = code; - _this.name = name; - _this.message = message; - return _this; - } - return LegacyException; -}(core_1.Exception)); -(function (Exceptions) { - var ConfigurationError = /** @class */ (function (_super) { - tslib_1.__extends(ConfigurationError, _super); - function ConfigurationError(parameter, value) { - var _this = _super.call(this, 1, "CONFIGURATION_ERROR", (!value) ? "Missing parameter: " + parameter : - "Invalid value " + JSON.stringify(value) + " for parameter '" + parameter + "'") || this; - _this.type = Enums_1.TypeStrings.ConfigurationError; - _this.parameter = parameter; - _this.value = value; - return _this; - } - return ConfigurationError; - }(LegacyException)); - Exceptions.ConfigurationError = ConfigurationError; - var InvalidStateError = /** @class */ (function (_super) { - tslib_1.__extends(InvalidStateError, _super); - function InvalidStateError(status) { - var _this = _super.call(this, 2, "INVALID_STATE_ERROR", "Invalid status: " + status) || this; - _this.type = Enums_1.TypeStrings.InvalidStateError; - _this.status = status; - return _this; - } - return InvalidStateError; - }(LegacyException)); - Exceptions.InvalidStateError = InvalidStateError; - var NotSupportedError = /** @class */ (function (_super) { - tslib_1.__extends(NotSupportedError, _super); - function NotSupportedError(message) { - var _this = _super.call(this, 3, "NOT_SUPPORTED_ERROR", message) || this; - _this.type = Enums_1.TypeStrings.NotSupportedError; - return _this; - } - return NotSupportedError; - }(LegacyException)); - Exceptions.NotSupportedError = NotSupportedError; - // 4 was GetDescriptionError, which was deprecated and now removed - var RenegotiationError = /** @class */ (function (_super) { - tslib_1.__extends(RenegotiationError, _super); - function RenegotiationError(message) { - var _this = _super.call(this, 5, "RENEGOTIATION_ERROR", message) || this; - _this.type = Enums_1.TypeStrings.RenegotiationError; - return _this; - } - return RenegotiationError; - }(LegacyException)); - Exceptions.RenegotiationError = RenegotiationError; - var MethodParameterError = /** @class */ (function (_super) { - tslib_1.__extends(MethodParameterError, _super); - function MethodParameterError(method, parameter, value) { - var _this = _super.call(this, 6, "METHOD_PARAMETER_ERROR", (!value) ? - "Missing parameter: " + parameter : - "Invalid value " + JSON.stringify(value) + " for parameter '" + parameter + "'") || this; - _this.type = Enums_1.TypeStrings.MethodParameterError; - _this.method = method; - _this.parameter = parameter; - _this.value = value; - return _this; - } - return MethodParameterError; - }(LegacyException)); - Exceptions.MethodParameterError = MethodParameterError; - // 7 was TransportError, which was replaced - var SessionDescriptionHandlerError = /** @class */ (function (_super) { - tslib_1.__extends(SessionDescriptionHandlerError, _super); - function SessionDescriptionHandlerError(method, error, message) { - var _this = _super.call(this, 8, "SESSION_DESCRIPTION_HANDLER_ERROR", message || "Error with Session Description Handler") || this; - _this.type = Enums_1.TypeStrings.SessionDescriptionHandlerError; - _this.method = method; - _this.error = error; - return _this; - } - return SessionDescriptionHandlerError; - }(LegacyException)); - Exceptions.SessionDescriptionHandlerError = SessionDescriptionHandlerError; -})(Exceptions = exports.Exceptions || (exports.Exceptions = {})); - - -/***/ }), -/* 85 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var core_1 = __webpack_require__(2); -/** - * Extract and parse every header of a SIP message. - * @namespace - */ -var Parser; -(function (Parser) { - function getHeader(data, headerStart) { - // 'start' position of the header. - var start = headerStart; - // 'end' position of the header. - var end = 0; - // 'partial end' position of the header. - var partialEnd = 0; - // End of message. - if (data.substring(start, start + 2).match(/(^\r\n)/)) { - return -2; - } - while (end === 0) { - // Partial End of Header. - partialEnd = data.indexOf("\r\n", start); - // 'indexOf' returns -1 if the value to be found never occurs. - if (partialEnd === -1) { - return partialEnd; - } - if (!data.substring(partialEnd + 2, partialEnd + 4).match(/(^\r\n)/) && - data.charAt(partialEnd + 2).match(/(^\s+)/)) { - // Not the end of the message. Continue from the next position. - start = partialEnd + 2; - } - else { - end = partialEnd; - } - } - return end; - } - Parser.getHeader = getHeader; - function parseHeader(message, data, headerStart, headerEnd) { - var hcolonIndex = data.indexOf(":", headerStart); - var headerName = data.substring(headerStart, hcolonIndex).trim(); - var headerValue = data.substring(hcolonIndex + 1, headerEnd).trim(); - var parsed; - // If header-field is well-known, parse it. - switch (headerName.toLowerCase()) { - case "via": - case "v": - message.addHeader("via", headerValue); - if (message.getHeaders("via").length === 1) { - parsed = message.parseHeader("Via"); - if (parsed) { - message.via = parsed; - message.viaBranch = parsed.branch; - } - } - else { - parsed = 0; - } - break; - case "from": - case "f": - message.setHeader("from", headerValue); - parsed = message.parseHeader("from"); - if (parsed) { - message.from = parsed; - message.fromTag = parsed.getParam("tag"); - } - break; - case "to": - case "t": - message.setHeader("to", headerValue); - parsed = message.parseHeader("to"); - if (parsed) { - message.to = parsed; - message.toTag = parsed.getParam("tag"); - } - break; - case "record-route": - parsed = core_1.Grammar.parse(headerValue, "Record_Route"); - if (parsed === -1) { - parsed = undefined; - break; - } - for (var header in parsed) { - if (parsed[header]) { - message.addHeader("record-route", headerValue.substring(parsed[header].position, parsed[header].offset)); - message.headers["Record-Route"][message.getHeaders("record-route").length - 1].parsed = - parsed[header].parsed; - } - } - break; - case "call-id": - case "i": - message.setHeader("call-id", headerValue); - parsed = message.parseHeader("call-id"); - if (parsed) { - message.callId = headerValue; - } - break; - case "contact": - case "m": - parsed = core_1.Grammar.parse(headerValue, "Contact"); - if (parsed === -1) { - parsed = undefined; - break; - } - if (!(parsed instanceof Array)) { - parsed = undefined; - break; - } - parsed.forEach(function (header) { - message.addHeader("contact", headerValue.substring(header.position, header.offset)); - message.headers.Contact[message.getHeaders("contact").length - 1].parsed = header.parsed; - }); - break; - case "content-length": - case "l": - message.setHeader("content-length", headerValue); - parsed = message.parseHeader("content-length"); - break; - case "content-type": - case "c": - message.setHeader("content-type", headerValue); - parsed = message.parseHeader("content-type"); - break; - case "cseq": - message.setHeader("cseq", headerValue); - parsed = message.parseHeader("cseq"); - if (parsed) { - message.cseq = parsed.value; - } - if (message instanceof core_1.IncomingResponseMessage) { - message.method = parsed.method; - } - break; - case "max-forwards": - message.setHeader("max-forwards", headerValue); - parsed = message.parseHeader("max-forwards"); - break; - case "www-authenticate": - message.setHeader("www-authenticate", headerValue); - parsed = message.parseHeader("www-authenticate"); - break; - case "proxy-authenticate": - message.setHeader("proxy-authenticate", headerValue); - parsed = message.parseHeader("proxy-authenticate"); - break; - case "refer-to": - case "r": - message.setHeader("refer-to", headerValue); - parsed = message.parseHeader("refer-to"); - if (parsed) { - message.referTo = parsed; - } - break; - default: - // Do not parse this header. - message.addHeader(headerName.toLowerCase(), headerValue); - parsed = 0; - } - if (parsed === undefined) { - return { - error: "error parsing header '" + headerName + "'" - }; - } - else { - return true; - } - } - Parser.parseHeader = parseHeader; - /** Parse SIP Message - * @function - * @param {String} message SIP message. - * @param {Object} logger object. - * @returns {SIP.IncomingRequest|SIP.IncomingResponse|undefined} - */ - function parseMessage(data, logger) { - var headerStart = 0; - var headerEnd = data.indexOf("\r\n"); - if (headerEnd === -1) { - logger.warn("no CRLF found, not a SIP message, discarded"); - return; - } - // Parse first line. Check if it is a Request or a Reply. - var firstLine = data.substring(0, headerEnd); - var parsed = core_1.Grammar.parse(firstLine, "Request_Response"); - var message; - if (parsed === -1) { - logger.warn('error parsing first line of SIP message: "' + firstLine + '"'); - return; - } - else if (!parsed.status_code) { - message = new core_1.IncomingRequestMessage(); - message.method = parsed.method; - message.ruri = parsed.uri; - } - else { - message = new core_1.IncomingResponseMessage(); - message.statusCode = parsed.status_code; - message.reasonPhrase = parsed.reason_phrase; - } - message.data = data; - headerStart = headerEnd + 2; - /* Loop over every line in data. Detect the end of each header and parse - * it or simply add to the headers collection. - */ - var bodyStart; - while (true) { - headerEnd = getHeader(data, headerStart); - // The SIP message has normally finished. - if (headerEnd === -2) { - bodyStart = headerStart + 2; - break; - } - else if (headerEnd === -1) { - // data.indexOf returned -1 due to a malformed message. - logger.error("malformed message"); - return; - } - var parsedHeader = parseHeader(message, data, headerStart, headerEnd); - if (parsedHeader !== true) { - logger.error(parsed.error); - return; - } - headerStart = headerEnd + 2; - } - /* RFC3261 18.3. - * If there are additional bytes in the transport packet - * beyond the end of the body, they MUST be discarded. - */ - if (message.hasHeader("content-length")) { - message.body = data.substr(bodyStart, Number(message.getHeader("content-length"))); - } - else { - message.body = data.substring(bodyStart); - } - return message; - } - Parser.parseMessage = parseMessage; -})(Parser = exports.Parser || (exports.Parser = {})); - - -/***/ }), -/* 86 */, -/* 87 */, -/* 88 */, -/* 89 */, -/* 90 */, -/* 91 */, -/* 92 */, -/* 93 */, -/* 94 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var events_1 = __webpack_require__(30); -var session_1 = __webpack_require__(95); -var Enums_1 = __webpack_require__(82); -var Exceptions_1 = __webpack_require__(84); -var Utils_1 = __webpack_require__(83); -var Modifiers = tslib_1.__importStar(__webpack_require__(101)); -var SessionDescriptionHandlerObserver_1 = __webpack_require__(102); -/* SessionDescriptionHandler - * @class PeerConnection helper Class. - * @param {SIP.Session} session - * @param {Object} [options] - */ -var SessionDescriptionHandler = /** @class */ (function (_super) { - tslib_1.__extends(SessionDescriptionHandler, _super); - function SessionDescriptionHandler(logger, observer, options) { - var _this = _super.call(this) || this; - _this.type = Enums_1.TypeStrings.SessionDescriptionHandler; - // TODO: Validate the options - _this.options = options || {}; - _this.logger = logger; - _this.observer = observer; - _this.dtmfSender = undefined; - _this.shouldAcquireMedia = true; - _this.CONTENT_TYPE = "application/sdp"; - _this.C = { - DIRECTION: { - NULL: null, - SENDRECV: "sendrecv", - SENDONLY: "sendonly", - RECVONLY: "recvonly", - INACTIVE: "inactive" - } - }; - _this.logger.log("SessionDescriptionHandlerOptions: " + JSON.stringify(_this.options)); - _this.direction = _this.C.DIRECTION.NULL; - _this.modifiers = _this.options.modifiers || []; - if (!Array.isArray(_this.modifiers)) { - _this.modifiers = [_this.modifiers]; - } - _this.iceGatheringTimeout = false; - _this.initPeerConnection(_this.options.peerConnectionOptions); - _this.constraints = _this.checkAndDefaultConstraints(_this.options.constraints); - return _this; - } - /** - * @param {SIP.Session} session - * @param {Object} [options] - */ - SessionDescriptionHandler.defaultFactory = function (session, options) { - var logger = (session instanceof session_1.Session) ? - session.userAgent.getLogger("sip.sessionDescriptionHandler", session.id) : - session.ua.getLogger("sip.invitecontext.sessionDescriptionHandler", session.id); - var observer = new SessionDescriptionHandlerObserver_1.SessionDescriptionHandlerObserver(session, options); - return new SessionDescriptionHandler(logger, observer, options); - }; - // Functions the sesssion can use - /** - * Destructor - */ - SessionDescriptionHandler.prototype.close = function () { - this.logger.log("closing PeerConnection"); - // have to check signalingState since this.close() gets called multiple times - if (this.peerConnection && this.peerConnection.signalingState !== "closed") { - if (this.peerConnection.getSenders) { - this.peerConnection.getSenders().forEach(function (sender) { - if (sender.track) { - sender.track.stop(); - } - }); - } - else { - this.logger.warn("Using getLocalStreams which is deprecated"); - this.peerConnection.getLocalStreams().forEach(function (stream) { - stream.getTracks().forEach(function (track) { - track.stop(); - }); - }); - } - if (this.peerConnection.getReceivers) { - this.peerConnection.getReceivers().forEach(function (receiver) { - if (receiver.track) { - receiver.track.stop(); - } - }); - } - else { - this.logger.warn("Using getRemoteStreams which is deprecated"); - this.peerConnection.getRemoteStreams().forEach(function (stream) { - stream.getTracks().forEach(function (track) { - track.stop(); - }); - }); - } - this.resetIceGatheringComplete(); - this.peerConnection.close(); - } - }; - /** - * Gets the local description from the underlying media implementation - * @param {Object} [options] Options object to be used by getDescription - * @param {MediaStreamConstraints} [options.constraints] MediaStreamConstraints - * https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints - * @param {Object} [options.peerConnectionOptions] If this is set it will recreate the peer - * connection with the new options - * @param {Array} [modifiers] Array with one time use description modifiers - * @returns {Promise} Promise that resolves with the local description to be used for the session - */ - SessionDescriptionHandler.prototype.getDescription = function (options, modifiers) { - var _this = this; - if (options === void 0) { options = {}; } - if (modifiers === void 0) { modifiers = []; } - if (options.peerConnectionOptions) { - this.initPeerConnection(options.peerConnectionOptions); - } - // Merge passed constraints with saved constraints and save - var newConstraints = Object.assign({}, this.constraints, options.constraints); - newConstraints = this.checkAndDefaultConstraints(newConstraints); - if (JSON.stringify(newConstraints) !== JSON.stringify(this.constraints)) { - this.constraints = newConstraints; - this.shouldAcquireMedia = true; - } - if (!Array.isArray(modifiers)) { - modifiers = [modifiers]; - } - modifiers = modifiers.concat(this.modifiers); - return Promise.resolve().then(function () { - if (_this.shouldAcquireMedia) { - return _this.acquire(_this.constraints).then(function () { - _this.shouldAcquireMedia = false; - }); - } - }).then(function () { return _this.createOfferOrAnswer(options.RTCOfferOptions, modifiers); }) - .then(function (description) { - if (description.sdp === undefined) { - throw new Exceptions_1.Exceptions.SessionDescriptionHandlerError("getDescription", undefined, "SDP undefined"); - } - _this.emit("getDescription", description); - return { - body: description.sdp, - contentType: _this.CONTENT_TYPE - }; - }); - }; - /** - * Check if the Session Description Handler can handle the Content-Type described by a SIP Message - * @param {String} contentType The content type that is in the SIP Message - * @returns {boolean} - */ - SessionDescriptionHandler.prototype.hasDescription = function (contentType) { - return contentType === this.CONTENT_TYPE; - }; - /** - * The modifier that should be used when the session would like to place the call on hold - * @param {String} [sdp] The description that will be modified - * @returns {Promise} Promise that resolves with modified SDP - */ - SessionDescriptionHandler.prototype.holdModifier = function (description) { - if (!description.sdp) { - return Promise.resolve(description); - } - if (!(/a=(sendrecv|sendonly|recvonly|inactive)/).test(description.sdp)) { - description.sdp = description.sdp.replace(/(m=[^\r]*\r\n)/g, "$1a=sendonly\r\n"); - } - else { - description.sdp = description.sdp.replace(/a=sendrecv\r\n/g, "a=sendonly\r\n"); - description.sdp = description.sdp.replace(/a=recvonly\r\n/g, "a=inactive\r\n"); - } - return Promise.resolve(description); - }; - /** - * Set the remote description to the underlying media implementation - * @param {String} sessionDescription The description provided by a SIP message to be set on the media implementation - * @param {Object} [options] Options object to be used by getDescription - * @param {MediaStreamConstraints} [options.constraints] MediaStreamConstraints - * https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints - * @param {Object} [options.peerConnectionOptions] If this is set it will recreate the peer - * connection with the new options - * @param {Array} [modifiers] Array with one time use description modifiers - * @returns {Promise} Promise that resolves once the description is set - */ - SessionDescriptionHandler.prototype.setDescription = function (sessionDescription, options, modifiers) { - var _this = this; - if (options === void 0) { options = {}; } - if (modifiers === void 0) { modifiers = []; } - if (options.peerConnectionOptions) { - this.initPeerConnection(options.peerConnectionOptions); - } - if (!Array.isArray(modifiers)) { - modifiers = [modifiers]; - } - modifiers = modifiers.concat(this.modifiers); - var description = { - type: this.hasOffer("local") ? "answer" : "offer", - sdp: sessionDescription - }; - return Promise.resolve().then(function () { - // Media should be acquired in getDescription unless we need to do it sooner for some reason (FF61+) - if (_this.shouldAcquireMedia && _this.options.alwaysAcquireMediaFirst) { - return _this.acquire(_this.constraints).then(function () { - _this.shouldAcquireMedia = false; - }); - } - }).then(function () { return Utils_1.Utils.reducePromises(modifiers, description); }) - .catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("setDescription", e, "The modifiers did not resolve successfully"); - _this.logger.error(error.message); - _this.emit("peerConnection-setRemoteDescriptionFailed", error); - throw error; - }).then(function (modifiedDescription) { - _this.emit("setDescription", modifiedDescription); - return _this.peerConnection.setRemoteDescription(modifiedDescription); - }).catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - // Check the original SDP for video, and ensure that we have want to do audio fallback - if ((/^m=video.+$/gm).test(sessionDescription) && !options.disableAudioFallback) { - // Do not try to audio fallback again - options.disableAudioFallback = true; - // Remove video first, then do the other modifiers - return _this.setDescription(sessionDescription, options, [Modifiers.stripVideo].concat(modifiers)); - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("setDescription", e); - if (error.error) { - _this.logger.error(error.error); - } - _this.emit("peerConnection-setRemoteDescriptionFailed", error); - throw error; - }).then(function () { - if (_this.peerConnection.getReceivers) { - _this.emit("setRemoteDescription", _this.peerConnection.getReceivers()); - } - else { - _this.emit("setRemoteDescription", _this.peerConnection.getRemoteStreams()); - } - _this.emit("confirmed", _this); - }); - }; - /** - * Send DTMF via RTP (RFC 4733) - * @param {String} tones A string containing DTMF digits - * @param {Object} [options] Options object to be used by sendDtmf - * @returns {boolean} true if DTMF send is successful, false otherwise - */ - SessionDescriptionHandler.prototype.sendDtmf = function (tones, options) { - if (options === void 0) { options = {}; } - if (!this.dtmfSender && this.hasBrowserGetSenderSupport()) { - var senders = this.peerConnection.getSenders(); - if (senders.length > 0) { - this.dtmfSender = senders[0].dtmf; - } - } - if (!this.dtmfSender && this.hasBrowserTrackSupport()) { - var streams = this.peerConnection.getLocalStreams(); - if (streams.length > 0) { - var audioTracks = streams[0].getAudioTracks(); - if (audioTracks.length > 0) { - this.dtmfSender = this.peerConnection.createDTMFSender(audioTracks[0]); - } - } - } - if (!this.dtmfSender) { - return false; - } - try { - this.dtmfSender.insertDTMF(tones, options.duration, options.interToneGap); - } - catch (e) { - if (e.type === "InvalidStateError" || e.type === "InvalidCharacterError") { - this.logger.error(e); - return false; - } - else { - throw e; - } - } - this.logger.log("DTMF sent via RTP: " + tones.toString()); - return true; - }; - /** - * Get the direction of the session description - * @returns {String} direction of the description - */ - SessionDescriptionHandler.prototype.getDirection = function () { - return this.direction; - }; - SessionDescriptionHandler.prototype.on = function (name, callback) { return _super.prototype.on.call(this, name, callback); }; - SessionDescriptionHandler.prototype.getMediaStream = function (constraints) { - return navigator.mediaDevices.getUserMedia(constraints); - }; - // Internal functions - SessionDescriptionHandler.prototype.createOfferOrAnswer = function (RTCOfferOptions, modifiers) { - var _this = this; - if (RTCOfferOptions === void 0) { RTCOfferOptions = {}; } - if (modifiers === void 0) { modifiers = []; } - var methodName = this.hasOffer("remote") ? "createAnswer" : "createOffer"; - var pc = this.peerConnection; - this.logger.log(methodName); - var method = this.hasOffer("remote") ? pc.createAnswer : pc.createOffer; - return method.apply(pc, RTCOfferOptions).catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer", e, "peerConnection-" + methodName + "Failed"); - _this.emit("peerConnection-" + methodName + "Failed", error); - throw error; - }).then(function (sdp) { - return Utils_1.Utils.reducePromises(modifiers, _this.createRTCSessionDescriptionInit(sdp)); - }).then(function (sdp) { - _this.resetIceGatheringComplete(); - _this.logger.log("Setting local sdp."); - _this.logger.log("sdp is " + sdp.sdp || false); - return pc.setLocalDescription(sdp); - }).catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer", e, "peerConnection-SetLocalDescriptionFailed"); - _this.emit("peerConnection-SetLocalDescriptionFailed", error); - throw error; - }).then(function () { return _this.waitForIceGatheringComplete(); }) - .then(function () { - if (!_this.peerConnection.localDescription) { - throw new Exceptions_1.Exceptions.SessionDescriptionHandlerError("Missing local description"); - } - var localDescription = _this.createRTCSessionDescriptionInit(_this.peerConnection.localDescription); - return Utils_1.Utils.reducePromises(modifiers, localDescription); - }).then(function (localDescription) { - _this.setDirection(localDescription.sdp || ""); - return localDescription; - }).catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer", e); - _this.logger.error(error.toString()); - throw error; - }); - }; - // Creates an RTCSessionDescriptionInit from an RTCSessionDescription - SessionDescriptionHandler.prototype.createRTCSessionDescriptionInit = function (RTCSessionDescription) { - return { - type: RTCSessionDescription.type, - sdp: RTCSessionDescription.sdp - }; - }; - SessionDescriptionHandler.prototype.addDefaultIceCheckingTimeout = function (peerConnectionOptions) { - if (peerConnectionOptions.iceCheckingTimeout === undefined) { - peerConnectionOptions.iceCheckingTimeout = 5000; - } - return peerConnectionOptions; - }; - SessionDescriptionHandler.prototype.addDefaultIceServers = function (rtcConfiguration) { - if (!rtcConfiguration.iceServers) { - rtcConfiguration.iceServers = [{ urls: "stun:stun.l.google.com:19302" }]; - } - return rtcConfiguration; - }; - SessionDescriptionHandler.prototype.checkAndDefaultConstraints = function (constraints) { - var defaultConstraints = { audio: true, video: !this.options.alwaysAcquireMediaFirst }; - constraints = constraints || defaultConstraints; - // Empty object check - if (Object.keys(constraints).length === 0 && constraints.constructor === Object) { - return defaultConstraints; - } - return constraints; - }; - SessionDescriptionHandler.prototype.hasBrowserTrackSupport = function () { - return Boolean(this.peerConnection.addTrack); - }; - SessionDescriptionHandler.prototype.hasBrowserGetSenderSupport = function () { - return Boolean(this.peerConnection.getSenders); - }; - SessionDescriptionHandler.prototype.initPeerConnection = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - options = this.addDefaultIceCheckingTimeout(options); - options.rtcConfiguration = options.rtcConfiguration || {}; - options.rtcConfiguration = this.addDefaultIceServers(options.rtcConfiguration); - this.logger.log("initPeerConnection"); - if (this.peerConnection) { - this.logger.log("Already have a peer connection for this session. Tearing down."); - this.resetIceGatheringComplete(); - this.peerConnection.close(); - } - this.peerConnection = new RTCPeerConnection(options.rtcConfiguration); - this.logger.log("New peer connection created"); - if ("ontrack" in this.peerConnection) { - this.peerConnection.addEventListener("track", function (e) { - _this.logger.log("track added"); - _this.observer.trackAdded(); - _this.emit("addTrack", e); - }); - } - else { - this.logger.warn("Using onaddstream which is deprecated"); - this.peerConnection.onaddstream = function (e) { - _this.logger.log("stream added"); - _this.emit("addStream", e); - }; - } - this.peerConnection.onicecandidate = function (e) { - _this.emit("iceCandidate", e); - if (e.candidate) { - _this.logger.log("ICE candidate received: " + - (e.candidate.candidate === null ? null : e.candidate.candidate.trim())); - } - else if (e.candidate === null) { - // indicates the end of candidate gathering - _this.logger.log("ICE candidate gathering complete"); - _this.triggerIceGatheringComplete(); - } - }; - this.peerConnection.onicegatheringstatechange = function () { - _this.logger.log("RTCIceGatheringState changed: " + _this.peerConnection.iceGatheringState); - switch (_this.peerConnection.iceGatheringState) { - case "gathering": - _this.emit("iceGathering", _this); - if (!_this.iceGatheringTimer && options.iceCheckingTimeout) { - _this.iceGatheringTimeout = false; - _this.iceGatheringTimer = setTimeout(function () { - _this.logger.log("RTCIceChecking Timeout Triggered after " + options.iceCheckingTimeout + " milliseconds"); - _this.iceGatheringTimeout = true; - _this.triggerIceGatheringComplete(); - }, options.iceCheckingTimeout); - } - break; - case "complete": - _this.triggerIceGatheringComplete(); - break; - } - }; - this.peerConnection.oniceconnectionstatechange = function () { - var stateEvent; - switch (_this.peerConnection.iceConnectionState) { - case "new": - stateEvent = "iceConnection"; - break; - case "checking": - stateEvent = "iceConnectionChecking"; - break; - case "connected": - stateEvent = "iceConnectionConnected"; - break; - case "completed": - stateEvent = "iceConnectionCompleted"; - break; - case "failed": - stateEvent = "iceConnectionFailed"; - break; - case "disconnected": - stateEvent = "iceConnectionDisconnected"; - break; - case "closed": - stateEvent = "iceConnectionClosed"; - break; - default: - _this.logger.warn("Unknown iceConnection state: " + _this.peerConnection.iceConnectionState); - return; - } - _this.logger.log("ICE Connection State changed to " + stateEvent); - _this.emit(stateEvent, _this); - }; - }; - SessionDescriptionHandler.prototype.acquire = function (constraints) { - var _this = this; - // Default audio & video to true - constraints = this.checkAndDefaultConstraints(constraints); - return new Promise(function (resolve, reject) { - /* - * Make the call asynchronous, so that ICCs have a chance - * to define callbacks to `userMediaRequest` - */ - _this.logger.log("acquiring local media"); - _this.emit("userMediaRequest", constraints); - if (constraints.audio || constraints.video) { - _this.getMediaStream(constraints).then(function (streams) { - _this.observer.trackAdded(); - _this.emit("userMedia", streams); - resolve(streams); - }).catch(function (e) { - _this.emit("userMediaFailed", e); - reject(e); - }); - } - else { - // Local streams were explicitly excluded. - resolve([]); - } - }).catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("acquire", e, "unable to acquire streams"); - _this.logger.error(error.message); - if (error.error) { - _this.logger.error(error.error); - } - throw error; - }).then(function (streams) { - _this.logger.log("acquired local media streams"); - // Remove old tracks - if (_this.peerConnection.removeTrack) { - _this.peerConnection.getSenders().forEach(function (sender) { - _this.peerConnection.removeTrack(sender); - }); - } - return streams; - }).catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("acquire", e, "error removing streams"); - _this.logger.error(error.message); - if (error.error) { - _this.logger.error(error.error); - } - throw error; - }).then(function (streams) { - var streamsArr = [].concat(streams); - streamsArr.forEach(function (stream) { - if (_this.peerConnection.addTrack) { - stream.getTracks().forEach(function (track) { - _this.peerConnection.addTrack(track, stream); - }); - } - else { - // Chrome 59 does not support addTrack - _this.peerConnection.addStream(stream); - } - }); - return Promise.resolve(); - }).catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("acquire", e, "error adding stream"); - _this.logger.error(error.message); - if (error.error) { - _this.logger.error(error.error); - } - throw error; - }); - }; - SessionDescriptionHandler.prototype.hasOffer = function (where) { - var offerState = "have-" + where + "-offer"; - return this.peerConnection.signalingState === offerState; - }; - // ICE gathering state handling - SessionDescriptionHandler.prototype.isIceGatheringComplete = function () { - return this.peerConnection.iceGatheringState === "complete" || this.iceGatheringTimeout; - }; - SessionDescriptionHandler.prototype.resetIceGatheringComplete = function () { - this.iceGatheringTimeout = false; - this.logger.log("resetIceGatheringComplete"); - if (this.iceGatheringTimer) { - clearTimeout(this.iceGatheringTimer); - this.iceGatheringTimer = undefined; - } - if (this.iceGatheringDeferred) { - this.iceGatheringDeferred.reject(); - this.iceGatheringDeferred = undefined; - } - }; - SessionDescriptionHandler.prototype.setDirection = function (sdp) { - var match = sdp.match(/a=(sendrecv|sendonly|recvonly|inactive)/); - if (match === null) { - this.direction = this.C.DIRECTION.NULL; - this.observer.directionChanged(); - return; - } - var direction = match[1]; - switch (direction) { - case this.C.DIRECTION.SENDRECV: - case this.C.DIRECTION.SENDONLY: - case this.C.DIRECTION.RECVONLY: - case this.C.DIRECTION.INACTIVE: - this.direction = direction; - break; - default: - this.direction = this.C.DIRECTION.NULL; - break; - } - this.observer.directionChanged(); - }; - SessionDescriptionHandler.prototype.triggerIceGatheringComplete = function () { - if (this.isIceGatheringComplete()) { - this.emit("iceGatheringComplete", this); - if (this.iceGatheringTimer) { - clearTimeout(this.iceGatheringTimer); - this.iceGatheringTimer = undefined; - } - if (this.iceGatheringDeferred) { - this.iceGatheringDeferred.resolve(); - this.iceGatheringDeferred = undefined; - } - } - }; - SessionDescriptionHandler.prototype.waitForIceGatheringComplete = function () { - this.logger.log("waitForIceGatheringComplete"); - if (this.isIceGatheringComplete()) { - this.logger.log("ICE is already complete. Return resolved."); - return Promise.resolve(); - } - else if (!this.iceGatheringDeferred) { - this.iceGatheringDeferred = Utils_1.Utils.defer(); - } - this.logger.log("ICE is not complete. Returning promise"); - return this.iceGatheringDeferred ? this.iceGatheringDeferred.promise : Promise.resolve(); - }; - return SessionDescriptionHandler; -}(events_1.EventEmitter)); -exports.SessionDescriptionHandler = SessionDescriptionHandler; - - -/***/ }), -/* 95 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var events_1 = __webpack_require__(30); -var Constants_1 = __webpack_require__(80); -var core_1 = __webpack_require__(2); -var allowed_methods_1 = __webpack_require__(58); -var Enums_1 = __webpack_require__(82); -var Exceptions_1 = __webpack_require__(84); -var Utils_1 = __webpack_require__(83); -var emitter_1 = __webpack_require__(96); -var info_1 = __webpack_require__(97); -var notification_1 = __webpack_require__(98); -var referral_1 = __webpack_require__(99); -var session_state_1 = __webpack_require__(100); -/** - * A session provides real time communication between one or more participants. - * @public - */ -var Session = /** @class */ (function (_super) { - tslib_1.__extends(Session, _super); - /** - * Constructor. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @internal - */ - function Session(userAgent, options) { - if (options === void 0) { options = {}; } - var _this = _super.call(this) || this; - // Property overlap with ClientContext & ServerContext Interfaces - /** @internal */ - _this.type = Enums_1.TypeStrings.Session; - /** @internal */ - _this.method = Constants_1.C.INVITE; - /** @internal */ - _this.localHold = false; - /** DEPRECATED: Session status */ - /** @internal */ - _this.status = Enums_1.SessionStatus.STATUS_NULL; - /** True if an error caused session termination. */ - /** @internal */ - _this.isFailed = false; - /** @internal */ - _this.rel100 = Constants_1.C.supported.UNSUPPORTED; - /** @internal */ - _this.expiresTimer = undefined; - /** @internal */ - _this.userNoAnswerTimer = undefined; - _this._state = session_state_1.SessionState.Initial; - _this._stateEventEmitter = new events_1.EventEmitter(); - _this.pendingReinvite = false; - _this.tones = undefined; - _this.userAgent = userAgent; - _this.delegate = options.delegate; - _this.logger = userAgent.getLogger("sip.session"); - _this.errorListener = _this.onTransportError.bind(_this); - if (userAgent.transport) { - userAgent.transport.on("transportError", _this.errorListener); - } - return _this; - } - /** - * @deprecated Legacy state transition. - * @internal - */ - Session.prototype.on = function (name, callback) { - return _super.prototype.on.call(this, name, callback); - }; - /** - * @deprecated Legacy state transition. - * @internal - */ - Session.prototype.emit = function (event) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - return _super.prototype.emit.apply(this, [event].concat(args)); - }; - Object.defineProperty(Session.prototype, "sessionDescriptionHandler", { - /** - * Session description handler. - */ - get: function () { - return this._sessionDescriptionHandler; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Session.prototype, "sessionDescriptionHandlerFactory", { - /** - * Session description handler factory. - */ - get: function () { - return this.userAgent.configuration.sessionDescriptionHandlerFactory; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Session.prototype, "state", { - /** - * Session state. - */ - get: function () { - return this._state; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Session.prototype, "stateChange", { - /** - * Session state change emitter. - */ - get: function () { - return emitter_1.makeEmitter(this._stateEventEmitter); - }, - enumerable: true, - configurable: true - }); - /** - * Renegotiate the session. Sends a re-INVITE. - * @param options - Options bucket. - */ - Session.prototype.invite = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - this.logger.log("Session.invite"); - if (this.state !== session_state_1.SessionState.Established) { - return Promise.reject(new Error("Invalid session state " + this.state)); - } - if (this.pendingReinvite) { - return Promise.reject(new Error("Reinvite in progress. Please wait until complete, then try again.")); - } - if (!this._sessionDescriptionHandler) { - throw new Error("Session description handler undefined."); - } - this.pendingReinvite = true; - var delegate = { - onAccept: function (response) { - // A re-INVITE transaction has an offer/answer [RFC3264] exchange - // associated with it. The UAC (User Agent Client) generating a given - // re-INVITE can act as the offerer or as the answerer. A UAC willing - // to act as the offerer includes an offer in the re-INVITE. The UAS - // (User Agent Server) then provides an answer in a response to the - // re-INVITE. A UAC willing to act as answerer does not include an - // offer in the re-INVITE. The UAS then provides an offer in a response - // to the re-INVITE becoming, thus, the offerer. - // https://tools.ietf.org/html/rfc6141#section-1 - var body = core_1.getBody(response.message); - if (!body) { - // No way to recover, so terminate session and mark as failed. - _this.logger.error("Received 2xx response to re-INVITE without a session description"); - _this.ackAndBye(response, 400, "Missing session description"); - _this.stateTransition(session_state_1.SessionState.Terminated); - _this.isFailed = true; - _this.pendingReinvite = false; - return; - } - if (options.withoutSdp) { - // INVITE without SDP - set remote offer and send an answer in the ACK - // FIXME: SDH options & SDH modifiers options are applied somewhat ambiguously - // This behavior was ported from legacy code and the issue punted down the road. - var answerOptions = { - sessionDescriptionHandlerOptions: options.sessionDescriptionHandlerOptions, - sessionDescriptionHandlerModifiers: options.sessionDescriptionHandlerModifiers - }; - _this.setOfferAndGetAnswer(body, answerOptions) - .then(function (answerBody) { - var request = response.ack({ body: answerBody }); - }) - .catch(function (error) { - // No way to recover, so terminate session and mark as failed. - _this.logger.error(error.message); - _this.logger.error("Failed to handle offer in 2xx response to re-INVITE"); - _this.ackAndBye(response, 488, "Bad Media Description"); - _this.stateTransition(session_state_1.SessionState.Terminated); - _this.isFailed = true; - }) - .then(function () { - _this.pendingReinvite = false; - if (options.requestDelegate && options.requestDelegate.onAccept) { - options.requestDelegate.onAccept(response); - } - }); - } - else { - // INVITE with SDP - set remote answer and send an ACK - // FIXME: SDH options & SDH modifiers options are applied somewhat ambiguously - // This behavior was ported from legacy code and the issue punted down the road. - var answerOptions = { - sessionDescriptionHandlerOptions: _this.sessionDescriptionHandlerOptions, - sessionDescriptionHandlerModifiers: _this.sessionDescriptionHandlerModifiers - }; - _this.setAnswer(body, answerOptions) - .then(function () { - var request = response.ack(); - }) - .catch(function (error) { - // No way to recover, so terminate session and mark as failed. - _this.logger.error(error.message); - _this.logger.error("Failed to handle answer in 2xx response to re-INVITE"); - _this.ackAndBye(response, 488, "Bad Media Description"); - _this.stateTransition(session_state_1.SessionState.Terminated); - _this.isFailed = true; - }) - .then(function () { - _this.pendingReinvite = false; - if (options.requestDelegate && options.requestDelegate.onAccept) { - options.requestDelegate.onAccept(response); - } - }); - } - }, - onProgress: function (response) { - return; - }, - onRedirect: function (response) { - return; - }, - onReject: function (response) { - _this.logger.warn("Received a non-2xx response to re-INVITE"); - _this.pendingReinvite = false; - if (options.withoutSdp) { - if (options.requestDelegate && options.requestDelegate.onReject) { - options.requestDelegate.onReject(response); - } - } - else { - _this.rollbackOffer() - .catch(function (error) { - // No way to recover, so terminate session and mark as failed. - _this.logger.error(error.message); - _this.logger.error("Failed to rollback offer on non-2xx response to re-INVITE"); - // Note that the ACK was already sent by the transaction, so just need to send BYE - if (!_this.dialog) { - throw new Error("Dialog undefined."); - } - var extraHeaders = []; - extraHeaders.push("Reason: " + Utils_1.Utils.getReasonHeaderValue(500, "Internal Server Error")); - var outgoingByeRequest = _this.dialog.bye(undefined, { extraHeaders: extraHeaders }); - _this.stateTransition(session_state_1.SessionState.Terminated); - _this.isFailed = true; - }) - .then(function () { - if (options.requestDelegate && options.requestDelegate.onReject) { - options.requestDelegate.onReject(response); - } - }); - } - }, - onTrying: function (response) { - return; - } - }; - var requestOptions = options.requestOptions || {}; - requestOptions.extraHeaders = (requestOptions.extraHeaders || []).slice(); - requestOptions.extraHeaders.push("Allow: " + allowed_methods_1.AllowedMethods.toString()); - requestOptions.extraHeaders.push("Contact: " + this.contact); - // Just send an INVITE with no sdp... - if (options.withoutSdp) { - if (!this.dialog) { - this.pendingReinvite = false; - return Promise.reject(new Error("Dialog undefined.")); - } - return Promise.resolve(this.dialog.invite(delegate, requestOptions)); - } - // Get an offer and send it in an INVITE - // FIXME: SDH options & SDH modifiers options are applied somewhat ambiguously - // This behavior was ported from legacy code and the issue punted down the road. - var offerOptions = { - sessionDescriptionHandlerOptions: options.sessionDescriptionHandlerOptions, - sessionDescriptionHandlerModifiers: options.sessionDescriptionHandlerModifiers - }; - return this.getOffer(offerOptions) - .then(function (offerBody) { - if (!_this.dialog) { - _this.pendingReinvite = false; - throw new Error("Dialog undefined."); - } - requestOptions.body = offerBody; - return _this.dialog.invite(delegate, requestOptions); - }) - .catch(function (error) { - _this.logger.error(error.message); - _this.logger.error("Failed to send re-INVITE"); - _this.pendingReinvite = false; - throw error; - }); - }; - /** - * TODO: This is awkward. - * Helper function - * @internal - */ - Session.prototype.byePending = function () { - this.stateTransition(session_state_1.SessionState.Terminating); - this.terminated(); - }; - /** - * TODO: This is awkward. - * Helper function - * @internal - */ - Session.prototype.byeSent = function (request) { - this.emit("bye", request.message); - this.stateTransition(session_state_1.SessionState.Terminated); - this.terminated(); - }; - /** - * Send BYE. - * @param delegate - Request delegate. - * @param options - Request options bucket. - * @internal - */ - Session.prototype.bye = function (delegate, options) { - var _this = this; - // Using core session dialog - if (!this.dialog) { - return Promise.reject(new Error("Session dialog undefined.")); - } - var dialog = this.dialog; - // The caller's UA MAY send a BYE for either confirmed or early dialogs, - // and the callee's UA MAY send a BYE on confirmed dialogs, but MUST NOT - // send a BYE on early dialogs. However, the callee's UA MUST NOT send a - // BYE on a confirmed dialog until it has received an ACK for its 2xx - // response or until the server transaction times out. - // https://tools.ietf.org/html/rfc3261#section-15 - switch (dialog.sessionState) { - case core_1.SessionState.Initial: - throw new Error("Invalid dialog state " + dialog.sessionState); - case core_1.SessionState.Early: // Implementation choice - not sending BYE for early dialogs. - throw new Error("Invalid dialog state " + dialog.sessionState); - case core_1.SessionState.AckWait: { // This state only occurs if we are the callee. - this.byePending(); - return new Promise(function (resolve, reject) { - dialog.delegate = { - // When ACK shows up, say BYE. - onAck: function () { - var request = dialog.bye(delegate, options); - _this.byeSent(request); - resolve(request); - }, - // Or the server transaction times out before the ACK arrives. - onAckTimeout: function () { - var request = dialog.bye(delegate, options); - _this.byeSent(request); - resolve(request); - } - }; - }); - } - case core_1.SessionState.Confirmed: { - var request = dialog.bye(delegate, options); - this.byeSent(request); - return Promise.resolve(request); - } - case core_1.SessionState.Terminated: - throw new Error("Invalid dialog state " + dialog.sessionState); - default: - throw new Error("Unrecognized state."); - } - }; - /** - * Send INFO. - * @param delegate - Request delegate. - * @param options - Request options bucket. - * @internal - */ - Session.prototype.info = function (delegate, options) { - // Using core session dialog - if (!this.dialog) { - return Promise.reject(new Error("Session dialog undefined.")); - } - return Promise.resolve(this.dialog.info(delegate, options)); - }; - /** - * Send REFER. - * @param delegate - Request delegate. - * @param options - Request options bucket. - * @internal - */ - Session.prototype.refer = function (referrer, delegate, options) { - // Using core session dialog - if (!this.dialog) { - return Promise.reject(new Error("Session dialog undefined.")); - } - // If the session has a referrer, it will receive any in-dialog NOTIFY requests. - this.referrer = referrer; - return Promise.resolve(this.dialog.refer(delegate, options)); - }; - /** - * @internal - */ - Session.prototype.close = function () { - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return; - } - this.logger.log("closing INVITE session " + this.id); - // 1st Step. Terminate media. - if (this._sessionDescriptionHandler) { - this._sessionDescriptionHandler.close(); - } - // 2nd Step. Terminate signaling. - // Clear session timers - if (this.expiresTimer) { - clearTimeout(this.expiresTimer); - } - if (this.userNoAnswerTimer) { - clearTimeout(this.userNoAnswerTimer); - } - this.status = Enums_1.SessionStatus.STATUS_TERMINATED; - if (this.userAgent.transport) { - this.userAgent.transport.removeListener("transportError", this.errorListener); - } - if (!this.id) { - throw new Error("Session id undefined."); - } - delete this.userAgent.sessions[this.id]; - return; - }; - /** - * @internal - */ - Session.prototype.onRequestTimeout = function () { - if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { - this.terminated(undefined, Constants_1.C.causes.REQUEST_TIMEOUT); - } - else if (this.status !== Enums_1.SessionStatus.STATUS_TERMINATED) { - this.failed(undefined, Constants_1.C.causes.REQUEST_TIMEOUT); - this.terminated(undefined, Constants_1.C.causes.REQUEST_TIMEOUT); - } - }; - /** - * @internal - */ - Session.prototype.onTransportError = function () { - if (this.status !== Enums_1.SessionStatus.STATUS_CONFIRMED && this.status !== Enums_1.SessionStatus.STATUS_TERMINATED) { - this.failed(undefined, Constants_1.C.causes.CONNECTION_ERROR); - } - }; - /** - * Send ACK and then BYE. There are unrecoverable errors which can occur - * while handling dialog forming and in-dialog INVITE responses and when - * they occur we ACK the response and terminate the session. - * @param inviteResponse - The response causing the error. - * @param statusCode - Status code for he reason phrase. - * @param reasonPhrase - Reason phrase for the BYE. - * @internal - */ - Session.prototype.ackAndBye = function (response, statusCode, reasonPhrase) { - var outgoingAckRequest = response.ack(); - var extraHeaders = []; - if (statusCode) { - extraHeaders.push("Reason: " + Utils_1.Utils.getReasonHeaderValue(statusCode, reasonPhrase)); - } - var outgoingByeRequest = response.session.bye(undefined, { extraHeaders: extraHeaders }); - this.emit("bye", outgoingByeRequest.message); - }; - /** - * Handle in dialog ACK request. - * @internal - */ - Session.prototype.onAckRequest = function (request) { - var _this = this; - this.logger.log("Session.onAckRequest"); - if (this.state !== session_state_1.SessionState.Initial && - this.state !== session_state_1.SessionState.Establishing && - this.state !== session_state_1.SessionState.Established && - this.state !== session_state_1.SessionState.Terminating) { - this.logger.error("ACK received while in state " + this.state + ", dropping request"); - return; - } - // FIXME: Review is this ever true? We're "Established" when dialog created in accept(). - if (this.state === session_state_1.SessionState.Initial || this.state === session_state_1.SessionState.Establishing) { - this.stateTransition(session_state_1.SessionState.Established); - } - var dialog = this.dialog; - if (!dialog) { - throw new Error("Dialog undefined."); - } - // Helper function. - var confirmSession = function () { - _this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; - _this.emit("confirmed", request.message); - }; - // If the ACK doesn't have an offer/answer, nothing to be done. - var body = core_1.getBody(request.message); - if (!body) { - confirmSession(); - return; - } - if (body.contentDisposition === "render") { - this.renderbody = body.content; - this.rendertype = body.contentType; - confirmSession(); - return; - } - if (body.contentDisposition !== "session") { - confirmSession(); - return; - } - var options = { - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers - }; - switch (dialog.signalingState) { - case core_1.SignalingState.Initial: - // State should never be reached as first reliable response must have answer/offer. - throw new Error("Invalid signaling state " + dialog.signalingState + "."); - case core_1.SignalingState.Stable: - // Receved answer. - this.setAnswer(body, options) - .then(function () { return confirmSession(); }) - .catch(function (error) { - // FIXME: TODO - need to do something to handle this error - _this.logger.error(error); - var extraHeaders = ["Reason: " + Utils_1.Utils.getReasonHeaderValue(488, "Bad Media Description")]; - _this.bye(undefined, { extraHeaders: extraHeaders }); - _this.failed(request.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - _this.terminated(request.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - throw error; - }); - return; - case core_1.SignalingState.HaveLocalOffer: - // State should never be reached as local offer would be answered by this ACK - throw new Error("Invalid signaling state " + dialog.signalingState + "."); - case core_1.SignalingState.HaveRemoteOffer: - // State should never be reached as remote offer would be answered in first reliable response. - throw new Error("Invalid signaling state " + dialog.signalingState + "."); - case core_1.SignalingState.Closed: - throw new Error("Invalid signaling state " + dialog.signalingState + "."); - default: - throw new Error("Invalid signaling state " + dialog.signalingState + "."); - } - }; - /** - * Handle in dialog BYE request. - * @internal - */ - Session.prototype.onByeRequest = function (request) { - this.logger.log("Session.onByeRequest"); - if (this.state !== session_state_1.SessionState.Established) { - this.logger.error("BYE received while in state " + this.state + ", dropping request"); - return; - } - request.accept(); - this.stateTransition(session_state_1.SessionState.Terminated); - if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { - this.emit("bye", request.message); - this.terminated(request.message, Constants_1.C.BYE); - } - }; - /** - * Handle in dialog INFO request. - * @internal - */ - Session.prototype.onInfoRequest = function (request) { - this.logger.log("Session.onInfoRequest"); - if (this.state !== session_state_1.SessionState.Established) { - this.logger.error("INFO received while in state " + this.state + ", dropping request"); - return; - } - if (this.delegate && this.delegate.onInfo) { - var info = new info_1.Info(request); - this.delegate.onInfo(info); - } - else { - request.accept(); - } - }; - /** - * Handle in dialog INVITE request. - * @internal - */ - Session.prototype.onInviteRequest = function (request) { - var _this = this; - this.logger.log("Session.onInviteRequest"); - if (this.state !== session_state_1.SessionState.Established) { - this.logger.error("INVITE received while in state " + this.state + ", dropping request"); - return; - } - // TODO: would be nice to have core track and set the Contact header, - // but currently the session which is setting it is holding onto it. - var extraHeaders = ["Contact: " + this.contact]; - // Check testing hooks - if (this.delegate && this.delegate.onReinviteTest) { - var test = this.delegate.onReinviteTest(); - if (test === "acceptWithoutDescription") { - request.accept({ statusCode: 200, extraHeaders: extraHeaders }); - return; - } - if (test === "reject488") { - request.reject({ statusCode: 488 }); - return; - } - } - // Handle P-Asserted-Identity - if (request.message.hasHeader("P-Asserted-Identity")) { - var header = request.message.getHeader("P-Asserted-Identity"); - if (!header) { - throw new Error("Header undefined."); - } - this.assertedIdentity = core_1.Grammar.nameAddrHeaderParse(header); - } - // FIXME: SDH options & SDH modifiers options are applied somewhat ambiguously - // This behavior was ported from legacy code and the issue punted down the road. - var options = { - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers - }; - this.generateResponseOfferAnswerInDialog(options) - .then(function (body) { - var outgoingResponse = request.accept({ statusCode: 200, extraHeaders: extraHeaders, body: body }); - if (_this.delegate && _this.delegate.onInvite) { - _this.delegate.onInvite(request.message, outgoingResponse.message, 200); - } - }) - .catch(function (error) { - _this.logger.error(error.message); - _this.logger.error("Failed to handle to re-INVITE request"); - if (!_this.dialog) { - throw new Error("Dialog undefined."); - } - _this.logger.error(_this.dialog.signalingState); - // If we don't have a local/remote offer... - if (_this.dialog.signalingState === core_1.SignalingState.Stable) { - var outgoingResponse = request.reject({ statusCode: 488 }); // Not Acceptable Here - if (_this.delegate && _this.delegate.onInvite) { - _this.delegate.onInvite(request.message, outgoingResponse.message, 488); - } - return; - } - // Otherwise rollback - _this.rollbackOffer() - .then(function () { - var outgoingResponse = request.reject({ statusCode: 488 }); // Not Acceptable Here - if (_this.delegate && _this.delegate.onInvite) { - _this.delegate.onInvite(request.message, outgoingResponse.message, 488); - } - }) - .catch(function (errorRollback) { - // No way to recover, so terminate session and mark as failed. - _this.logger.error(errorRollback.message); - _this.logger.error("Failed to rollback offer on re-INVITE request"); - var outgoingResponse = request.reject({ statusCode: 488 }); // Not Acceptable Here - var extraHeadersBye = []; - extraHeadersBye.push("Reason: " + Utils_1.Utils.getReasonHeaderValue(500, "Internal Server Error")); - if (!_this.dialog) { - throw new Error("Dialog undefined."); - } - var outgoingByeRequest = _this.dialog.bye(undefined, { extraHeaders: extraHeaders }); - _this.stateTransition(session_state_1.SessionState.Terminated); - _this.isFailed = true; - if (_this.delegate && _this.delegate.onInvite) { - _this.delegate.onInvite(request.message, outgoingResponse.message, 488); - } - }); - }); - }; - /** - * Handle in dialog NOTIFY request. - * @internal - */ - Session.prototype.onNotifyRequest = function (request) { - this.logger.log("Session.onNotifyRequest"); - if (this.state !== session_state_1.SessionState.Established) { - this.logger.error("NOTIFY received while in state " + this.state + ", dropping request"); - return; - } - // DEPRECATED BEGIN - // ReferClientContext is deprecated - // if ( - // this.referContext && - // this.referContext.type === TypeStrings.ReferClientContext && - // incomingRequest.message.hasHeader("event") && - // /^refer(;.*)?$/.test(incomingRequest.message.getHeader("event") as string) - // ) { - // this.referContext.receiveNotify(incomingRequest); - // return; - // } - // DEPRECATED END - // If this a NOTIFY associated with the progress of a REFER, - // look to delegate handling to the associated Referrer. - if (this.referrer && this.referrer.delegate && this.referrer.delegate.onNotify) { - var notification = new notification_1.Notification(request); - this.referrer.delegate.onNotify(notification); - return; - } - // Otherwise accept the NOTIFY. - if (this.delegate && this.delegate.onNotify) { - var notification = new notification_1.Notification(request); - this.delegate.onNotify(notification); - } - else { - request.accept(); - } - this.emit("notify", request.message); - }; - /** - * Handle in dialog PRACK request. - * @internal - */ - Session.prototype.onPrackRequest = function (request) { - this.logger.log("Session.onPrackRequest"); - if (this.state !== session_state_1.SessionState.Established) { - this.logger.error("PRACK received while in state " + this.state + ", dropping request"); - return; - } - throw new Error("Unimplemented."); - }; - /** - * Handle in dialog REFER request. - * @internal - */ - Session.prototype.onReferRequest = function (request) { - var _this = this; - this.logger.log("Session.onReferRequest"); - if (this.state !== session_state_1.SessionState.Established) { - this.logger.error("REFER received while in state " + this.state + ", dropping request"); - return; - } - if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { - // RFC 3515 2.4.1 - if (!request.message.hasHeader("refer-to")) { - this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting."); - request.reject(); - return; - } - // DEPRECATED BEGIN - // // ReferServerContext is deprecated - // if (this.listeners("referRequested").length) { - // const referContext = new ReferServerContext(this.ua, incomingRequest, this.dialog); - // this.emit("referRequested", referContext); - // return; - // } - // DEPRECATED END - var referral_2 = new referral_1.Referral(request, this); - if (this.delegate && this.delegate.onRefer) { - this.delegate.onRefer(referral_2); - } - else { - this.logger.log("No delegate available to handle REFER, automatically accepting and following."); - referral_2 - .accept() - .then(function () { return referral_2 - .makeInviter(_this.passedOptions) - .invite(); }) - .catch(function (error) { - // FIXME: logging and eating error... - _this.logger.error(error.message); - }); - } - } - }; - /** - * @deprecated Legacy state transition. - * @internal - */ - Session.prototype.connecting = function (request) { - this.emit("connecting", { request: request }); - }; - /** - * @deprecated Legacy state transition. - * @internal - */ - Session.prototype.failed = function (response, cause) { - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return; - } - this.emit("failed", response, cause); - }; - /** - * @deprecated Legacy state transition. - * @internal - */ - Session.prototype.rejected = function (response, cause) { - this.emit("rejected", response, cause); - }; - /** - * @deprecated Legacy state transition. - * @internal - */ - Session.prototype.terminated = function (message, cause) { - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return; - } - this.endTime = new Date(); - this.close(); - this.emit("terminated", message, cause); - }; - /** - * Generate an offer or answer for a response to an INVITE request. - * If a remote offer was provided in the request, set the remote - * description and get a local answer. If a remote offer was not - * provided, generates a local offer. - * @internal - */ - Session.prototype.generateResponseOfferAnswer = function (request, options) { - if (this.dialog) { - return this.generateResponseOfferAnswerInDialog(options); - } - var body = core_1.getBody(request.message); - if (!body || body.contentDisposition !== "session") { - return this.getOffer(options); - } - else { - return this.setOfferAndGetAnswer(body, options); - } - }; - /** - * Generate an offer or answer for a response to an INVITE request - * when a dialog (early or otherwise) has already been established. - * This method may NOT be called if a dialog has yet to be established. - * @internal - */ - Session.prototype.generateResponseOfferAnswerInDialog = function (options) { - if (!this.dialog) { - throw new Error("Dialog undefined."); - } - switch (this.dialog.signalingState) { - case core_1.SignalingState.Initial: - return this.getOffer(options); - case core_1.SignalingState.HaveLocalOffer: - // o Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - return Promise.resolve(undefined); - case core_1.SignalingState.HaveRemoteOffer: - if (!this.dialog.offer) { - throw new Error("Session offer undefined in signaling state " + this.dialog.signalingState + "."); - } - return this.setOfferAndGetAnswer(this.dialog.offer, options); - case core_1.SignalingState.Stable: - // o Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - if (this.state !== session_state_1.SessionState.Established) { - return Promise.resolve(undefined); - } - // In dialog INVITE without offer, get an offer for the response. - return this.getOffer(options); - case core_1.SignalingState.Closed: - throw new Error("Invalid signaling state " + this.dialog.signalingState + "."); - default: - throw new Error("Invalid signaling state " + this.dialog.signalingState + "."); - } - }; - /** - * Get local offer. - * @internal - */ - Session.prototype.getOffer = function (options) { - var sdh = this.setupSessionDescriptionHandler(); - var sdhOptions = options.sessionDescriptionHandlerOptions; - var sdhModifiers = options.sessionDescriptionHandlerModifiers; - return sdh.getDescription(sdhOptions, sdhModifiers) - .then(function (bodyAndContentType) { return Utils_1.Utils.fromBodyObj(bodyAndContentType); }) - .catch(function (error) { - throw (error instanceof Error ? error : new Error(error)); - }); - }; - /** - * Rollback local/remote offer. - * @internal - */ - Session.prototype.rollbackOffer = function () { - var sdh = this.setupSessionDescriptionHandler(); - if (!sdh.rollbackDescription) { - return Promise.resolve(); - } - return sdh.rollbackDescription() - .catch(function (error) { - throw (error instanceof Error ? error : new Error(error)); - }); - }; - /** - * Set remote answer. - * @internal - */ - Session.prototype.setAnswer = function (answer, options) { - var sdh = this.setupSessionDescriptionHandler(); - var sdhOptions = options.sessionDescriptionHandlerOptions; - var sdhModifiers = options.sessionDescriptionHandlerModifiers; - if (!sdh.hasDescription(answer.contentType)) { - return Promise.reject(new Exceptions_1.Exceptions.UnsupportedSessionDescriptionContentTypeError()); - } - return sdh.setDescription(answer.content, sdhOptions, sdhModifiers) - .catch(function (error) { - throw (error instanceof Error ? error : new Error(error)); - }); - }; - /** - * Set remote offer and get local answer. - * @internal - */ - Session.prototype.setOfferAndGetAnswer = function (offer, options) { - var sdh = this.setupSessionDescriptionHandler(); - var sdhOptions = options.sessionDescriptionHandlerOptions; - var sdhModifiers = options.sessionDescriptionHandlerModifiers; - if (!sdh.hasDescription(offer.contentType)) { - return Promise.reject(new Exceptions_1.Exceptions.UnsupportedSessionDescriptionContentTypeError()); - } - return sdh.setDescription(offer.content, sdhOptions, sdhModifiers) - .then(function () { return sdh.getDescription(sdhOptions, sdhModifiers); }) - .then(function (bodyAndContentType) { return Utils_1.Utils.fromBodyObj(bodyAndContentType); }) - .catch(function (error) { - throw (error instanceof Error ? error : new Error(error)); - }); - }; - /** - * SDH for confirmed dialog. - * @internal - */ - Session.prototype.setSessionDescriptionHandler = function (sdh) { - if (this._sessionDescriptionHandler) { - throw new Error("Sessionn description handler defined."); - } - this._sessionDescriptionHandler = sdh; - }; - /** - * SDH for confirmed dialog. - * @internal - */ - Session.prototype.setupSessionDescriptionHandler = function () { - if (this._sessionDescriptionHandler) { - return this._sessionDescriptionHandler; - } - this._sessionDescriptionHandler = - this.sessionDescriptionHandlerFactory(this, this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions); - this.emit("SessionDescriptionHandler-created", this._sessionDescriptionHandler); - return this._sessionDescriptionHandler; - }; - /** - * Transition session state. - * @internal - */ - Session.prototype.stateTransition = function (newState) { - var _this = this; - var invalidTransition = function () { - throw new Error("Invalid state transition from " + _this._state + " to " + newState); - }; - // Validate transition - switch (this._state) { - case session_state_1.SessionState.Initial: - if (newState !== session_state_1.SessionState.Establishing && - newState !== session_state_1.SessionState.Established && - newState !== session_state_1.SessionState.Terminating && - newState !== session_state_1.SessionState.Terminated) { - invalidTransition(); - } - break; - case session_state_1.SessionState.Establishing: - if (newState !== session_state_1.SessionState.Established && - newState !== session_state_1.SessionState.Terminating && - newState !== session_state_1.SessionState.Terminated) { - invalidTransition(); - } - break; - case session_state_1.SessionState.Established: - if (newState !== session_state_1.SessionState.Terminating && - newState !== session_state_1.SessionState.Terminated) { - invalidTransition(); - } - break; - case session_state_1.SessionState.Terminating: - if (newState !== session_state_1.SessionState.Terminated) { - invalidTransition(); - } - break; - case session_state_1.SessionState.Terminated: - invalidTransition(); - break; - default: - throw new Error("Unrecognized state."); - } - // Deprecated legacy ported behavior - if (newState === session_state_1.SessionState.Established) { - this.startTime = new Date(); - } - // Transition - this._state = newState; - this.logger.log("Session " + this.id + " transitioned to state " + this._state); - this._stateEventEmitter.emit("event", this._state); - }; - // DEPRECATED - /** @internal */ - Session.C = Enums_1.SessionStatus; - return Session; -}(events_1.EventEmitter)); -exports.Session = Session; - - -/***/ }), -/* 96 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * Creates an {@link Emitter}. - * @param eventEmitter - An event emitter. - * @param eventName - Event name. - * @internal - */ -function makeEmitter(eventEmitter, eventName) { - if (eventName === void 0) { eventName = "event"; } - return { - on: function (listener) { - eventEmitter.on(eventName, listener); - }, - off: function (listener) { - eventEmitter.removeListener(eventName, listener); - }, - once: function (listener) { - eventEmitter.once(eventName, listener); - } - }; -} -exports.makeEmitter = makeEmitter; - - -/***/ }), -/* 97 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * An exchange of information (incoming INFO). - * @public - */ -var Info = /** @class */ (function () { - /** @internal */ - function Info(incomingInfoRequest) { - this.incomingInfoRequest = incomingInfoRequest; - } - Object.defineProperty(Info.prototype, "request", { - /** Incoming MESSAGE request message. */ - get: function () { - return this.incomingInfoRequest.message; - }, - enumerable: true, - configurable: true - }); - /** Accept the request. */ - Info.prototype.accept = function (options) { - this.incomingInfoRequest.accept(options); - return Promise.resolve(); - }; - /** Reject the request. */ - Info.prototype.reject = function (options) { - this.incomingInfoRequest.reject(options); - return Promise.resolve(); - }; - return Info; -}()); -exports.Info = Info; - - -/***/ }), -/* 98 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * A notification of an event (incoming NOTIFY). - * @public - */ -var Notification = /** @class */ (function () { - /** @internal */ - function Notification(incomingNotifyRequest) { - this.incomingNotifyRequest = incomingNotifyRequest; - } - Object.defineProperty(Notification.prototype, "request", { - /** Incoming NOTIFY request message. */ - get: function () { - return this.incomingNotifyRequest.message; - }, - enumerable: true, - configurable: true - }); - /** Accept the request. */ - Notification.prototype.accept = function (options) { - this.incomingNotifyRequest.accept(options); - return Promise.resolve(); - }; - /** Reject the request. */ - Notification.prototype.reject = function (options) { - this.incomingNotifyRequest.reject(options); - return Promise.resolve(); - }; - return Notification; -}()); -exports.Notification = Notification; - - -/***/ }), -/* 99 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var core_1 = __webpack_require__(2); -/** - * A request to establish a {@link Session} elsewhere (incoming REFER). - * @public - */ -var Referral = /** @class */ (function () { - /** @internal */ - function Referral(incomingReferRequest, session) { - this.incomingReferRequest = incomingReferRequest; - this.session = session; - } - Object.defineProperty(Referral.prototype, "referTo", { - get: function () { - var referTo = this.incomingReferRequest.message.parseHeader("refer-to"); - if (!(referTo instanceof core_1.NameAddrHeader)) { - throw new Error("Failed to parse Refer-To header."); - } - return referTo; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Referral.prototype, "referredBy", { - get: function () { - return this.incomingReferRequest.message.getHeader("referred-by"); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Referral.prototype, "replaces", { - get: function () { - return this.referTo.uri.getHeader("replaces"); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Referral.prototype, "request", { - /** Incoming REFER request message. */ - get: function () { - return this.incomingReferRequest.message; - }, - enumerable: true, - configurable: true - }); - /** Accept the request. */ - Referral.prototype.accept = function (options) { - if (options === void 0) { options = { statusCode: 202 }; } - this.incomingReferRequest.accept(options); - return Promise.resolve(); - }; - /** Reject the request. */ - Referral.prototype.reject = function (options) { - this.incomingReferRequest.reject(options); - return Promise.resolve(); - }; - /** - * Creates an inviter which may be used to send an out of dialog INVITE request. - * - * @remarks - * This a helper method to create an Inviter which will execute the referral - * of the `Session` which was referred. The appropriate headers are set and - * the referred `Session` is linked to the new `Session`. Note that only a - * single instance of the `Inviter` will be created and returned (if called - * more than once a reference to the same `Inviter` will be returned every time). - * - * @param options - Options bucket. - * @param modifiers - Session description handler modifiers. - */ - Referral.prototype.makeInviter = function (options) { - if (this.inviter) { - return this.inviter; - } - var targetURI = this.referTo.uri.clone(); - targetURI.clearHeaders(); - options = options || {}; - var extraHeaders = (options.extraHeaders || []).slice(); - var replaces = this.replaces; - if (replaces) { - // decodeURIComponent is a holdover from 2c086eb4. Not sure that it is actually necessary - extraHeaders.push("Replaces: " + decodeURIComponent(replaces)); - } - var referredBy = this.referredBy; - if (referredBy) { - extraHeaders.push("Referred-By: " + referredBy); - } - options.extraHeaders = extraHeaders; - this.inviter = this.session.userAgent.makeInviter(targetURI, options); - this.inviter.referred = this.session; - this.session.referral = this.inviter; - return this.inviter; - }; - return Referral; -}()); -exports.Referral = Referral; - - -/***/ }), -/* 100 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * {@link Session} state. - * @remarks - * Valid state transitions: - * ``` - * 1. "initial" --> "establishing" (before INVITE sent on outgoing, before OK sent on incoming) - * 2. "initial" --> "established" (after ACK is sent on outgoing, after OK sent on incoming) - * 4. "initial" --> "terminating" - * 4. "initial" --> "terminated" - * 5. "establishing" --> "established" - * 6. "establishing" --> "terminating" - * 7. "establishing" --> "terminated" - * 8. "established" --> "terminating" - * 9. "established" --> "terminated" - * 10. "terminating" --> "terminated" - * ``` - * @public - */ -var SessionState; -(function (SessionState) { - SessionState["Initial"] = "Initial"; - SessionState["Establishing"] = "Establishing"; - SessionState["Established"] = "Established"; - SessionState["Terminating"] = "Terminating"; - SessionState["Terminated"] = "Terminated"; -})(SessionState = exports.SessionState || (exports.SessionState = {})); - - -/***/ }), -/* 101 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var stripPayload = function (sdp, payload) { - var mediaDescs = []; - var lines = sdp.split(/\r\n/); - var currentMediaDesc; - for (var i = 0; i < lines.length;) { - var line = lines[i]; - if (/^m=(?:audio|video)/.test(line)) { - currentMediaDesc = { - index: i, - stripped: [] - }; - mediaDescs.push(currentMediaDesc); - } - else if (currentMediaDesc) { - var rtpmap = /^a=rtpmap:(\d+) ([^/]+)\//.exec(line); - if (rtpmap && payload === rtpmap[2]) { - lines.splice(i, 1); - currentMediaDesc.stripped.push(rtpmap[1]); - continue; // Don't increment 'i' - } - } - i++; - } - for (var _i = 0, mediaDescs_1 = mediaDescs; _i < mediaDescs_1.length; _i++) { - var mediaDesc = mediaDescs_1[_i]; - var mline = lines[mediaDesc.index].split(" "); - // Ignore the first 3 parameters of the mline. The codec information is after that - for (var j = 3; j < mline.length;) { - if (mediaDesc.stripped.indexOf(mline[j]) !== -1) { - mline.splice(j, 1); - continue; - } - j++; - } - lines[mediaDesc.index] = mline.join(" "); - } - return lines.join("\r\n"); -}; -var stripMediaDescription = function (sdp, description) { - var descriptionRegExp = new RegExp("m=" + description + ".*$", "gm"); - var groupRegExp = new RegExp("^a=group:.*$", "gm"); - if (descriptionRegExp.test(sdp)) { - var midLineToRemove_1; - sdp = sdp.split(/^m=/gm).filter(function (section) { - if (section.substr(0, description.length) === description) { - midLineToRemove_1 = section.match(/^a=mid:.*$/gm); - if (midLineToRemove_1) { - var step = midLineToRemove_1[0].match(/:.+$/g); - if (step) { - midLineToRemove_1 = step[0].substr(1); - } - } - return false; - } - return true; - }).join("m="); - var groupLine = sdp.match(groupRegExp); - if (groupLine && groupLine.length === 1) { - var groupLinePortion = groupLine[0]; - var groupRegExpReplace = new RegExp("\ *" + midLineToRemove_1 + "[^\ ]*", "g"); - groupLinePortion = groupLinePortion.replace(groupRegExpReplace, ""); - sdp = sdp.split(groupRegExp).join(groupLinePortion); - } - } - return sdp; -}; -function stripTcpCandidates(description) { - description.sdp = (description.sdp || "").replace(/^a=candidate:\d+ \d+ tcp .*?\r\n/img, ""); - return Promise.resolve(description); -} -exports.stripTcpCandidates = stripTcpCandidates; -function stripTelephoneEvent(description) { - description.sdp = stripPayload(description.sdp || "", "telephone-event"); - return Promise.resolve(description); -} -exports.stripTelephoneEvent = stripTelephoneEvent; -function cleanJitsiSdpImageattr(description) { - description.sdp = (description.sdp || "").replace(/^(a=imageattr:.*?)(x|y)=\[0-/gm, "$1$2=[1:"); - return Promise.resolve(description); -} -exports.cleanJitsiSdpImageattr = cleanJitsiSdpImageattr; -function stripG722(description) { - description.sdp = stripPayload(description.sdp || "", "G722"); - return Promise.resolve(description); -} -exports.stripG722 = stripG722; -function stripRtpPayload(payload) { - return function (description) { - description.sdp = stripPayload(description.sdp || "", payload); - return Promise.resolve(description); - }; -} -exports.stripRtpPayload = stripRtpPayload; -function stripVideo(description) { - description.sdp = stripMediaDescription(description.sdp || "", "video"); - return Promise.resolve(description); -} -exports.stripVideo = stripVideo; -function addMidLines(description) { - var sdp = description.sdp || ""; - if (sdp.search(/^a=mid.*$/gm) === -1) { - var mlines_1 = sdp.match(/^m=.*$/gm); - var sdpArray_1 = sdp.split(/^m=.*$/gm); - if (mlines_1) { - mlines_1.forEach(function (elem, idx) { - mlines_1[idx] = elem + "\na=mid:" + idx; - }); - } - sdpArray_1.forEach(function (elem, idx) { - if (mlines_1 && mlines_1[idx]) { - sdpArray_1[idx] = elem + mlines_1[idx]; - } - }); - sdp = sdpArray_1.join(""); - description.sdp = sdp; - } - return Promise.resolve(description); -} -exports.addMidLines = addMidLines; - - -/***/ }), -/* 102 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var Enums_1 = __webpack_require__(82); -/* SessionDescriptionHandlerObserver - * @class SessionDescriptionHandler Observer Class. - * @param {SIP.Session} session - * @param {Object} [options] - */ -var SessionDescriptionHandlerObserver = /** @class */ (function () { - function SessionDescriptionHandlerObserver(session, options) { - this.type = Enums_1.TypeStrings.SessionDescriptionHandlerObserver; - this.session = session; - this.options = options; - } - SessionDescriptionHandlerObserver.prototype.trackAdded = function () { - this.session.emit("trackAdded"); - }; - SessionDescriptionHandlerObserver.prototype.directionChanged = function () { - this.session.emit("directionChanged"); - }; - return SessionDescriptionHandlerObserver; -}()); -exports.SessionDescriptionHandlerObserver = SessionDescriptionHandlerObserver; - - -/***/ }), -/* 103 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var core_1 = __webpack_require__(2); -var Enums_1 = __webpack_require__(82); -var Exceptions_1 = __webpack_require__(84); -var Utils_1 = __webpack_require__(83); -var TransportStatus; -(function (TransportStatus) { - TransportStatus[TransportStatus["STATUS_CONNECTING"] = 0] = "STATUS_CONNECTING"; - TransportStatus[TransportStatus["STATUS_OPEN"] = 1] = "STATUS_OPEN"; - TransportStatus[TransportStatus["STATUS_CLOSING"] = 2] = "STATUS_CLOSING"; - TransportStatus[TransportStatus["STATUS_CLOSED"] = 3] = "STATUS_CLOSED"; -})(TransportStatus = exports.TransportStatus || (exports.TransportStatus = {})); -/** - * Compute an amount of time in seconds to wait before sending another - * keep-alive. - * @returns {Number} - */ -var computeKeepAliveTimeout = function (upperBound) { - var lowerBound = upperBound * 0.8; - return 1000 * (Math.random() * (upperBound - lowerBound) + lowerBound); -}; -/** - * @class Transport - * @param {Object} options - */ -var Transport = /** @class */ (function (_super) { - tslib_1.__extends(Transport, _super); - function Transport(logger, options) { - if (options === void 0) { options = {}; } - var _this = _super.call(this, logger, options) || this; - _this.type = Enums_1.TypeStrings.Transport; - _this.reconnectionAttempts = 0; - _this.status = TransportStatus.STATUS_CONNECTING; - _this.configuration = _this.loadConfig(options); - _this.server = _this.configuration.wsServers[0]; - return _this; - } - /** - * @returns {Boolean} - */ - Transport.prototype.isConnected = function () { - return this.status === TransportStatus.STATUS_OPEN; - }; - /** - * Send a message. - * @param {SIP.OutgoingRequest|String} msg - * @param {Object} [options] - * @returns {Promise} - */ - Transport.prototype.sendPromise = function (msg, options) { - if (options === void 0) { options = {}; } - if (!this.statusAssert(TransportStatus.STATUS_OPEN, options.force)) { - this.onError("unable to send message - WebSocket not open"); - return Promise.reject(); - } - var message = msg.toString(); - if (this.ws) { - if (this.configuration.traceSip === true) { - this.logger.log("sending WebSocket message:\n\n" + message + "\n"); - } - this.ws.send(message); - return Promise.resolve({ msg: message }); - } - else { - this.onError("unable to send message - WebSocket does not exist"); - return Promise.reject(); - } - }; - /** - * Disconnect socket. - */ - Transport.prototype.disconnectPromise = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - if (this.disconnectionPromise) { // Already disconnecting. Just return this. - return this.disconnectionPromise; - } - options.code = options.code || 1000; - if (!this.statusTransition(TransportStatus.STATUS_CLOSING, options.force)) { - if (this.status === TransportStatus.STATUS_CLOSED) { // Websocket is already closed - return Promise.resolve({ overrideEvent: true }); - } - else if (this.connectionPromise) { // Websocket is connecting, cannot move to disconneting yet - return this.connectionPromise.then(function () { return Promise.reject("The websocket did not disconnect"); }) - .catch(function () { return Promise.resolve({ overrideEvent: true }); }); - } - else { - // Cannot move to disconnecting, but not in connecting state. - return Promise.reject("The websocket did not disconnect"); - } - } - this.emit("disconnecting"); - this.disconnectionPromise = new Promise(function (resolve, reject) { - _this.disconnectDeferredResolve = resolve; - if (_this.reconnectTimer) { - clearTimeout(_this.reconnectTimer); - _this.reconnectTimer = undefined; - } - if (_this.ws) { - _this.stopSendingKeepAlives(); - _this.logger.log("closing WebSocket " + _this.server.wsUri); - _this.ws.close(options.code, options.reason); - } - else { - reject("Attempted to disconnect but the websocket doesn't exist"); - } - }); - return this.disconnectionPromise; - }; - /** - * Connect socket. - */ - Transport.prototype.connectPromise = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - if (this.status === TransportStatus.STATUS_CLOSING && !options.force) { - return Promise.reject("WebSocket " + this.server.wsUri + " is closing"); - } - if (this.connectionPromise) { - return this.connectionPromise; - } - this.server = this.server || this.getNextWsServer(options.force); - this.connectionPromise = new Promise(function (resolve, reject) { - if ((_this.status === TransportStatus.STATUS_OPEN || _this.status === TransportStatus.STATUS_CLOSING) - && !options.force) { - _this.logger.warn("WebSocket " + _this.server.wsUri + " is already connected"); - reject("Failed status check - attempted to open a connection but already open/closing"); - return; - } - _this.connectDeferredResolve = resolve; - _this.connectDeferredReject = reject; - _this.status = TransportStatus.STATUS_CONNECTING; - _this.emit("connecting"); - _this.logger.log("connecting to WebSocket " + _this.server.wsUri); - _this.disposeWs(); - try { - _this.ws = new WebSocket(_this.server.wsUri, "sip"); - } - catch (e) { - _this.ws = null; - _this.statusTransition(TransportStatus.STATUS_CLOSED, true); - _this.onError("error connecting to WebSocket " + _this.server.wsUri + ":" + e); - reject("Failed to create a websocket"); - _this.connectDeferredResolve = undefined; - _this.connectDeferredReject = undefined; - return; - } - if (!_this.ws) { - reject("Unexpected instance websocket not set"); - _this.connectDeferredResolve = undefined; - _this.connectDeferredReject = undefined; - return; - } - _this.connectionTimeout = setTimeout(function () { - _this.statusTransition(TransportStatus.STATUS_CLOSED); - _this.logger.warn("took too long to connect - exceeded time set in configuration.connectionTimeout: " + - _this.configuration.connectionTimeout + "s"); - _this.emit("disconnected", { code: 1000 }); - _this.connectionPromise = undefined; - reject("Connection timeout"); - _this.connectDeferredResolve = undefined; - _this.connectDeferredReject = undefined; - var ws = _this.ws; - _this.disposeWs(); - ws.close(1000); - }, _this.configuration.connectionTimeout * 1000); - _this.boundOnOpen = _this.onOpen.bind(_this); - _this.boundOnMessage = _this.onMessage.bind(_this); - _this.boundOnClose = _this.onClose.bind(_this); - _this.boundOnError = _this.onWebsocketError.bind(_this); - _this.ws.addEventListener("open", _this.boundOnOpen); - _this.ws.addEventListener("message", _this.boundOnMessage); - _this.ws.addEventListener("close", _this.boundOnClose); - _this.ws.addEventListener("error", _this.boundOnError); - }); - return this.connectionPromise; - }; - /** - * @event - * @param {event} e - */ - Transport.prototype.onMessage = function (e) { - var data = e.data; - var finishedData; - // CRLF Keep Alive response from server. Clear our keep alive timeout. - if (/^(\r\n)+$/.test(data)) { - this.clearKeepAliveTimeout(); - if (this.configuration.traceSip === true) { - this.logger.log("received WebSocket message with CRLF Keep Alive response"); - } - return; - } - else if (!data) { - this.logger.warn("received empty message, message discarded"); - return; - } - else if (typeof data !== "string") { // WebSocket binary message. - try { - // the UInt8Data was here prior to types, and doesn't check - finishedData = String.fromCharCode.apply(null, new Uint8Array(data)); - } - catch (err) { - this.logger.warn("received WebSocket binary message failed to be converted into string, message discarded"); - return; - } - if (this.configuration.traceSip === true) { - this.logger.log("received WebSocket binary message:\n\n" + data + "\n"); - } - } - else { // WebSocket text message. - if (this.configuration.traceSip === true) { - this.logger.log("received WebSocket text message:\n\n" + data + "\n"); - } - finishedData = data; - } - this.emit("message", finishedData); - }; - // Transport Event Handlers - /** - * @event - * @param {event} e - */ - Transport.prototype.onOpen = function () { - if (this.status === TransportStatus.STATUS_CLOSED) { // Indicated that the transport thinks the ws is dead already - var ws = this.ws; - this.disposeWs(); - ws.close(1000); - return; - } - this.statusTransition(TransportStatus.STATUS_OPEN, true); - this.emit("connected"); - if (this.connectionTimeout) { - clearTimeout(this.connectionTimeout); - this.connectionTimeout = undefined; - } - this.logger.log("WebSocket " + this.server.wsUri + " connected"); - // Clear reconnectTimer since we are not disconnected - if (this.reconnectTimer !== undefined) { - clearTimeout(this.reconnectTimer); - this.reconnectTimer = undefined; - } - // Reset reconnectionAttempts - this.reconnectionAttempts = 0; - // Reset disconnection promise so we can disconnect from a fresh state - this.disconnectionPromise = undefined; - this.disconnectDeferredResolve = undefined; - // Start sending keep-alives - this.startSendingKeepAlives(); - if (this.connectDeferredResolve) { - this.connectDeferredResolve({ overrideEvent: true }); - this.connectDeferredResolve = undefined; - this.connectDeferredReject = undefined; - } - else { - this.logger.warn("Unexpected websocket.onOpen with no connectDeferredResolve"); - } - }; - /** - * @event - * @param {event} e - */ - Transport.prototype.onClose = function (e) { - this.logger.log("WebSocket disconnected (code: " + e.code + (e.reason ? "| reason: " + e.reason : "") + ")"); - if (this.status !== TransportStatus.STATUS_CLOSING) { - this.logger.warn("WebSocket closed without SIP.js requesting it"); - this.emit("transportError"); - } - this.stopSendingKeepAlives(); - // Clean up connection variables so we can connect again from a fresh state - if (this.connectionTimeout) { - clearTimeout(this.connectionTimeout); - } - if (this.connectDeferredReject) { - this.connectDeferredReject("Websocket Closed"); - } - this.connectionTimeout = undefined; - this.connectionPromise = undefined; - this.connectDeferredResolve = undefined; - this.connectDeferredReject = undefined; - // Check whether the user requested to close. - if (this.disconnectDeferredResolve) { - this.disconnectDeferredResolve({ overrideEvent: true }); - this.statusTransition(TransportStatus.STATUS_CLOSED); - this.disconnectDeferredResolve = undefined; - return; - } - this.statusTransition(TransportStatus.STATUS_CLOSED, true); - this.emit("disconnected", { code: e.code, reason: e.reason }); - this.disposeWs(); - this.reconnect(); - }; - /** - * Removes event listeners and clears the instance ws - */ - Transport.prototype.disposeWs = function () { - if (this.ws) { - this.ws.removeEventListener("open", this.boundOnOpen); - this.ws.removeEventListener("message", this.boundOnMessage); - this.ws.removeEventListener("close", this.boundOnClose); - this.ws.removeEventListener("error", this.boundOnError); - this.ws = undefined; - } - }; - /** - * @event - * @param {string} e - */ - Transport.prototype.onError = function (e) { - this.logger.warn("Transport error: " + e); - this.emit("transportError"); - }; - /** - * @event - * @private - */ - Transport.prototype.onWebsocketError = function () { - this.onError("The Websocket had an error"); - }; - /** - * Reconnection attempt logic. - */ - Transport.prototype.reconnect = function () { - var _this = this; - if (this.reconnectionAttempts > 0) { - this.logger.log("Reconnection attempt " + this.reconnectionAttempts + " failed"); - } - if (this.noAvailableServers()) { - this.logger.warn("attempted to get next ws server but there are no available ws servers left"); - this.logger.warn("no available ws servers left - going to closed state"); - this.statusTransition(TransportStatus.STATUS_CLOSED, true); - this.emit("closed"); - this.resetServerErrorStatus(); - return; - } - if (this.isConnected()) { - this.logger.warn("attempted to reconnect while connected - forcing disconnect"); - this.disconnect({ force: true }); - } - this.reconnectionAttempts += 1; - if (this.reconnectionAttempts > this.configuration.maxReconnectionAttempts) { - this.logger.warn("maximum reconnection attempts for WebSocket " + this.server.wsUri); - this.logger.log("transport " + this.server.wsUri + " failed | connection state set to 'error'"); - this.server.isError = true; - this.emit("transportError"); - if (!this.noAvailableServers()) { - this.server = this.getNextWsServer(); - } - // When there are no available servers, the reconnect function ends on the next recursive call - // after checking for no available servers again. - this.reconnectionAttempts = 0; - this.reconnect(); - } - else { - this.logger.log("trying to reconnect to WebSocket " + - this.server.wsUri + " (reconnection attempt " + this.reconnectionAttempts + ")"); - this.reconnectTimer = setTimeout(function () { - _this.connect(); - _this.reconnectTimer = undefined; - }, (this.reconnectionAttempts === 1) ? 0 : this.configuration.reconnectionTimeout * 1000); - } - }; - /** - * Resets the error state of all servers in the configuration - */ - Transport.prototype.resetServerErrorStatus = function () { - for (var _i = 0, _a = this.configuration.wsServers; _i < _a.length; _i++) { - var websocket = _a[_i]; - websocket.isError = false; - } - }; - /** - * Retrieve the next server to which connect. - * @param {Boolean} force allows bypass of server error status checking - * @returns {Object} WsServer - */ - Transport.prototype.getNextWsServer = function (force) { - if (force === void 0) { force = false; } - if (this.noAvailableServers()) { - this.logger.warn("attempted to get next ws server but there are no available ws servers left"); - throw new Error("Attempted to get next ws server, but there are no available ws servers left."); - } - // Order servers by weight - var candidates = []; - for (var _i = 0, _a = this.configuration.wsServers; _i < _a.length; _i++) { - var wsServer = _a[_i]; - if (wsServer.isError && !force) { - continue; - } - else if (candidates.length === 0) { - candidates.push(wsServer); - } - else if (wsServer.weight > candidates[0].weight) { - candidates = [wsServer]; - } - else if (wsServer.weight === candidates[0].weight) { - candidates.push(wsServer); - } - } - var idx = Math.floor(Math.random() * candidates.length); - return candidates[idx]; - }; - /** - * Checks all configuration servers, returns true if all of them have isError: true and false otherwise - * @returns {Boolean} - */ - Transport.prototype.noAvailableServers = function () { - for (var _i = 0, _a = this.configuration.wsServers; _i < _a.length; _i++) { - var server = _a[_i]; - if (!server.isError) { - return false; - } - } - return true; - }; - // ============================== - // KeepAlive Stuff - // ============================== - /** - * Send a keep-alive (a double-CRLF sequence). - * @returns {Boolean} - */ - Transport.prototype.sendKeepAlive = function () { - var _this = this; - if (this.keepAliveDebounceTimeout) { - // We already have an outstanding keep alive, do not send another. - return; - } - this.keepAliveDebounceTimeout = setTimeout(function () { - _this.emit("keepAliveDebounceTimeout"); - _this.clearKeepAliveTimeout(); - }, this.configuration.keepAliveDebounce * 1000); - return this.send("\r\n\r\n"); - }; - Transport.prototype.clearKeepAliveTimeout = function () { - if (this.keepAliveDebounceTimeout) { - clearTimeout(this.keepAliveDebounceTimeout); - } - this.keepAliveDebounceTimeout = undefined; - }; - /** - * Start sending keep-alives. - */ - Transport.prototype.startSendingKeepAlives = function () { - var _this = this; - if (this.configuration.keepAliveInterval && !this.keepAliveInterval) { - this.keepAliveInterval = setInterval(function () { - _this.sendKeepAlive(); - _this.startSendingKeepAlives(); - }, computeKeepAliveTimeout(this.configuration.keepAliveInterval)); - } - }; - /** - * Stop sending keep-alives. - */ - Transport.prototype.stopSendingKeepAlives = function () { - if (this.keepAliveInterval) { - clearInterval(this.keepAliveInterval); - } - if (this.keepAliveDebounceTimeout) { - clearTimeout(this.keepAliveDebounceTimeout); - } - this.keepAliveInterval = undefined; - this.keepAliveDebounceTimeout = undefined; - }; - // ============================== - // Status Stuff - // ============================== - /** - * Checks given status against instance current status. Returns true if they match - * @param {Number} status - * @param {Boolean} [force] - * @returns {Boolean} - */ - Transport.prototype.statusAssert = function (status, force) { - if (status === this.status) { - return true; - } - else { - if (force) { - this.logger.warn("Attempted to assert " + - Object.keys(TransportStatus)[this.status] + " as " + - Object.keys(TransportStatus)[status] + "- continuing with option: 'force'"); - return true; - } - else { - this.logger.warn("Tried to assert " + - Object.keys(TransportStatus)[status] + " but is currently " + - Object.keys(TransportStatus)[this.status]); - return false; - } - } - }; - /** - * Transitions the status. Checks for legal transition via assertion beforehand - * @param {Number} status - * @param {Boolean} [force] - * @returns {Boolean} - */ - Transport.prototype.statusTransition = function (status, force) { - if (force === void 0) { force = false; } - this.logger.log("Attempting to transition status from " + - Object.keys(TransportStatus)[this.status] + " to " + - Object.keys(TransportStatus)[status]); - if ((status === TransportStatus.STATUS_CONNECTING && this.statusAssert(TransportStatus.STATUS_CLOSED, force)) || - (status === TransportStatus.STATUS_OPEN && this.statusAssert(TransportStatus.STATUS_CONNECTING, force)) || - (status === TransportStatus.STATUS_CLOSING && this.statusAssert(TransportStatus.STATUS_OPEN, force)) || - (status === TransportStatus.STATUS_CLOSED)) { - this.status = status; - return true; - } - else { - this.logger.warn("Status transition failed - result: no-op - reason:" + - " either gave an nonexistent status or attempted illegal transition"); - return false; - } - }; - // ============================== - // Configuration Handling - // ============================== - /** - * Configuration load. - * returns {Configuration} - */ - Transport.prototype.loadConfig = function (configuration) { - var settings = { - wsServers: [{ - scheme: "WSS", - sipUri: "", - weight: 0, - wsUri: "wss://edge.sip.onsip.com", - isError: false - }], - connectionTimeout: 5, - maxReconnectionAttempts: 3, - reconnectionTimeout: 4, - keepAliveInterval: 0, - keepAliveDebounce: 10, - // Logging - traceSip: false - }; - var configCheck = this.getConfigurationCheck(); - // Check Mandatory parameters - for (var parameter in configCheck.mandatory) { - if (!configuration.hasOwnProperty(parameter)) { - throw new Exceptions_1.Exceptions.ConfigurationError(parameter); - } - else { - var value = configuration[parameter]; - var checkedValue = configCheck.mandatory[parameter](value); - if (checkedValue !== undefined) { - settings[parameter] = checkedValue; - } - else { - throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); - } - } - } - // Check Optional parameters - for (var parameter in configCheck.optional) { - if (configuration.hasOwnProperty(parameter)) { - var value = configuration[parameter]; - // If the parameter value is an empty array, but shouldn't be, apply its default value. - // If the parameter value is null, empty string, or undefined then apply its default value. - // If it's a number with NaN value then also apply its default value. - // NOTE: JS does not allow "value === NaN", the following does the work: - if ((value instanceof Array && value.length === 0) || - (value === null || value === "" || value === undefined) || - (typeof (value) === "number" && isNaN(value))) { - continue; - } - var checkedValue = configCheck.optional[parameter](value); - if (checkedValue !== undefined) { - settings[parameter] = checkedValue; - } - else { - throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); - } - } - } - var skeleton = {}; // Fill the value of the configuration_skeleton - for (var parameter in settings) { - if (settings.hasOwnProperty(parameter)) { - skeleton[parameter] = { - value: settings[parameter], - }; - } - } - var returnConfiguration = Object.defineProperties({}, skeleton); - this.logger.log("configuration parameters after validation:"); - for (var parameter in settings) { - if (settings.hasOwnProperty(parameter)) { - this.logger.log("· " + parameter + ": " + JSON.stringify(settings[parameter])); - } - } - return returnConfiguration; - }; - /** - * Configuration checker. - * @return {Boolean} - */ - Transport.prototype.getConfigurationCheck = function () { - return { - mandatory: {}, - optional: { - // Note: this function used to call 'this.logger.error' but calling 'this' with anything here is invalid - wsServers: function (wsServers) { - /* Allow defining wsServers parameter as: - * String: "host" - * Array of Strings: ["host1", "host2"] - * Array of Objects: [{wsUri:"host1", weight:1}, {wsUri:"host2", weight:0}] - * Array of Objects and Strings: [{wsUri:"host1"}, "host2"] - */ - if (typeof wsServers === "string") { - wsServers = [{ wsUri: wsServers }]; - } - else if (wsServers instanceof Array) { - for (var idx = 0; idx < wsServers.length; idx++) { - if (typeof wsServers[idx] === "string") { - wsServers[idx] = { wsUri: wsServers[idx] }; - } - } - } - else { - return; - } - if (wsServers.length === 0) { - return false; - } - for (var _i = 0, wsServers_1 = wsServers; _i < wsServers_1.length; _i++) { - var wsServer = wsServers_1[_i]; - if (!wsServer.wsUri) { - return; - } - if (wsServer.weight && !Number(wsServer.weight)) { - return; - } - var url = core_1.Grammar.parse(wsServer.wsUri, "absoluteURI"); - if (url === -1) { - return; - } - else if (["wss", "ws", "udp"].indexOf(url.scheme) < 0) { - return; - } - else { - wsServer.sipUri = ""; - if (!wsServer.weight) { - wsServer.weight = 0; - } - wsServer.isError = false; - wsServer.scheme = url.scheme.toUpperCase(); - } - } - return wsServers; - }, - keepAliveInterval: function (keepAliveInterval) { - if (Utils_1.Utils.isDecimal(keepAliveInterval)) { - var value = Number(keepAliveInterval); - if (value > 0) { - return value; - } - } - }, - keepAliveDebounce: function (keepAliveDebounce) { - if (Utils_1.Utils.isDecimal(keepAliveDebounce)) { - var value = Number(keepAliveDebounce); - if (value > 0) { - return value; - } - } - }, - traceSip: function (traceSip) { - if (typeof traceSip === "boolean") { - return traceSip; - } - }, - connectionTimeout: function (connectionTimeout) { - if (Utils_1.Utils.isDecimal(connectionTimeout)) { - var value = Number(connectionTimeout); - if (value > 0) { - return value; - } - } - }, - maxReconnectionAttempts: function (maxReconnectionAttempts) { - if (Utils_1.Utils.isDecimal(maxReconnectionAttempts)) { - var value = Number(maxReconnectionAttempts); - if (value >= 0) { - return value; - } - } - }, - reconnectionTimeout: function (reconnectionTimeout) { - if (Utils_1.Utils.isDecimal(reconnectionTimeout)) { - var value = Number(reconnectionTimeout); - if (value > 0) { - return value; - } - } - } - } - }; - }; - Transport.C = TransportStatus; - return Transport; -}(core_1.Transport)); -exports.Transport = Transport; - - -/***/ }), -/* 104 */, -/* 105 */, -/* 106 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -tslib_1.__exportStar(__webpack_require__(107), exports); -tslib_1.__exportStar(__webpack_require__(96), exports); -tslib_1.__exportStar(__webpack_require__(97), exports); -tslib_1.__exportStar(__webpack_require__(110), exports); -tslib_1.__exportStar(__webpack_require__(108), exports); -tslib_1.__exportStar(__webpack_require__(111), exports); -tslib_1.__exportStar(__webpack_require__(112), exports); -tslib_1.__exportStar(__webpack_require__(113), exports); -tslib_1.__exportStar(__webpack_require__(98), exports); -tslib_1.__exportStar(__webpack_require__(114), exports); -tslib_1.__exportStar(__webpack_require__(99), exports); -tslib_1.__exportStar(__webpack_require__(115), exports); -tslib_1.__exportStar(__webpack_require__(116), exports); -tslib_1.__exportStar(__webpack_require__(117), exports); -tslib_1.__exportStar(__webpack_require__(100), exports); -tslib_1.__exportStar(__webpack_require__(95), exports); -tslib_1.__exportStar(__webpack_require__(118), exports); -tslib_1.__exportStar(__webpack_require__(120), exports); -tslib_1.__exportStar(__webpack_require__(119), exports); -tslib_1.__exportStar(__webpack_require__(109), exports); -tslib_1.__exportStar(__webpack_require__(121), exports); - - -/***/ }), -/* 107 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var invitation_1 = __webpack_require__(108); -var session_state_1 = __webpack_require__(100); -/** - * A byer ends a {@link Session} (outgoing BYE). - * @remarks - * Sends an outgoing in dialog BYE request. - * @public - */ -var Byer = /** @class */ (function () { - /** - * Constructs a new instance of the `Byer` class. - * @param session - The session the BYE will be sent from. See {@link Session} for details. - * @param options - An options bucket. See {@link ByerOptions} for details. - */ - function Byer(session, options) { - this._session = session; - } - Object.defineProperty(Byer.prototype, "session", { - /** The byer session. */ - get: function () { - return this._session; - }, - enumerable: true, - configurable: true - }); - /** - * Sends the BYE request. - * @param options - {@link ByerByeOptions} options bucket. - */ - Byer.prototype.bye = function (options) { - if (options === void 0) { options = {}; } - // guard session state - if (this.session.state !== session_state_1.SessionState.Established && - this.session.state !== session_state_1.SessionState.Terminating) { - var message = "Byer.bye() may only be called if established session."; - if (this.session.state === session_state_1.SessionState.Terminated) { - message += " However this session is already terminated."; - } - else { - if (this.session instanceof invitation_1.Invitation) { - message += " However Invitation.accept() has not yet been called."; - message += " Perhaps you should have called Invitation.reject()?"; - } - else { - message += " However a dialog does not yet exist."; - message += " Perhaps you should have called Inviter.cancel()?"; - } - } - this.session.logger.error(message); - return Promise.reject(new Error("Invalid session state " + this.session.state)); - } - return this.session.bye(options.requestDelegate, options.requestOptions); - }; - return Byer; -}()); -exports.Byer = Byer; - - -/***/ }), -/* 108 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var Constants_1 = __webpack_require__(80); -var core_1 = __webpack_require__(2); -var utils_1 = __webpack_require__(16); -var Enums_1 = __webpack_require__(82); -var Exceptions_1 = __webpack_require__(84); -var session_1 = __webpack_require__(95); -var session_state_1 = __webpack_require__(100); -var user_agent_options_1 = __webpack_require__(109); -/** - * An invitation is an offer to establish a {@link Session} (incoming INVITE). - * @public - */ -var Invitation = /** @class */ (function (_super) { - tslib_1.__extends(Invitation, _super); - /** @internal */ - function Invitation(userAgent, incomingInviteRequest) { - var _this = _super.call(this, userAgent) || this; - _this.incomingInviteRequest = incomingInviteRequest; - // BEGIN ServerContext Interface - // public type: TypeStrings; - // public ua: UA; - // public logger: Logger; - // public data: any = {}; - // public method = C.INVITE; - /** @internal */ - _this.body = undefined; - // public accept: (options: any = {}) => any; - // public progress: (options: any = {}) => any; - // public reject: (options: any = {}) => any; - // public reply!: (options: any) => any; // not used - // public onRequestTimeout: () => void; - // public onTransportError: () => void; - // END ServerContext interface - /** - * FIXME: TODO: - * Used to squelch throwing of errors due to async race condition. - * We have an internal race between calling `accept()` and handling - * an incoming CANCEL request. As there is no good way currently to - * delegate the handling of this async errors to the caller of - * `accept()`, we are squelching the throwing ALL errors when - * they occur after receiving a CANCEL to catch the ONE we know - * is a "normal" exceptional condition. While this is a completely - * reasonable appraoch, the decision should be left up to the library user. - */ - _this._canceled = false; - _this.rseq = Math.floor(Math.random() * 10000); - // ServerContext properties - _this.type = Enums_1.TypeStrings.InviteServerContext; - _this.logger = userAgent.getLogger("sip.invitation", _this.id); - if (_this.request.body) { - _this.body = _this.request.body; - } - if (_this.request.hasHeader("Content-Type")) { - _this.contentType = _this.request.getHeader("Content-Type"); - } - _this.localIdentity = _this.request.to; - _this.remoteIdentity = _this.request.from; - var hasAssertedIdentity = _this.request.hasHeader("P-Asserted-Identity"); - if (hasAssertedIdentity) { - var assertedIdentity = _this.request.getHeader("P-Asserted-Identity"); - if (assertedIdentity) { - _this.assertedIdentity = core_1.Grammar.nameAddrHeaderParse(assertedIdentity); - } - } - // Session properties - _this.contact = _this.userAgent.contact.toString(); - _this.fromTag = _this.request.fromTag; - _this.id = _this.request.callId + _this.fromTag; - // this.modifiers = - // this.onInfo = - // this.passedOptions = - var contentDisposition = _this.request.parseHeader("Content-Disposition"); - if (contentDisposition && contentDisposition.type === "render") { - _this.renderbody = _this.request.body; - _this.rendertype = _this.request.getHeader("Content-Type"); - } - // FIXME: This is being done twice... - // Update logger - _this.logger = userAgent.getLogger("sip.invitation", _this.id); - // Update status - _this.status = Enums_1.SessionStatus.STATUS_INVITE_RECEIVED; - // Save the session into the ua sessions collection. - _this.userAgent.sessions[_this.id] = _this; - // Set 100rel if necessary - var request = _this.request; - var set100rel = function (header, relSetting) { - if (request.hasHeader(header) && request.getHeader(header).toLowerCase().indexOf("100rel") >= 0) { - _this.rel100 = relSetting; - } - }; - set100rel("require", Constants_1.C.supported.REQUIRED); - set100rel("supported", Constants_1.C.supported.SUPPORTED); - // Set the toTag on the incoming request to the toTag which - // will be used in the response to the incoming request!!! - // FIXME: HACK: This is a hack to port an existing behavior. - // The behavior being ported appears to be a hack itself, - // so this is a hack to port a hack. At least one test spec - // relies on it (which is yet another hack). - _this.request.toTag = incomingInviteRequest.toTag; - // Update status again - sigh - _this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER; - // Set userNoAnswerTimer - _this.userNoAnswerTimer = setTimeout(function () { - // FIXME: refactor the following bit - // transition state - _this.stateTransition(session_state_1.SessionState.Terminated); - incomingInviteRequest.reject({ statusCode: 408 }); - _this.failed(request, Constants_1.C.causes.NO_ANSWER); - _this.terminated(request, Constants_1.C.causes.NO_ANSWER); - }, _this.userAgent.configuration.noAnswerTimeout ? _this.userAgent.configuration.noAnswerTimeout * 1000 : 60000); - // Set expiresTimer (RFC3261 13.3.1) - if (request.hasHeader("expires")) { - var expires = Number(request.getHeader("expires") || 0) * 1000; - _this.expiresTimer = setTimeout(function () { - if (_this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER) { - // FIXME: refactor the following bit - // transition state - _this.stateTransition(session_state_1.SessionState.Terminated); - incomingInviteRequest.reject({ statusCode: 487 }); - _this.failed(request, Constants_1.C.causes.EXPIRES); - _this.terminated(request, Constants_1.C.causes.EXPIRES); - } - }, expires); - } - return _this; - } - Object.defineProperty(Invitation.prototype, "autoSendAnInitialProvisionalResponse", { - /** - * If true, a first provisional response after the 100 Trying - * will be sent automatically. This is false it the UAC required - * reliable provisional responses (100rel in Require header), - * otherwise it is true. The provisional is sent by calling - * `progress()` without any options. - * - * FIXME: TODO: It seems reasonable that the ISC user should - * be able to optionally disable this behavior. As the provisional - * is sent prior to the "invite" event being emitted, it's a known - * issue that the ISC user cannot register listeners or do any other - * setup prior to the call to `progress()`. As an example why this is - * an issue, setting `ua.configuration.rel100` to REQUIRED will result - * in an attempt by `progress()` to send a 183 with SDP produced by - * calling `getDescription()` on a session description handler, but - * the ISC user cannot perform any potentially required session description - * handler initialization (thus preventing the utilization of setting - * `ua.configuration.rel100` to REQUIRED). That begs the question of - * why this behavior is disabled when the UAC requires 100rel but not - * when the UAS requires 100rel? But ignoring that, it's just one example - * of a class of cases where the ISC user needs to do something prior - * to the first call to `progress()` and is unable to do so. - * @internal - */ - get: function () { - return this.rel100 === Constants_1.C.supported.REQUIRED ? false : true; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Invitation.prototype, "request", { - /** Incoming MESSAGE request message. */ - get: function () { - return this.incomingInviteRequest.message; - }, - enumerable: true, - configurable: true - }); - /** - * Accept the invitation. - * @remarks - * Accept the incoming INVITE request to start a Session. - * Replies to the INVITE request with a 200 Ok response. - * @param options - Options bucket. - */ - Invitation.prototype.accept = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - this.logger.log("Invitation.accept"); - // validate state - if (this.state !== session_state_1.SessionState.Initial) { - var error = new Error("Invalid session state " + this.state); - this.logger.error(error.message); - return Promise.reject(error); - } - // transition state - this.stateTransition(session_state_1.SessionState.Establishing); - return this._accept(options) - .then(function (_a) { - var message = _a.message, session = _a.session; - session.delegate = { - onAck: function (ackRequest) { return _this.onAckRequest(ackRequest); }, - onAckTimeout: function () { return _this.onAckTimeout(); }, - onBye: function (byeRequest) { return _this.onByeRequest(byeRequest); }, - onInfo: function (infoRequest) { return _this.onInfoRequest(infoRequest); }, - onInvite: function (inviteRequest) { return _this.onInviteRequest(inviteRequest); }, - onNotify: function (notifyRequest) { return _this.onNotifyRequest(notifyRequest); }, - onPrack: function (prackRequest) { return _this.onPrackRequest(prackRequest); }, - onRefer: function (referRequest) { return _this.onReferRequest(referRequest); } - }; - _this.dialog = session; - _this.stateTransition(session_state_1.SessionState.Established); - // TODO: Reconsider this "automagic" send of a BYE to replacee behavior. - // This behavoir has been ported forward from legacy versions. - if (_this.replacee) { - _this.replacee.bye(); - } - }) - .catch(function (error) { - _this.onContextError(error); - // FIXME: Assuming error due to async race on CANCEL and eating error. - if (!_this._canceled) { - throw error; - } - }); - }; - /** - * Indicate progress processing the invitation. - * @remarks - * Report progress to the the caller. - * Replies to the INVITE request with a 1xx provisional response. - * @param options - Options bucket. - */ - Invitation.prototype.progress = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - this.logger.log("Invitation.progress"); - // validate state - if (this.state !== session_state_1.SessionState.Initial) { - var error = new Error("Invalid session state " + this.state); - this.logger.error(error.message); - return Promise.reject(error); - } - // Ported - var statusCode = options.statusCode || 180; - if (statusCode < 100 || statusCode > 199) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - // Ported - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - this.logger.warn("Unexpected call for progress while terminated, ignoring"); - return Promise.resolve(); - } - // Added - if (this.status === Enums_1.SessionStatus.STATUS_ANSWERED) { - this.logger.warn("Unexpected call for progress while answered, ignoring"); - return Promise.resolve(); - } - // Added - if (this.status === Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK) { - this.logger.warn("Unexpected call for progress while answered (waiting for prack), ignoring"); - return Promise.resolve(); - } - // After the first reliable provisional response for a request has been - // acknowledged, the UAS MAY send additional reliable provisional - // responses. The UAS MUST NOT send a second reliable provisional - // response until the first is acknowledged. After the first, it is - // RECOMMENDED that the UAS not send an additional reliable provisional - // response until the previous is acknowledged. The first reliable - // provisional response receives special treatment because it conveys - // the initial sequence number. If additional reliable provisional - // responses were sent before the first was acknowledged, the UAS could - // not be certain these were received in order. - // https://tools.ietf.org/html/rfc3262#section-3 - if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK) { - this.logger.warn("Unexpected call for progress while waiting for prack, ignoring"); - return Promise.resolve(); - } - // Ported - if (options.statusCode === 100) { - try { - this.incomingInviteRequest.trying(); - } - catch (error) { - this.onContextError(error); - // FIXME: Assuming error due to async race on CANCEL and eating error. - if (!this._canceled) { - return Promise.reject(error); - } - } - return Promise.resolve(); - } - // Standard provisional response. - if (!(this.rel100 === Constants_1.C.supported.REQUIRED) && - !(this.rel100 === Constants_1.C.supported.SUPPORTED && options.rel100) && - !(this.rel100 === Constants_1.C.supported.SUPPORTED && - this.userAgent.configuration.sipExtension100rel === user_agent_options_1.SIPExtension.Required)) { - return this._progress(options) - .then(function (response) { return; }) - .catch(function (error) { - _this.onContextError(error); - // FIXME: Assuming error due to async race on CANCEL and eating error. - if (!_this._canceled) { - throw error; - } - }); - } - // Reliable provisional response. - return this._progressReliableWaitForPrack(options) - .then(function (response) { return; }) - .catch(function (error) { - _this.onContextError(error); - // FIXME: Assuming error due to async race on CANCEL and eating error. - if (!_this._canceled) { - throw error; - } - }); - }; - /** - * Reject the invitation. - * @param options - Options bucket. - */ - Invitation.prototype.reject = function (options) { - if (options === void 0) { options = {}; } - this.logger.log("Invitation.reject"); - // validate state - if (this.state !== session_state_1.SessionState.Initial) { - var error = new Error("Invalid session state " + this.state); - this.logger.error(error.message); - return Promise.reject(error); - } - // transition state - this.stateTransition(session_state_1.SessionState.Terminated); - // Check Session Status - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - throw new Exceptions_1.Exceptions.InvalidStateError(this.status); - } - this.logger.log("rejecting RTCSession"); - var statusCode = options.statusCode || 480; - var reasonPhrase = options.reasonPhrase ? options.reasonPhrase : utils_1.getReasonPhrase(statusCode); - var extraHeaders = options.extraHeaders || []; - if (statusCode < 300 || statusCode > 699) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - var body = options.body ? core_1.fromBodyLegacy(options.body) : undefined; - // FIXME: Need to redirect to someplae - var response = statusCode < 400 ? - this.incomingInviteRequest.redirect([], { statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }) : - this.incomingInviteRequest.reject({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); - this.emit("rejected", response.message, reasonPhrase); - this.emit("failed", response.message, reasonPhrase); - this.terminated(); - return Promise.resolve(); - }; - /** - * FIXME: Kill this legacy emission - * @internal - */ - Invitation.prototype.byePending = function () { - this.emit("bye", this.request); - _super.prototype.byePending.call(this); - }; - /** - * Handle CANCEL request. - * @param message - CANCEL message. - * @internal - */ - Invitation.prototype.onCancel = function (message) { - this.logger.log("Invitation.onCancel"); - // validate state - if (this.state !== session_state_1.SessionState.Initial && - this.state !== session_state_1.SessionState.Establishing) { - this.logger.error("CANCEL received while in state " + this.state + ", dropping request"); - return; - } - // flag canceled - this._canceled = true; - // transition state - this.stateTransition(session_state_1.SessionState.Terminated); - // reject INVITE with 487 status code - this.incomingInviteRequest.reject({ statusCode: 487 }); - this.rejected(message, Constants_1.C.causes.CANCELED); - this.failed(message, Constants_1.C.causes.CANCELED); - this.terminated(message, Constants_1.C.causes.CANCELED); - }; - /** - * Called when session terminated. - * Using it here just for the PRACK timeout. - * @internal - */ - Invitation.prototype.terminated = function (message, cause) { - this.prackNeverArrived(); - _super.prototype.terminated.call(this, message, cause); - }; - /** - * A version of `accept` which resolves a session when the 200 Ok response is sent. - * @param options - Options bucket. - */ - Invitation.prototype._accept = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - // FIXME: Ported - callback for in dialog INFO requests. - // Turns out accept() can be called more than once if we are waiting - // for a PRACK in which case "options" get completely tossed away. - // So this is broken in that case (and potentially other uses of options). - // Tempted to just try to fix it now, but leaving it broken for the moment. - this.onInfo = options.onInfo; - // The UAS MAY send a final response to the initial request before - // having received PRACKs for all unacknowledged reliable provisional - // responses, unless the final response is 2xx and any of the - // unacknowledged reliable provisional responses contained a session - // description. In that case, it MUST NOT send a final response until - // those provisional responses are acknowledged. If the UAS does send a - // final response when reliable responses are still unacknowledged, it - // SHOULD NOT continue to retransmit the unacknowledged reliable - // provisional responses, but it MUST be prepared to process PRACK - // requests for those outstanding responses. A UAS MUST NOT send new - // reliable provisional responses (as opposed to retransmissions of - // unacknowledged ones) after sending a final response to a request. - // https://tools.ietf.org/html/rfc3262#section-3 - if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK) { - this.status = Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK; - return this.waitForArrivalOfPrack() - .then(function () { - _this.status = Enums_1.SessionStatus.STATUS_ANSWERED; - clearTimeout(_this.userNoAnswerTimer); // Ported - }) - .then(function () { return _this.generateResponseOfferAnswer(_this.incomingInviteRequest, options); }) - .then(function (body) { return _this.incomingInviteRequest.accept({ statusCode: 200, body: body }); }); - } - // Ported - if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER) { - this.status = Enums_1.SessionStatus.STATUS_ANSWERED; - } - else { - return Promise.reject(new Exceptions_1.Exceptions.InvalidStateError(this.status)); - } - this.status = Enums_1.SessionStatus.STATUS_ANSWERED; - clearTimeout(this.userNoAnswerTimer); // Ported - return this.generateResponseOfferAnswer(this.incomingInviteRequest, options) - .then(function (body) { return _this.incomingInviteRequest.accept({ statusCode: 200, body: body }); }); - }; - /** - * A version of `progress` which resolves when the provisional response is sent. - * @param options - Options bucket. - */ - Invitation.prototype._progress = function (options) { - if (options === void 0) { options = {}; } - // Ported - var statusCode = options.statusCode || 180; - var reasonPhrase = options.reasonPhrase; - var extraHeaders = (options.extraHeaders || []).slice(); - var body = options.body ? core_1.fromBodyLegacy(options.body) : undefined; - // The 183 (Session Progress) response is used to convey information - // about the progress of the call that is not otherwise classified. The - // Reason-Phrase, header fields, or message body MAY be used to convey - // more details about the call progress. - // https://tools.ietf.org/html/rfc3261#section-21.1.5 - // It is the de facto industry standard to utilize 183 with SDP to provide "early media". - // While it is unlikely someone would want to send a 183 without SDP, so it should be an option. - if (statusCode === 183 && !body) { - return this._progressWithSDP(options); - } - try { - var progressResponse = this.incomingInviteRequest.progress({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); - this.emit("progress", progressResponse.message, reasonPhrase); // Ported - this.dialog = progressResponse.session; - return Promise.resolve(progressResponse); - } - catch (error) { - return Promise.reject(error); - } - }; - /** - * A version of `progress` which resolves when the provisional response with sdp is sent. - * @param options - Options bucket. - */ - Invitation.prototype._progressWithSDP = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - var statusCode = options.statusCode || 183; - var reasonPhrase = options.reasonPhrase; - var extraHeaders = (options.extraHeaders || []).slice(); - // Get an offer/answer and send a reply. - return this.generateResponseOfferAnswer(this.incomingInviteRequest, options) - .then(function (body) { return _this.incomingInviteRequest.progress({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); }) - .then(function (progressResponse) { - _this.emit("progress", progressResponse.message, reasonPhrase); // Ported - _this.dialog = progressResponse.session; - return progressResponse; - }); - }; - /** - * A version of `progress` which resolves when the reliable provisional response is sent. - * @param options - Options bucket. - */ - Invitation.prototype._progressReliable = function (options) { - if (options === void 0) { options = {}; } - options.extraHeaders = (options.extraHeaders || []).slice(); - options.extraHeaders.push("Require: 100rel"); - options.extraHeaders.push("RSeq: " + Math.floor(Math.random() * 10000)); - return this._progressWithSDP(options); - }; - /** - * A version of `progress` which resolves when the reliable provisional response is acknowledged. - * @param options - Options bucket. - */ - Invitation.prototype._progressReliableWaitForPrack = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - var statusCode = options.statusCode || 183; - var reasonPhrase = options.reasonPhrase; - var extraHeaders = (options.extraHeaders || []).slice(); - extraHeaders.push("Require: 100rel"); - extraHeaders.push("RSeq: " + this.rseq++); - var body; - // Ported - set status. - this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK; - return new Promise(function (resolve, reject) { - var waitingForPrack = true; - return _this.generateResponseOfferAnswer(_this.incomingInviteRequest, options) - .then(function (offerAnswer) { - body = offerAnswer; - return _this.incomingInviteRequest.progress({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); - }) - .then(function (progressResponse) { - _this.emit("progress", progressResponse.message, reasonPhrase); // Ported - _this.dialog = progressResponse.session; - var prackRequest; - var prackResponse; - progressResponse.session.delegate = { - onPrack: function (request) { - prackRequest = request; - clearTimeout(prackWaitTimeoutTimer); - clearTimeout(rel1xxRetransmissionTimer); - if (!waitingForPrack) { - return; - } - waitingForPrack = false; - _this.handlePrackOfferAnswer(prackRequest, options) - .then(function (prackResponseBody) { - try { - prackResponse = prackRequest.accept({ statusCode: 200, body: prackResponseBody }); - // Ported - set status. - if (_this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK) { - _this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER; - } - _this.prackArrived(); - resolve({ prackRequest: prackRequest, prackResponse: prackResponse, progressResponse: progressResponse }); - } - catch (error) { - reject(error); - } - }); - } - }; - // https://tools.ietf.org/html/rfc3262#section-3 - var prackWaitTimeout = function () { - if (!waitingForPrack) { - return; - } - waitingForPrack = false; - _this.logger.warn("No PRACK received, rejecting INVITE."); - clearTimeout(rel1xxRetransmissionTimer); - try { - _this.incomingInviteRequest.reject({ statusCode: 504 }); - _this.terminated(undefined, Constants_1.C.causes.NO_PRACK); - reject(new Exceptions_1.Exceptions.TerminatedSessionError()); - } - catch (error) { - reject(error); - } - }; - var prackWaitTimeoutTimer = setTimeout(prackWaitTimeout, core_1.Timers.T1 * 64); - // https://tools.ietf.org/html/rfc3262#section-3 - var rel1xxRetransmission = function () { - try { - _this.incomingInviteRequest.progress({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); - } - catch (error) { - waitingForPrack = false; - reject(error); - return; - } - rel1xxRetransmissionTimer = setTimeout(rel1xxRetransmission, timeout *= 2); - }; - var timeout = core_1.Timers.T1; - var rel1xxRetransmissionTimer = setTimeout(rel1xxRetransmission, timeout); - }); - }); - }; - Invitation.prototype.handlePrackOfferAnswer = function (request, options) { - if (!this.dialog) { - throw new Error("Dialog undefined."); - } - // If the PRACK doesn't have an offer/answer, nothing to be done. - var body = core_1.getBody(request.message); - if (!body || body.contentDisposition !== "session") { - return Promise.resolve(undefined); - } - // If the UAC receives a reliable provisional response with an offer - // (this would occur if the UAC sent an INVITE without an offer, in - // which case the first reliable provisional response will contain the - // offer), it MUST generate an answer in the PRACK. If the UAC receives - // a reliable provisional response with an answer, it MAY generate an - // additional offer in the PRACK. If the UAS receives a PRACK with an - // offer, it MUST place the answer in the 2xx to the PRACK. - // https://tools.ietf.org/html/rfc3262#section-5 - switch (this.dialog.signalingState) { - case core_1.SignalingState.Initial: - // State should never be reached as first reliable provisional response must have answer/offer. - throw new Error("Invalid signaling state " + this.dialog.signalingState + "."); - case core_1.SignalingState.Stable: - // Receved answer. - return this.setAnswer(body, options).then(function () { return undefined; }); - case core_1.SignalingState.HaveLocalOffer: - // State should never be reached as local offer would be answered by this PRACK - throw new Error("Invalid signaling state " + this.dialog.signalingState + "."); - case core_1.SignalingState.HaveRemoteOffer: - // Received offer, generate answer. - return this.setOfferAndGetAnswer(body, options); - case core_1.SignalingState.Closed: - throw new Error("Invalid signaling state " + this.dialog.signalingState + "."); - default: - throw new Error("Invalid signaling state " + this.dialog.signalingState + "."); - } - }; - /** - * Callback for when ACK for a 2xx response is never received. - * @param session - Session the ACK never arrived for. - */ - Invitation.prototype.onAckTimeout = function () { - this.logger.log("Invitation.onAckTimeout"); - if (!this.dialog) { - throw new Error("Dialog undefined."); - } - this.logger.log("No ACK received for an extended period of time, terminating session"); - this.dialog.bye(); - this.stateTransition(session_state_1.SessionState.Terminated); - this.terminated(undefined, Constants_1.C.causes.NO_ACK); - }; - /** - * FIXME: TODO: The current library interface presents async methods without a - * proper async error handling mechanism. Arguably a promise based interface - * would be an improvement over the pattern of returning `this`. The approach has - * been generally along the lines of log a error and terminate. - */ - Invitation.prototype.onContextError = function (error) { - var statusCode = 480; - if (error instanceof core_1.Exception) { // There might be interest in catching these Exceptions. - if (error instanceof Exceptions_1.Exceptions.SessionDescriptionHandlerError) { - this.logger.error(error.message); - if (error.error) { - this.logger.error(error.error); - } - } - else if (error instanceof Exceptions_1.Exceptions.TerminatedSessionError) { - // PRACK never arrived, so we timed out waiting for it. - this.logger.warn("Incoming session terminated while waiting for PRACK."); - } - else if (error instanceof Exceptions_1.Exceptions.UnsupportedSessionDescriptionContentTypeError) { - statusCode = 415; - } - else if (error instanceof core_1.Exception) { - this.logger.error(error.message); - } - } - else if (error instanceof Error) { // Other Errors hould go uncaught. - this.logger.error(error.message); - } - else { - // We don't actually know what a session description handler implementation might throw - // our way, so as a last resort, just assume we are getting an "any" and log it. - this.logger.error("An error occurred in the session description handler."); - this.logger.error(error); - } - try { - this.incomingInviteRequest.reject({ statusCode: statusCode }); // "Temporarily Unavailable" - this.failed(this.incomingInviteRequest.message, error.message); - this.terminated(this.incomingInviteRequest.message, error.message); - } - catch (error) { - return; - } - }; - Invitation.prototype.prackArrived = function () { - if (this.waitingForPrackResolve) { - this.waitingForPrackResolve(); - } - this.waitingForPrackPromise = undefined; - this.waitingForPrackResolve = undefined; - this.waitingForPrackReject = undefined; - }; - Invitation.prototype.prackNeverArrived = function () { - if (this.waitingForPrackReject) { - this.waitingForPrackReject(new Exceptions_1.Exceptions.TerminatedSessionError()); - } - this.waitingForPrackPromise = undefined; - this.waitingForPrackResolve = undefined; - this.waitingForPrackReject = undefined; - }; - Invitation.prototype.waitForArrivalOfPrack = function () { - var _this = this; - if (this.waitingForPrackPromise) { - throw new Error("Already waiting for PRACK"); - } - this.waitingForPrackPromise = new Promise(function (resolve, reject) { - _this.waitingForPrackResolve = resolve; - _this.waitingForPrackReject = reject; - }); - return this.waitingForPrackPromise; - }; - return Invitation; -}(session_1.Session)); -exports.Invitation = Invitation; - - -/***/ }), -/* 109 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * SIP extension support level. - * @public - */ -var SIPExtension; -(function (SIPExtension) { - SIPExtension["Required"] = "Required"; - SIPExtension["Supported"] = "Supported"; - SIPExtension["Unsupported"] = "Unsupported"; -})(SIPExtension = exports.SIPExtension || (exports.SIPExtension = {})); -/** - * SIP Option Tags - * @remarks - * http://www.iana.org/assignments/sip-parameters/sip-parameters.xhtml#sip-parameters-4 - * @public - */ -exports.UserAgentRegisteredOptionTags = { - "100rel": true, - "199": true, - "answermode": true, - "early-session": true, - "eventlist": true, - "explicitsub": true, - "from-change": true, - "geolocation-http": true, - "geolocation-sip": true, - "gin": true, - "gruu": true, - "histinfo": true, - "ice": true, - "join": true, - "multiple-refer": true, - "norefersub": true, - "nosub": true, - "outbound": true, - "path": true, - "policy": true, - "precondition": true, - "pref": true, - "privacy": true, - "recipient-list-invite": true, - "recipient-list-message": true, - "recipient-list-subscribe": true, - "replaces": true, - "resource-priority": true, - "sdp-anat": true, - "sec-agree": true, - "tdialog": true, - "timer": true, - "uui": true // RFC 7433 -}; - - -/***/ }), -/* 110 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var session_state_1 = __webpack_require__(100); -/** - * An Infoer sends {@link Info} (outgoing INFO). - * @remarks - * Sends an outgoing in dialog INFO request. - * @public - */ -var Infoer = /** @class */ (function () { - /** - * Constructs a new instance of the `Infoer` class. - * @param session - The session the INFO will be sent from. See {@link Session} for details. - * @param options - An options bucket. - */ - function Infoer(session, options) { - this._session = session; - } - Object.defineProperty(Infoer.prototype, "session", { - /** The Infoer session. */ - get: function () { - return this._session; - }, - enumerable: true, - configurable: true - }); - /** - * Sends the INFO request. - * @param options - {@link InfoerInfoOptions} options bucket. - */ - Infoer.prototype.info = function (options) { - if (options === void 0) { options = {}; } - // guard session state - if (this.session.state !== session_state_1.SessionState.Established) { - var message = "Infoer.info() may only be called if established session."; - this.session.logger.error(message); - return Promise.reject(new Error("Invalid session state " + this.session.state)); - } - return this.session.info(options.requestDelegate, options.requestOptions); - }; - return Infoer; -}()); -exports.Infoer = Infoer; - - -/***/ }), -/* 111 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var Constants_1 = __webpack_require__(80); -var core_1 = __webpack_require__(2); -var Enums_1 = __webpack_require__(82); -var Exceptions_1 = __webpack_require__(84); -var Utils_1 = __webpack_require__(83); -var session_1 = __webpack_require__(95); -var session_state_1 = __webpack_require__(100); -var user_agent_options_1 = __webpack_require__(109); -/** - * An inviter offers to establish a {@link Session} (outgoing INVITE). - * @public - */ -var Inviter = /** @class */ (function (_super) { - tslib_1.__extends(Inviter, _super); - /** - * Constructs a new instance of the `Inviter` class. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @param targetURI - Request URI identifying the target of the message. - * @param options - Options bucket. See {@link InviterOptions} for details. - */ - function Inviter(userAgent, targetURI, options) { - if (options === void 0) { options = {}; } - var _this = _super.call(this, userAgent, options) || this; - // BEGIN ClientContext interface - // public type: TypeStrings; - // public ua: UA; - // public logger: Logger; - // public data: any = {}; - // public method = C.INVITE; - /** @internal */ - _this.body = undefined; - _this.earlyMediaSessionDescriptionHandlers = new Map(); - // Default options params - options.params = options.params || {}; - // Check Session Status - if (_this.status !== Enums_1.SessionStatus.STATUS_NULL) { - throw new Exceptions_1.Exceptions.InvalidStateError(_this.status); - } - // ClientContext properties - _this.type = Enums_1.TypeStrings.InviteClientContext; - _this.logger = userAgent.getLogger("sip.inviter"); - if (options.body) { - _this.body = { - body: options.body, - contentType: options.contentType ? options.contentType : "application/sdp" - }; - } - // Anonymous call - var anonymous = options.anonymous || false; - if (anonymous && userAgent.configuration.uri) { - options.params.fromDisplayName = "Anonymous"; - options.params.fromUri = "sip:anonymous@anonymous.invalid"; - } - // From Tag - var fromTag = Utils_1.Utils.newTag(); - // Contact - // Do not add ;ob in initial forming dialog requests if the registration over - // the current connection got a GRUU URI. - var contact = userAgent.contact.toString({ - anonymous: anonymous, - outbound: anonymous ? !userAgent.contact.tempGruu : !userAgent.contact.pubGruu - }); - // Params - var params = options.params || {}; - params.fromTag = fromTag; - // URIs - var fromURI = userAgent.userAgentCore.configuration.aor; - if (options.params.fromUri) { - fromURI = - (typeof options.params.fromUri === "string") ? - core_1.Grammar.URIParse(options.params.fromUri) : - options.params.fromUri; - } - if (!fromURI) { - throw new TypeError("Invalid from URI: " + options.params.fromUri); - } - var toURI = targetURI; - if (options.params.toUri) { - toURI = - (typeof options.params.toUri === "string") ? - core_1.Grammar.URIParse(options.params.toUri) : - options.params.toUri; - } - if (!toURI) { - throw new TypeError("Invalid to URI: " + options.params.toUri); - } - // Extra headers - var extraHeaders = (options.extraHeaders || []).slice(); - if (anonymous && userAgent.configuration.uri) { - extraHeaders.push("P-Preferred-Identity: " + userAgent.configuration.uri.toString()); - extraHeaders.push("Privacy: id"); - } - extraHeaders.push("Contact: " + contact); - // This is UA.C.ALLOWED_METHODS, removed to get around circular dependency - extraHeaders.push("Allow: " + [ - "ACK", - "CANCEL", - "INVITE", - "MESSAGE", - "BYE", - "OPTIONS", - "INFO", - "NOTIFY", - "REFER" - ].toString()); - if (userAgent.configuration.sipExtension100rel === user_agent_options_1.SIPExtension.Required) { - extraHeaders.push("Require: 100rel"); - } - if (userAgent.configuration.sipExtensionReplaces === user_agent_options_1.SIPExtension.Required) { - extraHeaders.push("Require: replaces"); - } - var body; - if (_this.body) { - body = Utils_1.Utils.fromBodyObj(_this.body); - } - // Request - _this.request = userAgent.userAgentCore.makeOutgoingRequestMessage(_this.method, targetURI, fromURI, toURI, params, extraHeaders, body); - if (!_this.request.from) { - throw new Error("From undefined."); - } - if (!_this.request.to) { - throw new Error("From undefined."); - } - _this.localIdentity = _this.request.from; - _this.remoteIdentity = _this.request.to; - // Options - options.params = params; - options.extraHeaders = extraHeaders; - // Session properties - _this.contact = contact; - _this.fromTag = fromTag; - _this.id = _this.request.callId + _this.fromTag; - _this.onInfo = options.onInfo; - _this.passedOptions = options; // Save for later to use with refer - _this.renderbody = options.renderbody || undefined; - _this.rendertype = options.rendertype || "text/plain"; - _this.sessionDescriptionHandlerModifiers = options.SessionDescriptionHandlerModifiers || []; - _this.sessionDescriptionHandlerOptions = options.sessionDescriptionHandlerOptions || {}; - // InviteClientContext properties - _this.inviteWithoutSdp = options.inviteWithoutSdp || false; - _this.isCanceled = false; - _this.earlyMedia = options.earlyMedia || false; - userAgent.applicants[_this.toString()] = _this; - return _this; - } - /** - * Cancels the INVITE request. - * @param options - Options bucket. - */ - Inviter.prototype.cancel = function (options) { - if (options === void 0) { options = {}; } - this.logger.log("Inviter.cancel"); - // validate state - if (this.state !== session_state_1.SessionState.Initial && this.state !== session_state_1.SessionState.Establishing) { - var error = new Error("Invalid session state " + this.state); - this.logger.error(error.message); - return Promise.reject(error); - } - // canceled has some special cases - if (this.isCanceled) { - throw new Error("Already canceled."); - } - this.isCanceled = true; - // transition state - this.stateTransition(session_state_1.SessionState.Terminating); - // cleanup media as needed - this.disposeEarlyMedia(); - if (this.sessionDescriptionHandler) { - this.sessionDescriptionHandler.close(); - } - if (this.outgoingInviteRequest) { - // the CANCEL may not be respected by peer(s), so don't transition to terminated - var cancelReason = void 0; - if (options.statusCode && options.reasonPhrase) { - cancelReason = Utils_1.Utils.getCancelReason(options.statusCode, options.reasonPhrase); - } - this.outgoingInviteRequest.cancel(cancelReason, options); - } - else { - this.logger.warn("Canceled session before INVITE was sent"); - this.stateTransition(session_state_1.SessionState.Terminated); - } - return Promise.resolve(); - }; - /** - * Sends the INVITE request. - * @remarks - * TLDR... - * 1) Only one offer/answer exchange permitted during initial INVITE. - * 2) No "early media" if the initial offer is in an INVITE (default behavior). - * 3) If "early media" and the initial offer is in an INVITE, no INVITE forking. - * - * 1) Only one offer/answer exchange permitted during initial INVITE. - * - * Our implementation replaces the following bullet point... - * - * o After having sent or received an answer to the first offer, the - * UAC MAY generate subsequent offers in requests based on rules - * specified for that method, but only if it has received answers - * to any previous offers, and has not sent any offers to which it - * hasn't gotten an answer. - * https://tools.ietf.org/html/rfc3261#section-13.2.1 - * - * ...with... - * - * o After having sent or received an answer to the first offer, the - * UAC MUST NOT generate subsequent offers in requests based on rules - * specified for that method. - * - * ...which in combination with this bullet point... - * - * o Once the UAS has sent or received an answer to the initial - * offer, it MUST NOT generate subsequent offers in any responses - * to the initial INVITE. This means that a UAS based on this - * specification alone can never generate subsequent offers until - * completion of the initial transaction. - * https://tools.ietf.org/html/rfc3261#section-13.2.1 - * - * ...ensures that EXACTLY ONE offer/answer exchange will occur - * during an initial out of dialog INVITE request made by our UAC. - * - * - * 2) No "early media" if the initial offer is in an INVITE (default behavior). - * - * While our implementation adheres to the following bullet point... - * - * o If the initial offer is in an INVITE, the answer MUST be in a - * reliable non-failure message from UAS back to UAC which is - * correlated to that INVITE. For this specification, that is - * only the final 2xx response to that INVITE. That same exact - * answer MAY also be placed in any provisional responses sent - * prior to the answer. The UAC MUST treat the first session - * description it receives as the answer, and MUST ignore any - * session descriptions in subsequent responses to the initial - * INVITE. - * https://tools.ietf.org/html/rfc3261#section-13.2.1 - * - * We have made the following implementation decision with regard to early media... - * - * o If the initial offer is in the INVITE, the answer from the - * UAS back to the UAC will establish a media session only - * only after the final 2xx response to that INVITE is received. - * - * The reason for this decision is rooted in a restriction currently - * inherent in WebRTC. Specifically, while a SIP INVITE request with an - * initial offer may fork resulting in more than one provisional answer, - * there is currently no easy/good way to to "fork" an offer generated - * by a peer connection. In particular, a WebRTC offer currently may only - * be matched with one answer and we have no good way to know which - * "provisional answer" is going to be the "final answer". So we have - * decided to punt and not create any "early media" sessions in this case. - * - * The upshot is that if you want "early media", you must not put the - * initial offer in the INVITE. Instead, force the UAS to provide the - * initial offer by sending an INVITE without an offer. In the WebRTC - * case this allows us to create a unique peer connection with a unique - * answer for every provisional offer with "early media" on all of them. - * - * - * 3) If "early media" and the initial offer is in an INVITE, no INVITE forking. - * - * The default behaviour may be altered and "early media" utilized if the - * initial offer is in the an INVITE by setting the `earlyMedia` options. - * However in that case the INVITE request MUST NOT fork. This allows for - * "early media" in environments where the forking behaviour of the SIP - * servers being utilized is configured to disallow forking. - */ - Inviter.prototype.invite = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - this.logger.log("Inviter.invite"); - // validate state - if (this.state !== session_state_1.SessionState.Initial) { - // re-invite - return _super.prototype.invite.call(this, options); - } - if (!this.id) { - throw new Error("Session id undefined."); - } - // save the session into the user agent sessions collection. - this.userAgent.sessions[this.id] = this; - // just send an INVITE with no sdp... - if (options.withoutSdp || this.inviteWithoutSdp) { - if (this.renderbody && this.rendertype) { - this.request.body = { contentType: this.rendertype, body: this.renderbody }; - } - // transition state - this.stateTransition(session_state_1.SessionState.Establishing); - this.status = Enums_1.SessionStatus.STATUS_INVITE_SENT; - return Promise.resolve(this.sendInvite(options)); - } - // get an offer and send it in an INVITE - var offerOptions = { - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers - }; - return this.getOffer(offerOptions) - .then(function (body) { - // TODO: Review error handling... - // There are some race conditions which can occur, all of which will cause stateTransition() to throw. - // - invite() can be called (a)synchronously after invite() is called (second call to invite() fails) - // - cancel() or terminate()) can be called (a)synchronously after invite() (invite() fails) - // The caller should avoid the first case, but the second one is common. - // For now we are just letting the state transition fail in all cases. - // transition state - _this.stateTransition(session_state_1.SessionState.Establishing); - _this.status = Enums_1.SessionStatus.STATUS_INVITE_SENT; - _this.request.body = { body: body.content, contentType: body.contentType }; - return _this.sendInvite(options); - }) - .catch(function (error) { - _this.logger.log(error.message); - _this.failed(undefined, Constants_1.C.causes.WEBRTC_ERROR); - _this.terminated(undefined, Constants_1.C.causes.WEBRTC_ERROR); - throw error; - }); - }; - /** - * 13.2.1 Creating the Initial INVITE - * - * Since the initial INVITE represents a request outside of a dialog, - * its construction follows the procedures of Section 8.1.1. Additional - * processing is required for the specific case of INVITE. - * - * An Allow header field (Section 20.5) SHOULD be present in the INVITE. - * It indicates what methods can be invoked within a dialog, on the UA - * sending the INVITE, for the duration of the dialog. For example, a - * UA capable of receiving INFO requests within a dialog [34] SHOULD - * include an Allow header field listing the INFO method. - * - * A Supported header field (Section 20.37) SHOULD be present in the - * INVITE. It enumerates all the extensions understood by the UAC. - * - * An Accept (Section 20.1) header field MAY be present in the INVITE. - * It indicates which Content-Types are acceptable to the UA, in both - * the response received by it, and in any subsequent requests sent to - * it within dialogs established by the INVITE. The Accept header field - * is especially useful for indicating support of various session - * description formats. - * - * The UAC MAY add an Expires header field (Section 20.19) to limit the - * validity of the invitation. If the time indicated in the Expires - * header field is reached and no final answer for the INVITE has been - * received, the UAC core SHOULD generate a CANCEL request for the - * INVITE, as per Section 9. - * - * A UAC MAY also find it useful to add, among others, Subject (Section - * 20.36), Organization (Section 20.25) and User-Agent (Section 20.41) - * header fields. They all contain information related to the INVITE. - * - * The UAC MAY choose to add a message body to the INVITE. Section - * 8.1.1.10 deals with how to construct the header fields -- Content- - * Type among others -- needed to describe the message body. - * - * https://tools.ietf.org/html/rfc3261#section-13.2.1 - */ - Inviter.prototype.sendInvite = function (options) { - // There are special rules for message bodies that contain a session - // description - their corresponding Content-Disposition is "session". - // SIP uses an offer/answer model where one UA sends a session - // description, called the offer, which contains a proposed description - // of the session. The offer indicates the desired communications means - // (audio, video, games), parameters of those means (such as codec - // types) and addresses for receiving media from the answerer. The - // other UA responds with another session description, called the - // answer, which indicates which communications means are accepted, the - // parameters that apply to those means, and addresses for receiving - // media from the offerer. An offer/answer exchange is within the - // context of a dialog, so that if a SIP INVITE results in multiple - // dialogs, each is a separate offer/answer exchange. The offer/answer - // model defines restrictions on when offers and answers can be made - // (for example, you cannot make a new offer while one is in progress). - // This results in restrictions on where the offers and answers can - // appear in SIP messages. In this specification, offers and answers - // can only appear in INVITE requests and responses, and ACK. The usage - // of offers and answers is further restricted. For the initial INVITE - // transaction, the rules are: - // - // o The initial offer MUST be in either an INVITE or, if not there, - // in the first reliable non-failure message from the UAS back to - // the UAC. In this specification, that is the final 2xx - // response. - // - // o If the initial offer is in an INVITE, the answer MUST be in a - // reliable non-failure message from UAS back to UAC which is - // correlated to that INVITE. For this specification, that is - // only the final 2xx response to that INVITE. That same exact - // answer MAY also be placed in any provisional responses sent - // prior to the answer. The UAC MUST treat the first session - // description it receives as the answer, and MUST ignore any - // session descriptions in subsequent responses to the initial - // INVITE. - // - // o If the initial offer is in the first reliable non-failure - // message from the UAS back to UAC, the answer MUST be in the - // acknowledgement for that message (in this specification, ACK - // for a 2xx response). - // - // o After having sent or received an answer to the first offer, the - // UAC MAY generate subsequent offers in requests based on rules - // specified for that method, but only if it has received answers - // to any previous offers, and has not sent any offers to which it - // hasn't gotten an answer. - // - // o Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - var _this = this; - if (options === void 0) { options = {}; } - // 5 The Offer/Answer Model and PRACK - // - // RFC 3261 describes guidelines for the sets of messages in which - // offers and answers [3] can appear. Based on those guidelines, this - // extension provides additional opportunities for offer/answer - // exchanges. - // If the INVITE contained an offer, the UAS MAY generate an answer in a - // reliable provisional response (assuming these are supported by the - // UAC). That results in the establishment of the session before - // completion of the call. Similarly, if a reliable provisional - // response is the first reliable message sent back to the UAC, and the - // INVITE did not contain an offer, one MUST appear in that reliable - // provisional response. - // If the UAC receives a reliable provisional response with an offer - // (this would occur if the UAC sent an INVITE without an offer, in - // which case the first reliable provisional response will contain the - // offer), it MUST generate an answer in the PRACK. If the UAC receives - // a reliable provisional response with an answer, it MAY generate an - // additional offer in the PRACK. If the UAS receives a PRACK with an - // offer, it MUST place the answer in the 2xx to the PRACK. - // Once an answer has been sent or received, the UA SHOULD establish the - // session based on the parameters of the offer and answer, even if the - // original INVITE itself has not been responded to. - // If the UAS had placed a session description in any reliable - // provisional response that is unacknowledged when the INVITE is - // accepted, the UAS MUST delay sending the 2xx until the provisional - // response is acknowledged. Otherwise, the reliability of the 1xx - // cannot be guaranteed, and reliability is needed for proper operation - // of the offer/answer exchange. - // All user agents that support this extension MUST support all - // offer/answer exchanges that are possible based on the rules in - // Section 13.2 of RFC 3261, based on the existence of INVITE and PRACK - // as requests, and 2xx and reliable 1xx as non-failure reliable - // responses. - // - // https://tools.ietf.org/html/rfc3262#section-5 - //// - // The Offer/Answer Model Implementation - // - // The offer/answer model is straight forward, but one MUST READ the specifications... - // - // 13.2.1 Creating the Initial INVITE (paragraph 8 in particular) - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // - // 5 The Offer/Answer Model and PRACK - // https://tools.ietf.org/html/rfc3262#section-5 - // - // Session Initiation Protocol (SIP) Usage of the Offer/Answer Model - // https://tools.ietf.org/html/rfc6337 - //// - //// - // TODO: The Offer/Answer Model Implementation - // - // Currently if `earlyMedia` is enabled and the INVITE request forks, - // the session is terminated if the early dialog does not match the - // confirmed dialog. This restriction make sense in a WebRTC environment, - // but there are other enviroments where this restriction does not hold. - // - // So while we currently cannot make the offer in INVITE+forking+webrtc - // case work, we propose doing the following... - // - // OPTION 1 - // - add a `earlyMediaForking` option and - // - require SDH.setDescription() to be callable multiple times. - // - // OPTION 2 - // 1) modify SDH Factory to provide an initial offer without giving us the SDH, and then... - // 2) stick that offer in the initial INVITE, and when 183 with initial answer is received... - // 3) ask SDH Factory if it supports "earlyRemoteAnswer" - // a) if true, ask SDH Factory to createSDH(localOffer).then((sdh) => sdh.setDescription(remoteAnswer) - // b) if false, defer getting a SDH until 2xx response is received - // - // Our supplied WebRTC SDH will default to behavior 3b which works in forking environment (without) - // early media if initial offer is in the INVITE). We will, however, provide an "inviteWillNotFork" - // option which if set to "true" will have our supplied WebRTC SDH behave in the 3a manner. - // That will result in - // - early media working with initial offer in the INVITE, and... - // - if the INVITE forks, the session terminating with an ERROR that reads like - // "You set 'inviteWillNotFork' to true but the INVITE forked. You can't eat your cake, and have it too." - // - furthermore, we accept that users will report that error to us as "bug" regardless - // - // So, SDH Factory is going to end up with a new interface along the lines of... - // - // interface SessionDescriptionHandlerFactory { - // makeLocalOffer(): Promise; - // makeSessionDescriptionHandler( - // initialOffer: ContentTypeAndBody, offerType: "local" | "remote" - // ): Promise; - // supportsEarlyRemoteAnswer: boolean; - // supportsContentType(contentType: string): boolean; - // getDescription(description: ContentTypeAndBody): Promise - // setDescription(description: ContentTypeAndBody): Promise - // } - //// - // Send the INVITE request. - this.outgoingInviteRequest = this.userAgent.userAgentCore.invite(this.request, { - onAccept: function (inviteResponse) { - // Our transaction layer is "non-standard" in that it will only - // pass us a 2xx response once per branch, so there is no need to - // worry about dealing with 2xx retransmissions. However, we can - // and do still get 2xx responses for multiple branches (when an - // INVITE is forked) which may create multiple confirmed dialogs. - // Herein we are acking and sending a bye to any confirmed dialogs - // which arrive beyond the first one. This is the desired behavior - // for most applications (but certainly not all). - // If we already received a confirmed dialog, ack & bye this additional confirmed session. - if (_this.dialog) { - _this.logger.log("Additional confirmed dialog, sending ACK and BYE"); - _this.ackAndBye(inviteResponse); - // We do NOT transition state in this case (this is an "extra" dialog) - return; - } - // If the user requested cancellation, ack & bye this session. - if (_this.isCanceled) { - _this.logger.log("Canceled session accepted, sending ACK and BYE"); - _this.ackAndBye(inviteResponse); - _this.stateTransition(session_state_1.SessionState.Terminated); - _this.emit("bye", _this.request); // FIXME: Ported this odd second "bye" emit - return; - } - _this.notifyReferer(inviteResponse); - _this.onAccept(inviteResponse) - .then(function () { - _this.disposeEarlyMedia(); - }) - .catch(function (error) { - _this.disposeEarlyMedia(); - }) - .then(function () { - if (options.requestDelegate && options.requestDelegate.onAccept) { - options.requestDelegate.onAccept(inviteResponse); - } - }); - }, - onProgress: function (inviteResponse) { - // If the user requested cancellation, ignore response. - if (_this.isCanceled) { - return; - } - _this.notifyReferer(inviteResponse); - _this.onProgress(inviteResponse) - .catch(function (error) { - _this.disposeEarlyMedia(); - }) - .then(function () { - if (options.requestDelegate && options.requestDelegate.onProgress) { - options.requestDelegate.onProgress(inviteResponse); - } - }); - }, - onRedirect: function (inviteResponse) { - _this.notifyReferer(inviteResponse); - _this.onRedirect(inviteResponse); - if (options.requestDelegate && options.requestDelegate.onRedirect) { - options.requestDelegate.onRedirect(inviteResponse); - } - }, - onReject: function (inviteResponse) { - _this.notifyReferer(inviteResponse); - _this.onReject(inviteResponse); - if (options.requestDelegate && options.requestDelegate.onReject) { - options.requestDelegate.onReject(inviteResponse); - } - }, - onTrying: function (inviteResponse) { - _this.notifyReferer(inviteResponse); - _this.onTrying(inviteResponse); - if (options.requestDelegate && options.requestDelegate.onTrying) { - options.requestDelegate.onTrying(inviteResponse); - } - } - }); - return this.outgoingInviteRequest; - }; - Inviter.prototype.disposeEarlyMedia = function () { - this.earlyMediaSessionDescriptionHandlers.forEach(function (sessionDescriptionHandler) { - sessionDescriptionHandler.close(); - }); - }; - Inviter.prototype.notifyReferer = function (response) { - var _this = this; - if (!this.referred) { - return; - } - if (!(this.referred instanceof session_1.Session)) { - throw new Error("Referred session not instance of session"); - } - if (!this.referred.dialog) { - return; - } - if (!response.message.statusCode) { - throw new Error("Status code undefined."); - } - if (!response.message.reasonPhrase) { - throw new Error("Reason phrase undefined."); - } - var statusCode = response.message.statusCode; - var reasonPhrase = response.message.reasonPhrase; - var body = ("SIP/2.0 " + statusCode + " " + reasonPhrase).trim(); - var outgoingNotifyRequest = this.referred.dialog.notify(undefined, { - extraHeaders: [ - "Event: refer", - "Subscription-State: terminated", - ], - body: { - contentDisposition: "render", - contentType: "message/sipfrag", - content: body - } - }); - // The implicit subscription created by a REFER is the same as a - // subscription created with a SUBSCRIBE request. The agent issuing the - // REFER can terminate this subscription prematurely by unsubscribing - // using the mechanisms described in [2]. Terminating a subscription, - // either by explicitly unsubscribing or rejecting NOTIFY, is not an - // indication that the referenced request should be withdrawn or - // abandoned. - // https://tools.ietf.org/html/rfc3515#section-2.4.4 - // FIXME: TODO: This should be done in a subscribe dialog to satisfy the above. - // If the notify is rejected, stop sending NOTIFY requests. - outgoingNotifyRequest.delegate = { - onReject: function () { - _this.referred = undefined; - } - }; - }; - /** - * Handle final response to initial INVITE. - * @param inviteResponse - 2xx response. - */ - Inviter.prototype.onAccept = function (inviteResponse) { - var _this = this; - this.logger.log("Inviter.onAccept"); - // validate state - if (this.state !== session_state_1.SessionState.Establishing) { - this.logger.error("Accept received while in state " + this.state + ", dropping response"); - return Promise.reject(new Error("Invalid session state " + this.state)); - } - var response = inviteResponse.message; - var session = inviteResponse.session; - // Ported behavior. - if (response.hasHeader("P-Asserted-Identity")) { - this.assertedIdentity = core_1.Grammar.nameAddrHeaderParse(response.getHeader("P-Asserted-Identity")); - } - // We have a confirmed dialog. - this.dialog = session; - this.dialog.delegate = { - onAck: function (ackRequest) { return _this.onAckRequest(ackRequest); }, - onBye: function (byeRequest) { return _this.onByeRequest(byeRequest); }, - onInfo: function (infoRequest) { return _this.onInfoRequest(infoRequest); }, - onInvite: function (inviteRequest) { return _this.onInviteRequest(inviteRequest); }, - onNotify: function (notifyRequest) { return _this.onNotifyRequest(notifyRequest); }, - onPrack: function (prackRequest) { return _this.onPrackRequest(prackRequest); }, - onRefer: function (referRequest) { return _this.onReferRequest(referRequest); } - }; - var sdhOptions = this.sessionDescriptionHandlerOptions; - var sdhModifiers = this.sessionDescriptionHandlerModifiers; - switch (session.signalingState) { - case core_1.SignalingState.Initial: - // INVITE without offer, so MUST have offer at this point, so invalid state. - this.ackAndBye(inviteResponse, 400, "Missing session description"); - this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - return Promise.reject(new Error(Constants_1.C.causes.BAD_MEDIA_DESCRIPTION)); - case core_1.SignalingState.HaveLocalOffer: - // INVITE with offer, so MUST have answer at this point, so invalid state. - this.ackAndBye(inviteResponse, 400, "Missing session description"); - this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - return Promise.reject(new Error(Constants_1.C.causes.BAD_MEDIA_DESCRIPTION)); - case core_1.SignalingState.HaveRemoteOffer: { - // INVITE without offer, received offer in 2xx, so MUST send answer in ACK. - if (!this.dialog.offer) { - throw new Error("Session offer undefined in signaling state " + this.dialog.signalingState + "."); - } - var options = { - sessionDescriptionHandlerOptions: sdhOptions, - sessionDescriptionHandlerModifiers: sdhModifiers - }; - return this.setOfferAndGetAnswer(this.dialog.offer, options) - .then(function (body) { - _this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; - var ackRequest = inviteResponse.ack({ body: body }); - _this.stateTransition(session_state_1.SessionState.Established); - }) - .catch(function (error) { - _this.ackAndBye(inviteResponse, 488, "Invalid session description"); - _this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - throw error; - }); - } - case core_1.SignalingState.Stable: { - // If INVITE without offer and we have already completed the initial exchange. - if (this.earlyMediaSessionDescriptionHandlers.size > 0) { - var sdh = this.earlyMediaSessionDescriptionHandlers.get(session.id); - if (!sdh) { - throw new Error("Session description handler undefined."); - } - this.setSessionDescriptionHandler(sdh); - this.earlyMediaSessionDescriptionHandlers.delete(session.id); - this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; - var ackRequest = inviteResponse.ack(); - this.stateTransition(session_state_1.SessionState.Established); - return Promise.resolve(); - } - // If INVITE with offer and we used an "early" answer in a provisional response for media - if (this.earlyMediaDialog) { - // If early media dialog doesn't match confirmed dialog, we must unfortunately fail. - // This limitation stems from how WebRTC currently implements its offer/answer model. - // There are details elsewhere, but in short a WebRTC offer cannot be forked. - if (this.earlyMediaDialog !== session) { - if (this.earlyMedia) { - var message = "You have set the 'earlyMedia' option to 'true' which requires that your INVITE requests " + - "do not fork and yet this INVITE request did in fact fork. Consequentially and not surprisingly " + - "the end point which accepted the INVITE (confirmed dialog) does not match the end point with " + - "which early media has been setup (early dialog) and thus this session is unable to proceed. " + - "In accordance with the SIP specifications, the SIP servers your end point is connected to " + - "determine if an INVITE forks and the forking behaviour of those servers cannot be controlled " + - "by this library. If you wish to use early media with this library you must configure those " + - "servers accordingly. Alternatively you may set the 'earlyMedia' to 'false' which will allow " + - "this library to function with any INVITE requests which do fork."; - this.logger.error(message); - } - var error = new Error("Early media dialog does not equal confirmed dialog, terminating session"); - this.logger.error(error.message); - this.ackAndBye(inviteResponse, 488, "Not Acceptable Here"); - this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - return Promise.reject(error); - } - // Otherwise we are good to go. - this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; - var ackRequest = inviteResponse.ack(); - this.stateTransition(session_state_1.SessionState.Established); - return Promise.resolve(); - } - // If INVITE with offer and we have been waiting till now to apply the answer. - var answer = session.answer; - if (!answer) { - throw new Error("Answer is undefined."); - } - var options = { - sessionDescriptionHandlerOptions: sdhOptions, - sessionDescriptionHandlerModifiers: sdhModifiers - }; - return this.setAnswer(answer, options) - .then(function () { - // This session has completed an initial offer/answer exchange... - var ackOptions; - if (_this.renderbody && _this.rendertype) { - ackOptions = { - body: { contentDisposition: "render", contentType: _this.rendertype, content: _this.renderbody } - }; - } - _this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; - var ackRequest = inviteResponse.ack(ackOptions); - _this.stateTransition(session_state_1.SessionState.Established); - }) - .catch(function (error) { - _this.logger.error(error.message); - _this.ackAndBye(inviteResponse, 488, "Not Acceptable Here"); - _this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - throw error; - }); - } - case core_1.SignalingState.Closed: - // Dialog has terminated. - return Promise.reject(new Error("Terminated.")); - default: - throw new Error("Unknown session signaling state."); - } - }; - /** - * Handle provisional response to initial INVITE. - * @param inviteResponse - 1xx response. - */ - Inviter.prototype.onProgress = function (inviteResponse) { - var _this = this; - this.logger.log("Inviter.onProgress"); - // validate state - if (this.state !== session_state_1.SessionState.Establishing) { - this.logger.error("Progress received while in state " + this.state + ", dropping response"); - return Promise.reject(new Error("Invalid session state " + this.state)); - } - if (!this.outgoingInviteRequest) { - throw new Error("Outgoing INVITE request undefined."); - } - var response = inviteResponse.message; - var session = inviteResponse.session; - // Ported - Set status. - this.status = Enums_1.SessionStatus.STATUS_1XX_RECEIVED; - // Ported - Set assertedIdentity. - if (response.hasHeader("P-Asserted-Identity")) { - this.assertedIdentity = core_1.Grammar.nameAddrHeaderParse(response.getHeader("P-Asserted-Identity")); - } - // If a provisional response is received for an initial request, and - // that response contains a Require header field containing the option - // tag 100rel, the response is to be sent reliably. If the response is - // a 100 (Trying) (as opposed to 101 to 199), this option tag MUST be - // ignored, and the procedures below MUST NOT be used. - // https://tools.ietf.org/html/rfc3262#section-4 - var requireHeader = response.getHeader("require"); - var rseqHeader = response.getHeader("rseq"); - var rseq = requireHeader && requireHeader.includes("100rel") && rseqHeader ? Number(rseqHeader) : undefined; - var responseReliable = !!rseq; - var extraHeaders = []; - if (responseReliable) { - extraHeaders.push("RAck: " + response.getHeader("rseq") + " " + response.getHeader("cseq")); - } - var sdhOptions = this.sessionDescriptionHandlerOptions; - var sdhModifiers = this.sessionDescriptionHandlerModifiers; - switch (session.signalingState) { - case core_1.SignalingState.Initial: - // INVITE without offer and session still has no offer (and no answer). - if (responseReliable) { - // Similarly, if a reliable provisional - // response is the first reliable message sent back to the UAC, and the - // INVITE did not contain an offer, one MUST appear in that reliable - // provisional response. - // https://tools.ietf.org/html/rfc3262#section-5 - this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."); - // FIXME: Known popular UA's currently end up here... - inviteResponse.prack({ extraHeaders: extraHeaders }); - } - this.emit("progress", response); - return Promise.resolve(); - case core_1.SignalingState.HaveLocalOffer: - // INVITE with offer and session only has that initial local offer. - if (responseReliable) { - inviteResponse.prack({ extraHeaders: extraHeaders }); - } - this.emit("progress", response); - return Promise.resolve(); - case core_1.SignalingState.HaveRemoteOffer: - if (!responseReliable) { - // The initial offer MUST be in either an INVITE or, if not there, - // in the first reliable non-failure message from the UAS back to - // the UAC. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // According to Section 13.2.1 of [RFC3261], 'The first reliable - // non-failure message' must have an offer if there is no offer in the - // INVITE request. This means that the User Agent (UA) that receives - // the INVITE request without an offer must include an offer in the - // first reliable response with 100rel extension. If no reliable - // provisional response has been sent, the User Agent Server (UAS) must - // include an offer when sending 2xx response. - // https://tools.ietf.org/html/rfc6337#section-2.2 - this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response."); - return Promise.resolve(); - } - // If the initial offer is in the first reliable non-failure - // message from the UAS back to UAC, the answer MUST be in the - // acknowledgement for that message - var sdh_1 = this.sessionDescriptionHandlerFactory(this, this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions || {}); - this.emit("SessionDescriptionHandler-created", sdh_1); - this.earlyMediaSessionDescriptionHandlers.set(session.id, sdh_1); - return sdh_1 - .setDescription(response.body, sdhOptions, sdhModifiers) - .then(function () { return sdh_1.getDescription(sdhOptions, sdhModifiers); }) - .then(function (description) { - var body = { - contentDisposition: "session", contentType: description.contentType, content: description.body - }; - inviteResponse.prack({ extraHeaders: extraHeaders, body: body }); - _this.emit("progress", response); - }) - .catch(function (error) { - if (_this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - throw error; - } - _this.failed(undefined, Constants_1.C.causes.WEBRTC_ERROR); - _this.terminated(undefined, Constants_1.C.causes.WEBRTC_ERROR); - throw error; - }); - case core_1.SignalingState.Stable: - // This session has completed an initial offer/answer exchange, so... - // - INVITE with SDP and this provisional response MAY be reliable - // - INVITE without SDP and this provisional response MAY be reliable - if (responseReliable) { - inviteResponse.prack({ extraHeaders: extraHeaders }); - } - if (this.earlyMedia && !this.earlyMediaDialog) { - this.earlyMediaDialog = session; - var answer = session.answer; - if (!answer) { - throw new Error("Answer is undefined."); - } - var options = { - sessionDescriptionHandlerOptions: sdhOptions, - sessionDescriptionHandlerModifiers: sdhModifiers - }; - return this.setAnswer(answer, options) - .then(function () { - _this.emit("progress", response); - }) - .catch(function (error) { - if (_this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - throw error; - } - _this.failed(undefined, Constants_1.C.causes.WEBRTC_ERROR); - _this.terminated(undefined, Constants_1.C.causes.WEBRTC_ERROR); - throw error; - }); - } - this.emit("progress", response); - return Promise.resolve(); - case core_1.SignalingState.Closed: - // Dialog has terminated. - return Promise.reject(new Error("Terminated.")); - default: - throw new Error("Unknown session signaling state."); - } - }; - /** - * Handle final response to initial INVITE. - * @param inviteResponse - 3xx response. - */ - Inviter.prototype.onRedirect = function (inviteResponse) { - this.logger.log("Inviter.onRedirect"); - // validate state - if (this.state !== session_state_1.SessionState.Establishing && - this.state !== session_state_1.SessionState.Terminating) { - this.logger.error("Redirect received while in state " + this.state + ", dropping response"); - return; - } - // transition state - this.stateTransition(session_state_1.SessionState.Terminated); - this.disposeEarlyMedia(); - var response = inviteResponse.message; - var statusCode = response.statusCode; - var cause = Utils_1.Utils.sipErrorCause(statusCode || 0); - this.rejected(response, cause); - this.failed(response, cause); - this.terminated(response, cause); - }; - /** - * Handle final response to initial INVITE. - * @param inviteResponse - 4xx, 5xx, or 6xx response. - */ - Inviter.prototype.onReject = function (inviteResponse) { - this.logger.log("Inviter.onReject"); - // validate state - if (this.state !== session_state_1.SessionState.Establishing && - this.state !== session_state_1.SessionState.Terminating) { - this.logger.error("Reject received while in state " + this.state + ", dropping response"); - return; - } - // transition state - this.stateTransition(session_state_1.SessionState.Terminated); - this.disposeEarlyMedia(); - var response = inviteResponse.message; - var statusCode = response.statusCode; - var cause = Utils_1.Utils.sipErrorCause(statusCode || 0); - this.rejected(response, cause); - this.failed(response, cause); - this.terminated(response, cause); - }; - /** - * Handle final response to initial INVITE. - * @param inviteResponse - 100 response. - */ - Inviter.prototype.onTrying = function (inviteResponse) { - this.logger.log("Inviter.onTrying"); - // legacy behavior - doing this in any state seems broken - this.emit("progress", inviteResponse.message); - // validate state - if (this.state !== session_state_1.SessionState.Establishing) { - this.logger.error("Trying received while in state " + this.state + ", dropping response"); - return; - } - }; - return Inviter; -}(session_1.Session)); -exports.Inviter = Inviter; - - -/***/ }), -/* 112 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * A received message (incoming MESSAGE). - * @public - */ -var Message = /** @class */ (function () { - /** @internal */ - function Message(incomingMessageRequest) { - this.incomingMessageRequest = incomingMessageRequest; - } - Object.defineProperty(Message.prototype, "request", { - /** Incoming MESSAGE request message. */ - get: function () { - return this.incomingMessageRequest.message; - }, - enumerable: true, - configurable: true - }); - /** Accept the request. */ - Message.prototype.accept = function (options) { - this.incomingMessageRequest.accept(options); - return Promise.resolve(); - }; - /** Reject the request. */ - Message.prototype.reject = function (options) { - this.incomingMessageRequest.reject(options); - return Promise.resolve(); - }; - return Message; -}()); -exports.Message = Message; - - -/***/ }), -/* 113 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var events_1 = __webpack_require__(30); -var core_1 = __webpack_require__(2); -/** - * A messager sends a {@link Message} (outgoing MESSAGE). - * @public - */ -var Messager = /** @class */ (function (_super) { - tslib_1.__extends(Messager, _super); - /** - * Constructs a new instance of the `Messager` class. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @param targetURI - Request URI identifying the target of the message. - * @param content - Content for the body of the message. - * @param contentType - Content type of the body of the message. - * @param options - Options bucket. See {@link MessagerOptions} for details. - */ - function Messager(userAgent, targetURI, content, contentType, options) { - if (contentType === void 0) { contentType = "text/plain"; } - if (options === void 0) { options = {}; } - var _this = _super.call(this) || this; - _this._disposed = false; - // Logger - _this.logger = userAgent.getLogger("sip.messager"); - // Default options params - options.params = options.params || {}; - // URIs - var fromURI = userAgent.userAgentCore.configuration.aor; - if (options.params.fromUri) { - fromURI = - (typeof options.params.fromUri === "string") ? - core_1.Grammar.URIParse(options.params.fromUri) : - options.params.fromUri; - } - if (!fromURI) { - throw new TypeError("Invalid from URI: " + options.params.fromUri); - } - var toURI = targetURI; - if (options.params.toUri) { - toURI = - (typeof options.params.toUri === "string") ? - core_1.Grammar.URIParse(options.params.toUri) : - options.params.toUri; - } - if (!toURI) { - throw new TypeError("Invalid to URI: " + options.params.toUri); - } - // Message params - var params = options.params ? tslib_1.__assign({}, options.params) : {}; - // Extra headers - var extraHeaders = (options.extraHeaders || []).slice(); - // Body - var contentDisposition = "render"; - var body = { - contentDisposition: contentDisposition, - contentType: contentType, - content: content - }; - // Build the request - _this.request = userAgent.userAgentCore.makeOutgoingRequestMessage(core_1.C.MESSAGE, targetURI, fromURI, toURI, params, extraHeaders, body); - // User agent - _this.userAgent = userAgent; - return _this; - } - /** - * Destructor. - * @internal - */ - Messager.prototype.dispose = function () { - if (this._disposed) { - return; - } - this._disposed = true; - }; - /** - * Send the message. - */ - Messager.prototype.message = function (options) { - if (options === void 0) { options = {}; } - this.userAgent.userAgentCore.request(this.request, options.requestDelegate); - return Promise.resolve(); - }; - return Messager; -}(events_1.EventEmitter)); -exports.Messager = Messager; - - -/***/ }), -/* 114 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var events_1 = __webpack_require__(30); -var core_1 = __webpack_require__(2); -var Exceptions_1 = __webpack_require__(84); -var Utils_1 = __webpack_require__(83); -/** - * A publisher publishes a document (outgoing PUBLISH). - * @public - */ -var Publisher = /** @class */ (function (_super) { - tslib_1.__extends(Publisher, _super); - /** - * Constructs a new instance of the `Publisher` class. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @param targetURI - Request URI identifying the target of the message. - * @param eventType - The event type identifying the published document. - * @param options - Options bucket. See {@link PublisherOptions} for details. - */ - function Publisher(userAgent, targetURI, eventType, options) { - if (options === void 0) { options = {}; } - var _this = _super.call(this) || this; - options.extraHeaders = (options.extraHeaders || []).slice(); - options.contentType = (options.contentType || "text/plain"); - if (typeof options.expires !== "number" || (options.expires % 1) !== 0) { - options.expires = 3600; - } - else { - options.expires = Number(options.expires); - } - if (typeof (options.unpublishOnClose) !== "boolean") { - options.unpublishOnClose = true; - } - _this.target = targetURI; - _this.event = eventType; - _this.options = options; - _this.pubRequestExpires = _this.options.expires; - _this.logger = userAgent.getLogger("sip.publisher"); - var params = options.params || {}; - var fromURI = params.fromUri ? params.fromUri : userAgent.userAgentCore.configuration.aor; - var toURI = params.toUri ? params.toUri : targetURI; - var body; - if (options.body && options.contentType) { - var contentDisposition = "render"; - var contentType = options.contentType; - var content = options.body; - body = { - contentDisposition: contentDisposition, - contentType: contentType, - content: content, - }; - } - var extraHeaders = (options.extraHeaders || []).slice(); - // Build the request - _this.request = userAgent.userAgentCore.makeOutgoingRequestMessage(core_1.C.PUBLISH, targetURI, fromURI, toURI, params, extraHeaders, body); - _this.userAgent = userAgent; - return _this; - } - /** - * Close - * @internal - */ - Publisher.prototype.close = function () { - // Send unpublish, if requested - if (this.options.unpublishOnClose) { - this.unpublish(); - } - else { - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - this.pubRequestBody = undefined; - this.pubRequestExpires = 0; - this.pubRequestEtag = undefined; - } - if (this.userAgent.publishers[this.target.toString() + ":" + this.event]) { - delete this.userAgent.publishers[this.target.toString() + ":" + this.event]; - } - }; - /** - * Publish - * @param content - Body to publish - */ - Publisher.prototype.publish = function (content, options) { - if (options === void 0) { options = {}; } - // Clean up before the run - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - // is Initial or Modify request - this.options.body = content; - this.pubRequestBody = this.options.body; - if (this.pubRequestExpires === 0) { - // This is Initial request after unpublish - this.pubRequestExpires = this.options.expires; - this.pubRequestEtag = undefined; - } - if (!(this.userAgent.publishers[this.target.toString() + ":" + this.event])) { - this.userAgent.publishers[this.target.toString() + ":" + this.event] = this; - } - this.sendPublishRequest(); - }; - /** - * Unpublish - */ - Publisher.prototype.unpublish = function (options) { - if (options === void 0) { options = {}; } - // Clean up before the run - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - this.pubRequestBody = undefined; - this.pubRequestExpires = 0; - if (this.pubRequestEtag !== undefined) { - this.sendPublishRequest(); - } - }; - /** @internal */ - Publisher.prototype.receiveResponse = function (response) { - var _this = this; - var statusCode = response.statusCode || 0; - var cause = Utils_1.Utils.getReasonPhrase(statusCode); - switch (true) { - case /^1[0-9]{2}$/.test(statusCode.toString()): - this.emit("progress", response, cause); - break; - case /^2[0-9]{2}$/.test(statusCode.toString()): - // Set SIP-Etag - if (response.hasHeader("SIP-ETag")) { - this.pubRequestEtag = response.getHeader("SIP-ETag"); - } - else { - this.logger.warn("SIP-ETag header missing in a 200-class response to PUBLISH"); - } - // Update Expire - if (response.hasHeader("Expires")) { - var expires = Number(response.getHeader("Expires")); - if (typeof expires === "number" && expires >= 0 && expires <= this.pubRequestExpires) { - this.pubRequestExpires = expires; - } - else { - this.logger.warn("Bad Expires header in a 200-class response to PUBLISH"); - } - } - else { - this.logger.warn("Expires header missing in a 200-class response to PUBLISH"); - } - if (this.pubRequestExpires !== 0) { - // Schedule refresh - this.publishRefreshTimer = setTimeout(function () { return _this.refreshRequest(); }, this.pubRequestExpires * 900); - this.emit("published", response, cause); - } - else { - this.emit("unpublished", response, cause); - } - break; - case /^412$/.test(statusCode.toString()): - // 412 code means no matching ETag - possibly the PUBLISH expired - // Resubmit as new request, if the current request is not a "remove" - if (this.pubRequestEtag !== undefined && this.pubRequestExpires !== 0) { - this.logger.warn("412 response to PUBLISH, recovering"); - this.pubRequestEtag = undefined; - this.emit("progress", response, cause); - this.publish(this.options.body); - } - else { - this.logger.warn("412 response to PUBLISH, recovery failed"); - this.pubRequestExpires = 0; - this.emit("failed", response, cause); - this.emit("unpublished", response, cause); - } - break; - case /^423$/.test(statusCode.toString()): - // 423 code means we need to adjust the Expires interval up - if (this.pubRequestExpires !== 0 && response.hasHeader("Min-Expires")) { - var minExpires = Number(response.getHeader("Min-Expires")); - if (typeof minExpires === "number" || minExpires > this.pubRequestExpires) { - this.logger.warn("423 code in response to PUBLISH, adjusting the Expires value and trying to recover"); - this.pubRequestExpires = minExpires; - this.emit("progress", response, cause); - this.publish(this.options.body); - } - else { - this.logger.warn("Bad 423 response Min-Expires header received for PUBLISH"); - this.pubRequestExpires = 0; - this.emit("failed", response, cause); - this.emit("unpublished", response, cause); - } - } - else { - this.logger.warn("423 response to PUBLISH, recovery failed"); - this.pubRequestExpires = 0; - this.emit("failed", response, cause); - this.emit("unpublished", response, cause); - } - break; - default: - this.pubRequestExpires = 0; - this.emit("failed", response, cause); - this.emit("unpublished", response, cause); - break; - } - // Do the cleanup - if (this.pubRequestExpires === 0) { - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - this.pubRequestBody = undefined; - this.pubRequestEtag = undefined; - } - }; - /** @internal */ - Publisher.prototype.send = function () { - var _this = this; - this.userAgent.userAgentCore.publish(this.request, { - onAccept: function (response) { return _this.receiveResponse(response.message); }, - onProgress: function (response) { return _this.receiveResponse(response.message); }, - onRedirect: function (response) { return _this.receiveResponse(response.message); }, - onReject: function (response) { return _this.receiveResponse(response.message); }, - onTrying: function (response) { return _this.receiveResponse(response.message); } - }); - return this; - }; - Publisher.prototype.refreshRequest = function () { - // Clean up before the run - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - // This is Refresh request - this.pubRequestBody = undefined; - if (this.pubRequestEtag === undefined) { - // Request not valid - throw new Exceptions_1.Exceptions.MethodParameterError("Publish", "Body", undefined); - } - if (this.pubRequestExpires === 0) { - // Request not valid - throw new Exceptions_1.Exceptions.MethodParameterError("Publish", "Expire", this.pubRequestExpires); - } - this.sendPublishRequest(); - }; - Publisher.prototype.sendPublishRequest = function () { - var reqOptions = Object.create(this.options || Object.prototype); - reqOptions.extraHeaders = (this.options.extraHeaders || []).slice(); - reqOptions.extraHeaders.push("Event: " + this.event); - reqOptions.extraHeaders.push("Expires: " + this.pubRequestExpires); - if (this.pubRequestEtag !== undefined) { - reqOptions.extraHeaders.push("SIP-If-Match: " + this.pubRequestEtag); - } - var ruri = this.target; - var params = this.options.params || {}; - var bodyAndContentType; - if (this.pubRequestBody !== undefined) { - bodyAndContentType = { - body: this.pubRequestBody, - contentType: this.options.contentType - }; - } - var body; - if (bodyAndContentType) { - body = Utils_1.Utils.fromBodyObj(bodyAndContentType); - } - this.request = this.userAgent.userAgentCore.makeOutgoingRequestMessage(core_1.C.PUBLISH, ruri, params.fromUri ? params.fromUri : this.userAgent.userAgentCore.configuration.aor, params.toUri ? params.toUri : this.target, params, reqOptions.extraHeaders, body); - this.send(); - }; - return Publisher; -}(events_1.EventEmitter)); -exports.Publisher = Publisher; - - -/***/ }), -/* 115 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var core_1 = __webpack_require__(2); -var session_state_1 = __webpack_require__(100); -/** - * A referrer sends a {@link Referral} (outgoing REFER). - * @remarks - * Sends an outgoing in dialog REFER request. - * @public - */ -var Referrer = /** @class */ (function () { - /** - * Constructs a new instance of the `Referrer` class. - * @param session - The session the REFER will be sent from. See {@link Session} for details. - * @param referTo - The referral target. If a `Session`, a REFER w/Replaces is sent. - * @param options - An options bucket. See {@link ReferrerOptions} for details. - */ - function Referrer(session, referTo, options) { - this._session = session; - this._referTo = referTo; - } - Object.defineProperty(Referrer.prototype, "session", { - /** The referrer session. */ - get: function () { - return this._session; - }, - enumerable: true, - configurable: true - }); - /** - * Sends the REFER request. - * @param options - An options bucket. - */ - Referrer.prototype.refer = function (options) { - if (options === void 0) { options = {}; } - // guard session state - if (this.session.state !== session_state_1.SessionState.Established) { - var message = "Referrer.refer() may only be called if established session."; - this.session.logger.error(message); - return Promise.reject(new Error("Invalid session state " + this.session.state)); - } - var requestDelegate = options.requestDelegate; - var requestOptions = options.requestOptions || {}; - var extraHeaders = this.extraHeaders(this.referToString(this._referTo)); - requestOptions.extraHeaders = requestOptions.extraHeaders || []; - requestOptions.extraHeaders = requestOptions.extraHeaders.concat(extraHeaders); - return this.session.refer(this, requestDelegate, requestOptions); - }; - Referrer.prototype.extraHeaders = function (referTo) { - var extraHeaders = []; - extraHeaders.push("Referred-By: <" + this._session.userAgent.configuration.uri + ">"); - extraHeaders.push("Contact: " + this._session.contact); - extraHeaders.push("Allow: " + [ - "ACK", - "CANCEL", - "INVITE", - "MESSAGE", - "BYE", - "OPTIONS", - "INFO", - "NOTIFY", - "REFER" - ].toString()); - extraHeaders.push("Refer-To: " + referTo); - return extraHeaders; - }; - Referrer.prototype.referToString = function (target) { - var referTo; - if (target instanceof core_1.URI) { - // REFER without Replaces (Blind Transfer) - referTo = target.toString(); - } - else { - // REFER with Replaces (Attended Transfer) - if (!target.dialog) { - throw new Error("Dialog undefined."); - } - var displayName = target.remoteIdentity.friendlyName; - var remoteTarget = target.dialog.remoteTarget.toString(); - var callId = target.dialog.callId; - var remoteTag = target.dialog.remoteTag; - var localTag = target.dialog.localTag; - var replaces = encodeURIComponent(callId + ";to-tag=" + remoteTag + ";from-tag=" + localTag); - referTo = "\"" + displayName + "\" <" + remoteTarget + "?Replaces=" + replaces + ">"; - } - return referTo; - }; - return Referrer; -}()); -exports.Referrer = Referrer; - - -/***/ }), -/* 116 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * {@link Registerer} state. - * @remarks - * Valid state transitions: - * ``` - * 1. "initial" --> "registered" - * 2. "initial" --> "unregistered" - * 3. "registered" --> "unregistered" - * 3. "unregistered" --> "registered" - * ``` - * @public - */ -var RegistererState; -(function (RegistererState) { - RegistererState["Initial"] = "Initial"; - RegistererState["Registered"] = "Registered"; - RegistererState["Unregistered"] = "Unregistered"; -})(RegistererState = exports.RegistererState || (exports.RegistererState = {})); - - -/***/ }), -/* 117 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var events_1 = __webpack_require__(30); -var Constants_1 = __webpack_require__(80); -var core_1 = __webpack_require__(2); -var Exceptions_1 = __webpack_require__(84); -var Utils_1 = __webpack_require__(83); -var emitter_1 = __webpack_require__(96); -var registerer_state_1 = __webpack_require__(116); -/** - * @internal - */ -function loadConfig(configuration) { - var settings = { - expires: 600, - extraContactHeaderParams: [], - instanceId: undefined, - params: {}, - regId: undefined, - registrar: undefined, - }; - var configCheck = getConfigurationCheck(); - // Check Mandatory parameters - for (var parameter in configCheck.mandatory) { - if (!configuration.hasOwnProperty(parameter)) { - throw new Exceptions_1.Exceptions.ConfigurationError(parameter); - } - else { - var value = configuration[parameter]; - var checkedValue = configCheck.mandatory[parameter](value); - if (checkedValue !== undefined) { - settings[parameter] = checkedValue; - } - else { - throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); - } - } - } - // Check Optional parameters - for (var parameter in configCheck.optional) { - if (configuration.hasOwnProperty(parameter)) { - var value = configuration[parameter]; - // If the parameter value is an empty array, but shouldn't be, apply its default value. - if (value instanceof Array && value.length === 0) { - continue; - } - // If the parameter value is null, empty string, or undefined then apply its default value. - // If it's a number with NaN value then also apply its default value. - // NOTE: JS does not allow "value === NaN", the following does the work: - if (value === null || value === "" || value === undefined || - (typeof (value) === "number" && isNaN(value))) { - continue; - } - var checkedValue = configCheck.optional[parameter](value); - if (checkedValue !== undefined) { - settings[parameter] = checkedValue; - } - else { - throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); - } - } - } - return settings; -} -/** - * @internal - */ -function getConfigurationCheck() { - return { - mandatory: {}, - optional: { - expires: function (expires) { - if (Utils_1.Utils.isDecimal(expires)) { - var value = Number(expires); - if (value >= 0) { - return value; - } - } - }, - extraContactHeaderParams: function (extraContactHeaderParams) { - if (extraContactHeaderParams instanceof Array) { - return extraContactHeaderParams.filter(function (contactHeaderParam) { return (typeof contactHeaderParam === "string"); }); - } - }, - instanceId: function (instanceId) { - if (typeof instanceId !== "string") { - return; - } - if ((/^uuid:/i.test(instanceId))) { - instanceId = instanceId.substr(5); - } - if (core_1.Grammar.parse(instanceId, "uuid") === -1) { - return; - } - else { - return instanceId; - } - }, - params: function (params) { - if (typeof params === "object") { - return params; - } - }, - regId: function (regId) { - if (Utils_1.Utils.isDecimal(regId)) { - var value = Number(regId); - if (value >= 0) { - return value; - } - } - }, - registrar: function (registrar) { - if (typeof registrar !== "string") { - return; - } - if (!/^sip:/i.test(registrar)) { - registrar = Constants_1.C.SIP + ":" + registrar; - } - var parsed = core_1.Grammar.URIParse(registrar); - if (!parsed) { - return; - } - else if (parsed.user) { - return; - } - else { - return parsed; - } - } - } - }; -} -/** - * A registerer registers a contact for an address of record (outgoing REGISTER). - * @public - */ -var Registerer = /** @class */ (function () { - /** - * Constructs a new instance of the `Registerer` class. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @param options - Options bucket. See {@link RegistererOptions} for details. - */ - function Registerer(userAgent, options) { - var _this = this; - if (options === void 0) { options = {}; } - /** The contacts returned from the most recent accepted REGISTER request. */ - this._contacts = []; - /** The registration state. */ - this._state = registerer_state_1.RegistererState.Initial; - /** Emits when the registration state changes. */ - this._stateEventEmitter = new events_1.EventEmitter(); - /** True is waiting for final response to outstanding REGISTER request. */ - this._waiting = false; - /** Emits when waiting changes. */ - this._waitingEventEmitter = new events_1.EventEmitter(); - var settings = loadConfig(options); - if (settings.regId && !settings.instanceId) { - settings.instanceId = Utils_1.Utils.newUUID(); - } - else if (!settings.regId && settings.instanceId) { - settings.regId = 1; - } - settings.params.toUri = settings.params.toUri || userAgent.configuration.uri; - settings.params.toDisplayName = settings.params.toDisplayName || userAgent.configuration.displayName; - settings.params.callId = settings.params.callId || Utils_1.Utils.createRandomToken(22); - settings.params.cseq = settings.params.cseq || Math.floor(Math.random() * 10000); - /* If no 'registrarServer' is set use the 'uri' value without user portion. */ - if (!settings.registrar) { - var registrarServer = {}; - if (typeof userAgent.configuration.uri === "object") { - registrarServer = userAgent.configuration.uri.clone(); - registrarServer.user = undefined; - } - else { - registrarServer = userAgent.configuration.uri; - } - settings.registrar = registrarServer; - } - this.userAgent = userAgent; - this.logger = userAgent.getLogger("sip.registerer"); - var extraHeaders = (options.extraHeaders || []).slice(); - // Build the request - this.request = userAgent.userAgentCore.makeOutgoingRequestMessage(Constants_1.C.REGISTER, settings.registrar, settings.params.fromUri ? settings.params.fromUri : userAgent.userAgentCore.configuration.aor, settings.params.toUri ? settings.params.toUri : settings.registrar, settings.params, extraHeaders, undefined); - this.options = settings; - this.logger.log("configuration parameters for RegisterContext after validation:"); - for (var parameter in settings) { - if (settings.hasOwnProperty(parameter)) { - this.logger.log("· " + parameter + ": " + JSON.stringify(settings[parameter])); - } - } - // Registration expires - this.expires = settings.expires; - // Contact header - this.contact = userAgent.contact.toString(); - userAgent.transport.on("disconnected", function () { return _this.onTransportDisconnected(); }); - // Add to UA's collection - this.id = this.request.callId + this.request.from.parameters.tag; - this.userAgent.registerers[this.id] = this; - } - Object.defineProperty(Registerer.prototype, "contacts", { - /** The registered contacts. */ - get: function () { - return this._contacts.slice(); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Registerer.prototype, "state", { - /** The registration state. */ - get: function () { - return this._state; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Registerer.prototype, "stateChange", { - /** Emits when the registerer state changes. */ - get: function () { - return emitter_1.makeEmitter(this._stateEventEmitter); - }, - enumerable: true, - configurable: true - }); - /** Destructor. */ - Registerer.prototype.dispose = function () { - return tslib_1.__awaiter(this, void 0, void 0, function () { - var _this = this; - return tslib_1.__generator(this, function (_a) { - // Remove from UA's collection - delete this.userAgent.registerers[this.id]; - // If registered, unregisters and resolves after final response received. - return [2 /*return*/, new Promise(function (resolve, reject) { - var doClose = function () { - // If we are registered, unregister and resolve after our state changes - if (!_this.waiting && _this._state === registerer_state_1.RegistererState.Registered) { - _this.stateChange.once(function () { return resolve(); }); - _this.unregister(); - return; - } - // Otherwise just resolve - resolve(); - }; - // If we are waiting for an outstanding request, wait for it to finish and then try closing. - // Otherwise just try closing. - if (_this.waiting) { - _this.waitingChange.once(function () { return doClose(); }); - } - else { - doClose(); - } - })]; - }); - }); - }; - /** - * Sends the REGISTER request. - * @remarks - * If successfull, sends re-REGISTER requests prior to registration expiration until `unsubscribe()` is called. - */ - Registerer.prototype.register = function (options) { - if (options === void 0) { options = {}; } - return tslib_1.__awaiter(this, void 0, void 0, function () { - var error, extraHeaders, outgoingRegisterRequest; - var _this = this; - return tslib_1.__generator(this, function (_a) { - // UAs MUST NOT send a new registration (that is, containing new Contact - // header field values, as opposed to a retransmission) until they have - // received a final response from the registrar for the previous one or - // the previous REGISTER request has timed out. - // https://tools.ietf.org/html/rfc3261#section-10.2 - if (this.waiting) { - error = new Error("REGISTER request already in progress, waiting for final response"); - return [2 /*return*/, Promise.reject(error)]; - } - // Options - if (options.requestOptions) { - this.options = tslib_1.__assign({}, this.options, options.requestOptions); - } - extraHeaders = (this.options.extraHeaders || []).slice(); - extraHeaders.push("Contact: " + this.generateContactHeader(this.expires)); - // this is UA.C.ALLOWED_METHODS, removed to get around circular dependency - extraHeaders.push("Allow: " + [ - "ACK", - "CANCEL", - "INVITE", - "MESSAGE", - "BYE", - "OPTIONS", - "INFO", - "NOTIFY", - "REFER" - ].toString()); - // Call-ID: All registrations from a UAC SHOULD use the same Call-ID - // header field value for registrations sent to a particular - // registrar. - // - // CSeq: The CSeq value guarantees proper ordering of REGISTER - // requests. A UA MUST increment the CSeq value by one for each - // REGISTER request with the same Call-ID. - // https://tools.ietf.org/html/rfc3261#section-10.2 - this.request.cseq++; - this.request.setHeader("cseq", this.request.cseq + " REGISTER"); - this.request.extraHeaders = extraHeaders; - this.waitingToggle(true); - outgoingRegisterRequest = this.userAgent.userAgentCore.register(this.request, { - onAccept: function (response) { - var expires; - // FIXME: This does NOT appear to be to spec and should be removed. - // I haven't found anywhere that an Expires header may be used in a response. - if (response.message.hasHeader("expires")) { - expires = Number(response.message.getHeader("expires")); - } - // 8. The registrar returns a 200 (OK) response. The response MUST - // contain Contact header field values enumerating all current - // bindings. Each Contact value MUST feature an "expires" - // parameter indicating its expiration interval chosen by the - // registrar. The response SHOULD include a Date header field. - // https://tools.ietf.org/html/rfc3261#section-10.3 - _this._contacts = response.message.getHeaders("contact"); - var contacts = _this._contacts.length; - if (!contacts) { - _this.logger.error("No Contact header in response to REGISTER, dropping response."); - _this.unregistered(); - return; - } - // The 200 (OK) response from the registrar contains a list of Contact - // fields enumerating all current bindings. The UA compares each - // contact address to see if it created the contact address, using - // comparison rules in Section 19.1.4. If so, it updates the expiration - // time interval according to the expires parameter or, if absent, the - // Expires field value. The UA then issues a REGISTER request for each - // of its bindings before the expiration interval has elapsed. - // https://tools.ietf.org/html/rfc3261#section-10.2.4 - var contact; - while (contacts--) { - contact = response.message.parseHeader("contact", contacts); - if (contact.uri.user === _this.userAgent.contact.uri.user) { - expires = contact.getParam("expires"); - break; - } - else { - contact = undefined; - } - } - // There must be a matching contact. - if (contact === undefined) { - _this.logger.error("No Contact header pointing to us, dropping response"); - _this.unregistered(); - _this.waitingToggle(false); - return; - } - // The contact must have an expires. - if (expires === undefined) { - _this.logger.error("Contact pointing to us is missing expires parameter, dropping response"); - _this.unregistered(); - _this.waitingToggle(false); - return; - } - // Save gruu values - if (contact.hasParam("temp-gruu")) { - _this.userAgent.contact.tempGruu = core_1.Grammar.URIParse(contact.getParam("temp-gruu").replace(/"/g, "")); - } - if (contact.hasParam("pub-gruu")) { - _this.userAgent.contact.pubGruu = core_1.Grammar.URIParse(contact.getParam("pub-gruu").replace(/"/g, "")); - } - _this.registered(expires); - _this.waitingToggle(false); - }, - onProgress: function (response) { - return; - }, - onRedirect: function (response) { - _this.logger.error("Redirect received. Not supported."); - _this.unregistered(); - _this.waitingToggle(false); - }, - onReject: function (response) { - if (response.message.statusCode === 423) { - // If a UA receives a 423 (Interval Too Brief) response, it MAY retry - // the registration after making the expiration interval of all contact - // addresses in the REGISTER request equal to or greater than the - // expiration interval within the Min-Expires header field of the 423 - // (Interval Too Brief) response. - // https://tools.ietf.org/html/rfc3261#section-10.2.8 - // - // The registrar MAY choose an expiration less than the requested - // expiration interval. If and only if the requested expiration - // interval is greater than zero AND smaller than one hour AND - // less than a registrar-configured minimum, the registrar MAY - // reject the registration with a response of 423 (Interval Too - // Brief). This response MUST contain a Min-Expires header field - // that states the minimum expiration interval the registrar is - // willing to honor. It then skips the remaining steps. - // https://tools.ietf.org/html/rfc3261#section-10.3 - if (!response.message.hasHeader("min-expires")) { - // This response MUST contain a Min-Expires header field - _this.logger.error("423 response received for REGISTER without Min-Expires"); - _this.unregistered(); - _this.waitingToggle(false); - return; - } - // Increase our registration interval to the suggested minimum - _this.expires = Number(response.message.getHeader("min-expires")); - // Attempt the registration again immediately - _this.waitingToggle(false); - _this.register(); - return; - } - _this.logger.warn("Failed to register, status code " + response.message.statusCode); - _this.unregistered(); - _this.waitingToggle(false); - }, - onTrying: function (response) { - return; - } - }); - return [2 /*return*/, Promise.resolve(outgoingRegisterRequest)]; - }); - }); - }; - /** - * Sends the REGISTER request with expires equal to zero. - */ - Registerer.prototype.unregister = function (options) { - if (options === void 0) { options = {}; } - return tslib_1.__awaiter(this, void 0, void 0, function () { - var error, extraHeaders, outgoingRegisterRequest; - var _this = this; - return tslib_1.__generator(this, function (_a) { - // UAs MUST NOT send a new registration (that is, containing new Contact - // header field values, as opposed to a retransmission) until they have - // received a final response from the registrar for the previous one or - // the previous REGISTER request has timed out. - // https://tools.ietf.org/html/rfc3261#section-10.2 - if (this.waiting) { - error = new Error("REGISTER request already in progress, waiting for final response"); - return [2 /*return*/, Promise.reject(error)]; - } - if (this._state !== registerer_state_1.RegistererState.Registered && !options.all) { - this.logger.warn("Not currently registered, but sending an unregister anyway."); - } - extraHeaders = (options.requestOptions && options.requestOptions.extraHeaders || []).slice(); - this.request.extraHeaders = extraHeaders; - // Registrations are soft state and expire unless refreshed, but can - // also be explicitly removed. A client can attempt to influence the - // expiration interval selected by the registrar as described in Section - // 10.2.1. A UA requests the immediate removal of a binding by - // specifying an expiration interval of "0" for that contact address in - // a REGISTER request. UAs SHOULD support this mechanism so that - // bindings can be removed before their expiration interval has passed. - // - // The REGISTER-specific Contact header field value of "*" applies to - // all registrations, but it MUST NOT be used unless the Expires header - // field is present with a value of "0". - // https://tools.ietf.org/html/rfc3261#section-10.2.2 - if (options.all) { - extraHeaders.push("Contact: *"); - extraHeaders.push("Expires: 0"); - } - else { - extraHeaders.push("Contact: " + this.generateContactHeader(0)); - } - // Call-ID: All registrations from a UAC SHOULD use the same Call-ID - // header field value for registrations sent to a particular - // registrar. - // - // CSeq: The CSeq value guarantees proper ordering of REGISTER - // requests. A UA MUST increment the CSeq value by one for each - // REGISTER request with the same Call-ID. - // https://tools.ietf.org/html/rfc3261#section-10.2 - this.request.cseq++; - this.request.setHeader("cseq", this.request.cseq + " REGISTER"); - // Pre-emptively clear the registration timer to avoid a race condition where - // this timer fires while waiting for a final response to the unsubscribe. - if (this.registrationTimer !== undefined) { - clearTimeout(this.registrationTimer); - this.registrationTimer = undefined; - } - this.waitingToggle(true); - outgoingRegisterRequest = this.userAgent.userAgentCore.register(this.request, { - onAccept: function (response) { - _this._contacts = response.message.getHeaders("contact"); // Update contacts - _this.unregistered(); - if (options.requestDelegate && options.requestDelegate.onAccept) { - options.requestDelegate.onAccept(response); - } - _this.waitingToggle(false); - }, - onProgress: function (response) { - if (options.requestDelegate && options.requestDelegate.onProgress) { - options.requestDelegate.onProgress(response); - } - }, - onRedirect: function (response) { - _this.logger.error("Unregister redirected. Not currently supported."); - _this.unregistered(); - if (options.requestDelegate && options.requestDelegate.onRedirect) { - options.requestDelegate.onRedirect(response); - } - _this.waitingToggle(false); - }, - onReject: function (response) { - _this.waitingToggle(false); - _this.logger.error("Unregister rejected with status code " + response.message.statusCode); - _this.unregistered(); - if (options.requestDelegate && options.requestDelegate.onReject) { - options.requestDelegate.onReject(response); - } - _this.waitingToggle(false); - }, - onTrying: function (response) { - if (options.requestDelegate && options.requestDelegate.onTrying) { - options.requestDelegate.onTrying(response); - } - } - }); - return [2 /*return*/, Promise.resolve(outgoingRegisterRequest)]; - }); - }); - }; - /** @internal */ - Registerer.prototype.clearTimers = function () { - if (this.registrationTimer !== undefined) { - clearTimeout(this.registrationTimer); - this.registrationTimer = undefined; - } - if (this.registrationExpiredTimer !== undefined) { - clearTimeout(this.registrationExpiredTimer); - this.registrationExpiredTimer = undefined; - } - }; - /** - * Helper Function to generate Contact Header - * @internal - */ - Registerer.prototype.generateContactHeader = function (expires) { - if (expires === void 0) { expires = 0; } - var contact = this.contact; - if (this.options.regId && this.options.instanceId) { - contact += ";reg-id=" + this.options.regId; - contact += ';+sip.instance=""'; - } - if (this.options.extraContactHeaderParams) { - this.options.extraContactHeaderParams.forEach(function (header) { - contact += ";" + header; - }); - } - contact += ";expires=" + expires; - return contact; - }; - /** @internal */ - Registerer.prototype.onTransportDisconnected = function () { - this.unregistered(); - }; - /** @internal */ - Registerer.prototype.registered = function (expires) { - var _this = this; - this.clearTimers(); - // Re-Register before the expiration interval has elapsed. - // For that, decrease the expires value. ie: 3 seconds - this.registrationTimer = setTimeout(function () { - _this.registrationTimer = undefined; - _this.register(); - }, (expires * 1000) - 3000); - // We are unregistered if the registration expires. - this.registrationExpiredTimer = setTimeout(function () { - _this.logger.warn("Registration expired"); - _this.unregistered(); - }, expires * 1000); - if (this._state !== registerer_state_1.RegistererState.Registered) { - this.stateTransition(registerer_state_1.RegistererState.Registered); - } - }; - /** @internal */ - Registerer.prototype.unregistered = function () { - this.clearTimers(); - if (this._state !== registerer_state_1.RegistererState.Unregistered) { - this.stateTransition(registerer_state_1.RegistererState.Unregistered); - } - }; - /** - * Transition registration state. - * @internal - */ - Registerer.prototype.stateTransition = function (newState) { - var _this = this; - var invalidTransition = function () { - throw new Error("Invalid state transition from " + _this._state + " to " + newState); - }; - // Validate transition - switch (this._state) { - case registerer_state_1.RegistererState.Initial: - if (newState !== registerer_state_1.RegistererState.Registered && - newState !== registerer_state_1.RegistererState.Unregistered) { - invalidTransition(); - } - break; - case registerer_state_1.RegistererState.Registered: - if (newState !== registerer_state_1.RegistererState.Unregistered) { - invalidTransition(); - } - break; - case registerer_state_1.RegistererState.Unregistered: - if (newState !== registerer_state_1.RegistererState.Registered) { - invalidTransition(); - } - break; - default: - throw new Error("Unrecognized state."); - } - // Transition - this._state = newState; - this.logger.log("Registration transitioned to state " + this._state); - this._stateEventEmitter.emit("event", this._state); - }; - Object.defineProperty(Registerer.prototype, "waiting", { - /** True if waiting for final response to a REGISTER request. */ - get: function () { - return this._waiting; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Registerer.prototype, "waitingChange", { - /** Emits when the registerer toggles waiting. */ - get: function () { - return emitter_1.makeEmitter(this._waitingEventEmitter); - }, - enumerable: true, - configurable: true - }); - /** - * Toggle waiting. - * @internal - */ - Registerer.prototype.waitingToggle = function (waiting) { - if (this._waiting === waiting) { - throw new Error("Invalid waiting transition from " + this._waiting + " to " + waiting); - } - this._waiting = waiting; - this.logger.log("Waiting toggled to " + this._waiting); - this._waitingEventEmitter.emit("event", this._waiting); - }; - return Registerer; -}()); -exports.Registerer = Registerer; - - -/***/ }), -/* 118 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var core_1 = __webpack_require__(2); -var allowed_methods_1 = __webpack_require__(58); -var Utils_1 = __webpack_require__(83); -var notification_1 = __webpack_require__(98); -var subscription_1 = __webpack_require__(119); -var subscription_state_1 = __webpack_require__(120); -/** - * A subscriber establishes a {@link Subscription} (outgoing SUBSCRIBE). - * - * @remarks - * This is (more or less) an implementation of a "subscriber" as - * defined in RFC 6665 "SIP-Specific Event Notifications". - * https://tools.ietf.org/html/rfc6665 - * - * @example - * ```ts - * // Create a new subscriber. - * const targetURI = new URI("sip", "alice", "example.com"); - * const eventType = "example-name"; // https://www.iana.org/assignments/sip-events/sip-events.xhtml - * const subscriber = new Subscriber(userAgent, targetURI, eventType); - * - * // Add delegate to handle event notifications. - * subscriber.delegate = { - * onNotify: (notification: Notification) => { - * // handle notification here - * } - * }; - * - * // Monitor subscription state changes. - * subscriber.stateChange.on((newState: SubscriptionState) => { - * if (newState === SubscriptionState.Terminated) { - * // handle state change here - * } - * }); - * - * // Attempt to establish the subscription - * subscriber.subscribe(); - * - * // Sometime later when done with subscription - * subscriber.unsubscribe(); - * ``` - * - * @public - */ -var Subscriber = /** @class */ (function (_super) { - tslib_1.__extends(Subscriber, _super); - /** - * Constructor. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @param targetURI - The request URI identifying the subscribed event. - * @param eventType - The event type identifying the subscribed event. - * @param options - Options bucket. See {@link SubscriberOptions} for details. - */ - function Subscriber(userAgent, targetURI, eventType, options) { - if (options === void 0) { options = {}; } - var _this = _super.call(this, userAgent, options) || this; - _this.body = undefined; - _this.logger = userAgent.getLogger("sip.subscription"); - if (options.body) { - _this.body = { - body: options.body, - contentType: options.contentType ? options.contentType : "application/sdp" - }; - } - _this.userAgent = userAgent; - _this.targetURI = targetURI; - // Subscription event - _this.event = eventType; - // Subscription expires - if (options.expires === undefined) { - _this.expires = 3600; - } - else if (typeof options.expires !== "number") { // pre-typescript type guard - _this.logger.warn("Option \"expires\" must be a number. Using default of 3600."); - _this.expires = 3600; - } - else { - _this.expires = options.expires; - } - // Subscription extra headers - _this.extraHeaders = (options.extraHeaders || []).slice(); - // Subscription context. - _this.context = _this.initContext(); - _this.request = _this.context.message; - // Add to UA's collection - _this.id = _this.request.callId + _this.request.from.parameters.tag + _this.event; - _this.userAgent.subscriptions[_this.id] = _this; - return _this; - } - /** - * Destructor. - * @internal - */ - Subscriber.prototype.dispose = function () { - if (this.disposed) { - return; - } - _super.prototype.dispose.call(this); - if (this.retryAfterTimer) { - clearTimeout(this.retryAfterTimer); - this.retryAfterTimer = undefined; - } - this.context.dispose(); - // Remove from userAgent's collection - delete this.userAgent.subscriptions[this.id]; - }; - /** - * Subscribe to event notifications. - * - * @remarks - * Send an initial SUBSCRIBE request if no subscription as been established. - * Sends a re-SUBSCRIBE request if the subscription is "active". - */ - Subscriber.prototype.subscribe = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - switch (this.context.state) { - case core_1.SubscriptionState.Initial: - // we can end up here when retrying so only state transition if in SubscriptionState.Initial state - if (this.state === subscription_state_1.SubscriptionState.Initial) { - this.stateTransition(subscription_state_1.SubscriptionState.NotifyWait); - } - this.context.subscribe().then(function (result) { - if (result.success) { - if (result.success.subscription) { - _this.dialog = result.success.subscription; - _this.dialog.delegate = { - onNotify: function (request) { return _this.onNotify(request); }, - onRefresh: function (request) { return _this.onRefresh(request); }, - onTerminated: function () { - _this.dispose(); - _this.onTerminated(); - } - }; - } - _this.onNotify(result.success.request); - } - else if (result.failure) { - _this.onFailed(result.failure.response); - } - }); - break; - case core_1.SubscriptionState.NotifyWait: - break; - case core_1.SubscriptionState.Pending: - break; - case core_1.SubscriptionState.Active: - if (this.dialog) { - var request = this.dialog.refresh(); - request.delegate = { - onAccept: (function (response) { return _this.onAccepted(response); }), - onRedirect: (function (response) { return _this.onFailed(response); }), - onReject: (function (response) { return _this.onFailed(response); }), - }; - } - break; - case core_1.SubscriptionState.Terminated: - break; - default: - break; - } - return Promise.resolve(); - }; - /** - * Unsubscribe. - * @internal - */ - Subscriber.prototype.unsubscribe = function (options) { - if (options === void 0) { options = {}; } - if (this.disposed) { - return Promise.resolve(); - } - switch (this.context.state) { - case core_1.SubscriptionState.Initial: - break; - case core_1.SubscriptionState.NotifyWait: - break; - case core_1.SubscriptionState.Pending: - if (this.dialog) { - this.dialog.unsubscribe(); - // responses intentionally ignored - } - break; - case core_1.SubscriptionState.Active: - if (this.dialog) { - this.dialog.unsubscribe(); - // responses intentionally ignored - } - break; - case core_1.SubscriptionState.Terminated: - break; - default: - break; - } - this.dispose(); - this.onTerminated(); - return Promise.resolve(); - }; - /** - * Alias for `unsubscribe`. - * @deprecated Use `unsubscribe` instead. - * @internal - */ - Subscriber.prototype.close = function () { - return this.unsubscribe(); - }; - /** - * Sends a re-SUBSCRIBE request if the subscription is "active". - * @deprecated Use `subscribe` instead. - * @internal - */ - Subscriber.prototype.refresh = function () { - if (this.context.state === core_1.SubscriptionState.Active) { - return this.subscribe(); - } - return Promise.resolve(); - }; - /** @internal */ - Subscriber.prototype.on = function (name, callback) { - return _super.prototype.on.call(this, name, callback); - }; - /** @internal */ - Subscriber.prototype.emit = function (event) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - return _super.prototype.emit.apply(this, [event].concat(args)); - }; - /** @internal */ - Subscriber.prototype.onAccepted = function (response) { - var statusCode = response.message.statusCode ? response.message.statusCode : 0; - var cause = Utils_1.Utils.getReasonPhrase(statusCode); - this.emit("accepted", response.message, cause); - }; - /** @internal */ - Subscriber.prototype.onFailed = function (response) { - this.close(); - if (response) { - var statusCode = response.message.statusCode ? response.message.statusCode : 0; - var cause = Utils_1.Utils.getReasonPhrase(statusCode); - this.emit("failed", response.message, cause); - this.emit("rejected", response.message, cause); - } - }; - /** @internal */ - Subscriber.prototype.onNotify = function (request) { - var _this = this; - // DEPRECATED BEGIN - // request.accept(); // Send 200 response. - this.emit("notify", { request: request.message }); - // DEPRECATED END - // If we've set state to done, no further processing should take place - // and we are only interested in cleaning up after the appropriate NOTIFY. - if (this.disposed) { - request.accept(); - return; - } - // State transition if needed. - if (this.state !== subscription_state_1.SubscriptionState.Subscribed) { - this.stateTransition(subscription_state_1.SubscriptionState.Subscribed); - } - // Delegate notification. - if (this.delegate && this.delegate.onNotify) { - var notification = new notification_1.Notification(request); - this.delegate.onNotify(notification); - } - else { - request.accept(); - } - // If the "Subscription-State" value is SubscriptionState.Terminated, the subscriber - // MUST consider the subscription terminated. The "expires" parameter - // has no semantics for SubscriptionState.Terminated -- notifiers SHOULD NOT include an - // "expires" parameter on a "Subscription-State" header field with a - // value of SubscriptionState.Terminated, and subscribers MUST ignore any such - // parameter, if present. If a reason code is present, the client - // should behave as described below. If no reason code or an unknown - // reason code is present, the client MAY attempt to re-subscribe at any - // time (unless a "retry-after" parameter is present, in which case the - // client SHOULD NOT attempt re-subscription until after the number of - // seconds specified by the "retry-after" parameter). The reason codes - // defined by this document are: - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - var subscriptionState = request.message.parseHeader("Subscription-State"); - if (subscriptionState && subscriptionState.state) { - switch (subscriptionState.state) { - case "terminated": - if (subscriptionState.reason) { - this.logger.log("Terminated subscription with reason " + subscriptionState.reason); - switch (subscriptionState.reason) { - case "deactivated": - case "timeout": - this.initContext(); - this.subscribe(); - return; - case "probation": - case "giveup": - this.initContext(); - if (subscriptionState.params && subscriptionState.params["retry-after"]) { - this.retryAfterTimer = setTimeout(function () { return _this.subscribe(); }, subscriptionState.params["retry-after"]); - } - else { - this.subscribe(); - } - return; - case "rejected": - case "noresource": - case "invariant": - break; - } - } - this.close(); - break; - default: - break; - } - } - }; - /** @internal */ - Subscriber.prototype.onRefresh = function (request) { - var _this = this; - request.delegate = { - onAccept: function (response) { return _this.onAccepted(response); } - }; - }; - /** @internal */ - Subscriber.prototype.onTerminated = function () { - this.emit("terminated"); - }; - Subscriber.prototype.initContext = function () { - var _this = this; - var options = { - extraHeaders: this.extraHeaders, - body: this.body ? Utils_1.Utils.fromBodyObj(this.body) : undefined - }; - this.context = new SubscribeClientContext(this.userAgent.userAgentCore, this.targetURI, this.event, this.expires, options); - this.context.delegate = { - onAccept: (function (response) { return _this.onAccepted(response); }) - }; - return this.context; - }; - return Subscriber; -}(subscription_1.Subscription)); -exports.Subscriber = Subscriber; -// tslint:disable-next-line:max-classes-per-file -var SubscribeClientContext = /** @class */ (function () { - function SubscribeClientContext(core, target, event, expires, options, delegate) { - this.core = core; - this.target = target; - this.event = event; - this.expires = expires; - this.subscribed = false; - this.logger = core.loggerFactory.getLogger("sip.subscription"); - this.delegate = delegate; - var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); - var extraHeaders = (options && options.extraHeaders || []).slice(); - extraHeaders.push(allowHeader); - extraHeaders.push("Event: " + this.event); - extraHeaders.push("Expires: " + this.expires); - extraHeaders.push("Contact: " + this.core.configuration.contact.toString()); - var body = options && options.body; - this.message = core.makeOutgoingRequestMessage(core_1.C.SUBSCRIBE, this.target, this.core.configuration.aor, this.target, {}, extraHeaders, body); - } - /** Destructor. */ - SubscribeClientContext.prototype.dispose = function () { - if (this.subscription) { - this.subscription.dispose(); - } - if (this.request) { - this.request.waitNotifyStop(); - this.request.dispose(); - } - }; - Object.defineProperty(SubscribeClientContext.prototype, "state", { - /** Subscription state. */ - get: function () { - if (this.subscription) { - return this.subscription.subscriptionState; - } - else if (this.subscribed) { - return core_1.SubscriptionState.NotifyWait; - } - else { - return core_1.SubscriptionState.Initial; - } - }, - enumerable: true, - configurable: true - }); - /** - * Establish subscription. - * @param options Options bucket. - */ - SubscribeClientContext.prototype.subscribe = function () { - var _this = this; - if (this.subscribed) { - return Promise.reject(new Error("Not in initial state. Did you call subscribe more than once?")); - } - this.subscribed = true; - return new Promise(function (resolve, reject) { - if (!_this.message) { - throw new Error("Message undefined."); - } - _this.request = _this.core.subscribe(_this.message, { - // This SUBSCRIBE request will be confirmed with a final response. - // 200-class responses indicate that the subscription has been accepted - // and that a NOTIFY request will be sent immediately. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - onAccept: function (response) { - if (_this.delegate && _this.delegate.onAccept) { - _this.delegate.onAccept(response); - } - }, - // Due to the potential for out-of-order messages, packet loss, and - // forking, the subscriber MUST be prepared to receive NOTIFY requests - // before the SUBSCRIBE transaction has completed. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.4 - onNotify: function (requestWithSubscription) { - _this.subscription = requestWithSubscription.subscription; - if (_this.subscription) { - _this.subscription.autoRefresh = true; - } - resolve({ success: requestWithSubscription }); - }, - // If this Timer N expires prior to the receipt of a NOTIFY request, - // the subscriber considers the subscription failed, and cleans up - // any state associated with the subscription attempt. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.4 - onNotifyTimeout: function () { - resolve({ failure: {} }); - }, - // This SUBSCRIBE request will be confirmed with a final response. - // Non-200-class final responses indicate that no subscription or new - // dialog usage has been created, and no subsequent NOTIFY request will - // be sent. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - onRedirect: function (response) { - resolve({ failure: { response: response } }); - }, - // This SUBSCRIBE request will be confirmed with a final response. - // Non-200-class final responses indicate that no subscription or new - // dialog usage has been created, and no subsequent NOTIFY request will - // be sent. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - onReject: function (response) { - resolve({ failure: { response: response } }); - } - }); - }); - }; - return SubscribeClientContext; -}()); - - -/***/ }), -/* 119 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var events_1 = __webpack_require__(30); -var emitter_1 = __webpack_require__(96); -var subscription_state_1 = __webpack_require__(120); -/** - * A subscription provides asynchronous {@link Notification} of events. - * - * @remarks - * See {@link Subscriber} for details on establishing a subscription. - * - * @public - */ -var Subscription = /** @class */ (function (_super) { - tslib_1.__extends(Subscription, _super); - /** - * Constructor. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @internal - */ - function Subscription(userAgent, options) { - if (options === void 0) { options = {}; } - var _this = _super.call(this) || this; - _this._disposed = false; - _this._state = subscription_state_1.SubscriptionState.Initial; - _this._stateEventEmitter = new events_1.EventEmitter(); - _this._logger = userAgent.getLogger("sip.subscription"); - _this.userAgent = userAgent; - _this.delegate = options.delegate; - return _this; - } - /** - * Destructor. - * @internal - */ - Subscription.prototype.dispose = function () { - if (this._disposed) { - return; - } - this._disposed = true; - this.stateTransition(subscription_state_1.SubscriptionState.Terminated); - this._stateEventEmitter.removeAllListeners(); - }; - Object.defineProperty(Subscription.prototype, "disposed", { - /** - * True if disposed. - * @internal - */ - get: function () { - return this._disposed; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Subscription.prototype, "state", { - /** - * Subscription state. See {@link SubscriptionState} for details. - */ - get: function () { - return this._state; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Subscription.prototype, "stateChange", { - /** - * Emits when the subscription `state` property changes. - */ - get: function () { - return emitter_1.makeEmitter(this._stateEventEmitter); - }, - enumerable: true, - configurable: true - }); - /** @internal */ - Subscription.prototype.stateTransition = function (newState) { - var _this = this; - var invalidTransition = function () { - throw new Error("Invalid state transition from " + _this._state + " to " + newState); - }; - // Validate transition - switch (this._state) { - case subscription_state_1.SubscriptionState.Initial: - if (newState !== subscription_state_1.SubscriptionState.NotifyWait && newState !== subscription_state_1.SubscriptionState.Terminated) { - invalidTransition(); - } - break; - case subscription_state_1.SubscriptionState.NotifyWait: - if (newState !== subscription_state_1.SubscriptionState.Subscribed && newState !== subscription_state_1.SubscriptionState.Terminated) { - invalidTransition(); - } - break; - case subscription_state_1.SubscriptionState.Subscribed: - if (newState !== subscription_state_1.SubscriptionState.Terminated) { - invalidTransition(); - } - break; - case subscription_state_1.SubscriptionState.Terminated: - invalidTransition(); - break; - default: - throw new Error("Unrecognized state."); - } - // Guard against duplicate transition - if (this._state === newState) { - return; - } - // Transition - this._state = newState; - this._logger.log("Subscription " + (this.dialog ? this.dialog.id : undefined) + " transitioned to " + this._state); - this._stateEventEmitter.emit("event", this._state); - }; - return Subscription; -}(events_1.EventEmitter)); -exports.Subscription = Subscription; - - -/***/ }), -/* 120 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * {@link Subscription} state. - * @remarks - * Valid state transitions: - * ``` - * 1. "initial" --> "notify-wait" --> "subscribed" --> "terminated" - * 2. "initial" --> "notify-wait" --> "terminated" - * 3. "initial" --> "terminated" - * ``` - * @public - */ -var SubscriptionState; -(function (SubscriptionState) { - SubscriptionState["Initial"] = "Initial"; - SubscriptionState["NotifyWait"] = "NotifyWait"; - SubscriptionState["Subscribed"] = "Subscribed"; - SubscriptionState["Terminated"] = "Terminated"; -})(SubscriptionState = exports.SubscriptionState || (exports.SubscriptionState = {})); - - -/***/ }), -/* 121 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var events_1 = __webpack_require__(30); -var core_1 = __webpack_require__(2); -var utils_1 = __webpack_require__(16); -var Enums_1 = __webpack_require__(82); -var Parser_1 = __webpack_require__(85); -var version_1 = __webpack_require__(81); -var SessionDescriptionHandler_1 = __webpack_require__(94); -var Transport_1 = __webpack_require__(103); -var invitation_1 = __webpack_require__(108); -var inviter_1 = __webpack_require__(111); -var message_1 = __webpack_require__(112); -var notification_1 = __webpack_require__(98); -var session_state_1 = __webpack_require__(100); -var user_agent_options_1 = __webpack_require__(109); -var user_agent_state_1 = __webpack_require__(122); -/** - * A user agent sends and receives requests using a `Transport`. - * - * @remarks - * A user agent (UA) is associated with a user via the user's SIP address of record (AOR) - * and acts on behalf of that user to send and receive SIP requests. The user agent can - * register to receive incoming requests, as well as create and send outbound messages. - * The user agent also maintains the Transport over which its signaling travels. - * - * @public - */ -var UserAgent = /** @class */ (function () { - /** - * Constructs a new instance of the `UserAgent` class. - * @param options - Options bucket. See {@link UserAgentOptions} for details. - */ - function UserAgent(options) { - var _this = this; - if (options === void 0) { options = {}; } - /** @internal */ - this.data = {}; - /** @internal */ - this.applicants = {}; - /** @internal */ - this.publishers = {}; - /** @internal */ - this.registerers = {}; - /** @internal */ - this.sessions = {}; - /** @internal */ - this.subscriptions = {}; - /** @internal */ - this.status = Enums_1.UAStatus.STATUS_INIT; - /** LoggerFactory. */ - this.loggerFactory = new core_1.LoggerFactory(); - this._state = user_agent_state_1.UserAgentState.Initial; - this._stateEventEmitter = new events_1.EventEmitter(); - /** Unload listener. */ - this.unloadListener = (function () { _this.stop(); }); - // initialize delegate - this.delegate = options.delegate; - // initialize configuration - this.options = tslib_1.__assign({}, UserAgent.defaultOptions, { sipjsId: utils_1.createRandomToken(5) }, { uri: new core_1.URI("sip", "anonymous." + utils_1.createRandomToken(6), "anonymous.invalid") }, { viaHost: utils_1.createRandomToken(12) + ".invalid" }, options); - // viaHost is hack - if (this.options.hackIpInContact) { - if (typeof this.options.hackIpInContact === "boolean" && this.options.hackIpInContact) { - var from = 1; - var to = 254; - var octet = Math.floor(Math.random() * (to - from + 1) + from); - // random Test-Net IP (http://tools.ietf.org/html/rfc5735) - this.options.viaHost = "192.0.2." + octet; - } - else if (this.options.hackIpInContact) { - this.options.viaHost = this.options.hackIpInContact; - } - } - // initialize logger & logger factory - this.logger = this.loggerFactory.getLogger("sip.UserAgent"); - this.loggerFactory.builtinEnabled = this.options.logBuiltinEnabled; - this.loggerFactory.connector = this.options.logConnector; - switch (this.options.logLevel) { - case "error": - this.loggerFactory.level = core_1.Levels.error; - break; - case "warn": - this.loggerFactory.level = core_1.Levels.warn; - break; - case "log": - this.loggerFactory.level = core_1.Levels.log; - break; - case "debug": - this.loggerFactory.level = core_1.Levels.debug; - break; - default: - break; - } - if (this.options.logConfiguration) { - this.logger.log("Configuration:"); - for (var _i = 0, _a = Object.entries(this.options); _i < _a.length; _i++) { - var _b = _a[_i], key = _b[0], value = _b[1]; - switch (key) { - case "uri": - case "sessionDescriptionHandlerFactory": - this.logger.log("· " + key + ": " + value); - break; - case "authorizationPassword": - this.logger.log("· " + key + ": " + "NOT SHOWN"); - break; - case "transportConstructor": - this.logger.log("· " + key + ": " + value.name); - break; - default: - this.logger.log("· " + key + ": " + JSON.stringify(value)); - } - } - } - // initialize transport - this.transport = new this.options.transportConstructor(this.getLogger("sip.transport"), this.options.transportOptions); - // initialize contact - this.contact = this.initContact(); - // initialize core - this.userAgentCore = this.initCore(); - if (this.options.autoStart) { - this.start(); - } - } - /** - * Create a URI instance from a string. - * @param uri - The string to parse. - * - * @example - * ```ts - * const uri = UserAgent.makeURI("sip:edgar@example.com"); - * ``` - */ - UserAgent.makeURI = function (uri) { - return core_1.Grammar.URIParse(uri); - }; - Object.defineProperty(UserAgent.prototype, "configuration", { - /** - * User agent configuration. - */ - get: function () { - return this.options; - }, - enumerable: true, - configurable: true - }); - /** - * Connect user agent to network transport. - * @remarks - * Connect to the WS server if status = STATUS_INIT. - * Resume UA after being closed. - */ - UserAgent.prototype.start = function () { - this.logger.log("user requested startup..."); - if (this.status === Enums_1.UAStatus.STATUS_INIT) { - this.status = Enums_1.UAStatus.STATUS_STARTING; - this.setTransportListeners(); - return this.transport.connect(); - } - else if (this.status === Enums_1.UAStatus.STATUS_USER_CLOSED) { - this.logger.log("resuming"); - this.status = Enums_1.UAStatus.STATUS_READY; - return this.transport.connect(); - } - else if (this.status === Enums_1.UAStatus.STATUS_STARTING) { - this.logger.log("UA is in STARTING status, not opening new connection"); - } - else if (this.status === Enums_1.UAStatus.STATUS_READY) { - this.logger.log("UA is in READY status, not resuming"); - } - else { - this.logger.error("Connection is down. Auto-Recovery system is trying to connect"); - } - if (this.options.autoStop) { - // Google Chrome Packaged Apps don't allow 'unload' listeners: unload is not available in packaged apps - var googleChromePackagedApp = typeof chrome !== "undefined" && chrome.app && chrome.app.runtime ? true : false; - if (typeof window !== "undefined" && - typeof window.addEventListener === "function" && - !googleChromePackagedApp) { - window.addEventListener("unload", this.unloadListener); - } - } - return Promise.resolve(); - }; - /** - * Gracefully close. - * Gracefully disconnect from network transport. - * @remarks - * Unregisters and terminates active sessions/subscriptions. - */ - UserAgent.prototype.stop = function () { - return tslib_1.__awaiter(this, void 0, void 0, function () { - var _a, _b, _i, id, id, session, subscription, publisher, applicant, googleChromePackagedApp; - return tslib_1.__generator(this, function (_c) { - switch (_c.label) { - case 0: - this.logger.log("Stopping user agent " + this.configuration.uri + "..."); - if (this.status === Enums_1.UAStatus.STATUS_USER_CLOSED) { - this.logger.warn("UA already closed"); - } - _a = []; - for (_b in this.registerers) - _a.push(_b); - _i = 0; - _c.label = 1; - case 1: - if (!(_i < _a.length)) return [3 /*break*/, 4]; - id = _a[_i]; - if (!this.registerers[id]) return [3 /*break*/, 3]; - return [4 /*yield*/, this.registerers[id].dispose()]; - case 2: - _c.sent(); - _c.label = 3; - case 3: - _i++; - return [3 /*break*/, 1]; - case 4: - // End every Session - for (id in this.sessions) { - if (this.sessions[id]) { - this.logger.log("closing session " + id); - session = this.sessions[id]; - switch (session.state) { - case session_state_1.SessionState.Initial: - case session_state_1.SessionState.Establishing: - if (session instanceof invitation_1.Invitation) { - session.reject(); - } - if (session instanceof inviter_1.Inviter) { - session.cancel(); - } - break; - case session_state_1.SessionState.Established: - session.bye(); - break; - case session_state_1.SessionState.Terminating: - case session_state_1.SessionState.Terminated: - default: - break; - } - } - } - // Run unsubscribe on every Subscription - for (subscription in this.subscriptions) { - if (this.subscriptions[subscription]) { - this.logger.log("unsubscribe " + subscription); - this.subscriptions[subscription].unsubscribe(); - } - } - // Run close on every Publisher - for (publisher in this.publishers) { - if (this.publishers[publisher]) { - this.logger.log("unpublish " + publisher); - this.publishers[publisher].close(); - } - } - // Run close on every applicant - for (applicant in this.applicants) { - if (this.applicants[applicant]) { - this.applicants[applicant].close(); - } - } - this.status = Enums_1.UAStatus.STATUS_USER_CLOSED; - // Disconnect the transport and reset user agent core - this.transport.disconnect(); - this.userAgentCore.reset(); - if (this.options.autoStop) { - googleChromePackagedApp = typeof chrome !== "undefined" && chrome.app && chrome.app.runtime ? true : false; - if (typeof window !== "undefined" && - window.removeEventListener && - !googleChromePackagedApp) { - window.removeEventListener("unload", this.unloadListener); - } - } - return [2 /*return*/, Promise.resolve()]; - } - }); - }); - }; - /** @internal */ - UserAgent.prototype.findSession = function (request) { - return this.sessions[request.callId + request.fromTag] || - this.sessions[request.callId + request.toTag] || - undefined; - }; - /** @internal */ - UserAgent.prototype.getLogger = function (category, label) { - return this.loggerFactory.getLogger(category, label); - }; - /** @internal */ - UserAgent.prototype.getLoggerFactory = function () { - return this.loggerFactory; - }; - /** @internal */ - UserAgent.prototype.getSupportedResponseOptions = function () { - var optionTags = []; - if (this.contact.pubGruu || this.contact.tempGruu) { - optionTags.push("gruu"); - } - if (this.options.sipExtension100rel === user_agent_options_1.SIPExtension.Supported) { - optionTags.push("100rel"); - } - if (this.options.sipExtensionReplaces === user_agent_options_1.SIPExtension.Supported) { - optionTags.push("replaces"); - } - optionTags.push("outbound"); - optionTags = optionTags.concat(this.options.sipExtensionExtraSupported || []); - var allowUnregistered = this.options.hackAllowUnregisteredOptionTags || false; - var optionTagSet = {}; - optionTags = optionTags.filter(function (optionTag) { - var registered = user_agent_options_1.UserAgentRegisteredOptionTags[optionTag]; - var unique = !optionTagSet[optionTag]; - optionTagSet[optionTag] = true; - return (registered || allowUnregistered) && unique; - }); - return optionTags; - }; - /** @internal */ - UserAgent.prototype.makeInviter = function (targetURI, options) { - return new inviter_1.Inviter(this, targetURI, options); - }; - // ============================== - // Event Handlers - // ============================== - UserAgent.prototype.onTransportError = function () { - if (this.status === Enums_1.UAStatus.STATUS_USER_CLOSED) { - return; - } - this.status = Enums_1.UAStatus.STATUS_NOT_READY; - }; - /** - * Helper function. Sets transport listeners - */ - UserAgent.prototype.setTransportListeners = function () { - var _this = this; - this.transport.on("connected", function () { return _this.onTransportConnected(); }); - this.transport.on("message", function (message) { return _this.onTransportReceiveMsg(message); }); - this.transport.on("transportError", function () { return _this.onTransportError(); }); - }; - /** - * Transport connection event. - */ - UserAgent.prototype.onTransportConnected = function () { - // if (this.configuration.register) { - // // In an effor to maintain behavior from when we "initialized" an - // // authentication factory, this is in a Promise.then - // Promise.resolve().then(() => this.registerer.register()); - // } - }; - /** - * Handle SIP message received from the transport. - * @param messageString - The message. - */ - UserAgent.prototype.onTransportReceiveMsg = function (messageString) { - var _this = this; - var message = Parser_1.Parser.parseMessage(messageString, this.getLogger("sip.parser")); - if (!message) { - this.logger.warn("Failed to parse incoming message. Dropping."); - return; - } - if (this.status === Enums_1.UAStatus.STATUS_USER_CLOSED && message instanceof core_1.IncomingRequestMessage) { - this.logger.warn("Received " + message.method + " request in state USER_CLOSED. Dropping."); - return; - } - // A valid SIP request formulated by a UAC MUST, at a minimum, contain - // the following header fields: To, From, CSeq, Call-ID, Max-Forwards, - // and Via; all of these header fields are mandatory in all SIP - // requests. - // https://tools.ietf.org/html/rfc3261#section-8.1.1 - var hasMinimumHeaders = function () { - var mandatoryHeaders = ["from", "to", "call_id", "cseq", "via"]; - for (var _i = 0, mandatoryHeaders_1 = mandatoryHeaders; _i < mandatoryHeaders_1.length; _i++) { - var header = mandatoryHeaders_1[_i]; - if (!message.hasHeader(header)) { - _this.logger.warn("Missing mandatory header field : " + header + "."); - return false; - } - } - return true; - }; - // Request Checks - if (message instanceof core_1.IncomingRequestMessage) { - // This is port of SanityCheck.minimumHeaders(). - if (!hasMinimumHeaders()) { - this.logger.warn("Request missing mandatory header field. Dropping."); - return; - } - // FIXME: This is non-standard and should be a configruable behavior (desirable regardless). - // Custom SIP.js check to reject request from ourself (this instance of SIP.js). - // This is port of SanityCheck.rfc3261_16_3_4(). - if (!message.toTag && message.callId.substr(0, 5) === this.options.sipjsId) { - this.userAgentCore.replyStateless(message, { statusCode: 482 }); - return; - } - // FIXME: This should be Transport check before we get here (Section 18). - // Custom SIP.js check to reject requests if body length wrong. - // This is port of SanityCheck.rfc3261_18_3_request(). - var len = utils_1.str_utf8_length(message.body); - var contentLength = message.getHeader("content-length"); - if (contentLength && len < Number(contentLength)) { - this.userAgentCore.replyStateless(message, { statusCode: 400 }); - return; - } - } - // Reponse Checks - if (message instanceof core_1.IncomingResponseMessage) { - // This is port of SanityCheck.minimumHeaders(). - if (!hasMinimumHeaders()) { - this.logger.warn("Response missing mandatory header field. Dropping."); - return; - } - // Custom SIP.js check to drop responses if multiple Via headers. - // This is port of SanityCheck.rfc3261_8_1_3_3(). - if (message.getHeaders("via").length > 1) { - this.logger.warn("More than one Via header field present in the response. Dropping."); - return; - } - // FIXME: This should be Transport check before we get here (Section 18). - // Custom SIP.js check to drop responses if bad Via header. - // This is port of SanityCheck.rfc3261_18_1_2(). - if (message.via.host !== this.options.viaHost || message.via.port !== undefined) { - this.logger.warn("Via sent-by in the response does not match UA Via host value. Dropping."); - return; - } - // FIXME: This should be Transport check before we get here (Section 18). - // Custom SIP.js check to reject requests if body length wrong. - // This is port of SanityCheck.rfc3261_18_3_response(). - var len = utils_1.str_utf8_length(message.body); - var contentLength = message.getHeader("content-length"); - if (contentLength && len < Number(contentLength)) { - this.logger.warn("Message body length is lower than the value in Content-Length header field. Dropping."); - return; - } - } - // Handle Request - if (message instanceof core_1.IncomingRequestMessage) { - this.userAgentCore.receiveIncomingRequestFromTransport(message); - return; - } - // Handle Response - if (message instanceof core_1.IncomingResponseMessage) { - this.userAgentCore.receiveIncomingResponseFromTransport(message); - return; - } - throw new Error("Invalid message type."); - }; - UserAgent.prototype.initContact = function () { - var _this = this; - var contactName = utils_1.createRandomToken(8); // FIXME: should be configurable - var contactTransport = this.options.hackWssInTransport ? "wss" : "ws"; // FIXME: clearly broken for non ws transports - var contact = { - pubGruu: undefined, - tempGruu: undefined, - uri: new core_1.URI("sip", contactName, this.options.viaHost, undefined, { transport: contactTransport }), - toString: function (contactToStringOptions) { - if (contactToStringOptions === void 0) { contactToStringOptions = {}; } - var anonymous = contactToStringOptions.anonymous || false; - var outbound = contactToStringOptions.outbound || false; - var contactString = "<"; - if (anonymous) { - contactString += _this.contact.tempGruu || "sip:anonymous@anonymous.invalid;transport=" + contactTransport; - } - else { - contactString += _this.contact.pubGruu || _this.contact.uri; - } - if (outbound) { - contactString += ";ob"; - } - contactString += ">"; - return contactString; - } - }; - return contact; - }; - UserAgent.prototype.initCore = function () { - var _this = this; - // supported options - var supportedOptionTags = []; - supportedOptionTags.push("outbound"); // TODO: is this really supported? - if (this.options.sipExtension100rel === user_agent_options_1.SIPExtension.Supported) { - supportedOptionTags.push("100rel"); - } - if (this.options.sipExtensionReplaces === user_agent_options_1.SIPExtension.Supported) { - supportedOptionTags.push("replaces"); - } - if (this.options.sipExtensionExtraSupported) { - supportedOptionTags.push.apply(supportedOptionTags, this.options.sipExtensionExtraSupported); - } - if (!this.options.hackAllowUnregisteredOptionTags) { - supportedOptionTags = supportedOptionTags.filter(function (optionTag) { return user_agent_options_1.UserAgentRegisteredOptionTags[optionTag]; }); - } - supportedOptionTags = Array.from(new Set(supportedOptionTags)); // array of unique values - // FIXME: TODO: This was ported, but this is and was just plain broken. - var supportedOptionTagsResponse = supportedOptionTags.slice(); - if (this.contact.pubGruu || this.contact.tempGruu) { - supportedOptionTagsResponse.push("gruu"); - } - // core configuration - var userAgentCoreConfiguration = { - aor: this.options.uri, - contact: this.contact, - displayName: this.options.displayName, - loggerFactory: this.loggerFactory, - hackViaTcp: this.options.hackViaTcp, - routeSet: this.options.usePreloadedRoute && this.transport.server && this.transport.server.sipUri ? - [this.transport.server.sipUri] : - [], - supportedOptionTags: supportedOptionTags, - supportedOptionTagsResponse: supportedOptionTagsResponse, - sipjsId: this.options.sipjsId, - userAgentHeaderFieldValue: this.options.userAgentString, - viaForceRport: this.options.forceRport, - viaHost: this.options.viaHost, - authenticationFactory: function () { - var username = _this.options.authorizationUsername ? - _this.options.authorizationUsername : - _this.options.uri.user; // if authorization username not provided, use uri user as username - var password = _this.options.authorizationPassword ? - _this.options.authorizationPassword : - undefined; - return new core_1.DigestAuthentication(_this.getLoggerFactory(), username, password); - }, - transportAccessor: function () { return _this.transport; } - }; - var userAgentCoreDelegate = { - onInvite: function (incomingInviteRequest) { - var invitation = new invitation_1.Invitation(_this, incomingInviteRequest); - incomingInviteRequest.delegate = { - onCancel: function (cancel) { - invitation.onCancel(cancel); - }, - onTransportError: function (error) { - invitation.onTransportError(); - } - }; - // FIXME: Ported - 100 Trying send should be configurable. - // Only required if TU will not respond in 200ms. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - incomingInviteRequest.trying(); - // The Replaces header contains information used to match an existing - // SIP dialog (call-id, to-tag, and from-tag). Upon receiving an INVITE - // with a Replaces header, the User Agent (UA) attempts to match this - // information with a confirmed or early dialog. - // https://tools.ietf.org/html/rfc3891#section-3 - if (_this.options.sipExtensionReplaces !== user_agent_options_1.SIPExtension.Unsupported) { - var message = incomingInviteRequest.message; - var replaces = message.parseHeader("replaces"); - if (replaces) { - var callId = replaces.call_id; - if (typeof callId !== "string") { - throw new Error("Type of call id is not string"); - } - var toTag = replaces.replaces_to_tag; - if (typeof toTag !== "string") { - throw new Error("Type of to tag is not string"); - } - var fromTag = replaces.replaces_from_tag; - if (typeof fromTag !== "string") { - throw new Error("type of from tag is not string"); - } - var targetDialogId = callId + toTag + fromTag; - var targetDialog = _this.userAgentCore.dialogs.get(targetDialogId); - // If no match is found, the UAS rejects the INVITE and returns a 481 - // Call/Transaction Does Not Exist response. Likewise, if the Replaces - // header field matches a dialog which was not created with an INVITE, - // the UAS MUST reject the request with a 481 response. - // https://tools.ietf.org/html/rfc3891#section-3 - if (!targetDialog) { - invitation.reject({ statusCode: 481 }); - return; - } - // If the Replaces header field matches a confirmed dialog, it checks - // for the presence of the "early-only" flag in the Replaces header - // field. (This flag allows the UAC to prevent a potentially - // undesirable race condition described in Section 7.1.) If the flag is - // present, the UA rejects the request with a 486 Busy response. - // https://tools.ietf.org/html/rfc3891#section-3 - if (!targetDialog.early && replaces.early_only === true) { - invitation.reject({ statusCode: 486 }); - return; - } - // Provide a handle on the session being replaced. - var targetSession = _this.sessions[callId + fromTag] || _this.sessions[callId + toTag] || undefined; - if (!targetSession) { - throw new Error("Session does not exist."); - } - invitation.replacee = targetSession; - } - } - // A common scenario occurs when the callee is currently not willing or - // able to take additional calls at this end system. A 486 (Busy Here) - // SHOULD be returned in such a scenario. - // https://tools.ietf.org/html/rfc3261#section-13.3.1.3 - if (!_this.delegate || !_this.delegate.onInvite) { - invitation.reject({ statusCode: 486 }); - return; - } - // Delegate invitation handling. - if (!invitation.autoSendAnInitialProvisionalResponse) { - _this.delegate.onInvite(invitation); - } - else { - var onInvite_1 = _this.delegate.onInvite; - invitation.progress() - .then(function () { return onInvite_1(invitation); }); - } - }, - onMessage: function (incomingMessageRequest) { - if (_this.delegate && _this.delegate.onMessage) { - var message = new message_1.Message(incomingMessageRequest); - _this.delegate.onMessage(message); - } - else { - // Accept the MESSAGE request, but do nothing with it. - incomingMessageRequest.accept(); - } - }, - onNotify: function (incomingNotifyRequest) { - // NOTIFY requests are sent to inform subscribers of changes in state to - // which the subscriber has a subscription. Subscriptions are created - // using the SUBSCRIBE method. In legacy implementations, it is - // possible that other means of subscription creation have been used. - // However, this specification does not allow the creation of - // subscriptions except through SUBSCRIBE requests and (for backwards- - // compatibility) REFER requests [RFC3515]. - // https://tools.ietf.org/html/rfc6665#section-3.2 - if (_this.delegate && _this.delegate.onNotify) { - var notification = new notification_1.Notification(incomingNotifyRequest); - _this.delegate.onNotify(notification); - } - else { - // Per the above which sbsoletes https://tools.ietf.org/html/rfc3265, - // the use of out of dialog NOTIFY is obsolete, but... - if (_this.options.allowLegacyNotifications) { - incomingNotifyRequest.accept(); // Accept the NOTIFY request, but do nothing with it. - } - else { - incomingNotifyRequest.reject({ statusCode: 481 }); - } - } - }, - onRefer: function (incomingReferRequest) { - _this.logger.log("Received an out of dialog refer"); - if (!_this.options.allowOutOfDialogRefers) { - incomingReferRequest.reject({ statusCode: 405 }); - } - _this.logger.log("Allow out of dialog refers is enabled on the UA"); - // const referContext = new ReferServerContext(this, incomingReferRequest); - // if (this.listeners("outOfDialogReferRequested").length) { - // this.emit("outOfDialogReferRequested", referContext); - // } else { - // this.logger.log( - // "No outOfDialogReferRequest listeners, automatically accepting and following the out of dialog refer" - // ); - // referContext.accept({ followRefer: true }); - // } - // if (this.delegate && this.delegate.onRefer) { - // this.delegate.onRefer(incomingReferRequest); - // } - }, - onRegister: function (incomingRegisterRequest) { - // TOOD: this.delegate.onRegister(...) - if (_this.delegate && _this.delegate.onRegisterRequest) { - _this.delegate.onRegisterRequest(incomingRegisterRequest); - } - }, - onSubscribe: function (incomingSubscribeRequest) { - // TOOD: this.delegate.onSubscribe(...) - if (_this.delegate && _this.delegate.onSubscribeRequest) { - _this.delegate.onSubscribeRequest(incomingSubscribeRequest); - } - } - }; - return new core_1.UserAgentCore(userAgentCoreConfiguration, userAgentCoreDelegate); - }; - /** Default user agent options. */ - UserAgent.defaultOptions = { - allowLegacyNotifications: false, - allowOutOfDialogRefers: false, - authorizationPassword: "", - authorizationUsername: "", - autoStart: false, - autoStop: true, - delegate: {}, - displayName: "", - forceRport: false, - hackAllowUnregisteredOptionTags: false, - hackIpInContact: false, - hackViaTcp: false, - hackWssInTransport: false, - logBuiltinEnabled: true, - logConfiguration: true, - logConnector: function () { }, - logLevel: "log", - noAnswerTimeout: 60, - sessionDescriptionHandlerFactory: SessionDescriptionHandler_1.SessionDescriptionHandler.defaultFactory, - sessionDescriptionHandlerFactoryOptions: {}, - sipExtension100rel: user_agent_options_1.SIPExtension.Unsupported, - sipExtensionReplaces: user_agent_options_1.SIPExtension.Unsupported, - sipExtensionExtraSupported: [], - sipjsId: "", - transportConstructor: Transport_1.Transport, - transportOptions: {}, - uri: new core_1.URI("sip", "anonymous", "anonymous.invalid"), - usePreloadedRoute: false, - userAgentString: "SIP.js/" + version_1.LIBRARY_VERSION, - viaHost: "" - }; - return UserAgent; -}()); -exports.UserAgent = UserAgent; - - -/***/ }), -/* 122 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * {@link UserAgent} state. - * @remarks - * Valid state transitions: - * ``` - * 1. "initial" --> "starting" - * 2. "starting" --> "started" - * 3. "starting" --> "stopped" - * 4. "started" --> "stopping" - * 5. "started" --> "stopped" - * 6. "stopped" --> "starting" - * ``` - * @public - */ -var UserAgentState; -(function (UserAgentState) { - UserAgentState["Initial"] = "Initial"; - UserAgentState["Starting"] = "Starting"; - UserAgentState["Started"] = "Started"; - UserAgentState["Stopping"] = "Stopping"; - UserAgentState["Stopped"] = "Stopped"; -})(UserAgentState = exports.UserAgentState || (exports.UserAgentState = {})); - - -/***/ }) -/******/ ]); -}); \ No newline at end of file diff --git a/dist/sip-api.min.js b/dist/sip-api.min.js deleted file mode 100644 index 60c164620..000000000 --- a/dist/sip-api.min.js +++ /dev/null @@ -1 +0,0 @@ -!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.SIP=t():e.SIP=t()}(this,(function(){return function(e){var t={};function r(i){if(t[i])return t[i].exports;var n=t[i]={i:i,l:!1,exports:{}};return e[i].call(n.exports,n,n.exports,r),n.l=!0,n.exports}return r.m=e,r.c=t,r.d=function(e,t,i){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:i})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var i=Object.create(null);if(r.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var n in e)r.d(i,n,function(t){return e[t]}.bind(null,n));return i},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=113)}([function(e,t,r){"use strict";r.r(t),r.d(t,"__extends",(function(){return n})),r.d(t,"__assign",(function(){return s})),r.d(t,"__rest",(function(){return o})),r.d(t,"__decorate",(function(){return a})),r.d(t,"__param",(function(){return c})),r.d(t,"__metadata",(function(){return u})),r.d(t,"__awaiter",(function(){return d})),r.d(t,"__generator",(function(){return l})),r.d(t,"__exportStar",(function(){return p})),r.d(t,"__values",(function(){return h})),r.d(t,"__read",(function(){return g})),r.d(t,"__spread",(function(){return f})),r.d(t,"__spreadArrays",(function(){return v})),r.d(t,"__await",(function(){return m})),r.d(t,"__asyncGenerator",(function(){return S})),r.d(t,"__asyncDelegator",(function(){return y})),r.d(t,"__asyncValues",(function(){return T})),r.d(t,"__makeTemplateObject",(function(){return b})),r.d(t,"__importStar",(function(){return E})),r.d(t,"__importDefault",(function(){return _}));var i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};function n(e,t){function r(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var s=function(){return(s=Object.assign||function(e){for(var t,r=1,i=arguments.length;r=0;a--)(n=e[a])&&(o=(s<3?n(o):s>3?n(t,r,o):n(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o}function c(e,t){return function(r,i){t(r,i,e)}}function u(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function d(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){e.done?n(e.value):new r((function(t){t(e.value)})).then(o,a)}c((i=i.apply(e,t||[])).next())}))}function l(e,t){var r,i,n,s,o={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;o;)try{if(r=1,i&&(n=2&s[0]?i.return:s[0]?i.throw||((n=i.return)&&n.call(i),0):i.next)&&!(n=n.call(i,s[1])).done)return n;switch(i=0,n&&(s=[2&s[0],n.value]),s[0]){case 0:case 1:n=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,i=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!(n=(n=o.trys).length>0&&n[n.length-1])&&(6===s[0]||2===s[0])){o=0;continue}if(3===s[0]&&(!n||s[1]>n[0]&&s[1]=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}function g(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var i,n,s=r.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(i=s.next()).done;)o.push(i.value)}catch(e){n={error:e}}finally{try{i&&!i.done&&(r=s.return)&&r.call(s)}finally{if(n)throw n.error}}return o}function f(){for(var e=[],t=0;t1||a(e,t)}))})}function a(e,t){try{(r=n[e](t)).value instanceof m?Promise.resolve(r.value.v).then(c,u):d(s[0][2],r)}catch(e){d(s[0][3],e)}var r}function c(e){a("next",e)}function u(e){a("throw",e)}function d(e,t){e(t),s.shift(),s.length&&a(s[0][0],s[0][1])}}function y(e){var t,r;return t={},i("next"),i("throw",(function(e){throw e})),i("return"),t[Symbol.iterator]=function(){return this},t;function i(i,n){t[i]=e[i]?function(t){return(r=!r)?{value:m(e[i](t)),done:"return"===i}:n?n(t):t}:n}}function T(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=h(e),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(r){t[r]=e[r]&&function(t){return new Promise((function(i,n){(function(e,t,r,i){Promise.resolve(i).then((function(t){e({value:t,done:r})}),t)})(i,n,(t=e[r](t)).done,t.value)}))}}}function b(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}function E(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function _(e){return e&&e.__esModule?e:{default:e}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0);i.__exportStar(r(22),t),i.__exportStar(r(35),t),i.__exportStar(r(67),t),i.__exportStar(r(68),t),i.__exportStar(r(69),t),i.__exportStar(r(35),t),i.__exportStar(r(25),t),i.__exportStar(r(13),t),i.__exportStar(r(23),t)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0);i.__exportStar(r(55),t),i.__exportStar(r(57),t),i.__exportStar(r(59),t),i.__exportStar(r(29),t),i.__exportStar(r(19),t),i.__exportStar(r(32),t),i.__exportStar(r(33),t),i.__exportStar(r(20),t),i.__exportStar(r(34),t),i.__exportStar(r(62),t),i.__exportStar(r(21),t),i.__exportStar(r(30),t)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(2),n=r(1),s=function(){function e(e,t,r,i){this.transactionConstructor=e,this.core=t,this.message=r,this.delegate=i,this.challenged=!1,this.stale=!1,this.logger=this.loggerFactory.getLogger("sip.user-agent-client"),this.init()}return e.prototype.dispose=function(){this.transaction.dispose()},Object.defineProperty(e.prototype,"loggerFactory",{get:function(){return this.core.loggerFactory},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"transaction",{get:function(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction},enumerable:!0,configurable:!0}),e.prototype.cancel=function(t,r){var s=this;if(void 0===r&&(r={}),!this.transaction)throw new Error("Transaction undefined.");if(!this.message.to)throw new Error("To undefined.");if(!this.message.from)throw new Error("From undefined.");var o=this.core.makeOutgoingRequestMessage(i.C.CANCEL,this.message.ruri,this.message.from.uri,this.message.to.uri,{toTag:this.message.toTag,fromTag:this.message.fromTag,callId:this.message.callId,cseq:this.message.cseq},r.extraHeaders);if(o.branch=this.message.branch,this.message.headers.Route&&(o.headers.Route=this.message.headers.Route),t&&o.setHeader("Reason",t),this.transaction.state===n.TransactionState.Proceeding)new e(n.NonInviteClientTransaction,this.core,o);else this.transaction.once("stateChanged",(function(){if(s.transaction&&s.transaction.state===n.TransactionState.Proceeding)new e(n.NonInviteClientTransaction,s.core,o)}));return o},e.prototype.authenticationGuard=function(e){var t,r,i=e.statusCode;if(!i)throw new Error("Response status code undefined.");if(401!==i&&407!==i)return!0;if(401===i?(t=e.parseHeader("www-authenticate"),r="authorization"):(t=e.parseHeader("proxy-authenticate"),r="proxy-authorization"),!t)return this.logger.warn(i+" with wrong or missing challenge, cannot authenticate"),!0;if(this.challenged&&(this.stale||!0!==t.stale))return this.logger.warn(i+" apparently in authentication loop, cannot authenticate"),!0;if(!this.credentials&&(this.credentials=this.core.configuration.authenticationFactory(),!this.credentials))return this.logger.warn("Unable to obtain credentials, cannot authenticate"),!0;if(!this.credentials.authenticate(this.message,t))return!0;this.challenged=!0,t.stale&&(this.stale=!0);var n=this.message.cseq+=1;return this.message.setHeader("cseq",n+" "+this.message.method),this.message.setHeader(r,this.credentials.toString()),this.init(),!1},e.prototype.receiveResponse=function(e){if(this.authenticationGuard(e)){var t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e});break;case/^1[0-9]{2}$/.test(t):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e});break;case/^2[0-9]{2}$/.test(t):this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e});break;case/^3[0-9]{2}$/.test(t):this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e});break;case/^[4-6][0-9]{2}$/.test(t):this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e});break;default:throw new Error("Invalid status code "+t)}}},e.prototype.init=function(){var e=this,t={loggerFactory:this.loggerFactory,onRequestTimeout:function(){return e.onRequestTimeout()},onStateChange:function(t){t===n.TransactionState.Terminated&&(e.core.userAgentClients.delete(i),r===e._transaction&&e.dispose())},onTransportError:function(t){return e.onTransportError(t)},receiveResponse:function(t){return e.receiveResponse(t)}},r=new this.transactionConstructor(this.message,this.core.transport,t);this._transaction=r;var i=r.id+r.request.method;this.core.userAgentClients.set(i,this)},e.prototype.onRequestTimeout=function(){this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout.");var e=new i.IncomingResponseMessage;e.statusCode=408,e.reasonPhrase="Request Timeout",this.receiveResponse(e)},e.prototype.onTransportError=function(e){this.logger.error(e.message),this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable.");var t=new i.IncomingResponseMessage;t.statusCode=503,t.reasonPhrase="Service Unavailable",this.receiveResponse(t)},e}();t.UserAgentClient=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(16),n=r(2),s=r(10),o=r(1),a=function(){function e(e,t,r,i){this.transactionConstructor=e,this.core=t,this.message=r,this.delegate=i,this.logger=this.loggerFactory.getLogger("sip.user-agent-server"),this.toTag=r.toTag?r.toTag:s.newTag(),this.init()}return e.prototype.dispose=function(){this.transaction.dispose()},Object.defineProperty(e.prototype,"loggerFactory",{get:function(){return this.core.loggerFactory},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"transaction",{get:function(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction},enumerable:!0,configurable:!0}),e.prototype.accept=function(e){if(void 0===e&&(e={statusCode:200}),!this.acceptable)throw new i.TransactionStateError(this.message.method+" not acceptable in state "+this.transaction.state+".");var t=e.statusCode;if(t<200||t>299)throw new TypeError("Invalid statusCode: "+t);return this.reply(e)},e.prototype.progress=function(e){if(void 0===e&&(e={statusCode:180}),!this.progressable)throw new i.TransactionStateError(this.message.method+" not progressable in state "+this.transaction.state+".");var t=e.statusCode;if(t<101||t>199)throw new TypeError("Invalid statusCode: "+t);return this.reply(e)},e.prototype.redirect=function(e,t){if(void 0===t&&(t={statusCode:302}),!this.redirectable)throw new i.TransactionStateError(this.message.method+" not redirectable in state "+this.transaction.state+".");var r=t.statusCode;if(r<300||r>399)throw new TypeError("Invalid statusCode: "+r);var n=new Array;return e.forEach((function(e){return n.push("Contact: "+e.toString())})),t.extraHeaders=(t.extraHeaders||[]).concat(n),this.reply(t)},e.prototype.reject=function(e){if(void 0===e&&(e={statusCode:480}),!this.rejectable)throw new i.TransactionStateError(this.message.method+" not rejectable in state "+this.transaction.state+".");var t=e.statusCode;if(t<400||t>699)throw new TypeError("Invalid statusCode: "+t);return this.reply(e)},e.prototype.trying=function(e){if(!this.tryingable)throw new i.TransactionStateError(this.message.method+" not tryingable in state "+this.transaction.state+".");return this.reply({statusCode:100})},e.prototype.receiveCancel=function(e){this.delegate&&this.delegate.onCancel&&this.delegate.onCancel(e)},Object.defineProperty(e.prototype,"acceptable",{get:function(){if(this.transaction instanceof o.InviteServerTransaction)return this.transaction.state===o.TransactionState.Proceeding||this.transaction.state===o.TransactionState.Accepted;if(this.transaction instanceof o.NonInviteServerTransaction)return this.transaction.state===o.TransactionState.Trying||this.transaction.state===o.TransactionState.Proceeding;throw new Error("Unknown transaction type.")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"progressable",{get:function(){if(this.transaction instanceof o.InviteServerTransaction)return this.transaction.state===o.TransactionState.Proceeding;if(this.transaction instanceof o.NonInviteServerTransaction)return!1;throw new Error("Unknown transaction type.")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"redirectable",{get:function(){if(this.transaction instanceof o.InviteServerTransaction)return this.transaction.state===o.TransactionState.Proceeding;if(this.transaction instanceof o.NonInviteServerTransaction)return this.transaction.state===o.TransactionState.Trying||this.transaction.state===o.TransactionState.Proceeding;throw new Error("Unknown transaction type.")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rejectable",{get:function(){if(this.transaction instanceof o.InviteServerTransaction)return this.transaction.state===o.TransactionState.Proceeding;if(this.transaction instanceof o.NonInviteServerTransaction)return this.transaction.state===o.TransactionState.Trying||this.transaction.state===o.TransactionState.Proceeding;throw new Error("Unknown transaction type.")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"tryingable",{get:function(){if(this.transaction instanceof o.InviteServerTransaction)return this.transaction.state===o.TransactionState.Proceeding;if(this.transaction instanceof o.NonInviteServerTransaction)return this.transaction.state===o.TransactionState.Trying;throw new Error("Unknown transaction type.")},enumerable:!0,configurable:!0}),e.prototype.reply=function(e){e.toTag||100===e.statusCode||(e.toTag=this.toTag),e.userAgent=e.userAgent||this.core.configuration.userAgentHeaderFieldValue,e.supported=e.supported||this.core.configuration.supportedOptionTagsResponse;var t=n.constructOutgoingResponse(this.message,e);return this.transaction.receiveResponse(e.statusCode,t.message),t},e.prototype.init=function(){var e=this,t={loggerFactory:this.loggerFactory,onStateChange:function(t){t===o.TransactionState.Terminated&&(e.core.userAgentServers.delete(i),e.dispose())},onTransportError:function(t){e.logger.error(t.message),e.delegate&&e.delegate.onTransportError?e.delegate.onTransportError(t):e.logger.error("User agent server response transport error.")}},r=new this.transactionConstructor(this.message,this.core.transport,t);this._transaction=r;var i=r.id;this.core.userAgentServers.set(r.id,this)},e}();t.UserAgentServer=a},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0);i.__exportStar(r(17),t),i.__exportStar(r(16),t),i.__exportStar(r(71),t),i.__exportStar(r(2),t),i.__exportStar(r(15),t),i.__exportStar(r(27),t),i.__exportStar(r(1),t),i.__exportStar(r(73),t),i.__exportStar(r(50),t),i.__exportStar(r(6),t),i.__exportStar(r(86),t)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=500;t.Timers={T1:i,T2:4e3,T4:5e3,TIMER_B:32e3,TIMER_D:0,TIMER_F:32e3,TIMER_H:32e3,TIMER_I:0,TIMER_J:0,TIMER_K:0,TIMER_L:32e3,TIMER_M:32e3,TIMER_N:32e3,PROVISIONAL_RESPONSE_INTERVAL:6e4}},function(e,t,r){"use strict";var i,n="object"==typeof Reflect?Reflect:null,s=n&&"function"==typeof n.apply?n.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};i=n&&"function"==typeof n.ownKeys?n.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var o=Number.isNaN||function(e){return e!=e};function a(){a.init.call(this)}e.exports=a,a.EventEmitter=a,a.prototype._events=void 0,a.prototype._eventsCount=0,a.prototype._maxListeners=void 0;var c=10;function u(e){return void 0===e._maxListeners?a.defaultMaxListeners:e._maxListeners}function d(e,t,r,i){var n,s,o,a;if("function"!=typeof r)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof r);if(void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),s=e._events),o=s[t]),void 0===o)o=s[t]=r,++e._eventsCount;else if("function"==typeof o?o=s[t]=i?[r,o]:[o,r]:i?o.unshift(r):o.push(r),(n=u(e))>0&&o.length>n&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=o.length,a=c,console&&console.warn&&console.warn(a)}return e}function l(){for(var e=[],t=0;t0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=n[e];if(void 0===c)return!1;if("function"==typeof c)s(c,this,t);else{var u=c.length,d=f(c,u);for(r=0;r=0;s--)if(r[s]===t||r[s].listener===t){o=r[s].listener,n=s;break}if(n<0)return this;0===n?r.shift():function(e,t){for(;t+1=0;i--)this.removeListener(e,t[i]);return this},a.prototype.listeners=function(e){return h(this,e,!0)},a.prototype.rawListeners=function(e){return h(this,e,!1)},a.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):g.call(e,t)},a.prototype.listenerCount=g,a.prototype.eventNames=function(){return this._eventsCount>0?i(this._events):[]}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e){e[e.STATUS_EARLY=1]="STATUS_EARLY",e[e.STATUS_CONFIRMED=2]="STATUS_CONFIRMED"}(t.DialogStatus||(t.DialogStatus={})),function(e){e[e.STATUS_NULL=0]="STATUS_NULL",e[e.STATUS_INVITE_SENT=1]="STATUS_INVITE_SENT",e[e.STATUS_1XX_RECEIVED=2]="STATUS_1XX_RECEIVED",e[e.STATUS_INVITE_RECEIVED=3]="STATUS_INVITE_RECEIVED",e[e.STATUS_WAITING_FOR_ANSWER=4]="STATUS_WAITING_FOR_ANSWER",e[e.STATUS_ANSWERED=5]="STATUS_ANSWERED",e[e.STATUS_WAITING_FOR_PRACK=6]="STATUS_WAITING_FOR_PRACK",e[e.STATUS_WAITING_FOR_ACK=7]="STATUS_WAITING_FOR_ACK",e[e.STATUS_CANCELED=8]="STATUS_CANCELED",e[e.STATUS_TERMINATED=9]="STATUS_TERMINATED",e[e.STATUS_ANSWERED_WAITING_FOR_PRACK=10]="STATUS_ANSWERED_WAITING_FOR_PRACK",e[e.STATUS_EARLY_MEDIA=11]="STATUS_EARLY_MEDIA",e[e.STATUS_CONFIRMED=12]="STATUS_CONFIRMED"}(t.SessionStatus||(t.SessionStatus={})),function(e){e[e.ClientContext=0]="ClientContext",e[e.ConfigurationError=1]="ConfigurationError",e[e.Dialog=2]="Dialog",e[e.DigestAuthentication=3]="DigestAuthentication",e[e.DTMF=4]="DTMF",e[e.IncomingMessage=5]="IncomingMessage",e[e.IncomingRequest=6]="IncomingRequest",e[e.IncomingResponse=7]="IncomingResponse",e[e.InvalidStateError=8]="InvalidStateError",e[e.InviteClientContext=9]="InviteClientContext",e[e.InviteServerContext=10]="InviteServerContext",e[e.Logger=11]="Logger",e[e.LoggerFactory=12]="LoggerFactory",e[e.MethodParameterError=13]="MethodParameterError",e[e.NameAddrHeader=14]="NameAddrHeader",e[e.NotSupportedError=15]="NotSupportedError",e[e.OutgoingRequest=16]="OutgoingRequest",e[e.Parameters=17]="Parameters",e[e.PublishContext=18]="PublishContext",e[e.ReferClientContext=19]="ReferClientContext",e[e.ReferServerContext=20]="ReferServerContext",e[e.RegisterContext=21]="RegisterContext",e[e.RenegotiationError=22]="RenegotiationError",e[e.RequestSender=23]="RequestSender",e[e.ServerContext=24]="ServerContext",e[e.Session=25]="Session",e[e.SessionDescriptionHandler=26]="SessionDescriptionHandler",e[e.SessionDescriptionHandlerError=27]="SessionDescriptionHandlerError",e[e.SessionDescriptionHandlerObserver=28]="SessionDescriptionHandlerObserver",e[e.Subscription=29]="Subscription",e[e.Transport=30]="Transport",e[e.UA=31]="UA",e[e.URI=32]="URI"}(t.TypeStrings||(t.TypeStrings={})),function(e){e[e.STATUS_INIT=0]="STATUS_INIT",e[e.STATUS_STARTING=1]="STATUS_STARTING",e[e.STATUS_READY=2]="STATUS_READY",e[e.STATUS_USER_CLOSED=3]="STATUS_USER_CLOSED",e[e.STATUS_NOT_READY=4]="STATUS_NOT_READY"}(t.UAStatus||(t.UAStatus={}))},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(11),n=r(29),s=r(30);!function(e){e.defer=function(){var e={};return e.promise=new Promise((function(t,r){e.resolve=t,e.reject=r})),e},e.reducePromises=function(e,t){return e.reduce((function(e,t){return e=e.then(t)}),Promise.resolve(t))},e.str_utf8_length=function(e){return encodeURIComponent(e).replace(/%[A-F\d]{2}/g,"U").length},e.generateFakeSDP=function(e){if(e){var t=e.indexOf("o="),r=e.indexOf("\r\n",t);return"v=0\r\n"+e.slice(t,r)+"\r\ns=-\r\nt=0 0\r\nc=IN IP4 0.0.0.0"}},e.isDecimal=function(e){var t=parseInt(e,10);return!isNaN(t)&&parseFloat(e)===t},e.createRandomToken=function(e,t){void 0===t&&(t=32);for(var r="",i=0;i699)throw new TypeError("Invalid statusCode: "+t);if(t)return e.getReasonHeaderValue(t,r)},e.buildStatusLine=function(t,r){if(!t||t<100||t>699)throw new TypeError("Invalid statusCode: "+t);if(r&&"string"!=typeof r&&!(r instanceof String))throw new TypeError("Invalid reason: "+r);return"SIP/2.0 "+t+" "+(r=e.getReasonPhrase(t,r))+"\r\n"},e.fromBodyObj=function(e){var t=e.body,r=e.contentType;return{contentDisposition:function(e){return"application/sdp"===e?"session":"render"}(r),contentType:r,content:t}},e.toBodyObj=function(e){return{body:e.content,contentType:e.contentType}}}(t.Utils||(t.Utils={}))},function(e,t,r){"use strict";function i(e,t){void 0===t&&(t=32);for(var r="",i=0;i=this.headers[e].length)){var r=this.headers[e][t],s=r.raw;if(r.parsed)return r.parsed;var o=i.Grammar.parse(s,e.replace(/-/g,"_"));return-1===o?void this.headers[e].splice(t,1):(r.parsed=o,o)}},e.prototype.s=function(e,t){return void 0===t&&(t=0),this.parseHeader(e,t)},e.prototype.setHeader=function(e,t){this.headers[n.headerize(e)]=[{raw:t}]},e.prototype.toString=function(){return this.data},e}();t.IncomingMessage=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=function(e){function t(t,r,i){var n=e.call(this,i)||this;return n.uri=t,n._displayName=r,n}return i.__extends(t,e),Object.defineProperty(t.prototype,"friendlyName",{get:function(){return this.displayName||this.uri.aor},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"displayName",{get:function(){return this._displayName},set:function(e){this._displayName=e},enumerable:!0,configurable:!0}),t.prototype.clone=function(){return new t(this.uri.clone(),this._displayName,JSON.parse(JSON.stringify(this.parameters)))},t.prototype.toString=function(){var e=this.displayName||"0"===this.displayName?'"'+this.displayName+'" ':"";for(var t in e+="<"+this.uri.toString()+">",this.parameters)this.parameters.hasOwnProperty(t)&&(e+=";"+t,null!==this.parameters[t]&&(e+="="+this.parameters[t]));return e},t}(r(21).Parameters);t.NameAddrHeader=n},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e){for(var t in this.parameters={},e)e.hasOwnProperty(t)&&this.setParam(t,e[t])}return e.prototype.setParam=function(e,t){e&&(this.parameters[e.toLowerCase()]=null==t?null:t.toString())},e.prototype.getParam=function(e){if(e)return this.parameters[e.toLowerCase()]},e.prototype.hasParam=function(e){return!!e&&!!this.parameters.hasOwnProperty(e.toLowerCase())},e.prototype.deleteParam=function(e){if(e=e.toLowerCase(),this.parameters.hasOwnProperty(e)){var t=this.parameters[e];return delete this.parameters[e],t}},e.prototype.clearParams=function(){this.parameters={}},e}();t.Parameters=i},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=function(e){function t(r,i,n,s,o){var a=e.call(this,i,n,t.makeId(r),s,o)||this;a._request=r,a.user=n;var c=i.server&&i.server.scheme?i.server.scheme:void 0;return r.setViaHeader(a.id,c),a}return i.__extends(t,e),t.makeId=function(e){if("CANCEL"===e.method){if(!e.branch)throw new Error("Outgoing CANCEL request without a branch.");return e.branch}return"z9hG4bK"+Math.floor(1e7*Math.random())},Object.defineProperty(t.prototype,"request",{get:function(){return this._request},enumerable:!0,configurable:!0}),t.prototype.onRequestTimeout=function(){this.user.onRequestTimeout&&this.user.onRequestTimeout()},t}(r(23).Transaction);t.ClientTransaction=n},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(7),s=r(16),o=function(e){function t(t,r,i,n,s){var o=e.call(this)||this;return o._transport=t,o._user=r,o._id=i,o._state=n,o.logger=r.loggerFactory.getLogger(s,i),o.logger.debug("Constructing "+o.typeToString()+" with id "+o.id+"."),o}return i.__extends(t,e),t.prototype.dispose=function(){this.logger.debug("Destroyed "+this.typeToString()+" with id "+this.id+".")},Object.defineProperty(t.prototype,"id",{get:function(){return this._id},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"kind",{get:function(){throw new Error("Invalid kind.")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"state",{get:function(){return this._state},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"transport",{get:function(){return this._transport},enumerable:!0,configurable:!0}),t.prototype.on=function(t,r){return e.prototype.on.call(this,t,r)},t.prototype.logTransportError=function(e,t){this.logger.error(e.message),this.logger.error("Transport error occurred in "+this.typeToString()+" with id "+this.id+"."),this.logger.error(t)},t.prototype.send=function(e){var t=this;return this.transport.send(e).catch((function(e){var r;if(!(e instanceof s.TransportError))throw r=e&&"string"==typeof e.message?new s.TransportError(e.message):new s.TransportError,t.onTransportError(r),r;t.onTransportError(e)}))},t.prototype.setState=function(e){this.logger.debug('State change to "'+e+'" on '+this.typeToString()+" with id "+this.id+"."),this._state=e,this._user.onStateChange&&this._user.onStateChange(e),this.emit("stateChanged")},t.prototype.typeToString=function(){return"UnknownType"},t}(n.EventEmitter);t.Transaction=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=function(e){function t(t){var r=this.constructor,i=e.call(this,t)||this;return Object.setPrototypeOf(i,r.prototype),i}return i.__extends(t,e),t}(Error);t.Exception=n},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=function(e){function t(t,r,i,n,s){var o=e.call(this,r,i,t.viaBranch,n,s)||this;return o._request=t,o.user=i,o}return i.__extends(t,e),Object.defineProperty(t.prototype,"request",{get:function(){return this._request},enumerable:!0,configurable:!0}),t}(r(23).Transaction);t.ServerTransaction=n},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){var s=void 0!==t.userAgentCore?t.userAgentCore:t;return e.call(this,n.NonInviteServerTransaction,s,r,i)||this}return i.__extends(t,e),t}(r(4).UserAgentServer);t.NotifyUserAgentServer=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),r(0).__exportStar(r(70),t)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e){e[e.error=0]="error",e[e.warn=1]="warn",e[e.log=2]="log",e[e.debug=3]="debug"}(t.Levels||(t.Levels={}))},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0).__importStar(r(58));!function(e){e.parse=function(e,t){var r={startRule:t};try{i.parse(e,r)}catch(e){r.data=-1}return r.data},e.nameAddrHeaderParse=function(t){var r=e.parse(t,"Name_Addr_Header");return-1!==r?r:void 0},e.URIParse=function(t){var r=e.parse(t,"SIP_URI");return-1!==r?r:void 0}}(t.Grammar||(t.Grammar={}))},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=function(e){function t(t,r,i,n,s,o){var a=e.call(this,s)||this;if(a.headers={},!i)throw new TypeError('missing or invalid "host" parameter');for(var c in t=t||"sip",o)o.hasOwnProperty(c)&&a.setHeader(c,o[c]);return a.raw={scheme:t,user:r,host:i,port:n},a.normal={scheme:t.toLowerCase(),user:r,host:i.toLowerCase(),port:n},a}return i.__extends(t,e),Object.defineProperty(t.prototype,"scheme",{get:function(){return this.normal.scheme},set:function(e){this.raw.scheme=e,this.normal.scheme=e.toLowerCase()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"user",{get:function(){return this.normal.user},set:function(e){this.normal.user=this.raw.user=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"host",{get:function(){return this.normal.host},set:function(e){this.raw.host=e,this.normal.host=e.toLowerCase()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"aor",{get:function(){return this.normal.user+"@"+this.normal.host},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"port",{get:function(){return this.normal.port},set:function(e){this.normal.port=this.raw.port=e},enumerable:!0,configurable:!0}),t.prototype.setHeader=function(e,t){this.headers[this.headerize(e)]=t instanceof Array?t:[t]},t.prototype.getHeader=function(e){if(e)return this.headers[this.headerize(e)]},t.prototype.hasHeader=function(e){return!!e&&!!this.headers.hasOwnProperty(this.headerize(e))},t.prototype.deleteHeader=function(e){if(e=this.headerize(e),this.headers.hasOwnProperty(e)){var t=this.headers[e];return delete this.headers[e],t}},t.prototype.clearHeaders=function(){this.headers={}},t.prototype.clone=function(){return new t(this._raw.scheme,this._raw.user||"",this._raw.host,this._raw.port,JSON.parse(JSON.stringify(this.parameters)),JSON.parse(JSON.stringify(this.headers)))},t.prototype.toRaw=function(){return this._toString(this._raw)},t.prototype.toString=function(){return this._toString(this._normal)},Object.defineProperty(t.prototype,"_normal",{get:function(){return this.normal},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"_raw",{get:function(){return this.raw},enumerable:!0,configurable:!0}),t.prototype._toString=function(e){var t=e.scheme+":";for(var r in e.scheme.toLowerCase().match("^sips?$")||(t+="//"),e.user&&(t+=this.escapeUser(e.user)+"@"),t+=e.host,(e.port||0===e.port)&&(t+=":"+e.port),this.parameters)this.parameters.hasOwnProperty(r)&&(t+=";"+r,null!==this.parameters[r]&&(t+="="+this.parameters[r]));var i=[];for(var n in this.headers)if(this.headers.hasOwnProperty(n))for(var s in this.headers[n])this.headers[n].hasOwnProperty(s)&&i.push(n+"="+this.headers[n][s]);return i.length>0&&(t+="?"+i.join("&")),t},t.prototype.escapeUser=function(e){var t;try{t=decodeURIComponent(e)}catch(e){throw e}return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%2B/gi,"+").replace(/%3F/gi,"?").replace(/%2F/gi,"/")},t.prototype.headerize=function(e){for(var t={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},r=e.toLowerCase().replace(/_/g,"-").split("-"),i=r.length,n="",s=0;s699)throw new Error("Invalid status code "+r);switch(this.state){case o.TransactionState.Calling:if(r>=100&&r<=199)return this.stateTransition(o.TransactionState.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(r>=200&&r<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(o.TransactionState.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(r>=300&&r<=699)return this.stateTransition(o.TransactionState.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case o.TransactionState.Proceeding:if(r>=100&&r<=199)return void(this.user.receiveResponse&&this.user.receiveResponse(e));if(r>=200&&r<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(o.TransactionState.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(r>=300&&r<=699)return this.stateTransition(o.TransactionState.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case o.TransactionState.Accepted:if(r>=200&&r<=299){if(!this.ackRetransmissionCache.has(e.toTag))return this.ackRetransmissionCache.set(e.toTag,void 0),void(this.user.receiveResponse&&this.user.receiveResponse(e));var i=this.ackRetransmissionCache.get(e.toTag);return i?void this.send(i.toString()).catch((function(e){t.logTransportError(e,"Failed to send retransmission of ACK to 2xx response.")})):void 0}break;case o.TransactionState.Completed:if(r>=300&&r<=699)return void this.ack(e);break;case o.TransactionState.Terminated:break;default:throw new Error("Invalid state "+this.state)}var n="Received unexpected "+r+" response while in state "+this.state+".";this.logger.warn(n)},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(o.TransactionState.Terminated,!0)},t.prototype.typeToString=function(){return"INVITE client transaction"},t.prototype.ack=function(e){var t=this,r=this.request.ruri,i=this.request.callId,n=this.request.cseq,s=this.request.getHeader("from"),o=e.getHeader("to"),a=this.request.getHeader("via"),c=this.request.getHeader("route");if(!s)throw new Error("From undefined.");if(!o)throw new Error("To undefined.");if(!a)throw new Error("Via undefined.");var u="ACK "+r+" SIP/2.0\r\n";c&&(u+="Route: "+c+"\r\n"),u+="Via: "+a+"\r\n",u+="To: "+o+"\r\n",u+="From: "+s+"\r\n",u+="Call-ID: "+i+"\r\n",u+="CSeq: "+n+" ACK\r\n",u+="Max-Forwards: 70\r\n",u+="Content-Length: 0\r\n\r\n",this.send(u).catch((function(e){t.logTransportError(e,"Failed to send ACK to non-2xx response.")}))},t.prototype.stateTransition=function(e,t){var r=this;void 0===t&&(t=!1);var i=function(){throw new Error("Invalid state transition from "+r.state+" to "+e)};switch(e){case o.TransactionState.Calling:i();break;case o.TransactionState.Proceeding:this.state!==o.TransactionState.Calling&&i();break;case o.TransactionState.Accepted:case o.TransactionState.Completed:this.state!==o.TransactionState.Calling&&this.state!==o.TransactionState.Proceeding&&i();break;case o.TransactionState.Terminated:this.state!==o.TransactionState.Calling&&this.state!==o.TransactionState.Accepted&&this.state!==o.TransactionState.Completed&&(t||i());break;default:i()}this.B&&(clearTimeout(this.B),this.B=void 0),o.TransactionState.Proceeding,e===o.TransactionState.Completed&&(this.D=setTimeout((function(){return r.timer_D()}),n.Timers.TIMER_D)),e===o.TransactionState.Accepted&&(this.M=setTimeout((function(){return r.timer_M()}),n.Timers.TIMER_M)),e===o.TransactionState.Terminated&&this.dispose(),this.setState(e)},t.prototype.timer_A=function(){},t.prototype.timer_B=function(){this.logger.debug("Timer B expired for INVITE client transaction "+this.id+"."),this.state===o.TransactionState.Calling&&(this.onRequestTimeout(),this.stateTransition(o.TransactionState.Terminated))},t.prototype.timer_D=function(){this.logger.debug("Timer D expired for INVITE client transaction "+this.id+"."),this.state===o.TransactionState.Completed&&this.stateTransition(o.TransactionState.Terminated)},t.prototype.timer_M=function(){this.logger.debug("Timer M expired for INVITE client transaction "+this.id+"."),this.state===o.TransactionState.Accepted&&this.stateTransition(o.TransactionState.Terminated)},t}(s.ClientTransaction);t.InviteClientTransaction=a},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(2),s=r(1),o=function(e){function t(t,r,i){var o,a=t.createOutgoingRequestMessage(n.C.BYE,i);return o=e.call(this,s.NonInviteClientTransaction,t.userAgentCore,a,r)||this,t.dispose(),o}return i.__extends(t,e),t}(r(3).UserAgentClient);t.ByeUserAgentClient=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){return e.call(this,n.NonInviteServerTransaction,t.userAgentCore,r,i)||this}return i.__extends(t,e),t}(r(4).UserAgentServer);t.ByeUserAgentServer=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(2),s=r(1),o=function(e){function t(t,r,i){var o=t.createOutgoingRequestMessage(n.C.INFO,i);return e.call(this,s.NonInviteClientTransaction,t.userAgentCore,o,r)||this}return i.__extends(t,e),t}(r(3).UserAgentClient);t.InfoUserAgentClient=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){return e.call(this,n.NonInviteServerTransaction,t.userAgentCore,r,i)||this}return i.__extends(t,e),t}(r(4).UserAgentServer);t.InfoUserAgentServer=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(2),s=r(1),o=function(e){function t(t,r,i){var o=t.createOutgoingRequestMessage(n.C.NOTIFY,i);return e.call(this,s.NonInviteClientTransaction,t.userAgentCore,o,r)||this}return i.__extends(t,e),t}(r(3).UserAgentClient);t.NotifyUserAgentClient=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(2),s=r(1),o=function(e){function t(t,r,i){var o,a=t.createOutgoingRequestMessage(n.C.PRACK,i);return o=e.call(this,s.NonInviteClientTransaction,t.userAgentCore,a,r)||this,t.signalingStateTransition(a),o}return i.__extends(t,e),t}(r(3).UserAgentClient);t.PrackUserAgentClient=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){var s=e.call(this,n.NonInviteServerTransaction,t.userAgentCore,r,i)||this;return t.signalingStateTransition(r),s.dialog=t,s}return i.__extends(t,e),t.prototype.accept=function(t){return void 0===t&&(t={statusCode:200}),t.body&&this.dialog.signalingStateTransition(t.body),e.prototype.accept.call(this,t)},t}(r(4).UserAgentServer);t.PrackUserAgentServer=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(2),s=r(1),o=function(e){function t(t,r,i){var o=this,a=t.createOutgoingRequestMessage(n.C.INVITE,i);return(o=e.call(this,s.InviteClientTransaction,t.userAgentCore,a,r)||this).delegate=r,t.signalingStateTransition(a),t.reinviteUserAgentClient=o,o.dialog=t,o}return i.__extends(t,e),t.prototype.receiveResponse=function(e){var t=this,r=e.statusCode?e.statusCode.toString():"";if(!r)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(r):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e});break;case/^1[0-9]{2}$/.test(r):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:this.dialog,prack:function(e){throw new Error("Unimplemented.")}});break;case/^2[0-9]{2}$/.test(r):this.dialog.signalingStateTransition(e),this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e,session:this.dialog,ack:function(e){return t.dialog.ack(e)}});break;case/^3[0-9]{2}$/.test(r):this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentClient=void 0,this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e});break;case/^[4-6][0-9]{2}$/.test(r):this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentClient=void 0,this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e});break;default:throw new Error("Invalid status code "+r)}},t}(r(3).UserAgentClient);t.ReInviteUserAgentClient=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){var s=e.call(this,n.InviteServerTransaction,t.userAgentCore,r,i)||this;return t.reinviteUserAgentServer=s,s.dialog=t,s}return i.__extends(t,e),t.prototype.accept=function(t){void 0===t&&(t={statusCode:200}),t.extraHeaders=t.extraHeaders||[],t.extraHeaders=t.extraHeaders.concat(this.dialog.routeSet.map((function(e){return"Record-Route: "+e})));var r=e.prototype.accept.call(this,t),n=this.dialog,s=i.__assign({},r,{session:n});return t.body&&this.dialog.signalingStateTransition(t.body),this.dialog.reConfirm(),s},t.prototype.progress=function(t){void 0===t&&(t={statusCode:180});var r=e.prototype.progress.call(this,t),n=this.dialog,s=i.__assign({},r,{session:n});return t.body&&this.dialog.signalingStateTransition(t.body),s},t.prototype.redirect=function(e,t){throw void 0===t&&(t={statusCode:302}),this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,new Error("Unimplemented.")},t.prototype.reject=function(t){return void 0===t&&(t={statusCode:488}),this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,e.prototype.reject.call(this,t)},t}(r(4).UserAgentServer);t.ReInviteUserAgentServer=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(2),s=r(1),o=function(e){function t(t,r,i){var o=t.createOutgoingRequestMessage(n.C.REFER,i);return e.call(this,s.NonInviteClientTransaction,t.userAgentCore,o,r)||this}return i.__extends(t,e),t}(r(3).UserAgentClient);t.ReferUserAgentClient=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){var s=void 0!==t.userAgentCore?t.userAgentCore:t;return e.call(this,n.NonInviteServerTransaction,s,r,i)||this}return i.__extends(t,e),t}(r(4).UserAgentServer);t.ReferUserAgentServer=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(2),s=r(27),o=r(6),a=r(14),c=r(26),u=r(48),d=function(e){function t(t,r,i,n,s,o){var a=e.call(this,n,s)||this;return a.delegate=o,a._autoRefresh=!1,a._subscriptionEvent=t,a._subscriptionExpires=r,a._subscriptionExpiresInitial=r,a._subscriptionExpiresLastSet=Math.floor(Date.now()/1e3),a._subscriptionRefresh=void 0,a._subscriptionRefreshLastSet=void 0,a._subscriptionState=i,a.logger=n.loggerFactory.getLogger("sip.subscribe-dialog"),a.logger.log("SUBSCRIBE dialog "+a.id+" constructed"),a}return i.__extends(t,e),t.initialDialogStateForSubscription=function(e,t){var r=t.getHeaders("record-route"),i=t.parseHeader("contact");if(!i)throw new Error("Contact undefined.");if(!(i instanceof n.NameAddrHeader))throw new Error("Contact not instance of NameAddrHeader.");var s=i.uri,o=e.cseq,a=e.callId,c=e.fromTag,u=t.fromTag;if(!a)throw new Error("Call id undefined.");if(!c)throw new Error("From tag undefined.");if(!u)throw new Error("To tag undefined.");if(!e.from)throw new Error("From undefined.");if(!e.to)throw new Error("To undefined.");return{id:a+c+u,early:!1,callId:a,localTag:c,remoteTag:u,localSequenceNumber:o,remoteSequenceNumber:void 0,localURI:e.from.uri,remoteURI:e.to.uri,remoteTarget:s,routeSet:r,secure:!1}},t.prototype.dispose=function(){e.prototype.dispose.call(this),this.N&&(clearTimeout(this.N),this.N=void 0),this.refreshTimerClear(),this.logger.log("SUBSCRIBE dialog "+this.id+" destroyed")},Object.defineProperty(t.prototype,"autoRefresh",{get:function(){return this._autoRefresh},set:function(e){this._autoRefresh=!0,this.refreshTimerSet()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionEvent",{get:function(){return this._subscriptionEvent},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionExpires",{get:function(){var e=Math.floor(Date.now()/1e3)-this._subscriptionExpiresLastSet,t=this._subscriptionExpires-e;return Math.max(t,0)},set:function(e){if(e<0)throw new Error("Expires must be greater than or equal to zero.");if(this._subscriptionExpires=e,this._subscriptionExpiresLastSet=Math.floor(Date.now()/1e3),this.autoRefresh){var t=this.subscriptionRefresh;(void 0===t||t>=e)&&this.refreshTimerSet()}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionExpiresInitial",{get:function(){return this._subscriptionExpiresInitial},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionRefresh",{get:function(){if(void 0!==this._subscriptionRefresh&&void 0!==this._subscriptionRefreshLastSet){var e=Math.floor(Date.now()/1e3)-this._subscriptionRefreshLastSet,t=this._subscriptionRefresh-e;return Math.max(t,0)}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionState",{get:function(){return this._subscriptionState},enumerable:!0,configurable:!0}),t.prototype.receiveRequest=function(t){if(this.logger.log("SUBSCRIBE dialog "+this.id+" received "+t.method+" request"),this.sequenceGuard(t))switch(e.prototype.receiveRequest.call(this,t),t.method){case n.C.NOTIFY:this.onNotify(t);break;default:this.logger.log("SUBSCRIBE dialog "+this.id+" received unimplemented "+t.method+" request"),this.core.replyStateless(t,{statusCode:501})}else this.logger.log("SUBSCRIBE dialog "+this.id+" rejected out of order "+t.method+" request.")},t.prototype.refresh=function(){var e="Allow: "+a.AllowedMethods.toString(),t={};return t.extraHeaders=(t.extraHeaders||[]).slice(),t.extraHeaders.push(e),t.extraHeaders.push("Event: "+this.subscriptionEvent),t.extraHeaders.push("Expires: "+this.subscriptionExpiresInitial),t.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,t)},t.prototype.subscribe=function(e,t){var r=this;if(void 0===t&&(t={}),this.subscriptionState!==s.SubscriptionState.Pending&&this.subscriptionState!==s.SubscriptionState.Active)throw new Error("Invalid state "+this.subscriptionState+'. May only re-subscribe while in state "pending" or "active".');this.logger.log("SUBSCRIBE dialog "+this.id+" sending SUBSCRIBE request");var i=new u.ReSubscribeUserAgentClient(this,e,t);return this.N=setTimeout((function(){return r.timer_N()}),o.Timers.TIMER_N),i},t.prototype.terminate=function(){this.stateTransition(s.SubscriptionState.Terminated),this.onTerminated()},t.prototype.unsubscribe=function(){var e="Allow: "+a.AllowedMethods.toString(),t={};return t.extraHeaders=(t.extraHeaders||[]).slice(),t.extraHeaders.push(e),t.extraHeaders.push("Event: "+this.subscriptionEvent),t.extraHeaders.push("Expires: 0"),t.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,t)},t.prototype.onNotify=function(e){var t=e.parseHeader("Event").event;if(t&&t===this.subscriptionEvent){this.N&&(clearTimeout(this.N),this.N=void 0);var r=e.parseHeader("Subscription-State");if(r&&r.state){var i=r.state,n=r.expires?Math.max(r.expires,0):void 0;switch(i){case"pending":this.stateTransition(s.SubscriptionState.Pending,n);break;case"active":this.stateTransition(s.SubscriptionState.Active,n);break;case"terminated":this.stateTransition(s.SubscriptionState.Terminated,n);break;default:this.logger.warn("Unrecognized subscription state.")}var o=new c.NotifyUserAgentServer(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(o):o.accept()}else this.core.replyStateless(e,{statusCode:489})}else this.core.replyStateless(e,{statusCode:489})},t.prototype.onRefresh=function(e){this.delegate&&this.delegate.onRefresh&&this.delegate.onRefresh(e)},t.prototype.onTerminated=function(){this.delegate&&this.delegate.onTerminated&&this.delegate.onTerminated()},t.prototype.refreshTimerClear=function(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=void 0)},t.prototype.refreshTimerSet=function(){var e=this;if(this.refreshTimerClear(),this.autoRefresh&&this.subscriptionExpires>0){var t=900*this.subscriptionExpires;this._subscriptionRefresh=Math.floor(t/1e3),this._subscriptionRefreshLastSet=Math.floor(Date.now()/1e3),this.refreshTimer=setTimeout((function(){e.refreshTimer=void 0,e._subscriptionRefresh=void 0,e._subscriptionRefreshLastSet=void 0,e.onRefresh(e.refresh())}),t)}},t.prototype.stateTransition=function(e,t){var r=this,i=function(){r.logger.warn("Invalid subscription state transition from "+r.subscriptionState+" to "+e)};switch(e){case s.SubscriptionState.Initial:case s.SubscriptionState.NotifyWait:return void i();case s.SubscriptionState.Pending:if(this.subscriptionState!==s.SubscriptionState.NotifyWait&&this.subscriptionState!==s.SubscriptionState.Pending)return void i();break;case s.SubscriptionState.Active:case s.SubscriptionState.Terminated:if(this.subscriptionState!==s.SubscriptionState.NotifyWait&&this.subscriptionState!==s.SubscriptionState.Pending&&this.subscriptionState!==s.SubscriptionState.Active)return void i();break;default:return void i()}e===s.SubscriptionState.Pending&&t&&(this.subscriptionExpires=t),e===s.SubscriptionState.Active&&t&&(this.subscriptionExpires=t),e===s.SubscriptionState.Terminated&&this.dispose(),this._subscriptionState=e},t.prototype.timer_N=function(){this.subscriptionState!==s.SubscriptionState.Terminated&&(this.stateTransition(s.SubscriptionState.Terminated),this.onTerminated())},t}(r(18).Dialog);t.SubscriptionDialog=d},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(2),s=r(1),o=function(e){function t(t,r,i){var o=this,a=t.createOutgoingRequestMessage(n.C.SUBSCRIBE,i);return(o=e.call(this,s.NonInviteClientTransaction,t.userAgentCore,a,r)||this).dialog=t,o}return i.__extends(t,e),t.prototype.waitNotifyStop=function(){},t.prototype.receiveResponse=function(t){if(t.statusCode&&t.statusCode>=200&&t.statusCode<300){var r=t.getHeader("Expires");if(r){var i=Number(r);this.dialog.subscriptionExpires>i&&(this.dialog.subscriptionExpires=i)}else this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE")}if(t.statusCode&&t.statusCode>=400&&t.statusCode<700){[404,405,410,416,480,481,482,483,484,485,489,501,604].includes(t.statusCode)&&this.dialog.terminate()}e.prototype.receiveResponse.call(this,t)},t}(r(3).UserAgentClient);t.ReSubscribeUserAgentClient=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(28),n=function(){function e(e,t,r){this.logger=e,this.category=t,this.label=r}return e.prototype.error=function(e){this.genericLog(i.Levels.error,e)},e.prototype.warn=function(e){this.genericLog(i.Levels.warn,e)},e.prototype.log=function(e){this.genericLog(i.Levels.log,e)},e.prototype.debug=function(e){this.genericLog(i.Levels.debug,e)},e.prototype.genericLog=function(e,t){this.logger.genericLog(e,this.category,this.label,t)},e}();t.Logger=n},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0);i.__exportStar(r(36),t),i.__exportStar(r(37),t),i.__exportStar(r(75),t),i.__exportStar(r(38),t),i.__exportStar(r(39),t),i.__exportStar(r(76),t),i.__exportStar(r(77),t),i.__exportStar(r(78),t),i.__exportStar(r(79),t),i.__exportStar(r(40),t),i.__exportStar(r(26),t),i.__exportStar(r(80),t),i.__exportStar(r(41),t),i.__exportStar(r(42),t),i.__exportStar(r(43),t),i.__exportStar(r(44),t),i.__exportStar(r(48),t),i.__exportStar(r(81),t),i.__exportStar(r(45),t),i.__exportStar(r(46),t),i.__exportStar(r(82),t),i.__exportStar(r(83),t),i.__exportStar(r(84),t),i.__exportStar(r(85),t),i.__exportStar(r(3),t),i.__exportStar(r(4),t)},,function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(7),s=r(11),o=r(5),a=r(14),c=r(8),u=r(12),d=r(9),l=r(53),p=r(92),h=r(54),g=r(93),f=r(31),v=function(e){function t(t,r){void 0===r&&(r={});var i=e.call(this)||this;return i.type=c.TypeStrings.Session,i.method=s.C.INVITE,i.localHold=!1,i.status=c.SessionStatus.STATUS_NULL,i.isFailed=!1,i.rel100=s.C.supported.UNSUPPORTED,i.expiresTimer=void 0,i.userNoAnswerTimer=void 0,i._state=f.SessionState.Initial,i._stateEventEmitter=new n.EventEmitter,i.pendingReinvite=!1,i.tones=void 0,i.userAgent=t,i.delegate=r.delegate,i.logger=t.getLogger("sip.session"),i.errorListener=i.onTransportError.bind(i),t.transport&&t.transport.on("transportError",i.errorListener),i}return i.__extends(t,e),t.prototype.on=function(t,r){return e.prototype.on.call(this,t,r)},t.prototype.emit=function(t){for(var r=[],i=1;i0){for(t=1,r=1;t",y(">",!1),"\\",y("\\",!1),"[",y("[",!1),"]",y("]",!1),"{",y("{",!1),"}",y("}",!1),function(){return"*"},function(){return"/"},function(){return"="},function(){return"("},function(){return")"},function(){return">"},function(){return"<"},function(){return","},function(){return";"},function(){return":"},function(){return'"'},/^[!-']/,T([["!","'"]],!1,!1),/^[*-[]/,T([["*","["]],!1,!1),/^[\]-~]/,T([["]","~"]],!1,!1),function(e){return e},/^[#-[]/,T([["#","["]],!1,!1),/^[\0-\t]/,T([["\0","\t"]],!1,!1),/^[\x0B-\f]/,T([["\v","\f"]],!1,!1),/^[\x0E-\x7F]/,T([["\x0e","\x7f"]],!1,!1),function(){(t=t||{data:{}}).data.uri=new s.URI(t.data.scheme,t.data.user,t.data.host,t.data.port),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port},function(){(t=t||{data:{}}).data.uri=new s.URI(t.data.scheme,t.data.user,t.data.host,t.data.port,t.data.uri_params,t.data.uri_headers),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port,delete t.data.uri_params,"SIP_URI"===t.startRule&&(t.data=t.data.uri)},"sips",y("sips",!0),"sip",y("sip",!0),function(e){(t=t||{data:{}}).data.scheme=e},function(){(t=t||{data:{}}).data.user=decodeURIComponent(m().slice(0,-1))},function(){(t=t||{data:{}}).data.password=m()},function(){return(t=t||{data:{}}).data.host=m(),t.data.host},function(){return(t=t||{data:{}}).data.host_type="domain",m()},/^[a-zA-Z0-9_\-]/,T([["a","z"],["A","Z"],["0","9"],"_","-"],!1,!1),/^[a-zA-Z0-9\-]/,T([["a","z"],["A","Z"],["0","9"],"-"],!1,!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",m()},"::",y("::",!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",m()},function(){return(t=t||{data:{}}).data.host_type="IPv4",m()},"25",y("25",!1),/^[0-5]/,T([["0","5"]],!1,!1),"2",y("2",!1),/^[0-4]/,T([["0","4"]],!1,!1),"1",y("1",!1),/^[1-9]/,T([["1","9"]],!1,!1),function(e){return t=t||{data:{}},e=parseInt(e.join("")),t.data.port=e,e},"transport=",y("transport=",!0),"udp",y("udp",!0),"tcp",y("tcp",!0),"sctp",y("sctp",!0),"tls",y("tls",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.transport=e.toLowerCase()},"user=",y("user=",!0),"phone",y("phone",!0),"ip",y("ip",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.user=e.toLowerCase()},"method=",y("method=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.method=e},"ttl=",y("ttl=",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.ttl=e},"maddr=",y("maddr=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.maddr=e},"lr",y("lr",!0),function(){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.lr=void 0},function(e,r){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),r=null===r?void 0:r[1],t.data.uri_params[e.toLowerCase()]=r},function(e,r){e=e.join("").toLowerCase(),r=r.join(""),(t=t||{data:{}}).data.uri_headers||(t.data.uri_headers={}),t.data.uri_headers[e]?t.data.uri_headers[e].push(r):t.data.uri_headers[e]=[r]},function(){"Refer_To"===(t=t||{data:{}}).startRule&&(t.data.uri=new s.URI(t.data.scheme,t.data.user,t.data.host,t.data.port,t.data.uri_params,t.data.uri_headers),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port,delete t.data.uri_params)},"//",y("//",!1),function(){(t=t||{data:{}}).data.scheme=m()},y("SIP",!0),function(){(t=t||{data:{}}).data.sip_version=m()},"INVITE",y("INVITE",!1),"ACK",y("ACK",!1),"VXACH",y("VXACH",!1),"OPTIONS",y("OPTIONS",!1),"BYE",y("BYE",!1),"CANCEL",y("CANCEL",!1),"REGISTER",y("REGISTER",!1),"SUBSCRIBE",y("SUBSCRIBE",!1),"NOTIFY",y("NOTIFY",!1),"REFER",y("REFER",!1),"PUBLISH",y("PUBLISH",!1),function(){return(t=t||{data:{}}).data.method=m(),t.data.method},function(e){(t=t||{data:{}}).data.status_code=parseInt(e.join(""))},function(){(t=t||{data:{}}).data.reason_phrase=m()},function(){(t=t||{data:{}}).data=m()},function(){var e,r;for(r=(t=t||{data:{}}).data.multi_header.length,e=0;e""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),R(";).# &;,"),R('2F""6F7G.} &2H""6H7I.q &2J""6J7K.e &2L""6L7M.Y &2N""6N7O.M &2P""6P7Q.A &2R""6R7S.5 &2T""6T7U.) &2V""6V7W'),R('%%2X""6X7Y/5#;#/,$;#/#$+#)(#\'#("\'#&\'#/"!&,)'),R('%%$;$0#*;$&/,#; /#$+")("\'#&\'#." &"/=#$;$/�#*;$&&&#/\'$8":Z" )("\'#&\'#'),R(';.." &"'),R("%$;'.# &;(0)*;'.# &;(&/?#28\"\"6879/0$;//'$8#:[# )(#'#(\"'#&'#"),R('%%$;2/�#*;2&&&#/g#$%$;.0#*;.&/,#;2/#$+")("\'#&\'#0=*%$;.0#*;.&/,#;2/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),R('4\\""5!7].# &;3'),R('4^""5!7_'),R('4`""5!7a'),R(';!.) &4b""5!7c'),R('%$;).\x95 &2F""6F7G.\x89 &2J""6J7K.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O/\x9e#0\x9b*;).\x95 &2F""6F7G.\x89 &2J""6J7K.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O&&&#/"!&,)'),R('%$;).\x89 &2F""6F7G.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O/\x92#0\x8f*;).\x89 &2F""6F7G.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O&&&#/"!&,)'),R('2T""6T7U.\xe3 &2V""6V7W.\xd7 &2f""6f7g.\xcb &2h""6h7i.\xbf &2:""6:7;.\xb3 &2D""6D7E.\xa7 &22""6273.\x9b &28""6879.\x8f &2j""6j7k.\x83 &;&.} &24""6475.q &2l""6l7m.e &2n""6n7o.Y &26""6677.M &2>""6>7?.A &2p""6p7q.5 &2r""6r7s.) &;\'.# &;('),R('%$;).\u012b &2F""6F7G.\u011f &2J""6J7K.\u0113 &2L""6L7M.\u0107 &2X""6X7Y.\xfb &2P""6P7Q.\xef &2H""6H7I.\xe3 &2@""6@7A.\xd7 &2d""6d7e.\xcb &2R""6R7S.\xbf &2N""6N7O.\xb3 &2T""6T7U.\xa7 &2V""6V7W.\x9b &2f""6f7g.\x8f &2h""6h7i.\x83 &28""6879.w &2j""6j7k.k &;&.e &24""6475.Y &2l""6l7m.M &2n""6n7o.A &26""6677.5 &2p""6p7q.) &2r""6r7s/\u0134#0\u0131*;).\u012b &2F""6F7G.\u011f &2J""6J7K.\u0113 &2L""6L7M.\u0107 &2X""6X7Y.\xfb &2P""6P7Q.\xef &2H""6H7I.\xe3 &2@""6@7A.\xd7 &2d""6d7e.\xcb &2R""6R7S.\xbf &2N""6N7O.\xb3 &2T""6T7U.\xa7 &2V""6V7W.\x9b &2f""6f7g.\x8f &2h""6h7i.\x83 &28""6879.w &2j""6j7k.k &;&.e &24""6475.Y &2l""6l7m.M &2n""6n7o.A &26""6677.5 &2p""6p7q.) &2r""6r7s&&&#/"!&,)'),R("%;//?#2P\"\"6P7Q/0$;//'$8#:t# )(#'#(\"'#&'#"),R("%;//?#24\"\"6475/0$;//'$8#:u# )(#'#(\"'#&'#"),R("%;//?#2>\"\"6>7?/0$;//'$8#:v# )(#'#(\"'#&'#"),R("%;//?#2T\"\"6T7U/0$;//'$8#:w# )(#'#(\"'#&'#"),R("%;//?#2V\"\"6V7W/0$;//'$8#:x# )(#'#(\"'#&'#"),R('%2h""6h7i/0#;//\'$8":y" )("\'#&\'#'),R('%;//6#2f""6f7g/\'$8":z" )("\'#&\'#'),R("%;//?#2D\"\"6D7E/0$;//'$8#:{# )(#'#(\"'#&'#"),R("%;//?#22\"\"6273/0$;//'$8#:|# )(#'#(\"'#&'#"),R("%;//?#28\"\"6879/0$;//'$8#:}# )(#'#(\"'#&'#"),R("%;//0#;&/'$8\":~\" )(\"'#&'#"),R("%;&/0#;//'$8\":~\" )(\"'#&'#"),R("%;=/T#$;G.) &;K.# &;F0/*;G.) &;K.# &;F&/,$;>/#$+#)(#'#(\"'#&'#"),R('4\x7f""5!7\x80.A &4\x81""5!7\x82.5 &4\x83""5!7\x84.) &;3.# &;.'),R("%%;//Q#;&/H$$;J.# &;K0)*;J.# &;K&/,$;&/#$+$)($'#(#'#(\"'#&'#/\"!&,)"),R("%;//]#;&/T$%$;J.# &;K0)*;J.# &;K&/\"!&,)/1$;&/($8$:\x85$!!)($'#(#'#(\"'#&'#"),R(';..G &2L""6L7M.; &4\x86""5!7\x87./ &4\x83""5!7\x84.# &;3'),R('%2j""6j7k/J#4\x88""5!7\x89.5 &4\x8a""5!7\x8b.) &4\x8c""5!7\x8d/#$+")("\'#&\'#'),R("%;N/M#28\"\"6879/>$;O.\" &\"/0$;S/'$8$:\x8e$ )($'#(#'#(\"'#&'#"),R("%;N/d#28\"\"6879/U$;O.\" &\"/G$;S/>$;_/5$;l.\" &\"/'$8&:\x8f& )(&'#(%'#($'#(#'#(\"'#&'#"),R('%3\x90""5$7\x91.) &3\x92""5#7\x93/\' 8!:\x94!! )'),R('%;P/]#%28""6879/,#;R/#$+")("\'#&\'#." &"/6$2:""6:7;/\'$8#:\x95# )(#\'#("\'#&\'#'),R("$;+.) &;-.# &;Q/2#0/*;+.) &;-.# &;Q&&&#"),R('2<""6<7=.q &2>""6>7?.e &2@""6@7A.Y &2B""6B7C.M &2D""6D7E.A &22""6273.5 &26""6677.) &24""6475'),R('%$;+._ &;-.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E0e*;+._ &;-.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E&/& 8!:\x96! )'),R('%;T/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),R("%;U.) &;\\.# &;X/& 8!:\x97! )"),R('%$%;V/2#2J""6J7K/#$+")("\'#&\'#0<*%;V/2#2J""6J7K/#$+")("\'#&\'#&/D#;W/;$2J""6J7K." &"/\'$8#:\x98# )(#\'#("\'#&\'#'),R('$4\x99""5!7\x9a/,#0)*4\x99""5!7\x9a&&&#'),R('%4$""5!7%/?#$4\x9b""5!7\x9c0)*4\x9b""5!7\x9c&/#$+")("\'#&\'#'),R('%2l""6l7m/?#;Y/6$2n""6n7o/\'$8#:\x9d# )(#\'#("\'#&\'#'),R('%%;Z/\xb3#28""6879/\xa4$;Z/\x9b$28""6879/\x8c$;Z/\x83$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+-)(-\'#(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u0790 &%2\x9e""6\x9e7\x9f/\xa4#;Z/\x9b$28""6879/\x8c$;Z/\x83$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+,)(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u06f9 &%2\x9e""6\x9e7\x9f/\x8c#;Z/\x83$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u067a &%2\x9e""6\x9e7\x9f/t#;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u0613 &%2\x9e""6\x9e7\x9f/\\#;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+&)(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u05c4 &%2\x9e""6\x9e7\x9f/D#;Z/;$28""6879/,$;[/#$+$)($\'#(#\'#("\'#&\'#.\u058d &%2\x9e""6\x9e7\x9f/,#;[/#$+")("\'#&\'#.\u056e &%2\x9e""6\x9e7\x9f/,#;Z/#$+")("\'#&\'#.\u054f &%;Z/\x9b#2\x9e""6\x9e7\x9f/\x8c$;Z/\x83$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$++)(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u04c7 &%;Z/\xaa#%28""6879/,#;Z/#$+")("\'#&\'#." &"/\x83$2\x9e""6\x9e7\x9f/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u0430 &%;Z/\xb9#%28""6879/,#;Z/#$+")("\'#&\'#." &"/\x92$%28""6879/,#;Z/#$+")("\'#&\'#." &"/k$2\x9e""6\x9e7\x9f/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+))()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u038a &%;Z/\xc8#%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xa1$%28""6879/,#;Z/#$+")("\'#&\'#." &"/z$%28""6879/,#;Z/#$+")("\'#&\'#." &"/S$2\x9e""6\x9e7\x9f/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u02d5 &%;Z/\xd7#%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xb0$%28""6879/,#;Z/#$+")("\'#&\'#." &"/\x89$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2\x9e""6\x9e7\x9f/,$;[/#$+\')(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u0211 &%;Z/\xfe#%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xd7$%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xb0$%28""6879/,#;Z/#$+")("\'#&\'#." &"/\x89$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2\x9e""6\x9e7\x9f/,$;Z/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u0126 &%;Z/\u011c#%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xf5$%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xce$%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xa7$%28""6879/,#;Z/#$+")("\'#&\'#." &"/\x80$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Y$%28""6879/,#;Z/#$+")("\'#&\'#." &"/2$2\x9e""6\x9e7\x9f/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#/& 8!:\xa0! )'),R('%;#/M#;#." &"/?$;#." &"/1$;#." &"/#$+$)($\'#(#\'#("\'#&\'#'),R("%;Z/;#28\"\"6879/,$;Z/#$+#)(#'#(\"'#&'#.# &;\\"),R("%;]/o#2J\"\"6J7K/`$;]/W$2J\"\"6J7K/H$;]/?$2J\"\"6J7K/0$;]/'$8':\xa1' )(''#(&'#(%'#($'#(#'#(\"'#&'#"),R('%2\xa2""6\xa27\xa3/2#4\xa4""5!7\xa5/#$+")("\'#&\'#.\x98 &%2\xa6""6\xa67\xa7/;#4\xa8""5!7\xa9/,$;!/#$+#)(#\'#("\'#&\'#.j &%2\xaa""6\xaa7\xab/5#;!/,$;!/#$+#)(#\'#("\'#&\'#.B &%4\xac""5!7\xad/,#;!/#$+")("\'#&\'#.# &;!'),R('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:\xae!! )'),R('$%22""6273/,#;`/#$+")("\'#&\'#0<*%22""6273/,#;`/#$+")("\'#&\'#&'),R(";a.A &;b.; &;c.5 &;d./ &;e.) &;f.# &;g"),R('%3\xaf""5*7\xb0/a#3\xb1""5#7\xb2.G &3\xb3""5#7\xb4.; &3\xb5""5$7\xb6./ &3\xb7""5#7\xb8.# &;6/($8":\xb9"! )("\'#&\'#'),R('%3\xba""5%7\xbb/I#3\xbc""5%7\xbd./ &3\xbe""5"7\xbf.# &;6/($8":\xc0"! )("\'#&\'#'),R('%3\xc1""5\'7\xc2/1#;\x90/($8":\xc3"! )("\'#&\'#'),R('%3\xc4""5$7\xc5/1#;\xf0/($8":\xc6"! )("\'#&\'#'),R('%3\xc7""5&7\xc8/1#;T/($8":\xc9"! )("\'#&\'#'),R('%3\xca""5"7\xcb/N#%2>""6>7?/,#;6/#$+")("\'#&\'#." &"/\'$8":\xcc" )("\'#&\'#'),R('%;h/P#%2>""6>7?/,#;i/#$+")("\'#&\'#." &"/)$8":\xcd""! )("\'#&\'#'),R('%$;j/�#*;j&&&#/"!&,)'),R('%$;j/�#*;j&&&#/"!&,)'),R(";k.) &;+.# &;-"),R('2l""6l7m.e &2n""6n7o.Y &24""6475.M &28""6879.A &2<""6<7=.5 &2@""6@7A.) &2B""6B7C'),R('%26""6677/n#;m/e$$%2<""6<7=/,#;m/#$+")("\'#&\'#0<*%2<""6<7=/,#;m/#$+")("\'#&\'#&/#$+#)(#\'#("\'#&\'#'),R('%;n/A#2>""6>7?/2$;o/)$8#:\xce#"" )(#\'#("\'#&\'#'),R("$;p.) &;+.# &;-/2#0/*;p.) &;+.# &;-&&&#"),R("$;p.) &;+.# &;-0/*;p.) &;+.# &;-&"),R('2l""6l7m.e &2n""6n7o.Y &24""6475.M &26""6677.A &28""6879.5 &2@""6@7A.) &2B""6B7C'),R(";\x91.# &;r"),R("%;\x90/G#;'/>$;s/5$;'/,$;\x84/#$+%)(%'#($'#(#'#(\"'#&'#"),R(";M.# &;t"),R("%;\x7f/E#28\"\"6879/6$;u.# &;x/'$8#:\xcf# )(#'#(\"'#&'#"),R('%;v.# &;w/J#%26""6677/,#;\x83/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),R('%2\xd0""6\xd07\xd1/:#;\x80/1$;w." &"/#$+#)(#\'#("\'#&\'#'),R('%24""6475/,#;{/#$+")("\'#&\'#'),R("%;z/3#$;y0#*;y&/#$+\")(\"'#&'#"),R(";*.) &;+.# &;-"),R(';+.\x8f &;-.\x89 &22""6273.} &26""6677.q &28""6879.e &2:""6:7;.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),R('%;|/e#$%24""6475/,#;|/#$+")("\'#&\'#0<*%24""6475/,#;|/#$+")("\'#&\'#&/#$+")("\'#&\'#'),R('%$;~0#*;~&/e#$%22""6273/,#;}/#$+")("\'#&\'#0<*%22""6273/,#;}/#$+")("\'#&\'#&/#$+")("\'#&\'#'),R("$;~0#*;~&"),R(';+.w &;-.q &28""6879.e &2:""6:7;.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),R('%%;"/\x87#$;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K0M*;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K&/#$+")("\'#&\'#/& 8!:\xd2! )'),R(";\x81.# &;\x82"),R('%%;O/2#2:""6:7;/#$+")("\'#&\'#." &"/,#;S/#$+")("\'#&\'#." &"'),R('$;+.\x83 &;-.} &2B""6B7C.q &2D""6D7E.e &22""6273.Y &28""6879.M &2:""6:7;.A &2<""6<7=.5 &2>""6>7?.) &2@""6@7A/\x8c#0\x89*;+.\x83 &;-.} &2B""6B7C.q &2D""6D7E.e &22""6273.Y &28""6879.M &2:""6:7;.A &2<""6<7=.5 &2>""6>7?.) &2@""6@7A&&&#'),R("$;y0#*;y&"),R('%3\x92""5#7\xd3/q#24""6475/b$$;!/�#*;!&&&#/L$2J""6J7K/=$$;!/�#*;!&&&#/\'$8%:\xd4% )(%\'#($\'#(#\'#("\'#&\'#'),R('2\xd5""6\xd57\xd6'),R('2\xd7""6\xd77\xd8'),R('2\xd9""6\xd97\xda'),R('2\xdb""6\xdb7\xdc'),R('2\xdd""6\xdd7\xde'),R('2\xdf""6\xdf7\xe0'),R('2\xe1""6\xe17\xe2'),R('2\xe3""6\xe37\xe4'),R('2\xe5""6\xe57\xe6'),R('2\xe7""6\xe77\xe8'),R('2\xe9""6\xe97\xea'),R("%;\x85.Y &;\x86.S &;\x88.M &;\x89.G &;\x8a.A &;\x8b.; &;\x8c.5 &;\x8f./ &;\x8d.) &;\x8e.# &;6/& 8!:\xeb! )"),R("%;\x84/G#;'/>$;\x92/5$;'/,$;\x94/#$+%)(%'#($'#(#'#(\"'#&'#"),R("%;\x93/' 8!:\xec!! )"),R("%;!/5#;!/,$;!/#$+#)(#'#(\"'#&'#"),R("%$;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(0G*;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(&/& 8!:\xed! )"),R("%;\xb6/Y#$%;A/,#;\xb6/#$+\")(\"'#&'#06*%;A/,#;\xb6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),R('%;9/N#%2:""6:7;/,#;9/#$+")("\'#&\'#." &"/\'$8":\xee" )("\'#&\'#'),R("%;:.c &%;\x98/Y#$%;A/,#;\x98/#$+\")(\"'#&'#06*%;A/,#;\x98/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/& 8!:\xef! )"),R("%;L.# &;\x99/]#$%;B/,#;\x9b/#$+\")(\"'#&'#06*%;B/,#;\x9b/#$+\")(\"'#&'#&/'$8\":\xf0\" )(\"'#&'#"),R("%;\x9a.\" &\"/>#;@/5$;M/,$;?/#$+$)($'#(#'#(\"'#&'#"),R("%%;6/Y#$%;./,#;6/#$+\")(\"'#&'#06*%;./,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#.# &;H/' 8!:\xf1!! )"),R(";\x9c.) &;\x9d.# &;\xa0"),R("%3\xf2\"\"5!7\xf3/:#;$;\xcf/5$;./,$;\x90/#$+%)(%'#($'#(#'#(\"'#&'#"),R("%$;!/�#*;!&&&#/' 8!:\u014b!! )"),R("%;\xd1/]#$%;A/,#;\xd1/#$+\")(\"'#&'#06*%;A/,#;\xd1/#$+\")(\"'#&'#&/'$8\":\u014c\" )(\"'#&'#"),R("%;\x99/]#$%;B/,#;\xa0/#$+\")(\"'#&'#06*%;B/,#;\xa0/#$+\")(\"'#&'#&/'$8\":\u014d\" )(\"'#&'#"),R('%;L.O &;\x99.I &%;@." &"/:#;t/1$;?." &"/#$+#)(#\'#("\'#&\'#/]#$%;B/,#;\xa0/#$+")("\'#&\'#06*%;B/,#;\xa0/#$+")("\'#&\'#&/\'$8":\u014e" )("\'#&\'#'),R("%;\xd4/]#$%;B/,#;\xd5/#$+\")(\"'#&'#06*%;B/,#;\xd5/#$+\")(\"'#&'#&/'$8\":\u014f\" )(\"'#&'#"),R("%;\x96/& 8!:\u0150! )"),R('%3\u0151""5(7\u0152/:#;$;6/5$;;/,$;\xec/#$+%)(%'#($'#(#'#(\"'#&'#"),R('%3\x92""5#7\xd3.# &;6/\' 8!:\u018b!! )'),R('%3\xb1""5#7\u018c.G &3\xb3""5#7\u018d.; &3\xb7""5#7\u018e./ &3\xb5""5$7\u018f.# &;6/\' 8!:\u0190!! )'),R('%;\xee/D#%;C/,#;\xef/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),R("%;U.) &;\\.# &;X/& 8!:\u0191! )"),R('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:\u0192!! )'),R('%%;!/?#;!." &"/1$;!." &"/#$+#)(#\'#("\'#&\'#/\' 8!:\u0193!! )'),R(";\xbe"),R('%;\x9e/^#$%;B/,#;\xf3/#$+")("\'#&\'#06*%;B/,#;\xf3/#$+")("\'#&\'#&/($8":\u0194"!!)("\'#&\'#'),R(";\xf4.# &;\xa0"),R('%2\u0195""6\u01957\u0196/L#;""6>7?'),R('%;\u0100/b#28""6879/S$;\xfb/J$%2\u01a3""6\u01a37\u01a4/,#;\xec/#$+")("\'#&\'#." &"/#$+$)($\'#(#\'#("\'#&\'#'),R('%3\u01a5""5%7\u01a6.) &3\u01a7""5$7\u01a8/\' 8!:\u01a1!! )'),R('%3\xb1""5#7\xb2.6 &3\xb3""5#7\xb4.* &$;+0#*;+&/\' 8!:\u01a9!! )'),R("%;\u0104/\x87#2F\"\"6F7G/x$;\u0103/o$2F\"\"6F7G/`$;\u0103/W$2F\"\"6F7G/H$;\u0103/?$2F\"\"6F7G/0$;\u0105/'$8):\u01aa) )()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#"),R("%;#/>#;#/5$;#/,$;#/#$+$)($'#(#'#(\"'#&'#"),R("%;\u0103/,#;\u0103/#$+\")(\"'#&'#"),R("%;\u0103/5#;\u0103/,$;\u0103/#$+#)(#'#(\"'#&'#"),R("%;q/T#$;m0#*;m&/D$%; /,#;\xf8/#$+\")(\"'#&'#.\" &\"/#$+#)(#'#(\"'#&'#"),R('%2\u01ab""6\u01ab7\u01ac.) &2\u01ad""6\u01ad7\u01ae/w#;0/n$;\u0108/e$$%;B/2#;\u0109.# &;\xa0/#$+")("\'#&\'#0<*%;B/2#;\u0109.# &;\xa0/#$+")("\'#&\'#&/#$+$)($\'#(#\'#("\'#&\'#'),R(";\x99.# &;L"),R("%2\u01af\"\"6\u01af7\u01b0/5#;g&&(g=l,f=[]),f.push(e))}function w(e,t,r){return new o(o.buildMessage(e,t),e,t,r)}function R(e){return e.split("").map((function(e){return e.charCodeAt(0)-32}))}if(t.data={},(r=function t(r){for(var n,s=d[r],o=0,a=[],c=s.length,h=[],g=[];;){for(;ol?(c=o+3+s[o+1],o+=3):(c=o+3+s[o+1]+s[o+2],o+=3+s[o+1]);break;case 18:h.push(c),a.push(o+4+s[o+2]+s[o+3]),e.substr(l,u[s[o+1]].length)===u[s[o+1]]?(c=o+4+s[o+2],o+=4):(c=o+4+s[o+2]+s[o+3],o+=4+s[o+2]);break;case 19:h.push(c),a.push(o+4+s[o+2]+s[o+3]),e.substr(l,u[s[o+1]].length).toLowerCase()===u[s[o+1]]?(c=o+4+s[o+2],o+=4):(c=o+4+s[o+2]+s[o+3],o+=4+s[o+2]);break;case 20:h.push(c),a.push(o+4+s[o+2]+s[o+3]),u[s[o+1]].test(e.charAt(l))?(c=o+4+s[o+2],o+=4):(c=o+4+s[o+2]+s[o+3],o+=4+s[o+2]);break;case 21:g.push(e.substr(l,s[o+1])),l+=s[o+1],o+=2;break;case 22:g.push(u[s[o+1]]),l+=u[s[o+1]].length,o+=2;break;case 23:g.push(i),0===v&&_(u[s[o+1]]),o+=2;break;case 24:p=g[g.length-1-s[o+1]],o+=2;break;case 25:p=l,o++;break;case 26:n=s.slice(o+4,o+4+s[o+3]).map((function(e){return g[g.length-1-e]})),g.splice(g.length-s[o+2],s[o+2],u[s[o+1]].apply(null,n)),o+=4+s[o+3];break;case 27:g.push(t(s[o+1])),o+=2;break;case 28:v++,o++;break;case 29:v--,o++;break;default:throw new Error("Invalid opcode: "+s[o]+".")}if(!(h.length>0))break;c=h.pop(),o=a.pop()}return g[0]}(c))!==i&&l===e.length)return r;throw r!==i&&l-1)this.qop="auth";else{if(!(t.qop.indexOf("auth-int")>-1))return this.logger.warn("challenge without Digest qop different than 'auth' or 'auth-int', authentication aborted"),!1;this.qop="auth-int"}else this.qop=void 0;return this.method=e.method,this.uri=e.ruri,this.cnonce=n.createRandomToken(12),this.nc+=1,this.updateNcHex(),4294967296===this.nc&&(this.nc=1,this.ncHex="00000001"),this.calculateResponse(r),!0},e.prototype.toString=function(){var e=[];if(!this.response)throw new Error("response field does not exist, cannot generate Authorization header");return e.push("algorithm="+this.algorithm),e.push('username="'+this.username+'"'),e.push('realm="'+this.realm+'"'),e.push('nonce="'+this.nonce+'"'),e.push('uri="'+this.uri+'"'),e.push('response="'+this.response+'"'),this.opaque&&e.push('opaque="'+this.opaque+'"'),this.qop&&(e.push("qop="+this.qop),e.push('cnonce="'+this.cnonce+'"'),e.push("nc="+this.ncHex)),"Digest "+e.join(", ")},e.prototype.updateNcHex=function(){var e=Number(this.nc).toString(16);this.ncHex="00000000".substr(0,8-e.length)+e},e.prototype.calculateResponse=function(e){var t,r=i.default(this.username+":"+this.realm+":"+this.password);"auth"===this.qop?(t=i.default(this.method+":"+this.uri),this.response=i.default(r+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth:"+t)):"auth-int"===this.qop?(t=i.default(this.method+":"+this.uri+":"+i.default(e||"")),this.response=i.default(r+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth-int:"+t)):void 0===this.qop&&(t=i.default(this.method+":"+this.uri),this.response=i.default(r+":"+this.nonce+":"+t))},e}();t.DigestAuthentication=s},function(e,t,r){var i;e.exports=(i=r(61),function(e){var t=i,r=t.lib,n=r.WordArray,s=r.Hasher,o=t.algo,a=[];!function(){for(var t=0;t<64;t++)a[t]=4294967296*e.abs(e.sin(t+1))|0}();var c=o.MD5=s.extend({_doReset:function(){this._hash=new n.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(e,t){for(var r=0;r<16;r++){var i=t+r,n=e[i];e[i]=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8)}var s=this._hash.words,o=e[t+0],c=e[t+1],h=e[t+2],g=e[t+3],f=e[t+4],v=e[t+5],m=e[t+6],S=e[t+7],y=e[t+8],T=e[t+9],b=e[t+10],E=e[t+11],_=e[t+12],w=e[t+13],R=e[t+14],I=e[t+15],C=s[0],A=s[1],x=s[2],P=s[3];C=u(C,A,x,P,o,7,a[0]),P=u(P,C,A,x,c,12,a[1]),x=u(x,P,C,A,h,17,a[2]),A=u(A,x,P,C,g,22,a[3]),C=u(C,A,x,P,f,7,a[4]),P=u(P,C,A,x,v,12,a[5]),x=u(x,P,C,A,m,17,a[6]),A=u(A,x,P,C,S,22,a[7]),C=u(C,A,x,P,y,7,a[8]),P=u(P,C,A,x,T,12,a[9]),x=u(x,P,C,A,b,17,a[10]),A=u(A,x,P,C,E,22,a[11]),C=u(C,A,x,P,_,7,a[12]),P=u(P,C,A,x,w,12,a[13]),x=u(x,P,C,A,R,17,a[14]),C=d(C,A=u(A,x,P,C,I,22,a[15]),x,P,c,5,a[16]),P=d(P,C,A,x,m,9,a[17]),x=d(x,P,C,A,E,14,a[18]),A=d(A,x,P,C,o,20,a[19]),C=d(C,A,x,P,v,5,a[20]),P=d(P,C,A,x,b,9,a[21]),x=d(x,P,C,A,I,14,a[22]),A=d(A,x,P,C,f,20,a[23]),C=d(C,A,x,P,T,5,a[24]),P=d(P,C,A,x,R,9,a[25]),x=d(x,P,C,A,g,14,a[26]),A=d(A,x,P,C,y,20,a[27]),C=d(C,A,x,P,w,5,a[28]),P=d(P,C,A,x,h,9,a[29]),x=d(x,P,C,A,S,14,a[30]),C=l(C,A=d(A,x,P,C,_,20,a[31]),x,P,v,4,a[32]),P=l(P,C,A,x,y,11,a[33]),x=l(x,P,C,A,E,16,a[34]),A=l(A,x,P,C,R,23,a[35]),C=l(C,A,x,P,c,4,a[36]),P=l(P,C,A,x,f,11,a[37]),x=l(x,P,C,A,S,16,a[38]),A=l(A,x,P,C,b,23,a[39]),C=l(C,A,x,P,w,4,a[40]),P=l(P,C,A,x,o,11,a[41]),x=l(x,P,C,A,g,16,a[42]),A=l(A,x,P,C,m,23,a[43]),C=l(C,A,x,P,T,4,a[44]),P=l(P,C,A,x,_,11,a[45]),x=l(x,P,C,A,I,16,a[46]),C=p(C,A=l(A,x,P,C,h,23,a[47]),x,P,o,6,a[48]),P=p(P,C,A,x,S,10,a[49]),x=p(x,P,C,A,R,15,a[50]),A=p(A,x,P,C,v,21,a[51]),C=p(C,A,x,P,_,6,a[52]),P=p(P,C,A,x,g,10,a[53]),x=p(x,P,C,A,b,15,a[54]),A=p(A,x,P,C,c,21,a[55]),C=p(C,A,x,P,y,6,a[56]),P=p(P,C,A,x,I,10,a[57]),x=p(x,P,C,A,m,15,a[58]),A=p(A,x,P,C,w,21,a[59]),C=p(C,A,x,P,f,6,a[60]),P=p(P,C,A,x,E,10,a[61]),x=p(x,P,C,A,h,15,a[62]),A=p(A,x,P,C,T,21,a[63]),s[0]=s[0]+C|0,s[1]=s[1]+A|0,s[2]=s[2]+x|0,s[3]=s[3]+P|0},_doFinalize:function(){var t=this._data,r=t.words,i=8*this._nDataBytes,n=8*t.sigBytes;r[n>>>5]|=128<<24-n%32;var s=e.floor(i/4294967296),o=i;r[15+(n+64>>>9<<4)]=16711935&(s<<8|s>>>24)|4278255360&(s<<24|s>>>8),r[14+(n+64>>>9<<4)]=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8),t.sigBytes=4*(r.length+1),this._process();for(var a=this._hash,c=a.words,u=0;u<4;u++){var d=c[u];c[u]=16711935&(d<<8|d>>>24)|4278255360&(d<<24|d>>>8)}return a},clone:function(){var e=s.clone.call(this);return e._hash=this._hash.clone(),e}});function u(e,t,r,i,n,s,o){var a=e+(t&r|~t&i)+n+o;return(a<>>32-s)+t}function d(e,t,r,i,n,s,o){var a=e+(t&i|r&~i)+n+o;return(a<>>32-s)+t}function l(e,t,r,i,n,s,o){var a=e+(t^r^i)+n+o;return(a<>>32-s)+t}function p(e,t,r,i,n,s,o){var a=e+(r^(t|~i))+n+o;return(a<>>32-s)+t}t.MD5=s._createHelper(c),t.HmacMD5=s._createHmacHelper(c)}(Math),i.MD5)},function(e,t,r){var i;e.exports=(i=i||function(e,t){var r=Object.create||function(){function e(){}return function(t){var r;return e.prototype=t,r=new e,e.prototype=null,r}}(),i={},n=i.lib={},s=n.Base={extend:function(e){var t=r(this);return e&&t.mixIn(e),t.hasOwnProperty("init")&&this.init!==t.init||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},o=n.WordArray=s.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||c).stringify(this)},concat:function(e){var t=this.words,r=e.words,i=this.sigBytes,n=e.sigBytes;if(this.clamp(),i%4)for(var s=0;s>>2]>>>24-s%4*8&255;t[i+s>>>2]|=o<<24-(i+s)%4*8}else for(s=0;s>>2]=r[s>>>2];return this.sigBytes+=n,this},clamp:function(){var t=this.words,r=this.sigBytes;t[r>>>2]&=4294967295<<32-r%4*8,t.length=e.ceil(r/4)},clone:function(){var e=s.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var r,i=[],n=function(t){t=t;var r=987654321,i=4294967295;return function(){var n=((r=36969*(65535&r)+(r>>16)&i)<<16)+(t=18e3*(65535&t)+(t>>16)&i)&i;return n/=4294967296,(n+=.5)*(e.random()>.5?1:-1)}},s=0;s>>2]>>>24-n%4*8&255;i.push((s>>>4).toString(16)),i.push((15&s).toString(16))}return i.join("")},parse:function(e){for(var t=e.length,r=[],i=0;i>>3]|=parseInt(e.substr(i,2),16)<<24-i%8*4;return new o.init(r,t/2)}},u=a.Latin1={stringify:function(e){for(var t=e.words,r=e.sigBytes,i=[],n=0;n>>2]>>>24-n%4*8&255;i.push(String.fromCharCode(s))}return i.join("")},parse:function(e){for(var t=e.length,r=[],i=0;i>>2]|=(255&e.charCodeAt(i))<<24-i%4*8;return new o.init(r,t)}},d=a.Utf8={stringify:function(e){try{return decodeURIComponent(escape(u.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return u.parse(unescape(encodeURIComponent(e)))}},l=n.BufferedBlockAlgorithm=s.extend({reset:function(){this._data=new o.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=d.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var r=this._data,i=r.words,n=r.sigBytes,s=this.blockSize,a=n/(4*s),c=(a=t?e.ceil(a):e.max((0|a)-this._minBufferSize,0))*s,u=e.min(4*c,n);if(c){for(var d=0;d699)throw new TypeError("Invalid statusCode: "+t.statusCode);var n=t.reasonPhrase?t.reasonPhrase:i.getReasonPhrase(t.statusCode),s="SIP/2.0 "+t.statusCode+" "+n+r;t.statusCode>=100&&t.statusCode,t.statusCode;var o="From: "+e.getHeader("From")+r,a="Call-ID: "+e.callId+r,c="CSeq: "+e.cseq+" "+e.method+r,u=e.getHeaders("via").reduce((function(e,t){return e+"Via: "+t+r}),""),d="To: "+e.getHeader("to");if(t.statusCode>100&&!e.parseHeader("to").hasParam("tag")){var l=t.toTag;l||(l=i.newTag()),d+=";tag="+l}d+=r;var p="";t.supported&&(p="Supported: "+t.supported.join(", ")+r);var h="";t.userAgent&&(h="User-Agent: "+t.userAgent+r);var g="";return t.extraHeaders&&(g=t.extraHeaders.reduce((function(e,t){return e+t.trim()+r}),"")),s+=u,s+=o,s+=d,s+=c,s+=a,s+=p,s+=h,s+=g,t.body?(s+="Content-Type: "+t.body.contentType+r,s+="Content-Length: "+i.str_utf8_length(t.body.content)+r+r,s+=t.body.content):s+="Content-Length: 0\r\n\r\n",{message:s}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(2),s=r(15),o=r(6),a=r(1),c=r(36),u=r(37),d=r(38),l=r(39),p=r(40),h=r(26),g=r(41),f=r(42),v=r(43),m=r(44),S=r(45),y=r(46),T=function(e){function t(t,r,i,n){var o=e.call(this,r,i)||this;return o.initialTransaction=t,o._signalingState=s.SignalingState.Initial,o.ackWait=!1,o.delegate=n,t instanceof a.InviteServerTransaction&&(o.ackWait=!0),o.early||o.start2xxRetransmissionTimer(),o.signalingStateTransition(t.request),o.logger=r.loggerFactory.getLogger("sip.invite-dialog"),o.logger.log("INVITE dialog "+o.id+" constructed"),o}return i.__extends(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this),this._signalingState=s.SignalingState.Closed,this._offer=void 0,this._answer=void 0,this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.logger.log("INVITE dialog "+this.id+" destroyed")},Object.defineProperty(t.prototype,"sessionState",{get:function(){return this.early?s.SessionState.Early:this.ackWait?s.SessionState.AckWait:this._signalingState===s.SignalingState.Closed?s.SessionState.Terminated:s.SessionState.Confirmed},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"signalingState",{get:function(){return this._signalingState},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"offer",{get:function(){return this._offer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"answer",{get:function(){return this._answer},enumerable:!0,configurable:!0}),t.prototype.confirm=function(){this.early&&this.start2xxRetransmissionTimer(),e.prototype.confirm.call(this)},t.prototype.reConfirm=function(){this.reinviteUserAgentServer&&this.startReInvite2xxRetransmissionTimer()},t.prototype.ack=function(e){var t;if(void 0===e&&(e={}),this.logger.log("INVITE dialog "+this.id+" sending ACK request"),this.reinviteUserAgentClient){if(!(this.reinviteUserAgentClient.transaction instanceof a.InviteClientTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");t=this.reinviteUserAgentClient.transaction,this.reinviteUserAgentClient=void 0}else{if(!(this.initialTransaction instanceof a.InviteClientTransaction))throw new Error("Initial transaction not instance of InviteClientTransaction.");t=this.initialTransaction}e.cseq=t.request.cseq;var r=this.createOutgoingRequestMessage(n.C.ACK,e);return t.ackResponse(r),this.signalingStateTransition(r),{message:r}},t.prototype.bye=function(e,t){if(this.logger.log("INVITE dialog "+this.id+" sending BYE request"),this.initialTransaction instanceof a.InviteServerTransaction){if(this.early)throw new Error("UAS MUST NOT send a BYE on early dialogs.");if(this.ackWait&&this.initialTransaction.state!==a.TransactionState.Terminated)throw new Error("UAS MUST NOT send a BYE on a confirmed dialog until it has received an ACK for its 2xx response or until the server transaction times out.")}return new c.ByeUserAgentClient(this,e,t)},t.prototype.info=function(e,t){if(this.logger.log("INVITE dialog "+this.id+" sending INFO request"),this.early)throw new Error("Dialog not confirmed.");return new d.InfoUserAgentClient(this,e,t)},t.prototype.invite=function(e,t){if(this.logger.log("INVITE dialog "+this.id+" sending INVITE request"),this.early)throw new Error("Dialog not confirmed.");if(this.reinviteUserAgentClient)throw new Error("There is an ongoing re-INVITE client transaction.");if(this.reinviteUserAgentServer)throw new Error("There is an ongoing re-INVITE server transaction.");return new v.ReInviteUserAgentClient(this,e,t)},t.prototype.notify=function(e,t){if(this.logger.log("INVITE dialog "+this.id+" sending NOTIFY request"),this.early)throw new Error("Dialog not confirmed.");return new p.NotifyUserAgentClient(this,e,t)},t.prototype.prack=function(e,t){return this.logger.log("INVITE dialog "+this.id+" sending PRACK request"),new g.PrackUserAgentClient(this,e,t)},t.prototype.refer=function(e,t){if(this.logger.log("INVITE dialog "+this.id+" sending REFER request"),this.early)throw new Error("Dialog not confirmed.");return new S.ReferUserAgentClient(this,e,t)},t.prototype.receiveRequest=function(t){if(this.logger.log("INVITE dialog "+this.id+" received "+t.method+" request"),t.method===n.C.ACK){if(this.ackWait){if(this.initialTransaction instanceof a.InviteClientTransaction)return void this.logger.warn("INVITE dialog "+this.id+" received unexpected "+t.method+" request, dropping.");if(this.initialTransaction.request.cseq!==t.cseq)return void this.logger.warn("INVITE dialog "+this.id+" received unexpected "+t.method+" request, dropping.");this.ackWait=!1}else{if(!this.reinviteUserAgentServer)return void this.logger.warn("INVITE dialog "+this.id+" received unexpected "+t.method+" request, dropping.");if(this.reinviteUserAgentServer.transaction.request.cseq!==t.cseq)return void this.logger.warn("INVITE dialog "+this.id+" received unexpected "+t.method+" request, dropping.");this.reinviteUserAgentServer=void 0}return this.signalingStateTransition(t),void(this.delegate&&this.delegate.onAck&&this.delegate.onAck({message:t}))}if(this.sequenceGuard(t)){if(t.method===n.C.INVITE){if(this.reinviteUserAgentServer){var r=["Retry-After: "+(Math.floor(10*Math.random())+1)];return void this.core.replyStateless(t,{statusCode:500,extraHeaders:r})}if(this.reinviteUserAgentClient)return void this.core.replyStateless(t,{statusCode:491})}if(e.prototype.receiveRequest.call(this,t),t.method===n.C.INVITE){var i=t.parseHeader("contact");if(!i)throw new Error("Contact undefined.");if(!(i instanceof n.NameAddrHeader))throw new Error("Contact not instance of NameAddrHeader.");this.dialogState.remoteTarget=i.uri}switch(t.method){case n.C.BYE:var s=new u.ByeUserAgentServer(this,t);this.delegate&&this.delegate.onBye?this.delegate.onBye(s):s.accept(),this.dispose();break;case n.C.INFO:s=new l.InfoUserAgentServer(this,t);this.delegate&&this.delegate.onInfo?this.delegate.onInfo(s):s.reject({statusCode:469,extraHeaders:["Recv-Info :"]});break;case n.C.INVITE:s=new m.ReInviteUserAgentServer(this,t);this.signalingStateTransition(t),this.delegate&&this.delegate.onInvite?this.delegate.onInvite(s):s.reject({statusCode:488});break;case n.C.NOTIFY:s=new h.NotifyUserAgentServer(this,t);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(s):s.accept();break;case n.C.PRACK:s=new f.PrackUserAgentServer(this,t);this.delegate&&this.delegate.onPrack?this.delegate.onPrack(s):s.accept();break;case n.C.REFER:s=new y.ReferUserAgentServer(this,t);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(s):s.reject();break;default:this.logger.log("INVITE dialog "+this.id+" received unimplemented "+t.method+" request"),this.core.replyStateless(t,{statusCode:501})}}else this.logger.log("INVITE dialog "+this.id+" rejected out of order "+t.method+" request.")},t.prototype.reliableSequenceGuard=function(e){var t=e.statusCode;if(!t)throw new Error("Status code undefined");if(t>100&&t<200){var r=e.getHeader("require"),i=e.getHeader("rseq"),n=r&&r.includes("100rel")&&i?Number(i):void 0;if(n){if(this.rseq&&this.rseq+1!==n)return!1;this.rseq||(this.rseq=n)}}return!0},t.prototype.signalingStateRollback=function(){this._signalingState!==s.SignalingState.HaveLocalOffer&&this.signalingState!==s.SignalingState.HaveRemoteOffer||this._rollbackOffer&&this._rollbackAnswer&&(this._signalingState=s.SignalingState.Stable,this._offer=this._rollbackOffer,this._answer=this._rollbackAnswer)},t.prototype.signalingStateTransition=function(e){var t=n.getBody(e);if(t&&"session"===t.contentDisposition){if(this._signalingState===s.SignalingState.Stable&&(this._rollbackOffer=this._offer,this._rollbackAnswer=this._answer),e instanceof n.IncomingRequestMessage)switch(this._signalingState){case s.SignalingState.Initial:case s.SignalingState.Stable:this._signalingState=s.SignalingState.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case s.SignalingState.HaveLocalOffer:this._signalingState=s.SignalingState.Stable,this._answer=t;break;case s.SignalingState.HaveRemoteOffer:case s.SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof n.IncomingResponseMessage)switch(this._signalingState){case s.SignalingState.Initial:case s.SignalingState.Stable:this._signalingState=s.SignalingState.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case s.SignalingState.HaveLocalOffer:this._signalingState=s.SignalingState.Stable,this._answer=t;break;case s.SignalingState.HaveRemoteOffer:case s.SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof n.OutgoingRequestMessage)switch(this._signalingState){case s.SignalingState.Initial:case s.SignalingState.Stable:this._signalingState=s.SignalingState.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case s.SignalingState.HaveLocalOffer:break;case s.SignalingState.HaveRemoteOffer:this._signalingState=s.SignalingState.Stable,this._answer=t;break;case s.SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}if(n.isBody(e))switch(this._signalingState){case s.SignalingState.Initial:case s.SignalingState.Stable:this._signalingState=s.SignalingState.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case s.SignalingState.HaveLocalOffer:break;case s.SignalingState.HaveRemoteOffer:this._signalingState=s.SignalingState.Stable,this._answer=t;break;case s.SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}}},t.prototype.start2xxRetransmissionTimer=function(){var e=this;if(this.initialTransaction instanceof a.InviteServerTransaction){var t=this.initialTransaction,r=o.Timers.T1,i=function(){e.ackWait?(e.logger.log("No ACK for 2xx response received, attempting retransmission"),t.retransmitAcceptedResponse(),r=Math.min(2*r,o.Timers.T2),e.invite2xxTimer=setTimeout(i,r)):e.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(i,r);var n=function(){t.state===a.TransactionState.Terminated&&(t.removeListener("stateChanged",n),e.invite2xxTimer&&(clearTimeout(e.invite2xxTimer),e.invite2xxTimer=void 0),e.ackWait&&(e.delegate&&e.delegate.onAckTimeout?e.delegate.onAckTimeout():e.bye()))};t.addListener("stateChanged",n)}},t.prototype.startReInvite2xxRetransmissionTimer=function(){var e=this;if(this.reinviteUserAgentServer&&this.reinviteUserAgentServer.transaction instanceof a.InviteServerTransaction){var t=this.reinviteUserAgentServer.transaction,r=o.Timers.T1,i=function(){e.reinviteUserAgentServer?(e.logger.log("No ACK for 2xx response received, attempting retransmission"),t.retransmitAcceptedResponse(),r=Math.min(2*r,o.Timers.T2),e.invite2xxTimer=setTimeout(i,r)):e.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(i,r);var n=function(){t.state===a.TransactionState.Terminated&&(t.removeListener("stateChanged",n),e.invite2xxTimer&&(clearTimeout(e.invite2xxTimer),e.invite2xxTimer=void 0),e.reinviteUserAgentServer)};t.addListener("stateChanged",n)}},t}(r(18).Dialog);t.SessionDialog=T},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e){e.Initial="Initial",e.Early="Early",e.AckWait="AckWait",e.Confirmed="Confirmed",e.Terminated="Terminated"}(t.SessionState||(t.SessionState={})),function(e){e.Initial="Initial",e.HaveLocalOffer="HaveLocalOffer",e.HaveRemoteOffer="HaveRemoteOffer",e.Stable="Stable",e.Closed="Closed"}(t.SignalingState||(t.SignalingState={}))},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=function(e){function t(t){return e.call(this,t||"Transaction state error.")||this}return i.__extends(t,e),t}(r(24).Exception);t.TransactionStateError=n},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=function(e){function t(t){return e.call(this,t||"Unspecified transport error.")||this}return i.__extends(t,e),t}(r(24).Exception);t.TransportError=n},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(2),s=r(6),o=r(25),a=r(13),c=function(e){function t(t,r,i){return e.call(this,t,r,i,a.TransactionState.Proceeding,"sip.transaction.ist")||this}return i.__extends(t,e),t.prototype.dispose=function(){this.stopProgressExtensionTimer(),this.H&&(clearTimeout(this.H),this.H=void 0),this.I&&(clearTimeout(this.I),this.I=void 0),this.L&&(clearTimeout(this.L),this.L=void 0),e.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"kind",{get:function(){return"ist"},enumerable:!0,configurable:!0}),t.prototype.receiveRequest=function(e){var t=this;switch(this.state){case a.TransactionState.Proceeding:if(e.method===n.C.INVITE)return void(this.lastProvisionalResponse&&this.send(this.lastProvisionalResponse).catch((function(e){t.logTransportError(e,"Failed to send retransmission of provisional response.")})));break;case a.TransactionState.Accepted:if(e.method===n.C.INVITE)return;break;case a.TransactionState.Completed:if(e.method===n.C.INVITE){if(!this.lastFinalResponse)throw new Error("Last final response undefined.");return void this.send(this.lastFinalResponse).catch((function(e){t.logTransportError(e,"Failed to send retransmission of final response.")}))}if(e.method===n.C.ACK)return void this.stateTransition(a.TransactionState.Confirmed);break;case a.TransactionState.Confirmed:case a.TransactionState.Terminated:if(e.method===n.C.INVITE||e.method===n.C.ACK)return;break;default:throw new Error("Invalid state "+this.state)}var r="INVITE server transaction received unexpected "+e.method+" request while in state "+this.state+".";this.logger.warn(r)},t.prototype.receiveResponse=function(e,t){var r=this;if(e<100||e>699)throw new Error("Invalid status code "+e);switch(this.state){case a.TransactionState.Proceeding:if(e>=100&&e<=199)return this.lastProvisionalResponse=t,e>100&&this.startProgressExtensionTimer(),void this.send(t).catch((function(e){r.logTransportError(e,"Failed to send 1xx response.")}));if(e>=200&&e<=299)return this.lastFinalResponse=t,this.stateTransition(a.TransactionState.Accepted),void this.send(t).catch((function(e){r.logTransportError(e,"Failed to send 2xx response.")}));if(e>=300&&e<=699)return this.lastFinalResponse=t,this.stateTransition(a.TransactionState.Completed),void this.send(t).catch((function(e){r.logTransportError(e,"Failed to send non-2xx final response.")}));break;case a.TransactionState.Accepted:if(e>=200&&e<=299)return void this.send(t).catch((function(e){r.logTransportError(e,"Failed to send 2xx response.")}));break;case a.TransactionState.Completed:case a.TransactionState.Confirmed:case a.TransactionState.Terminated:break;default:throw new Error("Invalid state "+this.state)}var i="INVITE server transaction received unexpected "+e+" response from TU while in state "+this.state+".";throw this.logger.error(i),new Error(i)},t.prototype.retransmitAcceptedResponse=function(){var e=this;this.state===a.TransactionState.Accepted&&this.lastFinalResponse&&this.send(this.lastFinalResponse).catch((function(t){e.logTransportError(t,"Failed to send 2xx response.")}))},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e)},t.prototype.typeToString=function(){return"INVITE server transaction"},t.prototype.stateTransition=function(e){var t=this,r=function(){throw new Error("Invalid state transition from "+t.state+" to "+e)};switch(e){case a.TransactionState.Proceeding:r();break;case a.TransactionState.Accepted:case a.TransactionState.Completed:this.state!==a.TransactionState.Proceeding&&r();break;case a.TransactionState.Confirmed:this.state!==a.TransactionState.Completed&&r();break;case a.TransactionState.Terminated:this.state!==a.TransactionState.Accepted&&this.state!==a.TransactionState.Completed&&this.state!==a.TransactionState.Confirmed&&r();break;default:r()}this.stopProgressExtensionTimer(),e===a.TransactionState.Accepted&&(this.L=setTimeout((function(){return t.timer_L()}),s.Timers.TIMER_L)),e===a.TransactionState.Completed&&(this.H=setTimeout((function(){return t.timer_H()}),s.Timers.TIMER_H)),e===a.TransactionState.Confirmed&&(this.I=setTimeout((function(){return t.timer_I()}),s.Timers.TIMER_I)),e===a.TransactionState.Terminated&&this.dispose(),this.setState(e)},t.prototype.startProgressExtensionTimer=function(){var e=this;void 0===this.progressExtensionTimer&&(this.progressExtensionTimer=setInterval((function(){if(e.logger.debug("Progress extension timer expired for INVITE server transaction "+e.id+"."),!e.lastProvisionalResponse)throw new Error("Last provisional response undefined.");e.send(e.lastProvisionalResponse).catch((function(t){e.logTransportError(t,"Failed to send retransmission of provisional response.")}))}),s.Timers.PROVISIONAL_RESPONSE_INTERVAL))},t.prototype.stopProgressExtensionTimer=function(){void 0!==this.progressExtensionTimer&&(clearInterval(this.progressExtensionTimer),this.progressExtensionTimer=void 0)},t.prototype.timer_G=function(){},t.prototype.timer_H=function(){this.logger.debug("Timer H expired for INVITE server transaction "+this.id+"."),this.state===a.TransactionState.Completed&&(this.logger.warn("ACK to negative final response was never received, terminating transaction."),this.stateTransition(a.TransactionState.Terminated))},t.prototype.timer_I=function(){this.logger.debug("Timer I expired for INVITE server transaction "+this.id+"."),this.stateTransition(a.TransactionState.Terminated)},t.prototype.timer_L=function(){this.logger.debug("Timer L expired for INVITE server transaction "+this.id+"."),this.state===a.TransactionState.Accepted&&this.stateTransition(a.TransactionState.Terminated)},t}(o.ServerTransaction);t.InviteServerTransaction=c},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(6),s=r(22),o=r(13),a=function(e){function t(t,r,i){var s=e.call(this,t,r,i,o.TransactionState.Trying,"sip.transaction.nict")||this;return s.F=setTimeout((function(){return s.timer_F()}),n.Timers.TIMER_F),s.send(t.toString()).catch((function(e){s.logTransportError(e,"Failed to send initial outgoing request.")})),s}return i.__extends(t,e),t.prototype.dispose=function(){this.F&&(clearTimeout(this.F),this.F=void 0),this.K&&(clearTimeout(this.K),this.K=void 0),e.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"kind",{get:function(){return"nict"},enumerable:!0,configurable:!0}),t.prototype.receiveResponse=function(e){var t=e.statusCode;if(!t||t<100||t>699)throw new Error("Invalid status code "+t);switch(this.state){case o.TransactionState.Trying:if(t>=100&&t<=199)return this.stateTransition(o.TransactionState.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=699)return this.stateTransition(o.TransactionState.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case o.TransactionState.Proceeding:if(t>=100&&t<=199&&this.user.receiveResponse)return this.user.receiveResponse(e);if(t>=200&&t<=699)return this.stateTransition(o.TransactionState.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));case o.TransactionState.Completed:case o.TransactionState.Terminated:return;default:throw new Error("Invalid state "+this.state)}var r="Non-INVITE client transaction received unexpected "+t+" response while in state "+this.state+".";this.logger.warn(r)},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(o.TransactionState.Terminated,!0)},t.prototype.typeToString=function(){return"non-INVITE client transaction"},t.prototype.stateTransition=function(e,t){var r=this;void 0===t&&(t=!1);var i=function(){throw new Error("Invalid state transition from "+r.state+" to "+e)};switch(e){case o.TransactionState.Trying:i();break;case o.TransactionState.Proceeding:this.state!==o.TransactionState.Trying&&i();break;case o.TransactionState.Completed:this.state!==o.TransactionState.Trying&&this.state!==o.TransactionState.Proceeding&&i();break;case o.TransactionState.Terminated:this.state!==o.TransactionState.Trying&&this.state!==o.TransactionState.Proceeding&&this.state!==o.TransactionState.Completed&&(t||i());break;default:i()}e===o.TransactionState.Completed&&(this.F&&(clearTimeout(this.F),this.F=void 0),this.K=setTimeout((function(){return r.timer_K()}),n.Timers.TIMER_K)),e===o.TransactionState.Terminated&&this.dispose(),this.setState(e)},t.prototype.timer_F=function(){this.logger.debug("Timer F expired for non-INVITE client transaction "+this.id+"."),this.state!==o.TransactionState.Trying&&this.state!==o.TransactionState.Proceeding||(this.onRequestTimeout(),this.stateTransition(o.TransactionState.Terminated))},t.prototype.timer_K=function(){this.state===o.TransactionState.Completed&&this.stateTransition(o.TransactionState.Terminated)},t}(s.ClientTransaction);t.NonInviteClientTransaction=a},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(6),s=r(25),o=r(13),a=function(e){function t(t,r,i){return e.call(this,t,r,i,o.TransactionState.Trying,"sip.transaction.nist")||this}return i.__extends(t,e),t.prototype.dispose=function(){this.J&&(clearTimeout(this.J),this.J=void 0),e.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"kind",{get:function(){return"nist"},enumerable:!0,configurable:!0}),t.prototype.receiveRequest=function(e){var t=this;switch(this.state){case o.TransactionState.Trying:break;case o.TransactionState.Proceeding:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch((function(e){t.logTransportError(e,"Failed to send retransmission of provisional response.")}));break;case o.TransactionState.Completed:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch((function(e){t.logTransportError(e,"Failed to send retransmission of final response.")}));break;case o.TransactionState.Terminated:break;default:throw new Error("Invalid state "+this.state)}},t.prototype.receiveResponse=function(e,t){var r=this;if(e<100||e>699)throw new Error("Invalid status code "+e);if(e>100&&e<=199)throw new Error("Provisional response other than 100 not allowed.");switch(this.state){case o.TransactionState.Trying:if(this.lastResponse=t,e>=100&&e<200)return this.stateTransition(o.TransactionState.Proceeding),void this.send(t).catch((function(e){r.logTransportError(e,"Failed to send provisional response.")}));if(e>=200&&e<=699)return this.stateTransition(o.TransactionState.Completed),void this.send(t).catch((function(e){r.logTransportError(e,"Failed to send final response.")}));break;case o.TransactionState.Proceeding:if(this.lastResponse=t,e>=200&&e<=699)return this.stateTransition(o.TransactionState.Completed),void this.send(t).catch((function(e){r.logTransportError(e,"Failed to send final response.")}));break;case o.TransactionState.Completed:return;case o.TransactionState.Terminated:break;default:throw new Error("Invalid state "+this.state)}var i="Non-INVITE server transaction received unexpected "+e+" response from TU while in state "+this.state+".";throw this.logger.error(i),new Error(i)},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(o.TransactionState.Terminated,!0)},t.prototype.typeToString=function(){return"non-INVITE server transaction"},t.prototype.stateTransition=function(e,t){var r=this;void 0===t&&(t=!1);var i=function(){throw new Error("Invalid state transition from "+r.state+" to "+e)};switch(e){case o.TransactionState.Trying:i();break;case o.TransactionState.Proceeding:this.state!==o.TransactionState.Trying&&i();break;case o.TransactionState.Completed:this.state!==o.TransactionState.Trying&&this.state!==o.TransactionState.Proceeding&&i();break;case o.TransactionState.Terminated:this.state!==o.TransactionState.Proceeding&&this.state!==o.TransactionState.Completed&&(t||i());break;default:i()}e===o.TransactionState.Completed&&(this.J=setTimeout((function(){return r.timer_J()}),n.Timers.TIMER_J)),e===o.TransactionState.Terminated&&this.dispose(),this.setState(e)},t.prototype.timer_J=function(){this.logger.debug("Timer J expired for NON-INVITE server transaction "+this.id+"."),this.state===o.TransactionState.Completed&&this.stateTransition(o.TransactionState.Terminated)},t}(s.ServerTransaction);t.NonInviteServerTransaction=a},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e){e.Initial="Initial",e.NotifyWait="NotifyWait",e.Pending="Pending",e.Active="Active",e.Terminated="Terminated"}(t.SubscriptionState||(t.SubscriptionState={}))},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0);i.__exportStar(r(28),t),i.__exportStar(r(72),t),i.__exportStar(r(49),t)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(28),n=r(49),s=function(){function e(){this.builtinEnabled=!0,this._level=i.Levels.log,this.loggers={},this.logger=this.getLogger("sip:loggerfactory")}return Object.defineProperty(e.prototype,"level",{get:function(){return this._level},set:function(e){e>=0&&e<=3?this._level=e:e>3?this._level=3:i.Levels.hasOwnProperty(e)?this._level=e:this.logger.error("invalid 'level' parameter value: "+JSON.stringify(e))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"connector",{get:function(){return this._connector},set:function(e){e?"function"==typeof e?this._connector=e:this.logger.error("invalid 'connector' parameter value: "+JSON.stringify(e)):this._connector=void 0},enumerable:!0,configurable:!0}),e.prototype.getLogger=function(e,t){if(t&&3===this.level)return new n.Logger(this,e,t);if(this.loggers[e])return this.loggers[e];var r=new n.Logger(this,e);return this.loggers[e]=r,r},e.prototype.genericLog=function(e,t,r,n){this.level>=e&&this.builtinEnabled&&this.print(e,t,r,n),this.connector&&this.connector(i.Levels[e],t,r,n)},e.prototype.print=function(e,t,r,n){if("string"==typeof n){var s=[new Date,t];r&&s.push(r),n=s.concat(n).join(" | ")}switch(e){case i.Levels.error:console.error(n);break;case i.Levels.warn:console.warn(n);break;case i.Levels.log:console.log(n);break;case i.Levels.debug:console.debug(n)}},e}();t.LoggerFactory=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),r(0).__exportStar(r(74),t)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(2),s=r(1),o=r(50),a=r(14),c=["application/sdp","application/dtmf-relay"],u=function(){function e(e,t){void 0===t&&(t={}),this.userAgentClients=new Map,this.userAgentServers=new Map,this.configuration=e,this.delegate=t,this.dialogs=new Map,this.subscribers=new Map,this.logger=e.loggerFactory.getLogger("sip.user-agent-core")}return e.prototype.dispose=function(){this.reset()},e.prototype.reset=function(){this.dialogs.forEach((function(e){return e.dispose()})),this.dialogs.clear(),this.subscribers.forEach((function(e){return e.dispose()})),this.subscribers.clear(),this.userAgentClients.forEach((function(e){return e.dispose()})),this.userAgentClients.clear(),this.userAgentServers.forEach((function(e){return e.dispose()})),this.userAgentServers.clear()},Object.defineProperty(e.prototype,"loggerFactory",{get:function(){return this.configuration.loggerFactory},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"transport",{get:function(){var e=this.configuration.transportAccessor();if(!e)throw new Error("Transport undefined.");return e},enumerable:!0,configurable:!0}),e.prototype.invite=function(e,t){return new o.InviteUserAgentClient(this,e,t)},e.prototype.message=function(e,t){return new o.MessageUserAgentClient(this,e,t)},e.prototype.publish=function(e,t){return new o.PublishUserAgentClient(this,e,t)},e.prototype.register=function(e,t){return new o.RegisterUserAgentClient(this,e,t)},e.prototype.subscribe=function(e,t){return new o.SubscribeUserAgentClient(this,e,t)},e.prototype.request=function(e,t){return new o.UserAgentClient(s.NonInviteClientTransaction,this,e,t)},e.prototype.makeOutgoingRequestMessage=function(e,t,r,s,o,a,c){var u=this.configuration.sipjsId,d=this.configuration.displayName,l=this.configuration.viaForceRport,p=this.configuration.hackViaTcp,h=this.configuration.supportedOptionTags.slice();e===n.C.REGISTER&&h.push("path","gruu"),e===n.C.INVITE&&(this.configuration.contact.pubGruu||this.configuration.contact.tempGruu)&&h.push("gruu");var g={callIdPrefix:u,forceRport:l,fromDisplayName:d,hackViaTcp:p,optionTags:h,routeSet:this.configuration.routeSet,userAgentString:this.configuration.userAgentHeaderFieldValue,viaHost:this.configuration.viaHost},f=i.__assign({},g,o);return new n.OutgoingRequestMessage(e,t,r,s,f,a,c)},e.prototype.receiveIncomingRequestFromTransport=function(e){this.receiveRequestFromTransport(e)},e.prototype.receiveIncomingResponseFromTransport=function(e){this.receiveResponseFromTransport(e)},e.prototype.replyStateless=function(e,t){var r=this.configuration.userAgentHeaderFieldValue,s=this.configuration.supportedOptionTagsResponse;t=i.__assign({},t,{userAgent:r,supported:s});var o=n.constructOutgoingResponse(e,t);return this.transport.send(o.message),o},e.prototype.receiveRequestFromTransport=function(e){var t=e.viaBranch,r=this.userAgentServers.get(t);e.method===n.C.ACK&&r&&r.transaction.state===s.TransactionState.Accepted&&r instanceof o.InviteUserAgentServer?this.logger.warn("Discarding out of dialog ACK after 2xx response sent on transaction "+t+"."):e.method!==n.C.CANCEL?r?r.transaction.receiveRequest(e):this.receiveRequest(e):r?(this.replyStateless(e,{statusCode:200}),r.transaction instanceof s.InviteServerTransaction&&r.transaction.state===s.TransactionState.Proceeding&&r instanceof o.InviteUserAgentServer&&r.receiveCancel(e)):this.replyStateless(e,{statusCode:481})},e.prototype.receiveRequest=function(e){if(a.AllowedMethods.includes(e.method)){if(!e.ruri)throw new Error("Request-URI undefined.");if("sip"===e.ruri.scheme){var t=e.ruri,r=function(e){return!!e&&e.user===t.user};if(!r(this.configuration.aor)&&!(r(this.configuration.contact.uri)||r(this.configuration.contact.pubGruu)||r(this.configuration.contact.tempGruu)))return this.logger.warn("Request-URI does not point to us."),void(e.method!==n.C.ACK&&this.replyStateless(e,{statusCode:404}));if(e.method!==n.C.INVITE||e.hasHeader("Contact")){if(!e.toTag){var i=e.viaBranch;if(!this.userAgentServers.has(i))if(Array.from(this.userAgentServers.values()).some((function(t){return t.transaction.request.fromTag===e.fromTag&&t.transaction.request.callId===e.callId&&t.transaction.request.cseq===e.cseq})))return void this.replyStateless(e,{statusCode:482})}e.toTag?this.receiveInsideDialogRequest(e):this.receiveOutsideDialogRequest(e)}else this.replyStateless(e,{statusCode:400,reasonPhrase:"Missing Contact Header"})}else this.replyStateless(e,{statusCode:416})}else{var s="Allow: "+a.AllowedMethods.toString();this.replyStateless(e,{statusCode:405,extraHeaders:[s]})}},e.prototype.receiveInsideDialogRequest=function(e){if(e.method===n.C.NOTIFY){var t=e.parseHeader("Event");if(!t||!t.event)return void this.replyStateless(e,{statusCode:489});var r=e.callId+e.toTag+t.event,i=this.subscribers.get(r);if(i){var s=new o.NotifyUserAgentServer(this,e);return void i.onNotify(s)}}var u=e.callId+e.toTag+e.fromTag,d=this.dialogs.get(u);if(d){if(e.method===n.C.OPTIONS){var l="Allow: "+a.AllowedMethods.toString(),p="Accept: "+c.toString();return void this.replyStateless(e,{statusCode:200,extraHeaders:[l,p]})}d.receiveRequest(e)}else e.method!==n.C.ACK&&this.replyStateless(e,{statusCode:481})},e.prototype.receiveOutsideDialogRequest=function(e){switch(e.method){case n.C.ACK:break;case n.C.BYE:this.replyStateless(e,{statusCode:481});break;case n.C.CANCEL:throw new Error("Unexpected out of dialog request method "+e.method+".");case n.C.INFO:this.replyStateless(e,{statusCode:405});break;case n.C.INVITE:var t=new o.InviteUserAgentServer(this,e);this.delegate.onInvite?this.delegate.onInvite(t):t.reject();break;case n.C.MESSAGE:t=new o.MessageUserAgentServer(this,e);this.delegate.onMessage?this.delegate.onMessage(t):t.accept();break;case n.C.NOTIFY:t=new o.NotifyUserAgentServer(this,e);this.delegate.onNotify?this.delegate.onNotify(t):t.reject({statusCode:405});break;case n.C.OPTIONS:var r="Allow: "+a.AllowedMethods.toString(),i="Accept: "+c.toString();this.replyStateless(e,{statusCode:200,extraHeaders:[r,i]});break;case n.C.REFER:t=new o.ReferUserAgentServer(this,e);this.delegate.onRefer?this.delegate.onRefer(t):t.reject({statusCode:405});break;case n.C.REGISTER:t=new o.RegisterUserAgentServer(this,e);this.delegate.onRegister?this.delegate.onRegister(t):t.reject({statusCode:405});break;case n.C.SUBSCRIBE:t=new o.SubscribeUserAgentServer(this,e);this.delegate.onSubscribe?this.delegate.onSubscribe(t):t.reject({statusCode:480});break;default:throw new Error("Unexpected out of dialog request method "+e.method+".")}},e.prototype.receiveResponseFromTransport=function(e){if(e.getHeaders("via").length>1)this.logger.warn("More than one Via header field present in the response, dropping");else{var t=e.viaBranch+e.method,r=this.userAgentClients.get(t);r?r.transaction.receiveResponse(e):this.logger.warn("Discarding unmatched "+e.statusCode+" response to "+e.method+" "+t+".")}},e}();t.UserAgentCore=u},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){return e.call(this,n.NonInviteClientTransaction,t,r,i)||this}return i.__extends(t,e),t}(r(3).UserAgentClient);t.CancelUserAgentClient=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(17),s=r(15),o=r(1),a=function(e){function t(t,r,i){var n=e.call(this,o.InviteClientTransaction,t,r,i)||this;return n.confirmedDialogAcks=new Map,n.confirmedDialogs=new Map,n.earlyDialogs=new Map,n.delegate=i,n}return i.__extends(t,e),t.prototype.dispose=function(){this.earlyDialogs.forEach((function(e){return e.dispose()})),this.earlyDialogs.clear(),e.prototype.dispose.call(this)},t.prototype.receiveResponse=function(e){var t=this;if(this.authenticationGuard(e)){var r=e.statusCode?e.statusCode.toString():"";if(!r)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(r):return void(this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e}));case/^1[0-9]{2}$/.test(r):if(!e.toTag)return void this.logger.warn("Non-100 1xx INVITE response received without a to tag, dropping.");var i=n.Dialog.initialDialogStateForUserAgentClient(this.message,e),a=this.earlyDialogs.get(i.id);if(!a){if(!((d=this.transaction)instanceof o.InviteClientTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");a=new n.SessionDialog(d,this.core,i),this.earlyDialogs.set(a.id,a)}if(!a.reliableSequenceGuard(e))return void this.logger.warn("1xx INVITE reliable response received out of order, dropping.");a.signalingState!==s.SignalingState.Initial&&a.signalingState!==s.SignalingState.HaveLocalOffer||a.signalingStateTransition(e);var c=a;return void(this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:c,prack:function(e){return c.prack(void 0,e)}}));case/^2[0-9]{2}$/.test(r):i=n.Dialog.initialDialogStateForUserAgentClient(this.message,e);var u=this.confirmedDialogs.get(i.id);if(u){if(p=this.confirmedDialogAcks.get(i.id)){if(!((d=this.transaction)instanceof o.InviteClientTransaction))throw new Error("Client transaction not instance of InviteClientTransaction.");d.ackResponse(p.message)}return}if(u=this.earlyDialogs.get(i.id))u.confirm(),u.recomputeRouteSet(e),this.earlyDialogs.delete(u.id),this.confirmedDialogs.set(u.id,u);else{var d;if(!((d=this.transaction)instanceof o.InviteClientTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");u=new n.SessionDialog(d,this.core,i),this.confirmedDialogs.set(u.id,u)}u.signalingState!==s.SignalingState.Initial&&u.signalingState!==s.SignalingState.HaveLocalOffer||u.signalingStateTransition(e);var l=u;if(this.delegate&&this.delegate.onAccept)this.delegate.onAccept({message:e,session:l,ack:function(e){var r=l.ack(e);return t.confirmedDialogAcks.set(l.id,r),r}});else{var p=l.ack();this.confirmedDialogAcks.set(l.id,p)}return;case/^3[0-9]{2}$/.test(r):return this.earlyDialogs.forEach((function(e){return e.dispose()})),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e}));case/^[4-6][0-9]{2}$/.test(r):return this.earlyDialogs.forEach((function(e){return e.dispose()})),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e}));default:throw new Error("Invalid status code "+r)}throw new Error("Executing what should be an unreachable code path receiving "+r+" response.")}},t}(r(3).UserAgentClient);t.InviteUserAgentClient=a},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(17),s=r(16),o=r(15),a=r(1),c=r(14),u=function(e){function t(t,r,i){var n=e.call(this,a.InviteServerTransaction,t,r,i)||this;return n.core=t,n}return i.__extends(t,e),t.prototype.dispose=function(){this.earlyDialog&&this.earlyDialog.dispose(),e.prototype.dispose.call(this)},t.prototype.accept=function(t){if(void 0===t&&(t={statusCode:200}),!this.acceptable)throw new s.TransactionStateError(this.message.method+" not acceptable in state "+this.transaction.state+".");if(!this.confirmedDialog)if(this.earlyDialog)this.earlyDialog.confirm(),this.confirmedDialog=this.earlyDialog,this.earlyDialog=void 0;else{var r=this.transaction;if(!(r instanceof a.InviteServerTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");var u=n.Dialog.initialDialogStateForUserAgentServer(this.message,this.toTag);this.confirmedDialog=new n.SessionDialog(r,this.core,u)}var d=this.message.getHeaders("record-route").map((function(e){return"Record-Route: "+e})),l="Contact: "+this.core.configuration.contact.toString(),p="Allow: "+c.AllowedMethods.toString();if(!t.body)if(this.confirmedDialog.signalingState===o.SignalingState.Stable)t.body=this.confirmedDialog.answer;else if(this.confirmedDialog.signalingState===o.SignalingState.Initial||this.confirmedDialog.signalingState===o.SignalingState.HaveRemoteOffer)throw new Error("Response must have a body.");t.statusCode=t.statusCode||200,t.extraHeaders=t.extraHeaders||[],t.extraHeaders=t.extraHeaders.concat(d),t.extraHeaders.push(p),t.extraHeaders.push(l);var h=e.prototype.accept.call(this,t),g=this.confirmedDialog,f=i.__assign({},h,{session:g});return t.body&&this.confirmedDialog.signalingState!==o.SignalingState.Stable&&this.confirmedDialog.signalingStateTransition(t.body),f},t.prototype.progress=function(t){if(void 0===t&&(t={statusCode:180}),!this.progressable)throw new s.TransactionStateError(this.message.method+" not progressable in state "+this.transaction.state+".");if(!this.earlyDialog){var r=this.transaction;if(!(r instanceof a.InviteServerTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");var c=n.Dialog.initialDialogStateForUserAgentServer(this.message,this.toTag,!0);this.earlyDialog=new n.SessionDialog(r,this.core,c)}var u=this.message.getHeaders("record-route").map((function(e){return"Record-Route: "+e})),d="Contact: "+this.core.configuration.contact;t.extraHeaders=t.extraHeaders||[],t.extraHeaders=t.extraHeaders.concat(u),t.extraHeaders.push(d);var l=e.prototype.progress.call(this,t),p=this.earlyDialog,h=i.__assign({},l,{session:p});return t.body&&this.earlyDialog.signalingState!==o.SignalingState.Stable&&this.earlyDialog.signalingStateTransition(t.body),h},t.prototype.redirect=function(t,r){return void 0===r&&(r={statusCode:302}),e.prototype.redirect.call(this,t,r)},t.prototype.reject=function(t){return void 0===t&&(t={statusCode:486}),e.prototype.reject.call(this,t)},t}(r(4).UserAgentServer);t.InviteUserAgentServer=u},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){return e.call(this,n.NonInviteClientTransaction,t,r,i)||this}return i.__extends(t,e),t}(r(3).UserAgentClient);t.MessageUserAgentClient=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){var s=e.call(this,n.NonInviteServerTransaction,t,r,i)||this;return s.core=t,s}return i.__extends(t,e),t}(r(4).UserAgentServer);t.MessageUserAgentServer=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){return e.call(this,n.NonInviteClientTransaction,t,r,i)||this}return i.__extends(t,e),t}(r(3).UserAgentClient);t.PublishUserAgentClient=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){return e.call(this,n.NonInviteServerTransaction,t.userAgentCore,r,i)||this}return i.__extends(t,e),t}(r(4).UserAgentServer);t.ReSubscribeUserAgentServer=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){return e.call(this,n.NonInviteClientTransaction,t,r,i)||this}return i.__extends(t,e),t}(r(3).UserAgentClient);t.RegisterUserAgentClient=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){var s=e.call(this,n.NonInviteServerTransaction,t,r,i)||this;return s.core=t,s}return i.__extends(t,e),t}(r(4).UserAgentServer);t.RegisterUserAgentServer=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(47),s=r(27),o=r(6),a=r(1),c=function(e){function t(t,r,i){var n=this,o=r.getHeader("Event");if(!o)throw new Error("Event undefined");var c=r.getHeader("Expires");if(!c)throw new Error("Expires undefined");return(n=e.call(this,a.NonInviteClientTransaction,t,r,i)||this).delegate=i,n.subscriberId=r.callId+r.fromTag+o,n.subscriptionExpiresRequested=n.subscriptionExpires=Number(c),n.subscriptionEvent=o,n.subscriptionState=s.SubscriptionState.NotifyWait,n.waitNotifyStart(),n}return i.__extends(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this)},t.prototype.onNotify=function(e){var t=e.message.parseHeader("Event").event;if(!t||t!==this.subscriptionEvent)return this.logger.warn("Failed to parse event."),void e.reject({statusCode:489});var r=e.message.parseHeader("Subscription-State");if(!r||!r.state)return this.logger.warn("Failed to parse subscription state."),void e.reject({statusCode:489});var i=r.state;switch(i){case"pending":case"active":case"terminated":break;default:return this.logger.warn("Invalid subscription state "+i),void e.reject({statusCode:489})}if("terminated"!==i&&!e.message.parseHeader("contact"))return this.logger.warn("Failed to parse contact."),void e.reject({statusCode:489});if(this.dialog)throw new Error("Dialog already created. This implementation only supports install of single subscriptions.");switch(this.waitNotifyStop(),this.subscriptionExpires=r.expires?Math.min(this.subscriptionExpires,Math.max(r.expires,0)):this.subscriptionExpires,i){case"pending":this.subscriptionState=s.SubscriptionState.Pending;break;case"active":this.subscriptionState=s.SubscriptionState.Active;break;case"terminated":this.subscriptionState=s.SubscriptionState.Terminated;break;default:throw new Error("Unrecognized state "+i+".")}if(this.subscriptionState!==s.SubscriptionState.Terminated){var o=n.SubscriptionDialog.initialDialogStateForSubscription(this.message,e.message);this.dialog=new n.SubscriptionDialog(this.subscriptionEvent,this.subscriptionExpires,this.subscriptionState,this.core,o)}if(this.delegate&&this.delegate.onNotify){var a=e,c=this.dialog;this.delegate.onNotify({request:a,subscription:c})}else e.accept()},t.prototype.waitNotifyStart=function(){var e=this;this.N||(this.core.subscribers.set(this.subscriberId,this),this.N=setTimeout((function(){return e.timer_N()}),o.Timers.TIMER_N))},t.prototype.waitNotifyStop=function(){this.N&&(this.core.subscribers.delete(this.subscriberId),clearTimeout(this.N),this.N=void 0)},t.prototype.receiveResponse=function(t){if(this.authenticationGuard(t)){if(t.statusCode&&t.statusCode>=200&&t.statusCode<300){var r=t.getHeader("Expires");if(r){var i=Number(r);i>this.subscriptionExpiresRequested&&this.logger.warn("Expires header in a 200-class response to SUBSCRIBE with a higher value than the one in the request"),ithis.subscriptionExpires&&(this.dialog.subscriptionExpires=this.subscriptionExpires)}t.statusCode&&t.statusCode>=300&&t.statusCode<700&&this.waitNotifyStop(),e.prototype.receiveResponse.call(this,t)}},t.prototype.timer_N=function(){this.logger.warn("Timer N expired for SUBSCRIBE user agent client. Timed out waiting for NOTIFY."),this.waitNotifyStop(),this.delegate&&this.delegate.onNotifyTimeout&&this.delegate.onNotifyTimeout()},t}(r(3).UserAgentClient);t.SubscribeUserAgentClient=c},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){var s=e.call(this,n.NonInviteServerTransaction,t,r,i)||this;return s.core=t,s}return i.__extends(t,e),t}(r(4).UserAgentServer);t.SubscribeUserAgentServer=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=function(e){function t(t,r){var i=e.call(this)||this;return i.logger=t,i}return i.__extends(t,e),t.prototype.connect=function(e){var t=this;return void 0===e&&(e={}),this.connectPromise(e).then((function(e){e.overrideEvent||t.emit("connected")}))},t.prototype.send=function(e,t){var r=this;return void 0===t&&(t={}),this.sendPromise(e).then((function(e){e.overrideEvent||r.emit("messageSent",e.msg)}))},t.prototype.disconnect=function(e){var t=this;return void 0===e&&(e={}),this.disconnectPromise(e).then((function(e){e.overrideEvent||t.emit("disconnected")}))},t.prototype.afterConnected=function(e){this.isConnected()?e():this.once("connected",e)},t.prototype.waitForConnected=function(){var e=this;return console.warn("DEPRECATION WARNING Transport.waitForConnected(): use afterConnected() instead"),new Promise((function(t){e.afterConnected(t)}))},t}(r(7).EventEmitter);t.Transport=n},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=function(e,t){for(var r,i=[],n=e.split(/\r\n/),s=0;s0&&(this.dtmfSender=r[0].dtmf)}if(!this.dtmfSender&&this.hasBrowserTrackSupport()){var i=this.peerConnection.getLocalStreams();if(i.length>0){var n=i[0].getAudioTracks();n.length>0&&(this.dtmfSender=this.peerConnection.createDTMFSender(n[0]))}}if(!this.dtmfSender)return!1;try{this.dtmfSender.insertDTMF(e,t.duration,t.interToneGap)}catch(e){if("InvalidStateError"===e.type||"InvalidCharacterError"===e.type)return this.logger.error(e),!1;throw e}return this.logger.log("DTMF sent via RTP: "+e.toString()),!0},t.prototype.getDirection=function(){return this.direction},t.prototype.on=function(t,r){return e.prototype.on.call(this,t,r)},t.prototype.getMediaStream=function(e){return navigator.mediaDevices.getUserMedia(e)},t.prototype.createOfferOrAnswer=function(e,t){var r=this;void 0===e&&(e={}),void 0===t&&(t=[]);var i=this.hasOffer("remote")?"createAnswer":"createOffer",n=this.peerConnection;return this.logger.log(i),(this.hasOffer("remote")?n.createAnswer:n.createOffer).apply(n,e).catch((function(e){if(e.type===o.TypeStrings.SessionDescriptionHandlerError)throw e;var t=new a.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer",e,"peerConnection-"+i+"Failed");throw r.emit("peerConnection-"+i+"Failed",t),t})).then((function(e){return c.Utils.reducePromises(t,r.createRTCSessionDescriptionInit(e))})).then((function(e){return r.resetIceGatheringComplete(),r.logger.log("Setting local sdp."),r.logger.log("sdp is "+e.sdp||!1),n.setLocalDescription(e)})).catch((function(e){if(e.type===o.TypeStrings.SessionDescriptionHandlerError)throw e;var t=new a.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer",e,"peerConnection-SetLocalDescriptionFailed");throw r.emit("peerConnection-SetLocalDescriptionFailed",t),t})).then((function(){return r.waitForIceGatheringComplete()})).then((function(){if(!r.peerConnection.localDescription)throw new a.Exceptions.SessionDescriptionHandlerError("Missing local description");var e=r.createRTCSessionDescriptionInit(r.peerConnection.localDescription);return c.Utils.reducePromises(t,e)})).then((function(e){return r.setDirection(e.sdp||""),e})).catch((function(e){if(e.type===o.TypeStrings.SessionDescriptionHandlerError)throw e;var t=new a.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer",e);throw r.logger.error(t.toString()),t}))},t.prototype.createRTCSessionDescriptionInit=function(e){return{type:e.type,sdp:e.sdp}},t.prototype.addDefaultIceCheckingTimeout=function(e){return void 0===e.iceCheckingTimeout&&(e.iceCheckingTimeout=5e3),e},t.prototype.addDefaultIceServers=function(e){return e.iceServers||(e.iceServers=[{urls:"stun:stun.l.google.com:19302"}]),e},t.prototype.checkAndDefaultConstraints=function(e){var t={audio:!0,video:!this.options.alwaysAcquireMediaFirst};return e=e||t,0===Object.keys(e).length&&e.constructor===Object?t:e},t.prototype.hasBrowserTrackSupport=function(){return Boolean(this.peerConnection.addTrack)},t.prototype.hasBrowserGetSenderSupport=function(){return Boolean(this.peerConnection.getSenders)},t.prototype.initPeerConnection=function(e){var t=this;void 0===e&&(e={}),(e=this.addDefaultIceCheckingTimeout(e)).rtcConfiguration=e.rtcConfiguration||{},e.rtcConfiguration=this.addDefaultIceServers(e.rtcConfiguration),this.logger.log("initPeerConnection"),this.peerConnection&&(this.logger.log("Already have a peer connection for this session. Tearing down."),this.resetIceGatheringComplete(),this.peerConnection.close()),this.peerConnection=new RTCPeerConnection(e.rtcConfiguration),this.logger.log("New peer connection created"),"ontrack"in this.peerConnection?this.peerConnection.addEventListener("track",(function(e){t.logger.log("track added"),t.observer.trackAdded(),t.emit("addTrack",e)})):(this.logger.warn("Using onaddstream which is deprecated"),this.peerConnection.onaddstream=function(e){t.logger.log("stream added"),t.emit("addStream",e)}),this.peerConnection.onicecandidate=function(e){t.emit("iceCandidate",e),e.candidate?t.logger.log("ICE candidate received: "+(null===e.candidate.candidate?null:e.candidate.candidate.trim())):null===e.candidate&&(t.logger.log("ICE candidate gathering complete"),t.triggerIceGatheringComplete())},this.peerConnection.onicegatheringstatechange=function(){switch(t.logger.log("RTCIceGatheringState changed: "+t.peerConnection.iceGatheringState),t.peerConnection.iceGatheringState){case"gathering":t.emit("iceGathering",t),!t.iceGatheringTimer&&e.iceCheckingTimeout&&(t.iceGatheringTimeout=!1,t.iceGatheringTimer=setTimeout((function(){t.logger.log("RTCIceChecking Timeout Triggered after "+e.iceCheckingTimeout+" milliseconds"),t.iceGatheringTimeout=!0,t.triggerIceGatheringComplete()}),e.iceCheckingTimeout));break;case"complete":t.triggerIceGatheringComplete()}},this.peerConnection.oniceconnectionstatechange=function(){var e;switch(t.peerConnection.iceConnectionState){case"new":e="iceConnection";break;case"checking":e="iceConnectionChecking";break;case"connected":e="iceConnectionConnected";break;case"completed":e="iceConnectionCompleted";break;case"failed":e="iceConnectionFailed";break;case"disconnected":e="iceConnectionDisconnected";break;case"closed":e="iceConnectionClosed";break;default:return void t.logger.warn("Unknown iceConnection state: "+t.peerConnection.iceConnectionState)}t.logger.log("ICE Connection State changed to "+e),t.emit(e,t)}},t.prototype.acquire=function(e){var t=this;return e=this.checkAndDefaultConstraints(e),new Promise((function(r,i){t.logger.log("acquiring local media"),t.emit("userMediaRequest",e),e.audio||e.video?t.getMediaStream(e).then((function(e){t.observer.trackAdded(),t.emit("userMedia",e),r(e)})).catch((function(e){t.emit("userMediaFailed",e),i(e)})):r([])})).catch((function(e){if(e.type===o.TypeStrings.SessionDescriptionHandlerError)throw e;var r=new a.Exceptions.SessionDescriptionHandlerError("acquire",e,"unable to acquire streams");throw t.logger.error(r.message),r.error&&t.logger.error(r.error),r})).then((function(e){return t.logger.log("acquired local media streams"),t.peerConnection.removeTrack&&t.peerConnection.getSenders().forEach((function(e){t.peerConnection.removeTrack(e)})),e})).catch((function(e){if(e.type===o.TypeStrings.SessionDescriptionHandlerError)throw e;var r=new a.Exceptions.SessionDescriptionHandlerError("acquire",e,"error removing streams");throw t.logger.error(r.message),r.error&&t.logger.error(r.error),r})).then((function(e){return[].concat(e).forEach((function(e){t.peerConnection.addTrack?e.getTracks().forEach((function(r){t.peerConnection.addTrack(r,e)})):t.peerConnection.addStream(e)})),Promise.resolve()})).catch((function(e){if(e.type===o.TypeStrings.SessionDescriptionHandlerError)throw e;var r=new a.Exceptions.SessionDescriptionHandlerError("acquire",e,"error adding stream");throw t.logger.error(r.message),r.error&&t.logger.error(r.error),r}))},t.prototype.hasOffer=function(e){var t="have-"+e+"-offer";return this.peerConnection.signalingState===t},t.prototype.isIceGatheringComplete=function(){return"complete"===this.peerConnection.iceGatheringState||this.iceGatheringTimeout},t.prototype.resetIceGatheringComplete=function(){this.iceGatheringTimeout=!1,this.logger.log("resetIceGatheringComplete"),this.iceGatheringTimer&&(clearTimeout(this.iceGatheringTimer),this.iceGatheringTimer=void 0),this.iceGatheringDeferred&&(this.iceGatheringDeferred.reject(),this.iceGatheringDeferred=void 0)},t.prototype.setDirection=function(e){var t=e.match(/a=(sendrecv|sendonly|recvonly|inactive)/);if(null===t)return this.direction=this.C.DIRECTION.NULL,void this.observer.directionChanged();var r=t[1];switch(r){case this.C.DIRECTION.SENDRECV:case this.C.DIRECTION.SENDONLY:case this.C.DIRECTION.RECVONLY:case this.C.DIRECTION.INACTIVE:this.direction=r;break;default:this.direction=this.C.DIRECTION.NULL}this.observer.directionChanged()},t.prototype.triggerIceGatheringComplete=function(){this.isIceGatheringComplete()&&(this.emit("iceGatheringComplete",this),this.iceGatheringTimer&&(clearTimeout(this.iceGatheringTimer),this.iceGatheringTimer=void 0),this.iceGatheringDeferred&&(this.iceGatheringDeferred.resolve(),this.iceGatheringDeferred=void 0))},t.prototype.waitForIceGatheringComplete=function(){return this.logger.log("waitForIceGatheringComplete"),this.isIceGatheringComplete()?(this.logger.log("ICE is already complete. Return resolved."),Promise.resolve()):(this.iceGatheringDeferred||(this.iceGatheringDeferred=c.Utils.defer()),this.logger.log("ICE is not complete. Returning promise"),this.iceGatheringDeferred?this.iceGatheringDeferred.promise:Promise.resolve())},t}(n.EventEmitter);t.SessionDescriptionHandler=l},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e){this.incomingInfoRequest=e}return Object.defineProperty(e.prototype,"request",{get:function(){return this.incomingInfoRequest.message},enumerable:!0,configurable:!0}),e.prototype.accept=function(e){return this.incomingInfoRequest.accept(e),Promise.resolve()},e.prototype.reject=function(e){return this.incomingInfoRequest.reject(e),Promise.resolve()},e}();t.Info=i},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(5),n=function(){function e(e,t){this.incomingReferRequest=e,this.session=t}return Object.defineProperty(e.prototype,"referTo",{get:function(){var e=this.incomingReferRequest.message.parseHeader("refer-to");if(!(e instanceof i.NameAddrHeader))throw new Error("Failed to parse Refer-To header.");return e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"referredBy",{get:function(){return this.incomingReferRequest.message.getHeader("referred-by")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"replaces",{get:function(){return this.referTo.uri.getHeader("replaces")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"request",{get:function(){return this.incomingReferRequest.message},enumerable:!0,configurable:!0}),e.prototype.accept=function(e){return void 0===e&&(e={statusCode:202}),this.incomingReferRequest.accept(e),Promise.resolve()},e.prototype.reject=function(e){return this.incomingReferRequest.reject(e),Promise.resolve()},e.prototype.makeInviter=function(e){if(this.inviter)return this.inviter;var t=this.referTo.uri.clone();t.clearHeaders();var r=((e=e||{}).extraHeaders||[]).slice(),i=this.replaces;i&&r.push("Replaces: "+decodeURIComponent(i));var n=this.referredBy;return n&&r.push("Referred-By: "+n),e.extraHeaders=r,this.inviter=this.session.userAgent.makeInviter(t,e),this.inviter.referred=this.session,this.session.referral=this.inviter,this.inviter},e}();t.Referral=n},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i,n=r(0),s=r(5),o=r(8),a=r(12),c=r(9);!function(e){e[e.STATUS_CONNECTING=0]="STATUS_CONNECTING",e[e.STATUS_OPEN=1]="STATUS_OPEN",e[e.STATUS_CLOSING=2]="STATUS_CLOSING",e[e.STATUS_CLOSED=3]="STATUS_CLOSED"}(i=t.TransportStatus||(t.TransportStatus={}));var u=function(e){function t(t,r){void 0===r&&(r={});var n=e.call(this,t,r)||this;return n.type=o.TypeStrings.Transport,n.reconnectionAttempts=0,n.status=i.STATUS_CONNECTING,n.configuration=n.loadConfig(r),n.server=n.configuration.wsServers[0],n}return n.__extends(t,e),t.prototype.isConnected=function(){return this.status===i.STATUS_OPEN},t.prototype.sendPromise=function(e,t){if(void 0===t&&(t={}),!this.statusAssert(i.STATUS_OPEN,t.force))return this.onError("unable to send message - WebSocket not open"),Promise.reject();var r=e.toString();return this.ws?(!0===this.configuration.traceSip&&this.logger.log("sending WebSocket message:\n\n"+r+"\n"),this.ws.send(r),Promise.resolve({msg:r})):(this.onError("unable to send message - WebSocket does not exist"),Promise.reject())},t.prototype.disconnectPromise=function(e){var t=this;return void 0===e&&(e={}),this.disconnectionPromise?this.disconnectionPromise:(e.code=e.code||1e3,this.statusTransition(i.STATUS_CLOSING,e.force)?(this.emit("disconnecting"),this.disconnectionPromise=new Promise((function(r,i){t.disconnectDeferredResolve=r,t.reconnectTimer&&(clearTimeout(t.reconnectTimer),t.reconnectTimer=void 0),t.ws?(t.stopSendingKeepAlives(),t.logger.log("closing WebSocket "+t.server.wsUri),t.ws.close(e.code,e.reason)):i("Attempted to disconnect but the websocket doesn't exist")})),this.disconnectionPromise):this.status===i.STATUS_CLOSED?Promise.resolve({overrideEvent:!0}):this.connectionPromise?this.connectionPromise.then((function(){return Promise.reject("The websocket did not disconnect")})).catch((function(){return Promise.resolve({overrideEvent:!0})})):Promise.reject("The websocket did not disconnect"))},t.prototype.connectPromise=function(e){var t=this;return void 0===e&&(e={}),this.status!==i.STATUS_CLOSING||e.force?this.connectionPromise?this.connectionPromise:(this.server=this.server||this.getNextWsServer(e.force),this.connectionPromise=new Promise((function(r,n){if((t.status===i.STATUS_OPEN||t.status===i.STATUS_CLOSING)&&!e.force)return t.logger.warn("WebSocket "+t.server.wsUri+" is already connected"),void n("Failed status check - attempted to open a connection but already open/closing");t.connectDeferredResolve=r,t.connectDeferredReject=n,t.status=i.STATUS_CONNECTING,t.emit("connecting"),t.logger.log("connecting to WebSocket "+t.server.wsUri),t.disposeWs();try{t.ws=new WebSocket(t.server.wsUri,"sip")}catch(e){return t.ws=null,t.statusTransition(i.STATUS_CLOSED,!0),t.onError("error connecting to WebSocket "+t.server.wsUri+":"+e),n("Failed to create a websocket"),t.connectDeferredResolve=void 0,void(t.connectDeferredReject=void 0)}if(!t.ws)return n("Unexpected instance websocket not set"),t.connectDeferredResolve=void 0,void(t.connectDeferredReject=void 0);t.connectionTimeout=setTimeout((function(){t.statusTransition(i.STATUS_CLOSED),t.logger.warn("took too long to connect - exceeded time set in configuration.connectionTimeout: "+t.configuration.connectionTimeout+"s"),t.emit("disconnected",{code:1e3}),t.connectionPromise=void 0,n("Connection timeout"),t.connectDeferredResolve=void 0,t.connectDeferredReject=void 0;var e=t.ws;t.disposeWs(),e.close(1e3)}),1e3*t.configuration.connectionTimeout),t.boundOnOpen=t.onOpen.bind(t),t.boundOnMessage=t.onMessage.bind(t),t.boundOnClose=t.onClose.bind(t),t.boundOnError=t.onWebsocketError.bind(t),t.ws.addEventListener("open",t.boundOnOpen),t.ws.addEventListener("message",t.boundOnMessage),t.ws.addEventListener("close",t.boundOnClose),t.ws.addEventListener("error",t.boundOnError)})),this.connectionPromise):Promise.reject("WebSocket "+this.server.wsUri+" is closing")},t.prototype.onMessage=function(e){var t,r=e.data;if(/^(\r\n)+$/.test(r))return this.clearKeepAliveTimeout(),void(!0===this.configuration.traceSip&&this.logger.log("received WebSocket message with CRLF Keep Alive response"));if(r){if("string"!=typeof r){try{t=String.fromCharCode.apply(null,new Uint8Array(r))}catch(e){return void this.logger.warn("received WebSocket binary message failed to be converted into string, message discarded")}!0===this.configuration.traceSip&&this.logger.log("received WebSocket binary message:\n\n"+r+"\n")}else!0===this.configuration.traceSip&&this.logger.log("received WebSocket text message:\n\n"+r+"\n"),t=r;this.emit("message",t)}else this.logger.warn("received empty message, message discarded")},t.prototype.onOpen=function(){if(this.status===i.STATUS_CLOSED){var e=this.ws;return this.disposeWs(),void e.close(1e3)}this.statusTransition(i.STATUS_OPEN,!0),this.emit("connected"),this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=void 0),this.logger.log("WebSocket "+this.server.wsUri+" connected"),void 0!==this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.reconnectionAttempts=0,this.disconnectionPromise=void 0,this.disconnectDeferredResolve=void 0,this.startSendingKeepAlives(),this.connectDeferredResolve?(this.connectDeferredResolve({overrideEvent:!0}),this.connectDeferredResolve=void 0,this.connectDeferredReject=void 0):this.logger.warn("Unexpected websocket.onOpen with no connectDeferredResolve")},t.prototype.onClose=function(e){if(this.logger.log("WebSocket disconnected (code: "+e.code+(e.reason?"| reason: "+e.reason:"")+")"),this.status!==i.STATUS_CLOSING&&(this.logger.warn("WebSocket closed without SIP.js requesting it"),this.emit("transportError")),this.stopSendingKeepAlives(),this.connectionTimeout&&clearTimeout(this.connectionTimeout),this.connectDeferredReject&&this.connectDeferredReject("Websocket Closed"),this.connectionTimeout=void 0,this.connectionPromise=void 0,this.connectDeferredResolve=void 0,this.connectDeferredReject=void 0,this.disconnectDeferredResolve)return this.disconnectDeferredResolve({overrideEvent:!0}),this.statusTransition(i.STATUS_CLOSED),void(this.disconnectDeferredResolve=void 0);this.statusTransition(i.STATUS_CLOSED,!0),this.emit("disconnected",{code:e.code,reason:e.reason}),this.disposeWs(),this.reconnect()},t.prototype.disposeWs=function(){this.ws&&(this.ws.removeEventListener("open",this.boundOnOpen),this.ws.removeEventListener("message",this.boundOnMessage),this.ws.removeEventListener("close",this.boundOnClose),this.ws.removeEventListener("error",this.boundOnError),this.ws=void 0)},t.prototype.onError=function(e){this.logger.warn("Transport error: "+e),this.emit("transportError")},t.prototype.onWebsocketError=function(){this.onError("The Websocket had an error")},t.prototype.reconnect=function(){var e=this;if(this.reconnectionAttempts>0&&this.logger.log("Reconnection attempt "+this.reconnectionAttempts+" failed"),this.noAvailableServers())return this.logger.warn("attempted to get next ws server but there are no available ws servers left"),this.logger.warn("no available ws servers left - going to closed state"),this.statusTransition(i.STATUS_CLOSED,!0),this.emit("closed"),void this.resetServerErrorStatus();this.isConnected()&&(this.logger.warn("attempted to reconnect while connected - forcing disconnect"),this.disconnect({force:!0})),this.reconnectionAttempts+=1,this.reconnectionAttempts>this.configuration.maxReconnectionAttempts?(this.logger.warn("maximum reconnection attempts for WebSocket "+this.server.wsUri),this.logger.log("transport "+this.server.wsUri+" failed | connection state set to 'error'"),this.server.isError=!0,this.emit("transportError"),this.noAvailableServers()||(this.server=this.getNextWsServer()),this.reconnectionAttempts=0,this.reconnect()):(this.logger.log("trying to reconnect to WebSocket "+this.server.wsUri+" (reconnection attempt "+this.reconnectionAttempts+")"),this.reconnectTimer=setTimeout((function(){e.connect(),e.reconnectTimer=void 0}),1===this.reconnectionAttempts?0:1e3*this.configuration.reconnectionTimeout))},t.prototype.resetServerErrorStatus=function(){for(var e=0,t=this.configuration.wsServers;et[0].weight?t=[n]:n.weight===t[0].weight&&t.push(n))}return t[Math.floor(Math.random()*t.length)]},t.prototype.noAvailableServers=function(){for(var e=0,t=this.configuration.wsServers;e",weight:0,wsUri:"wss://edge.sip.onsip.com",isError:!1}],connectionTimeout:5,maxReconnectionAttempts:3,reconnectionTimeout:4,keepAliveInterval:0,keepAliveDebounce:10,traceSip:!1},r=this.getConfigurationCheck();for(var i in r.mandatory){if(!e.hasOwnProperty(i))throw new a.Exceptions.ConfigurationError(i);var n=e[i];if(void 0===(s=r.mandatory[i](n)))throw new a.Exceptions.ConfigurationError(i,n);t[i]=s}for(var i in r.optional)if(e.hasOwnProperty(i)){var s;if((n=e[i])instanceof Array&&0===n.length||null===n||""===n||void 0===n||"number"==typeof n&&isNaN(n))continue;if(void 0===(s=r.optional[i](n)))throw new a.Exceptions.ConfigurationError(i,n);t[i]=s}var o={};for(var i in t)t.hasOwnProperty(i)&&(o[i]={value:t[i]});var c=Object.defineProperties({},o);for(var i in this.logger.log("configuration parameters after validation:"),t)t.hasOwnProperty(i)&&this.logger.log("\xb7 "+i+": "+JSON.stringify(t[i]));return c},t.prototype.getConfigurationCheck=function(){return{mandatory:{},optional:{wsServers:function(e){if("string"==typeof e)e=[{wsUri:e}];else{if(!(e instanceof Array))return;for(var t=0;t",n.weight||(n.weight=0),n.isError=!1,n.scheme=o.scheme.toUpperCase()}return e},keepAliveInterval:function(e){if(c.Utils.isDecimal(e)){var t=Number(e);if(t>0)return t}},keepAliveDebounce:function(e){if(c.Utils.isDecimal(e)){var t=Number(e);if(t>0)return t}},traceSip:function(e){if("boolean"==typeof e)return e},connectionTimeout:function(e){if(c.Utils.isDecimal(e)){var t=Number(e);if(t>0)return t}},maxReconnectionAttempts:function(e){if(c.Utils.isDecimal(e)){var t=Number(e);if(t>=0)return t}},reconnectionTimeout:function(e){if(c.Utils.isDecimal(e)){var t=Number(e);if(t>0)return t}}}}},t.C=i,t}(s.Transport);t.Transport=u},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e){e.Required="Required",e.Supported="Supported",e.Unsupported="Unsupported"}(t.SIPExtension||(t.SIPExtension={})),t.UserAgentRegisteredOptionTags={"100rel":!0,199:!0,answermode:!0,"early-session":!0,eventlist:!0,explicitsub:!0,"from-change":!0,"geolocation-http":!0,"geolocation-sip":!0,gin:!0,gruu:!0,histinfo:!0,ice:!0,join:!0,"multiple-refer":!0,norefersub:!0,nosub:!0,outbound:!0,path:!0,policy:!0,precondition:!0,pref:!0,privacy:!0,"recipient-list-invite":!0,"recipient-list-message":!0,"recipient-list-subscribe":!0,replaces:!0,"resource-priority":!0,"sdp-anat":!0,"sec-agree":!0,tdialog:!0,timer:!0,uui:!0}},,function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(8),n=function(){function e(e,t){this.type=i.TypeStrings.SessionDescriptionHandlerObserver,this.session=e,this.options=t}return e.prototype.trackAdded=function(){this.session.emit("trackAdded")},e.prototype.directionChanged=function(){this.session.emit("directionChanged")},e}();t.SessionDescriptionHandlerObserver=n},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(11),s=r(5),o=r(10),a=r(8),c=r(12),u=r(52),d=r(31),l=r(95),p=function(e){function t(t,r){var i=e.call(this,t)||this;if(i.incomingInviteRequest=r,i.body=void 0,i._canceled=!1,i.rseq=Math.floor(1e4*Math.random()),i.type=a.TypeStrings.InviteServerContext,i.logger=t.getLogger("sip.invitation",i.id),i.request.body&&(i.body=i.request.body),i.request.hasHeader("Content-Type")&&(i.contentType=i.request.getHeader("Content-Type")),i.localIdentity=i.request.to,i.remoteIdentity=i.request.from,i.request.hasHeader("P-Asserted-Identity")){var o=i.request.getHeader("P-Asserted-Identity");o&&(i.assertedIdentity=s.Grammar.nameAddrHeaderParse(o))}i.contact=i.userAgent.contact.toString(),i.fromTag=i.request.fromTag,i.id=i.request.callId+i.fromTag;var c=i.request.parseHeader("Content-Disposition");c&&"render"===c.type&&(i.renderbody=i.request.body,i.rendertype=i.request.getHeader("Content-Type")),i.logger=t.getLogger("sip.invitation",i.id),i.status=a.SessionStatus.STATUS_INVITE_RECEIVED,i.userAgent.sessions[i.id]=i;var u=i.request,l=function(e,t){u.hasHeader(e)&&u.getHeader(e).toLowerCase().indexOf("100rel")>=0&&(i.rel100=t)};if(l("require",n.C.supported.REQUIRED),l("supported",n.C.supported.SUPPORTED),i.request.toTag=r.toTag,i.status=a.SessionStatus.STATUS_WAITING_FOR_ANSWER,i.userNoAnswerTimer=setTimeout((function(){i.stateTransition(d.SessionState.Terminated),r.reject({statusCode:408}),i.failed(u,n.C.causes.NO_ANSWER),i.terminated(u,n.C.causes.NO_ANSWER)}),i.userAgent.configuration.noAnswerTimeout?1e3*i.userAgent.configuration.noAnswerTimeout:6e4),u.hasHeader("expires")){var p=1e3*Number(u.getHeader("expires")||0);i.expiresTimer=setTimeout((function(){i.status===a.SessionStatus.STATUS_WAITING_FOR_ANSWER&&(i.stateTransition(d.SessionState.Terminated),r.reject({statusCode:487}),i.failed(u,n.C.causes.EXPIRES),i.terminated(u,n.C.causes.EXPIRES))}),p)}return i}return i.__extends(t,e),Object.defineProperty(t.prototype,"autoSendAnInitialProvisionalResponse",{get:function(){return this.rel100!==n.C.supported.REQUIRED},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"request",{get:function(){return this.incomingInviteRequest.message},enumerable:!0,configurable:!0}),t.prototype.accept=function(e){var t=this;if(void 0===e&&(e={}),this.logger.log("Invitation.accept"),this.state!==d.SessionState.Initial){var r=new Error("Invalid session state "+this.state);return this.logger.error(r.message),Promise.reject(r)}return this.stateTransition(d.SessionState.Establishing),this._accept(e).then((function(e){e.message;var r=e.session;r.delegate={onAck:function(e){return t.onAckRequest(e)},onAckTimeout:function(){return t.onAckTimeout()},onBye:function(e){return t.onByeRequest(e)},onInfo:function(e){return t.onInfoRequest(e)},onInvite:function(e){return t.onInviteRequest(e)},onNotify:function(e){return t.onNotifyRequest(e)},onPrack:function(e){return t.onPrackRequest(e)},onRefer:function(e){return t.onReferRequest(e)}},t.dialog=r,t.stateTransition(d.SessionState.Established),t.replacee&&t.replacee.bye()})).catch((function(e){if(t.onContextError(e),!t._canceled)throw e}))},t.prototype.progress=function(e){var t=this;if(void 0===e&&(e={}),this.logger.log("Invitation.progress"),this.state!==d.SessionState.Initial){var r=new Error("Invalid session state "+this.state);return this.logger.error(r.message),Promise.reject(r)}var i=e.statusCode||180;if(i<100||i>199)throw new TypeError("Invalid statusCode: "+i);if(this.status===a.SessionStatus.STATUS_TERMINATED)return this.logger.warn("Unexpected call for progress while terminated, ignoring"),Promise.resolve();if(this.status===a.SessionStatus.STATUS_ANSWERED)return this.logger.warn("Unexpected call for progress while answered, ignoring"),Promise.resolve();if(this.status===a.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK)return this.logger.warn("Unexpected call for progress while answered (waiting for prack), ignoring"),Promise.resolve();if(this.status===a.SessionStatus.STATUS_WAITING_FOR_PRACK)return this.logger.warn("Unexpected call for progress while waiting for prack, ignoring"),Promise.resolve();if(100===e.statusCode){try{this.incomingInviteRequest.trying()}catch(r){if(this.onContextError(r),!this._canceled)return Promise.reject(r)}return Promise.resolve()}return this.rel100===n.C.supported.REQUIRED||this.rel100===n.C.supported.SUPPORTED&&e.rel100||this.rel100===n.C.supported.SUPPORTED&&this.userAgent.configuration.sipExtension100rel===l.SIPExtension.Required?this._progressReliableWaitForPrack(e).then((function(e){})).catch((function(e){if(t.onContextError(e),!t._canceled)throw e})):this._progress(e).then((function(e){})).catch((function(e){if(t.onContextError(e),!t._canceled)throw e}))},t.prototype.reject=function(e){if(void 0===e&&(e={}),this.logger.log("Invitation.reject"),this.state!==d.SessionState.Initial){var t=new Error("Invalid session state "+this.state);return this.logger.error(t.message),Promise.reject(t)}if(this.stateTransition(d.SessionState.Terminated),this.status===a.SessionStatus.STATUS_TERMINATED)throw new c.Exceptions.InvalidStateError(this.status);this.logger.log("rejecting RTCSession");var r=e.statusCode||480,i=e.reasonPhrase?e.reasonPhrase:o.getReasonPhrase(r),n=e.extraHeaders||[];if(r<300||r>699)throw new TypeError("Invalid statusCode: "+r);var u=e.body?s.fromBodyLegacy(e.body):void 0,l=r<400?this.incomingInviteRequest.redirect([],{statusCode:r,reasonPhrase:i,extraHeaders:n,body:u}):this.incomingInviteRequest.reject({statusCode:r,reasonPhrase:i,extraHeaders:n,body:u});return this.emit("rejected",l.message,i),this.emit("failed",l.message,i),this.terminated(),Promise.resolve()},t.prototype.byePending=function(){this.emit("bye",this.request),e.prototype.byePending.call(this)},t.prototype.onCancel=function(e){this.logger.log("Invitation.onCancel"),this.state===d.SessionState.Initial||this.state===d.SessionState.Establishing?(this._canceled=!0,this.stateTransition(d.SessionState.Terminated),this.incomingInviteRequest.reject({statusCode:487}),this.rejected(e,n.C.causes.CANCELED),this.failed(e,n.C.causes.CANCELED),this.terminated(e,n.C.causes.CANCELED)):this.logger.error("CANCEL received while in state "+this.state+", dropping request")},t.prototype.terminated=function(t,r){this.prackNeverArrived(),e.prototype.terminated.call(this,t,r)},t.prototype._accept=function(e){var t=this;return void 0===e&&(e={}),this.onInfo=e.onInfo,this.status===a.SessionStatus.STATUS_WAITING_FOR_PRACK?(this.status=a.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK,this.waitForArrivalOfPrack().then((function(){t.status=a.SessionStatus.STATUS_ANSWERED,clearTimeout(t.userNoAnswerTimer)})).then((function(){return t.generateResponseOfferAnswer(t.incomingInviteRequest,e)})).then((function(e){return t.incomingInviteRequest.accept({statusCode:200,body:e})}))):this.status!==a.SessionStatus.STATUS_WAITING_FOR_ANSWER?Promise.reject(new c.Exceptions.InvalidStateError(this.status)):(this.status=a.SessionStatus.STATUS_ANSWERED,this.status=a.SessionStatus.STATUS_ANSWERED,clearTimeout(this.userNoAnswerTimer),this.generateResponseOfferAnswer(this.incomingInviteRequest,e).then((function(e){return t.incomingInviteRequest.accept({statusCode:200,body:e})})))},t.prototype._progress=function(e){void 0===e&&(e={});var t=e.statusCode||180,r=e.reasonPhrase,i=(e.extraHeaders||[]).slice(),n=e.body?s.fromBodyLegacy(e.body):void 0;if(183===t&&!n)return this._progressWithSDP(e);try{var o=this.incomingInviteRequest.progress({statusCode:t,reasonPhrase:r,extraHeaders:i,body:n});return this.emit("progress",o.message,r),this.dialog=o.session,Promise.resolve(o)}catch(e){return Promise.reject(e)}},t.prototype._progressWithSDP=function(e){var t=this;void 0===e&&(e={});var r=e.statusCode||183,i=e.reasonPhrase,n=(e.extraHeaders||[]).slice();return this.generateResponseOfferAnswer(this.incomingInviteRequest,e).then((function(e){return t.incomingInviteRequest.progress({statusCode:r,reasonPhrase:i,extraHeaders:n,body:e})})).then((function(e){return t.emit("progress",e.message,i),t.dialog=e.session,e}))},t.prototype._progressReliable=function(e){return void 0===e&&(e={}),e.extraHeaders=(e.extraHeaders||[]).slice(),e.extraHeaders.push("Require: 100rel"),e.extraHeaders.push("RSeq: "+Math.floor(1e4*Math.random())),this._progressWithSDP(e)},t.prototype._progressReliableWaitForPrack=function(e){var t=this;void 0===e&&(e={});var r,i=e.statusCode||183,o=e.reasonPhrase,u=(e.extraHeaders||[]).slice();return u.push("Require: 100rel"),u.push("RSeq: "+this.rseq++),this.status=a.SessionStatus.STATUS_WAITING_FOR_PRACK,new Promise((function(d,l){var p=!0;return t.generateResponseOfferAnswer(t.incomingInviteRequest,e).then((function(e){return r=e,t.incomingInviteRequest.progress({statusCode:i,reasonPhrase:o,extraHeaders:u,body:r})})).then((function(h){var g,f;t.emit("progress",h.message,o),t.dialog=h.session,h.session.delegate={onPrack:function(r){g=r,clearTimeout(v),clearTimeout(y),p&&(p=!1,t.handlePrackOfferAnswer(g,e).then((function(e){try{f=g.accept({statusCode:200,body:e}),t.status===a.SessionStatus.STATUS_WAITING_FOR_PRACK&&(t.status=a.SessionStatus.STATUS_WAITING_FOR_ANSWER),t.prackArrived(),d({prackRequest:g,prackResponse:f,progressResponse:h})}catch(e){l(e)}})))}};var v=setTimeout((function(){if(p){p=!1,t.logger.warn("No PRACK received, rejecting INVITE."),clearTimeout(y);try{t.incomingInviteRequest.reject({statusCode:504}),t.terminated(void 0,n.C.causes.NO_PRACK),l(new c.Exceptions.TerminatedSessionError)}catch(e){l(e)}}}),64*s.Timers.T1),m=function(){try{t.incomingInviteRequest.progress({statusCode:i,reasonPhrase:o,extraHeaders:u,body:r})}catch(e){return p=!1,void l(e)}y=setTimeout(m,S*=2)},S=s.Timers.T1,y=setTimeout(m,S)}))}))},t.prototype.handlePrackOfferAnswer=function(e,t){if(!this.dialog)throw new Error("Dialog undefined.");var r=s.getBody(e.message);if(!r||"session"!==r.contentDisposition)return Promise.resolve(void 0);switch(this.dialog.signalingState){case s.SignalingState.Initial:throw new Error("Invalid signaling state "+this.dialog.signalingState+".");case s.SignalingState.Stable:return this.setAnswer(r,t).then((function(){}));case s.SignalingState.HaveLocalOffer:throw new Error("Invalid signaling state "+this.dialog.signalingState+".");case s.SignalingState.HaveRemoteOffer:return this.setOfferAndGetAnswer(r,t);case s.SignalingState.Closed:default:throw new Error("Invalid signaling state "+this.dialog.signalingState+".")}},t.prototype.onAckTimeout=function(){if(this.logger.log("Invitation.onAckTimeout"),!this.dialog)throw new Error("Dialog undefined.");this.logger.log("No ACK received for an extended period of time, terminating session"),this.dialog.bye(),this.stateTransition(d.SessionState.Terminated),this.terminated(void 0,n.C.causes.NO_ACK)},t.prototype.onContextError=function(e){var t=480;e instanceof s.Exception?e instanceof c.Exceptions.SessionDescriptionHandlerError?(this.logger.error(e.message),e.error&&this.logger.error(e.error)):e instanceof c.Exceptions.TerminatedSessionError?this.logger.warn("Incoming session terminated while waiting for PRACK."):e instanceof c.Exceptions.UnsupportedSessionDescriptionContentTypeError?t=415:e instanceof s.Exception&&this.logger.error(e.message):e instanceof Error?this.logger.error(e.message):(this.logger.error("An error occurred in the session description handler."),this.logger.error(e));try{this.incomingInviteRequest.reject({statusCode:t}),this.failed(this.incomingInviteRequest.message,e.message),this.terminated(this.incomingInviteRequest.message,e.message)}catch(e){return}},t.prototype.prackArrived=function(){this.waitingForPrackResolve&&this.waitingForPrackResolve(),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0},t.prototype.prackNeverArrived=function(){this.waitingForPrackReject&&this.waitingForPrackReject(new c.Exceptions.TerminatedSessionError),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0},t.prototype.waitForArrivalOfPrack=function(){var e=this;if(this.waitingForPrackPromise)throw new Error("Already waiting for PRACK");return this.waitingForPrackPromise=new Promise((function(t,r){e.waitingForPrackResolve=t,e.waitingForPrackReject=r})),this.waitingForPrackPromise},t}(u.Session);t.Invitation=p},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e){e.Initial="Initial",e.NotifyWait="NotifyWait",e.Subscribed="Subscribed",e.Terminated="Terminated"}(t.SubscriptionState||(t.SubscriptionState={}))},,,,,,function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(11),s=r(5),o=r(8),a=r(12),c=r(9),u=r(52),d=r(31),l=r(95),p=function(e){function t(t,r,i){void 0===i&&(i={});var n=e.call(this,t,i)||this;if(n.body=void 0,n.earlyMediaSessionDescriptionHandlers=new Map,i.params=i.params||{},n.status!==o.SessionStatus.STATUS_NULL)throw new a.Exceptions.InvalidStateError(n.status);n.type=o.TypeStrings.InviteClientContext,n.logger=t.getLogger("sip.inviter"),i.body&&(n.body={body:i.body,contentType:i.contentType?i.contentType:"application/sdp"});var u=i.anonymous||!1;u&&t.configuration.uri&&(i.params.fromDisplayName="Anonymous",i.params.fromUri="sip:anonymous@anonymous.invalid");var d=c.Utils.newTag(),p=t.contact.toString({anonymous:u,outbound:u?!t.contact.tempGruu:!t.contact.pubGruu}),h=i.params||{};h.fromTag=d;var g=t.userAgentCore.configuration.aor;if(i.params.fromUri&&(g="string"==typeof i.params.fromUri?s.Grammar.URIParse(i.params.fromUri):i.params.fromUri),!g)throw new TypeError("Invalid from URI: "+i.params.fromUri);var f=r;if(i.params.toUri&&(f="string"==typeof i.params.toUri?s.Grammar.URIParse(i.params.toUri):i.params.toUri),!f)throw new TypeError("Invalid to URI: "+i.params.toUri);var v,m=(i.extraHeaders||[]).slice();if(u&&t.configuration.uri&&(m.push("P-Preferred-Identity: "+t.configuration.uri.toString()),m.push("Privacy: id")),m.push("Contact: "+p),m.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),t.configuration.sipExtension100rel===l.SIPExtension.Required&&m.push("Require: 100rel"),t.configuration.sipExtensionReplaces===l.SIPExtension.Required&&m.push("Require: replaces"),n.body&&(v=c.Utils.fromBodyObj(n.body)),n.request=t.userAgentCore.makeOutgoingRequestMessage(n.method,r,g,f,h,m,v),!n.request.from)throw new Error("From undefined.");if(!n.request.to)throw new Error("From undefined.");return n.localIdentity=n.request.from,n.remoteIdentity=n.request.to,i.params=h,i.extraHeaders=m,n.contact=p,n.fromTag=d,n.id=n.request.callId+n.fromTag,n.onInfo=i.onInfo,n.passedOptions=i,n.renderbody=i.renderbody||void 0,n.rendertype=i.rendertype||"text/plain",n.sessionDescriptionHandlerModifiers=i.SessionDescriptionHandlerModifiers||[],n.sessionDescriptionHandlerOptions=i.sessionDescriptionHandlerOptions||{},n.inviteWithoutSdp=i.inviteWithoutSdp||!1,n.isCanceled=!1,n.earlyMedia=i.earlyMedia||!1,t.applicants[n.toString()]=n,n}return i.__extends(t,e),t.prototype.cancel=function(e){if(void 0===e&&(e={}),this.logger.log("Inviter.cancel"),this.state!==d.SessionState.Initial&&this.state!==d.SessionState.Establishing){var t=new Error("Invalid session state "+this.state);return this.logger.error(t.message),Promise.reject(t)}if(this.isCanceled)throw new Error("Already canceled.");if(this.isCanceled=!0,this.stateTransition(d.SessionState.Terminating),this.disposeEarlyMedia(),this.sessionDescriptionHandler&&this.sessionDescriptionHandler.close(),this.outgoingInviteRequest){var r=void 0;e.statusCode&&e.reasonPhrase&&(r=c.Utils.getCancelReason(e.statusCode,e.reasonPhrase)),this.outgoingInviteRequest.cancel(r,e)}else this.logger.warn("Canceled session before INVITE was sent"),this.stateTransition(d.SessionState.Terminated);return Promise.resolve()},t.prototype.invite=function(t){var r=this;if(void 0===t&&(t={}),this.logger.log("Inviter.invite"),this.state!==d.SessionState.Initial)return e.prototype.invite.call(this,t);if(!this.id)throw new Error("Session id undefined.");if(this.userAgent.sessions[this.id]=this,t.withoutSdp||this.inviteWithoutSdp)return this.renderbody&&this.rendertype&&(this.request.body={contentType:this.rendertype,body:this.renderbody}),this.stateTransition(d.SessionState.Establishing),this.status=o.SessionStatus.STATUS_INVITE_SENT,Promise.resolve(this.sendInvite(t));var i={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers};return this.getOffer(i).then((function(e){return r.stateTransition(d.SessionState.Establishing),r.status=o.SessionStatus.STATUS_INVITE_SENT,r.request.body={body:e.content,contentType:e.contentType},r.sendInvite(t)})).catch((function(e){throw r.logger.log(e.message),r.failed(void 0,n.C.causes.WEBRTC_ERROR),r.terminated(void 0,n.C.causes.WEBRTC_ERROR),e}))},t.prototype.sendInvite=function(e){var t=this;return void 0===e&&(e={}),this.outgoingInviteRequest=this.userAgent.userAgentCore.invite(this.request,{onAccept:function(r){return t.dialog?(t.logger.log("Additional confirmed dialog, sending ACK and BYE"),void t.ackAndBye(r)):t.isCanceled?(t.logger.log("Canceled session accepted, sending ACK and BYE"),t.ackAndBye(r),t.stateTransition(d.SessionState.Terminated),void t.emit("bye",t.request)):(t.notifyReferer(r),void t.onAccept(r).then((function(){t.disposeEarlyMedia()})).catch((function(e){t.disposeEarlyMedia()})).then((function(){e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(r)})))},onProgress:function(r){t.isCanceled||(t.notifyReferer(r),t.onProgress(r).catch((function(e){t.disposeEarlyMedia()})).then((function(){e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(r)})))},onRedirect:function(r){t.notifyReferer(r),t.onRedirect(r),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(r)},onReject:function(r){t.notifyReferer(r),t.onReject(r),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(r)},onTrying:function(r){t.notifyReferer(r),t.onTrying(r),e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(r)}}),this.outgoingInviteRequest},t.prototype.disposeEarlyMedia=function(){this.earlyMediaSessionDescriptionHandlers.forEach((function(e){e.close()}))},t.prototype.notifyReferer=function(e){var t=this;if(this.referred){if(!(this.referred instanceof u.Session))throw new Error("Referred session not instance of session");if(this.referred.dialog){if(!e.message.statusCode)throw new Error("Status code undefined.");if(!e.message.reasonPhrase)throw new Error("Reason phrase undefined.");var r=("SIP/2.0 "+e.message.statusCode+" "+e.message.reasonPhrase).trim();this.referred.dialog.notify(void 0,{extraHeaders:["Event: refer","Subscription-State: terminated"],body:{contentDisposition:"render",contentType:"message/sipfrag",content:r}}).delegate={onReject:function(){t.referred=void 0}}}}},t.prototype.onAccept=function(e){var t=this;if(this.logger.log("Inviter.onAccept"),this.state!==d.SessionState.Establishing)return this.logger.error("Accept received while in state "+this.state+", dropping response"),Promise.reject(new Error("Invalid session state "+this.state));var r=e.message,i=e.session;r.hasHeader("P-Asserted-Identity")&&(this.assertedIdentity=s.Grammar.nameAddrHeaderParse(r.getHeader("P-Asserted-Identity"))),this.dialog=i,this.dialog.delegate={onAck:function(e){return t.onAckRequest(e)},onBye:function(e){return t.onByeRequest(e)},onInfo:function(e){return t.onInfoRequest(e)},onInvite:function(e){return t.onInviteRequest(e)},onNotify:function(e){return t.onNotifyRequest(e)},onPrack:function(e){return t.onPrackRequest(e)},onRefer:function(e){return t.onReferRequest(e)}};var a=this.sessionDescriptionHandlerOptions,c=this.sessionDescriptionHandlerModifiers;switch(i.signalingState){case s.SignalingState.Initial:case s.SignalingState.HaveLocalOffer:return this.ackAndBye(e,400,"Missing session description"),this.failed(r,n.C.causes.BAD_MEDIA_DESCRIPTION),Promise.reject(new Error(n.C.causes.BAD_MEDIA_DESCRIPTION));case s.SignalingState.HaveRemoteOffer:if(!this.dialog.offer)throw new Error("Session offer undefined in signaling state "+this.dialog.signalingState+".");var u={sessionDescriptionHandlerOptions:a,sessionDescriptionHandlerModifiers:c};return this.setOfferAndGetAnswer(this.dialog.offer,u).then((function(r){t.status=o.SessionStatus.STATUS_CONFIRMED;e.ack({body:r});t.stateTransition(d.SessionState.Established)})).catch((function(i){throw t.ackAndBye(e,488,"Invalid session description"),t.failed(r,n.C.causes.BAD_MEDIA_DESCRIPTION),i}));case s.SignalingState.Stable:if(this.earlyMediaSessionDescriptionHandlers.size>0){var l=this.earlyMediaSessionDescriptionHandlers.get(i.id);if(!l)throw new Error("Session description handler undefined.");this.setSessionDescriptionHandler(l),this.earlyMediaSessionDescriptionHandlers.delete(i.id),this.status=o.SessionStatus.STATUS_CONFIRMED;e.ack();return this.stateTransition(d.SessionState.Established),Promise.resolve()}if(this.earlyMediaDialog){if(this.earlyMediaDialog!==i){if(this.earlyMedia){this.logger.error("You have set the 'earlyMedia' option to 'true' which requires that your INVITE requests do not fork and yet this INVITE request did in fact fork. Consequentially and not surprisingly the end point which accepted the INVITE (confirmed dialog) does not match the end point with which early media has been setup (early dialog) and thus this session is unable to proceed. In accordance with the SIP specifications, the SIP servers your end point is connected to determine if an INVITE forks and the forking behaviour of those servers cannot be controlled by this library. If you wish to use early media with this library you must configure those servers accordingly. Alternatively you may set the 'earlyMedia' to 'false' which will allow this library to function with any INVITE requests which do fork.")}var p=new Error("Early media dialog does not equal confirmed dialog, terminating session");return this.logger.error(p.message),this.ackAndBye(e,488,"Not Acceptable Here"),this.failed(r,n.C.causes.BAD_MEDIA_DESCRIPTION),Promise.reject(p)}this.status=o.SessionStatus.STATUS_CONFIRMED;e.ack();return this.stateTransition(d.SessionState.Established),Promise.resolve()}var h=i.answer;if(!h)throw new Error("Answer is undefined.");u={sessionDescriptionHandlerOptions:a,sessionDescriptionHandlerModifiers:c};return this.setAnswer(h,u).then((function(){var r;t.renderbody&&t.rendertype&&(r={body:{contentDisposition:"render",contentType:t.rendertype,content:t.renderbody}}),t.status=o.SessionStatus.STATUS_CONFIRMED;e.ack(r);t.stateTransition(d.SessionState.Established)})).catch((function(i){throw t.logger.error(i.message),t.ackAndBye(e,488,"Not Acceptable Here"),t.failed(r,n.C.causes.BAD_MEDIA_DESCRIPTION),i}));case s.SignalingState.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}},t.prototype.onProgress=function(e){var t=this;if(this.logger.log("Inviter.onProgress"),this.state!==d.SessionState.Establishing)return this.logger.error("Progress received while in state "+this.state+", dropping response"),Promise.reject(new Error("Invalid session state "+this.state));if(!this.outgoingInviteRequest)throw new Error("Outgoing INVITE request undefined.");var r=e.message,i=e.session;this.status=o.SessionStatus.STATUS_1XX_RECEIVED,r.hasHeader("P-Asserted-Identity")&&(this.assertedIdentity=s.Grammar.nameAddrHeaderParse(r.getHeader("P-Asserted-Identity")));var a=r.getHeader("require"),c=r.getHeader("rseq"),u=!!(a&&a.includes("100rel")&&c?Number(c):void 0),l=[];u&&l.push("RAck: "+r.getHeader("rseq")+" "+r.getHeader("cseq"));var p=this.sessionDescriptionHandlerOptions,h=this.sessionDescriptionHandlerModifiers;switch(i.signalingState){case s.SignalingState.Initial:return u&&(this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."),e.prack({extraHeaders:l})),this.emit("progress",r),Promise.resolve();case s.SignalingState.HaveLocalOffer:return u&&e.prack({extraHeaders:l}),this.emit("progress",r),Promise.resolve();case s.SignalingState.HaveRemoteOffer:if(!u)return this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response."),Promise.resolve();var g=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions||{});return this.emit("SessionDescriptionHandler-created",g),this.earlyMediaSessionDescriptionHandlers.set(i.id,g),g.setDescription(r.body,p,h).then((function(){return g.getDescription(p,h)})).then((function(i){var n={contentDisposition:"session",contentType:i.contentType,content:i.body};e.prack({extraHeaders:l,body:n}),t.emit("progress",r)})).catch((function(e){if(t.status===o.SessionStatus.STATUS_TERMINATED)throw e;throw t.failed(void 0,n.C.causes.WEBRTC_ERROR),t.terminated(void 0,n.C.causes.WEBRTC_ERROR),e}));case s.SignalingState.Stable:if(u&&e.prack({extraHeaders:l}),this.earlyMedia&&!this.earlyMediaDialog){this.earlyMediaDialog=i;var f=i.answer;if(!f)throw new Error("Answer is undefined.");var v={sessionDescriptionHandlerOptions:p,sessionDescriptionHandlerModifiers:h};return this.setAnswer(f,v).then((function(){t.emit("progress",r)})).catch((function(e){if(t.status===o.SessionStatus.STATUS_TERMINATED)throw e;throw t.failed(void 0,n.C.causes.WEBRTC_ERROR),t.terminated(void 0,n.C.causes.WEBRTC_ERROR),e}))}return this.emit("progress",r),Promise.resolve();case s.SignalingState.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}},t.prototype.onRedirect=function(e){if(this.logger.log("Inviter.onRedirect"),this.state===d.SessionState.Establishing||this.state===d.SessionState.Terminating){this.stateTransition(d.SessionState.Terminated),this.disposeEarlyMedia();var t=e.message,r=t.statusCode,i=c.Utils.sipErrorCause(r||0);this.rejected(t,i),this.failed(t,i),this.terminated(t,i)}else this.logger.error("Redirect received while in state "+this.state+", dropping response")},t.prototype.onReject=function(e){if(this.logger.log("Inviter.onReject"),this.state===d.SessionState.Establishing||this.state===d.SessionState.Terminating){this.stateTransition(d.SessionState.Terminated),this.disposeEarlyMedia();var t=e.message,r=t.statusCode,i=c.Utils.sipErrorCause(r||0);this.rejected(t,i),this.failed(t,i),this.terminated(t,i)}else this.logger.error("Reject received while in state "+this.state+", dropping response")},t.prototype.onTrying=function(e){this.logger.log("Inviter.onTrying"),this.emit("progress",e.message),this.state===d.SessionState.Establishing||this.logger.error("Trying received while in state "+this.state+", dropping response")},t}(u.Session);t.Inviter=p},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e){this.incomingMessageRequest=e}return Object.defineProperty(e.prototype,"request",{get:function(){return this.incomingMessageRequest.message},enumerable:!0,configurable:!0}),e.prototype.accept=function(e){return this.incomingMessageRequest.accept(e),Promise.resolve()},e.prototype.reject=function(e){return this.incomingMessageRequest.reject(e),Promise.resolve()},e}();t.Message=i},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e){e.Initial="Initial",e.Registered="Registered",e.Unregistered="Unregistered"}(t.RegistererState||(t.RegistererState={}))},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(7),s=r(53),o=r(99),a=function(e){function t(t,r){void 0===r&&(r={});var i=e.call(this)||this;return i._disposed=!1,i._state=o.SubscriptionState.Initial,i._stateEventEmitter=new n.EventEmitter,i._logger=t.getLogger("sip.subscription"),i.userAgent=t,i.delegate=r.delegate,i}return i.__extends(t,e),t.prototype.dispose=function(){this._disposed||(this._disposed=!0,this.stateTransition(o.SubscriptionState.Terminated),this._stateEventEmitter.removeAllListeners())},Object.defineProperty(t.prototype,"disposed",{get:function(){return this._disposed},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"state",{get:function(){return this._state},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"stateChange",{get:function(){return s.makeEmitter(this._stateEventEmitter)},enumerable:!0,configurable:!0}),t.prototype.stateTransition=function(e){var t=this,r=function(){throw new Error("Invalid state transition from "+t._state+" to "+e)};switch(this._state){case o.SubscriptionState.Initial:e!==o.SubscriptionState.NotifyWait&&e!==o.SubscriptionState.Terminated&&r();break;case o.SubscriptionState.NotifyWait:e!==o.SubscriptionState.Subscribed&&e!==o.SubscriptionState.Terminated&&r();break;case o.SubscriptionState.Subscribed:e!==o.SubscriptionState.Terminated&&r();break;case o.SubscriptionState.Terminated:r();break;default:throw new Error("Unrecognized state.")}this._state!==e&&(this._state=e,this._logger.log("Subscription "+(this.dialog?this.dialog.id:void 0)+" transitioned to "+this._state),this._stateEventEmitter.emit("event",this._state))},t}(n.EventEmitter);t.Subscription=a},,,,,function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0);i.__exportStar(r(114),t),i.__exportStar(r(53),t),i.__exportStar(r(92),t),i.__exportStar(r(115),t),i.__exportStar(r(98),t),i.__exportStar(r(105),t),i.__exportStar(r(106),t),i.__exportStar(r(116),t),i.__exportStar(r(54),t),i.__exportStar(r(117),t),i.__exportStar(r(93),t),i.__exportStar(r(118),t),i.__exportStar(r(107),t),i.__exportStar(r(119),t),i.__exportStar(r(31),t),i.__exportStar(r(52),t),i.__exportStar(r(120),t),i.__exportStar(r(99),t),i.__exportStar(r(108),t),i.__exportStar(r(95),t),i.__exportStar(r(121),t)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(98),n=r(31),s=function(){function e(e,t){this._session=e}return Object.defineProperty(e.prototype,"session",{get:function(){return this._session},enumerable:!0,configurable:!0}),e.prototype.bye=function(e){if(void 0===e&&(e={}),this.session.state!==n.SessionState.Established&&this.session.state!==n.SessionState.Terminating){var t="Byer.bye() may only be called if established session.";return this.session.state===n.SessionState.Terminated?t+=" However this session is already terminated.":this.session instanceof i.Invitation?(t+=" However Invitation.accept() has not yet been called.",t+=" Perhaps you should have called Invitation.reject()?"):(t+=" However a dialog does not yet exist.",t+=" Perhaps you should have called Inviter.cancel()?"),this.session.logger.error(t),Promise.reject(new Error("Invalid session state "+this.session.state))}return this.session.bye(e.requestDelegate,e.requestOptions)},e}();t.Byer=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(31),n=function(){function e(e,t){this._session=e}return Object.defineProperty(e.prototype,"session",{get:function(){return this._session},enumerable:!0,configurable:!0}),e.prototype.info=function(e){if(void 0===e&&(e={}),this.session.state!==i.SessionState.Established){return this.session.logger.error("Infoer.info() may only be called if established session."),Promise.reject(new Error("Invalid session state "+this.session.state))}return this.session.info(e.requestDelegate,e.requestOptions)},e}();t.Infoer=n},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(7),s=r(5),o=function(e){function t(t,r,n,o,a){void 0===o&&(o="text/plain"),void 0===a&&(a={});var c=e.call(this)||this;c._disposed=!1,c.logger=t.getLogger("sip.messager"),a.params=a.params||{};var u=t.userAgentCore.configuration.aor;if(a.params.fromUri&&(u="string"==typeof a.params.fromUri?s.Grammar.URIParse(a.params.fromUri):a.params.fromUri),!u)throw new TypeError("Invalid from URI: "+a.params.fromUri);var d=r;if(a.params.toUri&&(d="string"==typeof a.params.toUri?s.Grammar.URIParse(a.params.toUri):a.params.toUri),!d)throw new TypeError("Invalid to URI: "+a.params.toUri);var l=a.params?i.__assign({},a.params):{},p=(a.extraHeaders||[]).slice(),h={contentDisposition:"render",contentType:o,content:n};return c.request=t.userAgentCore.makeOutgoingRequestMessage(s.C.MESSAGE,r,u,d,l,p,h),c.userAgent=t,c}return i.__extends(t,e),t.prototype.dispose=function(){this._disposed||(this._disposed=!0)},t.prototype.message=function(e){return void 0===e&&(e={}),this.userAgent.userAgentCore.request(this.request,e.requestDelegate),Promise.resolve()},t}(n.EventEmitter);t.Messager=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(7),s=r(5),o=r(12),a=r(9),c=function(e){function t(t,r,i,n){void 0===n&&(n={});var o=e.call(this)||this;n.extraHeaders=(n.extraHeaders||[]).slice(),n.contentType=n.contentType||"text/plain","number"!=typeof n.expires||n.expires%1!=0?n.expires=3600:n.expires=Number(n.expires),"boolean"!=typeof n.unpublishOnClose&&(n.unpublishOnClose=!0),o.target=r,o.event=i,o.options=n,o.pubRequestExpires=o.options.expires,o.logger=t.getLogger("sip.publisher");var a,c=n.params||{},u=c.fromUri?c.fromUri:t.userAgentCore.configuration.aor,d=c.toUri?c.toUri:r;if(n.body&&n.contentType){a={contentDisposition:"render",contentType:n.contentType,content:n.body}}var l=(n.extraHeaders||[]).slice();return o.request=t.userAgentCore.makeOutgoingRequestMessage(s.C.PUBLISH,r,u,d,c,l,a),o.userAgent=t,o}return i.__extends(t,e),t.prototype.close=function(){this.options.unpublishOnClose?this.unpublish():(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,this.pubRequestExpires=0,this.pubRequestEtag=void 0),this.userAgent.publishers[this.target.toString()+":"+this.event]&&delete this.userAgent.publishers[this.target.toString()+":"+this.event]},t.prototype.publish=function(e,t){void 0===t&&(t={}),this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.options.body=e,this.pubRequestBody=this.options.body,0===this.pubRequestExpires&&(this.pubRequestExpires=this.options.expires,this.pubRequestEtag=void 0),this.userAgent.publishers[this.target.toString()+":"+this.event]||(this.userAgent.publishers[this.target.toString()+":"+this.event]=this),this.sendPublishRequest()},t.prototype.unpublish=function(e){void 0===e&&(e={}),this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,this.pubRequestExpires=0,void 0!==this.pubRequestEtag&&this.sendPublishRequest()},t.prototype.receiveResponse=function(e){var t=this,r=e.statusCode||0,i=a.Utils.getReasonPhrase(r);switch(!0){case/^1[0-9]{2}$/.test(r.toString()):this.emit("progress",e,i);break;case/^2[0-9]{2}$/.test(r.toString()):if(e.hasHeader("SIP-ETag")?this.pubRequestEtag=e.getHeader("SIP-ETag"):this.logger.warn("SIP-ETag header missing in a 200-class response to PUBLISH"),e.hasHeader("Expires")){var n=Number(e.getHeader("Expires"));"number"==typeof n&&n>=0&&n<=this.pubRequestExpires?this.pubRequestExpires=n:this.logger.warn("Bad Expires header in a 200-class response to PUBLISH")}else this.logger.warn("Expires header missing in a 200-class response to PUBLISH");0!==this.pubRequestExpires?(this.publishRefreshTimer=setTimeout((function(){return t.refreshRequest()}),900*this.pubRequestExpires),this.emit("published",e,i)):this.emit("unpublished",e,i);break;case/^412$/.test(r.toString()):void 0!==this.pubRequestEtag&&0!==this.pubRequestExpires?(this.logger.warn("412 response to PUBLISH, recovering"),this.pubRequestEtag=void 0,this.emit("progress",e,i),this.publish(this.options.body)):(this.logger.warn("412 response to PUBLISH, recovery failed"),this.pubRequestExpires=0,this.emit("failed",e,i),this.emit("unpublished",e,i));break;case/^423$/.test(r.toString()):if(0!==this.pubRequestExpires&&e.hasHeader("Min-Expires")){var s=Number(e.getHeader("Min-Expires"));"number"==typeof s||s>this.pubRequestExpires?(this.logger.warn("423 code in response to PUBLISH, adjusting the Expires value and trying to recover"),this.pubRequestExpires=s,this.emit("progress",e,i),this.publish(this.options.body)):(this.logger.warn("Bad 423 response Min-Expires header received for PUBLISH"),this.pubRequestExpires=0,this.emit("failed",e,i),this.emit("unpublished",e,i))}else this.logger.warn("423 response to PUBLISH, recovery failed"),this.pubRequestExpires=0,this.emit("failed",e,i),this.emit("unpublished",e,i);break;default:this.pubRequestExpires=0,this.emit("failed",e,i),this.emit("unpublished",e,i)}0===this.pubRequestExpires&&(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,this.pubRequestEtag=void 0)},t.prototype.send=function(){var e=this;return this.userAgent.userAgentCore.publish(this.request,{onAccept:function(t){return e.receiveResponse(t.message)},onProgress:function(t){return e.receiveResponse(t.message)},onRedirect:function(t){return e.receiveResponse(t.message)},onReject:function(t){return e.receiveResponse(t.message)},onTrying:function(t){return e.receiveResponse(t.message)}}),this},t.prototype.refreshRequest=function(){if(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,void 0===this.pubRequestEtag)throw new o.Exceptions.MethodParameterError("Publish","Body",void 0);if(0===this.pubRequestExpires)throw new o.Exceptions.MethodParameterError("Publish","Expire",this.pubRequestExpires);this.sendPublishRequest()},t.prototype.sendPublishRequest=function(){var e=Object.create(this.options||Object.prototype);e.extraHeaders=(this.options.extraHeaders||[]).slice(),e.extraHeaders.push("Event: "+this.event),e.extraHeaders.push("Expires: "+this.pubRequestExpires),void 0!==this.pubRequestEtag&&e.extraHeaders.push("SIP-If-Match: "+this.pubRequestEtag);var t,r,i=this.target,n=this.options.params||{};void 0!==this.pubRequestBody&&(t={body:this.pubRequestBody,contentType:this.options.contentType}),t&&(r=a.Utils.fromBodyObj(t)),this.request=this.userAgent.userAgentCore.makeOutgoingRequestMessage(s.C.PUBLISH,i,n.fromUri?n.fromUri:this.userAgent.userAgentCore.configuration.aor,n.toUri?n.toUri:this.target,n,e.extraHeaders,r),this.send()},t}(n.EventEmitter);t.Publisher=c},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(5),n=r(31),s=function(){function e(e,t,r){this._session=e,this._referTo=t}return Object.defineProperty(e.prototype,"session",{get:function(){return this._session},enumerable:!0,configurable:!0}),e.prototype.refer=function(e){if(void 0===e&&(e={}),this.session.state!==n.SessionState.Established){return this.session.logger.error("Referrer.refer() may only be called if established session."),Promise.reject(new Error("Invalid session state "+this.session.state))}var t=e.requestDelegate,r=e.requestOptions||{},i=this.extraHeaders(this.referToString(this._referTo));return r.extraHeaders=r.extraHeaders||[],r.extraHeaders=r.extraHeaders.concat(i),this.session.refer(this,t,r)},e.prototype.extraHeaders=function(e){var t=[];return t.push("Referred-By: <"+this._session.userAgent.configuration.uri+">"),t.push("Contact: "+this._session.contact),t.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),t.push("Refer-To: "+e),t},e.prototype.referToString=function(e){var t;if(e instanceof i.URI)t=e.toString();else{if(!e.dialog)throw new Error("Dialog undefined.");var r=e.remoteIdentity.friendlyName,n=e.dialog.remoteTarget.toString(),s=e.dialog.callId,o=e.dialog.remoteTag,a=e.dialog.localTag;t='"'+r+'" <'+n+"?Replaces="+encodeURIComponent(s+";to-tag="+o+";from-tag="+a)+">"}return t},e}();t.Referrer=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(7),s=r(11),o=r(5),a=r(12),c=r(9),u=r(53),d=r(107);function l(e){var t={expires:600,extraContactHeaderParams:[],instanceId:void 0,params:{},regId:void 0,registrar:void 0},r={mandatory:{},optional:{expires:function(e){if(c.Utils.isDecimal(e)){var t=Number(e);if(t>=0)return t}},extraContactHeaderParams:function(e){if(e instanceof Array)return e.filter((function(e){return"string"==typeof e}))},instanceId:function(e){if("string"==typeof e)return/^uuid:/i.test(e)&&(e=e.substr(5)),-1===o.Grammar.parse(e,"uuid")?void 0:e},params:function(e){if("object"==typeof e)return e},regId:function(e){if(c.Utils.isDecimal(e)){var t=Number(e);if(t>=0)return t}},registrar:function(e){if("string"==typeof e){/^sip:/i.test(e)||(e=s.C.SIP+":"+e);var t=o.Grammar.URIParse(e);return t?t.user?void 0:t:void 0}}}};for(var i in r.mandatory){if(!e.hasOwnProperty(i))throw new a.Exceptions.ConfigurationError(i);var n=e[i];if(void 0===(u=r.mandatory[i](n)))throw new a.Exceptions.ConfigurationError(i,n);t[i]=u}for(var i in r.optional)if(e.hasOwnProperty(i)){var u;if((n=e[i])instanceof Array&&0===n.length)continue;if(null===n||""===n||void 0===n||"number"==typeof n&&isNaN(n))continue;if(void 0===(u=r.optional[i](n)))throw new a.Exceptions.ConfigurationError(i,n);t[i]=u}return t}var p=function(){function e(e,t){var r=this;void 0===t&&(t={}),this._contacts=[],this._state=d.RegistererState.Initial,this._stateEventEmitter=new n.EventEmitter,this._waiting=!1,this._waitingEventEmitter=new n.EventEmitter;var i=l(t);if(i.regId&&!i.instanceId?i.instanceId=c.Utils.newUUID():!i.regId&&i.instanceId&&(i.regId=1),i.params.toUri=i.params.toUri||e.configuration.uri,i.params.toDisplayName=i.params.toDisplayName||e.configuration.displayName,i.params.callId=i.params.callId||c.Utils.createRandomToken(22),i.params.cseq=i.params.cseq||Math.floor(1e4*Math.random()),!i.registrar){var o={};"object"==typeof e.configuration.uri?(o=e.configuration.uri.clone()).user=void 0:o=e.configuration.uri,i.registrar=o}this.userAgent=e,this.logger=e.getLogger("sip.registerer");var a=(t.extraHeaders||[]).slice();for(var u in this.request=e.userAgentCore.makeOutgoingRequestMessage(s.C.REGISTER,i.registrar,i.params.fromUri?i.params.fromUri:e.userAgentCore.configuration.aor,i.params.toUri?i.params.toUri:i.registrar,i.params,a,void 0),this.options=i,this.logger.log("configuration parameters for RegisterContext after validation:"),i)i.hasOwnProperty(u)&&this.logger.log("\xb7 "+u+": "+JSON.stringify(i[u]));this.expires=i.expires,this.contact=e.contact.toString(),e.transport.on("disconnected",(function(){return r.onTransportDisconnected()})),this.id=this.request.callId+this.request.from.parameters.tag,this.userAgent.registerers[this.id]=this}return Object.defineProperty(e.prototype,"contacts",{get:function(){return this._contacts.slice()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"state",{get:function(){return this._state},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"stateChange",{get:function(){return u.makeEmitter(this._stateEventEmitter)},enumerable:!0,configurable:!0}),e.prototype.dispose=function(){return i.__awaiter(this,void 0,void 0,(function(){var e=this;return i.__generator(this,(function(t){return delete this.userAgent.registerers[this.id],[2,new Promise((function(t,r){var i=function(){if(!e.waiting&&e._state===d.RegistererState.Registered)return e.stateChange.once((function(){return t()})),void e.unregister();t()};e.waiting?e.waitingChange.once((function(){return i()})):i()}))]}))}))},e.prototype.register=function(e){return void 0===e&&(e={}),i.__awaiter(this,void 0,void 0,(function(){var t,r,n,s=this;return i.__generator(this,(function(a){return this.waiting?(t=new Error("REGISTER request already in progress, waiting for final response"),[2,Promise.reject(t)]):(e.requestOptions&&(this.options=i.__assign({},this.options,e.requestOptions)),(r=(this.options.extraHeaders||[]).slice()).push("Contact: "+this.generateContactHeader(this.expires)),r.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),this.request.cseq++,this.request.setHeader("cseq",this.request.cseq+" REGISTER"),this.request.extraHeaders=r,this.waitingToggle(!0),n=this.userAgent.userAgentCore.register(this.request,{onAccept:function(e){var t;e.message.hasHeader("expires")&&(t=Number(e.message.getHeader("expires"))),s._contacts=e.message.getHeaders("contact");var r,i=s._contacts.length;if(!i)return s.logger.error("No Contact header in response to REGISTER, dropping response."),void s.unregistered();for(;i--;){if((r=e.message.parseHeader("contact",i)).uri.user===s.userAgent.contact.uri.user){t=r.getParam("expires");break}r=void 0}return void 0===r?(s.logger.error("No Contact header pointing to us, dropping response"),s.unregistered(),void s.waitingToggle(!1)):void 0===t?(s.logger.error("Contact pointing to us is missing expires parameter, dropping response"),s.unregistered(),void s.waitingToggle(!1)):(r.hasParam("temp-gruu")&&(s.userAgent.contact.tempGruu=o.Grammar.URIParse(r.getParam("temp-gruu").replace(/"/g,""))),r.hasParam("pub-gruu")&&(s.userAgent.contact.pubGruu=o.Grammar.URIParse(r.getParam("pub-gruu").replace(/"/g,""))),s.registered(t),void s.waitingToggle(!1))},onProgress:function(e){},onRedirect:function(e){s.logger.error("Redirect received. Not supported."),s.unregistered(),s.waitingToggle(!1)},onReject:function(e){if(423===e.message.statusCode)return e.message.hasHeader("min-expires")?(s.expires=Number(e.message.getHeader("min-expires")),s.waitingToggle(!1),void s.register()):(s.logger.error("423 response received for REGISTER without Min-Expires"),s.unregistered(),void s.waitingToggle(!1));s.logger.warn("Failed to register, status code "+e.message.statusCode),s.unregistered(),s.waitingToggle(!1)},onTrying:function(e){}}),[2,Promise.resolve(n)])}))}))},e.prototype.unregister=function(e){return void 0===e&&(e={}),i.__awaiter(this,void 0,void 0,(function(){var t,r,n,s=this;return i.__generator(this,(function(i){return this.waiting?(t=new Error("REGISTER request already in progress, waiting for final response"),[2,Promise.reject(t)]):(this._state===d.RegistererState.Registered||e.all||this.logger.warn("Not currently registered, but sending an unregister anyway."),r=(e.requestOptions&&e.requestOptions.extraHeaders||[]).slice(),this.request.extraHeaders=r,e.all?(r.push("Contact: *"),r.push("Expires: 0")):r.push("Contact: "+this.generateContactHeader(0)),this.request.cseq++,this.request.setHeader("cseq",this.request.cseq+" REGISTER"),void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),this.waitingToggle(!0),n=this.userAgent.userAgentCore.register(this.request,{onAccept:function(t){s._contacts=t.message.getHeaders("contact"),s.unregistered(),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t),s.waitingToggle(!1)},onProgress:function(t){e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)},onRedirect:function(t){s.logger.error("Unregister redirected. Not currently supported."),s.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t),s.waitingToggle(!1)},onReject:function(t){s.waitingToggle(!1),s.logger.error("Unregister rejected with status code "+t.message.statusCode),s.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t),s.waitingToggle(!1)},onTrying:function(t){e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}}),[2,Promise.resolve(n)])}))}))},e.prototype.clearTimers=function(){void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),void 0!==this.registrationExpiredTimer&&(clearTimeout(this.registrationExpiredTimer),this.registrationExpiredTimer=void 0)},e.prototype.generateContactHeader=function(e){void 0===e&&(e=0);var t=this.contact;return this.options.regId&&this.options.instanceId&&(t+=";reg-id="+this.options.regId,t+=';+sip.instance=""'),this.options.extraContactHeaderParams&&this.options.extraContactHeaderParams.forEach((function(e){t+=";"+e})),t+=";expires="+e},e.prototype.onTransportDisconnected=function(){this.unregistered()},e.prototype.registered=function(e){var t=this;this.clearTimers(),this.registrationTimer=setTimeout((function(){t.registrationTimer=void 0,t.register()}),1e3*e-3e3),this.registrationExpiredTimer=setTimeout((function(){t.logger.warn("Registration expired"),t.unregistered()}),1e3*e),this._state!==d.RegistererState.Registered&&this.stateTransition(d.RegistererState.Registered)},e.prototype.unregistered=function(){this.clearTimers(),this._state!==d.RegistererState.Unregistered&&this.stateTransition(d.RegistererState.Unregistered)},e.prototype.stateTransition=function(e){var t=this,r=function(){throw new Error("Invalid state transition from "+t._state+" to "+e)};switch(this._state){case d.RegistererState.Initial:e!==d.RegistererState.Registered&&e!==d.RegistererState.Unregistered&&r();break;case d.RegistererState.Registered:e!==d.RegistererState.Unregistered&&r();break;case d.RegistererState.Unregistered:e!==d.RegistererState.Registered&&r();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log("Registration transitioned to state "+this._state),this._stateEventEmitter.emit("event",this._state)},Object.defineProperty(e.prototype,"waiting",{get:function(){return this._waiting},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"waitingChange",{get:function(){return u.makeEmitter(this._waitingEventEmitter)},enumerable:!0,configurable:!0}),e.prototype.waitingToggle=function(e){if(this._waiting===e)throw new Error("Invalid waiting transition from "+this._waiting+" to "+e);this._waiting=e,this.logger.log("Waiting toggled to "+this._waiting),this._waitingEventEmitter.emit("event",this._waiting)},e}();t.Registerer=p},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(5),s=r(14),o=r(9),a=r(54),c=r(108),u=r(99),d=function(e){function t(t,r,i,n){void 0===n&&(n={});var s=e.call(this,t,n)||this;return s.body=void 0,s.logger=t.getLogger("sip.subscription"),n.body&&(s.body={body:n.body,contentType:n.contentType?n.contentType:"application/sdp"}),s.userAgent=t,s.targetURI=r,s.event=i,void 0===n.expires?s.expires=3600:"number"!=typeof n.expires?(s.logger.warn('Option "expires" must be a number. Using default of 3600.'),s.expires=3600):s.expires=n.expires,s.extraHeaders=(n.extraHeaders||[]).slice(),s.context=s.initContext(),s.request=s.context.message,s.id=s.request.callId+s.request.from.parameters.tag+s.event,s.userAgent.subscriptions[s.id]=s,s}return i.__extends(t,e),t.prototype.dispose=function(){this.disposed||(e.prototype.dispose.call(this),this.retryAfterTimer&&(clearTimeout(this.retryAfterTimer),this.retryAfterTimer=void 0),this.context.dispose(),delete this.userAgent.subscriptions[this.id])},t.prototype.subscribe=function(e){var t=this;switch(void 0===e&&(e={}),this.context.state){case n.SubscriptionState.Initial:this.state===u.SubscriptionState.Initial&&this.stateTransition(u.SubscriptionState.NotifyWait),this.context.subscribe().then((function(e){e.success?(e.success.subscription&&(t.dialog=e.success.subscription,t.dialog.delegate={onNotify:function(e){return t.onNotify(e)},onRefresh:function(e){return t.onRefresh(e)},onTerminated:function(){t.dispose(),t.onTerminated()}}),t.onNotify(e.success.request)):e.failure&&t.onFailed(e.failure.response)}));break;case n.SubscriptionState.NotifyWait:case n.SubscriptionState.Pending:break;case n.SubscriptionState.Active:if(this.dialog)this.dialog.refresh().delegate={onAccept:function(e){return t.onAccepted(e)},onRedirect:function(e){return t.onFailed(e)},onReject:function(e){return t.onFailed(e)}};break;case n.SubscriptionState.Terminated:}return Promise.resolve()},t.prototype.unsubscribe=function(e){if(void 0===e&&(e={}),this.disposed)return Promise.resolve();switch(this.context.state){case n.SubscriptionState.Initial:case n.SubscriptionState.NotifyWait:break;case n.SubscriptionState.Pending:case n.SubscriptionState.Active:this.dialog&&this.dialog.unsubscribe();break;case n.SubscriptionState.Terminated:}return this.dispose(),this.onTerminated(),Promise.resolve()},t.prototype.close=function(){return this.unsubscribe()},t.prototype.refresh=function(){return this.context.state===n.SubscriptionState.Active?this.subscribe():Promise.resolve()},t.prototype.on=function(t,r){return e.prototype.on.call(this,t,r)},t.prototype.emit=function(t){for(var r=[],i=1;i1)return void this.logger.warn("More than one Via header field present in the response. Dropping.");if(r.via.host!==this.options.viaHost||void 0!==r.via.port)return void this.logger.warn("Via sent-by in the response does not match UA Via host value. Dropping.");var u;n=o.str_utf8_length(r.body);if((u=r.getHeader("content-length"))&&n"}}},e.prototype.initCore=function(){var e=this,t=[];t.push("outbound"),this.options.sipExtension100rel===m.SIPExtension.Supported&&t.push("100rel"),this.options.sipExtensionReplaces===m.SIPExtension.Supported&&t.push("replaces"),this.options.sipExtensionExtraSupported&&t.push.apply(t,this.options.sipExtensionExtraSupported),this.options.hackAllowUnregisteredOptionTags||(t=t.filter((function(e){return m.UserAgentRegisteredOptionTags[e]})));var r=(t=Array.from(new Set(t))).slice();(this.contact.pubGruu||this.contact.tempGruu)&&r.push("gruu");var i={aor:this.options.uri,contact:this.contact,displayName:this.options.displayName,loggerFactory:this.loggerFactory,hackViaTcp:this.options.hackViaTcp,routeSet:this.options.usePreloadedRoute&&this.transport.server&&this.transport.server.sipUri?[this.transport.server.sipUri]:[],supportedOptionTags:t,supportedOptionTagsResponse:r,sipjsId:this.options.sipjsId,userAgentHeaderFieldValue:this.options.userAgentString,viaForceRport:this.options.forceRport,viaHost:this.options.viaHost,authenticationFactory:function(){var t=e.options.authorizationUsername?e.options.authorizationUsername:e.options.uri.user,r=e.options.authorizationPassword?e.options.authorizationPassword:void 0;return new s.DigestAuthentication(e.getLoggerFactory(),t,r)},transportAccessor:function(){return e.transport}},n={onInvite:function(t){var r=new p.Invitation(e,t);if(t.delegate={onCancel:function(e){r.onCancel(e)},onTransportError:function(e){r.onTransportError()}},t.trying(),e.options.sipExtensionReplaces!==m.SIPExtension.Unsupported){var i=t.message.parseHeader("replaces");if(i){var n=i.call_id;if("string"!=typeof n)throw new Error("Type of call id is not string");var s=i.replaces_to_tag;if("string"!=typeof s)throw new Error("Type of to tag is not string");var o=i.replaces_from_tag;if("string"!=typeof o)throw new Error("type of from tag is not string");var a=n+s+o,c=e.userAgentCore.dialogs.get(a);if(!c)return void r.reject({statusCode:481});if(!c.early&&!0===i.early_only)return void r.reject({statusCode:486});var u=e.sessions[n+o]||e.sessions[n+s]||void 0;if(!u)throw new Error("Session does not exist.");r.replacee=u}}if(e.delegate&&e.delegate.onInvite)if(r.autoSendAnInitialProvisionalResponse){var d=e.delegate.onInvite;r.progress().then((function(){return d(r)}))}else e.delegate.onInvite(r);else r.reject({statusCode:486})},onMessage:function(t){if(e.delegate&&e.delegate.onMessage){var r=new g.Message(t);e.delegate.onMessage(r)}else t.accept()},onNotify:function(t){if(e.delegate&&e.delegate.onNotify){var r=new f.Notification(t);e.delegate.onNotify(r)}else e.options.allowLegacyNotifications?t.accept():t.reject({statusCode:481})},onRefer:function(t){e.logger.log("Received an out of dialog refer"),e.options.allowOutOfDialogRefers||t.reject({statusCode:405}),e.logger.log("Allow out of dialog refers is enabled on the UA")},onRegister:function(t){e.delegate&&e.delegate.onRegisterRequest&&e.delegate.onRegisterRequest(t)},onSubscribe:function(t){e.delegate&&e.delegate.onSubscribeRequest&&e.delegate.onSubscribeRequest(t)}};return new s.UserAgentCore(i,n)},e.defaultOptions={allowLegacyNotifications:!1,allowOutOfDialogRefers:!1,authorizationPassword:"",authorizationUsername:"",autoStart:!1,autoStop:!0,delegate:{},displayName:"",forceRport:!1,hackAllowUnregisteredOptionTags:!1,hackIpInContact:!1,hackViaTcp:!1,hackWssInTransport:!1,logBuiltinEnabled:!0,logConfiguration:!0,logConnector:function(){},logLevel:"log",noAnswerTimeout:60,sessionDescriptionHandlerFactory:d.SessionDescriptionHandler.defaultFactory,sessionDescriptionHandlerFactoryOptions:{},sipExtension100rel:m.SIPExtension.Unsupported,sipExtensionReplaces:m.SIPExtension.Unsupported,sipExtensionExtraSupported:[],sipjsId:"",transportConstructor:l.Transport,transportOptions:{},uri:new s.URI("sip","anonymous","anonymous.invalid"),usePreloadedRoute:!1,userAgentString:"SIP.js/"+u.LIBRARY_VERSION,viaHost:""},e}();t.UserAgent=y},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e){e.Initial="Initial",e.Starting="Starting",e.Started="Started",e.Stopping="Stopping",e.Stopped="Stopped"}(t.UserAgentState||(t.UserAgentState={}))}])})); \ No newline at end of file diff --git a/dist/sip-core.js b/dist/sip-core.js deleted file mode 100644 index 836882c70..000000000 --- a/dist/sip-core.js +++ /dev/null @@ -1,12067 +0,0 @@ -/*! - * - * SIP version 0.15.5 - * Copyright (c) 2014-2019 Junction Networks, Inc - * Homepage: https://sipjs.com - * License: https://sipjs.com/license/ - * - * - * ~~~SIP.js contains substantial portions of JsSIP under the following license~~~ - * Homepage: http://jssip.net - * Copyright (c) 2012-2013 José Luis Millán - Versatica - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * ~~~ end JsSIP license ~~~ - * - * - * - * - */ -(function webpackUniversalModuleDefinition(root, factory) { - if(typeof exports === 'object' && typeof module === 'object') - module.exports = factory(); - else if(typeof define === 'function' && define.amd) - define([], factory); - else if(typeof exports === 'object') - exports["SIP"] = factory(); - else - root["SIP"] = factory(); -})(this, function() { -return /******/ (function(modules) { // webpackBootstrap -/******/ // The module cache -/******/ var installedModules = {}; -/******/ -/******/ // The require function -/******/ function __webpack_require__(moduleId) { -/******/ -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) { -/******/ return installedModules[moduleId].exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ i: moduleId, -/******/ l: false, -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); -/******/ -/******/ // Flag the module as loaded -/******/ module.l = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/******/ -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; -/******/ -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; -/******/ -/******/ // define getter function for harmony exports -/******/ __webpack_require__.d = function(exports, name, getter) { -/******/ if(!__webpack_require__.o(exports, name)) { -/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); -/******/ } -/******/ }; -/******/ -/******/ // define __esModule on exports -/******/ __webpack_require__.r = function(exports) { -/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { -/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); -/******/ } -/******/ Object.defineProperty(exports, '__esModule', { value: true }); -/******/ }; -/******/ -/******/ // create a fake namespace object -/******/ // mode & 1: value is a module id, require it -/******/ // mode & 2: merge all properties of value into the ns -/******/ // mode & 4: return value when already ns object -/******/ // mode & 8|1: behave like require -/******/ __webpack_require__.t = function(value, mode) { -/******/ if(mode & 1) value = __webpack_require__(value); -/******/ if(mode & 8) return value; -/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; -/******/ var ns = Object.create(null); -/******/ __webpack_require__.r(ns); -/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); -/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); -/******/ return ns; -/******/ }; -/******/ -/******/ // getDefaultExport function for compatibility with non-harmony modules -/******/ __webpack_require__.n = function(module) { -/******/ var getter = module && module.__esModule ? -/******/ function getDefault() { return module['default']; } : -/******/ function getModuleExports() { return module; }; -/******/ __webpack_require__.d(getter, 'a', getter); -/******/ return getter; -/******/ }; -/******/ -/******/ // Object.prototype.hasOwnProperty.call -/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; -/******/ -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = ""; -/******/ -/******/ -/******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = 2); -/******/ }) -/************************************************************************/ -/******/ ([ -/* 0 */, -/* 1 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__extends", function() { return __extends; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__assign", function() { return __assign; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__rest", function() { return __rest; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__decorate", function() { return __decorate; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__param", function() { return __param; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__metadata", function() { return __metadata; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__awaiter", function() { return __awaiter; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__generator", function() { return __generator; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__exportStar", function() { return __exportStar; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__values", function() { return __values; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__read", function() { return __read; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__spread", function() { return __spread; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__spreadArrays", function() { return __spreadArrays; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__await", function() { return __await; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncGenerator", function() { return __asyncGenerator; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncDelegator", function() { return __asyncDelegator; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncValues", function() { return __asyncValues; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__makeTemplateObject", function() { return __makeTemplateObject; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__importStar", function() { return __importStar; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__importDefault", function() { return __importDefault; }); -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ -/* global Reflect, Promise */ - -var extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); -}; - -function __extends(d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -} - -var __assign = function() { - __assign = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - } - return __assign.apply(this, arguments); -} - -function __rest(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; -} - -function __decorate(decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -} - -function __param(paramIndex, decorator) { - return function (target, key) { decorator(target, key, paramIndex); } -} - -function __metadata(metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); -} - -function __awaiter(thisArg, _arguments, P, generator) { - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -} - -function __generator(thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -} - -function __exportStar(m, exports) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; -} - -function __values(o) { - var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; - if (m) return m.call(o); - return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; -} - -function __read(o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; -} - -function __spread() { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read(arguments[i])); - return ar; -} - -function __spreadArrays() { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) - for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) - r[k] = a[j]; - return r; -}; - -function __await(v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); -} - -function __asyncGenerator(thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function fulfill(value) { resume("next", value); } - function reject(value) { resume("throw", value); } - function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } -} - -function __asyncDelegator(o) { - var i, p; - return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } -} - -function __asyncValues(o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } -} - -function __makeTemplateObject(cooked, raw) { - if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } - return cooked; -}; - -function __importStar(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result.default = mod; - return result; -} - -function __importDefault(mod) { - return (mod && mod.__esModule) ? mod : { default: mod }; -} - - -/***/ }), -/* 2 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -/** - * A core library implementing low level SIP protocol elements. - * @packageDocumentation - */ -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -// Directories -tslib_1.__exportStar(__webpack_require__(3), exports); -tslib_1.__exportStar(__webpack_require__(31), exports); -tslib_1.__exportStar(__webpack_require__(60), exports); -tslib_1.__exportStar(__webpack_require__(5), exports); -tslib_1.__exportStar(__webpack_require__(24), exports); -tslib_1.__exportStar(__webpack_require__(56), exports); -tslib_1.__exportStar(__webpack_require__(27), exports); -tslib_1.__exportStar(__webpack_require__(64), exports); -tslib_1.__exportStar(__webpack_require__(66), exports); -// Files -tslib_1.__exportStar(__webpack_require__(26), exports); -tslib_1.__exportStar(__webpack_require__(78), exports); - - -/***/ }), -/* 3 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -tslib_1.__exportStar(__webpack_require__(4), exports); -tslib_1.__exportStar(__webpack_require__(23), exports); -tslib_1.__exportStar(__webpack_require__(55), exports); - - -/***/ }), -/* 4 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var messages_1 = __webpack_require__(5); -/** - * Dialog. - * @remarks - * A key concept for a user agent is that of a dialog. A dialog - * represents a peer-to-peer SIP relationship between two user agents - * that persists for some time. The dialog facilitates sequencing of - * messages between the user agents and proper routing of requests - * between both of them. The dialog represents a context in which to - * interpret SIP messages. - * https://tools.ietf.org/html/rfc3261#section-12 - * @public - */ -var Dialog = /** @class */ (function () { - /** - * Dialog constructor. - * @param core - User agent core. - * @param dialogState - Initial dialog state. - */ - function Dialog(core, dialogState) { - this.core = core; - this.dialogState = dialogState; - this.core.dialogs.set(this.id, this); - } - /** - * When a UAC receives a response that establishes a dialog, it - * constructs the state of the dialog. This state MUST be maintained - * for the duration of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.1.2 - * @param outgoingRequestMessage - Outgoing request message for dialog. - * @param incomingResponseMessage - Incoming response message creating dialog. - */ - Dialog.initialDialogStateForUserAgentClient = function (outgoingRequestMessage, incomingResponseMessage) { - // If the request was sent over TLS, and the Request-URI contained a - // SIPS URI, the "secure" flag is set to TRUE. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - var secure = false; // FIXME: Currently no support for TLS. - // The route set MUST be set to the list of URIs in the Record-Route - // header field from the response, taken in reverse order and preserving - // all URI parameters. If no Record-Route header field is present in - // the response, the route set MUST be set to the empty set. This route - // set, even if empty, overrides any pre-existing route set for future - // requests in this dialog. The remote target MUST be set to the URI - // from the Contact header field of the response. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - var routeSet = incomingResponseMessage.getHeaders("record-route").reverse(); - var contact = incomingResponseMessage.parseHeader("contact"); - if (!contact) { // TODO: Review to make sure this will never happen - throw new Error("Contact undefined."); - } - if (!(contact instanceof messages_1.NameAddrHeader)) { - throw new Error("Contact not instance of NameAddrHeader."); - } - var remoteTarget = contact.uri; - // The local sequence number MUST be set to the value of the sequence - // number in the CSeq header field of the request. The remote sequence - // number MUST be empty (it is established when the remote UA sends a - // request within the dialog). The call identifier component of the - // dialog ID MUST be set to the value of the Call-ID in the request. - // The local tag component of the dialog ID MUST be set to the tag in - // the From field in the request, and the remote tag component of the - // dialog ID MUST be set to the tag in the To field of the response. A - // UAC MUST be prepared to receive a response without a tag in the To - // field, in which case the tag is considered to have a value of null. - // - // This is to maintain backwards compatibility with RFC 2543, which - // did not mandate To tags. - // - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - var localSequenceNumber = outgoingRequestMessage.cseq; - var remoteSequenceNumber = undefined; - var callId = outgoingRequestMessage.callId; - var localTag = outgoingRequestMessage.fromTag; - var remoteTag = incomingResponseMessage.toTag; - if (!callId) { // TODO: Review to make sure this will never happen - throw new Error("Call id undefined."); - } - if (!localTag) { // TODO: Review to make sure this will never happen - throw new Error("From tag undefined."); - } - if (!remoteTag) { // TODO: Review to make sure this will never happen - throw new Error("To tag undefined."); // FIXME: No backwards compatibility with RFC 2543 - } - // The remote URI MUST be set to the URI in the To field, and the local - // URI MUST be set to the URI in the From field. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - if (!outgoingRequestMessage.from) { // TODO: Review to make sure this will never happen - throw new Error("From undefined."); - } - if (!outgoingRequestMessage.to) { // TODO: Review to make sure this will never happen - throw new Error("To undefined."); - } - var localURI = outgoingRequestMessage.from.uri; - var remoteURI = outgoingRequestMessage.to.uri; - // A dialog can also be in the "early" state, which occurs when it is - // created with a provisional response, and then transition to the - // "confirmed" state when a 2xx final response arrives. - // https://tools.ietf.org/html/rfc3261#section-12 - if (!incomingResponseMessage.statusCode) { - throw new Error("Incoming response status code undefined."); - } - var early = incomingResponseMessage.statusCode < 200 ? true : false; - var dialogState = { - id: callId + localTag + remoteTag, - early: early, - callId: callId, - localTag: localTag, - remoteTag: remoteTag, - localSequenceNumber: localSequenceNumber, - remoteSequenceNumber: remoteSequenceNumber, - localURI: localURI, - remoteURI: remoteURI, - remoteTarget: remoteTarget, - routeSet: routeSet, - secure: secure - }; - return dialogState; - }; - /** - * The UAS then constructs the state of the dialog. This state MUST be - * maintained for the duration of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.1.1 - * @param incomingRequestMessage - Incoming request message creating dialog. - * @param toTag - Tag in the To field in the response to the incoming request. - */ - Dialog.initialDialogStateForUserAgentServer = function (incomingRequestMessage, toTag, early) { - if (early === void 0) { early = false; } - // If the request arrived over TLS, and the Request-URI contained a SIPS - // URI, the "secure" flag is set to TRUE. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - var secure = false; // FIXME: Currently no support for TLS. - // The route set MUST be set to the list of URIs in the Record-Route - // header field from the request, taken in order and preserving all URI - // parameters. If no Record-Route header field is present in the - // request, the route set MUST be set to the empty set. This route set, - // even if empty, overrides any pre-existing route set for future - // requests in this dialog. The remote target MUST be set to the URI - // from the Contact header field of the request. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - var routeSet = incomingRequestMessage.getHeaders("record-route"); - var contact = incomingRequestMessage.parseHeader("contact"); - if (!contact) { // TODO: Review to make sure this will never happen - throw new Error("Contact undefined."); - } - if (!(contact instanceof messages_1.NameAddrHeader)) { - throw new Error("Contact not instance of NameAddrHeader."); - } - var remoteTarget = contact.uri; - // The remote sequence number MUST be set to the value of the sequence - // number in the CSeq header field of the request. The local sequence - // number MUST be empty. The call identifier component of the dialog ID - // MUST be set to the value of the Call-ID in the request. The local - // tag component of the dialog ID MUST be set to the tag in the To field - // in the response to the request (which always includes a tag), and the - // remote tag component of the dialog ID MUST be set to the tag from the - // From field in the request. A UAS MUST be prepared to receive a - // request without a tag in the From field, in which case the tag is - // considered to have a value of null. - // - // This is to maintain backwards compatibility with RFC 2543, which - // did not mandate From tags. - // - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - var remoteSequenceNumber = incomingRequestMessage.cseq; - var localSequenceNumber = undefined; - var callId = incomingRequestMessage.callId; - var localTag = toTag; - var remoteTag = incomingRequestMessage.fromTag; - // The remote URI MUST be set to the URI in the From field, and the - // local URI MUST be set to the URI in the To field. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - var remoteURI = incomingRequestMessage.from.uri; - var localURI = incomingRequestMessage.to.uri; - var dialogState = { - id: callId + localTag + remoteTag, - early: early, - callId: callId, - localTag: localTag, - remoteTag: remoteTag, - localSequenceNumber: localSequenceNumber, - remoteSequenceNumber: remoteSequenceNumber, - localURI: localURI, - remoteURI: remoteURI, - remoteTarget: remoteTarget, - routeSet: routeSet, - secure: secure - }; - return dialogState; - }; - /** Destructor. */ - Dialog.prototype.dispose = function () { - this.core.dialogs.delete(this.id); - }; - Object.defineProperty(Dialog.prototype, "id", { - /** - * A dialog is identified at each UA with a dialog ID, which consists of - * a Call-ID value, a local tag and a remote tag. The dialog ID at each - * UA involved in the dialog is not the same. Specifically, the local - * tag at one UA is identical to the remote tag at the peer UA. The - * tags are opaque tokens that facilitate the generation of unique - * dialog IDs. - * https://tools.ietf.org/html/rfc3261#section-12 - */ - get: function () { - return this.dialogState.id; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "early", { - /** - * A dialog can also be in the "early" state, which occurs when it is - * created with a provisional response, and then it transition to the - * "confirmed" state when a 2xx final response received or is sent. - * - * Note: RFC 3261 is concise on when a dialog is "confirmed", but it - * can be a point of confusion if an INVITE dialog is "confirmed" after - * a 2xx is sent or after receiving the ACK for the 2xx response. - * With careful reading it can be inferred a dialog is always is - * "confirmed" when the 2xx is sent (regardless of type of dialog). - * However a INVITE dialog does have additional considerations - * when it is confirmed but an ACK has not yet been received (in - * particular with regard to a callee sending BYE requests). - */ - get: function () { - return this.dialogState.early; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "callId", { - /** Call identifier component of the dialog id. */ - get: function () { - return this.dialogState.callId; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "localTag", { - /** Local tag component of the dialog id. */ - get: function () { - return this.dialogState.localTag; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "remoteTag", { - /** Remote tag component of the dialog id. */ - get: function () { - return this.dialogState.remoteTag; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "localSequenceNumber", { - /** Local sequence number (used to order requests from the UA to its peer). */ - get: function () { - return this.dialogState.localSequenceNumber; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "remoteSequenceNumber", { - /** Remote sequence number (used to order requests from its peer to the UA). */ - get: function () { - return this.dialogState.remoteSequenceNumber; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "localURI", { - /** Local URI. */ - get: function () { - return this.dialogState.localURI; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "remoteURI", { - /** Remote URI. */ - get: function () { - return this.dialogState.remoteURI; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "remoteTarget", { - /** Remote target. */ - get: function () { - return this.dialogState.remoteTarget; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "routeSet", { - /** - * Route set, which is an ordered list of URIs. The route set is the - * list of servers that need to be traversed to send a request to the peer. - */ - get: function () { - return this.dialogState.routeSet; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "secure", { - /** - * If the request was sent over TLS, and the Request-URI contained - * a SIPS URI, the "secure" flag is set to true. *NOT IMPLEMENTED* - */ - get: function () { - return this.dialogState.secure; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "userAgentCore", { - /** The user agent core servicing this dialog. */ - get: function () { - return this.core; - }, - enumerable: true, - configurable: true - }); - /** Confirm the dialog. Only matters if dialog is currently early. */ - Dialog.prototype.confirm = function () { - this.dialogState.early = false; - }; - /** - * Requests sent within a dialog, as any other requests, are atomic. If - * a particular request is accepted by the UAS, all the state changes - * associated with it are performed. If the request is rejected, none - * of the state changes are performed. - * - * Note that some requests, such as INVITEs, affect several pieces of - * state. - * - * https://tools.ietf.org/html/rfc3261#section-12.2.2 - * @param message - Incoming request message within this dialog. - */ - Dialog.prototype.receiveRequest = function (message) { - // ACK guard. - // By convention, the handling of ACKs is the responsibility - // the particular dialog implementation. For example, see SessionDialog. - // Furthermore, ACKs have same sequence number as the associated INVITE. - if (message.method === messages_1.C.ACK) { - return; - } - // If the remote sequence number was not empty, but the sequence number - // of the request is lower than the remote sequence number, the request - // is out of order and MUST be rejected with a 500 (Server Internal - // Error) response. If the remote sequence number was not empty, and - // the sequence number of the request is greater than the remote - // sequence number, the request is in order. It is possible for the - // CSeq sequence number to be higher than the remote sequence number by - // more than one. This is not an error condition, and a UAS SHOULD be - // prepared to receive and process requests with CSeq values more than - // one higher than the previous received request. The UAS MUST then set - // the remote sequence number to the value of the sequence number in the - // CSeq header field value in the request. - // - // If a proxy challenges a request generated by the UAC, the UAC has - // to resubmit the request with credentials. The resubmitted request - // will have a new CSeq number. The UAS will never see the first - // request, and thus, it will notice a gap in the CSeq number space. - // Such a gap does not represent any error condition. - // - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (this.remoteSequenceNumber) { - if (message.cseq <= this.remoteSequenceNumber) { - throw new Error("Out of sequence in dialog request. Did you forget to call sequenceGuard()?"); - } - this.dialogState.remoteSequenceNumber = message.cseq; - } - // If the remote sequence number is empty, it MUST be set to the value - // of the sequence number in the CSeq header field value in the request. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (!this.remoteSequenceNumber) { - this.dialogState.remoteSequenceNumber = message.cseq; - } - // When a UAS receives a target refresh request, it MUST replace the - // dialog's remote target URI with the URI from the Contact header field - // in that request, if present. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - // Note: "target refresh request" processing delegated to sub-class. - }; - /** - * If the dialog identifier in the 2xx response matches the dialog - * identifier of an existing dialog, the dialog MUST be transitioned to - * the "confirmed" state, and the route set for the dialog MUST be - * recomputed based on the 2xx response using the procedures of Section - * 12.2.1.2. Otherwise, a new dialog in the "confirmed" state MUST be - * constructed using the procedures of Section 12.1.2. - * - * Note that the only piece of state that is recomputed is the route - * set. Other pieces of state such as the highest sequence numbers - * (remote and local) sent within the dialog are not recomputed. The - * route set only is recomputed for backwards compatibility. RFC - * 2543 did not mandate mirroring of the Record-Route header field in - * a 1xx, only 2xx. However, we cannot update the entire state of - * the dialog, since mid-dialog requests may have been sent within - * the early dialog, modifying the sequence numbers, for example. - * - * https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - */ - Dialog.prototype.recomputeRouteSet = function (message) { - this.dialogState.routeSet = message.getHeaders("record-route").reverse(); - }; - /** - * A request within a dialog is constructed by using many of the - * components of the state stored as part of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - * @param method - Outgoing request method. - */ - Dialog.prototype.createOutgoingRequestMessage = function (method, options) { - // The URI in the To field of the request MUST be set to the remote URI - // from the dialog state. The tag in the To header field of the request - // MUST be set to the remote tag of the dialog ID. The From URI of the - // request MUST be set to the local URI from the dialog state. The tag - // in the From header field of the request MUST be set to the local tag - // of the dialog ID. If the value of the remote or local tags is null, - // the tag parameter MUST be omitted from the To or From header fields, - // respectively. - // - // Usage of the URI from the To and From fields in the original - // request within subsequent requests is done for backwards - // compatibility with RFC 2543, which used the URI for dialog - // identification. In this specification, only the tags are used for - // dialog identification. It is expected that mandatory reflection - // of the original To and From URI in mid-dialog requests will be - // deprecated in a subsequent revision of this specification. - // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - var toUri = this.remoteURI; - var toTag = this.remoteTag; - var fromUri = this.localURI; - var fromTag = this.localTag; - // The Call-ID of the request MUST be set to the Call-ID of the dialog. - // Requests within a dialog MUST contain strictly monotonically - // increasing and contiguous CSeq sequence numbers (increasing-by-one) - // in each direction (excepting ACK and CANCEL of course, whose numbers - // equal the requests being acknowledged or cancelled). Therefore, if - // the local sequence number is not empty, the value of the local - // sequence number MUST be incremented by one, and this value MUST be - // placed into the CSeq header field. If the local sequence number is - // empty, an initial value MUST be chosen using the guidelines of - // Section 8.1.1.5. The method field in the CSeq header field value - // MUST match the method of the request. - // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - var callId = this.callId; - var cseq; - if (options && options.cseq) { - cseq = options.cseq; - } - else if (!this.dialogState.localSequenceNumber) { - cseq = this.dialogState.localSequenceNumber = 1; // https://tools.ietf.org/html/rfc3261#section-8.1.1.5 - } - else { - cseq = this.dialogState.localSequenceNumber += 1; - } - // The UAC uses the remote target and route set to build the Request-URI - // and Route header field of the request. - // - // If the route set is empty, the UAC MUST place the remote target URI - // into the Request-URI. The UAC MUST NOT add a Route header field to - // the request. - // - // If the route set is not empty, and the first URI in the route set - // contains the lr parameter (see Section 19.1.1), the UAC MUST place - // the remote target URI into the Request-URI and MUST include a Route - // header field containing the route set values in order, including all - // parameters. - // - // If the route set is not empty, and its first URI does not contain the - // lr parameter, the UAC MUST place the first URI from the route set - // into the Request-URI, stripping any parameters that are not allowed - // in a Request-URI. The UAC MUST add a Route header field containing - // the remainder of the route set values in order, including all - // parameters. The UAC MUST then place the remote target URI into the - // Route header field as the last value. - // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - // The lr parameter, when present, indicates that the element - // responsible for this resource implements the routing mechanisms - // specified in this document. This parameter will be used in the - // URIs proxies place into Record-Route header field values, and - // may appear in the URIs in a pre-existing route set. - // - // This parameter is used to achieve backwards compatibility with - // systems implementing the strict-routing mechanisms of RFC 2543 - // and the rfc2543bis drafts up to bis-05. An element preparing - // to send a request based on a URI not containing this parameter - // can assume the receiving element implements strict-routing and - // reformat the message to preserve the information in the - // Request-URI. - // https://tools.ietf.org/html/rfc3261#section-19.1.1 - // NOTE: Not backwards compatible with RFC 2543 (no support for strict-routing). - var ruri = this.remoteTarget; - var routeSet = this.routeSet; - var extraHeaders = options && options.extraHeaders; - var body = options && options.body; - // The relative order of header fields with different field names is not - // significant. However, it is RECOMMENDED that header fields which are - // needed for proxy processing (Via, Route, Record-Route, Proxy-Require, - // Max-Forwards, and Proxy-Authorization, for example) appear towards - // the top of the message to facilitate rapid parsing. - // https://tools.ietf.org/html/rfc3261#section-7.3.1 - var message = this.userAgentCore.makeOutgoingRequestMessage(method, ruri, fromUri, toUri, { - callId: callId, - cseq: cseq, - fromTag: fromTag, - toTag: toTag, - routeSet: routeSet - }, extraHeaders, body); - return message; - }; - /** - * If the remote sequence number was not empty, but the sequence number - * of the request is lower than the remote sequence number, the request - * is out of order and MUST be rejected with a 500 (Server Internal - * Error) response. - * https://tools.ietf.org/html/rfc3261#section-12.2.2 - * @param request - Incoming request to guard. - * @returns True if the program execution is to continue in the branch in question. - * Otherwise a 500 Server Internal Error was stateless sent and request processing must stop. - */ - Dialog.prototype.sequenceGuard = function (message) { - // ACK guard. - // By convention, handling of unexpected ACKs is responsibility - // the particular dialog implementation. For example, see SessionDialog. - // Furthermore, we cannot reply to an "out of sequence" ACK. - if (message.method === messages_1.C.ACK) { - return true; - } - // Note: We are rejecting on "less than or equal to" the remote - // sequence number (excepting ACK whose numbers equal the requests - // being acknowledged or cancelled), which is the correct thing to - // do in our case. The only time a request with the same sequence number - // will show up here if is a) it is a very late retransmission of a - // request we already handled or b) it is a different request with the - // same sequence number which would be violation of the standard. - // Request retransmissions are absorbed by the transaction layer, - // so any request with a duplicate sequence number getting here - // would have to be a retransmission after the transaction terminated - // or a broken request (with unique via branch value). - // Requests within a dialog MUST contain strictly monotonically - // increasing and contiguous CSeq sequence numbers (increasing-by-one) - // in each direction (excepting ACK and CANCEL of course, whose numbers - // equal the requests being acknowledged or cancelled). Therefore, if - // the local sequence number is not empty, the value of the local - // sequence number MUST be incremented by one, and this value MUST be - // placed into the CSeq header field. - // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - if (this.remoteSequenceNumber && message.cseq <= this.remoteSequenceNumber) { - this.core.replyStateless(message, { statusCode: 500 }); - return false; - } - return true; - }; - return Dialog; -}()); -exports.Dialog = Dialog; - - -/***/ }), -/* 5 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -// Directories -tslib_1.__exportStar(__webpack_require__(6), exports); -// Files -tslib_1.__exportStar(__webpack_require__(8), exports); -tslib_1.__exportStar(__webpack_require__(19), exports); -tslib_1.__exportStar(__webpack_require__(11), exports); -tslib_1.__exportStar(__webpack_require__(10), exports); -tslib_1.__exportStar(__webpack_require__(9), exports); -tslib_1.__exportStar(__webpack_require__(17), exports); -tslib_1.__exportStar(__webpack_require__(13), exports); -tslib_1.__exportStar(__webpack_require__(18), exports); -tslib_1.__exportStar(__webpack_require__(22), exports); -tslib_1.__exportStar(__webpack_require__(14), exports); -tslib_1.__exportStar(__webpack_require__(15), exports); - - -/***/ }), -/* 6 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -tslib_1.__exportStar(__webpack_require__(7), exports); - - -/***/ }), -/* 7 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * SIP Methods - * @internal - */ -var C; -(function (C) { - C.ACK = "ACK"; - C.BYE = "BYE"; - C.CANCEL = "CANCEL"; - C.INFO = "INFO"; - C.INVITE = "INVITE"; - C.MESSAGE = "MESSAGE"; - C.NOTIFY = "NOTIFY"; - C.OPTIONS = "OPTIONS"; - C.REGISTER = "REGISTER"; - C.UPDATE = "UPDATE"; - C.SUBSCRIBE = "SUBSCRIBE"; - C.PUBLISH = "PUBLISH"; - C.REFER = "REFER"; - C.PRACK = "PRACK"; -})(C = exports.C || (exports.C = {})); - - -/***/ }), -/* 8 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var incoming_request_message_1 = __webpack_require__(9); -var incoming_response_message_1 = __webpack_require__(17); -var outgoing_request_message_1 = __webpack_require__(18); -/** - * Create a Body given a legacy body type. - * @param bodyLegacy - Body Object - * @internal - */ -function fromBodyLegacy(bodyLegacy) { - var content = (typeof bodyLegacy === "string") ? bodyLegacy : bodyLegacy.body; - var contentType = (typeof bodyLegacy === "string") ? "application/sdp" : bodyLegacy.contentType; - var contentDisposition = contentTypeToContentDisposition(contentType); - var body = { contentDisposition: contentDisposition, contentType: contentType, content: content }; - return body; -} -exports.fromBodyLegacy = fromBodyLegacy; -/** - * Given a message, get a normalized body. - * The content disposition is inferred if not set. - * @param message - The message. - * @internal - */ -function getBody(message) { - var contentDisposition; - var contentType; - var content; - // We're in UAS role, receiving incoming request - if (message instanceof incoming_request_message_1.IncomingRequestMessage) { - if (message.body) { - // FIXME: Parsing needs typing - var parse = message.parseHeader("Content-Disposition"); - contentDisposition = parse ? parse.type : undefined; - contentType = message.parseHeader("Content-Type"); - content = message.body; - } - } - // We're in UAC role, receiving incoming response - if (message instanceof incoming_response_message_1.IncomingResponseMessage) { - if (message.body) { - // FIXME: Parsing needs typing - var parse = message.parseHeader("Content-Disposition"); - contentDisposition = parse ? parse.type : undefined; - contentType = message.parseHeader("Content-Type"); - content = message.body; - } - } - // We're in UAC role, sending outgoing request - if (message instanceof outgoing_request_message_1.OutgoingRequestMessage) { - if (message.body) { - contentDisposition = message.getHeader("Content-Disposition"); - contentType = message.getHeader("Content-Type"); - if (typeof message.body === "string") { - // FIXME: OutgoingRequest should not allow a "string" body without a "Content-Type" header. - if (!contentType) { - throw new Error("Header content type header does not equal body content type."); - } - content = message.body; - } - else { - // FIXME: OutgoingRequest should not allow the "Content-Type" header not to match th body content type - if (contentType && contentType !== message.body.contentType) { - throw new Error("Header content type header does not equal body content type."); - } - contentType = message.body.contentType; - content = message.body.body; - } - } - } - // We're in UAS role, sending outgoing response - if (isBody(message)) { - contentDisposition = message.contentDisposition; - contentType = message.contentType; - content = message.content; - } - // No content, no body. - if (!content) { - return undefined; - } - if (contentType && !contentDisposition) { - contentDisposition = contentTypeToContentDisposition(contentType); - } - if (!contentDisposition) { - throw new Error("Content disposition undefined."); - } - if (!contentType) { - throw new Error("Content type undefined."); - } - return { - contentDisposition: contentDisposition, - contentType: contentType, - content: content - }; -} -exports.getBody = getBody; -/** - * User-Defined Type Guard for Body. - * @param body - Body to check. - * @internal - */ -function isBody(body) { - return body && - typeof body.content === "string" && - typeof body.contentType === "string" && - body.contentDisposition === undefined ? true : typeof body.contentDisposition === "string"; -} -exports.isBody = isBody; -// If the Content-Disposition header field is missing, bodies of -// Content-Type application/sdp imply the disposition "session", while -// other content types imply "render". -// https://tools.ietf.org/html/rfc3261#section-13.2.1 -function contentTypeToContentDisposition(contentType) { - if (contentType === "application/sdp") { - return "session"; - } - else { - return "render"; - } -} - - -/***/ }), -/* 9 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var incoming_message_1 = __webpack_require__(10); -/** - * Incoming request message. - * @public - */ -var IncomingRequestMessage = /** @class */ (function (_super) { - tslib_1.__extends(IncomingRequestMessage, _super); - function IncomingRequestMessage() { - return _super.call(this) || this; - } - return IncomingRequestMessage; -}(incoming_message_1.IncomingMessage)); -exports.IncomingRequestMessage = IncomingRequestMessage; - - -/***/ }), -/* 10 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var grammar_1 = __webpack_require__(11); -var utils_1 = __webpack_require__(16); -/** - * Incoming message. - * @public - */ -var IncomingMessage = /** @class */ (function () { - function IncomingMessage() { - this.headers = {}; - } - /** - * Insert a header of the given name and value into the last position of the - * header array. - * @param name - header name - * @param value - header value - */ - IncomingMessage.prototype.addHeader = function (name, value) { - var header = { raw: value }; - name = utils_1.headerize(name); - if (this.headers[name]) { - this.headers[name].push(header); - } - else { - this.headers[name] = [header]; - } - }; - /** - * Get the value of the given header name at the given position. - * @param name - header name - * @returns Returns the specified header, undefined if header doesn't exist. - */ - IncomingMessage.prototype.getHeader = function (name) { - var header = this.headers[utils_1.headerize(name)]; - if (header) { - if (header[0]) { - return header[0].raw; - } - } - else { - return; - } - }; - /** - * Get the header/s of the given name. - * @param name - header name - * @returns Array - with all the headers of the specified name. - */ - IncomingMessage.prototype.getHeaders = function (name) { - var header = this.headers[utils_1.headerize(name)]; - var result = []; - if (!header) { - return []; - } - for (var _i = 0, header_1 = header; _i < header_1.length; _i++) { - var headerPart = header_1[_i]; - result.push(headerPart.raw); - } - return result; - }; - /** - * Verify the existence of the given header. - * @param name - header name - * @returns true if header with given name exists, false otherwise - */ - IncomingMessage.prototype.hasHeader = function (name) { - return !!this.headers[utils_1.headerize(name)]; - }; - /** - * Parse the given header on the given index. - * @param name - header name - * @param idx - header index - * @returns Parsed header object, undefined if the - * header is not present or in case of a parsing error. - */ - IncomingMessage.prototype.parseHeader = function (name, idx) { - if (idx === void 0) { idx = 0; } - name = utils_1.headerize(name); - if (!this.headers[name]) { - // this.logger.log("header '" + name + "' not present"); - return; - } - else if (idx >= this.headers[name].length) { - // this.logger.log("not so many '" + name + "' headers present"); - return; - } - var header = this.headers[name][idx]; - var value = header.raw; - if (header.parsed) { - return header.parsed; - } - // substitute '-' by '_' for grammar rule matching. - var parsed = grammar_1.Grammar.parse(value, name.replace(/-/g, "_")); - if (parsed === -1) { - this.headers[name].splice(idx, 1); // delete from headers - // this.logger.warn('error parsing "' + name + '" header field with value "' + value + '"'); - return; - } - else { - header.parsed = parsed; - return parsed; - } - }; - /** - * Message Header attribute selector. Alias of parseHeader. - * @param name - header name - * @param idx - header index - * @returns Parsed header object, undefined if the - * header is not present or in case of a parsing error. - * - * @example - * message.s('via',3).port - */ - IncomingMessage.prototype.s = function (name, idx) { - if (idx === void 0) { idx = 0; } - return this.parseHeader(name, idx); - }; - /** - * Replace the value of the given header by the value. - * @param name - header name - * @param value - header value - */ - IncomingMessage.prototype.setHeader = function (name, value) { - this.headers[utils_1.headerize(name)] = [{ raw: value }]; - }; - IncomingMessage.prototype.toString = function () { - return this.data; - }; - return IncomingMessage; -}()); -exports.IncomingMessage = IncomingMessage; - - -/***/ }), -/* 11 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var pegGrammar = tslib_1.__importStar(__webpack_require__(12)); -/** - * Grammar. - * @internal - */ -var Grammar; -(function (Grammar) { - /** - * Parse. - * @param input - - * @param startRule - - */ - function parse(input, startRule) { - var options = { startRule: startRule }; - try { - pegGrammar.parse(input, options); - } - catch (e) { - options.data = -1; - } - return options.data; - } - Grammar.parse = parse; - /** - * Parse the given string and returns a SIP.NameAddrHeader instance or undefined if - * it is an invalid NameAddrHeader. - * @param name_addr_header - - */ - function nameAddrHeaderParse(nameAddrHeader) { - var parsedNameAddrHeader = Grammar.parse(nameAddrHeader, "Name_Addr_Header"); - return parsedNameAddrHeader !== -1 ? parsedNameAddrHeader : undefined; - } - Grammar.nameAddrHeaderParse = nameAddrHeaderParse; - /** - * Parse the given string and returns a SIP.URI instance or undefined if - * it is an invalid URI. - * @param uri - - */ - function URIParse(uri) { - var parsedUri = Grammar.parse(uri, "SIP_URI"); - return parsedUri !== -1 ? parsedUri : undefined; - } - Grammar.URIParse = URIParse; -})(Grammar = exports.Grammar || (exports.Grammar = {})); - - -/***/ }), -/* 12 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// tslint:disable:interface-name -// tslint:disable: trailing-comma -// tslint:disable: object-literal-sort-keys -// tslint:disable: max-line-length -// tslint:disable: only-arrow-functions -// tslint:disable: one-variable-per-declaration -// tslint:disable: no-consecutive-blank-lines -// tslint:disable: align -// tslint:disable: radix -// tslint:disable: quotemark -// tslint:disable: semicolon -// tslint:disable: object-literal-shorthand -// tslint:disable: variable-name -// tslint:disable: no-var-keyword -// tslint:disable: whitespace -// tslint:disable: curly -// tslint:disable: prefer-const -// tslint:disable: object-literal-key-quotes -// tslint:disable: no-string-literal -// tslint:disable: one-line -// tslint:disable: no-unused-expression -// tslint:disable: space-before-function-paren -// tslint:disable: arrow-return-shorthand -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -// Generated by PEG.js v. 0.10.0 (ts-pegjs plugin v. 0.2.6 ) -// -// https://pegjs.org/ https://github.com/metadevpro/ts-pegjs -var name_addr_header_1 = __webpack_require__(13); -var uri_1 = __webpack_require__(15); -var SyntaxError = /** @class */ (function (_super) { - tslib_1.__extends(SyntaxError, _super); - function SyntaxError(message, expected, found, location) { - var _this = _super.call(this) || this; - _this.message = message; - _this.expected = expected; - _this.found = found; - _this.location = location; - _this.name = "SyntaxError"; - if (typeof Error.captureStackTrace === "function") { - Error.captureStackTrace(_this, SyntaxError); - } - return _this; - } - SyntaxError.buildMessage = function (expected, found) { - function hex(ch) { - return ch.charCodeAt(0).toString(16).toUpperCase(); - } - function literalEscape(s) { - return s - .replace(/\\/g, "\\\\") - .replace(/"/g, "\\\"") - .replace(/\0/g, "\\0") - .replace(/\t/g, "\\t") - .replace(/\n/g, "\\n") - .replace(/\r/g, "\\r") - .replace(/[\x00-\x0F]/g, function (ch) { return "\\x0" + hex(ch); }) - .replace(/[\x10-\x1F\x7F-\x9F]/g, function (ch) { return "\\x" + hex(ch); }); - } - function classEscape(s) { - return s - .replace(/\\/g, "\\\\") - .replace(/\]/g, "\\]") - .replace(/\^/g, "\\^") - .replace(/-/g, "\\-") - .replace(/\0/g, "\\0") - .replace(/\t/g, "\\t") - .replace(/\n/g, "\\n") - .replace(/\r/g, "\\r") - .replace(/[\x00-\x0F]/g, function (ch) { return "\\x0" + hex(ch); }) - .replace(/[\x10-\x1F\x7F-\x9F]/g, function (ch) { return "\\x" + hex(ch); }); - } - function describeExpectation(expectation) { - switch (expectation.type) { - case "literal": - return "\"" + literalEscape(expectation.text) + "\""; - case "class": - var escapedParts = expectation.parts.map(function (part) { - return Array.isArray(part) - ? classEscape(part[0]) + "-" + classEscape(part[1]) - : classEscape(part); - }); - return "[" + (expectation.inverted ? "^" : "") + escapedParts + "]"; - case "any": - return "any character"; - case "end": - return "end of input"; - case "other": - return expectation.description; - } - } - function describeExpected(expected1) { - var descriptions = expected1.map(describeExpectation); - var i; - var j; - descriptions.sort(); - if (descriptions.length > 0) { - for (i = 1, j = 1; i < descriptions.length; i++) { - if (descriptions[i - 1] !== descriptions[i]) { - descriptions[j] = descriptions[i]; - j++; - } - } - descriptions.length = j; - } - switch (descriptions.length) { - case 1: - return descriptions[0]; - case 2: - return descriptions[0] + " or " + descriptions[1]; - default: - return descriptions.slice(0, -1).join(", ") - + ", or " - + descriptions[descriptions.length - 1]; - } - } - function describeFound(found1) { - return found1 ? "\"" + literalEscape(found1) + "\"" : "end of input"; - } - return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found."; - }; - return SyntaxError; -}(Error)); -exports.SyntaxError = SyntaxError; -function peg$parse(input, options) { - options = options !== undefined ? options : {}; - var peg$FAILED = {}; - var peg$startRuleIndices = { Contact: 119, Name_Addr_Header: 156, Record_Route: 176, Request_Response: 81, SIP_URI: 45, Subscription_State: 186, Supported: 191, Require: 182, Via: 194, absoluteURI: 84, Call_ID: 118, Content_Disposition: 130, Content_Length: 135, Content_Type: 136, CSeq: 146, displayName: 122, Event: 149, From: 151, host: 52, Max_Forwards: 154, Min_SE: 213, Proxy_Authenticate: 157, quoted_string: 40, Refer_To: 178, Replaces: 179, Session_Expires: 210, stun_URI: 217, To: 192, turn_URI: 223, uuid: 226, WWW_Authenticate: 209, challenge: 158, sipfrag: 230, Referred_By: 231 }; - var peg$startRuleIndex = 119; - var peg$consts = [ - "\r\n", - peg$literalExpectation("\r\n", false), - /^[0-9]/, - peg$classExpectation([["0", "9"]], false, false), - /^[a-zA-Z]/, - peg$classExpectation([["a", "z"], ["A", "Z"]], false, false), - /^[0-9a-fA-F]/, - peg$classExpectation([["0", "9"], ["a", "f"], ["A", "F"]], false, false), - /^[\0-\xFF]/, - peg$classExpectation([["\0", "\xFF"]], false, false), - /^["]/, - peg$classExpectation(["\""], false, false), - " ", - peg$literalExpectation(" ", false), - "\t", - peg$literalExpectation("\t", false), - /^[a-zA-Z0-9]/, - peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"]], false, false), - ";", - peg$literalExpectation(";", false), - "/", - peg$literalExpectation("/", false), - "?", - peg$literalExpectation("?", false), - ":", - peg$literalExpectation(":", false), - "@", - peg$literalExpectation("@", false), - "&", - peg$literalExpectation("&", false), - "=", - peg$literalExpectation("=", false), - "+", - peg$literalExpectation("+", false), - "$", - peg$literalExpectation("$", false), - ",", - peg$literalExpectation(",", false), - "-", - peg$literalExpectation("-", false), - "_", - peg$literalExpectation("_", false), - ".", - peg$literalExpectation(".", false), - "!", - peg$literalExpectation("!", false), - "~", - peg$literalExpectation("~", false), - "*", - peg$literalExpectation("*", false), - "'", - peg$literalExpectation("'", false), - "(", - peg$literalExpectation("(", false), - ")", - peg$literalExpectation(")", false), - "%", - peg$literalExpectation("%", false), - function () { return " "; }, - function () { return ':'; }, - /^[!-~]/, - peg$classExpectation([["!", "~"]], false, false), - /^[\x80-\uFFFF]/, - peg$classExpectation([["\x80", "\uFFFF"]], false, false), - /^[\x80-\xBF]/, - peg$classExpectation([["\x80", "\xBF"]], false, false), - /^[a-f]/, - peg$classExpectation([["a", "f"]], false, false), - "`", - peg$literalExpectation("`", false), - "<", - peg$literalExpectation("<", false), - ">", - peg$literalExpectation(">", false), - "\\", - peg$literalExpectation("\\", false), - "[", - peg$literalExpectation("[", false), - "]", - peg$literalExpectation("]", false), - "{", - peg$literalExpectation("{", false), - "}", - peg$literalExpectation("}", false), - function () { return "*"; }, - function () { return "/"; }, - function () { return "="; }, - function () { return "("; }, - function () { return ")"; }, - function () { return ">"; }, - function () { return "<"; }, - function () { return ","; }, - function () { return ";"; }, - function () { return ":"; }, - function () { return "\""; }, - /^[!-']/, - peg$classExpectation([["!", "'"]], false, false), - /^[*-[]/, - peg$classExpectation([["*", "["]], false, false), - /^[\]-~]/, - peg$classExpectation([["]", "~"]], false, false), - function (contents) { - return contents; - }, - /^[#-[]/, - peg$classExpectation([["#", "["]], false, false), - /^[\0-\t]/, - peg$classExpectation([["\0", "\t"]], false, false), - /^[\x0B-\f]/, - peg$classExpectation([["\x0B", "\f"]], false, false), - /^[\x0E-\x7F]/, - peg$classExpectation([["\x0E", "\x7F"]], false, false), - function () { - options = options || { data: {} }; - options.data.uri = new uri_1.URI(options.data.scheme, options.data.user, options.data.host, options.data.port); - delete options.data.scheme; - delete options.data.user; - delete options.data.host; - delete options.data.host_type; - delete options.data.port; - }, - function () { - options = options || { data: {} }; - options.data.uri = new uri_1.URI(options.data.scheme, options.data.user, options.data.host, options.data.port, options.data.uri_params, options.data.uri_headers); - delete options.data.scheme; - delete options.data.user; - delete options.data.host; - delete options.data.host_type; - delete options.data.port; - delete options.data.uri_params; - if (options.startRule === 'SIP_URI') { - options.data = options.data.uri; - } - }, - "sips", - peg$literalExpectation("sips", true), - "sip", - peg$literalExpectation("sip", true), - function (uri_scheme) { - options = options || { data: {} }; - options.data.scheme = uri_scheme; - }, - function () { - options = options || { data: {} }; - options.data.user = decodeURIComponent(text().slice(0, -1)); - }, - function () { - options = options || { data: {} }; - options.data.password = text(); - }, - function () { - options = options || { data: {} }; - options.data.host = text(); - return options.data.host; - }, - function () { - options = options || { data: {} }; - options.data.host_type = 'domain'; - return text(); - }, - /^[a-zA-Z0-9_\-]/, - peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"], "_", "-"], false, false), - /^[a-zA-Z0-9\-]/, - peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"], "-"], false, false), - function () { - options = options || { data: {} }; - options.data.host_type = 'IPv6'; - return text(); - }, - "::", - peg$literalExpectation("::", false), - function () { - options = options || { data: {} }; - options.data.host_type = 'IPv6'; - return text(); - }, - function () { - options = options || { data: {} }; - options.data.host_type = 'IPv4'; - return text(); - }, - "25", - peg$literalExpectation("25", false), - /^[0-5]/, - peg$classExpectation([["0", "5"]], false, false), - "2", - peg$literalExpectation("2", false), - /^[0-4]/, - peg$classExpectation([["0", "4"]], false, false), - "1", - peg$literalExpectation("1", false), - /^[1-9]/, - peg$classExpectation([["1", "9"]], false, false), - function (port) { - options = options || { data: {} }; - port = parseInt(port.join('')); - options.data.port = port; - return port; - }, - "transport=", - peg$literalExpectation("transport=", true), - "udp", - peg$literalExpectation("udp", true), - "tcp", - peg$literalExpectation("tcp", true), - "sctp", - peg$literalExpectation("sctp", true), - "tls", - peg$literalExpectation("tls", true), - function (transport) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['transport'] = transport.toLowerCase(); - }, - "user=", - peg$literalExpectation("user=", true), - "phone", - peg$literalExpectation("phone", true), - "ip", - peg$literalExpectation("ip", true), - function (user) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['user'] = user.toLowerCase(); - }, - "method=", - peg$literalExpectation("method=", true), - function (method) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['method'] = method; - }, - "ttl=", - peg$literalExpectation("ttl=", true), - function (ttl) { - options = options || { data: {} }; - if (!options.data.params) - options.data.params = {}; - options.data.params['ttl'] = ttl; - }, - "maddr=", - peg$literalExpectation("maddr=", true), - function (maddr) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['maddr'] = maddr; - }, - "lr", - peg$literalExpectation("lr", true), - function () { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['lr'] = undefined; - }, - function (param, value) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - if (value === null) { - value = undefined; - } - else { - value = value[1]; - } - options.data.uri_params[param.toLowerCase()] = value; - }, - function (hname, hvalue) { - hname = hname.join('').toLowerCase(); - hvalue = hvalue.join(''); - options = options || { data: {} }; - if (!options.data.uri_headers) - options.data.uri_headers = {}; - if (!options.data.uri_headers[hname]) { - options.data.uri_headers[hname] = [hvalue]; - } - else { - options.data.uri_headers[hname].push(hvalue); - } - }, - function () { - options = options || { data: {} }; - // lots of tests fail if this isn't guarded... - if (options.startRule === 'Refer_To') { - options.data.uri = new uri_1.URI(options.data.scheme, options.data.user, options.data.host, options.data.port, options.data.uri_params, options.data.uri_headers); - delete options.data.scheme; - delete options.data.user; - delete options.data.host; - delete options.data.host_type; - delete options.data.port; - delete options.data.uri_params; - } - }, - "//", - peg$literalExpectation("//", false), - function () { - options = options || { data: {} }; - options.data.scheme = text(); - }, - peg$literalExpectation("SIP", true), - function () { - options = options || { data: {} }; - options.data.sip_version = text(); - }, - "INVITE", - peg$literalExpectation("INVITE", false), - "ACK", - peg$literalExpectation("ACK", false), - "VXACH", - peg$literalExpectation("VXACH", false), - "OPTIONS", - peg$literalExpectation("OPTIONS", false), - "BYE", - peg$literalExpectation("BYE", false), - "CANCEL", - peg$literalExpectation("CANCEL", false), - "REGISTER", - peg$literalExpectation("REGISTER", false), - "SUBSCRIBE", - peg$literalExpectation("SUBSCRIBE", false), - "NOTIFY", - peg$literalExpectation("NOTIFY", false), - "REFER", - peg$literalExpectation("REFER", false), - "PUBLISH", - peg$literalExpectation("PUBLISH", false), - function () { - options = options || { data: {} }; - options.data.method = text(); - return options.data.method; - }, - function (status_code) { - options = options || { data: {} }; - options.data.status_code = parseInt(status_code.join('')); - }, - function () { - options = options || { data: {} }; - options.data.reason_phrase = text(); - }, - function () { - options = options || { data: {} }; - options.data = text(); - }, - function () { - var idx, length; - options = options || { data: {} }; - length = options.data.multi_header.length; - for (idx = 0; idx < length; idx++) { - if (options.data.multi_header[idx].parsed === null) { - options.data = null; - break; - } - } - if (options.data !== null) { - options.data = options.data.multi_header; - } - else { - options.data = -1; - } - }, - function () { - var header; - options = options || { data: {} }; - if (!options.data.multi_header) - options.data.multi_header = []; - try { - header = new name_addr_header_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); - delete options.data.uri; - delete options.data.displayName; - delete options.data.params; - } - catch (e) { - header = null; - } - options.data.multi_header.push({ 'position': peg$currPos, - 'offset': location().start.offset, - 'parsed': header - }); - }, - function (displayName) { - displayName = text().trim(); - if (displayName[0] === '\"') { - displayName = displayName.substring(1, displayName.length - 1); - } - options = options || { data: {} }; - options.data.displayName = displayName; - }, - "q", - peg$literalExpectation("q", true), - function (q) { - options = options || { data: {} }; - if (!options.data.params) - options.data.params = {}; - options.data.params['q'] = q; - }, - "expires", - peg$literalExpectation("expires", true), - function (expires) { - options = options || { data: {} }; - if (!options.data.params) - options.data.params = {}; - options.data.params['expires'] = expires; - }, - function (delta_seconds) { - return parseInt(delta_seconds.join('')); - }, - "0", - peg$literalExpectation("0", false), - function () { - return parseFloat(text()); - }, - function (param, value) { - options = options || { data: {} }; - if (!options.data.params) - options.data.params = {}; - if (value === null) { - value = undefined; - } - else { - value = value[1]; - } - options.data.params[param.toLowerCase()] = value; - }, - "render", - peg$literalExpectation("render", true), - "session", - peg$literalExpectation("session", true), - "icon", - peg$literalExpectation("icon", true), - "alert", - peg$literalExpectation("alert", true), - function () { - options = options || { data: {} }; - if (options.startRule === 'Content_Disposition') { - options.data.type = text().toLowerCase(); - } - }, - "handling", - peg$literalExpectation("handling", true), - "optional", - peg$literalExpectation("optional", true), - "required", - peg$literalExpectation("required", true), - function (length) { - options = options || { data: {} }; - options.data = parseInt(length.join('')); - }, - function () { - options = options || { data: {} }; - options.data = text(); - }, - "text", - peg$literalExpectation("text", true), - "image", - peg$literalExpectation("image", true), - "audio", - peg$literalExpectation("audio", true), - "video", - peg$literalExpectation("video", true), - "application", - peg$literalExpectation("application", true), - "message", - peg$literalExpectation("message", true), - "multipart", - peg$literalExpectation("multipart", true), - "x-", - peg$literalExpectation("x-", true), - function (cseq_value) { - options = options || { data: {} }; - options.data.value = parseInt(cseq_value.join('')); - }, - function (expires) { options = options || { data: {} }; options.data = expires; }, - function (event_type) { - options = options || { data: {} }; - options.data.event = event_type.toLowerCase(); - }, - function () { - options = options || { data: {} }; - var tag = options.data.tag; - options.data = new name_addr_header_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); - if (tag) { - options.data.setParam('tag', tag); - } - }, - "tag", - peg$literalExpectation("tag", true), - function (tag) { options = options || { data: {} }; options.data.tag = tag; }, - function (forwards) { - options = options || { data: {} }; - options.data = parseInt(forwards.join('')); - }, - function (min_expires) { options = options || { data: {} }; options.data = min_expires; }, - function () { - options = options || { data: {} }; - options.data = new name_addr_header_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); - }, - "digest", - peg$literalExpectation("Digest", true), - "realm", - peg$literalExpectation("realm", true), - function (realm) { options = options || { data: {} }; options.data.realm = realm; }, - "domain", - peg$literalExpectation("domain", true), - "nonce", - peg$literalExpectation("nonce", true), - function (nonce) { options = options || { data: {} }; options.data.nonce = nonce; }, - "opaque", - peg$literalExpectation("opaque", true), - function (opaque) { options = options || { data: {} }; options.data.opaque = opaque; }, - "stale", - peg$literalExpectation("stale", true), - "true", - peg$literalExpectation("true", true), - function () { options = options || { data: {} }; options.data.stale = true; }, - "false", - peg$literalExpectation("false", true), - function () { options = options || { data: {} }; options.data.stale = false; }, - "algorithm", - peg$literalExpectation("algorithm", true), - "md5", - peg$literalExpectation("MD5", true), - "md5-sess", - peg$literalExpectation("MD5-sess", true), - function (algorithm) { - options = options || { data: {} }; - options.data.algorithm = algorithm.toUpperCase(); - }, - "qop", - peg$literalExpectation("qop", true), - "auth-int", - peg$literalExpectation("auth-int", true), - "auth", - peg$literalExpectation("auth", true), - function (qop_value) { - options = options || { data: {} }; - options.data.qop || (options.data.qop = []); - options.data.qop.push(qop_value.toLowerCase()); - }, - function (rack_value) { - options = options || { data: {} }; - options.data.value = parseInt(rack_value.join('')); - }, - function () { - var idx, length; - options = options || { data: {} }; - length = options.data.multi_header.length; - for (idx = 0; idx < length; idx++) { - if (options.data.multi_header[idx].parsed === null) { - options.data = null; - break; - } - } - if (options.data !== null) { - options.data = options.data.multi_header; - } - else { - options.data = -1; - } - }, - function () { - var header; - options = options || { data: {} }; - if (!options.data.multi_header) - options.data.multi_header = []; - try { - header = new name_addr_header_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); - delete options.data.uri; - delete options.data.displayName; - delete options.data.params; - } - catch (e) { - header = null; - } - options.data.multi_header.push({ 'position': peg$currPos, - 'offset': location().start.offset, - 'parsed': header - }); - }, - function () { - options = options || { data: {} }; - options.data = new name_addr_header_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); - }, - function () { - options = options || { data: {} }; - if (!(options.data.replaces_from_tag && options.data.replaces_to_tag)) { - options.data = -1; - } - }, - function () { - options = options || { data: {} }; - options.data = { - call_id: options.data - }; - }, - "from-tag", - peg$literalExpectation("from-tag", true), - function (from_tag) { - options = options || { data: {} }; - options.data.replaces_from_tag = from_tag; - }, - "to-tag", - peg$literalExpectation("to-tag", true), - function (to_tag) { - options = options || { data: {} }; - options.data.replaces_to_tag = to_tag; - }, - "early-only", - peg$literalExpectation("early-only", true), - function () { - options = options || { data: {} }; - options.data.early_only = true; - }, - function (head, r) { return r; }, - function (head, tail) { return list(head, tail); }, - function (value) { - options = options || { data: {} }; - if (options.startRule === 'Require') { - options.data = value || []; - } - }, - function (rseq_value) { - options = options || { data: {} }; - options.data.value = parseInt(rseq_value.join('')); - }, - "active", - peg$literalExpectation("active", true), - "pending", - peg$literalExpectation("pending", true), - "terminated", - peg$literalExpectation("terminated", true), - function () { - options = options || { data: {} }; - options.data.state = text(); - }, - "reason", - peg$literalExpectation("reason", true), - function (reason) { - options = options || { data: {} }; - if (typeof reason !== 'undefined') - options.data.reason = reason; - }, - function (expires) { - options = options || { data: {} }; - if (typeof expires !== 'undefined') - options.data.expires = expires; - }, - "retry_after", - peg$literalExpectation("retry_after", true), - function (retry_after) { - options = options || { data: {} }; - if (typeof retry_after !== 'undefined') - options.data.retry_after = retry_after; - }, - "deactivated", - peg$literalExpectation("deactivated", true), - "probation", - peg$literalExpectation("probation", true), - "rejected", - peg$literalExpectation("rejected", true), - "timeout", - peg$literalExpectation("timeout", true), - "giveup", - peg$literalExpectation("giveup", true), - "noresource", - peg$literalExpectation("noresource", true), - "invariant", - peg$literalExpectation("invariant", true), - function (value) { - options = options || { data: {} }; - if (options.startRule === 'Supported') { - options.data = value || []; - } - }, - function () { - options = options || { data: {} }; - var tag = options.data.tag; - options.data = new name_addr_header_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); - if (tag) { - options.data.setParam('tag', tag); - } - }, - "ttl", - peg$literalExpectation("ttl", true), - function (via_ttl_value) { - options = options || { data: {} }; - options.data.ttl = via_ttl_value; - }, - "maddr", - peg$literalExpectation("maddr", true), - function (via_maddr) { - options = options || { data: {} }; - options.data.maddr = via_maddr; - }, - "received", - peg$literalExpectation("received", true), - function (via_received) { - options = options || { data: {} }; - options.data.received = via_received; - }, - "branch", - peg$literalExpectation("branch", true), - function (via_branch) { - options = options || { data: {} }; - options.data.branch = via_branch; - }, - "rport", - peg$literalExpectation("rport", true), - function (response_port) { - options = options || { data: {} }; - if (typeof response_port !== 'undefined') - options.data.rport = response_port.join(''); - }, - function (via_protocol) { - options = options || { data: {} }; - options.data.protocol = via_protocol; - }, - peg$literalExpectation("UDP", true), - peg$literalExpectation("TCP", true), - peg$literalExpectation("TLS", true), - peg$literalExpectation("SCTP", true), - function (via_transport) { - options = options || { data: {} }; - options.data.transport = via_transport; - }, - function () { - options = options || { data: {} }; - options.data.host = text(); - }, - function (via_sent_by_port) { - options = options || { data: {} }; - options.data.port = parseInt(via_sent_by_port.join('')); - }, - function (ttl) { - return parseInt(ttl.join('')); - }, - function (deltaSeconds) { - options = options || { data: {} }; - if (options.startRule === 'Session_Expires') { - options.data.deltaSeconds = deltaSeconds; - } - }, - "refresher", - peg$literalExpectation("refresher", false), - "uas", - peg$literalExpectation("uas", false), - "uac", - peg$literalExpectation("uac", false), - function (endpoint) { - options = options || { data: {} }; - if (options.startRule === 'Session_Expires') { - options.data.refresher = endpoint; - } - }, - function (deltaSeconds) { - options = options || { data: {} }; - if (options.startRule === 'Min_SE') { - options.data = deltaSeconds; - } - }, - "stuns", - peg$literalExpectation("stuns", true), - "stun", - peg$literalExpectation("stun", true), - function (scheme) { - options = options || { data: {} }; - options.data.scheme = scheme; - }, - function (host) { - options = options || { data: {} }; - options.data.host = host; - }, - "?transport=", - peg$literalExpectation("?transport=", false), - "turns", - peg$literalExpectation("turns", true), - "turn", - peg$literalExpectation("turn", true), - function (transport) { - options = options || { data: {} }; - options.data.transport = transport; - }, - function () { - options = options || { data: {} }; - options.data = text(); - }, - "Referred-By", - peg$literalExpectation("Referred-By", false), - "b", - peg$literalExpectation("b", false), - "cid", - peg$literalExpectation("cid", false) - ]; - var peg$bytecode = [ - peg$decode("2 \"\"6 7!"), - peg$decode("4\"\"\"5!7#"), - peg$decode("4$\"\"5!7%"), - peg$decode("4&\"\"5!7'"), - peg$decode(";'.# &;("), - peg$decode("4(\"\"5!7)"), - peg$decode("4*\"\"5!7+"), - peg$decode("2,\"\"6,7-"), - peg$decode("2.\"\"6.7/"), - peg$decode("40\"\"5!71"), - peg$decode("22\"\"6273.\x89 &24\"\"6475.} &26\"\"6677.q &28\"\"6879.e &2:\"\"6:7;.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E"), - peg$decode(";).# &;,"), - peg$decode("2F\"\"6F7G.} &2H\"\"6H7I.q &2J\"\"6J7K.e &2L\"\"6L7M.Y &2N\"\"6N7O.M &2P\"\"6P7Q.A &2R\"\"6R7S.5 &2T\"\"6T7U.) &2V\"\"6V7W"), - peg$decode("%%2X\"\"6X7Y/5#;#/,$;#/#$+#)(#'#(\"'#&'#/\"!&,)"), - peg$decode("%%$;$0#*;$&/,#; /#$+\")(\"'#&'#.\" &\"/=#$;$/�#*;$&&&#/'$8\":Z\" )(\"'#&'#"), - peg$decode(";..\" &\""), - peg$decode("%$;'.# &;(0)*;'.# &;(&/?#28\"\"6879/0$;//'$8#:[# )(#'#(\"'#&'#"), - peg$decode("%%$;2/�#*;2&&&#/g#$%$;.0#*;.&/,#;2/#$+\")(\"'#&'#0=*%$;.0#*;.&/,#;2/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/\"!&,)"), - peg$decode("4\\\"\"5!7].# &;3"), - peg$decode("4^\"\"5!7_"), - peg$decode("4`\"\"5!7a"), - peg$decode(";!.) &4b\"\"5!7c"), - peg$decode("%$;).\x95 &2F\"\"6F7G.\x89 &2J\"\"6J7K.} &2L\"\"6L7M.q &2X\"\"6X7Y.e &2P\"\"6P7Q.Y &2H\"\"6H7I.M &2@\"\"6@7A.A &2d\"\"6d7e.5 &2R\"\"6R7S.) &2N\"\"6N7O/\x9E#0\x9B*;).\x95 &2F\"\"6F7G.\x89 &2J\"\"6J7K.} &2L\"\"6L7M.q &2X\"\"6X7Y.e &2P\"\"6P7Q.Y &2H\"\"6H7I.M &2@\"\"6@7A.A &2d\"\"6d7e.5 &2R\"\"6R7S.) &2N\"\"6N7O&&&#/\"!&,)"), - peg$decode("%$;).\x89 &2F\"\"6F7G.} &2L\"\"6L7M.q &2X\"\"6X7Y.e &2P\"\"6P7Q.Y &2H\"\"6H7I.M &2@\"\"6@7A.A &2d\"\"6d7e.5 &2R\"\"6R7S.) &2N\"\"6N7O/\x92#0\x8F*;).\x89 &2F\"\"6F7G.} &2L\"\"6L7M.q &2X\"\"6X7Y.e &2P\"\"6P7Q.Y &2H\"\"6H7I.M &2@\"\"6@7A.A &2d\"\"6d7e.5 &2R\"\"6R7S.) &2N\"\"6N7O&&&#/\"!&,)"), - peg$decode("2T\"\"6T7U.\xE3 &2V\"\"6V7W.\xD7 &2f\"\"6f7g.\xCB &2h\"\"6h7i.\xBF &2:\"\"6:7;.\xB3 &2D\"\"6D7E.\xA7 &22\"\"6273.\x9B &28\"\"6879.\x8F &2j\"\"6j7k.\x83 &;&.} &24\"\"6475.q &2l\"\"6l7m.e &2n\"\"6n7o.Y &26\"\"6677.M &2>\"\"6>7?.A &2p\"\"6p7q.5 &2r\"\"6r7s.) &;'.# &;("), - peg$decode("%$;).\u012B &2F\"\"6F7G.\u011F &2J\"\"6J7K.\u0113 &2L\"\"6L7M.\u0107 &2X\"\"6X7Y.\xFB &2P\"\"6P7Q.\xEF &2H\"\"6H7I.\xE3 &2@\"\"6@7A.\xD7 &2d\"\"6d7e.\xCB &2R\"\"6R7S.\xBF &2N\"\"6N7O.\xB3 &2T\"\"6T7U.\xA7 &2V\"\"6V7W.\x9B &2f\"\"6f7g.\x8F &2h\"\"6h7i.\x83 &28\"\"6879.w &2j\"\"6j7k.k &;&.e &24\"\"6475.Y &2l\"\"6l7m.M &2n\"\"6n7o.A &26\"\"6677.5 &2p\"\"6p7q.) &2r\"\"6r7s/\u0134#0\u0131*;).\u012B &2F\"\"6F7G.\u011F &2J\"\"6J7K.\u0113 &2L\"\"6L7M.\u0107 &2X\"\"6X7Y.\xFB &2P\"\"6P7Q.\xEF &2H\"\"6H7I.\xE3 &2@\"\"6@7A.\xD7 &2d\"\"6d7e.\xCB &2R\"\"6R7S.\xBF &2N\"\"6N7O.\xB3 &2T\"\"6T7U.\xA7 &2V\"\"6V7W.\x9B &2f\"\"6f7g.\x8F &2h\"\"6h7i.\x83 &28\"\"6879.w &2j\"\"6j7k.k &;&.e &24\"\"6475.Y &2l\"\"6l7m.M &2n\"\"6n7o.A &26\"\"6677.5 &2p\"\"6p7q.) &2r\"\"6r7s&&&#/\"!&,)"), - peg$decode("%;//?#2P\"\"6P7Q/0$;//'$8#:t# )(#'#(\"'#&'#"), - peg$decode("%;//?#24\"\"6475/0$;//'$8#:u# )(#'#(\"'#&'#"), - peg$decode("%;//?#2>\"\"6>7?/0$;//'$8#:v# )(#'#(\"'#&'#"), - peg$decode("%;//?#2T\"\"6T7U/0$;//'$8#:w# )(#'#(\"'#&'#"), - peg$decode("%;//?#2V\"\"6V7W/0$;//'$8#:x# )(#'#(\"'#&'#"), - peg$decode("%2h\"\"6h7i/0#;//'$8\":y\" )(\"'#&'#"), - peg$decode("%;//6#2f\"\"6f7g/'$8\":z\" )(\"'#&'#"), - peg$decode("%;//?#2D\"\"6D7E/0$;//'$8#:{# )(#'#(\"'#&'#"), - peg$decode("%;//?#22\"\"6273/0$;//'$8#:|# )(#'#(\"'#&'#"), - peg$decode("%;//?#28\"\"6879/0$;//'$8#:}# )(#'#(\"'#&'#"), - peg$decode("%;//0#;&/'$8\":~\" )(\"'#&'#"), - peg$decode("%;&/0#;//'$8\":~\" )(\"'#&'#"), - peg$decode("%;=/T#$;G.) &;K.# &;F0/*;G.) &;K.# &;F&/,$;>/#$+#)(#'#(\"'#&'#"), - peg$decode("4\x7F\"\"5!7\x80.A &4\x81\"\"5!7\x82.5 &4\x83\"\"5!7\x84.) &;3.# &;."), - peg$decode("%%;//Q#;&/H$$;J.# &;K0)*;J.# &;K&/,$;&/#$+$)($'#(#'#(\"'#&'#/\"!&,)"), - peg$decode("%;//]#;&/T$%$;J.# &;K0)*;J.# &;K&/\"!&,)/1$;&/($8$:\x85$!!)($'#(#'#(\"'#&'#"), - peg$decode(";..G &2L\"\"6L7M.; &4\x86\"\"5!7\x87./ &4\x83\"\"5!7\x84.# &;3"), - peg$decode("%2j\"\"6j7k/J#4\x88\"\"5!7\x89.5 &4\x8A\"\"5!7\x8B.) &4\x8C\"\"5!7\x8D/#$+\")(\"'#&'#"), - peg$decode("%;N/M#28\"\"6879/>$;O.\" &\"/0$;S/'$8$:\x8E$ )($'#(#'#(\"'#&'#"), - peg$decode("%;N/d#28\"\"6879/U$;O.\" &\"/G$;S/>$;_/5$;l.\" &\"/'$8&:\x8F& )(&'#(%'#($'#(#'#(\"'#&'#"), - peg$decode("%3\x90\"\"5$7\x91.) &3\x92\"\"5#7\x93/' 8!:\x94!! )"), - peg$decode("%;P/]#%28\"\"6879/,#;R/#$+\")(\"'#&'#.\" &\"/6$2:\"\"6:7;/'$8#:\x95# )(#'#(\"'#&'#"), - peg$decode("$;+.) &;-.# &;Q/2#0/*;+.) &;-.# &;Q&&&#"), - peg$decode("2<\"\"6<7=.q &2>\"\"6>7?.e &2@\"\"6@7A.Y &2B\"\"6B7C.M &2D\"\"6D7E.A &22\"\"6273.5 &26\"\"6677.) &24\"\"6475"), - peg$decode("%$;+._ &;-.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E0e*;+._ &;-.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E&/& 8!:\x96! )"), - peg$decode("%;T/J#%28\"\"6879/,#;^/#$+\")(\"'#&'#.\" &\"/#$+\")(\"'#&'#"), - peg$decode("%;U.) &;\\.# &;X/& 8!:\x97! )"), - peg$decode("%$%;V/2#2J\"\"6J7K/#$+\")(\"'#&'#0<*%;V/2#2J\"\"6J7K/#$+\")(\"'#&'#&/D#;W/;$2J\"\"6J7K.\" &\"/'$8#:\x98# )(#'#(\"'#&'#"), - peg$decode("$4\x99\"\"5!7\x9A/,#0)*4\x99\"\"5!7\x9A&&&#"), - peg$decode("%4$\"\"5!7%/?#$4\x9B\"\"5!7\x9C0)*4\x9B\"\"5!7\x9C&/#$+\")(\"'#&'#"), - peg$decode("%2l\"\"6l7m/?#;Y/6$2n\"\"6n7o/'$8#:\x9D# )(#'#(\"'#&'#"), - peg$decode("%%;Z/\xB3#28\"\"6879/\xA4$;Z/\x9B$28\"\"6879/\x8C$;Z/\x83$28\"\"6879/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+-)(-'#(,'#(+'#(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0790 &%2\x9E\"\"6\x9E7\x9F/\xA4#;Z/\x9B$28\"\"6879/\x8C$;Z/\x83$28\"\"6879/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+,)(,'#(+'#(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u06F9 &%2\x9E\"\"6\x9E7\x9F/\x8C#;Z/\x83$28\"\"6879/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+*)(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u067A &%2\x9E\"\"6\x9E7\x9F/t#;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+()(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0613 &%2\x9E\"\"6\x9E7\x9F/\\#;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+&)(&'#(%'#($'#(#'#(\"'#&'#.\u05C4 &%2\x9E\"\"6\x9E7\x9F/D#;Z/;$28\"\"6879/,$;[/#$+$)($'#(#'#(\"'#&'#.\u058D &%2\x9E\"\"6\x9E7\x9F/,#;[/#$+\")(\"'#&'#.\u056E &%2\x9E\"\"6\x9E7\x9F/,#;Z/#$+\")(\"'#&'#.\u054F &%;Z/\x9B#2\x9E\"\"6\x9E7\x9F/\x8C$;Z/\x83$28\"\"6879/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$++)(+'#(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u04C7 &%;Z/\xAA#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x83$2\x9E\"\"6\x9E7\x9F/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+*)(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0430 &%;Z/\xB9#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x92$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/k$2\x9E\"\"6\x9E7\x9F/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+))()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u038A &%;Z/\xC8#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xA1$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/z$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/S$2\x9E\"\"6\x9E7\x9F/D$;Z/;$28\"\"6879/,$;[/#$+()(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u02D5 &%;Z/\xD7#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xB0$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x89$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/b$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/;$2\x9E\"\"6\x9E7\x9F/,$;[/#$+')(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0211 &%;Z/\xFE#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xD7$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xB0$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x89$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/b$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/;$2\x9E\"\"6\x9E7\x9F/,$;Z/#$+()(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0126 &%;Z/\u011C#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xF5$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xCE$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xA7$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x80$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/Y$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/2$2\x9E\"\"6\x9E7\x9F/#$+()(('#(''#(&'#(%'#($'#(#'#(\"'#&'#/& 8!:\xA0! )"), - peg$decode("%;#/M#;#.\" &\"/?$;#.\" &\"/1$;#.\" &\"/#$+$)($'#(#'#(\"'#&'#"), - peg$decode("%;Z/;#28\"\"6879/,$;Z/#$+#)(#'#(\"'#&'#.# &;\\"), - peg$decode("%;]/o#2J\"\"6J7K/`$;]/W$2J\"\"6J7K/H$;]/?$2J\"\"6J7K/0$;]/'$8':\xA1' )(''#(&'#(%'#($'#(#'#(\"'#&'#"), - peg$decode("%2\xA2\"\"6\xA27\xA3/2#4\xA4\"\"5!7\xA5/#$+\")(\"'#&'#.\x98 &%2\xA6\"\"6\xA67\xA7/;#4\xA8\"\"5!7\xA9/,$;!/#$+#)(#'#(\"'#&'#.j &%2\xAA\"\"6\xAA7\xAB/5#;!/,$;!/#$+#)(#'#(\"'#&'#.B &%4\xAC\"\"5!7\xAD/,#;!/#$+\")(\"'#&'#.# &;!"), - peg$decode("%%;!.\" &\"/[#;!.\" &\"/M$;!.\" &\"/?$;!.\" &\"/1$;!.\" &\"/#$+%)(%'#($'#(#'#(\"'#&'#/' 8!:\xAE!! )"), - peg$decode("$%22\"\"6273/,#;`/#$+\")(\"'#&'#0<*%22\"\"6273/,#;`/#$+\")(\"'#&'#&"), - peg$decode(";a.A &;b.; &;c.5 &;d./ &;e.) &;f.# &;g"), - peg$decode("%3\xAF\"\"5*7\xB0/a#3\xB1\"\"5#7\xB2.G &3\xB3\"\"5#7\xB4.; &3\xB5\"\"5$7\xB6./ &3\xB7\"\"5#7\xB8.# &;6/($8\":\xB9\"! )(\"'#&'#"), - peg$decode("%3\xBA\"\"5%7\xBB/I#3\xBC\"\"5%7\xBD./ &3\xBE\"\"5\"7\xBF.# &;6/($8\":\xC0\"! )(\"'#&'#"), - peg$decode("%3\xC1\"\"5'7\xC2/1#;\x90/($8\":\xC3\"! )(\"'#&'#"), - peg$decode("%3\xC4\"\"5$7\xC5/1#;\xF0/($8\":\xC6\"! )(\"'#&'#"), - peg$decode("%3\xC7\"\"5&7\xC8/1#;T/($8\":\xC9\"! )(\"'#&'#"), - peg$decode("%3\xCA\"\"5\"7\xCB/N#%2>\"\"6>7?/,#;6/#$+\")(\"'#&'#.\" &\"/'$8\":\xCC\" )(\"'#&'#"), - peg$decode("%;h/P#%2>\"\"6>7?/,#;i/#$+\")(\"'#&'#.\" &\"/)$8\":\xCD\"\"! )(\"'#&'#"), - peg$decode("%$;j/�#*;j&&&#/\"!&,)"), - peg$decode("%$;j/�#*;j&&&#/\"!&,)"), - peg$decode(";k.) &;+.# &;-"), - peg$decode("2l\"\"6l7m.e &2n\"\"6n7o.Y &24\"\"6475.M &28\"\"6879.A &2<\"\"6<7=.5 &2@\"\"6@7A.) &2B\"\"6B7C"), - peg$decode("%26\"\"6677/n#;m/e$$%2<\"\"6<7=/,#;m/#$+\")(\"'#&'#0<*%2<\"\"6<7=/,#;m/#$+\")(\"'#&'#&/#$+#)(#'#(\"'#&'#"), - peg$decode("%;n/A#2>\"\"6>7?/2$;o/)$8#:\xCE#\"\" )(#'#(\"'#&'#"), - peg$decode("$;p.) &;+.# &;-/2#0/*;p.) &;+.# &;-&&&#"), - peg$decode("$;p.) &;+.# &;-0/*;p.) &;+.# &;-&"), - peg$decode("2l\"\"6l7m.e &2n\"\"6n7o.Y &24\"\"6475.M &26\"\"6677.A &28\"\"6879.5 &2@\"\"6@7A.) &2B\"\"6B7C"), - peg$decode(";\x91.# &;r"), - peg$decode("%;\x90/G#;'/>$;s/5$;'/,$;\x84/#$+%)(%'#($'#(#'#(\"'#&'#"), - peg$decode(";M.# &;t"), - peg$decode("%;\x7F/E#28\"\"6879/6$;u.# &;x/'$8#:\xCF# )(#'#(\"'#&'#"), - peg$decode("%;v.# &;w/J#%26\"\"6677/,#;\x83/#$+\")(\"'#&'#.\" &\"/#$+\")(\"'#&'#"), - peg$decode("%2\xD0\"\"6\xD07\xD1/:#;\x80/1$;w.\" &\"/#$+#)(#'#(\"'#&'#"), - peg$decode("%24\"\"6475/,#;{/#$+\")(\"'#&'#"), - peg$decode("%;z/3#$;y0#*;y&/#$+\")(\"'#&'#"), - peg$decode(";*.) &;+.# &;-"), - peg$decode(";+.\x8F &;-.\x89 &22\"\"6273.} &26\"\"6677.q &28\"\"6879.e &2:\"\"6:7;.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E"), - peg$decode("%;|/e#$%24\"\"6475/,#;|/#$+\")(\"'#&'#0<*%24\"\"6475/,#;|/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"), - peg$decode("%$;~0#*;~&/e#$%22\"\"6273/,#;}/#$+\")(\"'#&'#0<*%22\"\"6273/,#;}/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"), - peg$decode("$;~0#*;~&"), - peg$decode(";+.w &;-.q &28\"\"6879.e &2:\"\"6:7;.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E"), - peg$decode("%%;\"/\x87#$;\".G &;!.A &2@\"\"6@7A.5 &2F\"\"6F7G.) &2J\"\"6J7K0M*;\".G &;!.A &2@\"\"6@7A.5 &2F\"\"6F7G.) &2J\"\"6J7K&/#$+\")(\"'#&'#/& 8!:\xD2! )"), - peg$decode(";\x81.# &;\x82"), - peg$decode("%%;O/2#2:\"\"6:7;/#$+\")(\"'#&'#.\" &\"/,#;S/#$+\")(\"'#&'#.\" &\""), - peg$decode("$;+.\x83 &;-.} &2B\"\"6B7C.q &2D\"\"6D7E.e &22\"\"6273.Y &28\"\"6879.M &2:\"\"6:7;.A &2<\"\"6<7=.5 &2>\"\"6>7?.) &2@\"\"6@7A/\x8C#0\x89*;+.\x83 &;-.} &2B\"\"6B7C.q &2D\"\"6D7E.e &22\"\"6273.Y &28\"\"6879.M &2:\"\"6:7;.A &2<\"\"6<7=.5 &2>\"\"6>7?.) &2@\"\"6@7A&&&#"), - peg$decode("$;y0#*;y&"), - peg$decode("%3\x92\"\"5#7\xD3/q#24\"\"6475/b$$;!/�#*;!&&&#/L$2J\"\"6J7K/=$$;!/�#*;!&&&#/'$8%:\xD4% )(%'#($'#(#'#(\"'#&'#"), - peg$decode("2\xD5\"\"6\xD57\xD6"), - peg$decode("2\xD7\"\"6\xD77\xD8"), - peg$decode("2\xD9\"\"6\xD97\xDA"), - peg$decode("2\xDB\"\"6\xDB7\xDC"), - peg$decode("2\xDD\"\"6\xDD7\xDE"), - peg$decode("2\xDF\"\"6\xDF7\xE0"), - peg$decode("2\xE1\"\"6\xE17\xE2"), - peg$decode("2\xE3\"\"6\xE37\xE4"), - peg$decode("2\xE5\"\"6\xE57\xE6"), - peg$decode("2\xE7\"\"6\xE77\xE8"), - peg$decode("2\xE9\"\"6\xE97\xEA"), - peg$decode("%;\x85.Y &;\x86.S &;\x88.M &;\x89.G &;\x8A.A &;\x8B.; &;\x8C.5 &;\x8F./ &;\x8D.) &;\x8E.# &;6/& 8!:\xEB! )"), - peg$decode("%;\x84/G#;'/>$;\x92/5$;'/,$;\x94/#$+%)(%'#($'#(#'#(\"'#&'#"), - peg$decode("%;\x93/' 8!:\xEC!! )"), - peg$decode("%;!/5#;!/,$;!/#$+#)(#'#(\"'#&'#"), - peg$decode("%$;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(0G*;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(&/& 8!:\xED! )"), - peg$decode("%;\xB6/Y#$%;A/,#;\xB6/#$+\")(\"'#&'#06*%;A/,#;\xB6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"), - peg$decode("%;9/N#%2:\"\"6:7;/,#;9/#$+\")(\"'#&'#.\" &\"/'$8\":\xEE\" )(\"'#&'#"), - peg$decode("%;:.c &%;\x98/Y#$%;A/,#;\x98/#$+\")(\"'#&'#06*%;A/,#;\x98/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/& 8!:\xEF! )"), - peg$decode("%;L.# &;\x99/]#$%;B/,#;\x9B/#$+\")(\"'#&'#06*%;B/,#;\x9B/#$+\")(\"'#&'#&/'$8\":\xF0\" )(\"'#&'#"), - peg$decode("%;\x9A.\" &\"/>#;@/5$;M/,$;?/#$+$)($'#(#'#(\"'#&'#"), - peg$decode("%%;6/Y#$%;./,#;6/#$+\")(\"'#&'#06*%;./,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#.# &;H/' 8!:\xF1!! )"), - peg$decode(";\x9C.) &;\x9D.# &;\xA0"), - peg$decode("%3\xF2\"\"5!7\xF3/:#;$;\xCF/5$;./,$;\x90/#$+%)(%'#($'#(#'#(\"'#&'#"), - peg$decode("%$;!/�#*;!&&&#/' 8!:\u014B!! )"), - peg$decode("%;\xD1/]#$%;A/,#;\xD1/#$+\")(\"'#&'#06*%;A/,#;\xD1/#$+\")(\"'#&'#&/'$8\":\u014C\" )(\"'#&'#"), - peg$decode("%;\x99/]#$%;B/,#;\xA0/#$+\")(\"'#&'#06*%;B/,#;\xA0/#$+\")(\"'#&'#&/'$8\":\u014D\" )(\"'#&'#"), - peg$decode("%;L.O &;\x99.I &%;@.\" &\"/:#;t/1$;?.\" &\"/#$+#)(#'#(\"'#&'#/]#$%;B/,#;\xA0/#$+\")(\"'#&'#06*%;B/,#;\xA0/#$+\")(\"'#&'#&/'$8\":\u014E\" )(\"'#&'#"), - peg$decode("%;\xD4/]#$%;B/,#;\xD5/#$+\")(\"'#&'#06*%;B/,#;\xD5/#$+\")(\"'#&'#&/'$8\":\u014F\" )(\"'#&'#"), - peg$decode("%;\x96/& 8!:\u0150! )"), - peg$decode("%3\u0151\"\"5(7\u0152/:#;$;6/5$;;/,$;\xEC/#$+%)(%'#($'#(#'#(\"'#&'#"), - peg$decode("%3\x92\"\"5#7\xD3.# &;6/' 8!:\u018B!! )"), - peg$decode("%3\xB1\"\"5#7\u018C.G &3\xB3\"\"5#7\u018D.; &3\xB7\"\"5#7\u018E./ &3\xB5\"\"5$7\u018F.# &;6/' 8!:\u0190!! )"), - peg$decode("%;\xEE/D#%;C/,#;\xEF/#$+\")(\"'#&'#.\" &\"/#$+\")(\"'#&'#"), - peg$decode("%;U.) &;\\.# &;X/& 8!:\u0191! )"), - peg$decode("%%;!.\" &\"/[#;!.\" &\"/M$;!.\" &\"/?$;!.\" &\"/1$;!.\" &\"/#$+%)(%'#($'#(#'#(\"'#&'#/' 8!:\u0192!! )"), - peg$decode("%%;!/?#;!.\" &\"/1$;!.\" &\"/#$+#)(#'#(\"'#&'#/' 8!:\u0193!! )"), - peg$decode(";\xBE"), - peg$decode("%;\x9E/^#$%;B/,#;\xF3/#$+\")(\"'#&'#06*%;B/,#;\xF3/#$+\")(\"'#&'#&/($8\":\u0194\"!!)(\"'#&'#"), - peg$decode(";\xF4.# &;\xA0"), - peg$decode("%2\u0195\"\"6\u01957\u0196/L#;\"\"6>7?"), - peg$decode("%;\u0100/b#28\"\"6879/S$;\xFB/J$%2\u01A3\"\"6\u01A37\u01A4/,#;\xEC/#$+\")(\"'#&'#.\" &\"/#$+$)($'#(#'#(\"'#&'#"), - peg$decode("%3\u01A5\"\"5%7\u01A6.) &3\u01A7\"\"5$7\u01A8/' 8!:\u01A1!! )"), - peg$decode("%3\xB1\"\"5#7\xB2.6 &3\xB3\"\"5#7\xB4.* &$;+0#*;+&/' 8!:\u01A9!! )"), - peg$decode("%;\u0104/\x87#2F\"\"6F7G/x$;\u0103/o$2F\"\"6F7G/`$;\u0103/W$2F\"\"6F7G/H$;\u0103/?$2F\"\"6F7G/0$;\u0105/'$8):\u01AA) )()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#"), - peg$decode("%;#/>#;#/5$;#/,$;#/#$+$)($'#(#'#(\"'#&'#"), - peg$decode("%;\u0103/,#;\u0103/#$+\")(\"'#&'#"), - peg$decode("%;\u0103/5#;\u0103/,$;\u0103/#$+#)(#'#(\"'#&'#"), - peg$decode("%;q/T#$;m0#*;m&/D$%; /,#;\xF8/#$+\")(\"'#&'#.\" &\"/#$+#)(#'#(\"'#&'#"), - peg$decode("%2\u01AB\"\"6\u01AB7\u01AC.) &2\u01AD\"\"6\u01AD7\u01AE/w#;0/n$;\u0108/e$$%;B/2#;\u0109.# &;\xA0/#$+\")(\"'#&'#0<*%;B/2#;\u0109.# &;\xA0/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"), - peg$decode(";\x99.# &;L"), - peg$decode("%2\u01AF\"\"6\u01AF7\u01B0/5#; peg$maxFailPos) { - peg$maxFailPos = peg$currPos; - peg$maxFailExpected = []; - } - peg$maxFailExpected.push(expected1); - } - function peg$buildSimpleError(message, location1) { - return new SyntaxError(message, [], "", location1); - } - function peg$buildStructuredError(expected1, found, location1) { - return new SyntaxError(SyntaxError.buildMessage(expected1, found), expected1, found, location1); - } - function peg$decode(s) { - return s.split("").map(function (ch) { return ch.charCodeAt(0) - 32; }); - } - function peg$parseRule(index) { - var bc = peg$bytecode[index]; - var ip = 0; - var ips = []; - var end = bc.length; - var ends = []; - var stack = []; - var params; - while (true) { - while (ip < end) { - switch (bc[ip]) { - case 0: - stack.push(peg$consts[bc[ip + 1]]); - ip += 2; - break; - case 1: - stack.push(undefined); - ip++; - break; - case 2: - stack.push(null); - ip++; - break; - case 3: - stack.push(peg$FAILED); - ip++; - break; - case 4: - stack.push([]); - ip++; - break; - case 5: - stack.push(peg$currPos); - ip++; - break; - case 6: - stack.pop(); - ip++; - break; - case 7: - peg$currPos = stack.pop(); - ip++; - break; - case 8: - stack.length -= bc[ip + 1]; - ip += 2; - break; - case 9: - stack.splice(-2, 1); - ip++; - break; - case 10: - stack[stack.length - 2].push(stack.pop()); - ip++; - break; - case 11: - stack.push(stack.splice(stack.length - bc[ip + 1], bc[ip + 1])); - ip += 2; - break; - case 12: - stack.push(input.substring(stack.pop(), peg$currPos)); - ip++; - break; - case 13: - ends.push(end); - ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); - if (stack[stack.length - 1]) { - end = ip + 3 + bc[ip + 1]; - ip += 3; - } - else { - end = ip + 3 + bc[ip + 1] + bc[ip + 2]; - ip += 3 + bc[ip + 1]; - } - break; - case 14: - ends.push(end); - ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); - if (stack[stack.length - 1] === peg$FAILED) { - end = ip + 3 + bc[ip + 1]; - ip += 3; - } - else { - end = ip + 3 + bc[ip + 1] + bc[ip + 2]; - ip += 3 + bc[ip + 1]; - } - break; - case 15: - ends.push(end); - ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); - if (stack[stack.length - 1] !== peg$FAILED) { - end = ip + 3 + bc[ip + 1]; - ip += 3; - } - else { - end = ip + 3 + bc[ip + 1] + bc[ip + 2]; - ip += 3 + bc[ip + 1]; - } - break; - case 16: - if (stack[stack.length - 1] !== peg$FAILED) { - ends.push(end); - ips.push(ip); - end = ip + 2 + bc[ip + 1]; - ip += 2; - } - else { - ip += 2 + bc[ip + 1]; - } - break; - case 17: - ends.push(end); - ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); - if (input.length > peg$currPos) { - end = ip + 3 + bc[ip + 1]; - ip += 3; - } - else { - end = ip + 3 + bc[ip + 1] + bc[ip + 2]; - ip += 3 + bc[ip + 1]; - } - break; - case 18: - ends.push(end); - ips.push(ip + 4 + bc[ip + 2] + bc[ip + 3]); - if (input.substr(peg$currPos, peg$consts[bc[ip + 1]].length) === peg$consts[bc[ip + 1]]) { - end = ip + 4 + bc[ip + 2]; - ip += 4; - } - else { - end = ip + 4 + bc[ip + 2] + bc[ip + 3]; - ip += 4 + bc[ip + 2]; - } - break; - case 19: - ends.push(end); - ips.push(ip + 4 + bc[ip + 2] + bc[ip + 3]); - if (input.substr(peg$currPos, peg$consts[bc[ip + 1]].length).toLowerCase() === peg$consts[bc[ip + 1]]) { - end = ip + 4 + bc[ip + 2]; - ip += 4; - } - else { - end = ip + 4 + bc[ip + 2] + bc[ip + 3]; - ip += 4 + bc[ip + 2]; - } - break; - case 20: - ends.push(end); - ips.push(ip + 4 + bc[ip + 2] + bc[ip + 3]); - if (peg$consts[bc[ip + 1]].test(input.charAt(peg$currPos))) { - end = ip + 4 + bc[ip + 2]; - ip += 4; - } - else { - end = ip + 4 + bc[ip + 2] + bc[ip + 3]; - ip += 4 + bc[ip + 2]; - } - break; - case 21: - stack.push(input.substr(peg$currPos, bc[ip + 1])); - peg$currPos += bc[ip + 1]; - ip += 2; - break; - case 22: - stack.push(peg$consts[bc[ip + 1]]); - peg$currPos += peg$consts[bc[ip + 1]].length; - ip += 2; - break; - case 23: - stack.push(peg$FAILED); - if (peg$silentFails === 0) { - peg$fail(peg$consts[bc[ip + 1]]); - } - ip += 2; - break; - case 24: - peg$savedPos = stack[stack.length - 1 - bc[ip + 1]]; - ip += 2; - break; - case 25: - peg$savedPos = peg$currPos; - ip++; - break; - case 26: - params = bc.slice(ip + 4, ip + 4 + bc[ip + 3]) - .map(function (p) { return stack[stack.length - 1 - p]; }); - stack.splice(stack.length - bc[ip + 2], bc[ip + 2], peg$consts[bc[ip + 1]].apply(null, params)); - ip += 4 + bc[ip + 3]; - break; - case 27: - stack.push(peg$parseRule(bc[ip + 1])); - ip += 2; - break; - case 28: - peg$silentFails++; - ip++; - break; - case 29: - peg$silentFails--; - ip++; - break; - default: - throw new Error("Invalid opcode: " + bc[ip] + "."); - } - } - if (ends.length > 0) { - end = ends.pop(); - ip = ips.pop(); - } - else { - break; - } - } - return stack[0]; - } - options.data = {}; // Object to which header attributes will be assigned during parsing - function list(head, tail) { - return [head].concat(tail); - } - peg$result = peg$parseRule(peg$startRuleIndex); - if (peg$result !== peg$FAILED && peg$currPos === input.length) { - return peg$result; - } - else { - if (peg$result !== peg$FAILED && peg$currPos < input.length) { - peg$fail(peg$endExpectation()); - } - throw peg$buildStructuredError(peg$maxFailExpected, peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, peg$maxFailPos < input.length - ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) - : peg$computeLocation(peg$maxFailPos, peg$maxFailPos)); - } -} -exports.parse = peg$parse; - - -/***/ }), -/* 13 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var parameters_1 = __webpack_require__(14); -/** - * Name Address SIP header. - * @public - */ -var NameAddrHeader = /** @class */ (function (_super) { - tslib_1.__extends(NameAddrHeader, _super); - /** - * Constructor - * @param uri - - * @param displayName - - * @param parameters - - */ - function NameAddrHeader(uri, displayName, parameters) { - var _this = _super.call(this, parameters) || this; - _this.uri = uri; - _this._displayName = displayName; - return _this; - } - Object.defineProperty(NameAddrHeader.prototype, "friendlyName", { - get: function () { - return this.displayName || this.uri.aor; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(NameAddrHeader.prototype, "displayName", { - get: function () { return this._displayName; }, - set: function (value) { - this._displayName = value; - }, - enumerable: true, - configurable: true - }); - NameAddrHeader.prototype.clone = function () { - return new NameAddrHeader(this.uri.clone(), this._displayName, JSON.parse(JSON.stringify(this.parameters))); - }; - NameAddrHeader.prototype.toString = function () { - var body = (this.displayName || this.displayName === "0") ? '"' + this.displayName + '" ' : ""; - body += "<" + this.uri.toString() + ">"; - for (var parameter in this.parameters) { - if (this.parameters.hasOwnProperty(parameter)) { - body += ";" + parameter; - if (this.parameters[parameter] !== null) { - body += "=" + this.parameters[parameter]; - } - } - } - return body; - }; - return NameAddrHeader; -}(parameters_1.Parameters)); -exports.NameAddrHeader = NameAddrHeader; - - -/***/ }), -/* 14 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * @internal - */ -var Parameters = /** @class */ (function () { - function Parameters(parameters) { - this.parameters = {}; - for (var param in parameters) { - if (parameters.hasOwnProperty(param)) { - this.setParam(param, parameters[param]); - } - } - } - Parameters.prototype.setParam = function (key, value) { - if (key) { - this.parameters[key.toLowerCase()] = (typeof value === "undefined" || value === null) ? null : value.toString(); - } - }; - Parameters.prototype.getParam = function (key) { - if (key) { - return this.parameters[key.toLowerCase()]; - } - }; - Parameters.prototype.hasParam = function (key) { - if (key) { - return !!this.parameters.hasOwnProperty(key.toLowerCase()); - } - return false; - }; - Parameters.prototype.deleteParam = function (parameter) { - parameter = parameter.toLowerCase(); - if (this.parameters.hasOwnProperty(parameter)) { - var value = this.parameters[parameter]; - delete this.parameters[parameter]; - return value; - } - }; - Parameters.prototype.clearParams = function () { - this.parameters = {}; - }; - return Parameters; -}()); -exports.Parameters = Parameters; - - -/***/ }), -/* 15 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var parameters_1 = __webpack_require__(14); -/** - * URI. - * @public - */ -var URI = /** @class */ (function (_super) { - tslib_1.__extends(URI, _super); - /** - * Constructor - * @param scheme - - * @param user - - * @param host - - * @param port - - * @param parameters - - * @param headers - - */ - function URI(scheme, user, host, port, parameters, headers) { - var _this = _super.call(this, parameters) || this; - _this.headers = {}; - // Checks - if (!host) { - throw new TypeError('missing or invalid "host" parameter'); - } - // Initialize parameters - scheme = scheme || "sip"; - for (var header in headers) { - if (headers.hasOwnProperty(header)) { - _this.setHeader(header, headers[header]); - } - } - // Raw URI - _this.raw = { - scheme: scheme, - user: user, - host: host, - port: port - }; - // Normalized URI - _this.normal = { - scheme: scheme.toLowerCase(), - user: user, - host: host.toLowerCase(), - port: port - }; - return _this; - } - Object.defineProperty(URI.prototype, "scheme", { - get: function () { return this.normal.scheme; }, - set: function (value) { - this.raw.scheme = value; - this.normal.scheme = value.toLowerCase(); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(URI.prototype, "user", { - get: function () { return this.normal.user; }, - set: function (value) { - this.normal.user = this.raw.user = value; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(URI.prototype, "host", { - get: function () { return this.normal.host; }, - set: function (value) { - this.raw.host = value; - this.normal.host = value.toLowerCase(); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(URI.prototype, "aor", { - get: function () { return this.normal.user + "@" + this.normal.host; }, - enumerable: true, - configurable: true - }); - Object.defineProperty(URI.prototype, "port", { - get: function () { return this.normal.port; }, - set: function (value) { - this.normal.port = this.raw.port = value === 0 ? value : value; - }, - enumerable: true, - configurable: true - }); - URI.prototype.setHeader = function (name, value) { - this.headers[this.headerize(name)] = (value instanceof Array) ? value : [value]; - }; - URI.prototype.getHeader = function (name) { - if (name) { - return this.headers[this.headerize(name)]; - } - }; - URI.prototype.hasHeader = function (name) { - return !!name && !!this.headers.hasOwnProperty(this.headerize(name)); - }; - URI.prototype.deleteHeader = function (header) { - header = this.headerize(header); - if (this.headers.hasOwnProperty(header)) { - var value = this.headers[header]; - delete this.headers[header]; - return value; - } - }; - URI.prototype.clearHeaders = function () { - this.headers = {}; - }; - URI.prototype.clone = function () { - return new URI(this._raw.scheme, this._raw.user || "", this._raw.host, this._raw.port, JSON.parse(JSON.stringify(this.parameters)), JSON.parse(JSON.stringify(this.headers))); - }; - URI.prototype.toRaw = function () { - return this._toString(this._raw); - }; - URI.prototype.toString = function () { - return this._toString(this._normal); - }; - Object.defineProperty(URI.prototype, "_normal", { - get: function () { return this.normal; }, - enumerable: true, - configurable: true - }); - Object.defineProperty(URI.prototype, "_raw", { - get: function () { return this.raw; }, - enumerable: true, - configurable: true - }); - URI.prototype._toString = function (uri) { - var uriString = uri.scheme + ":"; - // add slashes if it's not a sip(s) URI - if (!uri.scheme.toLowerCase().match("^sips?$")) { - uriString += "//"; - } - if (uri.user) { - uriString += this.escapeUser(uri.user) + "@"; - } - uriString += uri.host; - if (uri.port || uri.port === 0) { - uriString += ":" + uri.port; - } - for (var parameter in this.parameters) { - if (this.parameters.hasOwnProperty(parameter)) { - uriString += ";" + parameter; - if (this.parameters[parameter] !== null) { - uriString += "=" + this.parameters[parameter]; - } - } - } - var headers = []; - for (var header in this.headers) { - if (this.headers.hasOwnProperty(header)) { - for (var idx in this.headers[header]) { - if (this.headers[header].hasOwnProperty(idx)) { - headers.push(header + "=" + this.headers[header][idx]); - } - } - } - } - if (headers.length > 0) { - uriString += "?" + headers.join("&"); - } - return uriString; - }; - /* - * Hex-escape a SIP URI user. - * @private - * @param {String} user - */ - URI.prototype.escapeUser = function (user) { - var decodedUser; - // FIXME: This is called by toString above which should never throw, but - // decodeURIComponent can throw and I've seen one case in production where - // it did throw resulting in a cascading failure. This class should be - // fixed so that decodeURIComponent is not called at this point (in toString). - // The user should be decoded when the URI is constructor or some other - // place where we can catch the error before the URI is created or somesuch. - try { - decodedUser = decodeURIComponent(user); - } - catch (error) { - throw error; - } - // Don't hex-escape ':' (%3A), '+' (%2B), '?' (%3F"), '/' (%2F). - return encodeURIComponent(decodedUser) - .replace(/%3A/ig, ":") - .replace(/%2B/ig, "+") - .replace(/%3F/ig, "?") - .replace(/%2F/ig, "/"); - }; - URI.prototype.headerize = function (str) { - var exceptions = { - "Call-Id": "Call-ID", - "Cseq": "CSeq", - "Min-Se": "Min-SE", - "Rack": "RAck", - "Rseq": "RSeq", - "Www-Authenticate": "WWW-Authenticate", - }; - var name = str.toLowerCase().replace(/_/g, "-").split("-"); - var parts = name.length; - var hname = ""; - for (var part = 0; part < parts; part++) { - if (part !== 0) { - hname += "-"; - } - hname += name[part].charAt(0).toUpperCase() + name[part].substring(1); - } - if (exceptions[hname]) { - hname = exceptions[hname]; - } - return hname; - }; - return URI; -}(parameters_1.Parameters)); -exports.URI = URI; - - -/***/ }), -/* 16 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * @param size - - * @param base - - * @internal - */ -function createRandomToken(size, base) { - if (base === void 0) { base = 32; } - var token = ""; - for (var i = 0; i < size; i++) { - var r = Math.floor(Math.random() * base); - token += r.toString(base); - } - return token; -} -exports.createRandomToken = createRandomToken; -/** - * @internal - */ -function getReasonPhrase(code) { - return REASON_PHRASE[code] || ""; -} -exports.getReasonPhrase = getReasonPhrase; -/** - * @internal - */ -function newTag() { - return createRandomToken(10); -} -exports.newTag = newTag; -/** - * @param str - - * @internal - */ -function headerize(str) { - var exceptions = { - "Call-Id": "Call-ID", - "Cseq": "CSeq", - "Min-Se": "Min-SE", - "Rack": "RAck", - "Rseq": "RSeq", - "Www-Authenticate": "WWW-Authenticate", - }; - var name = str.toLowerCase().replace(/_/g, "-").split("-"); - var parts = name.length; - var hname = ""; - for (var part = 0; part < parts; part++) { - if (part !== 0) { - hname += "-"; - } - hname += name[part].charAt(0).toUpperCase() + name[part].substring(1); - } - if (exceptions[hname]) { - hname = exceptions[hname]; - } - return hname; -} -exports.headerize = headerize; -/** - * @param str - - * @internal - */ -function str_utf8_length(str) { - return encodeURIComponent(str).replace(/%[A-F\d]{2}/g, "U").length; -} -exports.str_utf8_length = str_utf8_length; -/** - * SIP Response Reasons - * DOC: http://www.iana.org/assignments/sip-parameters - * @internal - */ -var REASON_PHRASE = { - 100: "Trying", - 180: "Ringing", - 181: "Call Is Being Forwarded", - 182: "Queued", - 183: "Session Progress", - 199: "Early Dialog Terminated", - 200: "OK", - 202: "Accepted", - 204: "No Notification", - 300: "Multiple Choices", - 301: "Moved Permanently", - 302: "Moved Temporarily", - 305: "Use Proxy", - 380: "Alternative Service", - 400: "Bad Request", - 401: "Unauthorized", - 402: "Payment Required", - 403: "Forbidden", - 404: "Not Found", - 405: "Method Not Allowed", - 406: "Not Acceptable", - 407: "Proxy Authentication Required", - 408: "Request Timeout", - 410: "Gone", - 412: "Conditional Request Failed", - 413: "Request Entity Too Large", - 414: "Request-URI Too Long", - 415: "Unsupported Media Type", - 416: "Unsupported URI Scheme", - 417: "Unknown Resource-Priority", - 420: "Bad Extension", - 421: "Extension Required", - 422: "Session Interval Too Small", - 423: "Interval Too Brief", - 428: "Use Identity Header", - 429: "Provide Referrer Identity", - 430: "Flow Failed", - 433: "Anonymity Disallowed", - 436: "Bad Identity-Info", - 437: "Unsupported Certificate", - 438: "Invalid Identity Header", - 439: "First Hop Lacks Outbound Support", - 440: "Max-Breadth Exceeded", - 469: "Bad Info Package", - 470: "Consent Needed", - 478: "Unresolvable Destination", - 480: "Temporarily Unavailable", - 481: "Call/Transaction Does Not Exist", - 482: "Loop Detected", - 483: "Too Many Hops", - 484: "Address Incomplete", - 485: "Ambiguous", - 486: "Busy Here", - 487: "Request Terminated", - 488: "Not Acceptable Here", - 489: "Bad Event", - 491: "Request Pending", - 493: "Undecipherable", - 494: "Security Agreement Required", - 500: "Internal Server Error", - 501: "Not Implemented", - 502: "Bad Gateway", - 503: "Service Unavailable", - 504: "Server Time-out", - 505: "Version Not Supported", - 513: "Message Too Large", - 580: "Precondition Failure", - 600: "Busy Everywhere", - 603: "Decline", - 604: "Does Not Exist Anywhere", - 606: "Not Acceptable" -}; - - -/***/ }), -/* 17 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var incoming_message_1 = __webpack_require__(10); -/** - * Incoming response message. - * @public - */ -var IncomingResponseMessage = /** @class */ (function (_super) { - tslib_1.__extends(IncomingResponseMessage, _super); - function IncomingResponseMessage() { - return _super.call(this) || this; - } - return IncomingResponseMessage; -}(incoming_message_1.IncomingMessage)); -exports.IncomingResponseMessage = IncomingResponseMessage; - - -/***/ }), -/* 18 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var name_addr_header_1 = __webpack_require__(13); -var utils_1 = __webpack_require__(16); -/** - * Outgoing SIP request message. - * @public - */ -var OutgoingRequestMessage = /** @class */ (function () { - function OutgoingRequestMessage(method, ruri, fromURI, toURI, options, extraHeaders, body) { - this.headers = {}; - this.extraHeaders = []; - this.options = OutgoingRequestMessage.getDefaultOptions(); - // Options - merge a deep copy - if (options) { - this.options = tslib_1.__assign({}, this.options, options); - if (this.options.optionTags && this.options.optionTags.length) { - this.options.optionTags = this.options.optionTags.slice(); - } - if (this.options.routeSet && this.options.routeSet.length) { - this.options.routeSet = this.options.routeSet.slice(); - } - } - // Extra headers - deep copy - if (extraHeaders && extraHeaders.length) { - this.extraHeaders = extraHeaders.slice(); - } - // Body - deep copy - if (body) { - // TODO: internal representation should be Body - // this.body = { ...body }; - this.body = { - body: body.content, - contentType: body.contentType - }; - } - // Method - this.method = method; - // RURI - this.ruri = ruri.clone(); - // From - this.fromURI = fromURI.clone(); - this.fromTag = this.options.fromTag ? this.options.fromTag : utils_1.newTag(); - this.from = OutgoingRequestMessage.makeNameAddrHeader(this.fromURI, this.options.fromDisplayName, this.fromTag); - // To - this.toURI = toURI.clone(); - this.toTag = this.options.toTag; - this.to = OutgoingRequestMessage.makeNameAddrHeader(this.toURI, this.options.toDisplayName, this.toTag); - // Call-ID - this.callId = this.options.callId ? this.options.callId : this.options.callIdPrefix + utils_1.createRandomToken(15); - // CSeq - this.cseq = this.options.cseq; - // The relative order of header fields with different field names is not - // significant. However, it is RECOMMENDED that header fields which are - // needed for proxy processing (Via, Route, Record-Route, Proxy-Require, - // Max-Forwards, and Proxy-Authorization, for example) appear towards - // the top of the message to facilitate rapid parsing. - // https://tools.ietf.org/html/rfc3261#section-7.3.1 - this.setHeader("route", this.options.routeSet); - this.setHeader("via", ""); - this.setHeader("to", this.to.toString()); - this.setHeader("from", this.from.toString()); - this.setHeader("cseq", this.cseq + " " + this.method); - this.setHeader("call-id", this.callId); - this.setHeader("max-forwards", "70"); - } - /** Get a copy of the default options. */ - OutgoingRequestMessage.getDefaultOptions = function () { - return { - callId: "", - callIdPrefix: "", - cseq: 1, - toDisplayName: "", - toTag: "", - fromDisplayName: "", - fromTag: "", - forceRport: false, - hackViaTcp: false, - optionTags: ["outbound"], - routeSet: [], - userAgentString: "sip.js", - viaHost: "" - }; - }; - OutgoingRequestMessage.makeNameAddrHeader = function (uri, displayName, tag) { - var parameters = {}; - if (tag) { - parameters.tag = tag; - } - return new name_addr_header_1.NameAddrHeader(uri, displayName, parameters); - }; - /** - * Get the value of the given header name at the given position. - * @param name - header name - * @returns Returns the specified header, undefined if header doesn't exist. - */ - OutgoingRequestMessage.prototype.getHeader = function (name) { - var header = this.headers[utils_1.headerize(name)]; - if (header) { - if (header[0]) { - return header[0]; - } - } - else { - var regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); - for (var _i = 0, _a = this.extraHeaders; _i < _a.length; _i++) { - var exHeader = _a[_i]; - if (regexp.test(exHeader)) { - return exHeader.substring(exHeader.indexOf(":") + 1).trim(); - } - } - } - return; - }; - /** - * Get the header/s of the given name. - * @param name - header name - * @returns Array with all the headers of the specified name. - */ - OutgoingRequestMessage.prototype.getHeaders = function (name) { - var result = []; - var headerArray = this.headers[utils_1.headerize(name)]; - if (headerArray) { - for (var _i = 0, headerArray_1 = headerArray; _i < headerArray_1.length; _i++) { - var headerPart = headerArray_1[_i]; - result.push(headerPart); - } - } - else { - var regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); - for (var _a = 0, _b = this.extraHeaders; _a < _b.length; _a++) { - var exHeader = _b[_a]; - if (regexp.test(exHeader)) { - result.push(exHeader.substring(exHeader.indexOf(":") + 1).trim()); - } - } - } - return result; - }; - /** - * Verify the existence of the given header. - * @param name - header name - * @returns true if header with given name exists, false otherwise - */ - OutgoingRequestMessage.prototype.hasHeader = function (name) { - if (this.headers[utils_1.headerize(name)]) { - return true; - } - else { - var regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); - for (var _i = 0, _a = this.extraHeaders; _i < _a.length; _i++) { - var extraHeader = _a[_i]; - if (regexp.test(extraHeader)) { - return true; - } - } - } - return false; - }; - /** - * Replace the the given header by the given value. - * @param name - header name - * @param value - header value - */ - OutgoingRequestMessage.prototype.setHeader = function (name, value) { - this.headers[utils_1.headerize(name)] = (value instanceof Array) ? value : [value]; - }; - /** - * The Via header field indicates the transport used for the transaction - * and identifies the location where the response is to be sent. A Via - * header field value is added only after the transport that will be - * used to reach the next hop has been selected (which may involve the - * usage of the procedures in [4]). - * - * When the UAC creates a request, it MUST insert a Via into that - * request. The protocol name and protocol version in the header field - * MUST be SIP and 2.0, respectively. The Via header field value MUST - * contain a branch parameter. This parameter is used to identify the - * transaction created by that request. This parameter is used by both - * the client and the server. - * https://tools.ietf.org/html/rfc3261#section-8.1.1.7 - * @param branchParameter - The branch parameter. - * @param scheme - The scheme. - */ - OutgoingRequestMessage.prototype.setViaHeader = function (branch, scheme) { - if (scheme === void 0) { scheme = "WSS"; } - // FIXME: Hack - if (this.options.hackViaTcp) { - scheme = "TCP"; - } - var via = "SIP/2.0/" + scheme; - via += " " + this.options.viaHost + ";branch=" + branch; - if (this.options.forceRport) { - via += ";rport"; - } - this.setHeader("via", via); - this.branch = branch; - }; - OutgoingRequestMessage.prototype.toString = function () { - var msg = ""; - msg += this.method + " " + this.ruri.toRaw() + " SIP/2.0\r\n"; - for (var header in this.headers) { - if (this.headers[header]) { - for (var _i = 0, _a = this.headers[header]; _i < _a.length; _i++) { - var headerPart = _a[_i]; - msg += header + ": " + headerPart + "\r\n"; - } - } - } - for (var _b = 0, _c = this.extraHeaders; _b < _c.length; _b++) { - var header = _c[_b]; - msg += header.trim() + "\r\n"; - } - msg += "Supported: " + this.options.optionTags.join(", ") + "\r\n"; - msg += "User-Agent: " + this.options.userAgentString + "\r\n"; - if (this.body) { - if (typeof this.body === "string") { - msg += "Content-Length: " + utils_1.str_utf8_length(this.body) + "\r\n\r\n"; - msg += this.body; - } - else { - if (this.body.body && this.body.contentType) { - msg += "Content-Type: " + this.body.contentType + "\r\n"; - msg += "Content-Length: " + utils_1.str_utf8_length(this.body.body) + "\r\n\r\n"; - msg += this.body.body; - } - else { - msg += "Content-Length: " + 0 + "\r\n\r\n"; - } - } - } - else { - msg += "Content-Length: " + 0 + "\r\n\r\n"; - } - return msg; - }; - return OutgoingRequestMessage; -}()); -exports.OutgoingRequestMessage = OutgoingRequestMessage; - - -/***/ }), -/* 19 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var md5_1 = tslib_1.__importDefault(__webpack_require__(20)); -var utils_1 = __webpack_require__(16); -/** - * Digest Authentication. - * @internal - */ -var DigestAuthentication = /** @class */ (function () { - /** - * Constructor. - * @param loggerFactory - LoggerFactory. - * @param username - Username. - * @param password - Password. - */ - function DigestAuthentication(loggerFactory, username, password) { - this.logger = loggerFactory.getLogger("sipjs.digestauthentication"); - this.username = username; - this.password = password; - this.nc = 0; - this.ncHex = "00000000"; - } - /** - * Performs Digest authentication given a SIP request and the challenge - * received in a response to that request. - * @param request - - * @param challenge - - * @returns true if credentials were successfully generated, false otherwise. - */ - DigestAuthentication.prototype.authenticate = function (request, challenge, body) { - // Inspect and validate the challenge. - this.algorithm = challenge.algorithm; - this.realm = challenge.realm; - this.nonce = challenge.nonce; - this.opaque = challenge.opaque; - this.stale = challenge.stale; - if (this.algorithm) { - if (this.algorithm !== "MD5") { - this.logger.warn("challenge with Digest algorithm different than 'MD5', authentication aborted"); - return false; - } - } - else { - this.algorithm = "MD5"; - } - if (!this.realm) { - this.logger.warn("challenge without Digest realm, authentication aborted"); - return false; - } - if (!this.nonce) { - this.logger.warn("challenge without Digest nonce, authentication aborted"); - return false; - } - // 'qop' can contain a list of values (Array). Let's choose just one. - if (challenge.qop) { - if (challenge.qop.indexOf("auth") > -1) { - this.qop = "auth"; - } - else if (challenge.qop.indexOf("auth-int") > -1) { - this.qop = "auth-int"; - } - else { - // Otherwise 'qop' is present but does not contain 'auth' or 'auth-int', so abort here. - this.logger.warn("challenge without Digest qop different than 'auth' or 'auth-int', authentication aborted"); - return false; - } - } - else { - this.qop = undefined; - } - // Fill other attributes. - this.method = request.method; - this.uri = request.ruri; - this.cnonce = utils_1.createRandomToken(12); - this.nc += 1; - this.updateNcHex(); - // nc-value = 8LHEX. Max value = 'FFFFFFFF'. - if (this.nc === 4294967296) { - this.nc = 1; - this.ncHex = "00000001"; - } - // Calculate the Digest "response" value. - this.calculateResponse(body); - return true; - }; - /** - * Return the Proxy-Authorization or WWW-Authorization header value. - */ - DigestAuthentication.prototype.toString = function () { - var authParams = []; - if (!this.response) { - throw new Error("response field does not exist, cannot generate Authorization header"); - } - authParams.push("algorithm=" + this.algorithm); - authParams.push('username="' + this.username + '"'); - authParams.push('realm="' + this.realm + '"'); - authParams.push('nonce="' + this.nonce + '"'); - authParams.push('uri="' + this.uri + '"'); - authParams.push('response="' + this.response + '"'); - if (this.opaque) { - authParams.push('opaque="' + this.opaque + '"'); - } - if (this.qop) { - authParams.push("qop=" + this.qop); - authParams.push('cnonce="' + this.cnonce + '"'); - authParams.push("nc=" + this.ncHex); - } - return "Digest " + authParams.join(", "); - }; - /** - * Generate the 'nc' value as required by Digest in this.ncHex by reading this.nc. - */ - DigestAuthentication.prototype.updateNcHex = function () { - var hex = Number(this.nc).toString(16); - this.ncHex = "00000000".substr(0, 8 - hex.length) + hex; - }; - /** - * Generate Digest 'response' value. - */ - DigestAuthentication.prototype.calculateResponse = function (body) { - var ha2; - // HA1 = MD5(A1) = MD5(username:realm:password) - var ha1 = md5_1.default(this.username + ":" + this.realm + ":" + this.password); - if (this.qop === "auth") { - // HA2 = MD5(A2) = MD5(method:digestURI) - ha2 = md5_1.default(this.method + ":" + this.uri); - // response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2) - this.response = md5_1.default(ha1 + ":" + this.nonce + ":" + this.ncHex + ":" + this.cnonce + ":auth:" + ha2); - } - else if (this.qop === "auth-int") { - // HA2 = MD5(A2) = MD5(method:digestURI:MD5(entityBody)) - ha2 = md5_1.default(this.method + ":" + this.uri + ":" + md5_1.default(body ? body : "")); - // response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2) - this.response = md5_1.default(ha1 + ":" + this.nonce + ":" + this.ncHex + ":" + this.cnonce + ":auth-int:" + ha2); - } - else if (this.qop === undefined) { - // HA2 = MD5(A2) = MD5(method:digestURI) - ha2 = md5_1.default(this.method + ":" + this.uri); - // response = MD5(HA1:nonce:HA2) - this.response = md5_1.default(ha1 + ":" + this.nonce + ":" + ha2); - } - }; - return DigestAuthentication; -}()); -exports.DigestAuthentication = DigestAuthentication; - - -/***/ }), -/* 20 */ -/***/ (function(module, exports, __webpack_require__) { - -;(function (root, factory) { - if (true) { - // CommonJS - module.exports = exports = factory(__webpack_require__(21)); - } - else {} -}(this, function (CryptoJS) { - - (function (Math) { - // Shortcuts - var C = CryptoJS; - var C_lib = C.lib; - var WordArray = C_lib.WordArray; - var Hasher = C_lib.Hasher; - var C_algo = C.algo; - - // Constants table - var T = []; - - // Compute constants - (function () { - for (var i = 0; i < 64; i++) { - T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0; - } - }()); - - /** - * MD5 hash algorithm. - */ - var MD5 = C_algo.MD5 = Hasher.extend({ - _doReset: function () { - this._hash = new WordArray.init([ - 0x67452301, 0xefcdab89, - 0x98badcfe, 0x10325476 - ]); - }, - - _doProcessBlock: function (M, offset) { - // Swap endian - for (var i = 0; i < 16; i++) { - // Shortcuts - var offset_i = offset + i; - var M_offset_i = M[offset_i]; - - M[offset_i] = ( - (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | - (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) - ); - } - - // Shortcuts - var H = this._hash.words; - - var M_offset_0 = M[offset + 0]; - var M_offset_1 = M[offset + 1]; - var M_offset_2 = M[offset + 2]; - var M_offset_3 = M[offset + 3]; - var M_offset_4 = M[offset + 4]; - var M_offset_5 = M[offset + 5]; - var M_offset_6 = M[offset + 6]; - var M_offset_7 = M[offset + 7]; - var M_offset_8 = M[offset + 8]; - var M_offset_9 = M[offset + 9]; - var M_offset_10 = M[offset + 10]; - var M_offset_11 = M[offset + 11]; - var M_offset_12 = M[offset + 12]; - var M_offset_13 = M[offset + 13]; - var M_offset_14 = M[offset + 14]; - var M_offset_15 = M[offset + 15]; - - // Working varialbes - var a = H[0]; - var b = H[1]; - var c = H[2]; - var d = H[3]; - - // Computation - a = FF(a, b, c, d, M_offset_0, 7, T[0]); - d = FF(d, a, b, c, M_offset_1, 12, T[1]); - c = FF(c, d, a, b, M_offset_2, 17, T[2]); - b = FF(b, c, d, a, M_offset_3, 22, T[3]); - a = FF(a, b, c, d, M_offset_4, 7, T[4]); - d = FF(d, a, b, c, M_offset_5, 12, T[5]); - c = FF(c, d, a, b, M_offset_6, 17, T[6]); - b = FF(b, c, d, a, M_offset_7, 22, T[7]); - a = FF(a, b, c, d, M_offset_8, 7, T[8]); - d = FF(d, a, b, c, M_offset_9, 12, T[9]); - c = FF(c, d, a, b, M_offset_10, 17, T[10]); - b = FF(b, c, d, a, M_offset_11, 22, T[11]); - a = FF(a, b, c, d, M_offset_12, 7, T[12]); - d = FF(d, a, b, c, M_offset_13, 12, T[13]); - c = FF(c, d, a, b, M_offset_14, 17, T[14]); - b = FF(b, c, d, a, M_offset_15, 22, T[15]); - - a = GG(a, b, c, d, M_offset_1, 5, T[16]); - d = GG(d, a, b, c, M_offset_6, 9, T[17]); - c = GG(c, d, a, b, M_offset_11, 14, T[18]); - b = GG(b, c, d, a, M_offset_0, 20, T[19]); - a = GG(a, b, c, d, M_offset_5, 5, T[20]); - d = GG(d, a, b, c, M_offset_10, 9, T[21]); - c = GG(c, d, a, b, M_offset_15, 14, T[22]); - b = GG(b, c, d, a, M_offset_4, 20, T[23]); - a = GG(a, b, c, d, M_offset_9, 5, T[24]); - d = GG(d, a, b, c, M_offset_14, 9, T[25]); - c = GG(c, d, a, b, M_offset_3, 14, T[26]); - b = GG(b, c, d, a, M_offset_8, 20, T[27]); - a = GG(a, b, c, d, M_offset_13, 5, T[28]); - d = GG(d, a, b, c, M_offset_2, 9, T[29]); - c = GG(c, d, a, b, M_offset_7, 14, T[30]); - b = GG(b, c, d, a, M_offset_12, 20, T[31]); - - a = HH(a, b, c, d, M_offset_5, 4, T[32]); - d = HH(d, a, b, c, M_offset_8, 11, T[33]); - c = HH(c, d, a, b, M_offset_11, 16, T[34]); - b = HH(b, c, d, a, M_offset_14, 23, T[35]); - a = HH(a, b, c, d, M_offset_1, 4, T[36]); - d = HH(d, a, b, c, M_offset_4, 11, T[37]); - c = HH(c, d, a, b, M_offset_7, 16, T[38]); - b = HH(b, c, d, a, M_offset_10, 23, T[39]); - a = HH(a, b, c, d, M_offset_13, 4, T[40]); - d = HH(d, a, b, c, M_offset_0, 11, T[41]); - c = HH(c, d, a, b, M_offset_3, 16, T[42]); - b = HH(b, c, d, a, M_offset_6, 23, T[43]); - a = HH(a, b, c, d, M_offset_9, 4, T[44]); - d = HH(d, a, b, c, M_offset_12, 11, T[45]); - c = HH(c, d, a, b, M_offset_15, 16, T[46]); - b = HH(b, c, d, a, M_offset_2, 23, T[47]); - - a = II(a, b, c, d, M_offset_0, 6, T[48]); - d = II(d, a, b, c, M_offset_7, 10, T[49]); - c = II(c, d, a, b, M_offset_14, 15, T[50]); - b = II(b, c, d, a, M_offset_5, 21, T[51]); - a = II(a, b, c, d, M_offset_12, 6, T[52]); - d = II(d, a, b, c, M_offset_3, 10, T[53]); - c = II(c, d, a, b, M_offset_10, 15, T[54]); - b = II(b, c, d, a, M_offset_1, 21, T[55]); - a = II(a, b, c, d, M_offset_8, 6, T[56]); - d = II(d, a, b, c, M_offset_15, 10, T[57]); - c = II(c, d, a, b, M_offset_6, 15, T[58]); - b = II(b, c, d, a, M_offset_13, 21, T[59]); - a = II(a, b, c, d, M_offset_4, 6, T[60]); - d = II(d, a, b, c, M_offset_11, 10, T[61]); - c = II(c, d, a, b, M_offset_2, 15, T[62]); - b = II(b, c, d, a, M_offset_9, 21, T[63]); - - // Intermediate hash value - H[0] = (H[0] + a) | 0; - H[1] = (H[1] + b) | 0; - H[2] = (H[2] + c) | 0; - H[3] = (H[3] + d) | 0; - }, - - _doFinalize: function () { - // Shortcuts - var data = this._data; - var dataWords = data.words; - - var nBitsTotal = this._nDataBytes * 8; - var nBitsLeft = data.sigBytes * 8; - - // Add padding - dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); - - var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000); - var nBitsTotalL = nBitsTotal; - dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = ( - (((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) | - (((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00) - ); - dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( - (((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) | - (((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00) - ); - - data.sigBytes = (dataWords.length + 1) * 4; - - // Hash final blocks - this._process(); - - // Shortcuts - var hash = this._hash; - var H = hash.words; - - // Swap endian - for (var i = 0; i < 4; i++) { - // Shortcut - var H_i = H[i]; - - H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | - (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); - } - - // Return final computed hash - return hash; - }, - - clone: function () { - var clone = Hasher.clone.call(this); - clone._hash = this._hash.clone(); - - return clone; - } - }); - - function FF(a, b, c, d, x, s, t) { - var n = a + ((b & c) | (~b & d)) + x + t; - return ((n << s) | (n >>> (32 - s))) + b; - } - - function GG(a, b, c, d, x, s, t) { - var n = a + ((b & d) | (c & ~d)) + x + t; - return ((n << s) | (n >>> (32 - s))) + b; - } - - function HH(a, b, c, d, x, s, t) { - var n = a + (b ^ c ^ d) + x + t; - return ((n << s) | (n >>> (32 - s))) + b; - } - - function II(a, b, c, d, x, s, t) { - var n = a + (c ^ (b | ~d)) + x + t; - return ((n << s) | (n >>> (32 - s))) + b; - } - - /** - * Shortcut function to the hasher's object interface. - * - * @param {WordArray|string} message The message to hash. - * - * @return {WordArray} The hash. - * - * @static - * - * @example - * - * var hash = CryptoJS.MD5('message'); - * var hash = CryptoJS.MD5(wordArray); - */ - C.MD5 = Hasher._createHelper(MD5); - - /** - * Shortcut function to the HMAC's object interface. - * - * @param {WordArray|string} message The message to hash. - * @param {WordArray|string} key The secret key. - * - * @return {WordArray} The HMAC. - * - * @static - * - * @example - * - * var hmac = CryptoJS.HmacMD5(message, key); - */ - C.HmacMD5 = Hasher._createHmacHelper(MD5); - }(Math)); - - - return CryptoJS.MD5; - -})); - -/***/ }), -/* 21 */ -/***/ (function(module, exports, __webpack_require__) { - -;(function (root, factory) { - if (true) { - // CommonJS - module.exports = exports = factory(); - } - else {} -}(this, function () { - - /** - * CryptoJS core components. - */ - var CryptoJS = CryptoJS || (function (Math, undefined) { - /* - * Local polyfil of Object.create - */ - var create = Object.create || (function () { - function F() {}; - - return function (obj) { - var subtype; - - F.prototype = obj; - - subtype = new F(); - - F.prototype = null; - - return subtype; - }; - }()) - - /** - * CryptoJS namespace. - */ - var C = {}; - - /** - * Library namespace. - */ - var C_lib = C.lib = {}; - - /** - * Base object for prototypal inheritance. - */ - var Base = C_lib.Base = (function () { - - - return { - /** - * Creates a new object that inherits from this object. - * - * @param {Object} overrides Properties to copy into the new object. - * - * @return {Object} The new object. - * - * @static - * - * @example - * - * var MyType = CryptoJS.lib.Base.extend({ - * field: 'value', - * - * method: function () { - * } - * }); - */ - extend: function (overrides) { - // Spawn - var subtype = create(this); - - // Augment - if (overrides) { - subtype.mixIn(overrides); - } - - // Create default initializer - if (!subtype.hasOwnProperty('init') || this.init === subtype.init) { - subtype.init = function () { - subtype.$super.init.apply(this, arguments); - }; - } - - // Initializer's prototype is the subtype object - subtype.init.prototype = subtype; - - // Reference supertype - subtype.$super = this; - - return subtype; - }, - - /** - * Extends this object and runs the init method. - * Arguments to create() will be passed to init(). - * - * @return {Object} The new object. - * - * @static - * - * @example - * - * var instance = MyType.create(); - */ - create: function () { - var instance = this.extend(); - instance.init.apply(instance, arguments); - - return instance; - }, - - /** - * Initializes a newly created object. - * Override this method to add some logic when your objects are created. - * - * @example - * - * var MyType = CryptoJS.lib.Base.extend({ - * init: function () { - * // ... - * } - * }); - */ - init: function () { - }, - - /** - * Copies properties into this object. - * - * @param {Object} properties The properties to mix in. - * - * @example - * - * MyType.mixIn({ - * field: 'value' - * }); - */ - mixIn: function (properties) { - for (var propertyName in properties) { - if (properties.hasOwnProperty(propertyName)) { - this[propertyName] = properties[propertyName]; - } - } - - // IE won't copy toString using the loop above - if (properties.hasOwnProperty('toString')) { - this.toString = properties.toString; - } - }, - - /** - * Creates a copy of this object. - * - * @return {Object} The clone. - * - * @example - * - * var clone = instance.clone(); - */ - clone: function () { - return this.init.prototype.extend(this); - } - }; - }()); - - /** - * An array of 32-bit words. - * - * @property {Array} words The array of 32-bit words. - * @property {number} sigBytes The number of significant bytes in this word array. - */ - var WordArray = C_lib.WordArray = Base.extend({ - /** - * Initializes a newly created word array. - * - * @param {Array} words (Optional) An array of 32-bit words. - * @param {number} sigBytes (Optional) The number of significant bytes in the words. - * - * @example - * - * var wordArray = CryptoJS.lib.WordArray.create(); - * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); - * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); - */ - init: function (words, sigBytes) { - words = this.words = words || []; - - if (sigBytes != undefined) { - this.sigBytes = sigBytes; - } else { - this.sigBytes = words.length * 4; - } - }, - - /** - * Converts this word array to a string. - * - * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex - * - * @return {string} The stringified word array. - * - * @example - * - * var string = wordArray + ''; - * var string = wordArray.toString(); - * var string = wordArray.toString(CryptoJS.enc.Utf8); - */ - toString: function (encoder) { - return (encoder || Hex).stringify(this); - }, - - /** - * Concatenates a word array to this word array. - * - * @param {WordArray} wordArray The word array to append. - * - * @return {WordArray} This word array. - * - * @example - * - * wordArray1.concat(wordArray2); - */ - concat: function (wordArray) { - // Shortcuts - var thisWords = this.words; - var thatWords = wordArray.words; - var thisSigBytes = this.sigBytes; - var thatSigBytes = wordArray.sigBytes; - - // Clamp excess bits - this.clamp(); - - // Concat - if (thisSigBytes % 4) { - // Copy one byte at a time - for (var i = 0; i < thatSigBytes; i++) { - var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; - thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); - } - } else { - // Copy one word at a time - for (var i = 0; i < thatSigBytes; i += 4) { - thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2]; - } - } - this.sigBytes += thatSigBytes; - - // Chainable - return this; - }, - - /** - * Removes insignificant bits. - * - * @example - * - * wordArray.clamp(); - */ - clamp: function () { - // Shortcuts - var words = this.words; - var sigBytes = this.sigBytes; - - // Clamp - words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); - words.length = Math.ceil(sigBytes / 4); - }, - - /** - * Creates a copy of this word array. - * - * @return {WordArray} The clone. - * - * @example - * - * var clone = wordArray.clone(); - */ - clone: function () { - var clone = Base.clone.call(this); - clone.words = this.words.slice(0); - - return clone; - }, - - /** - * Creates a word array filled with random bytes. - * - * @param {number} nBytes The number of random bytes to generate. - * - * @return {WordArray} The random word array. - * - * @static - * - * @example - * - * var wordArray = CryptoJS.lib.WordArray.random(16); - */ - random: function (nBytes) { - var words = []; - - var r = (function (m_w) { - var m_w = m_w; - var m_z = 0x3ade68b1; - var mask = 0xffffffff; - - return function () { - m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask; - m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask; - var result = ((m_z << 0x10) + m_w) & mask; - result /= 0x100000000; - result += 0.5; - return result * (Math.random() > .5 ? 1 : -1); - } - }); - - for (var i = 0, rcache; i < nBytes; i += 4) { - var _r = r((rcache || Math.random()) * 0x100000000); - - rcache = _r() * 0x3ade67b7; - words.push((_r() * 0x100000000) | 0); - } - - return new WordArray.init(words, nBytes); - } - }); - - /** - * Encoder namespace. - */ - var C_enc = C.enc = {}; - - /** - * Hex encoding strategy. - */ - var Hex = C_enc.Hex = { - /** - * Converts a word array to a hex string. - * - * @param {WordArray} wordArray The word array. - * - * @return {string} The hex string. - * - * @static - * - * @example - * - * var hexString = CryptoJS.enc.Hex.stringify(wordArray); - */ - stringify: function (wordArray) { - // Shortcuts - var words = wordArray.words; - var sigBytes = wordArray.sigBytes; - - // Convert - var hexChars = []; - for (var i = 0; i < sigBytes; i++) { - var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; - hexChars.push((bite >>> 4).toString(16)); - hexChars.push((bite & 0x0f).toString(16)); - } - - return hexChars.join(''); - }, - - /** - * Converts a hex string to a word array. - * - * @param {string} hexStr The hex string. - * - * @return {WordArray} The word array. - * - * @static - * - * @example - * - * var wordArray = CryptoJS.enc.Hex.parse(hexString); - */ - parse: function (hexStr) { - // Shortcut - var hexStrLength = hexStr.length; - - // Convert - var words = []; - for (var i = 0; i < hexStrLength; i += 2) { - words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); - } - - return new WordArray.init(words, hexStrLength / 2); - } - }; - - /** - * Latin1 encoding strategy. - */ - var Latin1 = C_enc.Latin1 = { - /** - * Converts a word array to a Latin1 string. - * - * @param {WordArray} wordArray The word array. - * - * @return {string} The Latin1 string. - * - * @static - * - * @example - * - * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); - */ - stringify: function (wordArray) { - // Shortcuts - var words = wordArray.words; - var sigBytes = wordArray.sigBytes; - - // Convert - var latin1Chars = []; - for (var i = 0; i < sigBytes; i++) { - var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; - latin1Chars.push(String.fromCharCode(bite)); - } - - return latin1Chars.join(''); - }, - - /** - * Converts a Latin1 string to a word array. - * - * @param {string} latin1Str The Latin1 string. - * - * @return {WordArray} The word array. - * - * @static - * - * @example - * - * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); - */ - parse: function (latin1Str) { - // Shortcut - var latin1StrLength = latin1Str.length; - - // Convert - var words = []; - for (var i = 0; i < latin1StrLength; i++) { - words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); - } - - return new WordArray.init(words, latin1StrLength); - } - }; - - /** - * UTF-8 encoding strategy. - */ - var Utf8 = C_enc.Utf8 = { - /** - * Converts a word array to a UTF-8 string. - * - * @param {WordArray} wordArray The word array. - * - * @return {string} The UTF-8 string. - * - * @static - * - * @example - * - * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); - */ - stringify: function (wordArray) { - try { - return decodeURIComponent(escape(Latin1.stringify(wordArray))); - } catch (e) { - throw new Error('Malformed UTF-8 data'); - } - }, - - /** - * Converts a UTF-8 string to a word array. - * - * @param {string} utf8Str The UTF-8 string. - * - * @return {WordArray} The word array. - * - * @static - * - * @example - * - * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); - */ - parse: function (utf8Str) { - return Latin1.parse(unescape(encodeURIComponent(utf8Str))); - } - }; - - /** - * Abstract buffered block algorithm template. - * - * The property blockSize must be implemented in a concrete subtype. - * - * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 - */ - var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ - /** - * Resets this block algorithm's data buffer to its initial state. - * - * @example - * - * bufferedBlockAlgorithm.reset(); - */ - reset: function () { - // Initial values - this._data = new WordArray.init(); - this._nDataBytes = 0; - }, - - /** - * Adds new data to this block algorithm's buffer. - * - * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. - * - * @example - * - * bufferedBlockAlgorithm._append('data'); - * bufferedBlockAlgorithm._append(wordArray); - */ - _append: function (data) { - // Convert string to WordArray, else assume WordArray already - if (typeof data == 'string') { - data = Utf8.parse(data); - } - - // Append - this._data.concat(data); - this._nDataBytes += data.sigBytes; - }, - - /** - * Processes available data blocks. - * - * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. - * - * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. - * - * @return {WordArray} The processed data. - * - * @example - * - * var processedData = bufferedBlockAlgorithm._process(); - * var processedData = bufferedBlockAlgorithm._process(!!'flush'); - */ - _process: function (doFlush) { - // Shortcuts - var data = this._data; - var dataWords = data.words; - var dataSigBytes = data.sigBytes; - var blockSize = this.blockSize; - var blockSizeBytes = blockSize * 4; - - // Count blocks ready - var nBlocksReady = dataSigBytes / blockSizeBytes; - if (doFlush) { - // Round up to include partial blocks - nBlocksReady = Math.ceil(nBlocksReady); - } else { - // Round down to include only full blocks, - // less the number of blocks that must remain in the buffer - nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); - } - - // Count words ready - var nWordsReady = nBlocksReady * blockSize; - - // Count bytes ready - var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); - - // Process blocks - if (nWordsReady) { - for (var offset = 0; offset < nWordsReady; offset += blockSize) { - // Perform concrete-algorithm logic - this._doProcessBlock(dataWords, offset); - } - - // Remove processed words - var processedWords = dataWords.splice(0, nWordsReady); - data.sigBytes -= nBytesReady; - } - - // Return processed words - return new WordArray.init(processedWords, nBytesReady); - }, - - /** - * Creates a copy of this object. - * - * @return {Object} The clone. - * - * @example - * - * var clone = bufferedBlockAlgorithm.clone(); - */ - clone: function () { - var clone = Base.clone.call(this); - clone._data = this._data.clone(); - - return clone; - }, - - _minBufferSize: 0 - }); - - /** - * Abstract hasher template. - * - * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) - */ - var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ - /** - * Configuration options. - */ - cfg: Base.extend(), - - /** - * Initializes a newly created hasher. - * - * @param {Object} cfg (Optional) The configuration options to use for this hash computation. - * - * @example - * - * var hasher = CryptoJS.algo.SHA256.create(); - */ - init: function (cfg) { - // Apply config defaults - this.cfg = this.cfg.extend(cfg); - - // Set initial values - this.reset(); - }, - - /** - * Resets this hasher to its initial state. - * - * @example - * - * hasher.reset(); - */ - reset: function () { - // Reset data buffer - BufferedBlockAlgorithm.reset.call(this); - - // Perform concrete-hasher logic - this._doReset(); - }, - - /** - * Updates this hasher with a message. - * - * @param {WordArray|string} messageUpdate The message to append. - * - * @return {Hasher} This hasher. - * - * @example - * - * hasher.update('message'); - * hasher.update(wordArray); - */ - update: function (messageUpdate) { - // Append - this._append(messageUpdate); - - // Update the hash - this._process(); - - // Chainable - return this; - }, - - /** - * Finalizes the hash computation. - * Note that the finalize operation is effectively a destructive, read-once operation. - * - * @param {WordArray|string} messageUpdate (Optional) A final message update. - * - * @return {WordArray} The hash. - * - * @example - * - * var hash = hasher.finalize(); - * var hash = hasher.finalize('message'); - * var hash = hasher.finalize(wordArray); - */ - finalize: function (messageUpdate) { - // Final message update - if (messageUpdate) { - this._append(messageUpdate); - } - - // Perform concrete-hasher logic - var hash = this._doFinalize(); - - return hash; - }, - - blockSize: 512/32, - - /** - * Creates a shortcut function to a hasher's object interface. - * - * @param {Hasher} hasher The hasher to create a helper for. - * - * @return {Function} The shortcut function. - * - * @static - * - * @example - * - * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); - */ - _createHelper: function (hasher) { - return function (message, cfg) { - return new hasher.init(cfg).finalize(message); - }; - }, - - /** - * Creates a shortcut function to the HMAC's object interface. - * - * @param {Hasher} hasher The hasher to use in this HMAC helper. - * - * @return {Function} The shortcut function. - * - * @static - * - * @example - * - * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); - */ - _createHmacHelper: function (hasher) { - return function (message, key) { - return new C_algo.HMAC.init(hasher, key).finalize(message); - }; - } - }); - - /** - * Algorithm namespace. - */ - var C_algo = C.algo = {}; - - return C; - }(Math)); - - - return CryptoJS; - -})); - -/***/ }), -/* 22 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var utils_1 = __webpack_require__(16); -/** - * When a UAS wishes to construct a response to a request, it follows - * the general procedures detailed in the following subsections. - * Additional behaviors specific to the response code in question, which - * are not detailed in this section, may also be required. - * https://tools.ietf.org/html/rfc3261#section-8.2.6 - * @internal - */ -function constructOutgoingResponse(message, options) { - var CRLF = "\r\n"; - if (options.statusCode < 100 || options.statusCode > 699) { - throw new TypeError("Invalid statusCode: " + options.statusCode); - } - var reasonPhrase = options.reasonPhrase ? options.reasonPhrase : utils_1.getReasonPhrase(options.statusCode); - // SIP responses are distinguished from requests by having a Status-Line - // as their start-line. A Status-Line consists of the protocol version - // followed by a numeric Status-Code and its associated textual phrase, - // with each element separated by a single SP character. - // https://tools.ietf.org/html/rfc3261#section-7.2 - var response = "SIP/2.0 " + options.statusCode + " " + reasonPhrase + CRLF; - // One largely non-method-specific guideline for the generation of - // responses is that UASs SHOULD NOT issue a provisional response for a - // non-INVITE request. Rather, UASs SHOULD generate a final response to - // a non-INVITE request as soon as possible. - // https://tools.ietf.org/html/rfc3261#section-8.2.6.1 - if (options.statusCode >= 100 && options.statusCode < 200) { - // TODO - } - // When a 100 (Trying) response is generated, any Timestamp header field - // present in the request MUST be copied into this 100 (Trying) - // response. If there is a delay in generating the response, the UAS - // SHOULD add a delay value into the Timestamp value in the response. - // This value MUST contain the difference between the time of sending of - // the response and receipt of the request, measured in seconds. - // https://tools.ietf.org/html/rfc3261#section-8.2.6.1 - if (options.statusCode === 100) { - // TODO - } - // The From field of the response MUST equal the From header field of - // the request. The Call-ID header field of the response MUST equal the - // Call-ID header field of the request. The CSeq header field of the - // response MUST equal the CSeq field of the request. The Via header - // field values in the response MUST equal the Via header field values - // in the request and MUST maintain the same ordering. - // https://tools.ietf.org/html/rfc3261#section-8.2.6.2 - var fromHeader = "From: " + message.getHeader("From") + CRLF; - var callIdHeader = "Call-ID: " + message.callId + CRLF; - var cSeqHeader = "CSeq: " + message.cseq + " " + message.method + CRLF; - var viaHeaders = message.getHeaders("via").reduce(function (previous, current) { - return previous + "Via: " + current + CRLF; - }, ""); - // If a request contained a To tag in the request, the To header field - // in the response MUST equal that of the request. However, if the To - // header field in the request did not contain a tag, the URI in the To - // header field in the response MUST equal the URI in the To header - // field; additionally, the UAS MUST add a tag to the To header field in - // the response (with the exception of the 100 (Trying) response, in - // which a tag MAY be present). This serves to identify the UAS that is - // responding, possibly resulting in a component of a dialog ID. The - // same tag MUST be used for all responses to that request, both final - // and provisional (again excepting the 100 (Trying)). - // https://tools.ietf.org/html/rfc3261#section-8.2.6.2 - var toHeader = "To: " + message.getHeader("to"); - if (options.statusCode > 100 && !message.parseHeader("to").hasParam("tag")) { - var toTag = options.toTag; - if (!toTag) { - // Stateless UAS Behavior... - // o To header tags MUST be generated for responses in a stateless - // manner - in a manner that will generate the same tag for the - // same request consistently. For information on tag construction - // see Section 19.3. - // https://tools.ietf.org/html/rfc3261#section-8.2.7 - toTag = utils_1.newTag(); // FIXME: newTag() currently generates random tags - } - toHeader += ";tag=" + toTag; - } - toHeader += CRLF; - // FIXME: TODO: needs review... moved to InviteUserAgentServer (as it is specific to that) - // let recordRouteHeaders = ""; - // if (request.method === C.INVITE && statusCode > 100 && statusCode <= 200) { - // recordRouteHeaders = request.getHeaders("record-route").reduce((previous, current) => { - // return previous + "Record-Route: " + current + CRLF; - // }, ""); - // } - // FIXME: TODO: needs review... - var supportedHeader = ""; - if (options.supported) { - supportedHeader = "Supported: " + options.supported.join(", ") + CRLF; - } - // FIXME: TODO: needs review... - var userAgentHeader = ""; - if (options.userAgent) { - userAgentHeader = "User-Agent: " + options.userAgent + CRLF; - } - var extensionHeaders = ""; - if (options.extraHeaders) { - extensionHeaders = options.extraHeaders.reduce(function (previous, current) { - return previous + current.trim() + CRLF; - }, ""); - } - // The relative order of header fields with different field names is not - // significant. However, it is RECOMMENDED that header fields which are - // needed for proxy processing (Via, Route, Record-Route, Proxy-Require, - // Max-Forwards, and Proxy-Authorization, for example) appear towards - // the top of the message to facilitate rapid parsing. - // https://tools.ietf.org/html/rfc3261#section-7.3.1 - // response += recordRouteHeaders; - response += viaHeaders; - response += fromHeader; - response += toHeader; - response += cSeqHeader; - response += callIdHeader; - response += supportedHeader; - response += userAgentHeader; - response += extensionHeaders; - if (options.body) { - response += "Content-Type: " + options.body.contentType + CRLF; - response += "Content-Length: " + utils_1.str_utf8_length(options.body.content) + CRLF + CRLF; - response += options.body.content; - } - else { - response += "Content-Length: " + 0 + CRLF + CRLF; - } - return { message: response }; -} -exports.constructOutgoingResponse = constructOutgoingResponse; - - -/***/ }), -/* 23 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var session_1 = __webpack_require__(24); -var timers_1 = __webpack_require__(26); -var transactions_1 = __webpack_require__(27); -var bye_user_agent_client_1 = __webpack_require__(41); -var bye_user_agent_server_1 = __webpack_require__(43); -var info_user_agent_client_1 = __webpack_require__(45); -var info_user_agent_server_1 = __webpack_require__(46); -var notify_user_agent_client_1 = __webpack_require__(47); -var notify_user_agent_server_1 = __webpack_require__(48); -var prack_user_agent_client_1 = __webpack_require__(49); -var prack_user_agent_server_1 = __webpack_require__(50); -var re_invite_user_agent_client_1 = __webpack_require__(51); -var re_invite_user_agent_server_1 = __webpack_require__(52); -var refer_user_agent_client_1 = __webpack_require__(53); -var refer_user_agent_server_1 = __webpack_require__(54); -var dialog_1 = __webpack_require__(4); -/** - * Session Dialog. - * @public - */ -var SessionDialog = /** @class */ (function (_super) { - tslib_1.__extends(SessionDialog, _super); - function SessionDialog(initialTransaction, core, state, delegate) { - var _this = _super.call(this, core, state) || this; - _this.initialTransaction = initialTransaction; - /** The state of the offer/answer exchange. */ - _this._signalingState = session_1.SignalingState.Initial; - /** True if waiting for an ACK to the initial transaction 2xx (UAS only). */ - _this.ackWait = false; - _this.delegate = delegate; - if (initialTransaction instanceof transactions_1.InviteServerTransaction) { - // If we're created by an invite server transaction, we're - // going to be waiting for an ACK if are to be confirmed. - _this.ackWait = true; - } - // If we're confirmed upon creation start the retransmitting whatever - // the 2xx final response was that confirmed us into existence. - if (!_this.early) { - _this.start2xxRetransmissionTimer(); - } - _this.signalingStateTransition(initialTransaction.request); - _this.logger = core.loggerFactory.getLogger("sip.invite-dialog"); - _this.logger.log("INVITE dialog " + _this.id + " constructed"); - return _this; - } - SessionDialog.prototype.dispose = function () { - _super.prototype.dispose.call(this); - this._signalingState = session_1.SignalingState.Closed; - this._offer = undefined; - this._answer = undefined; - if (this.invite2xxTimer) { - clearTimeout(this.invite2xxTimer); - this.invite2xxTimer = undefined; - } - // The UAS MUST still respond to any pending requests received for that - // dialog. It is RECOMMENDED that a 487 (Request Terminated) response - // be generated to those pending requests. - // https://tools.ietf.org/html/rfc3261#section-15.1.2 - // TODO: - // this.userAgentServers.forEach((uas) => uas.reply(487)); - this.logger.log("INVITE dialog " + this.id + " destroyed"); - }; - Object.defineProperty(SessionDialog.prototype, "sessionState", { - // FIXME: Need real state machine - get: function () { - if (this.early) { - return session_1.SessionState.Early; - } - else if (this.ackWait) { - return session_1.SessionState.AckWait; - } - else if (this._signalingState === session_1.SignalingState.Closed) { - return session_1.SessionState.Terminated; - } - else { - return session_1.SessionState.Confirmed; - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SessionDialog.prototype, "signalingState", { - /** The state of the offer/answer exchange. */ - get: function () { - return this._signalingState; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SessionDialog.prototype, "offer", { - /** The current offer. Undefined unless signaling state HaveLocalOffer, HaveRemoteOffer, of Stable. */ - get: function () { - return this._offer; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SessionDialog.prototype, "answer", { - /** The current answer. Undefined unless signaling state Stable. */ - get: function () { - return this._answer; - }, - enumerable: true, - configurable: true - }); - /** Confirm the dialog. Only matters if dialog is currently early. */ - SessionDialog.prototype.confirm = function () { - // When we're confirmed start the retransmitting whatever - // the 2xx final response that may have confirmed us. - if (this.early) { - this.start2xxRetransmissionTimer(); - } - _super.prototype.confirm.call(this); - }; - /** Re-confirm the dialog. Only matters if handling re-INVITE request. */ - SessionDialog.prototype.reConfirm = function () { - // When we're confirmed start the retransmitting whatever - // the 2xx final response that may have confirmed us. - if (this.reinviteUserAgentServer) { - this.startReInvite2xxRetransmissionTimer(); - } - }; - /** - * The UAC core MUST generate an ACK request for each 2xx received from - * the transaction layer. The header fields of the ACK are constructed - * in the same way as for any request sent within a dialog (see Section - * 12) with the exception of the CSeq and the header fields related to - * authentication. The sequence number of the CSeq header field MUST be - * the same as the INVITE being acknowledged, but the CSeq method MUST - * be ACK. The ACK MUST contain the same credentials as the INVITE. If - * the 2xx contains an offer (based on the rules above), the ACK MUST - * carry an answer in its body. If the offer in the 2xx response is not - * acceptable, the UAC core MUST generate a valid answer in the ACK and - * then send a BYE immediately. - * https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - * @param options - ACK options bucket. - */ - SessionDialog.prototype.ack = function (options) { - if (options === void 0) { options = {}; } - this.logger.log("INVITE dialog " + this.id + " sending ACK request"); - var transaction; - if (this.reinviteUserAgentClient) { - // We're sending ACK for a re-INVITE - if (!(this.reinviteUserAgentClient.transaction instanceof transactions_1.InviteClientTransaction)) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - transaction = this.reinviteUserAgentClient.transaction; - this.reinviteUserAgentClient = undefined; - } - else { - // We're sending ACK for the initial INVITE - if (!(this.initialTransaction instanceof transactions_1.InviteClientTransaction)) { - throw new Error("Initial transaction not instance of InviteClientTransaction."); - } - transaction = this.initialTransaction; - } - options.cseq = transaction.request.cseq; // ACK cseq is INVITE cseq - var message = this.createOutgoingRequestMessage(messages_1.C.ACK, options); - transaction.ackResponse(message); // See InviteClientTransaction for details. - this.signalingStateTransition(message); - return { message: message }; - }; - /** - * Terminating a Session - * - * This section describes the procedures for terminating a session - * established by SIP. The state of the session and the state of the - * dialog are very closely related. When a session is initiated with an - * INVITE, each 1xx or 2xx response from a distinct UAS creates a - * dialog, and if that response completes the offer/answer exchange, it - * also creates a session. As a result, each session is "associated" - * with a single dialog - the one which resulted in its creation. If an - * initial INVITE generates a non-2xx final response, that terminates - * all sessions (if any) and all dialogs (if any) that were created - * through responses to the request. By virtue of completing the - * transaction, a non-2xx final response also prevents further sessions - * from being created as a result of the INVITE. The BYE request is - * used to terminate a specific session or attempted session. In this - * case, the specific session is the one with the peer UA on the other - * side of the dialog. When a BYE is received on a dialog, any session - * associated with that dialog SHOULD terminate. A UA MUST NOT send a - * BYE outside of a dialog. The caller's UA MAY send a BYE for either - * confirmed or early dialogs, and the callee's UA MAY send a BYE on - * confirmed dialogs, but MUST NOT send a BYE on early dialogs. - * - * However, the callee's UA MUST NOT send a BYE on a confirmed dialog - * until it has received an ACK for its 2xx response or until the server - * transaction times out. If no SIP extensions have defined other - * application layer states associated with the dialog, the BYE also - * terminates the dialog. - * - * https://tools.ietf.org/html/rfc3261#section-15 - * FIXME: Make these proper Exceptions... - * @param options - BYE options bucket. - * @returns - * Throws `Error` if callee's UA attempts a BYE on an early dialog. - * Throws `Error` if callee's UA attempts a BYE on a confirmed dialog - * while it's waiting on the ACK for its 2xx response. - */ - SessionDialog.prototype.bye = function (delegate, options) { - this.logger.log("INVITE dialog " + this.id + " sending BYE request"); - // The caller's UA MAY send a BYE for either - // confirmed or early dialogs, and the callee's UA MAY send a BYE on - // confirmed dialogs, but MUST NOT send a BYE on early dialogs. - // - // However, the callee's UA MUST NOT send a BYE on a confirmed dialog - // until it has received an ACK for its 2xx response or until the server - // transaction times out. - // https://tools.ietf.org/html/rfc3261#section-15 - if (this.initialTransaction instanceof transactions_1.InviteServerTransaction) { - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("UAS MUST NOT send a BYE on early dialogs."); - } - if (this.ackWait && this.initialTransaction.state !== transactions_1.TransactionState.Terminated) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("UAS MUST NOT send a BYE on a confirmed dialog " + - "until it has received an ACK for its 2xx response " + - "or until the server transaction times out."); - } - } - // A BYE request is constructed as would any other request within a - // dialog, as described in Section 12. - // - // Once the BYE is constructed, the UAC core creates a new non-INVITE - // client transaction, and passes it the BYE request. The UAC MUST - // consider the session terminated (and therefore stop sending or - // listening for media) as soon as the BYE request is passed to the - // client transaction. If the response for the BYE is a 481 - // (Call/Transaction Does Not Exist) or a 408 (Request Timeout) or no - // response at all is received for the BYE (that is, a timeout is - // returned by the client transaction), the UAC MUST consider the - // session and the dialog terminated. - // https://tools.ietf.org/html/rfc3261#section-15.1.1 - return new bye_user_agent_client_1.ByeUserAgentClient(this, delegate, options); - }; - /** - * An INFO request can be associated with an Info Package (see - * Section 5), or associated with a legacy INFO usage (see Section 2). - * - * The construction of the INFO request is the same as any other - * non-target refresh request within an existing invite dialog usage as - * described in Section 12.2 of RFC 3261. - * https://tools.ietf.org/html/rfc6086#section-4.2.1 - * @param options - Options bucket. - */ - SessionDialog.prototype.info = function (delegate, options) { - this.logger.log("INVITE dialog " + this.id + " sending INFO request"); - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("Dialog not confirmed."); - } - return new info_user_agent_client_1.InfoUserAgentClient(this, delegate, options); - }; - /** - * Modifying an Existing Session - * - * A successful INVITE request (see Section 13) establishes both a - * dialog between two user agents and a session using the offer-answer - * model. Section 12 explains how to modify an existing dialog using a - * target refresh request (for example, changing the remote target URI - * of the dialog). This section describes how to modify the actual - * session. This modification can involve changing addresses or ports, - * adding a media stream, deleting a media stream, and so on. This is - * accomplished by sending a new INVITE request within the same dialog - * that established the session. An INVITE request sent within an - * existing dialog is known as a re-INVITE. - * - * Note that a single re-INVITE can modify the dialog and the - * parameters of the session at the same time. - * - * Either the caller or callee can modify an existing session. - * https://tools.ietf.org/html/rfc3261#section-14 - * @param options - Options bucket - */ - SessionDialog.prototype.invite = function (delegate, options) { - this.logger.log("INVITE dialog " + this.id + " sending INVITE request"); - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("Dialog not confirmed."); - } - // Note that a UAC MUST NOT initiate a new INVITE transaction within a - // dialog while another INVITE transaction is in progress in either - // direction. - // - // 1. If there is an ongoing INVITE client transaction, the TU MUST - // wait until the transaction reaches the completed or terminated - // state before initiating the new INVITE. - // - // 2. If there is an ongoing INVITE server transaction, the TU MUST - // wait until the transaction reaches the confirmed or terminated - // state before initiating the new INVITE. - // - // However, a UA MAY initiate a regular transaction while an INVITE - // transaction is in progress. A UA MAY also initiate an INVITE - // transaction while a regular transaction is in progress. - // https://tools.ietf.org/html/rfc3261#section-14.1 - if (this.reinviteUserAgentClient) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("There is an ongoing re-INVITE client transaction."); - } - if (this.reinviteUserAgentServer) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("There is an ongoing re-INVITE server transaction."); - } - return new re_invite_user_agent_client_1.ReInviteUserAgentClient(this, delegate, options); - }; - /** - * The NOTIFY mechanism defined in [2] MUST be used to inform the agent - * sending the REFER of the status of the reference. - * https://tools.ietf.org/html/rfc3515#section-2.4.4 - * @param options - Options bucket. - */ - SessionDialog.prototype.notify = function (delegate, options) { - this.logger.log("INVITE dialog " + this.id + " sending NOTIFY request"); - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("Dialog not confirmed."); - } - return new notify_user_agent_client_1.NotifyUserAgentClient(this, delegate, options); - }; - /** - * Assuming the response is to be transmitted reliably, the UAC MUST - * create a new request with method PRACK. This request is sent within - * the dialog associated with the provisional response (indeed, the - * provisional response may have created the dialog). PRACK requests - * MAY contain bodies, which are interpreted according to their type and - * disposition. - * https://tools.ietf.org/html/rfc3262#section-4 - * @param options - Options bucket. - */ - SessionDialog.prototype.prack = function (delegate, options) { - this.logger.log("INVITE dialog " + this.id + " sending PRACK request"); - return new prack_user_agent_client_1.PrackUserAgentClient(this, delegate, options); - }; - /** - * REFER is a SIP request and is constructed as defined in [1]. A REFER - * request MUST contain exactly one Refer-To header field value. - * https://tools.ietf.org/html/rfc3515#section-2.4.1 - * @param options - Options bucket. - */ - SessionDialog.prototype.refer = function (delegate, options) { - this.logger.log("INVITE dialog " + this.id + " sending REFER request"); - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("Dialog not confirmed."); - } - // FIXME: TODO: Validate Refer-To header field value. - return new refer_user_agent_client_1.ReferUserAgentClient(this, delegate, options); - }; - /** - * Requests sent within a dialog, as any other requests, are atomic. If - * a particular request is accepted by the UAS, all the state changes - * associated with it are performed. If the request is rejected, none - * of the state changes are performed. - * https://tools.ietf.org/html/rfc3261#section-12.2.2 - * @param message - Incoming request message within this dialog. - */ - SessionDialog.prototype.receiveRequest = function (message) { - this.logger.log("INVITE dialog " + this.id + " received " + message.method + " request"); - // Response retransmissions cease when an ACK request for the - // response is received. This is independent of whatever transport - // protocols are used to send the response. - // https://tools.ietf.org/html/rfc6026#section-8.1 - if (message.method === messages_1.C.ACK) { - // If ackWait is true, then this is the ACK to the initial INVITE, - // otherwise this is an ACK to an in dialog INVITE. In either case, - // guard to make sure the sequence number of the ACK matches the INVITE. - if (this.ackWait) { - if (this.initialTransaction instanceof transactions_1.InviteClientTransaction) { - this.logger.warn("INVITE dialog " + this.id + " received unexpected " + message.method + " request, dropping."); - return; - } - if (this.initialTransaction.request.cseq !== message.cseq) { - this.logger.warn("INVITE dialog " + this.id + " received unexpected " + message.method + " request, dropping."); - return; - } - // Update before the delegate has a chance to handle the - // message as delegate may callback into this dialog. - this.ackWait = false; - } - else { - if (!this.reinviteUserAgentServer) { - this.logger.warn("INVITE dialog " + this.id + " received unexpected " + message.method + " request, dropping."); - return; - } - if (this.reinviteUserAgentServer.transaction.request.cseq !== message.cseq) { - this.logger.warn("INVITE dialog " + this.id + " received unexpected " + message.method + " request, dropping."); - return; - } - this.reinviteUserAgentServer = undefined; - } - this.signalingStateTransition(message); - if (this.delegate && this.delegate.onAck) { - this.delegate.onAck({ message: message }); - } - return; - } - // Request within a dialog out of sequence guard. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (!this.sequenceGuard(message)) { - this.logger.log("INVITE dialog " + this.id + " rejected out of order " + message.method + " request."); - return; - } - if (message.method === messages_1.C.INVITE) { - // A UAS that receives a second INVITE before it sends the final - // response to a first INVITE with a lower CSeq sequence number on the - // same dialog MUST return a 500 (Server Internal Error) response to the - // second INVITE and MUST include a Retry-After header field with a - // randomly chosen value of between 0 and 10 seconds. - // https://tools.ietf.org/html/rfc3261#section-14.2 - if (this.reinviteUserAgentServer) { - // https://tools.ietf.org/html/rfc3261#section-20.33 - var retryAfter = Math.floor((Math.random() * 10)) + 1; - var extraHeaders = ["Retry-After: " + retryAfter]; - this.core.replyStateless(message, { statusCode: 500, extraHeaders: extraHeaders }); - return; - } - // A UAS that receives an INVITE on a dialog while an INVITE it had sent - // on that dialog is in progress MUST return a 491 (Request Pending) - // response to the received INVITE. - // https://tools.ietf.org/html/rfc3261#section-14.2 - if (this.reinviteUserAgentClient) { - this.core.replyStateless(message, { statusCode: 491 }); - return; - } - } - // Request within a dialog common processing. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - _super.prototype.receiveRequest.call(this, message); - // Requests within a dialog MAY contain Record-Route and Contact header - // fields. However, these requests do not cause the dialog's route set - // to be modified, although they may modify the remote target URI. - // Specifically, requests that are not target refresh requests do not - // modify the dialog's remote target URI, and requests that are target - // refresh requests do. For dialogs that have been established with an - // INVITE, the only target refresh request defined is re-INVITE (see - // Section 14). Other extensions may define different target refresh - // requests for dialogs established in other ways. - // - // Note that an ACK is NOT a target refresh request. - // - // Target refresh requests only update the dialog's remote target URI, - // and not the route set formed from the Record-Route. Updating the - // latter would introduce severe backwards compatibility problems with - // RFC 2543-compliant systems. - // https://tools.ietf.org/html/rfc3261#section-15 - if (message.method === messages_1.C.INVITE) { - // FIXME: parser needs to be typed... - var contact = message.parseHeader("contact"); - if (!contact) { // TODO: Review to make sure this will never happen - throw new Error("Contact undefined."); - } - if (!(contact instanceof messages_1.NameAddrHeader)) { - throw new Error("Contact not instance of NameAddrHeader."); - } - this.dialogState.remoteTarget = contact.uri; - } - // Switch on method and then delegate. - switch (message.method) { - case messages_1.C.BYE: - // A UAS core receiving a BYE request for an existing dialog MUST follow - // the procedures of Section 12.2.2 to process the request. Once done, - // the UAS SHOULD terminate the session (and therefore stop sending and - // listening for media). The only case where it can elect not to are - // multicast sessions, where participation is possible even if the other - // participant in the dialog has terminated its involvement in the - // session. Whether or not it ends its participation on the session, - // the UAS core MUST generate a 2xx response to the BYE, and MUST pass - // that to the server transaction for transmission. - // - // The UAS MUST still respond to any pending requests received for that - // dialog. It is RECOMMENDED that a 487 (Request Terminated) response - // be generated to those pending requests. - // https://tools.ietf.org/html/rfc3261#section-15.1.2 - { - var uas = new bye_user_agent_server_1.ByeUserAgentServer(this, message); - this.delegate && this.delegate.onBye ? - this.delegate.onBye(uas) : - uas.accept(); - this.dispose(); - } - break; - case messages_1.C.INFO: - // If a UA receives an INFO request associated with an Info Package that - // the UA has not indicated willingness to receive, the UA MUST send a - // 469 (Bad Info Package) response (see Section 11.6), which contains a - // Recv-Info header field with Info Packages for which the UA is willing - // to receive INFO requests. - { - var uas = new info_user_agent_server_1.InfoUserAgentServer(this, message); - this.delegate && this.delegate.onInfo ? - this.delegate.onInfo(uas) : - uas.reject({ - statusCode: 469, - extraHeaders: ["Recv-Info :"] - }); - } - break; - case messages_1.C.INVITE: - // If the new session description is not acceptable, the UAS can reject - // it by returning a 488 (Not Acceptable Here) response for the re- - // INVITE. This response SHOULD include a Warning header field. - // https://tools.ietf.org/html/rfc3261#section-14.2 - { - var uas = new re_invite_user_agent_server_1.ReInviteUserAgentServer(this, message); - this.signalingStateTransition(message); - this.delegate && this.delegate.onInvite ? - this.delegate.onInvite(uas) : - uas.reject({ statusCode: 488 }); // TODO: Warning header field. - } - break; - case messages_1.C.NOTIFY: - // https://tools.ietf.org/html/rfc3515#section-2.4.4 - { - var uas = new notify_user_agent_server_1.NotifyUserAgentServer(this, message); - this.delegate && this.delegate.onNotify ? - this.delegate.onNotify(uas) : - uas.accept(); - } - break; - case messages_1.C.PRACK: - // https://tools.ietf.org/html/rfc3262#section-4 - { - var uas = new prack_user_agent_server_1.PrackUserAgentServer(this, message); - this.delegate && this.delegate.onPrack ? - this.delegate.onPrack(uas) : - uas.accept(); - } - break; - case messages_1.C.REFER: - // https://tools.ietf.org/html/rfc3515#section-2.4.2 - { - var uas = new refer_user_agent_server_1.ReferUserAgentServer(this, message); - this.delegate && this.delegate.onRefer ? - this.delegate.onRefer(uas) : - uas.reject(); - } - break; - default: - { - this.logger.log("INVITE dialog " + this.id + " received unimplemented " + message.method + " request"); - this.core.replyStateless(message, { statusCode: 501 }); - } - break; - } - }; - SessionDialog.prototype.reliableSequenceGuard = function (message) { - var statusCode = message.statusCode; - if (!statusCode) { - throw new Error("Status code undefined"); - } - if (statusCode > 100 && statusCode < 200) { - // If a provisional response is received for an initial request, and - // that response contains a Require header field containing the option - // tag 100rel, the response is to be sent reliably. If the response is - // a 100 (Trying) (as opposed to 101 to 199), this option tag MUST be - // ignored, and the procedures below MUST NOT be used. - // https://tools.ietf.org/html/rfc3262#section-4 - var requireHeader = message.getHeader("require"); - var rseqHeader = message.getHeader("rseq"); - var rseq = requireHeader && requireHeader.includes("100rel") && rseqHeader ? Number(rseqHeader) : undefined; - if (rseq) { - // Handling of subsequent reliable provisional responses for the same - // initial request follows the same rules as above, with the following - // difference: reliable provisional responses are guaranteed to be in - // order. As a result, if the UAC receives another reliable provisional - // response to the same request, and its RSeq value is not one higher - // than the value of the sequence number, that response MUST NOT be - // acknowledged with a PRACK, and MUST NOT be processed further by the - // UAC. An implementation MAY discard the response, or MAY cache the - // response in the hopes of receiving the missing responses. - // https://tools.ietf.org/html/rfc3262#section-4 - if (this.rseq && this.rseq + 1 !== rseq) { - return false; - } - // Once a reliable provisional response is received, retransmissions of - // that response MUST be discarded. A response is a retransmission when - // its dialog ID, CSeq, and RSeq match the original response. The UAC - // MUST maintain a sequence number that indicates the most recently - // received in-order reliable provisional response for the initial - // request. This sequence number MUST be maintained until a final - // response is received for the initial request. Its value MUST be - // initialized to the RSeq header field in the first reliable - // provisional response received for the initial request. - // https://tools.ietf.org/html/rfc3262#section-4 - if (!this.rseq) { - this.rseq = rseq; - } - } - } - return true; - }; - /** - * If not in a stable signaling state, rollback to prior stable signaling state. - */ - SessionDialog.prototype.signalingStateRollback = function () { - if (this._signalingState === session_1.SignalingState.HaveLocalOffer || - this.signalingState === session_1.SignalingState.HaveRemoteOffer) { - if (this._rollbackOffer && this._rollbackAnswer) { - this._signalingState = session_1.SignalingState.Stable; - this._offer = this._rollbackOffer; - this._answer = this._rollbackAnswer; - } - } - }; - /** - * Update the signaling state of the dialog. - * @param message - The message to base the update off of. - */ - SessionDialog.prototype.signalingStateTransition = function (message) { - var body = messages_1.getBody(message); - // No body, no session. No, woman, no cry. - if (!body || body.contentDisposition !== "session") { - return; - } - // We've got an existing offer and answer which we may wish to rollback to - if (this._signalingState === session_1.SignalingState.Stable) { - this._rollbackOffer = this._offer; - this._rollbackAnswer = this._answer; - } - // We're in UAS role, receiving incoming request with session description - if (message instanceof messages_1.IncomingRequestMessage) { - switch (this._signalingState) { - case session_1.SignalingState.Initial: - case session_1.SignalingState.Stable: - this._signalingState = session_1.SignalingState.HaveRemoteOffer; - this._offer = body; - this._answer = undefined; - break; - case session_1.SignalingState.HaveLocalOffer: - this._signalingState = session_1.SignalingState.Stable; - this._answer = body; - break; - case session_1.SignalingState.HaveRemoteOffer: - // You cannot make a new offer while one is in progress. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // FIXME: What to do here? - break; - case session_1.SignalingState.Closed: - break; - default: - throw new Error("Unexpected signaling state."); - } - } - // We're in UAC role, receiving incoming response with session description - if (message instanceof messages_1.IncomingResponseMessage) { - switch (this._signalingState) { - case session_1.SignalingState.Initial: - case session_1.SignalingState.Stable: - this._signalingState = session_1.SignalingState.HaveRemoteOffer; - this._offer = body; - this._answer = undefined; - break; - case session_1.SignalingState.HaveLocalOffer: - this._signalingState = session_1.SignalingState.Stable; - this._answer = body; - break; - case session_1.SignalingState.HaveRemoteOffer: - // You cannot make a new offer while one is in progress. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // FIXME: What to do here? - break; - case session_1.SignalingState.Closed: - break; - default: - throw new Error("Unexpected signaling state."); - } - } - // We're in UAC role, sending outgoing request with session description - if (message instanceof messages_1.OutgoingRequestMessage) { - switch (this._signalingState) { - case session_1.SignalingState.Initial: - case session_1.SignalingState.Stable: - this._signalingState = session_1.SignalingState.HaveLocalOffer; - this._offer = body; - this._answer = undefined; - break; - case session_1.SignalingState.HaveLocalOffer: - // You cannot make a new offer while one is in progress. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // FIXME: What to do here? - break; - case session_1.SignalingState.HaveRemoteOffer: - this._signalingState = session_1.SignalingState.Stable; - this._answer = body; - break; - case session_1.SignalingState.Closed: - break; - default: - throw new Error("Unexpected signaling state."); - } - } - // We're in UAS role, sending outgoing response with session description - if (messages_1.isBody(message)) { - switch (this._signalingState) { - case session_1.SignalingState.Initial: - case session_1.SignalingState.Stable: - this._signalingState = session_1.SignalingState.HaveLocalOffer; - this._offer = body; - this._answer = undefined; - break; - case session_1.SignalingState.HaveLocalOffer: - // You cannot make a new offer while one is in progress. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // FIXME: What to do here? - break; - case session_1.SignalingState.HaveRemoteOffer: - this._signalingState = session_1.SignalingState.Stable; - this._answer = body; - break; - case session_1.SignalingState.Closed: - break; - default: - throw new Error("Unexpected signaling state."); - } - } - }; - SessionDialog.prototype.start2xxRetransmissionTimer = function () { - var _this = this; - if (this.initialTransaction instanceof transactions_1.InviteServerTransaction) { - var transaction_1 = this.initialTransaction; - // Once the response has been constructed, it is passed to the INVITE - // server transaction. In order to ensure reliable end-to-end - // transport of the response, it is necessary to periodically pass - // the response directly to the transport until the ACK arrives. The - // 2xx response is passed to the transport with an interval that - // starts at T1 seconds and doubles for each retransmission until it - // reaches T2 seconds (T1 and T2 are defined in Section 17). - // Response retransmissions cease when an ACK request for the - // response is received. This is independent of whatever transport - // protocols are used to send the response. - // https://tools.ietf.org/html/rfc6026#section-8.1 - var timeout_1 = timers_1.Timers.T1; - var retransmission_1 = function () { - if (!_this.ackWait) { - _this.invite2xxTimer = undefined; - return; - } - _this.logger.log("No ACK for 2xx response received, attempting retransmission"); - transaction_1.retransmitAcceptedResponse(); - timeout_1 = Math.min(timeout_1 * 2, timers_1.Timers.T2); - _this.invite2xxTimer = setTimeout(retransmission_1, timeout_1); - }; - this.invite2xxTimer = setTimeout(retransmission_1, timeout_1); - // If the server retransmits the 2xx response for 64*T1 seconds without - // receiving an ACK, the dialog is confirmed, but the session SHOULD be - // terminated. This is accomplished with a BYE, as described in Section 15. - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - var stateChanged_1 = function () { - if (transaction_1.state === transactions_1.TransactionState.Terminated) { - transaction_1.removeListener("stateChanged", stateChanged_1); - if (_this.invite2xxTimer) { - clearTimeout(_this.invite2xxTimer); - _this.invite2xxTimer = undefined; - } - if (_this.ackWait) { - if (_this.delegate && _this.delegate.onAckTimeout) { - _this.delegate.onAckTimeout(); - } - else { - _this.bye(); - } - } - } - }; - transaction_1.addListener("stateChanged", stateChanged_1); - } - }; - // FIXME: Refactor - SessionDialog.prototype.startReInvite2xxRetransmissionTimer = function () { - var _this = this; - if (this.reinviteUserAgentServer && this.reinviteUserAgentServer.transaction instanceof transactions_1.InviteServerTransaction) { - var transaction_2 = this.reinviteUserAgentServer.transaction; - // Once the response has been constructed, it is passed to the INVITE - // server transaction. In order to ensure reliable end-to-end - // transport of the response, it is necessary to periodically pass - // the response directly to the transport until the ACK arrives. The - // 2xx response is passed to the transport with an interval that - // starts at T1 seconds and doubles for each retransmission until it - // reaches T2 seconds (T1 and T2 are defined in Section 17). - // Response retransmissions cease when an ACK request for the - // response is received. This is independent of whatever transport - // protocols are used to send the response. - // https://tools.ietf.org/html/rfc6026#section-8.1 - var timeout_2 = timers_1.Timers.T1; - var retransmission_2 = function () { - if (!_this.reinviteUserAgentServer) { - _this.invite2xxTimer = undefined; - return; - } - _this.logger.log("No ACK for 2xx response received, attempting retransmission"); - transaction_2.retransmitAcceptedResponse(); - timeout_2 = Math.min(timeout_2 * 2, timers_1.Timers.T2); - _this.invite2xxTimer = setTimeout(retransmission_2, timeout_2); - }; - this.invite2xxTimer = setTimeout(retransmission_2, timeout_2); - // If the server retransmits the 2xx response for 64*T1 seconds without - // receiving an ACK, the dialog is confirmed, but the session SHOULD be - // terminated. This is accomplished with a BYE, as described in Section 15. - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - var stateChanged_2 = function () { - if (transaction_2.state === transactions_1.TransactionState.Terminated) { - transaction_2.removeListener("stateChanged", stateChanged_2); - if (_this.invite2xxTimer) { - clearTimeout(_this.invite2xxTimer); - _this.invite2xxTimer = undefined; - } - if (_this.reinviteUserAgentServer) { - // FIXME: TODO: What to do here - } - } - }; - transaction_2.addListener("stateChanged", stateChanged_2); - } - }; - return SessionDialog; -}(dialog_1.Dialog)); -exports.SessionDialog = SessionDialog; - - -/***/ }), -/* 24 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -tslib_1.__exportStar(__webpack_require__(25), exports); - - -/***/ }), -/* 25 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * Session state. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-13 - * @public - */ -var SessionState; -(function (SessionState) { - SessionState["Initial"] = "Initial"; - SessionState["Early"] = "Early"; - SessionState["AckWait"] = "AckWait"; - SessionState["Confirmed"] = "Confirmed"; - SessionState["Terminated"] = "Terminated"; -})(SessionState = exports.SessionState || (exports.SessionState = {})); -/** - * Offer/Answer state. - * @remarks - * ```txt - * Offer Answer RFC Ini Est Early - * ------------------------------------------------------------------- - * 1. INVITE Req. 2xx INVITE Resp. RFC 3261 Y Y N - * 2. 2xx INVITE Resp. ACK Req. RFC 3261 Y Y N - * 3. INVITE Req. 1xx-rel INVITE Resp. RFC 3262 Y Y N - * 4. 1xx-rel INVITE Resp. PRACK Req. RFC 3262 Y Y N - * 5. PRACK Req. 200 PRACK Resp. RFC 3262 N Y Y - * 6. UPDATE Req. 2xx UPDATE Resp. RFC 3311 N Y Y - * - * Table 1: Summary of SIP Usage of the Offer/Answer Model - * ``` - * https://tools.ietf.org/html/rfc6337#section-2.2 - * @public - */ -var SignalingState; -(function (SignalingState) { - SignalingState["Initial"] = "Initial"; - SignalingState["HaveLocalOffer"] = "HaveLocalOffer"; - SignalingState["HaveRemoteOffer"] = "HaveRemoteOffer"; - SignalingState["Stable"] = "Stable"; - SignalingState["Closed"] = "Closed"; -})(SignalingState = exports.SignalingState || (exports.SignalingState = {})); - - -/***/ }), -/* 26 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var T1 = 500; -var T2 = 4000; -var T4 = 5000; -/** - * Timers. - * @public - */ -exports.Timers = { - T1: T1, - T2: T2, - T4: T4, - TIMER_B: 64 * T1, - TIMER_D: 0 * T1, - TIMER_F: 64 * T1, - TIMER_H: 64 * T1, - TIMER_I: 0 * T4, - TIMER_J: 0 * T1, - TIMER_K: 0 * T4, - TIMER_L: 64 * T1, - TIMER_M: 64 * T1, - TIMER_N: 64 * T1, - PROVISIONAL_RESPONSE_INTERVAL: 60000 // See RFC 3261 Section 13.3.1.1 -}; - - -/***/ }), -/* 27 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -tslib_1.__exportStar(__webpack_require__(28), exports); -tslib_1.__exportStar(__webpack_require__(35), exports); -tslib_1.__exportStar(__webpack_require__(37), exports); -tslib_1.__exportStar(__webpack_require__(39), exports); -tslib_1.__exportStar(__webpack_require__(40), exports); -tslib_1.__exportStar(__webpack_require__(35), exports); -tslib_1.__exportStar(__webpack_require__(38), exports); -tslib_1.__exportStar(__webpack_require__(36), exports); -tslib_1.__exportStar(__webpack_require__(29), exports); - - -/***/ }), -/* 28 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transaction_1 = __webpack_require__(29); -/** - * Client Transaction. - * @remarks - * The client transaction provides its functionality through the - * maintenance of a state machine. - * - * The TU communicates with the client transaction through a simple - * interface. When the TU wishes to initiate a new transaction, it - * creates a client transaction and passes it the SIP request to send - * and an IP address, port, and transport to which to send it. The - * client transaction begins execution of its state machine. Valid - * responses are passed up to the TU from the client transaction. - * https://tools.ietf.org/html/rfc3261#section-17.1 - * @public - */ -var ClientTransaction = /** @class */ (function (_super) { - tslib_1.__extends(ClientTransaction, _super); - function ClientTransaction(_request, transport, user, state, loggerCategory) { - var _this = _super.call(this, transport, user, ClientTransaction.makeId(_request), state, loggerCategory) || this; - _this._request = _request; - _this.user = user; - // The Via header field indicates the transport used for the transaction - // and identifies the location where the response is to be sent. A Via - // header field value is added only after the transport that will be - // used to reach the next hop has been selected (which may involve the - // usage of the procedures in [4]). - // https://tools.ietf.org/html/rfc3261#section-8.1.1.7 - // FIXME: Transport's server property is not typed (as of writing this). - var scheme = transport.server && transport.server.scheme ? transport.server.scheme : undefined; - _request.setViaHeader(_this.id, scheme); - return _this; - } - ClientTransaction.makeId = function (request) { - if (request.method === "CANCEL") { - if (!request.branch) { - throw new Error("Outgoing CANCEL request without a branch."); - } - return request.branch; - } - else { - return "z9hG4bK" + Math.floor(Math.random() * 10000000); - } - }; - Object.defineProperty(ClientTransaction.prototype, "request", { - /** The outgoing request the transaction handling. */ - get: function () { - return this._request; - }, - enumerable: true, - configurable: true - }); - /** - * A 408 to non-INVITE will always arrive too late to be useful ([3]), - * The client already has full knowledge of the timeout. The only - * information this message would convey is whether or not the server - * believed the transaction timed out. However, with the current design - * of the NIT, a client cannot do anything with this knowledge. Thus, - * the 408 is simply wasting network resources and contributes to the - * response bombardment illustrated in [3]. - * https://tools.ietf.org/html/rfc4320#section-4.1 - */ - ClientTransaction.prototype.onRequestTimeout = function () { - if (this.user.onRequestTimeout) { - this.user.onRequestTimeout(); - } - }; - return ClientTransaction; -}(transaction_1.Transaction)); -exports.ClientTransaction = ClientTransaction; - - -/***/ }), -/* 29 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var events_1 = __webpack_require__(30); -var exceptions_1 = __webpack_require__(31); -/** - * Transaction. - * @remarks - * SIP is a transactional protocol: interactions between components take - * place in a series of independent message exchanges. Specifically, a - * SIP transaction consists of a single request and any responses to - * that request, which include zero or more provisional responses and - * one or more final responses. In the case of a transaction where the - * request was an INVITE (known as an INVITE transaction), the - * transaction also includes the ACK only if the final response was not - * a 2xx response. If the response was a 2xx, the ACK is not considered - * part of the transaction. - * https://tools.ietf.org/html/rfc3261#section-17 - * @public - */ -var Transaction = /** @class */ (function (_super) { - tslib_1.__extends(Transaction, _super); - function Transaction(_transport, _user, _id, _state, loggerCategory) { - var _this = _super.call(this) || this; - _this._transport = _transport; - _this._user = _user; - _this._id = _id; - _this._state = _state; - _this.logger = _user.loggerFactory.getLogger(loggerCategory, _id); - _this.logger.debug("Constructing " + _this.typeToString() + " with id " + _this.id + "."); - return _this; - } - /** - * Destructor. - * Once the transaction is in the "terminated" state, it is destroyed - * immediately and there is no need to call `dispose`. However, if a - * transaction needs to be ended prematurely, the transaction user may - * do so by calling this method (for example, perhaps the UA is shutting down). - * No state transition will occur upon calling this method, all outstanding - * transmission timers will be cancelled, and use of the transaction after - * calling `dispose` is undefined. - */ - Transaction.prototype.dispose = function () { - this.logger.debug("Destroyed " + this.typeToString() + " with id " + this.id + "."); - }; - Object.defineProperty(Transaction.prototype, "id", { - /** Transaction id. */ - get: function () { - return this._id; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Transaction.prototype, "kind", { - /** Transaction kind. Deprecated. */ - get: function () { - throw new Error("Invalid kind."); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Transaction.prototype, "state", { - /** Transaction state. */ - get: function () { - return this._state; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Transaction.prototype, "transport", { - /** Transaction transport. */ - get: function () { - return this._transport; - }, - enumerable: true, - configurable: true - }); - Transaction.prototype.on = function (name, callback) { return _super.prototype.on.call(this, name, callback); }; - Transaction.prototype.logTransportError = function (error, message) { - this.logger.error(error.message); - this.logger.error("Transport error occurred in " + this.typeToString() + " with id " + this.id + "."); - this.logger.error(message); - }; - /** - * Pass message to transport for transmission. If transport fails, - * the transaction user is notified by callback to onTransportError(). - * @returns - * Rejects with `TransportError` if transport fails. - */ - Transaction.prototype.send = function (message) { - var _this = this; - return this.transport.send(message).catch(function (error) { - // FIXME: Transport is not, yet, typed and it is not clear - // yet what send() may or may not send our way. So for now, - // make sure we convert it to a TransportError if need be. - if (error instanceof exceptions_1.TransportError) { - _this.onTransportError(error); - return; - } - var transportError; - if (error && typeof error.message === "string") { - transportError = new exceptions_1.TransportError(error.message); - } - else { - transportError = new exceptions_1.TransportError(); - } - _this.onTransportError(transportError); - throw transportError; - }); - }; - Transaction.prototype.setState = function (state) { - this.logger.debug("State change to \"" + state + "\" on " + this.typeToString() + " with id " + this.id + "."); - this._state = state; - if (this._user.onStateChange) { - this._user.onStateChange(state); - } - this.emit("stateChanged"); - }; - Transaction.prototype.typeToString = function () { - return "UnknownType"; - }; - return Transaction; -}(events_1.EventEmitter)); -exports.Transaction = Transaction; - - -/***/ }), -/* 30 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - -var R = typeof Reflect === 'object' ? Reflect : null -var ReflectApply = R && typeof R.apply === 'function' - ? R.apply - : function ReflectApply(target, receiver, args) { - return Function.prototype.apply.call(target, receiver, args); - } - -var ReflectOwnKeys -if (R && typeof R.ownKeys === 'function') { - ReflectOwnKeys = R.ownKeys -} else if (Object.getOwnPropertySymbols) { - ReflectOwnKeys = function ReflectOwnKeys(target) { - return Object.getOwnPropertyNames(target) - .concat(Object.getOwnPropertySymbols(target)); - }; -} else { - ReflectOwnKeys = function ReflectOwnKeys(target) { - return Object.getOwnPropertyNames(target); - }; -} - -function ProcessEmitWarning(warning) { - if (console && console.warn) console.warn(warning); -} - -var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { - return value !== value; -} - -function EventEmitter() { - EventEmitter.init.call(this); -} -module.exports = EventEmitter; - -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; - -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._eventsCount = 0; -EventEmitter.prototype._maxListeners = undefined; - -// By default EventEmitters will print a warning if more than 10 listeners are -// added to it. This is a useful default which helps finding memory leaks. -var defaultMaxListeners = 10; - -Object.defineProperty(EventEmitter, 'defaultMaxListeners', { - enumerable: true, - get: function() { - return defaultMaxListeners; - }, - set: function(arg) { - if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { - throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); - } - defaultMaxListeners = arg; - } -}); - -EventEmitter.init = function() { - - if (this._events === undefined || - this._events === Object.getPrototypeOf(this)._events) { - this._events = Object.create(null); - this._eventsCount = 0; - } - - this._maxListeners = this._maxListeners || undefined; -}; - -// Obviously not all Emitters should be limited to 10. This function allows -// that to be increased. Set to zero for unlimited. -EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { - if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { - throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); - } - this._maxListeners = n; - return this; -}; - -function $getMaxListeners(that) { - if (that._maxListeners === undefined) - return EventEmitter.defaultMaxListeners; - return that._maxListeners; -} - -EventEmitter.prototype.getMaxListeners = function getMaxListeners() { - return $getMaxListeners(this); -}; - -EventEmitter.prototype.emit = function emit(type) { - var args = []; - for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); - var doError = (type === 'error'); - - var events = this._events; - if (events !== undefined) - doError = (doError && events.error === undefined); - else if (!doError) - return false; - - // If there is no 'error' event listener then throw. - if (doError) { - var er; - if (args.length > 0) - er = args[0]; - if (er instanceof Error) { - // Note: The comments on the `throw` lines are intentional, they show - // up in Node's output if this results in an unhandled exception. - throw er; // Unhandled 'error' event - } - // At least give some kind of context to the user - var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); - err.context = er; - throw err; // Unhandled 'error' event - } - - var handler = events[type]; - - if (handler === undefined) - return false; - - if (typeof handler === 'function') { - ReflectApply(handler, this, args); - } else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - ReflectApply(listeners[i], this, args); - } - - return true; -}; - -function _addListener(target, type, listener, prepend) { - var m; - var events; - var existing; - - if (typeof listener !== 'function') { - throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); - } - - events = target._events; - if (events === undefined) { - events = target._events = Object.create(null); - target._eventsCount = 0; - } else { - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (events.newListener !== undefined) { - target.emit('newListener', type, - listener.listener ? listener.listener : listener); - - // Re-assign `events` because a newListener handler could have caused the - // this._events to be assigned to a new object - events = target._events; - } - existing = events[type]; - } - - if (existing === undefined) { - // Optimize the case of one listener. Don't need the extra array object. - existing = events[type] = listener; - ++target._eventsCount; - } else { - if (typeof existing === 'function') { - // Adding the second element, need to change to array. - existing = events[type] = - prepend ? [listener, existing] : [existing, listener]; - // If we've already got an array, just append. - } else if (prepend) { - existing.unshift(listener); - } else { - existing.push(listener); - } - - // Check for listener leak - m = $getMaxListeners(target); - if (m > 0 && existing.length > m && !existing.warned) { - existing.warned = true; - // No error code for this since it is a Warning - // eslint-disable-next-line no-restricted-syntax - var w = new Error('Possible EventEmitter memory leak detected. ' + - existing.length + ' ' + String(type) + ' listeners ' + - 'added. Use emitter.setMaxListeners() to ' + - 'increase limit'); - w.name = 'MaxListenersExceededWarning'; - w.emitter = target; - w.type = type; - w.count = existing.length; - ProcessEmitWarning(w); - } - } - - return target; -} - -EventEmitter.prototype.addListener = function addListener(type, listener) { - return _addListener(this, type, listener, false); -}; - -EventEmitter.prototype.on = EventEmitter.prototype.addListener; - -EventEmitter.prototype.prependListener = - function prependListener(type, listener) { - return _addListener(this, type, listener, true); - }; - -function onceWrapper() { - var args = []; - for (var i = 0; i < arguments.length; i++) args.push(arguments[i]); - if (!this.fired) { - this.target.removeListener(this.type, this.wrapFn); - this.fired = true; - ReflectApply(this.listener, this.target, args); - } -} - -function _onceWrap(target, type, listener) { - var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; - var wrapped = onceWrapper.bind(state); - wrapped.listener = listener; - state.wrapFn = wrapped; - return wrapped; -} - -EventEmitter.prototype.once = function once(type, listener) { - if (typeof listener !== 'function') { - throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); - } - this.on(type, _onceWrap(this, type, listener)); - return this; -}; - -EventEmitter.prototype.prependOnceListener = - function prependOnceListener(type, listener) { - if (typeof listener !== 'function') { - throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); - } - this.prependListener(type, _onceWrap(this, type, listener)); - return this; - }; - -// Emits a 'removeListener' event if and only if the listener was removed. -EventEmitter.prototype.removeListener = - function removeListener(type, listener) { - var list, events, position, i, originalListener; - - if (typeof listener !== 'function') { - throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); - } - - events = this._events; - if (events === undefined) - return this; - - list = events[type]; - if (list === undefined) - return this; - - if (list === listener || list.listener === listener) { - if (--this._eventsCount === 0) - this._events = Object.create(null); - else { - delete events[type]; - if (events.removeListener) - this.emit('removeListener', type, list.listener || listener); - } - } else if (typeof list !== 'function') { - position = -1; - - for (i = list.length - 1; i >= 0; i--) { - if (list[i] === listener || list[i].listener === listener) { - originalListener = list[i].listener; - position = i; - break; - } - } - - if (position < 0) - return this; - - if (position === 0) - list.shift(); - else { - spliceOne(list, position); - } - - if (list.length === 1) - events[type] = list[0]; - - if (events.removeListener !== undefined) - this.emit('removeListener', type, originalListener || listener); - } - - return this; - }; - -EventEmitter.prototype.off = EventEmitter.prototype.removeListener; - -EventEmitter.prototype.removeAllListeners = - function removeAllListeners(type) { - var listeners, events, i; - - events = this._events; - if (events === undefined) - return this; - - // not listening for removeListener, no need to emit - if (events.removeListener === undefined) { - if (arguments.length === 0) { - this._events = Object.create(null); - this._eventsCount = 0; - } else if (events[type] !== undefined) { - if (--this._eventsCount === 0) - this._events = Object.create(null); - else - delete events[type]; - } - return this; - } - - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - var keys = Object.keys(events); - var key; - for (i = 0; i < keys.length; ++i) { - key = keys[i]; - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = Object.create(null); - this._eventsCount = 0; - return this; - } - - listeners = events[type]; - - if (typeof listeners === 'function') { - this.removeListener(type, listeners); - } else if (listeners !== undefined) { - // LIFO order - for (i = listeners.length - 1; i >= 0; i--) { - this.removeListener(type, listeners[i]); - } - } - - return this; - }; - -function _listeners(target, type, unwrap) { - var events = target._events; - - if (events === undefined) - return []; - - var evlistener = events[type]; - if (evlistener === undefined) - return []; - - if (typeof evlistener === 'function') - return unwrap ? [evlistener.listener || evlistener] : [evlistener]; - - return unwrap ? - unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); -} - -EventEmitter.prototype.listeners = function listeners(type) { - return _listeners(this, type, true); -}; - -EventEmitter.prototype.rawListeners = function rawListeners(type) { - return _listeners(this, type, false); -}; - -EventEmitter.listenerCount = function(emitter, type) { - if (typeof emitter.listenerCount === 'function') { - return emitter.listenerCount(type); - } else { - return listenerCount.call(emitter, type); - } -}; - -EventEmitter.prototype.listenerCount = listenerCount; -function listenerCount(type) { - var events = this._events; - - if (events !== undefined) { - var evlistener = events[type]; - - if (typeof evlistener === 'function') { - return 1; - } else if (evlistener !== undefined) { - return evlistener.length; - } - } - - return 0; -} - -EventEmitter.prototype.eventNames = function eventNames() { - return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; -}; - -function arrayClone(arr, n) { - var copy = new Array(n); - for (var i = 0; i < n; ++i) - copy[i] = arr[i]; - return copy; -} - -function spliceOne(list, index) { - for (; index + 1 < list.length; index++) - list[index] = list[index + 1]; - list.pop(); -} - -function unwrapListeners(arr) { - var ret = new Array(arr.length); - for (var i = 0; i < ret.length; ++i) { - ret[i] = arr[i].listener || arr[i]; - } - return ret; -} - - -/***/ }), -/* 31 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -tslib_1.__exportStar(__webpack_require__(32), exports); -tslib_1.__exportStar(__webpack_require__(33), exports); -tslib_1.__exportStar(__webpack_require__(34), exports); - - -/***/ }), -/* 32 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -/** - * An Exception is considered a condition that a reasonable application may wish to catch. - * An Error indicates serious problems that a reasonable application should not try to catch. - * @public - */ -var Exception = /** @class */ (function (_super) { - tslib_1.__extends(Exception, _super); - function Exception(message) { - var _newTarget = this.constructor; - var _this = _super.call(this, message) || this; - Object.setPrototypeOf(_this, _newTarget.prototype); // restore prototype chain - return _this; - } - return Exception; -}(Error)); -exports.Exception = Exception; - - -/***/ }), -/* 33 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var exception_1 = __webpack_require__(32); -/** - * Indicates that the operation could not be completed given the current transaction state. - * @public - */ -var TransactionStateError = /** @class */ (function (_super) { - tslib_1.__extends(TransactionStateError, _super); - function TransactionStateError(message) { - return _super.call(this, message ? message : "Transaction state error.") || this; - } - return TransactionStateError; -}(exception_1.Exception)); -exports.TransactionStateError = TransactionStateError; - - -/***/ }), -/* 34 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var exception_1 = __webpack_require__(32); -/** - * Transport error. - * @public - */ -var TransportError = /** @class */ (function (_super) { - tslib_1.__extends(TransportError, _super); - function TransportError(message) { - return _super.call(this, message ? message : "Unspecified transport error.") || this; - } - return TransportError; -}(exception_1.Exception)); -exports.TransportError = TransportError; - - -/***/ }), -/* 35 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var timers_1 = __webpack_require__(26); -var client_transaction_1 = __webpack_require__(28); -var transaction_state_1 = __webpack_require__(36); -/** - * INVITE Client Transaction. - * @remarks - * The INVITE transaction consists of a three-way handshake. The client - * transaction sends an INVITE, the server transaction sends responses, - * and the client transaction sends an ACK. - * https://tools.ietf.org/html/rfc3261#section-17.1.1 - * @public - */ -var InviteClientTransaction = /** @class */ (function (_super) { - tslib_1.__extends(InviteClientTransaction, _super); - /** - * Constructor. - * Upon construction, the outgoing request's Via header is updated by calling `setViaHeader`. - * Then `toString` is called on the outgoing request and the message is sent via the transport. - * After construction the transaction will be in the "calling" state and the transaction id - * will equal the branch parameter set in the Via header of the outgoing request. - * https://tools.ietf.org/html/rfc3261#section-17.1.1 - * @param request - The outgoing INVITE request. - * @param transport - The transport. - * @param user - The transaction user. - */ - function InviteClientTransaction(request, transport, user) { - var _this = _super.call(this, request, transport, user, transaction_state_1.TransactionState.Calling, "sip.transaction.ict") || this; - /** - * Map of 2xx to-tag to ACK. - * If value is not undefined, value is the ACK which was sent. - * If key exists but value is undefined, a 2xx was received but the ACK not yet sent. - * Otherwise, a 2xx was not (yet) received for this transaction. - */ - _this.ackRetransmissionCache = new Map(); - // FIXME: Timer A for unreliable transport not implemented - // - // If an unreliable transport is being used, the client transaction - // MUST start timer A with a value of T1. If a reliable transport is being used, - // the client transaction SHOULD NOT start timer A (Timer A controls request retransmissions). - // For any transport, the client transaction MUST start timer B with a value - // of 64*T1 seconds (Timer B controls transaction timeouts). - // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - // - // While not spelled out in the RFC, Timer B is the maximum amount of time that a sender - // will wait for an INVITE message to be acknowledged (a SIP response message is received). - // So Timer B should be cleared when the transaction state proceeds from "Calling". - _this.B = setTimeout(function () { return _this.timer_B(); }, timers_1.Timers.TIMER_B); - _this.send(request.toString()).catch(function (error) { - _this.logTransportError(error, "Failed to send initial outgoing request."); - }); - return _this; - } - /** - * Destructor. - */ - InviteClientTransaction.prototype.dispose = function () { - if (this.B) { - clearTimeout(this.B); - this.B = undefined; - } - if (this.D) { - clearTimeout(this.D); - this.D = undefined; - } - if (this.M) { - clearTimeout(this.M); - this.M = undefined; - } - _super.prototype.dispose.call(this); - }; - Object.defineProperty(InviteClientTransaction.prototype, "kind", { - /** Transaction kind. Deprecated. */ - get: function () { - return "ict"; - }, - enumerable: true, - configurable: true - }); - /** - * ACK a 2xx final response. - * - * The transaction includes the ACK only if the final response was not a 2xx response (the - * transaction will generate and send the ACK to the transport automagically). If the - * final response was a 2xx, the ACK is not considered part of the transaction (the - * transaction user needs to generate and send the ACK). - * - * This library is not strictly RFC compliant with regard to ACK handling for 2xx final - * responses. Specifically, retransmissions of ACKs to a 2xx final responses is handled - * by the transaction layer (instead of the UAC core). The "standard" approach is for - * the UAC core to receive all 2xx responses and manage sending ACK retransmissions to - * the transport directly. Herein the transaction layer manages sending ACKs to 2xx responses - * and any retransmissions of those ACKs as needed. - * - * @param ack - The outgoing ACK request. - */ - InviteClientTransaction.prototype.ackResponse = function (ack) { - var _this = this; - var toTag = ack.toTag; - if (!toTag) { - throw new Error("To tag undefined."); - } - var id = "z9hG4bK" + Math.floor(Math.random() * 10000000); - // FIXME: Transport's server property is not typed (as of writing this). - var scheme = this.transport.server && this.transport.server.scheme ? this.transport.server.scheme : undefined; - ack.setViaHeader(id, scheme); - this.ackRetransmissionCache.set(toTag, ack); // Add to ACK retransmission cache - this.send(ack.toString()).catch(function (error) { - _this.logTransportError(error, "Failed to send ACK to 2xx response."); - }); - }; - /** - * Handler for incoming responses from the transport which match this transaction. - * @param response - The incoming response. - */ - InviteClientTransaction.prototype.receiveResponse = function (response) { - var _this = this; - var statusCode = response.statusCode; - if (!statusCode || statusCode < 100 || statusCode > 699) { - throw new Error("Invalid status code " + statusCode); - } - switch (this.state) { - case transaction_state_1.TransactionState.Calling: - // If the client transaction receives a provisional response while in - // the "Calling" state, it transitions to the "Proceeding" state. In the - // "Proceeding" state, the client transaction SHOULD NOT retransmit the - // request any longer. Furthermore, the provisional response MUST be - // passed to the TU. Any further provisional responses MUST be passed - // up to the TU while in the "Proceeding" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - if (statusCode >= 100 && statusCode <= 199) { - this.stateTransition(transaction_state_1.TransactionState.Proceeding); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // When a 2xx response is received while in either the "Calling" or - // "Proceeding" states, the client transaction MUST transition to - // the "Accepted" state... The 2xx response MUST be passed up to the TU. - // The client transaction MUST NOT generate an ACK to the 2xx response -- its - // handling is delegated to the TU. A UAC core will send an ACK to - // the 2xx response using a new transaction. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 200 && statusCode <= 299) { - this.ackRetransmissionCache.set(response.toTag, undefined); // Prime the ACK cache - this.stateTransition(transaction_state_1.TransactionState.Accepted); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // When in either the "Calling" or "Proceeding" states, reception of - // a response with status code from 300-699 MUST cause the client - // transaction to transition to "Completed". The client transaction - // MUST pass the received response up to the TU, and the client - // transaction MUST generate an ACK request, even if the transport is - // reliable (guidelines for constructing the ACK from the response - // are given in Section 17.1.1.3), and then pass the ACK to the - // transport layer for transmission. The ACK MUST be sent to the - // same address, port, and transport to which the original request was sent. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 300 && statusCode <= 699) { - this.stateTransition(transaction_state_1.TransactionState.Completed); - this.ack(response); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - break; - case transaction_state_1.TransactionState.Proceeding: - // In the "Proceeding" state, the client transaction SHOULD NOT retransmit the - // request any longer. Furthermore, the provisional response MUST be - // passed to the TU. Any further provisional responses MUST be passed - // up to the TU while in the "Proceeding" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - if (statusCode >= 100 && statusCode <= 199) { - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // When a 2xx response is received while in either the "Calling" or "Proceeding" states, - // the client transaction MUST transition to the "Accepted" state... - // The 2xx response MUST be passed up to the TU. The client - // transaction MUST NOT generate an ACK to the 2xx response -- its - // handling is delegated to the TU. A UAC core will send an ACK to - // the 2xx response using a new transaction. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 200 && statusCode <= 299) { - this.ackRetransmissionCache.set(response.toTag, undefined); // Prime the ACK cache - this.stateTransition(transaction_state_1.TransactionState.Accepted); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // When in either the "Calling" or "Proceeding" states, reception of - // a response with status code from 300-699 MUST cause the client - // transaction to transition to "Completed". The client transaction - // MUST pass the received response up to the TU, and the client - // transaction MUST generate an ACK request, even if the transport is - // reliable (guidelines for constructing the ACK from the response - // are given in Section 17.1.1.3), and then pass the ACK to the - // transport layer for transmission. The ACK MUST be sent to the - // same address, port, and transport to which the original request was sent. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 300 && statusCode <= 699) { - this.stateTransition(transaction_state_1.TransactionState.Completed); - this.ack(response); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - break; - case transaction_state_1.TransactionState.Accepted: - // The purpose of the "Accepted" state is to allow the client - // transaction to continue to exist to receive, and pass to the TU, - // any retransmissions of the 2xx response and any additional 2xx - // responses from other branches of the INVITE if it forked - // downstream. Timer M reflects the amount of time that the - // transaction user will wait for such messages. - // - // Any 2xx responses that match this client transaction and that are - // received while in the "Accepted" state MUST be passed up to the - // TU. The client transaction MUST NOT generate an ACK to the 2xx - // response. The client transaction takes no further action. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 200 && statusCode <= 299) { - // NOTE: This implementation herein is intentionally not RFC compliant. - // While the first 2xx response for a given branch is passed up to the TU, - // retransmissions of 2xx responses are absorbed and the ACK associated - // with the original response is resent. This approach is taken because - // our current transaction users are not currently in a good position to - // deal with 2xx retransmission. This SHOULD NOT cause any compliance issues - ;) - // - // If we don't have a cache hit, pass the response to the TU. - if (!this.ackRetransmissionCache.has(response.toTag)) { - this.ackRetransmissionCache.set(response.toTag, undefined); // Prime the ACK cache - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // If we have a cache hit, try pulling the ACK from cache and retransmitting it. - var ack = this.ackRetransmissionCache.get(response.toTag); - if (ack) { - this.send(ack.toString()).catch(function (error) { - _this.logTransportError(error, "Failed to send retransmission of ACK to 2xx response."); - }); - return; - } - // If an ACK was not found in cache then we have received a retransmitted 2xx - // response before the TU responded to the original response (we don't have an ACK yet). - // So discard this response under the assumption that the TU will eventually - // get us a ACK for the original response. - return; - } - break; - case transaction_state_1.TransactionState.Completed: - // Any retransmissions of a response with status code 300-699 that - // are received while in the "Completed" state MUST cause the ACK to - // be re-passed to the transport layer for retransmission, but the - // newly received response MUST NOT be passed up to the TU. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 300 && statusCode <= 699) { - this.ack(response); - return; - } - break; - case transaction_state_1.TransactionState.Terminated: - break; - default: - throw new Error("Invalid state " + this.state); - } - // Any response received that does not match an existing client - // transaction state machine is simply dropped. (Implementations are, - // of course, free to log or do other implementation-specific things - // with such responses, but the implementer should be sure to consider - // the impact of large numbers of malicious stray responses.) - // https://tools.ietf.org/html/rfc6026#section-7.2 - var message = "Received unexpected " + statusCode + " response while in state " + this.state + "."; - this.logger.warn(message); - return; - }; - /** - * The client transaction SHOULD inform the TU that a transport failure - * has occurred, and the client transaction SHOULD transition directly - * to the "Terminated" state. The TU will handle the failover - * mechanisms described in [4]. - * https://tools.ietf.org/html/rfc3261#section-17.1.4 - * @param error - The error. - */ - InviteClientTransaction.prototype.onTransportError = function (error) { - if (this.user.onTransportError) { - this.user.onTransportError(error); - } - this.stateTransition(transaction_state_1.TransactionState.Terminated, true); - }; - /** For logging. */ - InviteClientTransaction.prototype.typeToString = function () { - return "INVITE client transaction"; - }; - InviteClientTransaction.prototype.ack = function (response) { - var _this = this; - // The ACK request constructed by the client transaction MUST contain - // values for the Call-ID, From, and Request-URI that are equal to the - // values of those header fields in the request passed to the transport - // by the client transaction (call this the "original request"). The To - // header field in the ACK MUST equal the To header field in the - // response being acknowledged, and therefore will usually differ from - // the To header field in the original request by the addition of the - // tag parameter. The ACK MUST contain a single Via header field, and - // this MUST be equal to the top Via header field of the original - // request. The CSeq header field in the ACK MUST contain the same - // value for the sequence number as was present in the original request, - // but the method parameter MUST be equal to "ACK". - // - // If the INVITE request whose response is being acknowledged had Route - // header fields, those header fields MUST appear in the ACK. This is - // to ensure that the ACK can be routed properly through any downstream - // stateless proxies. - // https://tools.ietf.org/html/rfc3261#section-17.1.1.3 - var ruri = this.request.ruri; - var callId = this.request.callId; - var cseq = this.request.cseq; - var from = this.request.getHeader("from"); - var to = response.getHeader("to"); - var via = this.request.getHeader("via"); - var route = this.request.getHeader("route"); - if (!from) { - throw new Error("From undefined."); - } - if (!to) { - throw new Error("To undefined."); - } - if (!via) { - throw new Error("Via undefined."); - } - var ack = "ACK " + ruri + " SIP/2.0\r\n"; - if (route) { - ack += "Route: " + route + "\r\n"; - } - ack += "Via: " + via + "\r\n"; - ack += "To: " + to + "\r\n"; - ack += "From: " + from + "\r\n"; - ack += "Call-ID: " + callId + "\r\n"; - ack += "CSeq: " + cseq + " ACK\r\n"; - ack += "Max-Forwards: 70\r\n"; - ack += "Content-Length: 0\r\n\r\n"; - // TOOO: "User-Agent" header - this.send(ack).catch(function (error) { - _this.logTransportError(error, "Failed to send ACK to non-2xx response."); - }); - return; - }; - /** - * Execute a state transition. - * @param newState - New state. - */ - InviteClientTransaction.prototype.stateTransition = function (newState, dueToTransportError) { - var _this = this; - if (dueToTransportError === void 0) { dueToTransportError = false; } - // Assert valid state transitions. - var invalidStateTransition = function () { - throw new Error("Invalid state transition from " + _this.state + " to " + newState); - }; - switch (newState) { - case transaction_state_1.TransactionState.Calling: - invalidStateTransition(); - break; - case transaction_state_1.TransactionState.Proceeding: - if (this.state !== transaction_state_1.TransactionState.Calling) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Accepted: - case transaction_state_1.TransactionState.Completed: - if (this.state !== transaction_state_1.TransactionState.Calling && - this.state !== transaction_state_1.TransactionState.Proceeding) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Terminated: - if (this.state !== transaction_state_1.TransactionState.Calling && - this.state !== transaction_state_1.TransactionState.Accepted && - this.state !== transaction_state_1.TransactionState.Completed) { - if (!dueToTransportError) { - invalidStateTransition(); - } - } - break; - default: - invalidStateTransition(); - } - // While not spelled out in the RFC, Timer B is the maximum amount of time that a sender - // will wait for an INVITE message to be acknowledged (a SIP response message is received). - // So Timer B should be cleared when the transaction state proceeds from "Calling". - if (this.B) { - clearTimeout(this.B); - this.B = undefined; - } - if (newState === transaction_state_1.TransactionState.Proceeding) { - // Timers have no effect on "Proceeding" state. - // In the "Proceeding" state, the client transaction - // SHOULD NOT retransmit the request any longer. - // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - } - // The client transaction MUST start Timer D when it enters the "Completed" state - // for any reason, with a value of at least 32 seconds for unreliable transports, - // and a value of zero seconds for reliable transports. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (newState === transaction_state_1.TransactionState.Completed) { - this.D = setTimeout(function () { return _this.timer_D(); }, timers_1.Timers.TIMER_D); - } - // The client transaction MUST transition to the "Accepted" state, - // and Timer M MUST be started with a value of 64*T1. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (newState === transaction_state_1.TransactionState.Accepted) { - this.M = setTimeout(function () { return _this.timer_M(); }, timers_1.Timers.TIMER_M); - } - // Once the transaction is in the "Terminated" state, it MUST be destroyed immediately. - // https://tools.ietf.org/html/rfc6026#section-8.7 - if (newState === transaction_state_1.TransactionState.Terminated) { - this.dispose(); - } - // Update state. - this.setState(newState); - }; - /** - * When timer A fires, the client transaction MUST retransmit the - * request by passing it to the transport layer, and MUST reset the - * timer with a value of 2*T1. - * When timer A fires 2*T1 seconds later, the request MUST be - * retransmitted again (assuming the client transaction is still in this - * state). This process MUST continue so that the request is - * retransmitted with intervals that double after each transmission. - * These retransmissions SHOULD only be done while the client - * transaction is in the "Calling" state. - * https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - */ - InviteClientTransaction.prototype.timer_A = function () { - // TODO - }; - /** - * If the client transaction is still in the "Calling" state when timer - * B fires, the client transaction SHOULD inform the TU that a timeout - * has occurred. The client transaction MUST NOT generate an ACK. - * https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - */ - InviteClientTransaction.prototype.timer_B = function () { - this.logger.debug("Timer B expired for INVITE client transaction " + this.id + "."); - if (this.state === transaction_state_1.TransactionState.Calling) { - this.onRequestTimeout(); - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - /** - * If Timer D fires while the client transaction is in the "Completed" state, - * the client transaction MUST move to the "Terminated" state. - * https://tools.ietf.org/html/rfc6026#section-8.4 - */ - InviteClientTransaction.prototype.timer_D = function () { - this.logger.debug("Timer D expired for INVITE client transaction " + this.id + "."); - if (this.state === transaction_state_1.TransactionState.Completed) { - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - /** - * If Timer M fires while the client transaction is in the "Accepted" - * state, the client transaction MUST move to the "Terminated" state. - * https://tools.ietf.org/html/rfc6026#section-8.4 - */ - InviteClientTransaction.prototype.timer_M = function () { - this.logger.debug("Timer M expired for INVITE client transaction " + this.id + "."); - if (this.state === transaction_state_1.TransactionState.Accepted) { - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - return InviteClientTransaction; -}(client_transaction_1.ClientTransaction)); -exports.InviteClientTransaction = InviteClientTransaction; - - -/***/ }), -/* 36 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * Transaction state. - * @public - */ -var TransactionState; -(function (TransactionState) { - TransactionState["Accepted"] = "Accepted"; - TransactionState["Calling"] = "Calling"; - TransactionState["Completed"] = "Completed"; - TransactionState["Confirmed"] = "Confirmed"; - TransactionState["Proceeding"] = "Proceeding"; - TransactionState["Terminated"] = "Terminated"; - TransactionState["Trying"] = "Trying"; -})(TransactionState = exports.TransactionState || (exports.TransactionState = {})); - - -/***/ }), -/* 37 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var timers_1 = __webpack_require__(26); -var server_transaction_1 = __webpack_require__(38); -var transaction_state_1 = __webpack_require__(36); -/** - * INVITE Server Transaction. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - * @public - */ -var InviteServerTransaction = /** @class */ (function (_super) { - tslib_1.__extends(InviteServerTransaction, _super); - /** - * Constructor. - * Upon construction, a "100 Trying" reply will be immediately sent. - * After construction the transaction will be in the "proceeding" state and the transaction - * `id` will equal the branch parameter set in the Via header of the incoming request. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - * @param request - Incoming INVITE request from the transport. - * @param transport - The transport. - * @param user - The transaction user. - */ - function InviteServerTransaction(request, transport, user) { - return _super.call(this, request, transport, user, transaction_state_1.TransactionState.Proceeding, "sip.transaction.ist") || this; - } - /** - * Destructor. - */ - InviteServerTransaction.prototype.dispose = function () { - this.stopProgressExtensionTimer(); - if (this.H) { - clearTimeout(this.H); - this.H = undefined; - } - if (this.I) { - clearTimeout(this.I); - this.I = undefined; - } - if (this.L) { - clearTimeout(this.L); - this.L = undefined; - } - _super.prototype.dispose.call(this); - }; - Object.defineProperty(InviteServerTransaction.prototype, "kind", { - /** Transaction kind. Deprecated. */ - get: function () { - return "ist"; - }, - enumerable: true, - configurable: true - }); - /** - * Receive requests from transport matching this transaction. - * @param request - Request matching this transaction. - */ - InviteServerTransaction.prototype.receiveRequest = function (request) { - var _this = this; - switch (this.state) { - case transaction_state_1.TransactionState.Proceeding: - // If a request retransmission is received while in the "Proceeding" state, the most - // recent provisional response that was received from the TU MUST be passed to the - // transport layer for retransmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (request.method === messages_1.C.INVITE) { - if (this.lastProvisionalResponse) { - this.send(this.lastProvisionalResponse).catch(function (error) { - _this.logTransportError(error, "Failed to send retransmission of provisional response."); - }); - } - return; - } - break; - case transaction_state_1.TransactionState.Accepted: - // While in the "Accepted" state, any retransmissions of the INVITE - // received will match this transaction state machine and will be - // absorbed by the machine without changing its state. These - // retransmissions are not passed onto the TU. - // https://tools.ietf.org/html/rfc6026#section-7.1 - if (request.method === messages_1.C.INVITE) { - return; - } - break; - case transaction_state_1.TransactionState.Completed: - // Furthermore, while in the "Completed" state, if a request retransmission is - // received, the server SHOULD pass the response to the transport for retransmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (request.method === messages_1.C.INVITE) { - if (!this.lastFinalResponse) { - throw new Error("Last final response undefined."); - } - this.send(this.lastFinalResponse).catch(function (error) { - _this.logTransportError(error, "Failed to send retransmission of final response."); - }); - return; - } - // If an ACK is received while the server transaction is in the "Completed" state, - // the server transaction MUST transition to the "Confirmed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (request.method === messages_1.C.ACK) { - this.stateTransition(transaction_state_1.TransactionState.Confirmed); - return; - } - break; - case transaction_state_1.TransactionState.Confirmed: - // The purpose of the "Confirmed" state is to absorb any additional ACK messages that arrive, - // triggered from retransmissions of the final response. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (request.method === messages_1.C.INVITE || request.method === messages_1.C.ACK) { - return; - } - break; - case transaction_state_1.TransactionState.Terminated: - // For good measure absorb any additional messages that arrive (should not happen). - if (request.method === messages_1.C.INVITE || request.method === messages_1.C.ACK) { - return; - } - break; - default: - throw new Error("Invalid state " + this.state); - } - var message = "INVITE server transaction received unexpected " + request.method + " request while in state " + this.state + "."; - this.logger.warn(message); - return; - }; - /** - * Receive responses from TU for this transaction. - * @param statusCode - Status code of response. - * @param response - Response. - */ - InviteServerTransaction.prototype.receiveResponse = function (statusCode, response) { - var _this = this; - if (statusCode < 100 || statusCode > 699) { - throw new Error("Invalid status code " + statusCode); - } - switch (this.state) { - case transaction_state_1.TransactionState.Proceeding: - // The TU passes any number of provisional responses to the server - // transaction. So long as the server transaction is in the - // "Proceeding" state, each of these MUST be passed to the transport - // layer for transmission. They are not sent reliably by the - // transaction layer (they are not retransmitted by it) and do not cause - // a change in the state of the server transaction. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (statusCode >= 100 && statusCode <= 199) { - this.lastProvisionalResponse = response; - // Start the progress extension timer only for a non-100 provisional response. - if (statusCode > 100) { - this.startProgressExtensionTimer(); // FIXME: remove - } - this.send(response).catch(function (error) { - _this.logTransportError(error, "Failed to send 1xx response."); - }); - return; - } - // If, while in the "Proceeding" state, the TU passes a 2xx response - // to the server transaction, the server transaction MUST pass this - // response to the transport layer for transmission. It is not - // retransmitted by the server transaction; retransmissions of 2xx - // responses are handled by the TU. The server transaction MUST then - // transition to the "Accepted" state. - // https://tools.ietf.org/html/rfc6026#section-8.5 - if (statusCode >= 200 && statusCode <= 299) { - this.lastFinalResponse = response; - this.stateTransition(transaction_state_1.TransactionState.Accepted); - this.send(response).catch(function (error) { - _this.logTransportError(error, "Failed to send 2xx response."); - }); - return; - } - // While in the "Proceeding" state, if the TU passes a response with - // status code from 300 to 699 to the server transaction, the response - // MUST be passed to the transport layer for transmission, and the state - // machine MUST enter the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (statusCode >= 300 && statusCode <= 699) { - this.lastFinalResponse = response; - this.stateTransition(transaction_state_1.TransactionState.Completed); - this.send(response).catch(function (error) { - _this.logTransportError(error, "Failed to send non-2xx final response."); - }); - return; - } - break; - case transaction_state_1.TransactionState.Accepted: - // While in the "Accepted" state, if the TU passes a 2xx response, - // the server transaction MUST pass the response to the transport layer for transmission. - // https://tools.ietf.org/html/rfc6026#section-8.7 - if (statusCode >= 200 && statusCode <= 299) { - this.send(response).catch(function (error) { - _this.logTransportError(error, "Failed to send 2xx response."); - }); - return; - } - break; - case transaction_state_1.TransactionState.Completed: - break; - case transaction_state_1.TransactionState.Confirmed: - break; - case transaction_state_1.TransactionState.Terminated: - break; - default: - throw new Error("Invalid state " + this.state); - } - var message = "INVITE server transaction received unexpected " + statusCode + " response from TU while in state " + this.state + "."; - this.logger.error(message); - throw new Error(message); - }; - /** - * Retransmit the last 2xx response. This is a noop if not in the "accepted" state. - */ - InviteServerTransaction.prototype.retransmitAcceptedResponse = function () { - var _this = this; - if (this.state === transaction_state_1.TransactionState.Accepted && this.lastFinalResponse) { - this.send(this.lastFinalResponse).catch(function (error) { - _this.logTransportError(error, "Failed to send 2xx response."); - }); - } - }; - /** - * First, the procedures in [4] are followed, which attempt to deliver the response to a backup. - * If those should all fail, based on the definition of failure in [4], the server transaction SHOULD - * inform the TU that a failure has occurred, and MUST remain in the current state. - * https://tools.ietf.org/html/rfc6026#section-8.8 - */ - InviteServerTransaction.prototype.onTransportError = function (error) { - if (this.user.onTransportError) { - this.user.onTransportError(error); - } - }; - /** For logging. */ - InviteServerTransaction.prototype.typeToString = function () { - return "INVITE server transaction"; - }; - /** - * Execute a state transition. - * @param newState - New state. - */ - InviteServerTransaction.prototype.stateTransition = function (newState) { - var _this = this; - // Assert valid state transitions. - var invalidStateTransition = function () { - throw new Error("Invalid state transition from " + _this.state + " to " + newState); - }; - switch (newState) { - case transaction_state_1.TransactionState.Proceeding: - invalidStateTransition(); - break; - case transaction_state_1.TransactionState.Accepted: - case transaction_state_1.TransactionState.Completed: - if (this.state !== transaction_state_1.TransactionState.Proceeding) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Confirmed: - if (this.state !== transaction_state_1.TransactionState.Completed) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Terminated: - if (this.state !== transaction_state_1.TransactionState.Accepted && - this.state !== transaction_state_1.TransactionState.Completed && - this.state !== transaction_state_1.TransactionState.Confirmed) { - invalidStateTransition(); - } - break; - default: - invalidStateTransition(); - } - // On any state transition, stop resending provisonal responses - this.stopProgressExtensionTimer(); - // The purpose of the "Accepted" state is to absorb retransmissions of an accepted INVITE request. - // Any such retransmissions are absorbed entirely within the server transaction. - // They are not passed up to the TU since any downstream UAS cores that accepted the request have - // taken responsibility for reliability and will already retransmit their 2xx responses if necessary. - // https://tools.ietf.org/html/rfc6026#section-8.7 - if (newState === transaction_state_1.TransactionState.Accepted) { - this.L = setTimeout(function () { return _this.timer_L(); }, timers_1.Timers.TIMER_L); - } - // When the "Completed" state is entered, timer H MUST be set to fire in 64*T1 seconds for all transports. - // Timer H determines when the server transaction abandons retransmitting the response. - // If an ACK is received while the server transaction is in the "Completed" state, - // the server transaction MUST transition to the "Confirmed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (newState === transaction_state_1.TransactionState.Completed) { - // FIXME: Missing timer G for unreliable transports. - this.H = setTimeout(function () { return _this.timer_H(); }, timers_1.Timers.TIMER_H); - } - // The purpose of the "Confirmed" state is to absorb any additional ACK messages that arrive, - // triggered from retransmissions of the final response. When this state is entered, timer I - // is set to fire in T4 seconds for unreliable transports, and zero seconds for reliable - // transports. Once timer I fires, the server MUST transition to the "Terminated" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (newState === transaction_state_1.TransactionState.Confirmed) { - // FIXME: This timer is not getting set correctly for unreliable transports. - this.I = setTimeout(function () { return _this.timer_I(); }, timers_1.Timers.TIMER_I); - } - // Once the transaction is in the "Terminated" state, it MUST be destroyed immediately. - // https://tools.ietf.org/html/rfc6026#section-8.7 - if (newState === transaction_state_1.TransactionState.Terminated) { - this.dispose(); - } - // Update state. - this.setState(newState); - }; - /** - * FIXME: UAS Provisional Retransmission Timer. See RFC 3261 Section 13.3.1.1 - * This is in the wrong place. This is not a transaction level thing. It's a UAS level thing. - */ - InviteServerTransaction.prototype.startProgressExtensionTimer = function () { - var _this = this; - // Start the progress extension timer only for the first non-100 provisional response. - if (this.progressExtensionTimer === undefined) { - this.progressExtensionTimer = setInterval(function () { - _this.logger.debug("Progress extension timer expired for INVITE server transaction " + _this.id + "."); - if (!_this.lastProvisionalResponse) { - throw new Error("Last provisional response undefined."); - } - _this.send(_this.lastProvisionalResponse).catch(function (error) { - _this.logTransportError(error, "Failed to send retransmission of provisional response."); - }); - }, timers_1.Timers.PROVISIONAL_RESPONSE_INTERVAL); - } - }; - /** - * FIXME: UAS Provisional Retransmission Timer id. See RFC 3261 Section 13.3.1.1 - * This is in the wrong place. This is not a transaction level thing. It's a UAS level thing. - */ - InviteServerTransaction.prototype.stopProgressExtensionTimer = function () { - if (this.progressExtensionTimer !== undefined) { - clearInterval(this.progressExtensionTimer); - this.progressExtensionTimer = undefined; - } - }; - /** - * While in the "Proceeding" state, if the TU passes a response with status code - * from 300 to 699 to the server transaction, the response MUST be passed to the - * transport layer for transmission, and the state machine MUST enter the "Completed" state. - * For unreliable transports, timer G is set to fire in T1 seconds, and is not set to fire for - * reliable transports. If timer G fires, the response is passed to the transport layer once - * more for retransmission, and timer G is set to fire in MIN(2*T1, T2) seconds. From then on, - * when timer G fires, the response is passed to the transport again for transmission, and - * timer G is reset with a value that doubles, unless that value exceeds T2, in which case - * it is reset with the value of T2. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - */ - InviteServerTransaction.prototype.timer_G = function () { - // TODO - }; - /** - * If timer H fires while in the "Completed" state, it implies that the ACK was never received. - * In this case, the server transaction MUST transition to the "Terminated" state, and MUST - * indicate to the TU that a transaction failure has occurred. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - */ - InviteServerTransaction.prototype.timer_H = function () { - this.logger.debug("Timer H expired for INVITE server transaction " + this.id + "."); - if (this.state === transaction_state_1.TransactionState.Completed) { - this.logger.warn("ACK to negative final response was never received, terminating transaction."); - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - /** - * Once timer I fires, the server MUST transition to the "Terminated" state. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - */ - InviteServerTransaction.prototype.timer_I = function () { - this.logger.debug("Timer I expired for INVITE server transaction " + this.id + "."); - this.stateTransition(transaction_state_1.TransactionState.Terminated); - }; - /** - * When Timer L fires and the state machine is in the "Accepted" state, the machine MUST - * transition to the "Terminated" state. Once the transaction is in the "Terminated" state, - * it MUST be destroyed immediately. Timer L reflects the amount of time the server - * transaction could receive 2xx responses for retransmission from the - * TU while it is waiting to receive an ACK. - * https://tools.ietf.org/html/rfc6026#section-7.1 - * https://tools.ietf.org/html/rfc6026#section-8.7 - */ - InviteServerTransaction.prototype.timer_L = function () { - this.logger.debug("Timer L expired for INVITE server transaction " + this.id + "."); - if (this.state === transaction_state_1.TransactionState.Accepted) { - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - return InviteServerTransaction; -}(server_transaction_1.ServerTransaction)); -exports.InviteServerTransaction = InviteServerTransaction; - - -/***/ }), -/* 38 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transaction_1 = __webpack_require__(29); -/** - * Server Transaction. - * @remarks - * The server transaction is responsible for the delivery of requests to - * the TU and the reliable transmission of responses. It accomplishes - * this through a state machine. Server transactions are created by the - * core when a request is received, and transaction handling is desired - * for that request (this is not always the case). - * https://tools.ietf.org/html/rfc3261#section-17.2 - * @public - */ -var ServerTransaction = /** @class */ (function (_super) { - tslib_1.__extends(ServerTransaction, _super); - function ServerTransaction(_request, transport, user, state, loggerCategory) { - var _this = _super.call(this, transport, user, _request.viaBranch, state, loggerCategory) || this; - _this._request = _request; - _this.user = user; - return _this; - } - Object.defineProperty(ServerTransaction.prototype, "request", { - /** The incoming request the transaction handling. */ - get: function () { - return this._request; - }, - enumerable: true, - configurable: true - }); - return ServerTransaction; -}(transaction_1.Transaction)); -exports.ServerTransaction = ServerTransaction; - - -/***/ }), -/* 39 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var timers_1 = __webpack_require__(26); -var client_transaction_1 = __webpack_require__(28); -var transaction_state_1 = __webpack_require__(36); -/** - * Non-INVITE Client Transaction. - * @remarks - * Non-INVITE transactions do not make use of ACK. - * They are simple request-response interactions. - * https://tools.ietf.org/html/rfc3261#section-17.1.2 - * @public - */ -var NonInviteClientTransaction = /** @class */ (function (_super) { - tslib_1.__extends(NonInviteClientTransaction, _super); - /** - * Constructor - * Upon construction, the outgoing request's Via header is updated by calling `setViaHeader`. - * Then `toString` is called on the outgoing request and the message is sent via the transport. - * After construction the transaction will be in the "calling" state and the transaction id - * will equal the branch parameter set in the Via header of the outgoing request. - * https://tools.ietf.org/html/rfc3261#section-17.1.2 - * @param request - The outgoing Non-INVITE request. - * @param transport - The transport. - * @param user - The transaction user. - */ - function NonInviteClientTransaction(request, transport, user) { - var _this = _super.call(this, request, transport, user, transaction_state_1.TransactionState.Trying, "sip.transaction.nict") || this; - // FIXME: Timer E for unreliable transports not implemented. - // - // The "Trying" state is entered when the TU initiates a new client - // transaction with a request. When entering this state, the client - // transaction SHOULD set timer F to fire in 64*T1 seconds. The request - // MUST be passed to the transport layer for transmission. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - _this.F = setTimeout(function () { return _this.timer_F(); }, timers_1.Timers.TIMER_F); - _this.send(request.toString()).catch(function (error) { - _this.logTransportError(error, "Failed to send initial outgoing request."); - }); - return _this; - } - /** - * Destructor. - */ - NonInviteClientTransaction.prototype.dispose = function () { - if (this.F) { - clearTimeout(this.F); - this.F = undefined; - } - if (this.K) { - clearTimeout(this.K); - this.K = undefined; - } - _super.prototype.dispose.call(this); - }; - Object.defineProperty(NonInviteClientTransaction.prototype, "kind", { - /** Transaction kind. Deprecated. */ - get: function () { - return "nict"; - }, - enumerable: true, - configurable: true - }); - /** - * Handler for incoming responses from the transport which match this transaction. - * @param response - The incoming response. - */ - NonInviteClientTransaction.prototype.receiveResponse = function (response) { - var statusCode = response.statusCode; - if (!statusCode || statusCode < 100 || statusCode > 699) { - throw new Error("Invalid status code " + statusCode); - } - switch (this.state) { - case transaction_state_1.TransactionState.Trying: - // If a provisional response is received while in the "Trying" state, the - // response MUST be passed to the TU, and then the client transaction - // SHOULD move to the "Proceeding" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (statusCode >= 100 && statusCode <= 199) { - this.stateTransition(transaction_state_1.TransactionState.Proceeding); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // If a final response (status codes 200-699) is received while in the - // "Trying" state, the response MUST be passed to the TU, and the - // client transaction MUST transition to the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (statusCode >= 200 && statusCode <= 699) { - this.stateTransition(transaction_state_1.TransactionState.Completed); - if (statusCode === 408) { - this.onRequestTimeout(); - return; - } - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - break; - case transaction_state_1.TransactionState.Proceeding: - // If a provisional response is received while in the "Proceeding" state, - // the response MUST be passed to the TU. (From Figure 6) - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (statusCode >= 100 && statusCode <= 199) { - if (this.user.receiveResponse) { - return this.user.receiveResponse(response); - } - } - // If a final response (status codes 200-699) is received while in the - // "Proceeding" state, the response MUST be passed to the TU, and the - // client transaction MUST transition to the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (statusCode >= 200 && statusCode <= 699) { - this.stateTransition(transaction_state_1.TransactionState.Completed); - if (statusCode === 408) { - this.onRequestTimeout(); - return; - } - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - case transaction_state_1.TransactionState.Completed: - // The "Completed" state exists to buffer any additional response - // retransmissions that may be received (which is why the client - // transaction remains there only for unreliable transports). - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - return; - case transaction_state_1.TransactionState.Terminated: - // For good measure just absorb additional response retransmissions. - return; - default: - throw new Error("Invalid state " + this.state); - } - var message = "Non-INVITE client transaction received unexpected " + statusCode + " response while in state " + this.state + "."; - this.logger.warn(message); - return; - }; - /** - * The client transaction SHOULD inform the TU that a transport failure has occurred, - * and the client transaction SHOULD transition directly to the "Terminated" state. - * The TU will handle the failover mechanisms described in [4]. - * https://tools.ietf.org/html/rfc3261#section-17.1.4 - * @param error - Trasnsport error - */ - NonInviteClientTransaction.prototype.onTransportError = function (error) { - if (this.user.onTransportError) { - this.user.onTransportError(error); - } - this.stateTransition(transaction_state_1.TransactionState.Terminated, true); - }; - /** For logging. */ - NonInviteClientTransaction.prototype.typeToString = function () { - return "non-INVITE client transaction"; - }; - /** - * Execute a state transition. - * @param newState - New state. - */ - NonInviteClientTransaction.prototype.stateTransition = function (newState, dueToTransportError) { - var _this = this; - if (dueToTransportError === void 0) { dueToTransportError = false; } - // Assert valid state transitions. - var invalidStateTransition = function () { - throw new Error("Invalid state transition from " + _this.state + " to " + newState); - }; - switch (newState) { - case transaction_state_1.TransactionState.Trying: - invalidStateTransition(); - break; - case transaction_state_1.TransactionState.Proceeding: - if (this.state !== transaction_state_1.TransactionState.Trying) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Completed: - if (this.state !== transaction_state_1.TransactionState.Trying && - this.state !== transaction_state_1.TransactionState.Proceeding) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Terminated: - if (this.state !== transaction_state_1.TransactionState.Trying && - this.state !== transaction_state_1.TransactionState.Proceeding && - this.state !== transaction_state_1.TransactionState.Completed) { - if (!dueToTransportError) { - invalidStateTransition(); - } - } - break; - default: - invalidStateTransition(); - } - // Once the client transaction enters the "Completed" state, it MUST set - // Timer K to fire in T4 seconds for unreliable transports, and zero - // seconds for reliable transports The "Completed" state exists to - // buffer any additional response retransmissions that may be received - // (which is why the client transaction remains there only for unreliable transports). - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (newState === transaction_state_1.TransactionState.Completed) { - if (this.F) { - clearTimeout(this.F); - this.F = undefined; - } - this.K = setTimeout(function () { return _this.timer_K(); }, timers_1.Timers.TIMER_K); - } - // Once the transaction is in the terminated state, it MUST be destroyed immediately. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (newState === transaction_state_1.TransactionState.Terminated) { - this.dispose(); - } - // Update state. - this.setState(newState); - }; - /** - * If Timer F fires while the client transaction is still in the - * "Trying" state, the client transaction SHOULD inform the TU about the - * timeout, and then it SHOULD enter the "Terminated" state. - * If timer F fires while in the "Proceeding" state, the TU MUST be informed of - * a timeout, and the client transaction MUST transition to the terminated state. - * https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - */ - NonInviteClientTransaction.prototype.timer_F = function () { - this.logger.debug("Timer F expired for non-INVITE client transaction " + this.id + "."); - if (this.state === transaction_state_1.TransactionState.Trying || this.state === transaction_state_1.TransactionState.Proceeding) { - this.onRequestTimeout(); - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - /** - * If Timer K fires while in this (COMPLETED) state, the client transaction - * MUST transition to the "Terminated" state. - * https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - */ - NonInviteClientTransaction.prototype.timer_K = function () { - if (this.state === transaction_state_1.TransactionState.Completed) { - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - return NonInviteClientTransaction; -}(client_transaction_1.ClientTransaction)); -exports.NonInviteClientTransaction = NonInviteClientTransaction; - - -/***/ }), -/* 40 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var timers_1 = __webpack_require__(26); -var server_transaction_1 = __webpack_require__(38); -var transaction_state_1 = __webpack_require__(36); -/** - * Non-INVITE Server Transaction. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-17.2.2 - * @public - */ -var NonInviteServerTransaction = /** @class */ (function (_super) { - tslib_1.__extends(NonInviteServerTransaction, _super); - /** - * Constructor. - * After construction the transaction will be in the "trying": state and the transaction - * `id` will equal the branch parameter set in the Via header of the incoming request. - * https://tools.ietf.org/html/rfc3261#section-17.2.2 - * @param request - Incoming Non-INVITE request from the transport. - * @param transport - The transport. - * @param user - The transaction user. - */ - function NonInviteServerTransaction(request, transport, user) { - return _super.call(this, request, transport, user, transaction_state_1.TransactionState.Trying, "sip.transaction.nist") || this; - } - /** - * Destructor. - */ - NonInviteServerTransaction.prototype.dispose = function () { - if (this.J) { - clearTimeout(this.J); - this.J = undefined; - } - _super.prototype.dispose.call(this); - }; - Object.defineProperty(NonInviteServerTransaction.prototype, "kind", { - /** Transaction kind. Deprecated. */ - get: function () { - return "nist"; - }, - enumerable: true, - configurable: true - }); - /** - * Receive requests from transport matching this transaction. - * @param request - Request matching this transaction. - */ - NonInviteServerTransaction.prototype.receiveRequest = function (request) { - var _this = this; - switch (this.state) { - case transaction_state_1.TransactionState.Trying: - // Once in the "Trying" state, any further request retransmissions are discarded. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - break; - case transaction_state_1.TransactionState.Proceeding: - // If a retransmission of the request is received while in the "Proceeding" state, - // the most recently sent provisional response MUST be passed to the transport layer for retransmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - if (!this.lastResponse) { - throw new Error("Last response undefined."); - } - this.send(this.lastResponse).catch(function (error) { - _this.logTransportError(error, "Failed to send retransmission of provisional response."); - }); - break; - case transaction_state_1.TransactionState.Completed: - // While in the "Completed" state, the server transaction MUST pass the final response to the transport - // layer for retransmission whenever a retransmission of the request is received. Any other final responses - // passed by the TU to the server transaction MUST be discarded while in the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - if (!this.lastResponse) { - throw new Error("Last response undefined."); - } - this.send(this.lastResponse).catch(function (error) { - _this.logTransportError(error, "Failed to send retransmission of final response."); - }); - break; - case transaction_state_1.TransactionState.Terminated: - break; - default: - throw new Error("Invalid state " + this.state); - } - }; - /** - * Receive responses from TU for this transaction. - * @param statusCode - Status code of repsonse. 101-199 not allowed per RFC 4320. - * @param response - Response to send. - */ - NonInviteServerTransaction.prototype.receiveResponse = function (statusCode, response) { - var _this = this; - if (statusCode < 100 || statusCode > 699) { - throw new Error("Invalid status code " + statusCode); - } - // An SIP element MUST NOT send any provisional response with a - // Status-Code other than 100 to a non-INVITE request. - // An SIP element MUST NOT respond to a non-INVITE request with a - // Status-Code of 100 over any unreliable transport, such as UDP, - // before the amount of time it takes a client transaction's Timer E to be reset to T2. - // An SIP element MAY respond to a non-INVITE request with a - // Status-Code of 100 over a reliable transport at any time. - // https://tools.ietf.org/html/rfc4320#section-4.1 - if (statusCode > 100 && statusCode <= 199) { - throw new Error("Provisional response other than 100 not allowed."); - } - switch (this.state) { - case transaction_state_1.TransactionState.Trying: - // While in the "Trying" state, if the TU passes a provisional response - // to the server transaction, the server transaction MUST enter the "Proceeding" state. - // The response MUST be passed to the transport layer for transmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - this.lastResponse = response; - if (statusCode >= 100 && statusCode < 200) { - this.stateTransition(transaction_state_1.TransactionState.Proceeding); - this.send(response).catch(function (error) { - _this.logTransportError(error, "Failed to send provisional response."); - }); - return; - } - if (statusCode >= 200 && statusCode <= 699) { - this.stateTransition(transaction_state_1.TransactionState.Completed); - this.send(response).catch(function (error) { - _this.logTransportError(error, "Failed to send final response."); - }); - return; - } - break; - case transaction_state_1.TransactionState.Proceeding: - // Any further provisional responses that are received from the TU while - // in the "Proceeding" state MUST be passed to the transport layer for transmission. - // If the TU passes a final response (status codes 200-699) to the server while in - // the "Proceeding" state, the transaction MUST enter the "Completed" state, and - // the response MUST be passed to the transport layer for transmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - this.lastResponse = response; - if (statusCode >= 200 && statusCode <= 699) { - this.stateTransition(transaction_state_1.TransactionState.Completed); - this.send(response).catch(function (error) { - _this.logTransportError(error, "Failed to send final response."); - }); - return; - } - break; - case transaction_state_1.TransactionState.Completed: - // Any other final responses passed by the TU to the server - // transaction MUST be discarded while in the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - return; - case transaction_state_1.TransactionState.Terminated: - break; - default: - throw new Error("Invalid state " + this.state); - } - var message = "Non-INVITE server transaction received unexpected " + statusCode + " response from TU while in state " + this.state + "."; - this.logger.error(message); - throw new Error(message); - }; - /** - * First, the procedures in [4] are followed, which attempt to deliver the response to a backup. - * If those should all fail, based on the definition of failure in [4], the server transaction SHOULD - * inform the TU that a failure has occurred, and SHOULD transition to the terminated state. - * https://tools.ietf.org/html/rfc3261#section-17.2.4 - */ - NonInviteServerTransaction.prototype.onTransportError = function (error) { - if (this.user.onTransportError) { - this.user.onTransportError(error); - } - this.stateTransition(transaction_state_1.TransactionState.Terminated, true); - }; - /** For logging. */ - NonInviteServerTransaction.prototype.typeToString = function () { - return "non-INVITE server transaction"; - }; - NonInviteServerTransaction.prototype.stateTransition = function (newState, dueToTransportError) { - var _this = this; - if (dueToTransportError === void 0) { dueToTransportError = false; } - // Assert valid state transitions. - var invalidStateTransition = function () { - throw new Error("Invalid state transition from " + _this.state + " to " + newState); - }; - switch (newState) { - case transaction_state_1.TransactionState.Trying: - invalidStateTransition(); - break; - case transaction_state_1.TransactionState.Proceeding: - if (this.state !== transaction_state_1.TransactionState.Trying) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Completed: - if (this.state !== transaction_state_1.TransactionState.Trying && this.state !== transaction_state_1.TransactionState.Proceeding) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Terminated: - if (this.state !== transaction_state_1.TransactionState.Proceeding && this.state !== transaction_state_1.TransactionState.Completed) { - if (!dueToTransportError) { - invalidStateTransition(); - } - } - break; - default: - invalidStateTransition(); - } - // When the server transaction enters the "Completed" state, it MUST set Timer J to fire - // in 64*T1 seconds for unreliable transports, and zero seconds for reliable transports. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - if (newState === transaction_state_1.TransactionState.Completed) { - this.J = setTimeout(function () { return _this.timer_J(); }, timers_1.Timers.TIMER_J); - } - // The server transaction MUST be destroyed the instant it enters the "Terminated" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - if (newState === transaction_state_1.TransactionState.Terminated) { - this.dispose(); - } - this.setState(newState); - }; - /** - * The server transaction remains in this state until Timer J fires, - * at which point it MUST transition to the "Terminated" state. - * https://tools.ietf.org/html/rfc3261#section-17.2.2 - */ - NonInviteServerTransaction.prototype.timer_J = function () { - this.logger.debug("Timer J expired for NON-INVITE server transaction " + this.id + "."); - if (this.state === transaction_state_1.TransactionState.Completed) { - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - return NonInviteServerTransaction; -}(server_transaction_1.ServerTransaction)); -exports.NonInviteServerTransaction = NonInviteServerTransaction; - - -/***/ }), -/* 41 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * BYE UAC. - * @public - */ -var ByeUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(ByeUserAgentClient, _super); - function ByeUserAgentClient(dialog, delegate, options) { - var _this = this; - var message = dialog.createOutgoingRequestMessage(messages_1.C.BYE, options); - _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; - dialog.dispose(); - return _this; - } - return ByeUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.ByeUserAgentClient = ByeUserAgentClient; - - -/***/ }), -/* 42 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var messages_1 = __webpack_require__(5); -var transactions_1 = __webpack_require__(27); -/** - * User Agent Client (UAC). - * @remarks - * A user agent client is a logical entity - * that creates a new request, and then uses the client - * transaction state machinery to send it. The role of UAC lasts - * only for the duration of that transaction. In other words, if - * a piece of software initiates a request, it acts as a UAC for - * the duration of that transaction. If it receives a request - * later, it assumes the role of a user agent server for the - * processing of that transaction. - * https://tools.ietf.org/html/rfc3261#section-6 - * @public - */ -var UserAgentClient = /** @class */ (function () { - function UserAgentClient(transactionConstructor, core, message, delegate) { - this.transactionConstructor = transactionConstructor; - this.core = core; - this.message = message; - this.delegate = delegate; - this.challenged = false; - this.stale = false; - this.logger = this.loggerFactory.getLogger("sip.user-agent-client"); - this.init(); - } - UserAgentClient.prototype.dispose = function () { - this.transaction.dispose(); - }; - Object.defineProperty(UserAgentClient.prototype, "loggerFactory", { - get: function () { - return this.core.loggerFactory; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(UserAgentClient.prototype, "transaction", { - /** The transaction associated with this request. */ - get: function () { - if (!this._transaction) { - throw new Error("Transaction undefined."); - } - return this._transaction; - }, - enumerable: true, - configurable: true - }); - /** - * Since requests other than INVITE are responded to immediately, sending a - * CANCEL for a non-INVITE request would always create a race condition. - * A CANCEL request SHOULD NOT be sent to cancel a request other than INVITE. - * https://tools.ietf.org/html/rfc3261#section-9.1 - * @param options - Cancel options bucket. - */ - UserAgentClient.prototype.cancel = function (reason, options) { - var _this = this; - if (options === void 0) { options = {}; } - if (!this.transaction) { - throw new Error("Transaction undefined."); - } - if (!this.message.to) { - throw new Error("To undefined."); - } - if (!this.message.from) { - throw new Error("From undefined."); - } - // The following procedures are used to construct a CANCEL request. The - // Request-URI, Call-ID, To, the numeric part of CSeq, and From header - // fields in the CANCEL request MUST be identical to those in the - // request being cancelled, including tags. A CANCEL constructed by a - // client MUST have only a single Via header field value matching the - // top Via value in the request being cancelled. Using the same values - // for these header fields allows the CANCEL to be matched with the - // request it cancels (Section 9.2 indicates how such matching occurs). - // However, the method part of the CSeq header field MUST have a value - // of CANCEL. This allows it to be identified and processed as a - // transaction in its own right (See Section 17). - // https://tools.ietf.org/html/rfc3261#section-9.1 - var message = this.core.makeOutgoingRequestMessage(messages_1.C.CANCEL, this.message.ruri, this.message.from.uri, this.message.to.uri, { - toTag: this.message.toTag, - fromTag: this.message.fromTag, - callId: this.message.callId, - cseq: this.message.cseq - }, options.extraHeaders); - // TODO: Revisit this. - // The CANCEL needs to use the same branch parameter so that - // it matches the INVITE transaction, but this is a hacky way to do this. - // Or at the very least not well documented. If the the branch parameter - // is set on the outgoing request, the transaction will use it. - // Otherwise the transaction will make a new one. - message.branch = this.message.branch; - if (this.message.headers.Route) { - message.headers.Route = this.message.headers.Route; - } - if (reason) { - message.setHeader("Reason", reason); - } - // If no provisional response has been received, the CANCEL request MUST - // NOT be sent; rather, the client MUST wait for the arrival of a - // provisional response before sending the request. If the original - // request has generated a final response, the CANCEL SHOULD NOT be - // sent, as it is an effective no-op, since CANCEL has no effect on - // requests that have already generated a final response. - // https://tools.ietf.org/html/rfc3261#section-9.1 - if (this.transaction.state === transactions_1.TransactionState.Proceeding) { - var uac = new UserAgentClient(transactions_1.NonInviteClientTransaction, this.core, message); - } - else { - this.transaction.once("stateChanged", function () { - if (_this.transaction && _this.transaction.state === transactions_1.TransactionState.Proceeding) { - var uac = new UserAgentClient(transactions_1.NonInviteClientTransaction, _this.core, message); - } - }); - } - return message; - }; - /** - * If a 401 (Unauthorized) or 407 (Proxy Authentication Required) - * response is received, the UAC SHOULD follow the authorization - * procedures of Section 22.2 and Section 22.3 to retry the request with - * credentials. - * https://tools.ietf.org/html/rfc3261#section-8.1.3.5 - * 22 Usage of HTTP Authentication - * https://tools.ietf.org/html/rfc3261#section-22 - * 22.1 Framework - * https://tools.ietf.org/html/rfc3261#section-22.1 - * 22.2 User-to-User Authentication - * https://tools.ietf.org/html/rfc3261#section-22.2 - * 22.3 Proxy-to-User Authentication - * https://tools.ietf.org/html/rfc3261#section-22.3 - * - * FIXME: This "guard for and retry the request with credentials" - * implementation is not complete and at best minimally passable. - * @param response - The incoming response to guard. - * @returns True if the program execution is to continue in the branch in question. - * Otherwise the request is retried with credentials and current request processing must stop. - */ - UserAgentClient.prototype.authenticationGuard = function (message) { - var statusCode = message.statusCode; - if (!statusCode) { - throw new Error("Response status code undefined."); - } - // If a 401 (Unauthorized) or 407 (Proxy Authentication Required) - // response is received, the UAC SHOULD follow the authorization - // procedures of Section 22.2 and Section 22.3 to retry the request with - // credentials. - // https://tools.ietf.org/html/rfc3261#section-8.1.3.5 - if (statusCode !== 401 && statusCode !== 407) { - return true; - } - // Get and parse the appropriate WWW-Authenticate or Proxy-Authenticate header. - var challenge; - var authorizationHeaderName; - if (statusCode === 401) { - challenge = message.parseHeader("www-authenticate"); - authorizationHeaderName = "authorization"; - } - else { - challenge = message.parseHeader("proxy-authenticate"); - authorizationHeaderName = "proxy-authorization"; - } - // Verify it seems a valid challenge. - if (!challenge) { - this.logger.warn(statusCode + " with wrong or missing challenge, cannot authenticate"); - return true; - } - // Avoid infinite authentications. - if (this.challenged && (this.stale || challenge.stale !== true)) { - this.logger.warn(statusCode + " apparently in authentication loop, cannot authenticate"); - return true; - } - // Get credentials. - if (!this.credentials) { - this.credentials = this.core.configuration.authenticationFactory(); - if (!this.credentials) { - this.logger.warn("Unable to obtain credentials, cannot authenticate"); - return true; - } - } - // Verify that the challenge is really valid. - if (!this.credentials.authenticate(this.message, challenge)) { - return true; - } - this.challenged = true; - if (challenge.stale) { - this.stale = true; - } - var cseq = this.message.cseq += 1; - this.message.setHeader("cseq", cseq + " " + this.message.method); - this.message.setHeader(authorizationHeaderName, this.credentials.toString()); - // Calling init (again) will swap out our existing client transaction with a new one. - // FIXME: HACK: An assumption is being made here that there is nothing that needs to - // be cleaned up beyond the client transaction which is being replaced. For example, - // it is assumed that no early dialogs have been created. - this.init(); - return false; - }; - /** - * Receive a response from the transaction layer. - * @param message - Incoming response message. - */ - UserAgentClient.prototype.receiveResponse = function (message) { - if (!this.authenticationGuard(message)) { - return; - } - var statusCode = message.statusCode ? message.statusCode.toString() : ""; - if (!statusCode) { - throw new Error("Response status code undefined."); - } - switch (true) { - case /^100$/.test(statusCode): - if (this.delegate && this.delegate.onTrying) { - this.delegate.onTrying({ message: message }); - } - break; - case /^1[0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onProgress) { - this.delegate.onProgress({ message: message }); - } - break; - case /^2[0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onAccept) { - this.delegate.onAccept({ message: message }); - } - break; - case /^3[0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onRedirect) { - this.delegate.onRedirect({ message: message }); - } - break; - case /^[4-6][0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onReject) { - this.delegate.onReject({ message: message }); - } - break; - default: - throw new Error("Invalid status code " + statusCode); - } - }; - UserAgentClient.prototype.init = function () { - var _this = this; - // We are the transaction user. - var user = { - loggerFactory: this.loggerFactory, - onRequestTimeout: function () { return _this.onRequestTimeout(); }, - onStateChange: function (newState) { - if (newState === transactions_1.TransactionState.Terminated) { - // Remove the terminated transaction from the core. - _this.core.userAgentClients.delete(userAgentClientId); - // FIXME: HACK: Our transaction may have been swapped out with a new one - // post authentication (see above), so make sure to only to dispose of - // ourselves if this terminating transaction is our current transaction. - if (transaction === _this._transaction) { - _this.dispose(); - } - } - }, - onTransportError: function (error) { return _this.onTransportError(error); }, - receiveResponse: function (message) { return _this.receiveResponse(message); } - }; - // Create a new transaction with us as the user. - var transaction = new this.transactionConstructor(this.message, this.core.transport, user); - this._transaction = transaction; - // Add the new transaction to the core. - var userAgentClientId = transaction.id + transaction.request.method; - this.core.userAgentClients.set(userAgentClientId, this); - }; - /** - * 8.1.3.1 Transaction Layer Errors - * In some cases, the response returned by the transaction layer will - * not be a SIP message, but rather a transaction layer error. When a - * timeout error is received from the transaction layer, it MUST be - * treated as if a 408 (Request Timeout) status code has been received. - * If a fatal transport error is reported by the transport layer - * (generally, due to fatal ICMP errors in UDP or connection failures in - * TCP), the condition MUST be treated as a 503 (Service Unavailable) - * status code. - * https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - */ - UserAgentClient.prototype.onRequestTimeout = function () { - this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout."); - var message = new messages_1.IncomingResponseMessage(); - message.statusCode = 408; - message.reasonPhrase = "Request Timeout"; - this.receiveResponse(message); - return; - }; - /** - * 8.1.3.1 Transaction Layer Errors - * In some cases, the response returned by the transaction layer will - * not be a SIP message, but rather a transaction layer error. When a - * timeout error is received from the transaction layer, it MUST be - * treated as if a 408 (Request Timeout) status code has been received. - * If a fatal transport error is reported by the transport layer - * (generally, due to fatal ICMP errors in UDP or connection failures in - * TCP), the condition MUST be treated as a 503 (Service Unavailable) - * status code. - * https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - */ - UserAgentClient.prototype.onTransportError = function (error) { - this.logger.error(error.message); - this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable."); - var message = new messages_1.IncomingResponseMessage(); - message.statusCode = 503; - message.reasonPhrase = "Service Unavailable"; - this.receiveResponse(message); - }; - return UserAgentClient; -}()); -exports.UserAgentClient = UserAgentClient; - - -/***/ }), -/* 43 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * BYE UAS. - * @public - */ -var ByeUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(ByeUserAgentServer, _super); - function ByeUserAgentServer(dialog, message, delegate) { - return _super.call(this, transactions_1.NonInviteServerTransaction, dialog.userAgentCore, message, delegate) || this; - } - return ByeUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.ByeUserAgentServer = ByeUserAgentServer; - - -/***/ }), -/* 44 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var exceptions_1 = __webpack_require__(31); -var messages_1 = __webpack_require__(5); -var utils_1 = __webpack_require__(16); -var transactions_1 = __webpack_require__(27); -/** - * User Agent Server (UAS). - * @remarks - * A user agent server is a logical entity - * that generates a response to a SIP request. The response - * accepts, rejects, or redirects the request. This role lasts - * only for the duration of that transaction. In other words, if - * a piece of software responds to a request, it acts as a UAS for - * the duration of that transaction. If it generates a request - * later, it assumes the role of a user agent client for the - * processing of that transaction. - * https://tools.ietf.org/html/rfc3261#section-6 - * @public - */ -var UserAgentServer = /** @class */ (function () { - function UserAgentServer(transactionConstructor, core, message, delegate) { - this.transactionConstructor = transactionConstructor; - this.core = core; - this.message = message; - this.delegate = delegate; - this.logger = this.loggerFactory.getLogger("sip.user-agent-server"); - this.toTag = message.toTag ? message.toTag : utils_1.newTag(); - this.init(); - } - UserAgentServer.prototype.dispose = function () { - this.transaction.dispose(); - }; - Object.defineProperty(UserAgentServer.prototype, "loggerFactory", { - get: function () { - return this.core.loggerFactory; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(UserAgentServer.prototype, "transaction", { - /** The transaction associated with this request. */ - get: function () { - if (!this._transaction) { - throw new Error("Transaction undefined."); - } - return this._transaction; - }, - enumerable: true, - configurable: true - }); - UserAgentServer.prototype.accept = function (options) { - if (options === void 0) { options = { statusCode: 200 }; } - if (!this.acceptable) { - throw new exceptions_1.TransactionStateError(this.message.method + " not acceptable in state " + this.transaction.state + "."); - } - var statusCode = options.statusCode; - if (statusCode < 200 || statusCode > 299) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - var response = this.reply(options); - return response; - }; - UserAgentServer.prototype.progress = function (options) { - if (options === void 0) { options = { statusCode: 180 }; } - if (!this.progressable) { - throw new exceptions_1.TransactionStateError(this.message.method + " not progressable in state " + this.transaction.state + "."); - } - var statusCode = options.statusCode; - if (statusCode < 101 || statusCode > 199) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - var response = this.reply(options); - return response; - }; - UserAgentServer.prototype.redirect = function (contacts, options) { - if (options === void 0) { options = { statusCode: 302 }; } - if (!this.redirectable) { - throw new exceptions_1.TransactionStateError(this.message.method + " not redirectable in state " + this.transaction.state + "."); - } - var statusCode = options.statusCode; - if (statusCode < 300 || statusCode > 399) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - var contactHeaders = new Array(); - contacts.forEach(function (contact) { return contactHeaders.push("Contact: " + contact.toString()); }); - options.extraHeaders = (options.extraHeaders || []).concat(contactHeaders); - var response = this.reply(options); - return response; - }; - UserAgentServer.prototype.reject = function (options) { - if (options === void 0) { options = { statusCode: 480 }; } - if (!this.rejectable) { - throw new exceptions_1.TransactionStateError(this.message.method + " not rejectable in state " + this.transaction.state + "."); - } - var statusCode = options.statusCode; - if (statusCode < 400 || statusCode > 699) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - var response = this.reply(options); - return response; - }; - UserAgentServer.prototype.trying = function (options) { - if (!this.tryingable) { - throw new exceptions_1.TransactionStateError(this.message.method + " not tryingable in state " + this.transaction.state + "."); - } - var response = this.reply({ statusCode: 100 }); - return response; - }; - /** - * If the UAS did not find a matching transaction for the CANCEL - * according to the procedure above, it SHOULD respond to the CANCEL - * with a 481 (Call Leg/Transaction Does Not Exist). If the transaction - * for the original request still exists, the behavior of the UAS on - * receiving a CANCEL request depends on whether it has already sent a - * final response for the original request. If it has, the CANCEL - * request has no effect on the processing of the original request, no - * effect on any session state, and no effect on the responses generated - * for the original request. If the UAS has not issued a final response - * for the original request, its behavior depends on the method of the - * original request. If the original request was an INVITE, the UAS - * SHOULD immediately respond to the INVITE with a 487 (Request - * Terminated). A CANCEL request has no impact on the processing of - * transactions with any other method defined in this specification. - * https://tools.ietf.org/html/rfc3261#section-9.2 - * @param request - Incoming CANCEL request. - */ - UserAgentServer.prototype.receiveCancel = function (message) { - // Note: Currently CANCEL is being handled as a special case. - // No UAS is created to handle the CANCEL and the response to - // it CANCEL is being handled statelessly by the user agent core. - // As such, there is currently no way to externally impact the - // response to the a CANCEL request. - if (this.delegate && this.delegate.onCancel) { - this.delegate.onCancel(message); - } - }; - Object.defineProperty(UserAgentServer.prototype, "acceptable", { - get: function () { - if (this.transaction instanceof transactions_1.InviteServerTransaction) { - return (this.transaction.state === transactions_1.TransactionState.Proceeding || - this.transaction.state === transactions_1.TransactionState.Accepted); - } - if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { - return (this.transaction.state === transactions_1.TransactionState.Trying || - this.transaction.state === transactions_1.TransactionState.Proceeding); - } - throw new Error("Unknown transaction type."); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(UserAgentServer.prototype, "progressable", { - get: function () { - if (this.transaction instanceof transactions_1.InviteServerTransaction) { - return this.transaction.state === transactions_1.TransactionState.Proceeding; - } - if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { - return false; // https://tools.ietf.org/html/rfc4320#section-4.1 - } - throw new Error("Unknown transaction type."); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(UserAgentServer.prototype, "redirectable", { - get: function () { - if (this.transaction instanceof transactions_1.InviteServerTransaction) { - return this.transaction.state === transactions_1.TransactionState.Proceeding; - } - if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { - return (this.transaction.state === transactions_1.TransactionState.Trying || - this.transaction.state === transactions_1.TransactionState.Proceeding); - } - throw new Error("Unknown transaction type."); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(UserAgentServer.prototype, "rejectable", { - get: function () { - if (this.transaction instanceof transactions_1.InviteServerTransaction) { - return this.transaction.state === transactions_1.TransactionState.Proceeding; - } - if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { - return (this.transaction.state === transactions_1.TransactionState.Trying || - this.transaction.state === transactions_1.TransactionState.Proceeding); - } - throw new Error("Unknown transaction type."); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(UserAgentServer.prototype, "tryingable", { - get: function () { - if (this.transaction instanceof transactions_1.InviteServerTransaction) { - return this.transaction.state === transactions_1.TransactionState.Proceeding; - } - if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { - return this.transaction.state === transactions_1.TransactionState.Trying; - } - throw new Error("Unknown transaction type."); - }, - enumerable: true, - configurable: true - }); - /** - * When a UAS wishes to construct a response to a request, it follows - * the general procedures detailed in the following subsections. - * Additional behaviors specific to the response code in question, which - * are not detailed in this section, may also be required. - * - * Once all procedures associated with the creation of a response have - * been completed, the UAS hands the response back to the server - * transaction from which it received the request. - * https://tools.ietf.org/html/rfc3261#section-8.2.6 - * @param statusCode - Status code to reply with. - * @param options - Reply options bucket. - */ - UserAgentServer.prototype.reply = function (options) { - if (!options.toTag && options.statusCode !== 100) { - options.toTag = this.toTag; - } - options.userAgent = options.userAgent || this.core.configuration.userAgentHeaderFieldValue; - options.supported = options.supported || this.core.configuration.supportedOptionTagsResponse; - var response = messages_1.constructOutgoingResponse(this.message, options); - this.transaction.receiveResponse(options.statusCode, response.message); - return response; - }; - UserAgentServer.prototype.init = function () { - var _this = this; - // We are the transaction user. - var user = { - loggerFactory: this.loggerFactory, - onStateChange: function (newState) { - if (newState === transactions_1.TransactionState.Terminated) { - // Remove the terminated transaction from the core. - _this.core.userAgentServers.delete(userAgentServerId); - _this.dispose(); - } - }, - onTransportError: function (error) { - _this.logger.error(error.message); - if (_this.delegate && _this.delegate.onTransportError) { - _this.delegate.onTransportError(error); - } - else { - _this.logger.error("User agent server response transport error."); - } - } - }; - // Create a new transaction with us as the user. - var transaction = new this.transactionConstructor(this.message, this.core.transport, user); - this._transaction = transaction; - // Add the new transaction to the core. - var userAgentServerId = transaction.id; - this.core.userAgentServers.set(transaction.id, this); - }; - return UserAgentServer; -}()); -exports.UserAgentServer = UserAgentServer; - - -/***/ }), -/* 45 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * INFO UAC. - * @public - */ -var InfoUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(InfoUserAgentClient, _super); - function InfoUserAgentClient(dialog, delegate, options) { - var _this = this; - var message = dialog.createOutgoingRequestMessage(messages_1.C.INFO, options); - _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; - return _this; - } - return InfoUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.InfoUserAgentClient = InfoUserAgentClient; - - -/***/ }), -/* 46 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * INFO UAS. - * @public - */ -var InfoUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(InfoUserAgentServer, _super); - function InfoUserAgentServer(dialog, message, delegate) { - return _super.call(this, transactions_1.NonInviteServerTransaction, dialog.userAgentCore, message, delegate) || this; - } - return InfoUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.InfoUserAgentServer = InfoUserAgentServer; - - -/***/ }), -/* 47 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * NOTIFY UAS. - * @public - */ -var NotifyUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(NotifyUserAgentClient, _super); - function NotifyUserAgentClient(dialog, delegate, options) { - var _this = this; - var message = dialog.createOutgoingRequestMessage(messages_1.C.NOTIFY, options); - _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; - return _this; - } - return NotifyUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.NotifyUserAgentClient = NotifyUserAgentClient; - - -/***/ }), -/* 48 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * NOTIFY UAS. - * @public - */ -var NotifyUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(NotifyUserAgentServer, _super); - /** - * NOTIFY UAS constructor. - * @param dialogOrCore - Dialog for in dialog NOTIFY, UserAgentCore for out of dialog NOTIFY (deprecated). - * @param message - Incoming NOTIFY request message. - */ - function NotifyUserAgentServer(dialogOrCore, message, delegate) { - var _this = this; - var userAgentCore = instanceOfDialog(dialogOrCore) ? - dialogOrCore.userAgentCore : - dialogOrCore; - _this = _super.call(this, transactions_1.NonInviteServerTransaction, userAgentCore, message, delegate) || this; - return _this; - } - return NotifyUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.NotifyUserAgentServer = NotifyUserAgentServer; -function instanceOfDialog(object) { - return object.userAgentCore !== undefined; -} - - -/***/ }), -/* 49 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * PRACK UAC. - * @public - */ -var PrackUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(PrackUserAgentClient, _super); - function PrackUserAgentClient(dialog, delegate, options) { - var _this = this; - var message = dialog.createOutgoingRequestMessage(messages_1.C.PRACK, options); - _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; - dialog.signalingStateTransition(message); - return _this; - } - return PrackUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.PrackUserAgentClient = PrackUserAgentClient; - - -/***/ }), -/* 50 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * PRACK UAS. - * @public - */ -var PrackUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(PrackUserAgentServer, _super); - function PrackUserAgentServer(dialog, message, delegate) { - var _this = _super.call(this, transactions_1.NonInviteServerTransaction, dialog.userAgentCore, message, delegate) || this; - // Update dialog signaling state with offer/answer in body - dialog.signalingStateTransition(message); - _this.dialog = dialog; - return _this; - } - /** - * Update the dialog signaling state on a 2xx response. - * @param options - Options bucket. - */ - PrackUserAgentServer.prototype.accept = function (options) { - if (options === void 0) { options = { statusCode: 200 }; } - if (options.body) { - // Update dialog signaling state with offer/answer in body - this.dialog.signalingStateTransition(options.body); - } - return _super.prototype.accept.call(this, options); - }; - return PrackUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.PrackUserAgentServer = PrackUserAgentServer; - - -/***/ }), -/* 51 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * Re-INVITE UAC. - * @remarks - * 14 Modifying an Existing Session - * https://tools.ietf.org/html/rfc3261#section-14 - * 14.1 UAC Behavior - * https://tools.ietf.org/html/rfc3261#section-14.1 - * @public - */ -var ReInviteUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(ReInviteUserAgentClient, _super); - function ReInviteUserAgentClient(dialog, delegate, options) { - var _this = this; - var message = dialog.createOutgoingRequestMessage(messages_1.C.INVITE, options); - _this = _super.call(this, transactions_1.InviteClientTransaction, dialog.userAgentCore, message, delegate) || this; - _this.delegate = delegate; - dialog.signalingStateTransition(message); - // FIXME: TODO: next line obviously needs to be improved... - dialog.reinviteUserAgentClient = _this; // let the dialog know re-invite request sent - _this.dialog = dialog; - return _this; - } - ReInviteUserAgentClient.prototype.receiveResponse = function (message) { - var _this = this; - var statusCode = message.statusCode ? message.statusCode.toString() : ""; - if (!statusCode) { - throw new Error("Response status code undefined."); - } - switch (true) { - case /^100$/.test(statusCode): - if (this.delegate && this.delegate.onTrying) { - this.delegate.onTrying({ message: message }); - } - break; - case /^1[0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onProgress) { - this.delegate.onProgress({ - message: message, - session: this.dialog, - prack: function (options) { - throw new Error("Unimplemented."); - } - }); - } - break; - case /^2[0-9]{2}$/.test(statusCode): - // Update dialog signaling state with offer/answer in body - this.dialog.signalingStateTransition(message); - if (this.delegate && this.delegate.onAccept) { - this.delegate.onAccept({ - message: message, - session: this.dialog, - ack: function (options) { - var outgoingAckRequest = _this.dialog.ack(options); - return outgoingAckRequest; - } - }); - } - break; - case /^3[0-9]{2}$/.test(statusCode): - this.dialog.signalingStateRollback(); - this.dialog.reinviteUserAgentClient = undefined; // ACK was handled by transaction - if (this.delegate && this.delegate.onRedirect) { - this.delegate.onRedirect({ message: message }); - } - break; - case /^[4-6][0-9]{2}$/.test(statusCode): - this.dialog.signalingStateRollback(); - this.dialog.reinviteUserAgentClient = undefined; // ACK was handled by transaction - if (this.delegate && this.delegate.onReject) { - this.delegate.onReject({ message: message }); - } - else { - // If a UA receives a non-2xx final response to a re-INVITE, the session - // parameters MUST remain unchanged, as if no re-INVITE had been issued. - // Note that, as stated in Section 12.2.1.2, if the non-2xx final - // response is a 481 (Call/Transaction Does Not Exist), or a 408 - // (Request Timeout), or no response at all is received for the re- - // INVITE (that is, a timeout is returned by the INVITE client - // transaction), the UAC will terminate the dialog. - // - // If a UAC receives a 491 response to a re-INVITE, it SHOULD start a - // timer with a value T chosen as follows: - // - // 1. If the UAC is the owner of the Call-ID of the dialog ID - // (meaning it generated the value), T has a randomly chosen value - // between 2.1 and 4 seconds in units of 10 ms. - // - // 2. If the UAC is not the owner of the Call-ID of the dialog ID, T - // has a randomly chosen value of between 0 and 2 seconds in units - // of 10 ms. - // - // When the timer fires, the UAC SHOULD attempt the re-INVITE once more, - // if it still desires for that session modification to take place. For - // example, if the call was already hung up with a BYE, the re-INVITE - // would not take place. - // https://tools.ietf.org/html/rfc3261#section-14.1 - // FIXME: TODO: The above. - } - break; - default: - throw new Error("Invalid status code " + statusCode); - } - }; - return ReInviteUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.ReInviteUserAgentClient = ReInviteUserAgentClient; - - -/***/ }), -/* 52 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * Re-INVITE UAS. - * @remarks - * 14 Modifying an Existing Session - * https://tools.ietf.org/html/rfc3261#section-14 - * 14.2 UAS Behavior - * https://tools.ietf.org/html/rfc3261#section-14.2 - * @public - */ -var ReInviteUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(ReInviteUserAgentServer, _super); - function ReInviteUserAgentServer(dialog, message, delegate) { - var _this = _super.call(this, transactions_1.InviteServerTransaction, dialog.userAgentCore, message, delegate) || this; - dialog.reinviteUserAgentServer = _this; - _this.dialog = dialog; - return _this; - } - /** - * Update the dialog signaling state on a 2xx response. - * @param options - Options bucket. - */ - ReInviteUserAgentServer.prototype.accept = function (options) { - if (options === void 0) { options = { statusCode: 200 }; } - // FIXME: The next two lines SHOULD go away, but I suppose it's technically harmless... - // These are here because some versions of SIP.js prior to 0.13.8 set the route set - // of all in dialog ACKs based on the Record-Route headers in the associated 2xx - // response. While this worked for dialog forming 2xx responses, it was technically - // broken for re-INVITE ACKS as it only worked if the UAS populated the Record-Route - // headers in the re-INVITE 2xx response (which is not required and a waste of bandwidth - // as the should be ignored if present in re-INVITE ACKS) and the UAS populated - // the Record-Route headers with the correct values (would be weird not too, but...). - // Anyway, for now the technically useless Record-Route headers are being added - // to maintain "backwards compatibility" with the older broken versions of SIP.js. - options.extraHeaders = options.extraHeaders || []; - options.extraHeaders = options.extraHeaders.concat(this.dialog.routeSet.map(function (route) { return "Record-Route: " + route; })); - // Send and return the response - var response = _super.prototype.accept.call(this, options); - var session = this.dialog; - var result = tslib_1.__assign({}, response, { session: session }); - if (options.body) { - // Update dialog signaling state with offer/answer in body - this.dialog.signalingStateTransition(options.body); - } - // Update dialog - this.dialog.reConfirm(); - return result; - }; - /** - * Update the dialog signaling state on a 1xx response. - * @param options - Progress options bucket. - */ - ReInviteUserAgentServer.prototype.progress = function (options) { - if (options === void 0) { options = { statusCode: 180 }; } - // Send and return the response - var response = _super.prototype.progress.call(this, options); - var session = this.dialog; - var result = tslib_1.__assign({}, response, { session: session }); - // Update dialog signaling state - if (options.body) { - this.dialog.signalingStateTransition(options.body); - } - return result; - }; - /** - * TODO: Not Yet Supported - * @param contacts - Contacts to redirect to. - * @param options - Redirect options bucket. - */ - ReInviteUserAgentServer.prototype.redirect = function (contacts, options) { - if (options === void 0) { options = { statusCode: 302 }; } - this.dialog.signalingStateRollback(); - this.dialog.reinviteUserAgentServer = undefined; // ACK will be handled by transaction - throw new Error("Unimplemented."); - }; - /** - * 3.1 Background on Re-INVITE Handling by UASs - * An error response to a re-INVITE has the following semantics. As - * specified in Section 12.2.2 of RFC 3261 [RFC3261], if a re-INVITE is - * rejected, no state changes are performed. - * https://tools.ietf.org/html/rfc6141#section-3.1 - * @param options - Reject options bucket. - */ - ReInviteUserAgentServer.prototype.reject = function (options) { - if (options === void 0) { options = { statusCode: 488 }; } - this.dialog.signalingStateRollback(); - this.dialog.reinviteUserAgentServer = undefined; // ACK will be handled by transaction - return _super.prototype.reject.call(this, options); - }; - return ReInviteUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.ReInviteUserAgentServer = ReInviteUserAgentServer; - - -/***/ }), -/* 53 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * REFER UAC. - * @public - */ -var ReferUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(ReferUserAgentClient, _super); - function ReferUserAgentClient(dialog, delegate, options) { - var _this = this; - var message = dialog.createOutgoingRequestMessage(messages_1.C.REFER, options); - _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; - return _this; - } - return ReferUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.ReferUserAgentClient = ReferUserAgentClient; - - -/***/ }), -/* 54 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * REFER UAS. - * @public - */ -var ReferUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(ReferUserAgentServer, _super); - /** - * REFER UAS constructor. - * @param dialogOrCore - Dialog for in dialog REFER, UserAgentCore for out of dialog REFER. - * @param message - Incoming REFER request message. - */ - function ReferUserAgentServer(dialogOrCore, message, delegate) { - var _this = this; - var userAgentCore = instanceOfSessionDialog(dialogOrCore) ? - dialogOrCore.userAgentCore : - dialogOrCore; - _this = _super.call(this, transactions_1.NonInviteServerTransaction, userAgentCore, message, delegate) || this; - return _this; - } - return ReferUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.ReferUserAgentServer = ReferUserAgentServer; -function instanceOfSessionDialog(object) { - return object.userAgentCore !== undefined; -} - - -/***/ }), -/* 55 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var subscription_1 = __webpack_require__(56); -var timers_1 = __webpack_require__(26); -var allowed_methods_1 = __webpack_require__(58); -var notify_user_agent_server_1 = __webpack_require__(48); -var re_subscribe_user_agent_client_1 = __webpack_require__(59); -var dialog_1 = __webpack_require__(4); -/** - * Subscription Dialog. - * @remarks - * SIP-Specific Event Notification - * - * Abstract - * - * This document describes an extension to the Session Initiation - * Protocol (SIP) defined by RFC 3261. The purpose of this extension is - * to provide an extensible framework by which SIP nodes can request - * notification from remote nodes indicating that certain events have - * occurred. - * - * Note that the event notification mechanisms defined herein are NOT - * intended to be a general-purpose infrastructure for all classes of - * event subscription and notification. - * - * This document represents a backwards-compatible improvement on the - * original mechanism described by RFC 3265, taking into account several - * years of implementation experience. Accordingly, this document - * obsoletes RFC 3265. This document also updates RFC 4660 slightly to - * accommodate some small changes to the mechanism that were discussed - * in that document. - * - * https://tools.ietf.org/html/rfc6665 - * @public - */ -var SubscriptionDialog = /** @class */ (function (_super) { - tslib_1.__extends(SubscriptionDialog, _super); - function SubscriptionDialog(subscriptionEvent, subscriptionExpires, subscriptionState, core, state, delegate) { - var _this = _super.call(this, core, state) || this; - _this.delegate = delegate; - _this._autoRefresh = false; - _this._subscriptionEvent = subscriptionEvent; - _this._subscriptionExpires = subscriptionExpires; - _this._subscriptionExpiresInitial = subscriptionExpires; - _this._subscriptionExpiresLastSet = Math.floor(Date.now() / 1000); - _this._subscriptionRefresh = undefined; - _this._subscriptionRefreshLastSet = undefined; - _this._subscriptionState = subscriptionState; - _this.logger = core.loggerFactory.getLogger("sip.subscribe-dialog"); - _this.logger.log("SUBSCRIBE dialog " + _this.id + " constructed"); - return _this; - } - /** - * When a UAC receives a response that establishes a dialog, it - * constructs the state of the dialog. This state MUST be maintained - * for the duration of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.1.2 - * @param outgoingRequestMessage - Outgoing request message for dialog. - * @param incomingResponseMessage - Incoming response message creating dialog. - */ - SubscriptionDialog.initialDialogStateForSubscription = function (outgoingSubscribeRequestMessage, incomingNotifyRequestMessage) { - // If the request was sent over TLS, and the Request-URI contained a - // SIPS URI, the "secure" flag is set to TRUE. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - var secure = false; // FIXME: Currently no support for TLS. - // The route set MUST be set to the list of URIs in the Record-Route - // header field from the response, taken in reverse order and preserving - // all URI parameters. If no Record-Route header field is present in - // the response, the route set MUST be set to the empty set. This route - // set, even if empty, overrides any pre-existing route set for future - // requests in this dialog. The remote target MUST be set to the URI - // from the Contact header field of the response. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - var routeSet = incomingNotifyRequestMessage.getHeaders("record-route"); - var contact = incomingNotifyRequestMessage.parseHeader("contact"); - if (!contact) { // TODO: Review to make sure this will never happen - throw new Error("Contact undefined."); - } - if (!(contact instanceof messages_1.NameAddrHeader)) { - throw new Error("Contact not instance of NameAddrHeader."); - } - var remoteTarget = contact.uri; - // The local sequence number MUST be set to the value of the sequence - // number in the CSeq header field of the request. The remote sequence - // number MUST be empty (it is established when the remote UA sends a - // request within the dialog). The call identifier component of the - // dialog ID MUST be set to the value of the Call-ID in the request. - // The local tag component of the dialog ID MUST be set to the tag in - // the From field in the request, and the remote tag component of the - // dialog ID MUST be set to the tag in the To field of the response. A - // UAC MUST be prepared to receive a response without a tag in the To - // field, in which case the tag is considered to have a value of null. - // - // This is to maintain backwards compatibility with RFC 2543, which - // did not mandate To tags. - // - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - var localSequenceNumber = outgoingSubscribeRequestMessage.cseq; - var remoteSequenceNumber = undefined; - var callId = outgoingSubscribeRequestMessage.callId; - var localTag = outgoingSubscribeRequestMessage.fromTag; - var remoteTag = incomingNotifyRequestMessage.fromTag; - if (!callId) { // TODO: Review to make sure this will never happen - throw new Error("Call id undefined."); - } - if (!localTag) { // TODO: Review to make sure this will never happen - throw new Error("From tag undefined."); - } - if (!remoteTag) { // TODO: Review to make sure this will never happen - throw new Error("To tag undefined."); // FIXME: No backwards compatibility with RFC 2543 - } - // The remote URI MUST be set to the URI in the To field, and the local - // URI MUST be set to the URI in the From field. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - if (!outgoingSubscribeRequestMessage.from) { // TODO: Review to make sure this will never happen - throw new Error("From undefined."); - } - if (!outgoingSubscribeRequestMessage.to) { // TODO: Review to make sure this will never happen - throw new Error("To undefined."); - } - var localURI = outgoingSubscribeRequestMessage.from.uri; - var remoteURI = outgoingSubscribeRequestMessage.to.uri; - // A dialog can also be in the "early" state, which occurs when it is - // created with a provisional response, and then transition to the - // "confirmed" state when a 2xx final response arrives. - // https://tools.ietf.org/html/rfc3261#section-12 - var early = false; - var dialogState = { - id: callId + localTag + remoteTag, - early: early, - callId: callId, - localTag: localTag, - remoteTag: remoteTag, - localSequenceNumber: localSequenceNumber, - remoteSequenceNumber: remoteSequenceNumber, - localURI: localURI, - remoteURI: remoteURI, - remoteTarget: remoteTarget, - routeSet: routeSet, - secure: secure - }; - return dialogState; - }; - SubscriptionDialog.prototype.dispose = function () { - _super.prototype.dispose.call(this); - if (this.N) { - clearTimeout(this.N); - this.N = undefined; - } - this.refreshTimerClear(); - this.logger.log("SUBSCRIBE dialog " + this.id + " destroyed"); - }; - Object.defineProperty(SubscriptionDialog.prototype, "autoRefresh", { - get: function () { - return this._autoRefresh; - }, - set: function (autoRefresh) { - this._autoRefresh = true; - this.refreshTimerSet(); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SubscriptionDialog.prototype, "subscriptionEvent", { - get: function () { - return this._subscriptionEvent; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SubscriptionDialog.prototype, "subscriptionExpires", { - /** Number of seconds until subscription expires. */ - get: function () { - var secondsSinceLastSet = Math.floor(Date.now() / 1000) - this._subscriptionExpiresLastSet; - var secondsUntilExpires = this._subscriptionExpires - secondsSinceLastSet; - return Math.max(secondsUntilExpires, 0); - }, - set: function (expires) { - if (expires < 0) { - throw new Error("Expires must be greater than or equal to zero."); - } - this._subscriptionExpires = expires; - this._subscriptionExpiresLastSet = Math.floor(Date.now() / 1000); - if (this.autoRefresh) { - var refresh = this.subscriptionRefresh; - if (refresh === undefined || refresh >= expires) { - this.refreshTimerSet(); - } - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SubscriptionDialog.prototype, "subscriptionExpiresInitial", { - get: function () { - return this._subscriptionExpiresInitial; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SubscriptionDialog.prototype, "subscriptionRefresh", { - /** Number of seconds until subscription auto refresh. */ - get: function () { - if (this._subscriptionRefresh === undefined || this._subscriptionRefreshLastSet === undefined) { - return undefined; - } - var secondsSinceLastSet = Math.floor(Date.now() / 1000) - this._subscriptionRefreshLastSet; - var secondsUntilExpires = this._subscriptionRefresh - secondsSinceLastSet; - return Math.max(secondsUntilExpires, 0); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SubscriptionDialog.prototype, "subscriptionState", { - get: function () { - return this._subscriptionState; - }, - enumerable: true, - configurable: true - }); - /** - * Receive in dialog request message from transport. - * @param message - The incoming request message. - */ - SubscriptionDialog.prototype.receiveRequest = function (message) { - this.logger.log("SUBSCRIBE dialog " + this.id + " received " + message.method + " request"); - // Request within a dialog out of sequence guard. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (!this.sequenceGuard(message)) { - this.logger.log("SUBSCRIBE dialog " + this.id + " rejected out of order " + message.method + " request."); - return; - } - // Request within a dialog common processing. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - _super.prototype.receiveRequest.call(this, message); - // Switch on method and then delegate. - switch (message.method) { - case messages_1.C.NOTIFY: - this.onNotify(message); - break; - default: - this.logger.log("SUBSCRIBE dialog " + this.id + " received unimplemented " + message.method + " request"); - this.core.replyStateless(message, { statusCode: 501 }); - break; - } - }; - /** - * 4.1.2.2. Refreshing of Subscriptions - * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - */ - SubscriptionDialog.prototype.refresh = function () { - var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); - var options = {}; - options.extraHeaders = (options.extraHeaders || []).slice(); - options.extraHeaders.push(allowHeader); - options.extraHeaders.push("Event: " + this.subscriptionEvent); - options.extraHeaders.push("Expires: " + this.subscriptionExpiresInitial); - options.extraHeaders.push("Contact: " + this.core.configuration.contact.toString()); - return this.subscribe(undefined, options); - }; - /** - * 4.1.2.2. Refreshing of Subscriptions - * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - * @param delegate - Delegate to handle responses. - * @param options - Options bucket. - */ - SubscriptionDialog.prototype.subscribe = function (delegate, options) { - var _this = this; - if (options === void 0) { options = {}; } - if (this.subscriptionState !== subscription_1.SubscriptionState.Pending && this.subscriptionState !== subscription_1.SubscriptionState.Active) { - // FIXME: This needs to be a proper exception - throw new Error("Invalid state " + this.subscriptionState + ". May only re-subscribe while in state \"pending\" or \"active\"."); - } - this.logger.log("SUBSCRIBE dialog " + this.id + " sending SUBSCRIBE request"); - var uac = new re_subscribe_user_agent_client_1.ReSubscribeUserAgentClient(this, delegate, options); - // When refreshing a subscription, a subscriber starts Timer N, set to - // 64*T1, when it sends the SUBSCRIBE request. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - this.N = setTimeout(function () { return _this.timer_N(); }, timers_1.Timers.TIMER_N); - return uac; - }; - /** - * 4.4.1. Dialog Creation and Termination - * A subscription is destroyed after a notifier sends a NOTIFY request - * with a "Subscription-State" of "terminated", or in certain error - * situations described elsewhere in this document. - * https://tools.ietf.org/html/rfc6665#section-4.4.1 - */ - SubscriptionDialog.prototype.terminate = function () { - this.stateTransition(subscription_1.SubscriptionState.Terminated); - this.onTerminated(); - }; - /** - * 4.1.2.3. Unsubscribing - * https://tools.ietf.org/html/rfc6665#section-4.1.2.3 - */ - SubscriptionDialog.prototype.unsubscribe = function () { - var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); - var options = {}; - options.extraHeaders = (options.extraHeaders || []).slice(); - options.extraHeaders.push(allowHeader); - options.extraHeaders.push("Event: " + this.subscriptionEvent); - options.extraHeaders.push("Expires: 0"); - options.extraHeaders.push("Contact: " + this.core.configuration.contact.toString()); - return this.subscribe(undefined, options); - }; - /** - * Handle in dialog NOTIFY requests. - * This does not include the first NOTIFY which created the dialog. - * @param message - The incoming NOTIFY request message. - */ - SubscriptionDialog.prototype.onNotify = function (message) { - // If, for some reason, the event package designated in the "Event" - // header field of the NOTIFY request is not supported, the subscriber - // will respond with a 489 (Bad Event) response. - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - var event = message.parseHeader("Event").event; - if (!event || event !== this.subscriptionEvent) { - this.core.replyStateless(message, { statusCode: 489 }); - return; - } - // In the state diagram, "Re-subscription times out" means that an - // attempt to refresh or update the subscription using a new SUBSCRIBE - // request does not result in a NOTIFY request before the corresponding - // Timer N expires. - // https://tools.ietf.org/html/rfc6665#section-4.1.2 - if (this.N) { - clearTimeout(this.N); - this.N = undefined; - } - // NOTIFY requests MUST contain "Subscription-State" header fields that - // indicate the status of the subscription. - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - var subscriptionState = message.parseHeader("Subscription-State"); - if (!subscriptionState || !subscriptionState.state) { - this.core.replyStateless(message, { statusCode: 489 }); - return; - } - var state = subscriptionState.state; - var expires = subscriptionState.expires ? Math.max(subscriptionState.expires, 0) : undefined; - // Update our state and expiration. - switch (state) { - case "pending": - this.stateTransition(subscription_1.SubscriptionState.Pending, expires); - break; - case "active": - this.stateTransition(subscription_1.SubscriptionState.Active, expires); - break; - case "terminated": - this.stateTransition(subscription_1.SubscriptionState.Terminated, expires); - break; - default: - this.logger.warn("Unrecognized subscription state."); - break; - } - // Delegate remainder of NOTIFY handling. - var uas = new notify_user_agent_server_1.NotifyUserAgentServer(this, message); - if (this.delegate && this.delegate.onNotify) { - this.delegate.onNotify(uas); - } - else { - uas.accept(); - } - }; - SubscriptionDialog.prototype.onRefresh = function (request) { - if (this.delegate && this.delegate.onRefresh) { - this.delegate.onRefresh(request); - } - }; - SubscriptionDialog.prototype.onTerminated = function () { - if (this.delegate && this.delegate.onTerminated) { - this.delegate.onTerminated(); - } - }; - SubscriptionDialog.prototype.refreshTimerClear = function () { - if (this.refreshTimer) { - clearTimeout(this.refreshTimer); - this.refreshTimer = undefined; - } - }; - SubscriptionDialog.prototype.refreshTimerSet = function () { - var _this = this; - this.refreshTimerClear(); - if (this.autoRefresh && this.subscriptionExpires > 0) { - var refresh = this.subscriptionExpires * 900; - this._subscriptionRefresh = Math.floor(refresh / 1000); - this._subscriptionRefreshLastSet = Math.floor(Date.now() / 1000); - this.refreshTimer = setTimeout(function () { - _this.refreshTimer = undefined; - _this._subscriptionRefresh = undefined; - _this._subscriptionRefreshLastSet = undefined; - _this.onRefresh(_this.refresh()); - }, refresh); - } - }; - SubscriptionDialog.prototype.stateTransition = function (newState, newExpires) { - var _this = this; - // Assert valid state transitions. - var invalidStateTransition = function () { - _this.logger.warn("Invalid subscription state transition from " + _this.subscriptionState + " to " + newState); - }; - switch (newState) { - case subscription_1.SubscriptionState.Initial: - invalidStateTransition(); - return; - case subscription_1.SubscriptionState.NotifyWait: - invalidStateTransition(); - return; - case subscription_1.SubscriptionState.Pending: - if (this.subscriptionState !== subscription_1.SubscriptionState.NotifyWait && - this.subscriptionState !== subscription_1.SubscriptionState.Pending) { - invalidStateTransition(); - return; - } - break; - case subscription_1.SubscriptionState.Active: - if (this.subscriptionState !== subscription_1.SubscriptionState.NotifyWait && - this.subscriptionState !== subscription_1.SubscriptionState.Pending && - this.subscriptionState !== subscription_1.SubscriptionState.Active) { - invalidStateTransition(); - return; - } - break; - case subscription_1.SubscriptionState.Terminated: - if (this.subscriptionState !== subscription_1.SubscriptionState.NotifyWait && - this.subscriptionState !== subscription_1.SubscriptionState.Pending && - this.subscriptionState !== subscription_1.SubscriptionState.Active) { - invalidStateTransition(); - return; - } - break; - default: - invalidStateTransition(); - return; - } - // If the "Subscription-State" value is "pending", the subscription has - // been received by the notifier, but there is insufficient policy - // information to grant or deny the subscription yet. If the header - // field also contains an "expires" parameter, the subscriber SHOULD - // take it as the authoritative subscription duration and adjust - // accordingly. No further action is necessary on the part of the - // subscriber. The "retry-after" and "reason" parameters have no - // semantics for "pending". - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - if (newState === subscription_1.SubscriptionState.Pending) { - if (newExpires) { - this.subscriptionExpires = newExpires; - } - } - // If the "Subscription-State" header field value is "active", it means - // that the subscription has been accepted and (in general) has been - // authorized. If the header field also contains an "expires" - // parameter, the subscriber SHOULD take it as the authoritative - // subscription duration and adjust accordingly. The "retry-after" and - // "reason" parameters have no semantics for "active". - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - if (newState === subscription_1.SubscriptionState.Active) { - if (newExpires) { - this.subscriptionExpires = newExpires; - } - } - // If the "Subscription-State" value is "terminated", the subscriber - // MUST consider the subscription terminated. The "expires" parameter - // has no semantics for "terminated" -- notifiers SHOULD NOT include an - // "expires" parameter on a "Subscription-State" header field with a - // value of "terminated", and subscribers MUST ignore any such - // parameter, if present. - if (newState === subscription_1.SubscriptionState.Terminated) { - this.dispose(); - } - this._subscriptionState = newState; - }; - /** - * When refreshing a subscription, a subscriber starts Timer N, set to - * 64*T1, when it sends the SUBSCRIBE request. If this Timer N expires - * prior to the receipt of a NOTIFY request, the subscriber considers - * the subscription terminated. If the subscriber receives a success - * response to the SUBSCRIBE request that indicates that no NOTIFY - * request will be generated -- such as the 204 response defined for use - * with the optional extension described in [RFC5839] -- then it MUST - * cancel Timer N. - * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - */ - SubscriptionDialog.prototype.timer_N = function () { - if (this.subscriptionState !== subscription_1.SubscriptionState.Terminated) { - this.stateTransition(subscription_1.SubscriptionState.Terminated); - this.onTerminated(); - } - }; - return SubscriptionDialog; -}(dialog_1.Dialog)); -exports.SubscriptionDialog = SubscriptionDialog; - - -/***/ }), -/* 56 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -tslib_1.__exportStar(__webpack_require__(57), exports); - - -/***/ }), -/* 57 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * Subscription state. - * @remarks - * https://tools.ietf.org/html/rfc6665#section-4.1.2 - * @public - */ -var SubscriptionState; -(function (SubscriptionState) { - SubscriptionState["Initial"] = "Initial"; - SubscriptionState["NotifyWait"] = "NotifyWait"; - SubscriptionState["Pending"] = "Pending"; - SubscriptionState["Active"] = "Active"; - SubscriptionState["Terminated"] = "Terminated"; -})(SubscriptionState = exports.SubscriptionState || (exports.SubscriptionState = {})); - - -/***/ }), -/* 58 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var messages_1 = __webpack_require__(5); -/** - * FIXME: TODO: Should be configurable/variable. - */ -exports.AllowedMethods = [ - messages_1.C.ACK, - messages_1.C.BYE, - messages_1.C.CANCEL, - messages_1.C.INFO, - messages_1.C.INVITE, - messages_1.C.MESSAGE, - messages_1.C.NOTIFY, - messages_1.C.OPTIONS, - messages_1.C.PRACK, - messages_1.C.REFER, - messages_1.C.REGISTER, - messages_1.C.SUBSCRIBE -]; - - -/***/ }), -/* 59 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * Re-SUBSCRIBE UAC. - * @public - */ -var ReSubscribeUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(ReSubscribeUserAgentClient, _super); - function ReSubscribeUserAgentClient(dialog, delegate, options) { - var _this = this; - var message = dialog.createOutgoingRequestMessage(messages_1.C.SUBSCRIBE, options); - _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; - _this.dialog = dialog; - return _this; - } - ReSubscribeUserAgentClient.prototype.waitNotifyStop = function () { - // TODO: Placeholder. Not utilized currently. - return; - }; - /** - * Receive a response from the transaction layer. - * @param message - Incoming response message. - */ - ReSubscribeUserAgentClient.prototype.receiveResponse = function (message) { - if (message.statusCode && message.statusCode >= 200 && message.statusCode < 300) { - // The "Expires" header field in a 200-class response to SUBSCRIBE - // request indicates the actual duration for which the subscription will - // remain active (unless refreshed). The received value might be - // smaller than the value indicated in the SUBSCRIBE request but cannot - // be larger; see Section 4.2.1 for details. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - var expires = message.getHeader("Expires"); - if (!expires) { - this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE"); - } - else { - var subscriptionExpiresReceived = Number(expires); - if (this.dialog.subscriptionExpires > subscriptionExpiresReceived) { - this.dialog.subscriptionExpires = subscriptionExpiresReceived; - } - } - } - if (message.statusCode && message.statusCode >= 400 && message.statusCode < 700) { - // If a SUBSCRIBE request to refresh a subscription receives a 404, 405, - // 410, 416, 480-485, 489, 501, or 604 response, the subscriber MUST - // consider the subscription terminated. (See [RFC5057] for further - // details and notes about the effect of error codes on dialogs and - // usages within dialog, such as subscriptions). If the subscriber - // wishes to re-subscribe to the state, he does so by composing an - // unrelated initial SUBSCRIBE request with a freshly generated Call-ID - // and a new, unique "From" tag (see Section 4.1.2.1). - // https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - var errorCodes = [404, 405, 410, 416, 480, 481, 482, 483, 484, 485, 489, 501, 604]; - if (errorCodes.includes(message.statusCode)) { - this.dialog.terminate(); - } - // If a SUBSCRIBE request to refresh a subscription fails with any error - // code other than those listed above, the original subscription is - // still considered valid for the duration of the most recently known - // "Expires" value as negotiated by the most recent successful SUBSCRIBE - // transaction, or as communicated by a NOTIFY request in its - // "Subscription-State" header field "expires" parameter. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - } - _super.prototype.receiveResponse.call(this, message); - }; - return ReSubscribeUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.ReSubscribeUserAgentClient = ReSubscribeUserAgentClient; - - -/***/ }), -/* 60 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -tslib_1.__exportStar(__webpack_require__(61), exports); -tslib_1.__exportStar(__webpack_require__(62), exports); -tslib_1.__exportStar(__webpack_require__(63), exports); - - -/***/ }), -/* 61 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * Log levels. - * @public - */ -var Levels; -(function (Levels) { - Levels[Levels["error"] = 0] = "error"; - Levels[Levels["warn"] = 1] = "warn"; - Levels[Levels["log"] = 2] = "log"; - Levels[Levels["debug"] = 3] = "debug"; -})(Levels = exports.Levels || (exports.Levels = {})); - - -/***/ }), -/* 62 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var levels_1 = __webpack_require__(61); -var logger_1 = __webpack_require__(63); -/** - * Logger. - * @public - */ -var LoggerFactory = /** @class */ (function () { - function LoggerFactory() { - this.builtinEnabled = true; - this._level = levels_1.Levels.log; - this.loggers = {}; - this.logger = this.getLogger("sip:loggerfactory"); - } - Object.defineProperty(LoggerFactory.prototype, "level", { - get: function () { return this._level; }, - set: function (newLevel) { - if (newLevel >= 0 && newLevel <= 3) { - this._level = newLevel; - } - else if (newLevel > 3) { - this._level = 3; - } - else if (levels_1.Levels.hasOwnProperty(newLevel)) { - this._level = newLevel; - } - else { - this.logger.error("invalid 'level' parameter value: " + JSON.stringify(newLevel)); - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(LoggerFactory.prototype, "connector", { - get: function () { - return this._connector; - }, - set: function (value) { - if (!value) { - this._connector = undefined; - } - else if (typeof value === "function") { - this._connector = value; - } - else { - this.logger.error("invalid 'connector' parameter value: " + JSON.stringify(value)); - } - }, - enumerable: true, - configurable: true - }); - LoggerFactory.prototype.getLogger = function (category, label) { - if (label && this.level === 3) { - return new logger_1.Logger(this, category, label); - } - else if (this.loggers[category]) { - return this.loggers[category]; - } - else { - var logger = new logger_1.Logger(this, category); - this.loggers[category] = logger; - return logger; - } - }; - LoggerFactory.prototype.genericLog = function (levelToLog, category, label, content) { - if (this.level >= levelToLog) { - if (this.builtinEnabled) { - this.print(levelToLog, category, label, content); - } - } - if (this.connector) { - this.connector(levels_1.Levels[levelToLog], category, label, content); - } - }; - LoggerFactory.prototype.print = function (levelToLog, category, label, content) { - if (typeof content === "string") { - var prefix = [new Date(), category]; - if (label) { - prefix.push(label); - } - content = prefix.concat(content).join(" | "); - } - switch (levelToLog) { - case levels_1.Levels.error: - // tslint:disable-next-line:no-console - console.error(content); - break; - case levels_1.Levels.warn: - // tslint:disable-next-line:no-console - console.warn(content); - break; - case levels_1.Levels.log: - // tslint:disable-next-line:no-console - console.log(content); - break; - case levels_1.Levels.debug: - // tslint:disable-next-line:no-console - console.debug(content); - break; - default: - break; - } - }; - return LoggerFactory; -}()); -exports.LoggerFactory = LoggerFactory; - - -/***/ }), -/* 63 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var levels_1 = __webpack_require__(61); -/** - * Logger. - * @public - */ -var Logger = /** @class */ (function () { - function Logger(logger, category, label) { - this.logger = logger; - this.category = category; - this.label = label; - } - Logger.prototype.error = function (content) { this.genericLog(levels_1.Levels.error, content); }; - Logger.prototype.warn = function (content) { this.genericLog(levels_1.Levels.warn, content); }; - Logger.prototype.log = function (content) { this.genericLog(levels_1.Levels.log, content); }; - Logger.prototype.debug = function (content) { this.genericLog(levels_1.Levels.debug, content); }; - Logger.prototype.genericLog = function (level, content) { - this.logger.genericLog(level, this.category, this.label, content); - }; - return Logger; -}()); -exports.Logger = Logger; - - -/***/ }), -/* 64 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -tslib_1.__exportStar(__webpack_require__(65), exports); - - -/***/ }), -/* 65 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var transactions_1 = __webpack_require__(27); -var user_agents_1 = __webpack_require__(66); -var allowed_methods_1 = __webpack_require__(58); -/** - * This is ported from UA.C.ACCEPTED_BODY_TYPES. - * FIXME: TODO: Should be configurable/variable. - */ -var acceptedBodyTypes = [ - "application/sdp", - "application/dtmf-relay" -]; -/** - * User Agent Core. - * @remarks - * Core designates the functions specific to a particular type - * of SIP entity, i.e., specific to either a stateful or stateless - * proxy, a user agent or registrar. All cores, except those for - * the stateless proxy, are transaction users. - * https://tools.ietf.org/html/rfc3261#section-6 - * - * UAC Core: The set of processing functions required of a UAC that - * reside above the transaction and transport layers. - * https://tools.ietf.org/html/rfc3261#section-6 - * - * UAS Core: The set of processing functions required at a UAS that - * resides above the transaction and transport layers. - * https://tools.ietf.org/html/rfc3261#section-6 - * @public - */ -var UserAgentCore = /** @class */ (function () { - /** - * Constructor. - * @param configuration - Configuration. - * @param delegate - Delegate. - */ - function UserAgentCore(configuration, delegate) { - if (delegate === void 0) { delegate = {}; } - /** UACs. */ - this.userAgentClients = new Map(); - /** UASs. */ - this.userAgentServers = new Map(); - this.configuration = configuration; - this.delegate = delegate; - this.dialogs = new Map(); - this.subscribers = new Map(); - this.logger = configuration.loggerFactory.getLogger("sip.user-agent-core"); - } - /** Destructor. */ - UserAgentCore.prototype.dispose = function () { - this.reset(); - }; - /** Reset. */ - UserAgentCore.prototype.reset = function () { - this.dialogs.forEach(function (dialog) { return dialog.dispose(); }); - this.dialogs.clear(); - this.subscribers.forEach(function (subscriber) { return subscriber.dispose(); }); - this.subscribers.clear(); - this.userAgentClients.forEach(function (uac) { return uac.dispose(); }); - this.userAgentClients.clear(); - this.userAgentServers.forEach(function (uac) { return uac.dispose(); }); - this.userAgentServers.clear(); - }; - Object.defineProperty(UserAgentCore.prototype, "loggerFactory", { - /** Logger factory. */ - get: function () { - return this.configuration.loggerFactory; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(UserAgentCore.prototype, "transport", { - /** Transport. */ - get: function () { - var transport = this.configuration.transportAccessor(); - if (!transport) { - throw new Error("Transport undefined."); - } - return transport; - }, - enumerable: true, - configurable: true - }); - /** - * Send INVITE. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - UserAgentCore.prototype.invite = function (request, delegate) { - return new user_agents_1.InviteUserAgentClient(this, request, delegate); - }; - /** - * Send MESSAGE. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - UserAgentCore.prototype.message = function (request, delegate) { - return new user_agents_1.MessageUserAgentClient(this, request, delegate); - }; - /** - * Send PUBLISH. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - UserAgentCore.prototype.publish = function (request, delegate) { - return new user_agents_1.PublishUserAgentClient(this, request, delegate); - }; - /** - * Send REGISTER. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - UserAgentCore.prototype.register = function (request, delegate) { - return new user_agents_1.RegisterUserAgentClient(this, request, delegate); - }; - /** - * Send SUBSCRIBE. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - UserAgentCore.prototype.subscribe = function (request, delegate) { - return new user_agents_1.SubscribeUserAgentClient(this, request, delegate); - }; - /** - * Send a request. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - UserAgentCore.prototype.request = function (request, delegate) { - return new user_agents_1.UserAgentClient(transactions_1.NonInviteClientTransaction, this, request, delegate); - }; - /** - * Outgoing request message factory function. - * @param method - Method. - * @param requestURI - Request-URI. - * @param fromURI - From URI. - * @param toURI - To URI. - * @param options - Request options. - * @param extraHeaders - Extra headers to add. - * @param body - Message body. - */ - UserAgentCore.prototype.makeOutgoingRequestMessage = function (method, requestURI, fromURI, toURI, options, extraHeaders, body) { - // default values from user agent configuration - var callIdPrefix = this.configuration.sipjsId; - var fromDisplayName = this.configuration.displayName; - var forceRport = this.configuration.viaForceRport; - var hackViaTcp = this.configuration.hackViaTcp; - var optionTags = this.configuration.supportedOptionTags.slice(); - if (method === messages_1.C.REGISTER) { - optionTags.push("path", "gruu"); - } - if (method === messages_1.C.INVITE && (this.configuration.contact.pubGruu || this.configuration.contact.tempGruu)) { - optionTags.push("gruu"); - } - var routeSet = this.configuration.routeSet; - var userAgentString = this.configuration.userAgentHeaderFieldValue; - var viaHost = this.configuration.viaHost; - var defaultOptions = { - callIdPrefix: callIdPrefix, - forceRport: forceRport, - fromDisplayName: fromDisplayName, - hackViaTcp: hackViaTcp, - optionTags: optionTags, - routeSet: routeSet, - userAgentString: userAgentString, - viaHost: viaHost, - }; - // merge provided options with default options - var requestOptions = tslib_1.__assign({}, defaultOptions, options); - return new messages_1.OutgoingRequestMessage(method, requestURI, fromURI, toURI, requestOptions, extraHeaders, body); - }; - /** - * Handle an incoming request message from the transport. - * @param message - Incoming request message from transport layer. - */ - UserAgentCore.prototype.receiveIncomingRequestFromTransport = function (message) { - this.receiveRequestFromTransport(message); - }; - /** - * Handle an incoming response message from the transport. - * @param message - Incoming response message from transport layer. - */ - UserAgentCore.prototype.receiveIncomingResponseFromTransport = function (message) { - this.receiveResponseFromTransport(message); - }; - /** - * A stateless UAS is a UAS that does not maintain transaction state. - * It replies to requests normally, but discards any state that would - * ordinarily be retained by a UAS after a response has been sent. If a - * stateless UAS receives a retransmission of a request, it regenerates - * the response and re-sends it, just as if it were replying to the first - * instance of the request. A UAS cannot be stateless unless the request - * processing for that method would always result in the same response - * if the requests are identical. This rules out stateless registrars, - * for example. Stateless UASs do not use a transaction layer; they - * receive requests directly from the transport layer and send responses - * directly to the transport layer. - * https://tools.ietf.org/html/rfc3261#section-8.2.7 - * @param message - Incoming request message to reply to. - * @param statusCode - Status code to reply with. - */ - UserAgentCore.prototype.replyStateless = function (message, options) { - var userAgent = this.configuration.userAgentHeaderFieldValue; - var supported = this.configuration.supportedOptionTagsResponse; - options = tslib_1.__assign({}, options, { userAgent: userAgent, supported: supported }); - var response = messages_1.constructOutgoingResponse(message, options); - this.transport.send(response.message); - return response; - }; - /** - * In Section 18.2.1, replace the last paragraph with: - * - * Next, the server transport attempts to match the request to a - * server transaction. It does so using the matching rules described - * in Section 17.2.3. If a matching server transaction is found, the - * request is passed to that transaction for processing. If no match - * is found, the request is passed to the core, which may decide to - * construct a new server transaction for that request. - * https://tools.ietf.org/html/rfc6026#section-8.10 - * @param message - Incoming request message from transport layer. - */ - UserAgentCore.prototype.receiveRequestFromTransport = function (message) { - // When a request is received from the network by the server, it has to - // be matched to an existing transaction. This is accomplished in the - // following manner. - // - // The branch parameter in the topmost Via header field of the request - // is examined. If it is present and begins with the magic cookie - // "z9hG4bK", the request was generated by a client transaction - // compliant to this specification. Therefore, the branch parameter - // will be unique across all transactions sent by that client. The - // request matches a transaction if: - // - // 1. the branch parameter in the request is equal to the one in the - // top Via header field of the request that created the - // transaction, and - // - // 2. the sent-by value in the top Via of the request is equal to the - // one in the request that created the transaction, and - // - // 3. the method of the request matches the one that created the - // transaction, except for ACK, where the method of the request - // that created the transaction is INVITE. - // - // This matching rule applies to both INVITE and non-INVITE transactions - // alike. - // - // The sent-by value is used as part of the matching process because - // there could be accidental or malicious duplication of branch - // parameters from different clients. - // https://tools.ietf.org/html/rfc3261#section-17.2.3 - var transactionId = message.viaBranch; // FIXME: Currently only using rule 1... - var uas = this.userAgentServers.get(transactionId); - // When receiving an ACK that matches an existing INVITE server - // transaction and that does not contain a branch parameter containing - // the magic cookie defined in RFC 3261, the matching transaction MUST - // be checked to see if it is in the "Accepted" state. If it is, then - // the ACK must be passed directly to the transaction user instead of - // being absorbed by the transaction state machine. This is necessary - // as requests from RFC 2543 clients will not include a unique branch - // parameter, and the mechanisms for calculating the transaction ID from - // such a request will be the same for both INVITE and ACKs. - // https://tools.ietf.org/html/rfc6026#section-6 - // Any ACKs received from the network while in the "Accepted" state MUST be - // passed directly to the TU and not absorbed. - // https://tools.ietf.org/html/rfc6026#section-7.1 - if (message.method === messages_1.C.ACK) { - if (uas && uas.transaction.state === transactions_1.TransactionState.Accepted) { - if (uas instanceof user_agents_1.InviteUserAgentServer) { - // These are ACKs matching an INVITE server transaction. - // These should never happen with RFC 3261 compliant user agents - // (would be a broken ACK to negative final response or something) - // but is apparently how RFC 2543 user agents do things. - // We are not currently supporting this case. - // NOTE: Not backwards compatible with RFC 2543 (no support for strict-routing). - this.logger.warn("Discarding out of dialog ACK after 2xx response sent on transaction " + transactionId + "."); - return; - } - } - } - // The CANCEL method requests that the TU at the server side cancel a - // pending transaction. The TU determines the transaction to be - // cancelled by taking the CANCEL request, and then assuming that the - // request method is anything but CANCEL or ACK and applying the - // transaction matching procedures of Section 17.2.3. The matching - // transaction is the one to be cancelled. - // https://tools.ietf.org/html/rfc3261#section-9.2 - if (message.method === messages_1.C.CANCEL) { - if (uas) { - // Regardless of the method of the original request, as long as the - // CANCEL matched an existing transaction, the UAS answers the CANCEL - // request itself with a 200 (OK) response. - // https://tools.ietf.org/html/rfc3261#section-9.2 - this.replyStateless(message, { statusCode: 200 }); - // If the transaction for the original request still exists, the behavior - // of the UAS on receiving a CANCEL request depends on whether it has already - // sent a final response for the original request. If it has, the CANCEL - // request has no effect on the processing of the original request, no - // effect on any session state, and no effect on the responses generated - // for the original request. If the UAS has not issued a final response - // for the original request, its behavior depends on the method of the - // original request. If the original request was an INVITE, the UAS - // SHOULD immediately respond to the INVITE with a 487 (Request - // Terminated). - // https://tools.ietf.org/html/rfc3261#section-9.2 - if (uas.transaction instanceof transactions_1.InviteServerTransaction && - uas.transaction.state === transactions_1.TransactionState.Proceeding) { - if (uas instanceof user_agents_1.InviteUserAgentServer) { - uas.receiveCancel(message); - } - // A CANCEL request has no impact on the processing of - // transactions with any other method defined in this specification. - // https://tools.ietf.org/html/rfc3261#section-9.2 - } - } - else { - // If the UAS did not find a matching transaction for the CANCEL - // according to the procedure above, it SHOULD respond to the CANCEL - // with a 481 (Call Leg/Transaction Does Not Exist). - // https://tools.ietf.org/html/rfc3261#section-9.2 - this.replyStateless(message, { statusCode: 481 }); - } - return; - } - // If a matching server transaction is found, the request is passed to that - // transaction for processing. - // https://tools.ietf.org/html/rfc6026#section-8.10 - if (uas) { - uas.transaction.receiveRequest(message); - return; - } - // If no match is found, the request is passed to the core, which may decide to - // construct a new server transaction for that request. - // https://tools.ietf.org/html/rfc6026#section-8.10 - this.receiveRequest(message); - return; - }; - /** - * UAC and UAS procedures depend strongly on two factors. First, based - * on whether the request or response is inside or outside of a dialog, - * and second, based on the method of a request. Dialogs are discussed - * thoroughly in Section 12; they represent a peer-to-peer relationship - * between user agents and are established by specific SIP methods, such - * as INVITE. - * @param message - Incoming request message. - */ - UserAgentCore.prototype.receiveRequest = function (message) { - // 8.2 UAS Behavior - // UASs SHOULD process the requests in the order of the steps that - // follow in this section (that is, starting with authentication, then - // inspecting the method, the header fields, and so on throughout the - // remainder of this section). - // https://tools.ietf.org/html/rfc3261#section-8.2 - // 8.2.1 Method Inspection - // Once a request is authenticated (or authentication is skipped), the - // UAS MUST inspect the method of the request. If the UAS recognizes - // but does not support the method of a request, it MUST generate a 405 - // (Method Not Allowed) response. Procedures for generating responses - // are described in Section 8.2.6. The UAS MUST also add an Allow - // header field to the 405 (Method Not Allowed) response. The Allow - // header field MUST list the set of methods supported by the UAS - // generating the message. - // https://tools.ietf.org/html/rfc3261#section-8.2.1 - if (!allowed_methods_1.AllowedMethods.includes(message.method)) { - var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); - this.replyStateless(message, { - statusCode: 405, - extraHeaders: [allowHeader] - }); - return; - } - // 8.2.2 Header Inspection - // https://tools.ietf.org/html/rfc3261#section-8.2.2 - if (!message.ruri) { // FIXME: A request message should always have an ruri - throw new Error("Request-URI undefined."); - } - // 8.2.2.1 To and Request-URI - // If the Request-URI uses a scheme not supported by the UAS, it SHOULD - // reject the request with a 416 (Unsupported URI Scheme) response. - // https://tools.ietf.org/html/rfc3261#section-8.2.2.1 - if (message.ruri.scheme !== "sip") { - this.replyStateless(message, { statusCode: 416 }); - return; - } - // 8.2.2.1 To and Request-URI - // If the Request-URI does not identify an address that the - // UAS is willing to accept requests for, it SHOULD reject - // the request with a 404 (Not Found) response. - // https://tools.ietf.org/html/rfc3261#section-8.2.2.1 - var ruri = message.ruri; - var ruriMatches = function (uri) { - return !!uri && uri.user === ruri.user; - }; - if (!ruriMatches(this.configuration.aor) && - !(ruriMatches(this.configuration.contact.uri) || - ruriMatches(this.configuration.contact.pubGruu) || - ruriMatches(this.configuration.contact.tempGruu))) { - this.logger.warn("Request-URI does not point to us."); - if (message.method !== messages_1.C.ACK) { - this.replyStateless(message, { statusCode: 404 }); - } - return; - } - // 8.2.2.1 To and Request-URI - // Other potential sources of received Request-URIs include - // the Contact header fields of requests and responses sent by the UA - // that establish or refresh dialogs. - // https://tools.ietf.org/html/rfc3261#section-8.2.2.1 - if (message.method === messages_1.C.INVITE) { - if (!message.hasHeader("Contact")) { - this.replyStateless(message, { - statusCode: 400, - reasonPhrase: "Missing Contact Header" - }); - return; - } - } - // 8.2.2.2 Merged Requests - // If the request has no tag in the To header field, the UAS core MUST - // check the request against ongoing transactions. If the From tag, - // Call-ID, and CSeq exactly match those associated with an ongoing - // transaction, but the request does not match that transaction (based - // on the matching rules in Section 17.2.3), the UAS core SHOULD - // generate a 482 (Loop Detected) response and pass it to the server - // transaction. - // - // The same request has arrived at the UAS more than once, following - // different paths, most likely due to forking. The UAS processes - // the first such request received and responds with a 482 (Loop - // Detected) to the rest of them. - // https://tools.ietf.org/html/rfc3261#section-8.2.2.2 - if (!message.toTag) { - var transactionId = message.viaBranch; - if (!this.userAgentServers.has(transactionId)) { - var mergedRequest = Array.from(this.userAgentServers.values()) - .some(function (uas) { - return uas.transaction.request.fromTag === message.fromTag && - uas.transaction.request.callId === message.callId && - uas.transaction.request.cseq === message.cseq; - }); - if (mergedRequest) { - this.replyStateless(message, { statusCode: 482 }); - return; - } - } - } - // 8.2.2.3 Require - // https://tools.ietf.org/html/rfc3261#section-8.2.2.3 - // TODO - // 8.2.3 Content Processing - // https://tools.ietf.org/html/rfc3261#section-8.2.3 - // TODO - // 8.2.4 Applying Extensions - // https://tools.ietf.org/html/rfc3261#section-8.2.4 - // TODO - // 8.2.5 Processing the Request - // Assuming all of the checks in the previous subsections are passed, - // the UAS processing becomes method-specific. - // https://tools.ietf.org/html/rfc3261#section-8.2.5 - // The UAS will receive the request from the transaction layer. If the - // request has a tag in the To header field, the UAS core computes the - // dialog identifier corresponding to the request and compares it with - // existing dialogs. If there is a match, this is a mid-dialog request. - // In that case, the UAS first applies the same processing rules for - // requests outside of a dialog, discussed in Section 8.2. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (message.toTag) { - this.receiveInsideDialogRequest(message); - } - else { - this.receiveOutsideDialogRequest(message); - } - return; - }; - /** - * Once a dialog has been established between two UAs, either of them - * MAY initiate new transactions as needed within the dialog. The UA - * sending the request will take the UAC role for the transaction. The - * UA receiving the request will take the UAS role. Note that these may - * be different roles than the UAs held during the transaction that - * established the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.2 - * @param message - Incoming request message. - */ - UserAgentCore.prototype.receiveInsideDialogRequest = function (message) { - // NOTIFY requests are matched to such SUBSCRIBE requests if they - // contain the same "Call-ID", a "To" header field "tag" parameter that - // matches the "From" header field "tag" parameter of the SUBSCRIBE - // request, and the same "Event" header field. Rules for comparisons of - // the "Event" header fields are described in Section 8.2.1. - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - if (message.method === messages_1.C.NOTIFY) { - var event_1 = message.parseHeader("Event"); - if (!event_1 || !event_1.event) { - this.replyStateless(message, { statusCode: 489 }); - return; - } - // FIXME: Subscriber id should also matching on event id. - var subscriberId = message.callId + message.toTag + event_1.event; - var subscriber = this.subscribers.get(subscriberId); - if (subscriber) { - var uas = new user_agents_1.NotifyUserAgentServer(this, message); - subscriber.onNotify(uas); - return; - } - } - // Requests sent within a dialog, as any other requests, are atomic. If - // a particular request is accepted by the UAS, all the state changes - // associated with it are performed. If the request is rejected, none - // of the state changes are performed. - // - // Note that some requests, such as INVITEs, affect several pieces of - // state. - // - // The UAS will receive the request from the transaction layer. If the - // request has a tag in the To header field, the UAS core computes the - // dialog identifier corresponding to the request and compares it with - // existing dialogs. If there is a match, this is a mid-dialog request. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - var dialogId = message.callId + message.toTag + message.fromTag; - var dialog = this.dialogs.get(dialogId); - if (dialog) { - // [Sip-implementors] Reg. SIP reinvite, UPDATE and OPTIONS - // You got the question right. - // - // And you got the right answer too. :-) - // - // Thanks, - // Paul - // - // Robert Sparks wrote: - // > So I've lost track of the question during the musing. - // > - // > I _think_ the fundamental question being asked is this: - // > - // > Is an endpoint required to reject (with a 481) an OPTIONS request that - // > arrives with at to-tag but does not match any existing dialog state. - // > (Assuming some earlier requirement hasn't forced another error code). Or - // > is it OK if it just sends - // > a 200 OK anyhow. - // > - // > My take on the collection of specs is that its _not_ ok for it to send - // > the 200 OK anyhow and that it is required to send - // > the 481. I base this primarily on these sentences from 11.2 in 3261: - // > - // > The response to an OPTIONS is constructed using the standard rules - // > for a SIP response as discussed in Section 8.2.6. The response code - // > chosen MUST be the same that would have been chosen had the request - // > been an INVITE. - // > - // > Did I miss the point of the question? - // > - // > On May 15, 2008, at 12:48 PM, Paul Kyzivat wrote: - // > - // >> [Including Robert in hopes of getting his insight on this.] - // https://lists.cs.columbia.edu/pipermail/sip-implementors/2008-May/019178.html - // - // Requests that do not change in any way the state of a dialog may be - // received within a dialog (for example, an OPTIONS request). They are - // processed as if they had been received outside the dialog. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (message.method === messages_1.C.OPTIONS) { - var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); - var acceptHeader = "Accept: " + acceptedBodyTypes.toString(); - this.replyStateless(message, { - statusCode: 200, - extraHeaders: [allowHeader, acceptHeader] - }); - return; - } - // Pass the incoming request to the dialog for further handling. - dialog.receiveRequest(message); - return; - } - // The most important behaviors of a stateless UAS are the following: - // ... - // o A stateless UAS MUST ignore ACK requests. - // ... - // https://tools.ietf.org/html/rfc3261#section-8.2.7 - if (message.method === messages_1.C.ACK) { - // If a final response to an INVITE was sent statelessly, - // the corresponding ACK: - // - will not match an existing transaction - // - may have tag in the To header field - // - not not match any existing dialogs - // Absorb unmatched ACKs. - return; - } - // If the request has a tag in the To header field, but the dialog - // identifier does not match any existing dialogs, the UAS may have - // crashed and restarted, or it may have received a request for a - // different (possibly failed) UAS (the UASs can construct the To tags - // so that a UAS can identify that the tag was for a UAS for which it is - // providing recovery). Another possibility is that the incoming - // request has been simply mis-routed. Based on the To tag, the UAS MAY - // either accept or reject the request. Accepting the request for - // acceptable To tags provides robustness, so that dialogs can persist - // even through crashes. UAs wishing to support this capability must - // take into consideration some issues such as choosing monotonically - // increasing CSeq sequence numbers even across reboots, reconstructing - // the route set, and accepting out-of-range RTP timestamps and sequence - // numbers. - // - // If the UAS wishes to reject the request because it does not wish to - // recreate the dialog, it MUST respond to the request with a 481 - // (Call/Transaction Does Not Exist) status code and pass that to the - // server transaction. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - this.replyStateless(message, { statusCode: 481 }); - return; - }; - /** - * Assuming all of the checks in the previous subsections are passed, - * the UAS processing becomes method-specific. - * https://tools.ietf.org/html/rfc3261#section-8.2.5 - * @param message - Incoming request message. - */ - UserAgentCore.prototype.receiveOutsideDialogRequest = function (message) { - switch (message.method) { - case messages_1.C.ACK: - // Absorb stray out of dialog ACKs - break; - case messages_1.C.BYE: - // If the BYE does not match an existing dialog, the UAS core SHOULD - // generate a 481 (Call/Transaction Does Not Exist) response and pass - // that to the server transaction. This rule means that a BYE sent - // without tags by a UAC will be rejected. - // https://tools.ietf.org/html/rfc3261#section-15.1.2 - this.replyStateless(message, { statusCode: 481 }); - break; - case messages_1.C.CANCEL: - throw new Error("Unexpected out of dialog request method " + message.method + "."); - break; - case messages_1.C.INFO: - // Use of the INFO method does not constitute a separate dialog usage. - // INFO messages are always part of, and share the fate of, an invite - // dialog usage [RFC5057]. INFO messages cannot be sent as part of - // other dialog usages, or outside an existing dialog. - // https://tools.ietf.org/html/rfc6086#section-1 - this.replyStateless(message, { statusCode: 405 }); // Should never happen - break; - case messages_1.C.INVITE: - // https://tools.ietf.org/html/rfc3261#section-13.3.1 - { - var uas = new user_agents_1.InviteUserAgentServer(this, message); - this.delegate.onInvite ? - this.delegate.onInvite(uas) : - uas.reject(); - } - break; - case messages_1.C.MESSAGE: - // MESSAGE requests are discouraged inside a dialog. Implementations - // are restricted from creating a usage for the purpose of carrying a - // sequence of MESSAGE requests (though some implementations use it that - // way, against the standard recommendation). - // https://tools.ietf.org/html/rfc5057#section-5.3 - { - var uas = new user_agents_1.MessageUserAgentServer(this, message); - this.delegate.onMessage ? - this.delegate.onMessage(uas) : - uas.accept(); - } - break; - case messages_1.C.NOTIFY: - // Obsoleted by: RFC 6665 - // If any non-SUBSCRIBE mechanisms are defined to create subscriptions, - // it is the responsibility of the parties defining those mechanisms to - // ensure that correlation of a NOTIFY message to the corresponding - // subscription is possible. Designers of such mechanisms are also - // warned to make a distinction between sending a NOTIFY message to a - // subscriber who is aware of the subscription, and sending a NOTIFY - // message to an unsuspecting node. The latter behavior is invalid, and - // MUST receive a "481 Subscription does not exist" response (unless - // some other 400- or 500-class error code is more applicable), as - // described in section 3.2.4. In other words, knowledge of a - // subscription must exist in both the subscriber and the notifier to be - // valid, even if installed via a non-SUBSCRIBE mechanism. - // https://tools.ietf.org/html/rfc3265#section-3.2 - // - // NOTIFY requests are sent to inform subscribers of changes in state to - // which the subscriber has a subscription. Subscriptions are created - // using the SUBSCRIBE method. In legacy implementations, it is - // possible that other means of subscription creation have been used. - // However, this specification does not allow the creation of - // subscriptions except through SUBSCRIBE requests and (for backwards- - // compatibility) REFER requests [RFC3515]. - // https://tools.ietf.org/html/rfc6665#section-3.2 - { - var uas = new user_agents_1.NotifyUserAgentServer(this, message); - this.delegate.onNotify ? - this.delegate.onNotify(uas) : - uas.reject({ statusCode: 405 }); - } - break; - case messages_1.C.OPTIONS: - // https://tools.ietf.org/html/rfc3261#section-11.2 - { - var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); - var acceptHeader = "Accept: " + acceptedBodyTypes.toString(); - this.replyStateless(message, { - statusCode: 200, - extraHeaders: [allowHeader, acceptHeader] - }); - } - break; - case messages_1.C.REFER: - // https://tools.ietf.org/html/rfc3515#section-2.4.2 - { - var uas = new user_agents_1.ReferUserAgentServer(this, message); - this.delegate.onRefer ? - this.delegate.onRefer(uas) : - uas.reject({ statusCode: 405 }); - } - break; - case messages_1.C.REGISTER: - // https://tools.ietf.org/html/rfc3261#section-10.3 - { - var uas = new user_agents_1.RegisterUserAgentServer(this, message); - this.delegate.onRegister ? - this.delegate.onRegister(uas) : - uas.reject({ statusCode: 405 }); - } - break; - case messages_1.C.SUBSCRIBE: - // https://tools.ietf.org/html/rfc6665#section-4.2 - { - var uas = new user_agents_1.SubscribeUserAgentServer(this, message); - this.delegate.onSubscribe ? - this.delegate.onSubscribe(uas) : - uas.reject({ statusCode: 480 }); - } - break; - default: - throw new Error("Unexpected out of dialog request method " + message.method + "."); - } - return; - }; - /** - * Responses are first processed by the transport layer and then passed - * up to the transaction layer. The transaction layer performs its - * processing and then passes the response up to the TU. The majority - * of response processing in the TU is method specific. However, there - * are some general behaviors independent of the method. - * https://tools.ietf.org/html/rfc3261#section-8.1.3 - * @param message - Incoming response message from transport layer. - */ - UserAgentCore.prototype.receiveResponseFromTransport = function (message) { - // 8.1.3.1 Transaction Layer Errors - // https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - // Handled by transaction layer callbacks. - // 8.1.3.2 Unrecognized Responses - // https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - // TODO - // 8.1.3.3 Vias - // https://tools.ietf.org/html/rfc3261#section-8.1.3.3 - if (message.getHeaders("via").length > 1) { - this.logger.warn("More than one Via header field present in the response, dropping"); - return; - } - // 8.1.3.4 Processing 3xx Responses - // https://tools.ietf.org/html/rfc3261#section-8.1.3.4 - // TODO - // 8.1.3.5 Processing 4xx Responses - // https://tools.ietf.org/html/rfc3261#section-8.1.3.5 - // TODO - // When the transport layer in the client receives a response, it has to - // determine which client transaction will handle the response, so that - // the processing of Sections 17.1.1 and 17.1.2 can take place. The - // branch parameter in the top Via header field is used for this - // purpose. A response matches a client transaction under two - // conditions: - // - // 1. If the response has the same value of the branch parameter in - // the top Via header field as the branch parameter in the top - // Via header field of the request that created the transaction. - // - // 2. If the method parameter in the CSeq header field matches the - // method of the request that created the transaction. The - // method is needed since a CANCEL request constitutes a - // different transaction, but shares the same value of the branch - // parameter. - // https://tools.ietf.org/html/rfc3261#section-17.1.3 - var userAgentClientId = message.viaBranch + message.method; - var userAgentClient = this.userAgentClients.get(userAgentClientId); - // The client transport uses the matching procedures of Section - // 17.1.3 to attempt to match the response to an existing - // transaction. If there is a match, the response MUST be passed to - // that transaction. Otherwise, any element other than a stateless - // proxy MUST silently discard the response. - // https://tools.ietf.org/html/rfc6026#section-8.9 - if (userAgentClient) { - userAgentClient.transaction.receiveResponse(message); - } - else { - this.logger.warn("Discarding unmatched " + message.statusCode + " response to " + message.method + " " + userAgentClientId + "."); - } - }; - return UserAgentCore; -}()); -exports.UserAgentCore = UserAgentCore; - - -/***/ }), -/* 66 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -tslib_1.__exportStar(__webpack_require__(41), exports); -tslib_1.__exportStar(__webpack_require__(43), exports); -tslib_1.__exportStar(__webpack_require__(67), exports); -tslib_1.__exportStar(__webpack_require__(45), exports); -tslib_1.__exportStar(__webpack_require__(46), exports); -tslib_1.__exportStar(__webpack_require__(68), exports); -tslib_1.__exportStar(__webpack_require__(69), exports); -tslib_1.__exportStar(__webpack_require__(70), exports); -tslib_1.__exportStar(__webpack_require__(71), exports); -tslib_1.__exportStar(__webpack_require__(47), exports); -tslib_1.__exportStar(__webpack_require__(48), exports); -tslib_1.__exportStar(__webpack_require__(72), exports); -tslib_1.__exportStar(__webpack_require__(49), exports); -tslib_1.__exportStar(__webpack_require__(50), exports); -tslib_1.__exportStar(__webpack_require__(51), exports); -tslib_1.__exportStar(__webpack_require__(52), exports); -tslib_1.__exportStar(__webpack_require__(59), exports); -tslib_1.__exportStar(__webpack_require__(73), exports); -tslib_1.__exportStar(__webpack_require__(53), exports); -tslib_1.__exportStar(__webpack_require__(54), exports); -tslib_1.__exportStar(__webpack_require__(74), exports); -tslib_1.__exportStar(__webpack_require__(75), exports); -tslib_1.__exportStar(__webpack_require__(76), exports); -tslib_1.__exportStar(__webpack_require__(77), exports); -tslib_1.__exportStar(__webpack_require__(42), exports); -tslib_1.__exportStar(__webpack_require__(44), exports); - - -/***/ }), -/* 67 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * CANCEL UAC. - * @public - */ -var CancelUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(CancelUserAgentClient, _super); - function CancelUserAgentClient(core, message, delegate) { - return _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; - } - return CancelUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.CancelUserAgentClient = CancelUserAgentClient; - - -/***/ }), -/* 68 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var dialogs_1 = __webpack_require__(3); -var session_1 = __webpack_require__(24); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * INVITE UAC. - * @remarks - * 13 Initiating a Session - * https://tools.ietf.org/html/rfc3261#section-13 - * 13.1 Overview - * https://tools.ietf.org/html/rfc3261#section-13.1 - * 13.2 UAC Processing - * https://tools.ietf.org/html/rfc3261#section-13.2 - * @public - */ -var InviteUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(InviteUserAgentClient, _super); - function InviteUserAgentClient(core, message, delegate) { - var _this = _super.call(this, transactions_1.InviteClientTransaction, core, message, delegate) || this; - _this.confirmedDialogAcks = new Map(); - _this.confirmedDialogs = new Map(); - _this.earlyDialogs = new Map(); - _this.delegate = delegate; - return _this; - } - InviteUserAgentClient.prototype.dispose = function () { - // The UAC core considers the INVITE transaction completed 64*T1 seconds - // after the reception of the first 2xx response. At this point all the - // early dialogs that have not transitioned to established dialogs are - // terminated. Once the INVITE transaction is considered completed by - // the UAC core, no more new 2xx responses are expected to arrive. - // - // If, after acknowledging any 2xx response to an INVITE, the UAC does - // not want to continue with that dialog, then the UAC MUST terminate - // the dialog by sending a BYE request as described in Section 15. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - this.earlyDialogs.forEach(function (earlyDialog) { return earlyDialog.dispose(); }); - this.earlyDialogs.clear(); - _super.prototype.dispose.call(this); - }; - /** - * Once the INVITE has been passed to the INVITE client transaction, the - * UAC waits for responses for the INVITE. - * https://tools.ietf.org/html/rfc3261#section-13.2.2 - * @param incomingResponse - Incoming response to INVITE request. - */ - InviteUserAgentClient.prototype.receiveResponse = function (message) { - var _this = this; - if (!this.authenticationGuard(message)) { - return; - } - var statusCode = message.statusCode ? message.statusCode.toString() : ""; - if (!statusCode) { - throw new Error("Response status code undefined."); - } - switch (true) { - case /^100$/.test(statusCode): - if (this.delegate && this.delegate.onTrying) { - this.delegate.onTrying({ message: message }); - } - return; - case /^1[0-9]{2}$/.test(statusCode): - // Zero, one or multiple provisional responses may arrive before one or - // more final responses are received. Provisional responses for an - // INVITE request can create "early dialogs". If a provisional response - // has a tag in the To field, and if the dialog ID of the response does - // not match an existing dialog, one is constructed using the procedures - // defined in Section 12.1.2. - // - // The early dialog will only be needed if the UAC needs to send a - // request to its peer within the dialog before the initial INVITE - // transaction completes. Header fields present in a provisional - // response are applicable as long as the dialog is in the early state - // (for example, an Allow header field in a provisional response - // contains the methods that can be used in the dialog while this is in - // the early state). - // https://tools.ietf.org/html/rfc3261#section-13.2.2.1 - { - // Provisional without to tag, no dialog to create. - if (!message.toTag) { - this.logger.warn("Non-100 1xx INVITE response received without a to tag, dropping."); - return; - } - // Compute dialog state. - var dialogState = dialogs_1.Dialog.initialDialogStateForUserAgentClient(this.message, message); - // Have existing early dialog or create a new one. - var earlyDialog = this.earlyDialogs.get(dialogState.id); - if (!earlyDialog) { - var transaction = this.transaction; - if (!(transaction instanceof transactions_1.InviteClientTransaction)) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - earlyDialog = new dialogs_1.SessionDialog(transaction, this.core, dialogState); - this.earlyDialogs.set(earlyDialog.id, earlyDialog); - } - // Guard against out of order reliable provisional responses. - // Note that this is where the rseq tracking is done. - if (!earlyDialog.reliableSequenceGuard(message)) { - this.logger.warn("1xx INVITE reliable response received out of order, dropping."); - return; - } - // If the initial offer is in an INVITE, the answer MUST be in a - // reliable non-failure message from UAS back to UAC which is - // correlated to that INVITE. For this specification, that is - // only the final 2xx response to that INVITE. That same exact - // answer MAY also be placed in any provisional responses sent - // prior to the answer. The UAC MUST treat the first session - // description it receives as the answer, and MUST ignore any - // session descriptions in subsequent responses to the initial - // INVITE. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - if (earlyDialog.signalingState === session_1.SignalingState.Initial || - earlyDialog.signalingState === session_1.SignalingState.HaveLocalOffer) { - earlyDialog.signalingStateTransition(message); - } - // Pass response to delegate. - var session_2 = earlyDialog; - if (this.delegate && this.delegate.onProgress) { - this.delegate.onProgress({ - message: message, - session: session_2, - prack: function (options) { - var outgoingPrackRequest = session_2.prack(undefined, options); - return outgoingPrackRequest; - } - }); - } - } - return; - case /^2[0-9]{2}$/.test(statusCode): - // Multiple 2xx responses may arrive at the UAC for a single INVITE - // request due to a forking proxy. Each response is distinguished by - // the tag parameter in the To header field, and each represents a - // distinct dialog, with a distinct dialog identifier. - // - // If the dialog identifier in the 2xx response matches the dialog - // identifier of an existing dialog, the dialog MUST be transitioned to - // the "confirmed" state, and the route set for the dialog MUST be - // recomputed based on the 2xx response using the procedures of Section - // 12.2.1.2. Otherwise, a new dialog in the "confirmed" state MUST be - // constructed using the procedures of Section 12.1.2. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - { - // Compute dialog state. - var dialogState = dialogs_1.Dialog.initialDialogStateForUserAgentClient(this.message, message); - // NOTE: Currently our transaction layer is caching the 2xx ACKs and - // handling retransmissions of the ACK which is an approach which is - // not to spec. In any event, this block is intended to provide a to - // spec implementation of ACK retransmissions, but it should not be - // hit currently. - var dialog = this.confirmedDialogs.get(dialogState.id); - if (dialog) { - // Once the ACK has been constructed, the procedures of [4] are used to - // determine the destination address, port and transport. However, the - // request is passed to the transport layer directly for transmission, - // rather than a client transaction. This is because the UAC core - // handles retransmissions of the ACK, not the transaction layer. The - // ACK MUST be passed to the client transport every time a - // retransmission of the 2xx final response that triggered the ACK - // arrives. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - var outgoingAckRequest = this.confirmedDialogAcks.get(dialogState.id); - if (outgoingAckRequest) { - var transaction = this.transaction; - if (!(transaction instanceof transactions_1.InviteClientTransaction)) { - throw new Error("Client transaction not instance of InviteClientTransaction."); - } - transaction.ackResponse(outgoingAckRequest.message); - } - else { - // If still waiting for an ACK, drop the retransmission of the 2xx final response. - } - return; - } - // If the dialog identifier in the 2xx response matches the dialog - // identifier of an existing dialog, the dialog MUST be transitioned to - // the "confirmed" state, and the route set for the dialog MUST be - // recomputed based on the 2xx response using the procedures of Section - // 12.2.1.2. Otherwise, a new dialog in the "confirmed" state MUST be - // constructed using the procedures of Section 12.1.2. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - dialog = this.earlyDialogs.get(dialogState.id); - if (dialog) { - dialog.confirm(); - dialog.recomputeRouteSet(message); - this.earlyDialogs.delete(dialog.id); - this.confirmedDialogs.set(dialog.id, dialog); - } - else { - var transaction = this.transaction; - if (!(transaction instanceof transactions_1.InviteClientTransaction)) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - dialog = new dialogs_1.SessionDialog(transaction, this.core, dialogState); - this.confirmedDialogs.set(dialog.id, dialog); - } - // If the initial offer is in an INVITE, the answer MUST be in a - // reliable non-failure message from UAS back to UAC which is - // correlated to that INVITE. For this specification, that is - // only the final 2xx response to that INVITE. That same exact - // answer MAY also be placed in any provisional responses sent - // prior to the answer. The UAC MUST treat the first session - // description it receives as the answer, and MUST ignore any - // session descriptions in subsequent responses to the initial - // INVITE. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - if (dialog.signalingState === session_1.SignalingState.Initial || - dialog.signalingState === session_1.SignalingState.HaveLocalOffer) { - dialog.signalingStateTransition(message); - } - // Session Initiated! :) - var session_3 = dialog; - // The UAC core MUST generate an ACK request for each 2xx received from - // the transaction layer. The header fields of the ACK are constructed - // in the same way as for any request sent within a dialog (see Section - // 12) with the exception of the CSeq and the header fields related to - // authentication. The sequence number of the CSeq header field MUST be - // the same as the INVITE being acknowledged, but the CSeq method MUST - // be ACK. The ACK MUST contain the same credentials as the INVITE. If - // the 2xx contains an offer (based on the rules above), the ACK MUST - // carry an answer in its body. If the offer in the 2xx response is not - // acceptable, the UAC core MUST generate a valid answer in the ACK and - // then send a BYE immediately. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - if (this.delegate && this.delegate.onAccept) { - this.delegate.onAccept({ - message: message, - session: session_3, - ack: function (options) { - var outgoingAckRequest = session_3.ack(options); - _this.confirmedDialogAcks.set(session_3.id, outgoingAckRequest); - return outgoingAckRequest; - } - }); - } - else { - var outgoingAckRequest = session_3.ack(); - this.confirmedDialogAcks.set(session_3.id, outgoingAckRequest); - } - } - return; - case /^3[0-9]{2}$/.test(statusCode): - // 12.3 Termination of a Dialog - // - // Independent of the method, if a request outside of a dialog generates - // a non-2xx final response, any early dialogs created through - // provisional responses to that request are terminated. The mechanism - // for terminating confirmed dialogs is method specific. In this - // specification, the BYE method terminates a session and the dialog - // associated with it. See Section 15 for details. - // https://tools.ietf.org/html/rfc3261#section-12.3 - // All early dialogs are considered terminated upon reception of the - // non-2xx final response. - // - // After having received the non-2xx final response the UAC core - // considers the INVITE transaction completed. The INVITE client - // transaction handles the generation of ACKs for the response (see - // Section 17). - // https://tools.ietf.org/html/rfc3261#section-13.2.2.3 - this.earlyDialogs.forEach(function (earlyDialog) { return earlyDialog.dispose(); }); - this.earlyDialogs.clear(); - // A 3xx response may contain one or more Contact header field values - // providing new addresses where the callee might be reachable. - // Depending on the status code of the 3xx response (see Section 21.3), - // the UAC MAY choose to try those new addresses. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.2 - if (this.delegate && this.delegate.onRedirect) { - this.delegate.onRedirect({ message: message }); - } - return; - case /^[4-6][0-9]{2}$/.test(statusCode): - // 12.3 Termination of a Dialog - // - // Independent of the method, if a request outside of a dialog generates - // a non-2xx final response, any early dialogs created through - // provisional responses to that request are terminated. The mechanism - // for terminating confirmed dialogs is method specific. In this - // specification, the BYE method terminates a session and the dialog - // associated with it. See Section 15 for details. - // https://tools.ietf.org/html/rfc3261#section-12.3 - // All early dialogs are considered terminated upon reception of the - // non-2xx final response. - // - // After having received the non-2xx final response the UAC core - // considers the INVITE transaction completed. The INVITE client - // transaction handles the generation of ACKs for the response (see - // Section 17). - // https://tools.ietf.org/html/rfc3261#section-13.2.2.3 - this.earlyDialogs.forEach(function (earlyDialog) { return earlyDialog.dispose(); }); - this.earlyDialogs.clear(); - // A single non-2xx final response may be received for the INVITE. 4xx, - // 5xx and 6xx responses may contain a Contact header field value - // indicating the location where additional information about the error - // can be found. Subsequent final responses (which would only arrive - // under error conditions) MUST be ignored. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.3 - if (this.delegate && this.delegate.onReject) { - this.delegate.onReject({ message: message }); - } - return; - default: - throw new Error("Invalid status code " + statusCode); - } - throw new Error("Executing what should be an unreachable code path receiving " + statusCode + " response."); - }; - return InviteUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.InviteUserAgentClient = InviteUserAgentClient; - - -/***/ }), -/* 69 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var dialogs_1 = __webpack_require__(3); -var exceptions_1 = __webpack_require__(31); -var session_1 = __webpack_require__(24); -var transactions_1 = __webpack_require__(27); -var allowed_methods_1 = __webpack_require__(58); -var user_agent_server_1 = __webpack_require__(44); -/** - * INVITE UAS. - * @remarks - * 13 Initiating a Session - * https://tools.ietf.org/html/rfc3261#section-13 - * 13.1 Overview - * https://tools.ietf.org/html/rfc3261#section-13.1 - * 13.3 UAS Processing - * https://tools.ietf.org/html/rfc3261#section-13.3 - * @public - */ -var InviteUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(InviteUserAgentServer, _super); - function InviteUserAgentServer(core, message, delegate) { - var _this = _super.call(this, transactions_1.InviteServerTransaction, core, message, delegate) || this; - _this.core = core; - return _this; - } - InviteUserAgentServer.prototype.dispose = function () { - if (this.earlyDialog) { - this.earlyDialog.dispose(); - } - _super.prototype.dispose.call(this); - }; - /** - * 13.3.1.4 The INVITE is Accepted - * The UAS core generates a 2xx response. This response establishes a - * dialog, and therefore follows the procedures of Section 12.1.1 in - * addition to those of Section 8.2.6. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - * @param options - Accept options bucket. - */ - InviteUserAgentServer.prototype.accept = function (options) { - if (options === void 0) { options = { statusCode: 200 }; } - if (!this.acceptable) { - throw new exceptions_1.TransactionStateError(this.message.method + " not acceptable in state " + this.transaction.state + "."); - } - // This response establishes a dialog... - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - if (!this.confirmedDialog) { - if (this.earlyDialog) { - this.earlyDialog.confirm(); - this.confirmedDialog = this.earlyDialog; - this.earlyDialog = undefined; - } - else { - var transaction = this.transaction; - if (!(transaction instanceof transactions_1.InviteServerTransaction)) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - var state = dialogs_1.Dialog.initialDialogStateForUserAgentServer(this.message, this.toTag); - this.confirmedDialog = new dialogs_1.SessionDialog(transaction, this.core, state); - } - } - // When a UAS responds to a request with a response that establishes a - // dialog (such as a 2xx to INVITE), the UAS MUST copy all Record-Route - // header field values from the request into the response (including the - // URIs, URI parameters, and any Record-Route header field parameters, - // whether they are known or unknown to the UAS) and MUST maintain the - // order of those values. The UAS MUST add a Contact header field to - // the response. The Contact header field contains an address where the - // UAS would like to be contacted for subsequent requests in the dialog - // (which includes the ACK for a 2xx response in the case of an INVITE). - // Generally, the host portion of this URI is the IP address or FQDN of - // the host. The URI provided in the Contact header field MUST be a SIP - // or SIPS URI. If the request that initiated the dialog contained a - // SIPS URI in the Request-URI or in the top Record-Route header field - // value, if there was any, or the Contact header field if there was no - // Record-Route header field, the Contact header field in the response - // MUST be a SIPS URI. The URI SHOULD have global scope (that is, the - // same URI can be used in messages outside this dialog). The same way, - // the scope of the URI in the Contact header field of the INVITE is not - // limited to this dialog either. It can therefore be used in messages - // to the UAC even outside this dialog. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - var recordRouteHeader = this.message - .getHeaders("record-route") - .map(function (header) { return "Record-Route: " + header; }); - var contactHeader = "Contact: " + this.core.configuration.contact.toString(); - // A 2xx response to an INVITE SHOULD contain the Allow header field and - // the Supported header field, and MAY contain the Accept header field. - // Including these header fields allows the UAC to determine the - // features and extensions supported by the UAS for the duration of the - // call, without probing. - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - // FIXME: TODO: This should not be hard coded. - var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); - // FIXME: TODO: Supported header (see reply()) - // FIXME: TODO: Accept header - // If the INVITE request contained an offer, and the UAS had not yet - // sent an answer, the 2xx MUST contain an answer. If the INVITE did - // not contain an offer, the 2xx MUST contain an offer if the UAS had - // not yet sent an offer. - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - if (!options.body) { - if (this.confirmedDialog.signalingState === session_1.SignalingState.Stable) { - options.body = this.confirmedDialog.answer; // resend the answer sent in provisional response - } - else if (this.confirmedDialog.signalingState === session_1.SignalingState.Initial || - this.confirmedDialog.signalingState === session_1.SignalingState.HaveRemoteOffer) { - throw new Error("Response must have a body."); - } - } - options.statusCode = options.statusCode || 200; - options.extraHeaders = options.extraHeaders || []; - options.extraHeaders = options.extraHeaders.concat(recordRouteHeader); - options.extraHeaders.push(allowHeader); - options.extraHeaders.push(contactHeader); - var response = _super.prototype.accept.call(this, options); - var session = this.confirmedDialog; - var result = tslib_1.__assign({}, response, { session: session }); - // Update dialog signaling state - if (options.body) { - // Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - if (this.confirmedDialog.signalingState !== session_1.SignalingState.Stable) { - this.confirmedDialog.signalingStateTransition(options.body); - } - } - return result; - }; - /** - * 13.3.1.1 Progress - * If the UAS is not able to answer the invitation immediately, it can - * choose to indicate some kind of progress to the UAC (for example, an - * indication that a phone is ringing). This is accomplished with a - * provisional response between 101 and 199. These provisional - * responses establish early dialogs and therefore follow the procedures - * of Section 12.1.1 in addition to those of Section 8.2.6. A UAS MAY - * send as many provisional responses as it likes. Each of these MUST - * indicate the same dialog ID. However, these will not be delivered - * reliably. - * - * If the UAS desires an extended period of time to answer the INVITE, - * it will need to ask for an "extension" in order to prevent proxies - * from canceling the transaction. A proxy has the option of canceling - * a transaction when there is a gap of 3 minutes between responses in a - * transaction. To prevent cancellation, the UAS MUST send a non-100 - * provisional response at every minute, to handle the possibility of - * lost provisional responses. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.1 - * @param options - Progress options bucket. - */ - InviteUserAgentServer.prototype.progress = function (options) { - if (options === void 0) { options = { statusCode: 180 }; } - if (!this.progressable) { - throw new exceptions_1.TransactionStateError(this.message.method + " not progressable in state " + this.transaction.state + "."); - } - // This response establishes a dialog... - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - if (!this.earlyDialog) { - var transaction = this.transaction; - if (!(transaction instanceof transactions_1.InviteServerTransaction)) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - var state = dialogs_1.Dialog.initialDialogStateForUserAgentServer(this.message, this.toTag, true); - this.earlyDialog = new dialogs_1.SessionDialog(transaction, this.core, state); - } - // When a UAS responds to a request with a response that establishes a - // dialog (such as a 2xx to INVITE), the UAS MUST copy all Record-Route - // header field values from the request into the response (including the - // URIs, URI parameters, and any Record-Route header field parameters, - // whether they are known or unknown to the UAS) and MUST maintain the - // order of those values. The UAS MUST add a Contact header field to - // the response. The Contact header field contains an address where the - // UAS would like to be contacted for subsequent requests in the dialog - // (which includes the ACK for a 2xx response in the case of an INVITE). - // Generally, the host portion of this URI is the IP address or FQDN of - // the host. The URI provided in the Contact header field MUST be a SIP - // or SIPS URI. If the request that initiated the dialog contained a - // SIPS URI in the Request-URI or in the top Record-Route header field - // value, if there was any, or the Contact header field if there was no - // Record-Route header field, the Contact header field in the response - // MUST be a SIPS URI. The URI SHOULD have global scope (that is, the - // same URI can be used in messages outside this dialog). The same way, - // the scope of the URI in the Contact header field of the INVITE is not - // limited to this dialog either. It can therefore be used in messages - // to the UAC even outside this dialog. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - var recordRouteHeader = this.message - .getHeaders("record-route") - .map(function (header) { return "Record-Route: " + header; }); - var contactHeader = "Contact: " + this.core.configuration.contact; - options.extraHeaders = options.extraHeaders || []; - options.extraHeaders = options.extraHeaders.concat(recordRouteHeader); - options.extraHeaders.push(contactHeader); - var response = _super.prototype.progress.call(this, options); - var session = this.earlyDialog; - var result = tslib_1.__assign({}, response, { session: session }); - // Update dialog signaling state - if (options.body) { - // Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - if (this.earlyDialog.signalingState !== session_1.SignalingState.Stable) { - this.earlyDialog.signalingStateTransition(options.body); - } - } - return result; - }; - /** - * 13.3.1.2 The INVITE is Redirected - * If the UAS decides to redirect the call, a 3xx response is sent. A - * 300 (Multiple Choices), 301 (Moved Permanently) or 302 (Moved - * Temporarily) response SHOULD contain a Contact header field - * containing one or more URIs of new addresses to be tried. The - * response is passed to the INVITE server transaction, which will deal - * with its retransmissions. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.2 - * @param contacts - Contacts to redirect to. - * @param options - Redirect options bucket. - */ - InviteUserAgentServer.prototype.redirect = function (contacts, options) { - if (options === void 0) { options = { statusCode: 302 }; } - return _super.prototype.redirect.call(this, contacts, options); - }; - /** - * 13.3.1.3 The INVITE is Rejected - * A common scenario occurs when the callee is currently not willing or - * able to take additional calls at this end system. A 486 (Busy Here) - * SHOULD be returned in such a scenario. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.3 - * @param options - Reject options bucket. - */ - InviteUserAgentServer.prototype.reject = function (options) { - if (options === void 0) { options = { statusCode: 486 }; } - return _super.prototype.reject.call(this, options); - }; - return InviteUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.InviteUserAgentServer = InviteUserAgentServer; - - -/***/ }), -/* 70 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * MESSAGE UAS. - * @public - */ -var MessageUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(MessageUserAgentClient, _super); - function MessageUserAgentClient(core, message, delegate) { - return _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; - } - return MessageUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.MessageUserAgentClient = MessageUserAgentClient; - - -/***/ }), -/* 71 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * MESSAGE UAS. - * @public - */ -var MessageUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(MessageUserAgentServer, _super); - function MessageUserAgentServer(core, message, delegate) { - var _this = _super.call(this, transactions_1.NonInviteServerTransaction, core, message, delegate) || this; - _this.core = core; - return _this; - } - return MessageUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.MessageUserAgentServer = MessageUserAgentServer; - - -/***/ }), -/* 72 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * PUBLISH UAC. - * @public - */ -var PublishUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(PublishUserAgentClient, _super); - function PublishUserAgentClient(core, message, delegate) { - return _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; - } - return PublishUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.PublishUserAgentClient = PublishUserAgentClient; - - -/***/ }), -/* 73 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * Re-SUBSCRIBE UAS. - * @public - */ -var ReSubscribeUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(ReSubscribeUserAgentServer, _super); - function ReSubscribeUserAgentServer(dialog, message, delegate) { - return _super.call(this, transactions_1.NonInviteServerTransaction, dialog.userAgentCore, message, delegate) || this; - } - return ReSubscribeUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.ReSubscribeUserAgentServer = ReSubscribeUserAgentServer; - - -/***/ }), -/* 74 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * REGISTER UAC. - * @public - */ -var RegisterUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(RegisterUserAgentClient, _super); - function RegisterUserAgentClient(core, message, delegate) { - return _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; - } - return RegisterUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.RegisterUserAgentClient = RegisterUserAgentClient; - - -/***/ }), -/* 75 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * REGISTER UAS. - * @public - */ -var RegisterUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(RegisterUserAgentServer, _super); - function RegisterUserAgentServer(core, message, delegate) { - var _this = _super.call(this, transactions_1.NonInviteServerTransaction, core, message, delegate) || this; - _this.core = core; - return _this; - } - return RegisterUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.RegisterUserAgentServer = RegisterUserAgentServer; - - -/***/ }), -/* 76 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var subscription_dialog_1 = __webpack_require__(55); -var subscription_1 = __webpack_require__(56); -var timers_1 = __webpack_require__(26); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * SUBSCRIBE UAC. - * @remarks - * 4.1. Subscriber Behavior - * https://tools.ietf.org/html/rfc6665#section-4.1 - * - * User agent client for installation of a single subscription per SUBSCRIBE request. - * TODO: Support for installation of multiple subscriptions on forked SUBSCRIBE reqeuests. - * @public - */ -var SubscribeUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(SubscribeUserAgentClient, _super); - function SubscribeUserAgentClient(core, message, delegate) { - var _this = this; - // Get event from request message. - var event = message.getHeader("Event"); - if (!event) { - throw new Error("Event undefined"); - } - // Get expires from reqeust message. - var expires = message.getHeader("Expires"); - if (!expires) { - throw new Error("Expires undefined"); - } - _this = _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; - _this.delegate = delegate; - // FIXME: Subscriber id should also be matching on event id. - _this.subscriberId = message.callId + message.fromTag + event; - _this.subscriptionExpiresRequested = _this.subscriptionExpires = Number(expires); - _this.subscriptionEvent = event; - _this.subscriptionState = subscription_1.SubscriptionState.NotifyWait; - // Start waiting for a NOTIFY we can use to create a subscription. - _this.waitNotifyStart(); - return _this; - } - /** - * Destructor. - * Note that Timer N may live on waiting for an initial NOTIFY and - * the delegate may still receive that NOTIFY. If you don't want - * that behavior then either clear the delegate so the delegate - * doesn't get called (a 200 will be sent in response to the NOTIFY) - * or call `waitNotifyStop` which will clear Timer N and remove this - * UAC from the core (a 481 will be sent in response to the NOTIFY). - */ - SubscribeUserAgentClient.prototype.dispose = function () { - _super.prototype.dispose.call(this); - }; - /** - * Handle out of dialog NOTIFY assoicated with SUBSCRIBE request. - * This is the first NOTIFY received after the SUBSCRIBE request. - * @param uas - User agent server handling the subscription creating NOTIFY. - */ - SubscribeUserAgentClient.prototype.onNotify = function (uas) { - // NOTIFY requests are matched to such SUBSCRIBE requests if they - // contain the same "Call-ID", a "To" header field "tag" parameter that - // matches the "From" header field "tag" parameter of the SUBSCRIBE - // request, and the same "Event" header field. Rules for comparisons of - // the "Event" header fields are described in Section 8.2.1. - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - var event = uas.message.parseHeader("Event").event; - if (!event || event !== this.subscriptionEvent) { - this.logger.warn("Failed to parse event."); - uas.reject({ statusCode: 489 }); - return; - } - // NOTIFY requests MUST contain "Subscription-State" header fields that - // indicate the status of the subscription. - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - var subscriptionState = uas.message.parseHeader("Subscription-State"); - if (!subscriptionState || !subscriptionState.state) { - this.logger.warn("Failed to parse subscription state."); - uas.reject({ statusCode: 489 }); - return; - } - // Validate subscription state. - var state = subscriptionState.state; - switch (state) { - case "pending": - break; - case "active": - break; - case "terminated": - break; - default: - this.logger.warn("Invalid subscription state " + state); - uas.reject({ statusCode: 489 }); - return; - } - // Dialogs usages are created upon completion of a NOTIFY transaction - // for a new subscription, unless the NOTIFY request contains a - // "Subscription-State" of "terminated." - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - if (state !== "terminated") { - // The Contact header field MUST be present and contain exactly one SIP - // or SIPS URI in any request that can result in the establishment of a - // dialog. - // https://tools.ietf.org/html/rfc3261#section-8.1.1.8 - var contact = uas.message.parseHeader("contact"); - if (!contact) { - this.logger.warn("Failed to parse contact."); - uas.reject({ statusCode: 489 }); - return; - } - } - // In accordance with the rules for proxying non-INVITE requests as - // defined in [RFC3261], successful SUBSCRIBE requests will receive only - // one 200-class response; however, due to forking, the subscription may - // have been accepted by multiple nodes. The subscriber MUST therefore - // be prepared to receive NOTIFY requests with "From:" tags that differ - // from the "To:" tag received in the SUBSCRIBE 200-class response. - // - // If multiple NOTIFY requests are received in different dialogs in - // response to a single SUBSCRIBE request, each dialog represents a - // different destination to which the SUBSCRIBE request was forked. - // Subscriber handling in such situations varies by event package; see - // Section 5.4.9 for details. - // https://tools.ietf.org/html/rfc6665#section-4.1.4 - // Each event package MUST specify whether forked SUBSCRIBE requests are - // allowed to install multiple subscriptions. - // - // If such behavior is not allowed, the first potential dialog- - // establishing message will create a dialog. All subsequent NOTIFY - // requests that correspond to the SUBSCRIBE request (i.e., have - // matching "To", "From", "Call-ID", and "Event" header fields, as well - // as "From" header field "tag" parameter and "Event" header field "id" - // parameter) but that do not match the dialog would be rejected with a - // 481 response. Note that the 200-class response to the SUBSCRIBE - // request can arrive after a matching NOTIFY request has been received; - // such responses might not correlate to the same dialog established by - // the NOTIFY request. Except as required to complete the SUBSCRIBE - // transaction, such non-matching 200-class responses are ignored. - // - // If installing of multiple subscriptions by way of a single forked - // SUBSCRIBE request is allowed, the subscriber establishes a new dialog - // towards each notifier by returning a 200-class response to each - // NOTIFY request. Each dialog is then handled as its own entity and is - // refreshed independently of the other dialogs. - // - // In the case that multiple subscriptions are allowed, the event - // package MUST specify whether merging of the notifications to form a - // single state is required, and how such merging is to be performed. - // Note that it is possible that some event packages may be defined in - // such a way that each dialog is tied to a mutually exclusive state - // that is unaffected by the other dialogs; this MUST be clearly stated - // if it is the case. - // https://tools.ietf.org/html/rfc6665#section-5.4.9 - // *** NOTE: This implementation is only for event packages which - // do not allow forked requests to install muliple subscriptions. - // As such and in accordance with the specificaiton, we stop waiting - // and any future NOTIFY requests will be rejected with a 481. - if (this.dialog) { - throw new Error("Dialog already created. This implementation only supports install of single subscriptions."); - } - this.waitNotifyStop(); - // Update expires. - this.subscriptionExpires = - subscriptionState.expires ? - Math.min(this.subscriptionExpires, Math.max(subscriptionState.expires, 0)) : - this.subscriptionExpires; - // Update subscriptoin state. - switch (state) { - case "pending": - this.subscriptionState = subscription_1.SubscriptionState.Pending; - break; - case "active": - this.subscriptionState = subscription_1.SubscriptionState.Active; - break; - case "terminated": - this.subscriptionState = subscription_1.SubscriptionState.Terminated; - break; - default: - throw new Error("Unrecognized state " + state + "."); - } - // Dialogs usages are created upon completion of a NOTIFY transaction - // for a new subscription, unless the NOTIFY request contains a - // "Subscription-State" of "terminated." - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - if (this.subscriptionState !== subscription_1.SubscriptionState.Terminated) { - // Because the dialog usage is established by the NOTIFY request, the - // route set at the subscriber is taken from the NOTIFY request itself, - // as opposed to the route set present in the 200-class response to the - // SUBSCRIBE request. - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - var dialogState = subscription_dialog_1.SubscriptionDialog.initialDialogStateForSubscription(this.message, uas.message); - // Subscription Initiated! :) - this.dialog = new subscription_dialog_1.SubscriptionDialog(this.subscriptionEvent, this.subscriptionExpires, this.subscriptionState, this.core, dialogState); - } - // Delegate. - if (this.delegate && this.delegate.onNotify) { - var request = uas; - var subscription = this.dialog; - this.delegate.onNotify({ request: request, subscription: subscription }); - } - else { - uas.accept(); - } - }; - SubscribeUserAgentClient.prototype.waitNotifyStart = function () { - var _this = this; - if (!this.N) { - // Add ourselves to the core's subscriber map. - // This allows the core to route out of dialog NOTIFY messages to us. - this.core.subscribers.set(this.subscriberId, this); - this.N = setTimeout(function () { return _this.timer_N(); }, timers_1.Timers.TIMER_N); - } - }; - SubscribeUserAgentClient.prototype.waitNotifyStop = function () { - if (this.N) { - // Remove ourselves to the core's subscriber map. - // Any future out of dialog NOTIFY messages will be rejected with a 481. - this.core.subscribers.delete(this.subscriberId); - clearTimeout(this.N); - this.N = undefined; - } - }; - /** - * Receive a response from the transaction layer. - * @param message - Incoming response message. - */ - SubscribeUserAgentClient.prototype.receiveResponse = function (message) { - if (!this.authenticationGuard(message)) { - return; - } - if (message.statusCode && message.statusCode >= 200 && message.statusCode < 300) { - // The "Expires" header field in a 200-class response to SUBSCRIBE - // request indicates the actual duration for which the subscription will - // remain active (unless refreshed). The received value might be - // smaller than the value indicated in the SUBSCRIBE request but cannot - // be larger; see Section 4.2.1 for details. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - // The "Expires" values present in SUBSCRIBE 200-class responses behave - // in the same way as they do in REGISTER responses: the server MAY - // shorten the interval but MUST NOT lengthen it. - // - // If the duration specified in a SUBSCRIBE request is unacceptably - // short, the notifier may be able to send a 423 response, as - // described earlier in this section. - // - // 200-class responses to SUBSCRIBE requests will not generally contain - // any useful information beyond subscription duration; their primary - // purpose is to serve as a reliability mechanism. State information - // will be communicated via a subsequent NOTIFY request from the - // notifier. - // https://tools.ietf.org/html/rfc6665#section-4.2.1.1 - var expires = message.getHeader("Expires"); - if (!expires) { - this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE"); - } - else { - var subscriptionExpiresReceived = Number(expires); - if (subscriptionExpiresReceived > this.subscriptionExpiresRequested) { - this.logger.warn("Expires header in a 200-class response to SUBSCRIBE with a higher value than the one in the request"); - } - if (subscriptionExpiresReceived < this.subscriptionExpires) { - this.subscriptionExpires = subscriptionExpiresReceived; - } - } - // If a NOTIFY arrived before 200-class response a dialog may have been created. - // Updated the dialogs expiration only if this indicates earlier expiration. - if (this.dialog) { - if (this.dialog.subscriptionExpires > this.subscriptionExpires) { - this.dialog.subscriptionExpires = this.subscriptionExpires; - } - } - } - if (message.statusCode && message.statusCode >= 300 && message.statusCode < 700) { - this.waitNotifyStop(); // No NOTIFY will be sent after a negative final response. - } - _super.prototype.receiveResponse.call(this, message); - }; - /** - * To ensure that subscribers do not wait indefinitely for a - * subscription to be established, a subscriber starts a Timer N, set to - * 64*T1, when it sends a SUBSCRIBE request. If this Timer N expires - * prior to the receipt of a NOTIFY request, the subscriber considers - * the subscription failed, and cleans up any state associated with the - * subscription attempt. - * https://tools.ietf.org/html/rfc6665#section-4.1.2.4 - */ - SubscribeUserAgentClient.prototype.timer_N = function () { - this.logger.warn("Timer N expired for SUBSCRIBE user agent client. Timed out waiting for NOTIFY."); - this.waitNotifyStop(); - if (this.delegate && this.delegate.onNotifyTimeout) { - this.delegate.onNotifyTimeout(); - } - }; - return SubscribeUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.SubscribeUserAgentClient = SubscribeUserAgentClient; - - -/***/ }), -/* 77 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * SUBSCRIBE UAS. - * @public - */ -var SubscribeUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(SubscribeUserAgentServer, _super); - function SubscribeUserAgentServer(core, message, delegate) { - var _this = _super.call(this, transactions_1.NonInviteServerTransaction, core, message, delegate) || this; - _this.core = core; - return _this; - } - return SubscribeUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.SubscribeUserAgentServer = SubscribeUserAgentServer; - - -/***/ }), -/* 78 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var events_1 = __webpack_require__(30); -/** - * Transport. - * @remarks - * Abstract transport layer base class. - * @public - */ -var Transport = /** @class */ (function (_super) { - tslib_1.__extends(Transport, _super); - /** - * Constructor - * @param logger - Logger. - * @param options - Options bucket. - */ - function Transport(logger, options) { - var _this = _super.call(this) || this; - _this.logger = logger; - return _this; - } - /** - * Returns the promise designated by the child layer then emits a connected event. - * Automatically emits an event upon resolution, unless overrideEvent is set. If you - * override the event in this fashion, you should emit it in your implementation of connectPromise - * @param options - Options bucket. - */ - Transport.prototype.connect = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - return this.connectPromise(options).then(function (data) { - if (!data.overrideEvent) { - _this.emit("connected"); - } - }); - }; - /** - * Sends a message then emits a 'messageSent' event. Automatically emits an - * event upon resolution, unless data.overrideEvent is set. If you override - * the event in this fashion, you should emit it in your implementation of sendPromise - * @param msg - Message. - * @param options - Options bucket. - */ - Transport.prototype.send = function (msg, options) { - var _this = this; - if (options === void 0) { options = {}; } - return this.sendPromise(msg).then(function (data) { - if (!data.overrideEvent) { - _this.emit("messageSent", data.msg); - } - }); - }; - /** - * Returns the promise designated by the child layer then emits a - * disconnected event. Automatically emits an event upon resolution, - * unless overrideEvent is set. If you override the event in this fashion, - * you should emit it in your implementation of disconnectPromise - * @param options - Options bucket - */ - Transport.prototype.disconnect = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - return this.disconnectPromise(options).then(function (data) { - if (!data.overrideEvent) { - _this.emit("disconnected"); - } - }); - }; - Transport.prototype.afterConnected = function (callback) { - if (this.isConnected()) { - callback(); - } - else { - this.once("connected", callback); - } - }; - /** - * Returns a promise which resolves once the UA is connected. DEPRECATION WARNING: just use afterConnected() - */ - Transport.prototype.waitForConnected = function () { - var _this = this; - // tslint:disable-next-line:no-console - console.warn("DEPRECATION WARNING Transport.waitForConnected(): use afterConnected() instead"); - return new Promise(function (resolve) { - _this.afterConnected(resolve); - }); - }; - return Transport; -}(events_1.EventEmitter)); -exports.Transport = Transport; - - -/***/ }) -/******/ ]); -}); \ No newline at end of file diff --git a/dist/sip-core.min.js b/dist/sip-core.min.js deleted file mode 100644 index 0db94cee7..000000000 --- a/dist/sip-core.min.js +++ /dev/null @@ -1 +0,0 @@ -!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.SIP=t():e.SIP=t()}(this,(function(){return function(e){var t={};function r(n){if(t[n])return t[n].exports;var i=t[n]={i:n,l:!1,exports:{}};return e[n].call(i.exports,i,i.exports,r),i.l=!0,i.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)r.d(n,i,function(t){return e[t]}.bind(null,i));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=5)}([function(e,t,r){"use strict";r.r(t),r.d(t,"__extends",(function(){return i})),r.d(t,"__assign",(function(){return o})),r.d(t,"__rest",(function(){return a})),r.d(t,"__decorate",(function(){return s})),r.d(t,"__param",(function(){return c})),r.d(t,"__metadata",(function(){return u})),r.d(t,"__awaiter",(function(){return d})),r.d(t,"__generator",(function(){return l})),r.d(t,"__exportStar",(function(){return h})),r.d(t,"__values",(function(){return p})),r.d(t,"__read",(function(){return f})),r.d(t,"__spread",(function(){return g})),r.d(t,"__spreadArrays",(function(){return v})),r.d(t,"__await",(function(){return m})),r.d(t,"__asyncGenerator",(function(){return y})),r.d(t,"__asyncDelegator",(function(){return S})),r.d(t,"__asyncValues",(function(){return T})),r.d(t,"__makeTemplateObject",(function(){return b})),r.d(t,"__importStar",(function(){return _})),r.d(t,"__importDefault",(function(){return $}));var n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};function i(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var o=function(){return(o=Object.assign||function(e){for(var t,r=1,n=arguments.length;r=0;s--)(i=e[s])&&(a=(o<3?i(a):o>3?i(t,r,a):i(t,r))||a);return o>3&&a&&Object.defineProperty(t,r,a),a}function c(e,t){return function(r,n){t(r,n,e)}}function u(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function d(e,t,r,n){return new(r||(r=Promise))((function(i,o){function a(e){try{c(n.next(e))}catch(e){o(e)}}function s(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){e.done?i(e.value):new r((function(t){t(e.value)})).then(a,s)}c((n=n.apply(e,t||[])).next())}))}function l(e,t){var r,n,i,o,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;a;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,n=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!(i=(i=a.trys).length>0&&i[i.length-1])&&(6===o[0]||2===o[0])){a=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}function f(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)a.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return a}function g(){for(var e=[],t=0;t1||s(e,t)}))})}function s(e,t){try{(r=i[e](t)).value instanceof m?Promise.resolve(r.value.v).then(c,u):d(o[0][2],r)}catch(e){d(o[0][3],e)}var r}function c(e){s("next",e)}function u(e){s("throw",e)}function d(e,t){e(t),o.shift(),o.length&&s(o[0][0],o[0][1])}}function S(e){var t,r;return t={},n("next"),n("throw",(function(e){throw e})),n("return"),t[Symbol.iterator]=function(){return this},t;function n(n,i){t[n]=e[n]?function(t){return(r=!r)?{value:m(e[n](t)),done:"return"===n}:i?i(t):t}:i}}function T(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=p(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise((function(n,i){(function(e,t,r,n){Promise.resolve(n).then((function(t){e({value:t,done:r})}),t)})(n,i,(t=e[r](t)).done,t.value)}))}}}function b(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}function _(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function $(e){return e&&e.__esModule?e:{default:e}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0);n.__exportStar(r(22),t),n.__exportStar(r(35),t),n.__exportStar(r(67),t),n.__exportStar(r(68),t),n.__exportStar(r(69),t),n.__exportStar(r(35),t),n.__exportStar(r(25),t),n.__exportStar(r(13),t),n.__exportStar(r(23),t)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0);n.__exportStar(r(55),t),n.__exportStar(r(57),t),n.__exportStar(r(59),t),n.__exportStar(r(29),t),n.__exportStar(r(19),t),n.__exportStar(r(32),t),n.__exportStar(r(33),t),n.__exportStar(r(20),t),n.__exportStar(r(34),t),n.__exportStar(r(62),t),n.__exportStar(r(21),t),n.__exportStar(r(30),t)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(2),i=r(1),o=function(){function e(e,t,r,n){this.transactionConstructor=e,this.core=t,this.message=r,this.delegate=n,this.challenged=!1,this.stale=!1,this.logger=this.loggerFactory.getLogger("sip.user-agent-client"),this.init()}return e.prototype.dispose=function(){this.transaction.dispose()},Object.defineProperty(e.prototype,"loggerFactory",{get:function(){return this.core.loggerFactory},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"transaction",{get:function(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction},enumerable:!0,configurable:!0}),e.prototype.cancel=function(t,r){var o=this;if(void 0===r&&(r={}),!this.transaction)throw new Error("Transaction undefined.");if(!this.message.to)throw new Error("To undefined.");if(!this.message.from)throw new Error("From undefined.");var a=this.core.makeOutgoingRequestMessage(n.C.CANCEL,this.message.ruri,this.message.from.uri,this.message.to.uri,{toTag:this.message.toTag,fromTag:this.message.fromTag,callId:this.message.callId,cseq:this.message.cseq},r.extraHeaders);if(a.branch=this.message.branch,this.message.headers.Route&&(a.headers.Route=this.message.headers.Route),t&&a.setHeader("Reason",t),this.transaction.state===i.TransactionState.Proceeding)new e(i.NonInviteClientTransaction,this.core,a);else this.transaction.once("stateChanged",(function(){if(o.transaction&&o.transaction.state===i.TransactionState.Proceeding)new e(i.NonInviteClientTransaction,o.core,a)}));return a},e.prototype.authenticationGuard=function(e){var t,r,n=e.statusCode;if(!n)throw new Error("Response status code undefined.");if(401!==n&&407!==n)return!0;if(401===n?(t=e.parseHeader("www-authenticate"),r="authorization"):(t=e.parseHeader("proxy-authenticate"),r="proxy-authorization"),!t)return this.logger.warn(n+" with wrong or missing challenge, cannot authenticate"),!0;if(this.challenged&&(this.stale||!0!==t.stale))return this.logger.warn(n+" apparently in authentication loop, cannot authenticate"),!0;if(!this.credentials&&(this.credentials=this.core.configuration.authenticationFactory(),!this.credentials))return this.logger.warn("Unable to obtain credentials, cannot authenticate"),!0;if(!this.credentials.authenticate(this.message,t))return!0;this.challenged=!0,t.stale&&(this.stale=!0);var i=this.message.cseq+=1;return this.message.setHeader("cseq",i+" "+this.message.method),this.message.setHeader(r,this.credentials.toString()),this.init(),!1},e.prototype.receiveResponse=function(e){if(this.authenticationGuard(e)){var t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e});break;case/^1[0-9]{2}$/.test(t):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e});break;case/^2[0-9]{2}$/.test(t):this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e});break;case/^3[0-9]{2}$/.test(t):this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e});break;case/^[4-6][0-9]{2}$/.test(t):this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e});break;default:throw new Error("Invalid status code "+t)}}},e.prototype.init=function(){var e=this,t={loggerFactory:this.loggerFactory,onRequestTimeout:function(){return e.onRequestTimeout()},onStateChange:function(t){t===i.TransactionState.Terminated&&(e.core.userAgentClients.delete(n),r===e._transaction&&e.dispose())},onTransportError:function(t){return e.onTransportError(t)},receiveResponse:function(t){return e.receiveResponse(t)}},r=new this.transactionConstructor(this.message,this.core.transport,t);this._transaction=r;var n=r.id+r.request.method;this.core.userAgentClients.set(n,this)},e.prototype.onRequestTimeout=function(){this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout.");var e=new n.IncomingResponseMessage;e.statusCode=408,e.reasonPhrase="Request Timeout",this.receiveResponse(e)},e.prototype.onTransportError=function(e){this.logger.error(e.message),this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable.");var t=new n.IncomingResponseMessage;t.statusCode=503,t.reasonPhrase="Service Unavailable",this.receiveResponse(t)},e}();t.UserAgentClient=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(16),i=r(2),o=r(10),a=r(1),s=function(){function e(e,t,r,n){this.transactionConstructor=e,this.core=t,this.message=r,this.delegate=n,this.logger=this.loggerFactory.getLogger("sip.user-agent-server"),this.toTag=r.toTag?r.toTag:o.newTag(),this.init()}return e.prototype.dispose=function(){this.transaction.dispose()},Object.defineProperty(e.prototype,"loggerFactory",{get:function(){return this.core.loggerFactory},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"transaction",{get:function(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction},enumerable:!0,configurable:!0}),e.prototype.accept=function(e){if(void 0===e&&(e={statusCode:200}),!this.acceptable)throw new n.TransactionStateError(this.message.method+" not acceptable in state "+this.transaction.state+".");var t=e.statusCode;if(t<200||t>299)throw new TypeError("Invalid statusCode: "+t);return this.reply(e)},e.prototype.progress=function(e){if(void 0===e&&(e={statusCode:180}),!this.progressable)throw new n.TransactionStateError(this.message.method+" not progressable in state "+this.transaction.state+".");var t=e.statusCode;if(t<101||t>199)throw new TypeError("Invalid statusCode: "+t);return this.reply(e)},e.prototype.redirect=function(e,t){if(void 0===t&&(t={statusCode:302}),!this.redirectable)throw new n.TransactionStateError(this.message.method+" not redirectable in state "+this.transaction.state+".");var r=t.statusCode;if(r<300||r>399)throw new TypeError("Invalid statusCode: "+r);var i=new Array;return e.forEach((function(e){return i.push("Contact: "+e.toString())})),t.extraHeaders=(t.extraHeaders||[]).concat(i),this.reply(t)},e.prototype.reject=function(e){if(void 0===e&&(e={statusCode:480}),!this.rejectable)throw new n.TransactionStateError(this.message.method+" not rejectable in state "+this.transaction.state+".");var t=e.statusCode;if(t<400||t>699)throw new TypeError("Invalid statusCode: "+t);return this.reply(e)},e.prototype.trying=function(e){if(!this.tryingable)throw new n.TransactionStateError(this.message.method+" not tryingable in state "+this.transaction.state+".");return this.reply({statusCode:100})},e.prototype.receiveCancel=function(e){this.delegate&&this.delegate.onCancel&&this.delegate.onCancel(e)},Object.defineProperty(e.prototype,"acceptable",{get:function(){if(this.transaction instanceof a.InviteServerTransaction)return this.transaction.state===a.TransactionState.Proceeding||this.transaction.state===a.TransactionState.Accepted;if(this.transaction instanceof a.NonInviteServerTransaction)return this.transaction.state===a.TransactionState.Trying||this.transaction.state===a.TransactionState.Proceeding;throw new Error("Unknown transaction type.")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"progressable",{get:function(){if(this.transaction instanceof a.InviteServerTransaction)return this.transaction.state===a.TransactionState.Proceeding;if(this.transaction instanceof a.NonInviteServerTransaction)return!1;throw new Error("Unknown transaction type.")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"redirectable",{get:function(){if(this.transaction instanceof a.InviteServerTransaction)return this.transaction.state===a.TransactionState.Proceeding;if(this.transaction instanceof a.NonInviteServerTransaction)return this.transaction.state===a.TransactionState.Trying||this.transaction.state===a.TransactionState.Proceeding;throw new Error("Unknown transaction type.")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rejectable",{get:function(){if(this.transaction instanceof a.InviteServerTransaction)return this.transaction.state===a.TransactionState.Proceeding;if(this.transaction instanceof a.NonInviteServerTransaction)return this.transaction.state===a.TransactionState.Trying||this.transaction.state===a.TransactionState.Proceeding;throw new Error("Unknown transaction type.")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"tryingable",{get:function(){if(this.transaction instanceof a.InviteServerTransaction)return this.transaction.state===a.TransactionState.Proceeding;if(this.transaction instanceof a.NonInviteServerTransaction)return this.transaction.state===a.TransactionState.Trying;throw new Error("Unknown transaction type.")},enumerable:!0,configurable:!0}),e.prototype.reply=function(e){e.toTag||100===e.statusCode||(e.toTag=this.toTag),e.userAgent=e.userAgent||this.core.configuration.userAgentHeaderFieldValue,e.supported=e.supported||this.core.configuration.supportedOptionTagsResponse;var t=i.constructOutgoingResponse(this.message,e);return this.transaction.receiveResponse(e.statusCode,t.message),t},e.prototype.init=function(){var e=this,t={loggerFactory:this.loggerFactory,onStateChange:function(t){t===a.TransactionState.Terminated&&(e.core.userAgentServers.delete(n),e.dispose())},onTransportError:function(t){e.logger.error(t.message),e.delegate&&e.delegate.onTransportError?e.delegate.onTransportError(t):e.logger.error("User agent server response transport error.")}},r=new this.transactionConstructor(this.message,this.core.transport,t);this._transaction=r;var n=r.id;this.core.userAgentServers.set(r.id,this)},e}();t.UserAgentServer=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0);n.__exportStar(r(17),t),n.__exportStar(r(16),t),n.__exportStar(r(71),t),n.__exportStar(r(2),t),n.__exportStar(r(15),t),n.__exportStar(r(27),t),n.__exportStar(r(1),t),n.__exportStar(r(73),t),n.__exportStar(r(50),t),n.__exportStar(r(6),t),n.__exportStar(r(86),t)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=500;t.Timers={T1:n,T2:4e3,T4:5e3,TIMER_B:32e3,TIMER_D:0,TIMER_F:32e3,TIMER_H:32e3,TIMER_I:0,TIMER_J:0,TIMER_K:0,TIMER_L:32e3,TIMER_M:32e3,TIMER_N:32e3,PROVISIONAL_RESPONSE_INTERVAL:6e4}},function(e,t,r){"use strict";var n,i="object"==typeof Reflect?Reflect:null,o=i&&"function"==typeof i.apply?i.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};n=i&&"function"==typeof i.ownKeys?i.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var a=Number.isNaN||function(e){return e!=e};function s(){s.init.call(this)}e.exports=s,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var c=10;function u(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function d(e,t,r,n){var i,o,a,s;if("function"!=typeof r)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof r);if(void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),o=e._events),a=o[t]),void 0===a)a=o[t]=r,++e._eventsCount;else if("function"==typeof a?a=o[t]=n?[r,a]:[a,r]:n?a.unshift(r):a.push(r),(i=u(e))>0&&a.length>i&&!a.warned){a.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=a.length,s=c,console&&console.warn&&console.warn(s)}return e}function l(){for(var e=[],t=0;t0&&(a=t[0]),a instanceof Error)throw a;var s=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw s.context=a,s}var c=i[e];if(void 0===c)return!1;if("function"==typeof c)o(c,this,t);else{var u=c.length,d=g(c,u);for(r=0;r=0;o--)if(r[o]===t||r[o].listener===t){a=r[o].listener,i=o;break}if(i<0)return this;0===i?r.shift():function(e,t){for(;t+1=0;n--)this.removeListener(e,t[n]);return this},s.prototype.listeners=function(e){return p(this,e,!0)},s.prototype.rawListeners=function(e){return p(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):f.call(e,t)},s.prototype.listenerCount=f,s.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]}},,,function(e,t,r){"use strict";function n(e,t){void 0===t&&(t=32);for(var r="",n=0;n=this.headers[e].length)){var r=this.headers[e][t],o=r.raw;if(r.parsed)return r.parsed;var a=n.Grammar.parse(o,e.replace(/-/g,"_"));return-1===a?void this.headers[e].splice(t,1):(r.parsed=a,a)}},e.prototype.s=function(e,t){return void 0===t&&(t=0),this.parseHeader(e,t)},e.prototype.setHeader=function(e,t){this.headers[i.headerize(e)]=[{raw:t}]},e.prototype.toString=function(){return this.data},e}();t.IncomingMessage=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=function(e){function t(t,r,n){var i=e.call(this,n)||this;return i.uri=t,i._displayName=r,i}return n.__extends(t,e),Object.defineProperty(t.prototype,"friendlyName",{get:function(){return this.displayName||this.uri.aor},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"displayName",{get:function(){return this._displayName},set:function(e){this._displayName=e},enumerable:!0,configurable:!0}),t.prototype.clone=function(){return new t(this.uri.clone(),this._displayName,JSON.parse(JSON.stringify(this.parameters)))},t.prototype.toString=function(){var e=this.displayName||"0"===this.displayName?'"'+this.displayName+'" ':"";for(var t in e+="<"+this.uri.toString()+">",this.parameters)this.parameters.hasOwnProperty(t)&&(e+=";"+t,null!==this.parameters[t]&&(e+="="+this.parameters[t]));return e},t}(r(21).Parameters);t.NameAddrHeader=i},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(e){for(var t in this.parameters={},e)e.hasOwnProperty(t)&&this.setParam(t,e[t])}return e.prototype.setParam=function(e,t){e&&(this.parameters[e.toLowerCase()]=null==t?null:t.toString())},e.prototype.getParam=function(e){if(e)return this.parameters[e.toLowerCase()]},e.prototype.hasParam=function(e){return!!e&&!!this.parameters.hasOwnProperty(e.toLowerCase())},e.prototype.deleteParam=function(e){if(e=e.toLowerCase(),this.parameters.hasOwnProperty(e)){var t=this.parameters[e];return delete this.parameters[e],t}},e.prototype.clearParams=function(){this.parameters={}},e}();t.Parameters=n},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=function(e){function t(r,n,i,o,a){var s=e.call(this,n,i,t.makeId(r),o,a)||this;s._request=r,s.user=i;var c=n.server&&n.server.scheme?n.server.scheme:void 0;return r.setViaHeader(s.id,c),s}return n.__extends(t,e),t.makeId=function(e){if("CANCEL"===e.method){if(!e.branch)throw new Error("Outgoing CANCEL request without a branch.");return e.branch}return"z9hG4bK"+Math.floor(1e7*Math.random())},Object.defineProperty(t.prototype,"request",{get:function(){return this._request},enumerable:!0,configurable:!0}),t.prototype.onRequestTimeout=function(){this.user.onRequestTimeout&&this.user.onRequestTimeout()},t}(r(23).Transaction);t.ClientTransaction=i},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=r(7),o=r(16),a=function(e){function t(t,r,n,i,o){var a=e.call(this)||this;return a._transport=t,a._user=r,a._id=n,a._state=i,a.logger=r.loggerFactory.getLogger(o,n),a.logger.debug("Constructing "+a.typeToString()+" with id "+a.id+"."),a}return n.__extends(t,e),t.prototype.dispose=function(){this.logger.debug("Destroyed "+this.typeToString()+" with id "+this.id+".")},Object.defineProperty(t.prototype,"id",{get:function(){return this._id},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"kind",{get:function(){throw new Error("Invalid kind.")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"state",{get:function(){return this._state},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"transport",{get:function(){return this._transport},enumerable:!0,configurable:!0}),t.prototype.on=function(t,r){return e.prototype.on.call(this,t,r)},t.prototype.logTransportError=function(e,t){this.logger.error(e.message),this.logger.error("Transport error occurred in "+this.typeToString()+" with id "+this.id+"."),this.logger.error(t)},t.prototype.send=function(e){var t=this;return this.transport.send(e).catch((function(e){var r;if(!(e instanceof o.TransportError))throw r=e&&"string"==typeof e.message?new o.TransportError(e.message):new o.TransportError,t.onTransportError(r),r;t.onTransportError(e)}))},t.prototype.setState=function(e){this.logger.debug('State change to "'+e+'" on '+this.typeToString()+" with id "+this.id+"."),this._state=e,this._user.onStateChange&&this._user.onStateChange(e),this.emit("stateChanged")},t.prototype.typeToString=function(){return"UnknownType"},t}(i.EventEmitter);t.Transaction=a},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=function(e){function t(t){var r=this.constructor,n=e.call(this,t)||this;return Object.setPrototypeOf(n,r.prototype),n}return n.__extends(t,e),t}(Error);t.Exception=i},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=function(e){function t(t,r,n,i,o){var a=e.call(this,r,n,t.viaBranch,i,o)||this;return a._request=t,a.user=n,a}return n.__extends(t,e),Object.defineProperty(t.prototype,"request",{get:function(){return this._request},enumerable:!0,configurable:!0}),t}(r(23).Transaction);t.ServerTransaction=i},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=r(1),o=function(e){function t(t,r,n){var o=void 0!==t.userAgentCore?t.userAgentCore:t;return e.call(this,i.NonInviteServerTransaction,o,r,n)||this}return n.__extends(t,e),t}(r(4).UserAgentServer);t.NotifyUserAgentServer=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),r(0).__exportStar(r(70),t)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e){e[e.error=0]="error",e[e.warn=1]="warn",e[e.log=2]="log",e[e.debug=3]="debug"}(t.Levels||(t.Levels={}))},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0).__importStar(r(58));!function(e){e.parse=function(e,t){var r={startRule:t};try{n.parse(e,r)}catch(e){r.data=-1}return r.data},e.nameAddrHeaderParse=function(t){var r=e.parse(t,"Name_Addr_Header");return-1!==r?r:void 0},e.URIParse=function(t){var r=e.parse(t,"SIP_URI");return-1!==r?r:void 0}}(t.Grammar||(t.Grammar={}))},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=function(e){function t(t,r,n,i,o,a){var s=e.call(this,o)||this;if(s.headers={},!n)throw new TypeError('missing or invalid "host" parameter');for(var c in t=t||"sip",a)a.hasOwnProperty(c)&&s.setHeader(c,a[c]);return s.raw={scheme:t,user:r,host:n,port:i},s.normal={scheme:t.toLowerCase(),user:r,host:n.toLowerCase(),port:i},s}return n.__extends(t,e),Object.defineProperty(t.prototype,"scheme",{get:function(){return this.normal.scheme},set:function(e){this.raw.scheme=e,this.normal.scheme=e.toLowerCase()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"user",{get:function(){return this.normal.user},set:function(e){this.normal.user=this.raw.user=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"host",{get:function(){return this.normal.host},set:function(e){this.raw.host=e,this.normal.host=e.toLowerCase()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"aor",{get:function(){return this.normal.user+"@"+this.normal.host},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"port",{get:function(){return this.normal.port},set:function(e){this.normal.port=this.raw.port=e},enumerable:!0,configurable:!0}),t.prototype.setHeader=function(e,t){this.headers[this.headerize(e)]=t instanceof Array?t:[t]},t.prototype.getHeader=function(e){if(e)return this.headers[this.headerize(e)]},t.prototype.hasHeader=function(e){return!!e&&!!this.headers.hasOwnProperty(this.headerize(e))},t.prototype.deleteHeader=function(e){if(e=this.headerize(e),this.headers.hasOwnProperty(e)){var t=this.headers[e];return delete this.headers[e],t}},t.prototype.clearHeaders=function(){this.headers={}},t.prototype.clone=function(){return new t(this._raw.scheme,this._raw.user||"",this._raw.host,this._raw.port,JSON.parse(JSON.stringify(this.parameters)),JSON.parse(JSON.stringify(this.headers)))},t.prototype.toRaw=function(){return this._toString(this._raw)},t.prototype.toString=function(){return this._toString(this._normal)},Object.defineProperty(t.prototype,"_normal",{get:function(){return this.normal},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"_raw",{get:function(){return this.raw},enumerable:!0,configurable:!0}),t.prototype._toString=function(e){var t=e.scheme+":";for(var r in e.scheme.toLowerCase().match("^sips?$")||(t+="//"),e.user&&(t+=this.escapeUser(e.user)+"@"),t+=e.host,(e.port||0===e.port)&&(t+=":"+e.port),this.parameters)this.parameters.hasOwnProperty(r)&&(t+=";"+r,null!==this.parameters[r]&&(t+="="+this.parameters[r]));var n=[];for(var i in this.headers)if(this.headers.hasOwnProperty(i))for(var o in this.headers[i])this.headers[i].hasOwnProperty(o)&&n.push(i+"="+this.headers[i][o]);return n.length>0&&(t+="?"+n.join("&")),t},t.prototype.escapeUser=function(e){var t;try{t=decodeURIComponent(e)}catch(e){throw e}return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%2B/gi,"+").replace(/%3F/gi,"?").replace(/%2F/gi,"/")},t.prototype.headerize=function(e){for(var t={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},r=e.toLowerCase().replace(/_/g,"-").split("-"),n=r.length,i="",o=0;o699)throw new Error("Invalid status code "+r);switch(this.state){case a.TransactionState.Calling:if(r>=100&&r<=199)return this.stateTransition(a.TransactionState.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(r>=200&&r<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(a.TransactionState.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(r>=300&&r<=699)return this.stateTransition(a.TransactionState.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case a.TransactionState.Proceeding:if(r>=100&&r<=199)return void(this.user.receiveResponse&&this.user.receiveResponse(e));if(r>=200&&r<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(a.TransactionState.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(r>=300&&r<=699)return this.stateTransition(a.TransactionState.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case a.TransactionState.Accepted:if(r>=200&&r<=299){if(!this.ackRetransmissionCache.has(e.toTag))return this.ackRetransmissionCache.set(e.toTag,void 0),void(this.user.receiveResponse&&this.user.receiveResponse(e));var n=this.ackRetransmissionCache.get(e.toTag);return n?void this.send(n.toString()).catch((function(e){t.logTransportError(e,"Failed to send retransmission of ACK to 2xx response.")})):void 0}break;case a.TransactionState.Completed:if(r>=300&&r<=699)return void this.ack(e);break;case a.TransactionState.Terminated:break;default:throw new Error("Invalid state "+this.state)}var i="Received unexpected "+r+" response while in state "+this.state+".";this.logger.warn(i)},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(a.TransactionState.Terminated,!0)},t.prototype.typeToString=function(){return"INVITE client transaction"},t.prototype.ack=function(e){var t=this,r=this.request.ruri,n=this.request.callId,i=this.request.cseq,o=this.request.getHeader("from"),a=e.getHeader("to"),s=this.request.getHeader("via"),c=this.request.getHeader("route");if(!o)throw new Error("From undefined.");if(!a)throw new Error("To undefined.");if(!s)throw new Error("Via undefined.");var u="ACK "+r+" SIP/2.0\r\n";c&&(u+="Route: "+c+"\r\n"),u+="Via: "+s+"\r\n",u+="To: "+a+"\r\n",u+="From: "+o+"\r\n",u+="Call-ID: "+n+"\r\n",u+="CSeq: "+i+" ACK\r\n",u+="Max-Forwards: 70\r\n",u+="Content-Length: 0\r\n\r\n",this.send(u).catch((function(e){t.logTransportError(e,"Failed to send ACK to non-2xx response.")}))},t.prototype.stateTransition=function(e,t){var r=this;void 0===t&&(t=!1);var n=function(){throw new Error("Invalid state transition from "+r.state+" to "+e)};switch(e){case a.TransactionState.Calling:n();break;case a.TransactionState.Proceeding:this.state!==a.TransactionState.Calling&&n();break;case a.TransactionState.Accepted:case a.TransactionState.Completed:this.state!==a.TransactionState.Calling&&this.state!==a.TransactionState.Proceeding&&n();break;case a.TransactionState.Terminated:this.state!==a.TransactionState.Calling&&this.state!==a.TransactionState.Accepted&&this.state!==a.TransactionState.Completed&&(t||n());break;default:n()}this.B&&(clearTimeout(this.B),this.B=void 0),a.TransactionState.Proceeding,e===a.TransactionState.Completed&&(this.D=setTimeout((function(){return r.timer_D()}),i.Timers.TIMER_D)),e===a.TransactionState.Accepted&&(this.M=setTimeout((function(){return r.timer_M()}),i.Timers.TIMER_M)),e===a.TransactionState.Terminated&&this.dispose(),this.setState(e)},t.prototype.timer_A=function(){},t.prototype.timer_B=function(){this.logger.debug("Timer B expired for INVITE client transaction "+this.id+"."),this.state===a.TransactionState.Calling&&(this.onRequestTimeout(),this.stateTransition(a.TransactionState.Terminated))},t.prototype.timer_D=function(){this.logger.debug("Timer D expired for INVITE client transaction "+this.id+"."),this.state===a.TransactionState.Completed&&this.stateTransition(a.TransactionState.Terminated)},t.prototype.timer_M=function(){this.logger.debug("Timer M expired for INVITE client transaction "+this.id+"."),this.state===a.TransactionState.Accepted&&this.stateTransition(a.TransactionState.Terminated)},t}(o.ClientTransaction);t.InviteClientTransaction=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=r(2),o=r(1),a=function(e){function t(t,r,n){var a,s=t.createOutgoingRequestMessage(i.C.BYE,n);return a=e.call(this,o.NonInviteClientTransaction,t.userAgentCore,s,r)||this,t.dispose(),a}return n.__extends(t,e),t}(r(3).UserAgentClient);t.ByeUserAgentClient=a},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=r(1),o=function(e){function t(t,r,n){return e.call(this,i.NonInviteServerTransaction,t.userAgentCore,r,n)||this}return n.__extends(t,e),t}(r(4).UserAgentServer);t.ByeUserAgentServer=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=r(2),o=r(1),a=function(e){function t(t,r,n){var a=t.createOutgoingRequestMessage(i.C.INFO,n);return e.call(this,o.NonInviteClientTransaction,t.userAgentCore,a,r)||this}return n.__extends(t,e),t}(r(3).UserAgentClient);t.InfoUserAgentClient=a},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=r(1),o=function(e){function t(t,r,n){return e.call(this,i.NonInviteServerTransaction,t.userAgentCore,r,n)||this}return n.__extends(t,e),t}(r(4).UserAgentServer);t.InfoUserAgentServer=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=r(2),o=r(1),a=function(e){function t(t,r,n){var a=t.createOutgoingRequestMessage(i.C.NOTIFY,n);return e.call(this,o.NonInviteClientTransaction,t.userAgentCore,a,r)||this}return n.__extends(t,e),t}(r(3).UserAgentClient);t.NotifyUserAgentClient=a},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=r(2),o=r(1),a=function(e){function t(t,r,n){var a,s=t.createOutgoingRequestMessage(i.C.PRACK,n);return a=e.call(this,o.NonInviteClientTransaction,t.userAgentCore,s,r)||this,t.signalingStateTransition(s),a}return n.__extends(t,e),t}(r(3).UserAgentClient);t.PrackUserAgentClient=a},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=r(1),o=function(e){function t(t,r,n){var o=e.call(this,i.NonInviteServerTransaction,t.userAgentCore,r,n)||this;return t.signalingStateTransition(r),o.dialog=t,o}return n.__extends(t,e),t.prototype.accept=function(t){return void 0===t&&(t={statusCode:200}),t.body&&this.dialog.signalingStateTransition(t.body),e.prototype.accept.call(this,t)},t}(r(4).UserAgentServer);t.PrackUserAgentServer=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=r(2),o=r(1),a=function(e){function t(t,r,n){var a=this,s=t.createOutgoingRequestMessage(i.C.INVITE,n);return(a=e.call(this,o.InviteClientTransaction,t.userAgentCore,s,r)||this).delegate=r,t.signalingStateTransition(s),t.reinviteUserAgentClient=a,a.dialog=t,a}return n.__extends(t,e),t.prototype.receiveResponse=function(e){var t=this,r=e.statusCode?e.statusCode.toString():"";if(!r)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(r):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e});break;case/^1[0-9]{2}$/.test(r):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:this.dialog,prack:function(e){throw new Error("Unimplemented.")}});break;case/^2[0-9]{2}$/.test(r):this.dialog.signalingStateTransition(e),this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e,session:this.dialog,ack:function(e){return t.dialog.ack(e)}});break;case/^3[0-9]{2}$/.test(r):this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentClient=void 0,this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e});break;case/^[4-6][0-9]{2}$/.test(r):this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentClient=void 0,this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e});break;default:throw new Error("Invalid status code "+r)}},t}(r(3).UserAgentClient);t.ReInviteUserAgentClient=a},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=r(1),o=function(e){function t(t,r,n){var o=e.call(this,i.InviteServerTransaction,t.userAgentCore,r,n)||this;return t.reinviteUserAgentServer=o,o.dialog=t,o}return n.__extends(t,e),t.prototype.accept=function(t){void 0===t&&(t={statusCode:200}),t.extraHeaders=t.extraHeaders||[],t.extraHeaders=t.extraHeaders.concat(this.dialog.routeSet.map((function(e){return"Record-Route: "+e})));var r=e.prototype.accept.call(this,t),i=this.dialog,o=n.__assign({},r,{session:i});return t.body&&this.dialog.signalingStateTransition(t.body),this.dialog.reConfirm(),o},t.prototype.progress=function(t){void 0===t&&(t={statusCode:180});var r=e.prototype.progress.call(this,t),i=this.dialog,o=n.__assign({},r,{session:i});return t.body&&this.dialog.signalingStateTransition(t.body),o},t.prototype.redirect=function(e,t){throw void 0===t&&(t={statusCode:302}),this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,new Error("Unimplemented.")},t.prototype.reject=function(t){return void 0===t&&(t={statusCode:488}),this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,e.prototype.reject.call(this,t)},t}(r(4).UserAgentServer);t.ReInviteUserAgentServer=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=r(2),o=r(1),a=function(e){function t(t,r,n){var a=t.createOutgoingRequestMessage(i.C.REFER,n);return e.call(this,o.NonInviteClientTransaction,t.userAgentCore,a,r)||this}return n.__extends(t,e),t}(r(3).UserAgentClient);t.ReferUserAgentClient=a},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=r(1),o=function(e){function t(t,r,n){var o=void 0!==t.userAgentCore?t.userAgentCore:t;return e.call(this,i.NonInviteServerTransaction,o,r,n)||this}return n.__extends(t,e),t}(r(4).UserAgentServer);t.ReferUserAgentServer=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=r(2),o=r(27),a=r(6),s=r(14),c=r(26),u=r(48),d=function(e){function t(t,r,n,i,o,a){var s=e.call(this,i,o)||this;return s.delegate=a,s._autoRefresh=!1,s._subscriptionEvent=t,s._subscriptionExpires=r,s._subscriptionExpiresInitial=r,s._subscriptionExpiresLastSet=Math.floor(Date.now()/1e3),s._subscriptionRefresh=void 0,s._subscriptionRefreshLastSet=void 0,s._subscriptionState=n,s.logger=i.loggerFactory.getLogger("sip.subscribe-dialog"),s.logger.log("SUBSCRIBE dialog "+s.id+" constructed"),s}return n.__extends(t,e),t.initialDialogStateForSubscription=function(e,t){var r=t.getHeaders("record-route"),n=t.parseHeader("contact");if(!n)throw new Error("Contact undefined.");if(!(n instanceof i.NameAddrHeader))throw new Error("Contact not instance of NameAddrHeader.");var o=n.uri,a=e.cseq,s=e.callId,c=e.fromTag,u=t.fromTag;if(!s)throw new Error("Call id undefined.");if(!c)throw new Error("From tag undefined.");if(!u)throw new Error("To tag undefined.");if(!e.from)throw new Error("From undefined.");if(!e.to)throw new Error("To undefined.");return{id:s+c+u,early:!1,callId:s,localTag:c,remoteTag:u,localSequenceNumber:a,remoteSequenceNumber:void 0,localURI:e.from.uri,remoteURI:e.to.uri,remoteTarget:o,routeSet:r,secure:!1}},t.prototype.dispose=function(){e.prototype.dispose.call(this),this.N&&(clearTimeout(this.N),this.N=void 0),this.refreshTimerClear(),this.logger.log("SUBSCRIBE dialog "+this.id+" destroyed")},Object.defineProperty(t.prototype,"autoRefresh",{get:function(){return this._autoRefresh},set:function(e){this._autoRefresh=!0,this.refreshTimerSet()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionEvent",{get:function(){return this._subscriptionEvent},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionExpires",{get:function(){var e=Math.floor(Date.now()/1e3)-this._subscriptionExpiresLastSet,t=this._subscriptionExpires-e;return Math.max(t,0)},set:function(e){if(e<0)throw new Error("Expires must be greater than or equal to zero.");if(this._subscriptionExpires=e,this._subscriptionExpiresLastSet=Math.floor(Date.now()/1e3),this.autoRefresh){var t=this.subscriptionRefresh;(void 0===t||t>=e)&&this.refreshTimerSet()}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionExpiresInitial",{get:function(){return this._subscriptionExpiresInitial},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionRefresh",{get:function(){if(void 0!==this._subscriptionRefresh&&void 0!==this._subscriptionRefreshLastSet){var e=Math.floor(Date.now()/1e3)-this._subscriptionRefreshLastSet,t=this._subscriptionRefresh-e;return Math.max(t,0)}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionState",{get:function(){return this._subscriptionState},enumerable:!0,configurable:!0}),t.prototype.receiveRequest=function(t){if(this.logger.log("SUBSCRIBE dialog "+this.id+" received "+t.method+" request"),this.sequenceGuard(t))switch(e.prototype.receiveRequest.call(this,t),t.method){case i.C.NOTIFY:this.onNotify(t);break;default:this.logger.log("SUBSCRIBE dialog "+this.id+" received unimplemented "+t.method+" request"),this.core.replyStateless(t,{statusCode:501})}else this.logger.log("SUBSCRIBE dialog "+this.id+" rejected out of order "+t.method+" request.")},t.prototype.refresh=function(){var e="Allow: "+s.AllowedMethods.toString(),t={};return t.extraHeaders=(t.extraHeaders||[]).slice(),t.extraHeaders.push(e),t.extraHeaders.push("Event: "+this.subscriptionEvent),t.extraHeaders.push("Expires: "+this.subscriptionExpiresInitial),t.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,t)},t.prototype.subscribe=function(e,t){var r=this;if(void 0===t&&(t={}),this.subscriptionState!==o.SubscriptionState.Pending&&this.subscriptionState!==o.SubscriptionState.Active)throw new Error("Invalid state "+this.subscriptionState+'. May only re-subscribe while in state "pending" or "active".');this.logger.log("SUBSCRIBE dialog "+this.id+" sending SUBSCRIBE request");var n=new u.ReSubscribeUserAgentClient(this,e,t);return this.N=setTimeout((function(){return r.timer_N()}),a.Timers.TIMER_N),n},t.prototype.terminate=function(){this.stateTransition(o.SubscriptionState.Terminated),this.onTerminated()},t.prototype.unsubscribe=function(){var e="Allow: "+s.AllowedMethods.toString(),t={};return t.extraHeaders=(t.extraHeaders||[]).slice(),t.extraHeaders.push(e),t.extraHeaders.push("Event: "+this.subscriptionEvent),t.extraHeaders.push("Expires: 0"),t.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,t)},t.prototype.onNotify=function(e){var t=e.parseHeader("Event").event;if(t&&t===this.subscriptionEvent){this.N&&(clearTimeout(this.N),this.N=void 0);var r=e.parseHeader("Subscription-State");if(r&&r.state){var n=r.state,i=r.expires?Math.max(r.expires,0):void 0;switch(n){case"pending":this.stateTransition(o.SubscriptionState.Pending,i);break;case"active":this.stateTransition(o.SubscriptionState.Active,i);break;case"terminated":this.stateTransition(o.SubscriptionState.Terminated,i);break;default:this.logger.warn("Unrecognized subscription state.")}var a=new c.NotifyUserAgentServer(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(a):a.accept()}else this.core.replyStateless(e,{statusCode:489})}else this.core.replyStateless(e,{statusCode:489})},t.prototype.onRefresh=function(e){this.delegate&&this.delegate.onRefresh&&this.delegate.onRefresh(e)},t.prototype.onTerminated=function(){this.delegate&&this.delegate.onTerminated&&this.delegate.onTerminated()},t.prototype.refreshTimerClear=function(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=void 0)},t.prototype.refreshTimerSet=function(){var e=this;if(this.refreshTimerClear(),this.autoRefresh&&this.subscriptionExpires>0){var t=900*this.subscriptionExpires;this._subscriptionRefresh=Math.floor(t/1e3),this._subscriptionRefreshLastSet=Math.floor(Date.now()/1e3),this.refreshTimer=setTimeout((function(){e.refreshTimer=void 0,e._subscriptionRefresh=void 0,e._subscriptionRefreshLastSet=void 0,e.onRefresh(e.refresh())}),t)}},t.prototype.stateTransition=function(e,t){var r=this,n=function(){r.logger.warn("Invalid subscription state transition from "+r.subscriptionState+" to "+e)};switch(e){case o.SubscriptionState.Initial:case o.SubscriptionState.NotifyWait:return void n();case o.SubscriptionState.Pending:if(this.subscriptionState!==o.SubscriptionState.NotifyWait&&this.subscriptionState!==o.SubscriptionState.Pending)return void n();break;case o.SubscriptionState.Active:case o.SubscriptionState.Terminated:if(this.subscriptionState!==o.SubscriptionState.NotifyWait&&this.subscriptionState!==o.SubscriptionState.Pending&&this.subscriptionState!==o.SubscriptionState.Active)return void n();break;default:return void n()}e===o.SubscriptionState.Pending&&t&&(this.subscriptionExpires=t),e===o.SubscriptionState.Active&&t&&(this.subscriptionExpires=t),e===o.SubscriptionState.Terminated&&this.dispose(),this._subscriptionState=e},t.prototype.timer_N=function(){this.subscriptionState!==o.SubscriptionState.Terminated&&(this.stateTransition(o.SubscriptionState.Terminated),this.onTerminated())},t}(r(18).Dialog);t.SubscriptionDialog=d},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=r(2),o=r(1),a=function(e){function t(t,r,n){var a=this,s=t.createOutgoingRequestMessage(i.C.SUBSCRIBE,n);return(a=e.call(this,o.NonInviteClientTransaction,t.userAgentCore,s,r)||this).dialog=t,a}return n.__extends(t,e),t.prototype.waitNotifyStop=function(){},t.prototype.receiveResponse=function(t){if(t.statusCode&&t.statusCode>=200&&t.statusCode<300){var r=t.getHeader("Expires");if(r){var n=Number(r);this.dialog.subscriptionExpires>n&&(this.dialog.subscriptionExpires=n)}else this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE")}if(t.statusCode&&t.statusCode>=400&&t.statusCode<700){[404,405,410,416,480,481,482,483,484,485,489,501,604].includes(t.statusCode)&&this.dialog.terminate()}e.prototype.receiveResponse.call(this,t)},t}(r(3).UserAgentClient);t.ReSubscribeUserAgentClient=a},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(28),i=function(){function e(e,t,r){this.logger=e,this.category=t,this.label=r}return e.prototype.error=function(e){this.genericLog(n.Levels.error,e)},e.prototype.warn=function(e){this.genericLog(n.Levels.warn,e)},e.prototype.log=function(e){this.genericLog(n.Levels.log,e)},e.prototype.debug=function(e){this.genericLog(n.Levels.debug,e)},e.prototype.genericLog=function(e,t){this.logger.genericLog(e,this.category,this.label,t)},e}();t.Logger=i},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0);n.__exportStar(r(36),t),n.__exportStar(r(37),t),n.__exportStar(r(75),t),n.__exportStar(r(38),t),n.__exportStar(r(39),t),n.__exportStar(r(76),t),n.__exportStar(r(77),t),n.__exportStar(r(78),t),n.__exportStar(r(79),t),n.__exportStar(r(40),t),n.__exportStar(r(26),t),n.__exportStar(r(80),t),n.__exportStar(r(41),t),n.__exportStar(r(42),t),n.__exportStar(r(43),t),n.__exportStar(r(44),t),n.__exportStar(r(48),t),n.__exportStar(r(81),t),n.__exportStar(r(45),t),n.__exportStar(r(46),t),n.__exportStar(r(82),t),n.__exportStar(r(83),t),n.__exportStar(r(84),t),n.__exportStar(r(85),t),n.__exportStar(r(3),t),n.__exportStar(r(4),t)},,,,,function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),r(0).__exportStar(r(56),t)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e){e.ACK="ACK",e.BYE="BYE",e.CANCEL="CANCEL",e.INFO="INFO",e.INVITE="INVITE",e.MESSAGE="MESSAGE",e.NOTIFY="NOTIFY",e.OPTIONS="OPTIONS",e.REGISTER="REGISTER",e.UPDATE="UPDATE",e.SUBSCRIBE="SUBSCRIBE",e.PUBLISH="PUBLISH",e.REFER="REFER",e.PRACK="PRACK"}(t.C||(t.C={}))},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(32),i=r(33),o=r(34);function a(e){return!(!e||"string"!=typeof e.content||"string"!=typeof e.contentType||void 0!==e.contentDisposition)||"string"==typeof e.contentDisposition}function s(e){return"application/sdp"===e?"session":"render"}t.fromBodyLegacy=function(e){var t="string"==typeof e?e:e.body,r="string"==typeof e?"application/sdp":e.contentType;return{contentDisposition:s(r),contentType:r,content:t}},t.getBody=function(e){var t,r,c,u;if(e instanceof n.IncomingRequestMessage&&e.body&&(t=(u=e.parseHeader("Content-Disposition"))?u.type:void 0,r=e.parseHeader("Content-Type"),c=e.body),e instanceof i.IncomingResponseMessage&&e.body&&(t=(u=e.parseHeader("Content-Disposition"))?u.type:void 0,r=e.parseHeader("Content-Type"),c=e.body),e instanceof o.OutgoingRequestMessage&&e.body)if(t=e.getHeader("Content-Disposition"),r=e.getHeader("Content-Type"),"string"==typeof e.body){if(!r)throw new Error("Header content type header does not equal body content type.");c=e.body}else{if(r&&r!==e.body.contentType)throw new Error("Header content type header does not equal body content type.");r=e.body.contentType,c=e.body.body}if(a(e)&&(t=e.contentDisposition,r=e.contentType,c=e.content),c){if(r&&!t&&(t=s(r)),!t)throw new Error("Content disposition undefined.");if(!r)throw new Error("Content type undefined.");return{contentDisposition:t,contentType:r,content:c}}},t.isBody=a},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=r(20),o=r(30),a=function(e){function t(r,n,i,o){var a=e.call(this)||this;return a.message=r,a.expected=n,a.found=i,a.location=o,a.name="SyntaxError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(a,t),a}return n.__extends(t,e),t.buildMessage=function(e,t){function r(e){return e.charCodeAt(0).toString(16).toUpperCase()}function n(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,(function(e){return"\\x0"+r(e)})).replace(/[\x10-\x1F\x7F-\x9F]/g,(function(e){return"\\x"+r(e)}))}function i(e){return e.replace(/\\/g,"\\\\").replace(/\]/g,"\\]").replace(/\^/g,"\\^").replace(/-/g,"\\-").replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,(function(e){return"\\x0"+r(e)})).replace(/[\x10-\x1F\x7F-\x9F]/g,(function(e){return"\\x"+r(e)}))}function o(e){switch(e.type){case"literal":return'"'+n(e.text)+'"';case"class":var t=e.parts.map((function(e){return Array.isArray(e)?i(e[0])+"-"+i(e[1]):i(e)}));return"["+(e.inverted?"^":"")+t+"]";case"any":return"any character";case"end":return"end of input";case"other":return e.description}}return"Expected "+function(e){var t,r,n=e.map(o);if(n.sort(),n.length>0){for(t=1,r=1;t",S(">",!1),"\\",S("\\",!1),"[",S("[",!1),"]",S("]",!1),"{",S("{",!1),"}",S("}",!1),function(){return"*"},function(){return"/"},function(){return"="},function(){return"("},function(){return")"},function(){return">"},function(){return"<"},function(){return","},function(){return";"},function(){return":"},function(){return'"'},/^[!-']/,T([["!","'"]],!1,!1),/^[*-[]/,T([["*","["]],!1,!1),/^[\]-~]/,T([["]","~"]],!1,!1),function(e){return e},/^[#-[]/,T([["#","["]],!1,!1),/^[\0-\t]/,T([["\0","\t"]],!1,!1),/^[\x0B-\f]/,T([["\v","\f"]],!1,!1),/^[\x0E-\x7F]/,T([["\x0e","\x7f"]],!1,!1),function(){(t=t||{data:{}}).data.uri=new o.URI(t.data.scheme,t.data.user,t.data.host,t.data.port),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port},function(){(t=t||{data:{}}).data.uri=new o.URI(t.data.scheme,t.data.user,t.data.host,t.data.port,t.data.uri_params,t.data.uri_headers),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port,delete t.data.uri_params,"SIP_URI"===t.startRule&&(t.data=t.data.uri)},"sips",S("sips",!0),"sip",S("sip",!0),function(e){(t=t||{data:{}}).data.scheme=e},function(){(t=t||{data:{}}).data.user=decodeURIComponent(m().slice(0,-1))},function(){(t=t||{data:{}}).data.password=m()},function(){return(t=t||{data:{}}).data.host=m(),t.data.host},function(){return(t=t||{data:{}}).data.host_type="domain",m()},/^[a-zA-Z0-9_\-]/,T([["a","z"],["A","Z"],["0","9"],"_","-"],!1,!1),/^[a-zA-Z0-9\-]/,T([["a","z"],["A","Z"],["0","9"],"-"],!1,!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",m()},"::",S("::",!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",m()},function(){return(t=t||{data:{}}).data.host_type="IPv4",m()},"25",S("25",!1),/^[0-5]/,T([["0","5"]],!1,!1),"2",S("2",!1),/^[0-4]/,T([["0","4"]],!1,!1),"1",S("1",!1),/^[1-9]/,T([["1","9"]],!1,!1),function(e){return t=t||{data:{}},e=parseInt(e.join("")),t.data.port=e,e},"transport=",S("transport=",!0),"udp",S("udp",!0),"tcp",S("tcp",!0),"sctp",S("sctp",!0),"tls",S("tls",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.transport=e.toLowerCase()},"user=",S("user=",!0),"phone",S("phone",!0),"ip",S("ip",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.user=e.toLowerCase()},"method=",S("method=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.method=e},"ttl=",S("ttl=",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.ttl=e},"maddr=",S("maddr=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.maddr=e},"lr",S("lr",!0),function(){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.lr=void 0},function(e,r){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),r=null===r?void 0:r[1],t.data.uri_params[e.toLowerCase()]=r},function(e,r){e=e.join("").toLowerCase(),r=r.join(""),(t=t||{data:{}}).data.uri_headers||(t.data.uri_headers={}),t.data.uri_headers[e]?t.data.uri_headers[e].push(r):t.data.uri_headers[e]=[r]},function(){"Refer_To"===(t=t||{data:{}}).startRule&&(t.data.uri=new o.URI(t.data.scheme,t.data.user,t.data.host,t.data.port,t.data.uri_params,t.data.uri_headers),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port,delete t.data.uri_params)},"//",S("//",!1),function(){(t=t||{data:{}}).data.scheme=m()},S("SIP",!0),function(){(t=t||{data:{}}).data.sip_version=m()},"INVITE",S("INVITE",!1),"ACK",S("ACK",!1),"VXACH",S("VXACH",!1),"OPTIONS",S("OPTIONS",!1),"BYE",S("BYE",!1),"CANCEL",S("CANCEL",!1),"REGISTER",S("REGISTER",!1),"SUBSCRIBE",S("SUBSCRIBE",!1),"NOTIFY",S("NOTIFY",!1),"REFER",S("REFER",!1),"PUBLISH",S("PUBLISH",!1),function(){return(t=t||{data:{}}).data.method=m(),t.data.method},function(e){(t=t||{data:{}}).data.status_code=parseInt(e.join(""))},function(){(t=t||{data:{}}).data.reason_phrase=m()},function(){(t=t||{data:{}}).data=m()},function(){var e,r;for(r=(t=t||{data:{}}).data.multi_header.length,e=0;e""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),C(";).# &;,"),C('2F""6F7G.} &2H""6H7I.q &2J""6J7K.e &2L""6L7M.Y &2N""6N7O.M &2P""6P7Q.A &2R""6R7S.5 &2T""6T7U.) &2V""6V7W'),C('%%2X""6X7Y/5#;#/,$;#/#$+#)(#\'#("\'#&\'#/"!&,)'),C('%%$;$0#*;$&/,#; /#$+")("\'#&\'#." &"/=#$;$/�#*;$&&&#/\'$8":Z" )("\'#&\'#'),C(';.." &"'),C("%$;'.# &;(0)*;'.# &;(&/?#28\"\"6879/0$;//'$8#:[# )(#'#(\"'#&'#"),C('%%$;2/�#*;2&&&#/g#$%$;.0#*;.&/,#;2/#$+")("\'#&\'#0=*%$;.0#*;.&/,#;2/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),C('4\\""5!7].# &;3'),C('4^""5!7_'),C('4`""5!7a'),C(';!.) &4b""5!7c'),C('%$;).\x95 &2F""6F7G.\x89 &2J""6J7K.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O/\x9e#0\x9b*;).\x95 &2F""6F7G.\x89 &2J""6J7K.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O&&&#/"!&,)'),C('%$;).\x89 &2F""6F7G.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O/\x92#0\x8f*;).\x89 &2F""6F7G.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O&&&#/"!&,)'),C('2T""6T7U.\xe3 &2V""6V7W.\xd7 &2f""6f7g.\xcb &2h""6h7i.\xbf &2:""6:7;.\xb3 &2D""6D7E.\xa7 &22""6273.\x9b &28""6879.\x8f &2j""6j7k.\x83 &;&.} &24""6475.q &2l""6l7m.e &2n""6n7o.Y &26""6677.M &2>""6>7?.A &2p""6p7q.5 &2r""6r7s.) &;\'.# &;('),C('%$;).\u012b &2F""6F7G.\u011f &2J""6J7K.\u0113 &2L""6L7M.\u0107 &2X""6X7Y.\xfb &2P""6P7Q.\xef &2H""6H7I.\xe3 &2@""6@7A.\xd7 &2d""6d7e.\xcb &2R""6R7S.\xbf &2N""6N7O.\xb3 &2T""6T7U.\xa7 &2V""6V7W.\x9b &2f""6f7g.\x8f &2h""6h7i.\x83 &28""6879.w &2j""6j7k.k &;&.e &24""6475.Y &2l""6l7m.M &2n""6n7o.A &26""6677.5 &2p""6p7q.) &2r""6r7s/\u0134#0\u0131*;).\u012b &2F""6F7G.\u011f &2J""6J7K.\u0113 &2L""6L7M.\u0107 &2X""6X7Y.\xfb &2P""6P7Q.\xef &2H""6H7I.\xe3 &2@""6@7A.\xd7 &2d""6d7e.\xcb &2R""6R7S.\xbf &2N""6N7O.\xb3 &2T""6T7U.\xa7 &2V""6V7W.\x9b &2f""6f7g.\x8f &2h""6h7i.\x83 &28""6879.w &2j""6j7k.k &;&.e &24""6475.Y &2l""6l7m.M &2n""6n7o.A &26""6677.5 &2p""6p7q.) &2r""6r7s&&&#/"!&,)'),C("%;//?#2P\"\"6P7Q/0$;//'$8#:t# )(#'#(\"'#&'#"),C("%;//?#24\"\"6475/0$;//'$8#:u# )(#'#(\"'#&'#"),C("%;//?#2>\"\"6>7?/0$;//'$8#:v# )(#'#(\"'#&'#"),C("%;//?#2T\"\"6T7U/0$;//'$8#:w# )(#'#(\"'#&'#"),C("%;//?#2V\"\"6V7W/0$;//'$8#:x# )(#'#(\"'#&'#"),C('%2h""6h7i/0#;//\'$8":y" )("\'#&\'#'),C('%;//6#2f""6f7g/\'$8":z" )("\'#&\'#'),C("%;//?#2D\"\"6D7E/0$;//'$8#:{# )(#'#(\"'#&'#"),C("%;//?#22\"\"6273/0$;//'$8#:|# )(#'#(\"'#&'#"),C("%;//?#28\"\"6879/0$;//'$8#:}# )(#'#(\"'#&'#"),C("%;//0#;&/'$8\":~\" )(\"'#&'#"),C("%;&/0#;//'$8\":~\" )(\"'#&'#"),C("%;=/T#$;G.) &;K.# &;F0/*;G.) &;K.# &;F&/,$;>/#$+#)(#'#(\"'#&'#"),C('4\x7f""5!7\x80.A &4\x81""5!7\x82.5 &4\x83""5!7\x84.) &;3.# &;.'),C("%%;//Q#;&/H$$;J.# &;K0)*;J.# &;K&/,$;&/#$+$)($'#(#'#(\"'#&'#/\"!&,)"),C("%;//]#;&/T$%$;J.# &;K0)*;J.# &;K&/\"!&,)/1$;&/($8$:\x85$!!)($'#(#'#(\"'#&'#"),C(';..G &2L""6L7M.; &4\x86""5!7\x87./ &4\x83""5!7\x84.# &;3'),C('%2j""6j7k/J#4\x88""5!7\x89.5 &4\x8a""5!7\x8b.) &4\x8c""5!7\x8d/#$+")("\'#&\'#'),C("%;N/M#28\"\"6879/>$;O.\" &\"/0$;S/'$8$:\x8e$ )($'#(#'#(\"'#&'#"),C("%;N/d#28\"\"6879/U$;O.\" &\"/G$;S/>$;_/5$;l.\" &\"/'$8&:\x8f& )(&'#(%'#($'#(#'#(\"'#&'#"),C('%3\x90""5$7\x91.) &3\x92""5#7\x93/\' 8!:\x94!! )'),C('%;P/]#%28""6879/,#;R/#$+")("\'#&\'#." &"/6$2:""6:7;/\'$8#:\x95# )(#\'#("\'#&\'#'),C("$;+.) &;-.# &;Q/2#0/*;+.) &;-.# &;Q&&&#"),C('2<""6<7=.q &2>""6>7?.e &2@""6@7A.Y &2B""6B7C.M &2D""6D7E.A &22""6273.5 &26""6677.) &24""6475'),C('%$;+._ &;-.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E0e*;+._ &;-.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E&/& 8!:\x96! )'),C('%;T/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),C("%;U.) &;\\.# &;X/& 8!:\x97! )"),C('%$%;V/2#2J""6J7K/#$+")("\'#&\'#0<*%;V/2#2J""6J7K/#$+")("\'#&\'#&/D#;W/;$2J""6J7K." &"/\'$8#:\x98# )(#\'#("\'#&\'#'),C('$4\x99""5!7\x9a/,#0)*4\x99""5!7\x9a&&&#'),C('%4$""5!7%/?#$4\x9b""5!7\x9c0)*4\x9b""5!7\x9c&/#$+")("\'#&\'#'),C('%2l""6l7m/?#;Y/6$2n""6n7o/\'$8#:\x9d# )(#\'#("\'#&\'#'),C('%%;Z/\xb3#28""6879/\xa4$;Z/\x9b$28""6879/\x8c$;Z/\x83$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+-)(-\'#(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u0790 &%2\x9e""6\x9e7\x9f/\xa4#;Z/\x9b$28""6879/\x8c$;Z/\x83$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+,)(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u06f9 &%2\x9e""6\x9e7\x9f/\x8c#;Z/\x83$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u067a &%2\x9e""6\x9e7\x9f/t#;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u0613 &%2\x9e""6\x9e7\x9f/\\#;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+&)(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u05c4 &%2\x9e""6\x9e7\x9f/D#;Z/;$28""6879/,$;[/#$+$)($\'#(#\'#("\'#&\'#.\u058d &%2\x9e""6\x9e7\x9f/,#;[/#$+")("\'#&\'#.\u056e &%2\x9e""6\x9e7\x9f/,#;Z/#$+")("\'#&\'#.\u054f &%;Z/\x9b#2\x9e""6\x9e7\x9f/\x8c$;Z/\x83$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$++)(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u04c7 &%;Z/\xaa#%28""6879/,#;Z/#$+")("\'#&\'#." &"/\x83$2\x9e""6\x9e7\x9f/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u0430 &%;Z/\xb9#%28""6879/,#;Z/#$+")("\'#&\'#." &"/\x92$%28""6879/,#;Z/#$+")("\'#&\'#." &"/k$2\x9e""6\x9e7\x9f/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+))()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u038a &%;Z/\xc8#%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xa1$%28""6879/,#;Z/#$+")("\'#&\'#." &"/z$%28""6879/,#;Z/#$+")("\'#&\'#." &"/S$2\x9e""6\x9e7\x9f/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u02d5 &%;Z/\xd7#%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xb0$%28""6879/,#;Z/#$+")("\'#&\'#." &"/\x89$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2\x9e""6\x9e7\x9f/,$;[/#$+\')(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u0211 &%;Z/\xfe#%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xd7$%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xb0$%28""6879/,#;Z/#$+")("\'#&\'#." &"/\x89$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2\x9e""6\x9e7\x9f/,$;Z/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u0126 &%;Z/\u011c#%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xf5$%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xce$%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xa7$%28""6879/,#;Z/#$+")("\'#&\'#." &"/\x80$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Y$%28""6879/,#;Z/#$+")("\'#&\'#." &"/2$2\x9e""6\x9e7\x9f/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#/& 8!:\xa0! )'),C('%;#/M#;#." &"/?$;#." &"/1$;#." &"/#$+$)($\'#(#\'#("\'#&\'#'),C("%;Z/;#28\"\"6879/,$;Z/#$+#)(#'#(\"'#&'#.# &;\\"),C("%;]/o#2J\"\"6J7K/`$;]/W$2J\"\"6J7K/H$;]/?$2J\"\"6J7K/0$;]/'$8':\xa1' )(''#(&'#(%'#($'#(#'#(\"'#&'#"),C('%2\xa2""6\xa27\xa3/2#4\xa4""5!7\xa5/#$+")("\'#&\'#.\x98 &%2\xa6""6\xa67\xa7/;#4\xa8""5!7\xa9/,$;!/#$+#)(#\'#("\'#&\'#.j &%2\xaa""6\xaa7\xab/5#;!/,$;!/#$+#)(#\'#("\'#&\'#.B &%4\xac""5!7\xad/,#;!/#$+")("\'#&\'#.# &;!'),C('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:\xae!! )'),C('$%22""6273/,#;`/#$+")("\'#&\'#0<*%22""6273/,#;`/#$+")("\'#&\'#&'),C(";a.A &;b.; &;c.5 &;d./ &;e.) &;f.# &;g"),C('%3\xaf""5*7\xb0/a#3\xb1""5#7\xb2.G &3\xb3""5#7\xb4.; &3\xb5""5$7\xb6./ &3\xb7""5#7\xb8.# &;6/($8":\xb9"! )("\'#&\'#'),C('%3\xba""5%7\xbb/I#3\xbc""5%7\xbd./ &3\xbe""5"7\xbf.# &;6/($8":\xc0"! )("\'#&\'#'),C('%3\xc1""5\'7\xc2/1#;\x90/($8":\xc3"! )("\'#&\'#'),C('%3\xc4""5$7\xc5/1#;\xf0/($8":\xc6"! )("\'#&\'#'),C('%3\xc7""5&7\xc8/1#;T/($8":\xc9"! )("\'#&\'#'),C('%3\xca""5"7\xcb/N#%2>""6>7?/,#;6/#$+")("\'#&\'#." &"/\'$8":\xcc" )("\'#&\'#'),C('%;h/P#%2>""6>7?/,#;i/#$+")("\'#&\'#." &"/)$8":\xcd""! )("\'#&\'#'),C('%$;j/�#*;j&&&#/"!&,)'),C('%$;j/�#*;j&&&#/"!&,)'),C(";k.) &;+.# &;-"),C('2l""6l7m.e &2n""6n7o.Y &24""6475.M &28""6879.A &2<""6<7=.5 &2@""6@7A.) &2B""6B7C'),C('%26""6677/n#;m/e$$%2<""6<7=/,#;m/#$+")("\'#&\'#0<*%2<""6<7=/,#;m/#$+")("\'#&\'#&/#$+#)(#\'#("\'#&\'#'),C('%;n/A#2>""6>7?/2$;o/)$8#:\xce#"" )(#\'#("\'#&\'#'),C("$;p.) &;+.# &;-/2#0/*;p.) &;+.# &;-&&&#"),C("$;p.) &;+.# &;-0/*;p.) &;+.# &;-&"),C('2l""6l7m.e &2n""6n7o.Y &24""6475.M &26""6677.A &28""6879.5 &2@""6@7A.) &2B""6B7C'),C(";\x91.# &;r"),C("%;\x90/G#;'/>$;s/5$;'/,$;\x84/#$+%)(%'#($'#(#'#(\"'#&'#"),C(";M.# &;t"),C("%;\x7f/E#28\"\"6879/6$;u.# &;x/'$8#:\xcf# )(#'#(\"'#&'#"),C('%;v.# &;w/J#%26""6677/,#;\x83/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),C('%2\xd0""6\xd07\xd1/:#;\x80/1$;w." &"/#$+#)(#\'#("\'#&\'#'),C('%24""6475/,#;{/#$+")("\'#&\'#'),C("%;z/3#$;y0#*;y&/#$+\")(\"'#&'#"),C(";*.) &;+.# &;-"),C(';+.\x8f &;-.\x89 &22""6273.} &26""6677.q &28""6879.e &2:""6:7;.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),C('%;|/e#$%24""6475/,#;|/#$+")("\'#&\'#0<*%24""6475/,#;|/#$+")("\'#&\'#&/#$+")("\'#&\'#'),C('%$;~0#*;~&/e#$%22""6273/,#;}/#$+")("\'#&\'#0<*%22""6273/,#;}/#$+")("\'#&\'#&/#$+")("\'#&\'#'),C("$;~0#*;~&"),C(';+.w &;-.q &28""6879.e &2:""6:7;.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),C('%%;"/\x87#$;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K0M*;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K&/#$+")("\'#&\'#/& 8!:\xd2! )'),C(";\x81.# &;\x82"),C('%%;O/2#2:""6:7;/#$+")("\'#&\'#." &"/,#;S/#$+")("\'#&\'#." &"'),C('$;+.\x83 &;-.} &2B""6B7C.q &2D""6D7E.e &22""6273.Y &28""6879.M &2:""6:7;.A &2<""6<7=.5 &2>""6>7?.) &2@""6@7A/\x8c#0\x89*;+.\x83 &;-.} &2B""6B7C.q &2D""6D7E.e &22""6273.Y &28""6879.M &2:""6:7;.A &2<""6<7=.5 &2>""6>7?.) &2@""6@7A&&&#'),C("$;y0#*;y&"),C('%3\x92""5#7\xd3/q#24""6475/b$$;!/�#*;!&&&#/L$2J""6J7K/=$$;!/�#*;!&&&#/\'$8%:\xd4% )(%\'#($\'#(#\'#("\'#&\'#'),C('2\xd5""6\xd57\xd6'),C('2\xd7""6\xd77\xd8'),C('2\xd9""6\xd97\xda'),C('2\xdb""6\xdb7\xdc'),C('2\xdd""6\xdd7\xde'),C('2\xdf""6\xdf7\xe0'),C('2\xe1""6\xe17\xe2'),C('2\xe3""6\xe37\xe4'),C('2\xe5""6\xe57\xe6'),C('2\xe7""6\xe77\xe8'),C('2\xe9""6\xe97\xea'),C("%;\x85.Y &;\x86.S &;\x88.M &;\x89.G &;\x8a.A &;\x8b.; &;\x8c.5 &;\x8f./ &;\x8d.) &;\x8e.# &;6/& 8!:\xeb! )"),C("%;\x84/G#;'/>$;\x92/5$;'/,$;\x94/#$+%)(%'#($'#(#'#(\"'#&'#"),C("%;\x93/' 8!:\xec!! )"),C("%;!/5#;!/,$;!/#$+#)(#'#(\"'#&'#"),C("%$;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(0G*;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(&/& 8!:\xed! )"),C("%;\xb6/Y#$%;A/,#;\xb6/#$+\")(\"'#&'#06*%;A/,#;\xb6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),C('%;9/N#%2:""6:7;/,#;9/#$+")("\'#&\'#." &"/\'$8":\xee" )("\'#&\'#'),C("%;:.c &%;\x98/Y#$%;A/,#;\x98/#$+\")(\"'#&'#06*%;A/,#;\x98/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/& 8!:\xef! )"),C("%;L.# &;\x99/]#$%;B/,#;\x9b/#$+\")(\"'#&'#06*%;B/,#;\x9b/#$+\")(\"'#&'#&/'$8\":\xf0\" )(\"'#&'#"),C("%;\x9a.\" &\"/>#;@/5$;M/,$;?/#$+$)($'#(#'#(\"'#&'#"),C("%%;6/Y#$%;./,#;6/#$+\")(\"'#&'#06*%;./,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#.# &;H/' 8!:\xf1!! )"),C(";\x9c.) &;\x9d.# &;\xa0"),C("%3\xf2\"\"5!7\xf3/:#;$;\xcf/5$;./,$;\x90/#$+%)(%'#($'#(#'#(\"'#&'#"),C("%$;!/�#*;!&&&#/' 8!:\u014b!! )"),C("%;\xd1/]#$%;A/,#;\xd1/#$+\")(\"'#&'#06*%;A/,#;\xd1/#$+\")(\"'#&'#&/'$8\":\u014c\" )(\"'#&'#"),C("%;\x99/]#$%;B/,#;\xa0/#$+\")(\"'#&'#06*%;B/,#;\xa0/#$+\")(\"'#&'#&/'$8\":\u014d\" )(\"'#&'#"),C('%;L.O &;\x99.I &%;@." &"/:#;t/1$;?." &"/#$+#)(#\'#("\'#&\'#/]#$%;B/,#;\xa0/#$+")("\'#&\'#06*%;B/,#;\xa0/#$+")("\'#&\'#&/\'$8":\u014e" )("\'#&\'#'),C("%;\xd4/]#$%;B/,#;\xd5/#$+\")(\"'#&'#06*%;B/,#;\xd5/#$+\")(\"'#&'#&/'$8\":\u014f\" )(\"'#&'#"),C("%;\x96/& 8!:\u0150! )"),C('%3\u0151""5(7\u0152/:#;$;6/5$;;/,$;\xec/#$+%)(%'#($'#(#'#(\"'#&'#"),C('%3\x92""5#7\xd3.# &;6/\' 8!:\u018b!! )'),C('%3\xb1""5#7\u018c.G &3\xb3""5#7\u018d.; &3\xb7""5#7\u018e./ &3\xb5""5$7\u018f.# &;6/\' 8!:\u0190!! )'),C('%;\xee/D#%;C/,#;\xef/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),C("%;U.) &;\\.# &;X/& 8!:\u0191! )"),C('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:\u0192!! )'),C('%%;!/?#;!." &"/1$;!." &"/#$+#)(#\'#("\'#&\'#/\' 8!:\u0193!! )'),C(";\xbe"),C('%;\x9e/^#$%;B/,#;\xf3/#$+")("\'#&\'#06*%;B/,#;\xf3/#$+")("\'#&\'#&/($8":\u0194"!!)("\'#&\'#'),C(";\xf4.# &;\xa0"),C('%2\u0195""6\u01957\u0196/L#;""6>7?'),C('%;\u0100/b#28""6879/S$;\xfb/J$%2\u01a3""6\u01a37\u01a4/,#;\xec/#$+")("\'#&\'#." &"/#$+$)($\'#(#\'#("\'#&\'#'),C('%3\u01a5""5%7\u01a6.) &3\u01a7""5$7\u01a8/\' 8!:\u01a1!! )'),C('%3\xb1""5#7\xb2.6 &3\xb3""5#7\xb4.* &$;+0#*;+&/\' 8!:\u01a9!! )'),C("%;\u0104/\x87#2F\"\"6F7G/x$;\u0103/o$2F\"\"6F7G/`$;\u0103/W$2F\"\"6F7G/H$;\u0103/?$2F\"\"6F7G/0$;\u0105/'$8):\u01aa) )()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#"),C("%;#/>#;#/5$;#/,$;#/#$+$)($'#(#'#(\"'#&'#"),C("%;\u0103/,#;\u0103/#$+\")(\"'#&'#"),C("%;\u0103/5#;\u0103/,$;\u0103/#$+#)(#'#(\"'#&'#"),C("%;q/T#$;m0#*;m&/D$%; /,#;\xf8/#$+\")(\"'#&'#.\" &\"/#$+#)(#'#(\"'#&'#"),C('%2\u01ab""6\u01ab7\u01ac.) &2\u01ad""6\u01ad7\u01ae/w#;0/n$;\u0108/e$$%;B/2#;\u0109.# &;\xa0/#$+")("\'#&\'#0<*%;B/2#;\u0109.# &;\xa0/#$+")("\'#&\'#&/#$+$)($\'#(#\'#("\'#&\'#'),C(";\x99.# &;L"),C("%2\u01af\"\"6\u01af7\u01b0/5#;f&&(f=l,g=[]),g.push(e))}function w(e,t,r){return new a(a.buildMessage(e,t),e,t,r)}function C(e){return e.split("").map((function(e){return e.charCodeAt(0)-32}))}if(t.data={},(r=function t(r){for(var i,o=d[r],a=0,s=[],c=o.length,p=[],f=[];;){for(;al?(c=a+3+o[a+1],a+=3):(c=a+3+o[a+1]+o[a+2],a+=3+o[a+1]);break;case 18:p.push(c),s.push(a+4+o[a+2]+o[a+3]),e.substr(l,u[o[a+1]].length)===u[o[a+1]]?(c=a+4+o[a+2],a+=4):(c=a+4+o[a+2]+o[a+3],a+=4+o[a+2]);break;case 19:p.push(c),s.push(a+4+o[a+2]+o[a+3]),e.substr(l,u[o[a+1]].length).toLowerCase()===u[o[a+1]]?(c=a+4+o[a+2],a+=4):(c=a+4+o[a+2]+o[a+3],a+=4+o[a+2]);break;case 20:p.push(c),s.push(a+4+o[a+2]+o[a+3]),u[o[a+1]].test(e.charAt(l))?(c=a+4+o[a+2],a+=4):(c=a+4+o[a+2]+o[a+3],a+=4+o[a+2]);break;case 21:f.push(e.substr(l,o[a+1])),l+=o[a+1],a+=2;break;case 22:f.push(u[o[a+1]]),l+=u[o[a+1]].length,a+=2;break;case 23:f.push(n),0===v&&$(u[o[a+1]]),a+=2;break;case 24:h=f[f.length-1-o[a+1]],a+=2;break;case 25:h=l,a++;break;case 26:i=o.slice(a+4,a+4+o[a+3]).map((function(e){return f[f.length-1-e]})),f.splice(f.length-o[a+2],o[a+2],u[o[a+1]].apply(null,i)),a+=4+o[a+3];break;case 27:f.push(t(o[a+1])),a+=2;break;case 28:v++,a++;break;case 29:v--,a++;break;default:throw new Error("Invalid opcode: "+o[a]+".")}if(!(p.length>0))break;c=p.pop(),a=s.pop()}return f[0]}(c))!==n&&l===e.length)return r;throw r!==n&&l-1)this.qop="auth";else{if(!(t.qop.indexOf("auth-int")>-1))return this.logger.warn("challenge without Digest qop different than 'auth' or 'auth-int', authentication aborted"),!1;this.qop="auth-int"}else this.qop=void 0;return this.method=e.method,this.uri=e.ruri,this.cnonce=i.createRandomToken(12),this.nc+=1,this.updateNcHex(),4294967296===this.nc&&(this.nc=1,this.ncHex="00000001"),this.calculateResponse(r),!0},e.prototype.toString=function(){var e=[];if(!this.response)throw new Error("response field does not exist, cannot generate Authorization header");return e.push("algorithm="+this.algorithm),e.push('username="'+this.username+'"'),e.push('realm="'+this.realm+'"'),e.push('nonce="'+this.nonce+'"'),e.push('uri="'+this.uri+'"'),e.push('response="'+this.response+'"'),this.opaque&&e.push('opaque="'+this.opaque+'"'),this.qop&&(e.push("qop="+this.qop),e.push('cnonce="'+this.cnonce+'"'),e.push("nc="+this.ncHex)),"Digest "+e.join(", ")},e.prototype.updateNcHex=function(){var e=Number(this.nc).toString(16);this.ncHex="00000000".substr(0,8-e.length)+e},e.prototype.calculateResponse=function(e){var t,r=n.default(this.username+":"+this.realm+":"+this.password);"auth"===this.qop?(t=n.default(this.method+":"+this.uri),this.response=n.default(r+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth:"+t)):"auth-int"===this.qop?(t=n.default(this.method+":"+this.uri+":"+n.default(e||"")),this.response=n.default(r+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth-int:"+t)):void 0===this.qop&&(t=n.default(this.method+":"+this.uri),this.response=n.default(r+":"+this.nonce+":"+t))},e}();t.DigestAuthentication=o},function(e,t,r){var n;e.exports=(n=r(61),function(e){var t=n,r=t.lib,i=r.WordArray,o=r.Hasher,a=t.algo,s=[];!function(){for(var t=0;t<64;t++)s[t]=4294967296*e.abs(e.sin(t+1))|0}();var c=a.MD5=o.extend({_doReset:function(){this._hash=new i.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(e,t){for(var r=0;r<16;r++){var n=t+r,i=e[n];e[n]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8)}var o=this._hash.words,a=e[t+0],c=e[t+1],p=e[t+2],f=e[t+3],g=e[t+4],v=e[t+5],m=e[t+6],y=e[t+7],S=e[t+8],T=e[t+9],b=e[t+10],_=e[t+11],$=e[t+12],w=e[t+13],C=e[t+14],I=e[t+15],E=o[0],R=o[1],x=o[2],A=o[3];E=u(E,R,x,A,a,7,s[0]),A=u(A,E,R,x,c,12,s[1]),x=u(x,A,E,R,p,17,s[2]),R=u(R,x,A,E,f,22,s[3]),E=u(E,R,x,A,g,7,s[4]),A=u(A,E,R,x,v,12,s[5]),x=u(x,A,E,R,m,17,s[6]),R=u(R,x,A,E,y,22,s[7]),E=u(E,R,x,A,S,7,s[8]),A=u(A,E,R,x,T,12,s[9]),x=u(x,A,E,R,b,17,s[10]),R=u(R,x,A,E,_,22,s[11]),E=u(E,R,x,A,$,7,s[12]),A=u(A,E,R,x,w,12,s[13]),x=u(x,A,E,R,C,17,s[14]),E=d(E,R=u(R,x,A,E,I,22,s[15]),x,A,c,5,s[16]),A=d(A,E,R,x,m,9,s[17]),x=d(x,A,E,R,_,14,s[18]),R=d(R,x,A,E,a,20,s[19]),E=d(E,R,x,A,v,5,s[20]),A=d(A,E,R,x,b,9,s[21]),x=d(x,A,E,R,I,14,s[22]),R=d(R,x,A,E,g,20,s[23]),E=d(E,R,x,A,T,5,s[24]),A=d(A,E,R,x,C,9,s[25]),x=d(x,A,E,R,f,14,s[26]),R=d(R,x,A,E,S,20,s[27]),E=d(E,R,x,A,w,5,s[28]),A=d(A,E,R,x,p,9,s[29]),x=d(x,A,E,R,y,14,s[30]),E=l(E,R=d(R,x,A,E,$,20,s[31]),x,A,v,4,s[32]),A=l(A,E,R,x,S,11,s[33]),x=l(x,A,E,R,_,16,s[34]),R=l(R,x,A,E,C,23,s[35]),E=l(E,R,x,A,c,4,s[36]),A=l(A,E,R,x,g,11,s[37]),x=l(x,A,E,R,y,16,s[38]),R=l(R,x,A,E,b,23,s[39]),E=l(E,R,x,A,w,4,s[40]),A=l(A,E,R,x,a,11,s[41]),x=l(x,A,E,R,f,16,s[42]),R=l(R,x,A,E,m,23,s[43]),E=l(E,R,x,A,T,4,s[44]),A=l(A,E,R,x,$,11,s[45]),x=l(x,A,E,R,I,16,s[46]),E=h(E,R=l(R,x,A,E,p,23,s[47]),x,A,a,6,s[48]),A=h(A,E,R,x,y,10,s[49]),x=h(x,A,E,R,C,15,s[50]),R=h(R,x,A,E,v,21,s[51]),E=h(E,R,x,A,$,6,s[52]),A=h(A,E,R,x,f,10,s[53]),x=h(x,A,E,R,b,15,s[54]),R=h(R,x,A,E,c,21,s[55]),E=h(E,R,x,A,S,6,s[56]),A=h(A,E,R,x,I,10,s[57]),x=h(x,A,E,R,m,15,s[58]),R=h(R,x,A,E,w,21,s[59]),E=h(E,R,x,A,g,6,s[60]),A=h(A,E,R,x,_,10,s[61]),x=h(x,A,E,R,p,15,s[62]),R=h(R,x,A,E,T,21,s[63]),o[0]=o[0]+E|0,o[1]=o[1]+R|0,o[2]=o[2]+x|0,o[3]=o[3]+A|0},_doFinalize:function(){var t=this._data,r=t.words,n=8*this._nDataBytes,i=8*t.sigBytes;r[i>>>5]|=128<<24-i%32;var o=e.floor(n/4294967296),a=n;r[15+(i+64>>>9<<4)]=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8),r[14+(i+64>>>9<<4)]=16711935&(a<<8|a>>>24)|4278255360&(a<<24|a>>>8),t.sigBytes=4*(r.length+1),this._process();for(var s=this._hash,c=s.words,u=0;u<4;u++){var d=c[u];c[u]=16711935&(d<<8|d>>>24)|4278255360&(d<<24|d>>>8)}return s},clone:function(){var e=o.clone.call(this);return e._hash=this._hash.clone(),e}});function u(e,t,r,n,i,o,a){var s=e+(t&r|~t&n)+i+a;return(s<>>32-o)+t}function d(e,t,r,n,i,o,a){var s=e+(t&n|r&~n)+i+a;return(s<>>32-o)+t}function l(e,t,r,n,i,o,a){var s=e+(t^r^n)+i+a;return(s<>>32-o)+t}function h(e,t,r,n,i,o,a){var s=e+(r^(t|~n))+i+a;return(s<>>32-o)+t}t.MD5=o._createHelper(c),t.HmacMD5=o._createHmacHelper(c)}(Math),n.MD5)},function(e,t,r){var n;e.exports=(n=n||function(e,t){var r=Object.create||function(){function e(){}return function(t){var r;return e.prototype=t,r=new e,e.prototype=null,r}}(),n={},i=n.lib={},o=i.Base={extend:function(e){var t=r(this);return e&&t.mixIn(e),t.hasOwnProperty("init")&&this.init!==t.init||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},a=i.WordArray=o.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||c).stringify(this)},concat:function(e){var t=this.words,r=e.words,n=this.sigBytes,i=e.sigBytes;if(this.clamp(),n%4)for(var o=0;o>>2]>>>24-o%4*8&255;t[n+o>>>2]|=a<<24-(n+o)%4*8}else for(o=0;o>>2]=r[o>>>2];return this.sigBytes+=i,this},clamp:function(){var t=this.words,r=this.sigBytes;t[r>>>2]&=4294967295<<32-r%4*8,t.length=e.ceil(r/4)},clone:function(){var e=o.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var r,n=[],i=function(t){t=t;var r=987654321,n=4294967295;return function(){var i=((r=36969*(65535&r)+(r>>16)&n)<<16)+(t=18e3*(65535&t)+(t>>16)&n)&n;return i/=4294967296,(i+=.5)*(e.random()>.5?1:-1)}},o=0;o>>2]>>>24-i%4*8&255;n.push((o>>>4).toString(16)),n.push((15&o).toString(16))}return n.join("")},parse:function(e){for(var t=e.length,r=[],n=0;n>>3]|=parseInt(e.substr(n,2),16)<<24-n%8*4;return new a.init(r,t/2)}},u=s.Latin1={stringify:function(e){for(var t=e.words,r=e.sigBytes,n=[],i=0;i>>2]>>>24-i%4*8&255;n.push(String.fromCharCode(o))}return n.join("")},parse:function(e){for(var t=e.length,r=[],n=0;n>>2]|=(255&e.charCodeAt(n))<<24-n%4*8;return new a.init(r,t)}},d=s.Utf8={stringify:function(e){try{return decodeURIComponent(escape(u.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return u.parse(unescape(encodeURIComponent(e)))}},l=i.BufferedBlockAlgorithm=o.extend({reset:function(){this._data=new a.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=d.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var r=this._data,n=r.words,i=r.sigBytes,o=this.blockSize,s=i/(4*o),c=(s=t?e.ceil(s):e.max((0|s)-this._minBufferSize,0))*o,u=e.min(4*c,i);if(c){for(var d=0;d699)throw new TypeError("Invalid statusCode: "+t.statusCode);var i=t.reasonPhrase?t.reasonPhrase:n.getReasonPhrase(t.statusCode),o="SIP/2.0 "+t.statusCode+" "+i+r;t.statusCode>=100&&t.statusCode,t.statusCode;var a="From: "+e.getHeader("From")+r,s="Call-ID: "+e.callId+r,c="CSeq: "+e.cseq+" "+e.method+r,u=e.getHeaders("via").reduce((function(e,t){return e+"Via: "+t+r}),""),d="To: "+e.getHeader("to");if(t.statusCode>100&&!e.parseHeader("to").hasParam("tag")){var l=t.toTag;l||(l=n.newTag()),d+=";tag="+l}d+=r;var h="";t.supported&&(h="Supported: "+t.supported.join(", ")+r);var p="";t.userAgent&&(p="User-Agent: "+t.userAgent+r);var f="";return t.extraHeaders&&(f=t.extraHeaders.reduce((function(e,t){return e+t.trim()+r}),"")),o+=u,o+=a,o+=d,o+=c,o+=s,o+=h,o+=p,o+=f,t.body?(o+="Content-Type: "+t.body.contentType+r,o+="Content-Length: "+n.str_utf8_length(t.body.content)+r+r,o+=t.body.content):o+="Content-Length: 0\r\n\r\n",{message:o}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=r(2),o=r(15),a=r(6),s=r(1),c=r(36),u=r(37),d=r(38),l=r(39),h=r(40),p=r(26),f=r(41),g=r(42),v=r(43),m=r(44),y=r(45),S=r(46),T=function(e){function t(t,r,n,i){var a=e.call(this,r,n)||this;return a.initialTransaction=t,a._signalingState=o.SignalingState.Initial,a.ackWait=!1,a.delegate=i,t instanceof s.InviteServerTransaction&&(a.ackWait=!0),a.early||a.start2xxRetransmissionTimer(),a.signalingStateTransition(t.request),a.logger=r.loggerFactory.getLogger("sip.invite-dialog"),a.logger.log("INVITE dialog "+a.id+" constructed"),a}return n.__extends(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this),this._signalingState=o.SignalingState.Closed,this._offer=void 0,this._answer=void 0,this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.logger.log("INVITE dialog "+this.id+" destroyed")},Object.defineProperty(t.prototype,"sessionState",{get:function(){return this.early?o.SessionState.Early:this.ackWait?o.SessionState.AckWait:this._signalingState===o.SignalingState.Closed?o.SessionState.Terminated:o.SessionState.Confirmed},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"signalingState",{get:function(){return this._signalingState},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"offer",{get:function(){return this._offer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"answer",{get:function(){return this._answer},enumerable:!0,configurable:!0}),t.prototype.confirm=function(){this.early&&this.start2xxRetransmissionTimer(),e.prototype.confirm.call(this)},t.prototype.reConfirm=function(){this.reinviteUserAgentServer&&this.startReInvite2xxRetransmissionTimer()},t.prototype.ack=function(e){var t;if(void 0===e&&(e={}),this.logger.log("INVITE dialog "+this.id+" sending ACK request"),this.reinviteUserAgentClient){if(!(this.reinviteUserAgentClient.transaction instanceof s.InviteClientTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");t=this.reinviteUserAgentClient.transaction,this.reinviteUserAgentClient=void 0}else{if(!(this.initialTransaction instanceof s.InviteClientTransaction))throw new Error("Initial transaction not instance of InviteClientTransaction.");t=this.initialTransaction}e.cseq=t.request.cseq;var r=this.createOutgoingRequestMessage(i.C.ACK,e);return t.ackResponse(r),this.signalingStateTransition(r),{message:r}},t.prototype.bye=function(e,t){if(this.logger.log("INVITE dialog "+this.id+" sending BYE request"),this.initialTransaction instanceof s.InviteServerTransaction){if(this.early)throw new Error("UAS MUST NOT send a BYE on early dialogs.");if(this.ackWait&&this.initialTransaction.state!==s.TransactionState.Terminated)throw new Error("UAS MUST NOT send a BYE on a confirmed dialog until it has received an ACK for its 2xx response or until the server transaction times out.")}return new c.ByeUserAgentClient(this,e,t)},t.prototype.info=function(e,t){if(this.logger.log("INVITE dialog "+this.id+" sending INFO request"),this.early)throw new Error("Dialog not confirmed.");return new d.InfoUserAgentClient(this,e,t)},t.prototype.invite=function(e,t){if(this.logger.log("INVITE dialog "+this.id+" sending INVITE request"),this.early)throw new Error("Dialog not confirmed.");if(this.reinviteUserAgentClient)throw new Error("There is an ongoing re-INVITE client transaction.");if(this.reinviteUserAgentServer)throw new Error("There is an ongoing re-INVITE server transaction.");return new v.ReInviteUserAgentClient(this,e,t)},t.prototype.notify=function(e,t){if(this.logger.log("INVITE dialog "+this.id+" sending NOTIFY request"),this.early)throw new Error("Dialog not confirmed.");return new h.NotifyUserAgentClient(this,e,t)},t.prototype.prack=function(e,t){return this.logger.log("INVITE dialog "+this.id+" sending PRACK request"),new f.PrackUserAgentClient(this,e,t)},t.prototype.refer=function(e,t){if(this.logger.log("INVITE dialog "+this.id+" sending REFER request"),this.early)throw new Error("Dialog not confirmed.");return new y.ReferUserAgentClient(this,e,t)},t.prototype.receiveRequest=function(t){if(this.logger.log("INVITE dialog "+this.id+" received "+t.method+" request"),t.method===i.C.ACK){if(this.ackWait){if(this.initialTransaction instanceof s.InviteClientTransaction)return void this.logger.warn("INVITE dialog "+this.id+" received unexpected "+t.method+" request, dropping.");if(this.initialTransaction.request.cseq!==t.cseq)return void this.logger.warn("INVITE dialog "+this.id+" received unexpected "+t.method+" request, dropping.");this.ackWait=!1}else{if(!this.reinviteUserAgentServer)return void this.logger.warn("INVITE dialog "+this.id+" received unexpected "+t.method+" request, dropping.");if(this.reinviteUserAgentServer.transaction.request.cseq!==t.cseq)return void this.logger.warn("INVITE dialog "+this.id+" received unexpected "+t.method+" request, dropping.");this.reinviteUserAgentServer=void 0}return this.signalingStateTransition(t),void(this.delegate&&this.delegate.onAck&&this.delegate.onAck({message:t}))}if(this.sequenceGuard(t)){if(t.method===i.C.INVITE){if(this.reinviteUserAgentServer){var r=["Retry-After: "+(Math.floor(10*Math.random())+1)];return void this.core.replyStateless(t,{statusCode:500,extraHeaders:r})}if(this.reinviteUserAgentClient)return void this.core.replyStateless(t,{statusCode:491})}if(e.prototype.receiveRequest.call(this,t),t.method===i.C.INVITE){var n=t.parseHeader("contact");if(!n)throw new Error("Contact undefined.");if(!(n instanceof i.NameAddrHeader))throw new Error("Contact not instance of NameAddrHeader.");this.dialogState.remoteTarget=n.uri}switch(t.method){case i.C.BYE:var o=new u.ByeUserAgentServer(this,t);this.delegate&&this.delegate.onBye?this.delegate.onBye(o):o.accept(),this.dispose();break;case i.C.INFO:o=new l.InfoUserAgentServer(this,t);this.delegate&&this.delegate.onInfo?this.delegate.onInfo(o):o.reject({statusCode:469,extraHeaders:["Recv-Info :"]});break;case i.C.INVITE:o=new m.ReInviteUserAgentServer(this,t);this.signalingStateTransition(t),this.delegate&&this.delegate.onInvite?this.delegate.onInvite(o):o.reject({statusCode:488});break;case i.C.NOTIFY:o=new p.NotifyUserAgentServer(this,t);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(o):o.accept();break;case i.C.PRACK:o=new g.PrackUserAgentServer(this,t);this.delegate&&this.delegate.onPrack?this.delegate.onPrack(o):o.accept();break;case i.C.REFER:o=new S.ReferUserAgentServer(this,t);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(o):o.reject();break;default:this.logger.log("INVITE dialog "+this.id+" received unimplemented "+t.method+" request"),this.core.replyStateless(t,{statusCode:501})}}else this.logger.log("INVITE dialog "+this.id+" rejected out of order "+t.method+" request.")},t.prototype.reliableSequenceGuard=function(e){var t=e.statusCode;if(!t)throw new Error("Status code undefined");if(t>100&&t<200){var r=e.getHeader("require"),n=e.getHeader("rseq"),i=r&&r.includes("100rel")&&n?Number(n):void 0;if(i){if(this.rseq&&this.rseq+1!==i)return!1;this.rseq||(this.rseq=i)}}return!0},t.prototype.signalingStateRollback=function(){this._signalingState!==o.SignalingState.HaveLocalOffer&&this.signalingState!==o.SignalingState.HaveRemoteOffer||this._rollbackOffer&&this._rollbackAnswer&&(this._signalingState=o.SignalingState.Stable,this._offer=this._rollbackOffer,this._answer=this._rollbackAnswer)},t.prototype.signalingStateTransition=function(e){var t=i.getBody(e);if(t&&"session"===t.contentDisposition){if(this._signalingState===o.SignalingState.Stable&&(this._rollbackOffer=this._offer,this._rollbackAnswer=this._answer),e instanceof i.IncomingRequestMessage)switch(this._signalingState){case o.SignalingState.Initial:case o.SignalingState.Stable:this._signalingState=o.SignalingState.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case o.SignalingState.HaveLocalOffer:this._signalingState=o.SignalingState.Stable,this._answer=t;break;case o.SignalingState.HaveRemoteOffer:case o.SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof i.IncomingResponseMessage)switch(this._signalingState){case o.SignalingState.Initial:case o.SignalingState.Stable:this._signalingState=o.SignalingState.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case o.SignalingState.HaveLocalOffer:this._signalingState=o.SignalingState.Stable,this._answer=t;break;case o.SignalingState.HaveRemoteOffer:case o.SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof i.OutgoingRequestMessage)switch(this._signalingState){case o.SignalingState.Initial:case o.SignalingState.Stable:this._signalingState=o.SignalingState.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case o.SignalingState.HaveLocalOffer:break;case o.SignalingState.HaveRemoteOffer:this._signalingState=o.SignalingState.Stable,this._answer=t;break;case o.SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}if(i.isBody(e))switch(this._signalingState){case o.SignalingState.Initial:case o.SignalingState.Stable:this._signalingState=o.SignalingState.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case o.SignalingState.HaveLocalOffer:break;case o.SignalingState.HaveRemoteOffer:this._signalingState=o.SignalingState.Stable,this._answer=t;break;case o.SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}}},t.prototype.start2xxRetransmissionTimer=function(){var e=this;if(this.initialTransaction instanceof s.InviteServerTransaction){var t=this.initialTransaction,r=a.Timers.T1,n=function(){e.ackWait?(e.logger.log("No ACK for 2xx response received, attempting retransmission"),t.retransmitAcceptedResponse(),r=Math.min(2*r,a.Timers.T2),e.invite2xxTimer=setTimeout(n,r)):e.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(n,r);var i=function(){t.state===s.TransactionState.Terminated&&(t.removeListener("stateChanged",i),e.invite2xxTimer&&(clearTimeout(e.invite2xxTimer),e.invite2xxTimer=void 0),e.ackWait&&(e.delegate&&e.delegate.onAckTimeout?e.delegate.onAckTimeout():e.bye()))};t.addListener("stateChanged",i)}},t.prototype.startReInvite2xxRetransmissionTimer=function(){var e=this;if(this.reinviteUserAgentServer&&this.reinviteUserAgentServer.transaction instanceof s.InviteServerTransaction){var t=this.reinviteUserAgentServer.transaction,r=a.Timers.T1,n=function(){e.reinviteUserAgentServer?(e.logger.log("No ACK for 2xx response received, attempting retransmission"),t.retransmitAcceptedResponse(),r=Math.min(2*r,a.Timers.T2),e.invite2xxTimer=setTimeout(n,r)):e.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(n,r);var i=function(){t.state===s.TransactionState.Terminated&&(t.removeListener("stateChanged",i),e.invite2xxTimer&&(clearTimeout(e.invite2xxTimer),e.invite2xxTimer=void 0),e.reinviteUserAgentServer)};t.addListener("stateChanged",i)}},t}(r(18).Dialog);t.SessionDialog=T},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e){e.Initial="Initial",e.Early="Early",e.AckWait="AckWait",e.Confirmed="Confirmed",e.Terminated="Terminated"}(t.SessionState||(t.SessionState={})),function(e){e.Initial="Initial",e.HaveLocalOffer="HaveLocalOffer",e.HaveRemoteOffer="HaveRemoteOffer",e.Stable="Stable",e.Closed="Closed"}(t.SignalingState||(t.SignalingState={}))},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=function(e){function t(t){return e.call(this,t||"Transaction state error.")||this}return n.__extends(t,e),t}(r(24).Exception);t.TransactionStateError=i},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=function(e){function t(t){return e.call(this,t||"Unspecified transport error.")||this}return n.__extends(t,e),t}(r(24).Exception);t.TransportError=i},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=r(2),o=r(6),a=r(25),s=r(13),c=function(e){function t(t,r,n){return e.call(this,t,r,n,s.TransactionState.Proceeding,"sip.transaction.ist")||this}return n.__extends(t,e),t.prototype.dispose=function(){this.stopProgressExtensionTimer(),this.H&&(clearTimeout(this.H),this.H=void 0),this.I&&(clearTimeout(this.I),this.I=void 0),this.L&&(clearTimeout(this.L),this.L=void 0),e.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"kind",{get:function(){return"ist"},enumerable:!0,configurable:!0}),t.prototype.receiveRequest=function(e){var t=this;switch(this.state){case s.TransactionState.Proceeding:if(e.method===i.C.INVITE)return void(this.lastProvisionalResponse&&this.send(this.lastProvisionalResponse).catch((function(e){t.logTransportError(e,"Failed to send retransmission of provisional response.")})));break;case s.TransactionState.Accepted:if(e.method===i.C.INVITE)return;break;case s.TransactionState.Completed:if(e.method===i.C.INVITE){if(!this.lastFinalResponse)throw new Error("Last final response undefined.");return void this.send(this.lastFinalResponse).catch((function(e){t.logTransportError(e,"Failed to send retransmission of final response.")}))}if(e.method===i.C.ACK)return void this.stateTransition(s.TransactionState.Confirmed);break;case s.TransactionState.Confirmed:case s.TransactionState.Terminated:if(e.method===i.C.INVITE||e.method===i.C.ACK)return;break;default:throw new Error("Invalid state "+this.state)}var r="INVITE server transaction received unexpected "+e.method+" request while in state "+this.state+".";this.logger.warn(r)},t.prototype.receiveResponse=function(e,t){var r=this;if(e<100||e>699)throw new Error("Invalid status code "+e);switch(this.state){case s.TransactionState.Proceeding:if(e>=100&&e<=199)return this.lastProvisionalResponse=t,e>100&&this.startProgressExtensionTimer(),void this.send(t).catch((function(e){r.logTransportError(e,"Failed to send 1xx response.")}));if(e>=200&&e<=299)return this.lastFinalResponse=t,this.stateTransition(s.TransactionState.Accepted),void this.send(t).catch((function(e){r.logTransportError(e,"Failed to send 2xx response.")}));if(e>=300&&e<=699)return this.lastFinalResponse=t,this.stateTransition(s.TransactionState.Completed),void this.send(t).catch((function(e){r.logTransportError(e,"Failed to send non-2xx final response.")}));break;case s.TransactionState.Accepted:if(e>=200&&e<=299)return void this.send(t).catch((function(e){r.logTransportError(e,"Failed to send 2xx response.")}));break;case s.TransactionState.Completed:case s.TransactionState.Confirmed:case s.TransactionState.Terminated:break;default:throw new Error("Invalid state "+this.state)}var n="INVITE server transaction received unexpected "+e+" response from TU while in state "+this.state+".";throw this.logger.error(n),new Error(n)},t.prototype.retransmitAcceptedResponse=function(){var e=this;this.state===s.TransactionState.Accepted&&this.lastFinalResponse&&this.send(this.lastFinalResponse).catch((function(t){e.logTransportError(t,"Failed to send 2xx response.")}))},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e)},t.prototype.typeToString=function(){return"INVITE server transaction"},t.prototype.stateTransition=function(e){var t=this,r=function(){throw new Error("Invalid state transition from "+t.state+" to "+e)};switch(e){case s.TransactionState.Proceeding:r();break;case s.TransactionState.Accepted:case s.TransactionState.Completed:this.state!==s.TransactionState.Proceeding&&r();break;case s.TransactionState.Confirmed:this.state!==s.TransactionState.Completed&&r();break;case s.TransactionState.Terminated:this.state!==s.TransactionState.Accepted&&this.state!==s.TransactionState.Completed&&this.state!==s.TransactionState.Confirmed&&r();break;default:r()}this.stopProgressExtensionTimer(),e===s.TransactionState.Accepted&&(this.L=setTimeout((function(){return t.timer_L()}),o.Timers.TIMER_L)),e===s.TransactionState.Completed&&(this.H=setTimeout((function(){return t.timer_H()}),o.Timers.TIMER_H)),e===s.TransactionState.Confirmed&&(this.I=setTimeout((function(){return t.timer_I()}),o.Timers.TIMER_I)),e===s.TransactionState.Terminated&&this.dispose(),this.setState(e)},t.prototype.startProgressExtensionTimer=function(){var e=this;void 0===this.progressExtensionTimer&&(this.progressExtensionTimer=setInterval((function(){if(e.logger.debug("Progress extension timer expired for INVITE server transaction "+e.id+"."),!e.lastProvisionalResponse)throw new Error("Last provisional response undefined.");e.send(e.lastProvisionalResponse).catch((function(t){e.logTransportError(t,"Failed to send retransmission of provisional response.")}))}),o.Timers.PROVISIONAL_RESPONSE_INTERVAL))},t.prototype.stopProgressExtensionTimer=function(){void 0!==this.progressExtensionTimer&&(clearInterval(this.progressExtensionTimer),this.progressExtensionTimer=void 0)},t.prototype.timer_G=function(){},t.prototype.timer_H=function(){this.logger.debug("Timer H expired for INVITE server transaction "+this.id+"."),this.state===s.TransactionState.Completed&&(this.logger.warn("ACK to negative final response was never received, terminating transaction."),this.stateTransition(s.TransactionState.Terminated))},t.prototype.timer_I=function(){this.logger.debug("Timer I expired for INVITE server transaction "+this.id+"."),this.stateTransition(s.TransactionState.Terminated)},t.prototype.timer_L=function(){this.logger.debug("Timer L expired for INVITE server transaction "+this.id+"."),this.state===s.TransactionState.Accepted&&this.stateTransition(s.TransactionState.Terminated)},t}(a.ServerTransaction);t.InviteServerTransaction=c},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=r(6),o=r(22),a=r(13),s=function(e){function t(t,r,n){var o=e.call(this,t,r,n,a.TransactionState.Trying,"sip.transaction.nict")||this;return o.F=setTimeout((function(){return o.timer_F()}),i.Timers.TIMER_F),o.send(t.toString()).catch((function(e){o.logTransportError(e,"Failed to send initial outgoing request.")})),o}return n.__extends(t,e),t.prototype.dispose=function(){this.F&&(clearTimeout(this.F),this.F=void 0),this.K&&(clearTimeout(this.K),this.K=void 0),e.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"kind",{get:function(){return"nict"},enumerable:!0,configurable:!0}),t.prototype.receiveResponse=function(e){var t=e.statusCode;if(!t||t<100||t>699)throw new Error("Invalid status code "+t);switch(this.state){case a.TransactionState.Trying:if(t>=100&&t<=199)return this.stateTransition(a.TransactionState.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=699)return this.stateTransition(a.TransactionState.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case a.TransactionState.Proceeding:if(t>=100&&t<=199&&this.user.receiveResponse)return this.user.receiveResponse(e);if(t>=200&&t<=699)return this.stateTransition(a.TransactionState.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));case a.TransactionState.Completed:case a.TransactionState.Terminated:return;default:throw new Error("Invalid state "+this.state)}var r="Non-INVITE client transaction received unexpected "+t+" response while in state "+this.state+".";this.logger.warn(r)},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(a.TransactionState.Terminated,!0)},t.prototype.typeToString=function(){return"non-INVITE client transaction"},t.prototype.stateTransition=function(e,t){var r=this;void 0===t&&(t=!1);var n=function(){throw new Error("Invalid state transition from "+r.state+" to "+e)};switch(e){case a.TransactionState.Trying:n();break;case a.TransactionState.Proceeding:this.state!==a.TransactionState.Trying&&n();break;case a.TransactionState.Completed:this.state!==a.TransactionState.Trying&&this.state!==a.TransactionState.Proceeding&&n();break;case a.TransactionState.Terminated:this.state!==a.TransactionState.Trying&&this.state!==a.TransactionState.Proceeding&&this.state!==a.TransactionState.Completed&&(t||n());break;default:n()}e===a.TransactionState.Completed&&(this.F&&(clearTimeout(this.F),this.F=void 0),this.K=setTimeout((function(){return r.timer_K()}),i.Timers.TIMER_K)),e===a.TransactionState.Terminated&&this.dispose(),this.setState(e)},t.prototype.timer_F=function(){this.logger.debug("Timer F expired for non-INVITE client transaction "+this.id+"."),this.state!==a.TransactionState.Trying&&this.state!==a.TransactionState.Proceeding||(this.onRequestTimeout(),this.stateTransition(a.TransactionState.Terminated))},t.prototype.timer_K=function(){this.state===a.TransactionState.Completed&&this.stateTransition(a.TransactionState.Terminated)},t}(o.ClientTransaction);t.NonInviteClientTransaction=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=r(6),o=r(25),a=r(13),s=function(e){function t(t,r,n){return e.call(this,t,r,n,a.TransactionState.Trying,"sip.transaction.nist")||this}return n.__extends(t,e),t.prototype.dispose=function(){this.J&&(clearTimeout(this.J),this.J=void 0),e.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"kind",{get:function(){return"nist"},enumerable:!0,configurable:!0}),t.prototype.receiveRequest=function(e){var t=this;switch(this.state){case a.TransactionState.Trying:break;case a.TransactionState.Proceeding:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch((function(e){t.logTransportError(e,"Failed to send retransmission of provisional response.")}));break;case a.TransactionState.Completed:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch((function(e){t.logTransportError(e,"Failed to send retransmission of final response.")}));break;case a.TransactionState.Terminated:break;default:throw new Error("Invalid state "+this.state)}},t.prototype.receiveResponse=function(e,t){var r=this;if(e<100||e>699)throw new Error("Invalid status code "+e);if(e>100&&e<=199)throw new Error("Provisional response other than 100 not allowed.");switch(this.state){case a.TransactionState.Trying:if(this.lastResponse=t,e>=100&&e<200)return this.stateTransition(a.TransactionState.Proceeding),void this.send(t).catch((function(e){r.logTransportError(e,"Failed to send provisional response.")}));if(e>=200&&e<=699)return this.stateTransition(a.TransactionState.Completed),void this.send(t).catch((function(e){r.logTransportError(e,"Failed to send final response.")}));break;case a.TransactionState.Proceeding:if(this.lastResponse=t,e>=200&&e<=699)return this.stateTransition(a.TransactionState.Completed),void this.send(t).catch((function(e){r.logTransportError(e,"Failed to send final response.")}));break;case a.TransactionState.Completed:return;case a.TransactionState.Terminated:break;default:throw new Error("Invalid state "+this.state)}var n="Non-INVITE server transaction received unexpected "+e+" response from TU while in state "+this.state+".";throw this.logger.error(n),new Error(n)},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(a.TransactionState.Terminated,!0)},t.prototype.typeToString=function(){return"non-INVITE server transaction"},t.prototype.stateTransition=function(e,t){var r=this;void 0===t&&(t=!1);var n=function(){throw new Error("Invalid state transition from "+r.state+" to "+e)};switch(e){case a.TransactionState.Trying:n();break;case a.TransactionState.Proceeding:this.state!==a.TransactionState.Trying&&n();break;case a.TransactionState.Completed:this.state!==a.TransactionState.Trying&&this.state!==a.TransactionState.Proceeding&&n();break;case a.TransactionState.Terminated:this.state!==a.TransactionState.Proceeding&&this.state!==a.TransactionState.Completed&&(t||n());break;default:n()}e===a.TransactionState.Completed&&(this.J=setTimeout((function(){return r.timer_J()}),i.Timers.TIMER_J)),e===a.TransactionState.Terminated&&this.dispose(),this.setState(e)},t.prototype.timer_J=function(){this.logger.debug("Timer J expired for NON-INVITE server transaction "+this.id+"."),this.state===a.TransactionState.Completed&&this.stateTransition(a.TransactionState.Terminated)},t}(o.ServerTransaction);t.NonInviteServerTransaction=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e){e.Initial="Initial",e.NotifyWait="NotifyWait",e.Pending="Pending",e.Active="Active",e.Terminated="Terminated"}(t.SubscriptionState||(t.SubscriptionState={}))},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0);n.__exportStar(r(28),t),n.__exportStar(r(72),t),n.__exportStar(r(49),t)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(28),i=r(49),o=function(){function e(){this.builtinEnabled=!0,this._level=n.Levels.log,this.loggers={},this.logger=this.getLogger("sip:loggerfactory")}return Object.defineProperty(e.prototype,"level",{get:function(){return this._level},set:function(e){e>=0&&e<=3?this._level=e:e>3?this._level=3:n.Levels.hasOwnProperty(e)?this._level=e:this.logger.error("invalid 'level' parameter value: "+JSON.stringify(e))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"connector",{get:function(){return this._connector},set:function(e){e?"function"==typeof e?this._connector=e:this.logger.error("invalid 'connector' parameter value: "+JSON.stringify(e)):this._connector=void 0},enumerable:!0,configurable:!0}),e.prototype.getLogger=function(e,t){if(t&&3===this.level)return new i.Logger(this,e,t);if(this.loggers[e])return this.loggers[e];var r=new i.Logger(this,e);return this.loggers[e]=r,r},e.prototype.genericLog=function(e,t,r,i){this.level>=e&&this.builtinEnabled&&this.print(e,t,r,i),this.connector&&this.connector(n.Levels[e],t,r,i)},e.prototype.print=function(e,t,r,i){if("string"==typeof i){var o=[new Date,t];r&&o.push(r),i=o.concat(i).join(" | ")}switch(e){case n.Levels.error:console.error(i);break;case n.Levels.warn:console.warn(i);break;case n.Levels.log:console.log(i);break;case n.Levels.debug:console.debug(i)}},e}();t.LoggerFactory=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),r(0).__exportStar(r(74),t)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=r(2),o=r(1),a=r(50),s=r(14),c=["application/sdp","application/dtmf-relay"],u=function(){function e(e,t){void 0===t&&(t={}),this.userAgentClients=new Map,this.userAgentServers=new Map,this.configuration=e,this.delegate=t,this.dialogs=new Map,this.subscribers=new Map,this.logger=e.loggerFactory.getLogger("sip.user-agent-core")}return e.prototype.dispose=function(){this.reset()},e.prototype.reset=function(){this.dialogs.forEach((function(e){return e.dispose()})),this.dialogs.clear(),this.subscribers.forEach((function(e){return e.dispose()})),this.subscribers.clear(),this.userAgentClients.forEach((function(e){return e.dispose()})),this.userAgentClients.clear(),this.userAgentServers.forEach((function(e){return e.dispose()})),this.userAgentServers.clear()},Object.defineProperty(e.prototype,"loggerFactory",{get:function(){return this.configuration.loggerFactory},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"transport",{get:function(){var e=this.configuration.transportAccessor();if(!e)throw new Error("Transport undefined.");return e},enumerable:!0,configurable:!0}),e.prototype.invite=function(e,t){return new a.InviteUserAgentClient(this,e,t)},e.prototype.message=function(e,t){return new a.MessageUserAgentClient(this,e,t)},e.prototype.publish=function(e,t){return new a.PublishUserAgentClient(this,e,t)},e.prototype.register=function(e,t){return new a.RegisterUserAgentClient(this,e,t)},e.prototype.subscribe=function(e,t){return new a.SubscribeUserAgentClient(this,e,t)},e.prototype.request=function(e,t){return new a.UserAgentClient(o.NonInviteClientTransaction,this,e,t)},e.prototype.makeOutgoingRequestMessage=function(e,t,r,o,a,s,c){var u=this.configuration.sipjsId,d=this.configuration.displayName,l=this.configuration.viaForceRport,h=this.configuration.hackViaTcp,p=this.configuration.supportedOptionTags.slice();e===i.C.REGISTER&&p.push("path","gruu"),e===i.C.INVITE&&(this.configuration.contact.pubGruu||this.configuration.contact.tempGruu)&&p.push("gruu");var f={callIdPrefix:u,forceRport:l,fromDisplayName:d,hackViaTcp:h,optionTags:p,routeSet:this.configuration.routeSet,userAgentString:this.configuration.userAgentHeaderFieldValue,viaHost:this.configuration.viaHost},g=n.__assign({},f,a);return new i.OutgoingRequestMessage(e,t,r,o,g,s,c)},e.prototype.receiveIncomingRequestFromTransport=function(e){this.receiveRequestFromTransport(e)},e.prototype.receiveIncomingResponseFromTransport=function(e){this.receiveResponseFromTransport(e)},e.prototype.replyStateless=function(e,t){var r=this.configuration.userAgentHeaderFieldValue,o=this.configuration.supportedOptionTagsResponse;t=n.__assign({},t,{userAgent:r,supported:o});var a=i.constructOutgoingResponse(e,t);return this.transport.send(a.message),a},e.prototype.receiveRequestFromTransport=function(e){var t=e.viaBranch,r=this.userAgentServers.get(t);e.method===i.C.ACK&&r&&r.transaction.state===o.TransactionState.Accepted&&r instanceof a.InviteUserAgentServer?this.logger.warn("Discarding out of dialog ACK after 2xx response sent on transaction "+t+"."):e.method!==i.C.CANCEL?r?r.transaction.receiveRequest(e):this.receiveRequest(e):r?(this.replyStateless(e,{statusCode:200}),r.transaction instanceof o.InviteServerTransaction&&r.transaction.state===o.TransactionState.Proceeding&&r instanceof a.InviteUserAgentServer&&r.receiveCancel(e)):this.replyStateless(e,{statusCode:481})},e.prototype.receiveRequest=function(e){if(s.AllowedMethods.includes(e.method)){if(!e.ruri)throw new Error("Request-URI undefined.");if("sip"===e.ruri.scheme){var t=e.ruri,r=function(e){return!!e&&e.user===t.user};if(!r(this.configuration.aor)&&!(r(this.configuration.contact.uri)||r(this.configuration.contact.pubGruu)||r(this.configuration.contact.tempGruu)))return this.logger.warn("Request-URI does not point to us."),void(e.method!==i.C.ACK&&this.replyStateless(e,{statusCode:404}));if(e.method!==i.C.INVITE||e.hasHeader("Contact")){if(!e.toTag){var n=e.viaBranch;if(!this.userAgentServers.has(n))if(Array.from(this.userAgentServers.values()).some((function(t){return t.transaction.request.fromTag===e.fromTag&&t.transaction.request.callId===e.callId&&t.transaction.request.cseq===e.cseq})))return void this.replyStateless(e,{statusCode:482})}e.toTag?this.receiveInsideDialogRequest(e):this.receiveOutsideDialogRequest(e)}else this.replyStateless(e,{statusCode:400,reasonPhrase:"Missing Contact Header"})}else this.replyStateless(e,{statusCode:416})}else{var o="Allow: "+s.AllowedMethods.toString();this.replyStateless(e,{statusCode:405,extraHeaders:[o]})}},e.prototype.receiveInsideDialogRequest=function(e){if(e.method===i.C.NOTIFY){var t=e.parseHeader("Event");if(!t||!t.event)return void this.replyStateless(e,{statusCode:489});var r=e.callId+e.toTag+t.event,n=this.subscribers.get(r);if(n){var o=new a.NotifyUserAgentServer(this,e);return void n.onNotify(o)}}var u=e.callId+e.toTag+e.fromTag,d=this.dialogs.get(u);if(d){if(e.method===i.C.OPTIONS){var l="Allow: "+s.AllowedMethods.toString(),h="Accept: "+c.toString();return void this.replyStateless(e,{statusCode:200,extraHeaders:[l,h]})}d.receiveRequest(e)}else e.method!==i.C.ACK&&this.replyStateless(e,{statusCode:481})},e.prototype.receiveOutsideDialogRequest=function(e){switch(e.method){case i.C.ACK:break;case i.C.BYE:this.replyStateless(e,{statusCode:481});break;case i.C.CANCEL:throw new Error("Unexpected out of dialog request method "+e.method+".");case i.C.INFO:this.replyStateless(e,{statusCode:405});break;case i.C.INVITE:var t=new a.InviteUserAgentServer(this,e);this.delegate.onInvite?this.delegate.onInvite(t):t.reject();break;case i.C.MESSAGE:t=new a.MessageUserAgentServer(this,e);this.delegate.onMessage?this.delegate.onMessage(t):t.accept();break;case i.C.NOTIFY:t=new a.NotifyUserAgentServer(this,e);this.delegate.onNotify?this.delegate.onNotify(t):t.reject({statusCode:405});break;case i.C.OPTIONS:var r="Allow: "+s.AllowedMethods.toString(),n="Accept: "+c.toString();this.replyStateless(e,{statusCode:200,extraHeaders:[r,n]});break;case i.C.REFER:t=new a.ReferUserAgentServer(this,e);this.delegate.onRefer?this.delegate.onRefer(t):t.reject({statusCode:405});break;case i.C.REGISTER:t=new a.RegisterUserAgentServer(this,e);this.delegate.onRegister?this.delegate.onRegister(t):t.reject({statusCode:405});break;case i.C.SUBSCRIBE:t=new a.SubscribeUserAgentServer(this,e);this.delegate.onSubscribe?this.delegate.onSubscribe(t):t.reject({statusCode:480});break;default:throw new Error("Unexpected out of dialog request method "+e.method+".")}},e.prototype.receiveResponseFromTransport=function(e){if(e.getHeaders("via").length>1)this.logger.warn("More than one Via header field present in the response, dropping");else{var t=e.viaBranch+e.method,r=this.userAgentClients.get(t);r?r.transaction.receiveResponse(e):this.logger.warn("Discarding unmatched "+e.statusCode+" response to "+e.method+" "+t+".")}},e}();t.UserAgentCore=u},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=r(1),o=function(e){function t(t,r,n){return e.call(this,i.NonInviteClientTransaction,t,r,n)||this}return n.__extends(t,e),t}(r(3).UserAgentClient);t.CancelUserAgentClient=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=r(17),o=r(15),a=r(1),s=function(e){function t(t,r,n){var i=e.call(this,a.InviteClientTransaction,t,r,n)||this;return i.confirmedDialogAcks=new Map,i.confirmedDialogs=new Map,i.earlyDialogs=new Map,i.delegate=n,i}return n.__extends(t,e),t.prototype.dispose=function(){this.earlyDialogs.forEach((function(e){return e.dispose()})),this.earlyDialogs.clear(),e.prototype.dispose.call(this)},t.prototype.receiveResponse=function(e){var t=this;if(this.authenticationGuard(e)){var r=e.statusCode?e.statusCode.toString():"";if(!r)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(r):return void(this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e}));case/^1[0-9]{2}$/.test(r):if(!e.toTag)return void this.logger.warn("Non-100 1xx INVITE response received without a to tag, dropping.");var n=i.Dialog.initialDialogStateForUserAgentClient(this.message,e),s=this.earlyDialogs.get(n.id);if(!s){if(!((d=this.transaction)instanceof a.InviteClientTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");s=new i.SessionDialog(d,this.core,n),this.earlyDialogs.set(s.id,s)}if(!s.reliableSequenceGuard(e))return void this.logger.warn("1xx INVITE reliable response received out of order, dropping.");s.signalingState!==o.SignalingState.Initial&&s.signalingState!==o.SignalingState.HaveLocalOffer||s.signalingStateTransition(e);var c=s;return void(this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:c,prack:function(e){return c.prack(void 0,e)}}));case/^2[0-9]{2}$/.test(r):n=i.Dialog.initialDialogStateForUserAgentClient(this.message,e);var u=this.confirmedDialogs.get(n.id);if(u){if(h=this.confirmedDialogAcks.get(n.id)){if(!((d=this.transaction)instanceof a.InviteClientTransaction))throw new Error("Client transaction not instance of InviteClientTransaction.");d.ackResponse(h.message)}return}if(u=this.earlyDialogs.get(n.id))u.confirm(),u.recomputeRouteSet(e),this.earlyDialogs.delete(u.id),this.confirmedDialogs.set(u.id,u);else{var d;if(!((d=this.transaction)instanceof a.InviteClientTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");u=new i.SessionDialog(d,this.core,n),this.confirmedDialogs.set(u.id,u)}u.signalingState!==o.SignalingState.Initial&&u.signalingState!==o.SignalingState.HaveLocalOffer||u.signalingStateTransition(e);var l=u;if(this.delegate&&this.delegate.onAccept)this.delegate.onAccept({message:e,session:l,ack:function(e){var r=l.ack(e);return t.confirmedDialogAcks.set(l.id,r),r}});else{var h=l.ack();this.confirmedDialogAcks.set(l.id,h)}return;case/^3[0-9]{2}$/.test(r):return this.earlyDialogs.forEach((function(e){return e.dispose()})),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e}));case/^[4-6][0-9]{2}$/.test(r):return this.earlyDialogs.forEach((function(e){return e.dispose()})),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e}));default:throw new Error("Invalid status code "+r)}throw new Error("Executing what should be an unreachable code path receiving "+r+" response.")}},t}(r(3).UserAgentClient);t.InviteUserAgentClient=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=r(17),o=r(16),a=r(15),s=r(1),c=r(14),u=function(e){function t(t,r,n){var i=e.call(this,s.InviteServerTransaction,t,r,n)||this;return i.core=t,i}return n.__extends(t,e),t.prototype.dispose=function(){this.earlyDialog&&this.earlyDialog.dispose(),e.prototype.dispose.call(this)},t.prototype.accept=function(t){if(void 0===t&&(t={statusCode:200}),!this.acceptable)throw new o.TransactionStateError(this.message.method+" not acceptable in state "+this.transaction.state+".");if(!this.confirmedDialog)if(this.earlyDialog)this.earlyDialog.confirm(),this.confirmedDialog=this.earlyDialog,this.earlyDialog=void 0;else{var r=this.transaction;if(!(r instanceof s.InviteServerTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");var u=i.Dialog.initialDialogStateForUserAgentServer(this.message,this.toTag);this.confirmedDialog=new i.SessionDialog(r,this.core,u)}var d=this.message.getHeaders("record-route").map((function(e){return"Record-Route: "+e})),l="Contact: "+this.core.configuration.contact.toString(),h="Allow: "+c.AllowedMethods.toString();if(!t.body)if(this.confirmedDialog.signalingState===a.SignalingState.Stable)t.body=this.confirmedDialog.answer;else if(this.confirmedDialog.signalingState===a.SignalingState.Initial||this.confirmedDialog.signalingState===a.SignalingState.HaveRemoteOffer)throw new Error("Response must have a body.");t.statusCode=t.statusCode||200,t.extraHeaders=t.extraHeaders||[],t.extraHeaders=t.extraHeaders.concat(d),t.extraHeaders.push(h),t.extraHeaders.push(l);var p=e.prototype.accept.call(this,t),f=this.confirmedDialog,g=n.__assign({},p,{session:f});return t.body&&this.confirmedDialog.signalingState!==a.SignalingState.Stable&&this.confirmedDialog.signalingStateTransition(t.body),g},t.prototype.progress=function(t){if(void 0===t&&(t={statusCode:180}),!this.progressable)throw new o.TransactionStateError(this.message.method+" not progressable in state "+this.transaction.state+".");if(!this.earlyDialog){var r=this.transaction;if(!(r instanceof s.InviteServerTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");var c=i.Dialog.initialDialogStateForUserAgentServer(this.message,this.toTag,!0);this.earlyDialog=new i.SessionDialog(r,this.core,c)}var u=this.message.getHeaders("record-route").map((function(e){return"Record-Route: "+e})),d="Contact: "+this.core.configuration.contact;t.extraHeaders=t.extraHeaders||[],t.extraHeaders=t.extraHeaders.concat(u),t.extraHeaders.push(d);var l=e.prototype.progress.call(this,t),h=this.earlyDialog,p=n.__assign({},l,{session:h});return t.body&&this.earlyDialog.signalingState!==a.SignalingState.Stable&&this.earlyDialog.signalingStateTransition(t.body),p},t.prototype.redirect=function(t,r){return void 0===r&&(r={statusCode:302}),e.prototype.redirect.call(this,t,r)},t.prototype.reject=function(t){return void 0===t&&(t={statusCode:486}),e.prototype.reject.call(this,t)},t}(r(4).UserAgentServer);t.InviteUserAgentServer=u},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=r(1),o=function(e){function t(t,r,n){return e.call(this,i.NonInviteClientTransaction,t,r,n)||this}return n.__extends(t,e),t}(r(3).UserAgentClient);t.MessageUserAgentClient=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=r(1),o=function(e){function t(t,r,n){var o=e.call(this,i.NonInviteServerTransaction,t,r,n)||this;return o.core=t,o}return n.__extends(t,e),t}(r(4).UserAgentServer);t.MessageUserAgentServer=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=r(1),o=function(e){function t(t,r,n){return e.call(this,i.NonInviteClientTransaction,t,r,n)||this}return n.__extends(t,e),t}(r(3).UserAgentClient);t.PublishUserAgentClient=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=r(1),o=function(e){function t(t,r,n){return e.call(this,i.NonInviteServerTransaction,t.userAgentCore,r,n)||this}return n.__extends(t,e),t}(r(4).UserAgentServer);t.ReSubscribeUserAgentServer=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=r(1),o=function(e){function t(t,r,n){return e.call(this,i.NonInviteClientTransaction,t,r,n)||this}return n.__extends(t,e),t}(r(3).UserAgentClient);t.RegisterUserAgentClient=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=r(1),o=function(e){function t(t,r,n){var o=e.call(this,i.NonInviteServerTransaction,t,r,n)||this;return o.core=t,o}return n.__extends(t,e),t}(r(4).UserAgentServer);t.RegisterUserAgentServer=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=r(47),o=r(27),a=r(6),s=r(1),c=function(e){function t(t,r,n){var i=this,a=r.getHeader("Event");if(!a)throw new Error("Event undefined");var c=r.getHeader("Expires");if(!c)throw new Error("Expires undefined");return(i=e.call(this,s.NonInviteClientTransaction,t,r,n)||this).delegate=n,i.subscriberId=r.callId+r.fromTag+a,i.subscriptionExpiresRequested=i.subscriptionExpires=Number(c),i.subscriptionEvent=a,i.subscriptionState=o.SubscriptionState.NotifyWait,i.waitNotifyStart(),i}return n.__extends(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this)},t.prototype.onNotify=function(e){var t=e.message.parseHeader("Event").event;if(!t||t!==this.subscriptionEvent)return this.logger.warn("Failed to parse event."),void e.reject({statusCode:489});var r=e.message.parseHeader("Subscription-State");if(!r||!r.state)return this.logger.warn("Failed to parse subscription state."),void e.reject({statusCode:489});var n=r.state;switch(n){case"pending":case"active":case"terminated":break;default:return this.logger.warn("Invalid subscription state "+n),void e.reject({statusCode:489})}if("terminated"!==n&&!e.message.parseHeader("contact"))return this.logger.warn("Failed to parse contact."),void e.reject({statusCode:489});if(this.dialog)throw new Error("Dialog already created. This implementation only supports install of single subscriptions.");switch(this.waitNotifyStop(),this.subscriptionExpires=r.expires?Math.min(this.subscriptionExpires,Math.max(r.expires,0)):this.subscriptionExpires,n){case"pending":this.subscriptionState=o.SubscriptionState.Pending;break;case"active":this.subscriptionState=o.SubscriptionState.Active;break;case"terminated":this.subscriptionState=o.SubscriptionState.Terminated;break;default:throw new Error("Unrecognized state "+n+".")}if(this.subscriptionState!==o.SubscriptionState.Terminated){var a=i.SubscriptionDialog.initialDialogStateForSubscription(this.message,e.message);this.dialog=new i.SubscriptionDialog(this.subscriptionEvent,this.subscriptionExpires,this.subscriptionState,this.core,a)}if(this.delegate&&this.delegate.onNotify){var s=e,c=this.dialog;this.delegate.onNotify({request:s,subscription:c})}else e.accept()},t.prototype.waitNotifyStart=function(){var e=this;this.N||(this.core.subscribers.set(this.subscriberId,this),this.N=setTimeout((function(){return e.timer_N()}),a.Timers.TIMER_N))},t.prototype.waitNotifyStop=function(){this.N&&(this.core.subscribers.delete(this.subscriberId),clearTimeout(this.N),this.N=void 0)},t.prototype.receiveResponse=function(t){if(this.authenticationGuard(t)){if(t.statusCode&&t.statusCode>=200&&t.statusCode<300){var r=t.getHeader("Expires");if(r){var n=Number(r);n>this.subscriptionExpiresRequested&&this.logger.warn("Expires header in a 200-class response to SUBSCRIBE with a higher value than the one in the request"),nthis.subscriptionExpires&&(this.dialog.subscriptionExpires=this.subscriptionExpires)}t.statusCode&&t.statusCode>=300&&t.statusCode<700&&this.waitNotifyStop(),e.prototype.receiveResponse.call(this,t)}},t.prototype.timer_N=function(){this.logger.warn("Timer N expired for SUBSCRIBE user agent client. Timed out waiting for NOTIFY."),this.waitNotifyStop(),this.delegate&&this.delegate.onNotifyTimeout&&this.delegate.onNotifyTimeout()},t}(r(3).UserAgentClient);t.SubscribeUserAgentClient=c},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=r(1),o=function(e){function t(t,r,n){var o=e.call(this,i.NonInviteServerTransaction,t,r,n)||this;return o.core=t,o}return n.__extends(t,e),t}(r(4).UserAgentServer);t.SubscribeUserAgentServer=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=function(e){function t(t,r){var n=e.call(this)||this;return n.logger=t,n}return n.__extends(t,e),t.prototype.connect=function(e){var t=this;return void 0===e&&(e={}),this.connectPromise(e).then((function(e){e.overrideEvent||t.emit("connected")}))},t.prototype.send=function(e,t){var r=this;return void 0===t&&(t={}),this.sendPromise(e).then((function(e){e.overrideEvent||r.emit("messageSent",e.msg)}))},t.prototype.disconnect=function(e){var t=this;return void 0===e&&(e={}),this.disconnectPromise(e).then((function(e){e.overrideEvent||t.emit("disconnected")}))},t.prototype.afterConnected=function(e){this.isConnected()?e():this.once("connected",e)},t.prototype.waitForConnected=function(){var e=this;return console.warn("DEPRECATION WARNING Transport.waitForConnected(): use afterConnected() instead"),new Promise((function(t){e.afterConnected(t)}))},t}(r(7).EventEmitter);t.Transport=i}])})); \ No newline at end of file diff --git a/dist/sip.js b/dist/sip.js deleted file mode 100644 index 20d4c368b..000000000 --- a/dist/sip.js +++ /dev/null @@ -1,21461 +0,0 @@ -/*! - * - * SIP version 0.15.5 - * Copyright (c) 2014-2019 Junction Networks, Inc - * Homepage: https://sipjs.com - * License: https://sipjs.com/license/ - * - * - * ~~~SIP.js contains substantial portions of JsSIP under the following license~~~ - * Homepage: http://jssip.net - * Copyright (c) 2012-2013 José Luis Millán - Versatica - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * ~~~ end JsSIP license ~~~ - * - * - * - * - */ -(function webpackUniversalModuleDefinition(root, factory) { - if(typeof exports === 'object' && typeof module === 'object') - module.exports = factory(); - else if(typeof define === 'function' && define.amd) - define([], factory); - else if(typeof exports === 'object') - exports["SIP"] = factory(); - else - root["SIP"] = factory(); -})(this, function() { -return /******/ (function(modules) { // webpackBootstrap -/******/ // The module cache -/******/ var installedModules = {}; -/******/ -/******/ // The require function -/******/ function __webpack_require__(moduleId) { -/******/ -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) { -/******/ return installedModules[moduleId].exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ i: moduleId, -/******/ l: false, -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); -/******/ -/******/ // Flag the module as loaded -/******/ module.l = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/******/ -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; -/******/ -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; -/******/ -/******/ // define getter function for harmony exports -/******/ __webpack_require__.d = function(exports, name, getter) { -/******/ if(!__webpack_require__.o(exports, name)) { -/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); -/******/ } -/******/ }; -/******/ -/******/ // define __esModule on exports -/******/ __webpack_require__.r = function(exports) { -/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { -/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); -/******/ } -/******/ Object.defineProperty(exports, '__esModule', { value: true }); -/******/ }; -/******/ -/******/ // create a fake namespace object -/******/ // mode & 1: value is a module id, require it -/******/ // mode & 2: merge all properties of value into the ns -/******/ // mode & 4: return value when already ns object -/******/ // mode & 8|1: behave like require -/******/ __webpack_require__.t = function(value, mode) { -/******/ if(mode & 1) value = __webpack_require__(value); -/******/ if(mode & 8) return value; -/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; -/******/ var ns = Object.create(null); -/******/ __webpack_require__.r(ns); -/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); -/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); -/******/ return ns; -/******/ }; -/******/ -/******/ // getDefaultExport function for compatibility with non-harmony modules -/******/ __webpack_require__.n = function(module) { -/******/ var getter = module && module.__esModule ? -/******/ function getDefault() { return module['default']; } : -/******/ function getModuleExports() { return module; }; -/******/ __webpack_require__.d(getter, 'a', getter); -/******/ return getter; -/******/ }; -/******/ -/******/ // Object.prototype.hasOwnProperty.call -/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; -/******/ -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = ""; -/******/ -/******/ -/******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = 0); -/******/ }) -/************************************************************************/ -/******/ ([ -/* 0 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var core_1 = __webpack_require__(2); -exports.DigestAuthentication = core_1.DigestAuthentication; -exports.Grammar = core_1.Grammar; -exports.IncomingRequest = core_1.IncomingRequestMessage; -exports.IncomingResponse = core_1.IncomingResponseMessage; -exports.LoggerFactory = core_1.LoggerFactory; -exports.NameAddrHeader = core_1.NameAddrHeader; -exports.OutgoingRequest = core_1.OutgoingRequestMessage; -exports.Timers = core_1.Timers; -exports.Transport = core_1.Transport; -exports.URI = core_1.URI; -var ClientContext_1 = __webpack_require__(79); -exports.ClientContext = ClientContext_1.ClientContext; -var Constants_1 = __webpack_require__(80); -exports.C = Constants_1.C; -var Enums_1 = __webpack_require__(82); -exports.DialogStatus = Enums_1.DialogStatus; -exports.SessionStatus = Enums_1.SessionStatus; -exports.TypeStrings = Enums_1.TypeStrings; -exports.UAStatus = Enums_1.UAStatus; -var Exceptions_1 = __webpack_require__(84); -exports.Exceptions = Exceptions_1.Exceptions; -var Parser_1 = __webpack_require__(85); -exports.Parser = Parser_1.Parser; -var PublishContext_1 = __webpack_require__(86); -exports.PublishContext = PublishContext_1.PublishContext; -var ReferContext_1 = __webpack_require__(87); -exports.ReferClientContext = ReferContext_1.ReferClientContext; -exports.ReferServerContext = ReferContext_1.ReferServerContext; -var RegisterContext_1 = __webpack_require__(89); -exports.RegisterContext = RegisterContext_1.RegisterContext; -var ServerContext_1 = __webpack_require__(88); -exports.ServerContext = ServerContext_1.ServerContext; -var Session_1 = __webpack_require__(90); -exports.InviteClientContext = Session_1.InviteClientContext; -exports.InviteServerContext = Session_1.InviteServerContext; -exports.Session = Session_1.Session; -var Subscription_1 = __webpack_require__(92); -exports.Subscription = Subscription_1.Subscription; -var transactions_1 = __webpack_require__(27); -var Transactions = { - InviteClientTransaction: transactions_1.InviteClientTransaction, - InviteServerTransaction: transactions_1.InviteServerTransaction, - NonInviteClientTransaction: transactions_1.NonInviteClientTransaction, - NonInviteServerTransaction: transactions_1.NonInviteServerTransaction -}; -exports.Transactions = Transactions; -var UA_1 = __webpack_require__(93); -exports.makeUserAgentCoreConfigurationFromUA = UA_1.makeUserAgentCoreConfigurationFromUA; -exports.UA = UA_1.UA; -var Utils_1 = __webpack_require__(83); -exports.Utils = Utils_1.Utils; -var Web = tslib_1.__importStar(__webpack_require__(104)); -exports.Web = Web; -var version = Constants_1.C.version; -exports.version = version; -var name = "sip.js"; -exports.name = name; -var Core = tslib_1.__importStar(__webpack_require__(2)); -exports.Core = Core; - - -/***/ }), -/* 1 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__extends", function() { return __extends; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__assign", function() { return __assign; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__rest", function() { return __rest; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__decorate", function() { return __decorate; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__param", function() { return __param; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__metadata", function() { return __metadata; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__awaiter", function() { return __awaiter; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__generator", function() { return __generator; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__exportStar", function() { return __exportStar; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__values", function() { return __values; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__read", function() { return __read; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__spread", function() { return __spread; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__spreadArrays", function() { return __spreadArrays; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__await", function() { return __await; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncGenerator", function() { return __asyncGenerator; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncDelegator", function() { return __asyncDelegator; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncValues", function() { return __asyncValues; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__makeTemplateObject", function() { return __makeTemplateObject; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__importStar", function() { return __importStar; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__importDefault", function() { return __importDefault; }); -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ -/* global Reflect, Promise */ - -var extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); -}; - -function __extends(d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -} - -var __assign = function() { - __assign = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - } - return __assign.apply(this, arguments); -} - -function __rest(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; -} - -function __decorate(decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -} - -function __param(paramIndex, decorator) { - return function (target, key) { decorator(target, key, paramIndex); } -} - -function __metadata(metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); -} - -function __awaiter(thisArg, _arguments, P, generator) { - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -} - -function __generator(thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -} - -function __exportStar(m, exports) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; -} - -function __values(o) { - var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; - if (m) return m.call(o); - return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; -} - -function __read(o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; -} - -function __spread() { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read(arguments[i])); - return ar; -} - -function __spreadArrays() { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) - for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) - r[k] = a[j]; - return r; -}; - -function __await(v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); -} - -function __asyncGenerator(thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function fulfill(value) { resume("next", value); } - function reject(value) { resume("throw", value); } - function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } -} - -function __asyncDelegator(o) { - var i, p; - return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } -} - -function __asyncValues(o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } -} - -function __makeTemplateObject(cooked, raw) { - if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } - return cooked; -}; - -function __importStar(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result.default = mod; - return result; -} - -function __importDefault(mod) { - return (mod && mod.__esModule) ? mod : { default: mod }; -} - - -/***/ }), -/* 2 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -/** - * A core library implementing low level SIP protocol elements. - * @packageDocumentation - */ -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -// Directories -tslib_1.__exportStar(__webpack_require__(3), exports); -tslib_1.__exportStar(__webpack_require__(31), exports); -tslib_1.__exportStar(__webpack_require__(60), exports); -tslib_1.__exportStar(__webpack_require__(5), exports); -tslib_1.__exportStar(__webpack_require__(24), exports); -tslib_1.__exportStar(__webpack_require__(56), exports); -tslib_1.__exportStar(__webpack_require__(27), exports); -tslib_1.__exportStar(__webpack_require__(64), exports); -tslib_1.__exportStar(__webpack_require__(66), exports); -// Files -tslib_1.__exportStar(__webpack_require__(26), exports); -tslib_1.__exportStar(__webpack_require__(78), exports); - - -/***/ }), -/* 3 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -tslib_1.__exportStar(__webpack_require__(4), exports); -tslib_1.__exportStar(__webpack_require__(23), exports); -tslib_1.__exportStar(__webpack_require__(55), exports); - - -/***/ }), -/* 4 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var messages_1 = __webpack_require__(5); -/** - * Dialog. - * @remarks - * A key concept for a user agent is that of a dialog. A dialog - * represents a peer-to-peer SIP relationship between two user agents - * that persists for some time. The dialog facilitates sequencing of - * messages between the user agents and proper routing of requests - * between both of them. The dialog represents a context in which to - * interpret SIP messages. - * https://tools.ietf.org/html/rfc3261#section-12 - * @public - */ -var Dialog = /** @class */ (function () { - /** - * Dialog constructor. - * @param core - User agent core. - * @param dialogState - Initial dialog state. - */ - function Dialog(core, dialogState) { - this.core = core; - this.dialogState = dialogState; - this.core.dialogs.set(this.id, this); - } - /** - * When a UAC receives a response that establishes a dialog, it - * constructs the state of the dialog. This state MUST be maintained - * for the duration of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.1.2 - * @param outgoingRequestMessage - Outgoing request message for dialog. - * @param incomingResponseMessage - Incoming response message creating dialog. - */ - Dialog.initialDialogStateForUserAgentClient = function (outgoingRequestMessage, incomingResponseMessage) { - // If the request was sent over TLS, and the Request-URI contained a - // SIPS URI, the "secure" flag is set to TRUE. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - var secure = false; // FIXME: Currently no support for TLS. - // The route set MUST be set to the list of URIs in the Record-Route - // header field from the response, taken in reverse order and preserving - // all URI parameters. If no Record-Route header field is present in - // the response, the route set MUST be set to the empty set. This route - // set, even if empty, overrides any pre-existing route set for future - // requests in this dialog. The remote target MUST be set to the URI - // from the Contact header field of the response. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - var routeSet = incomingResponseMessage.getHeaders("record-route").reverse(); - var contact = incomingResponseMessage.parseHeader("contact"); - if (!contact) { // TODO: Review to make sure this will never happen - throw new Error("Contact undefined."); - } - if (!(contact instanceof messages_1.NameAddrHeader)) { - throw new Error("Contact not instance of NameAddrHeader."); - } - var remoteTarget = contact.uri; - // The local sequence number MUST be set to the value of the sequence - // number in the CSeq header field of the request. The remote sequence - // number MUST be empty (it is established when the remote UA sends a - // request within the dialog). The call identifier component of the - // dialog ID MUST be set to the value of the Call-ID in the request. - // The local tag component of the dialog ID MUST be set to the tag in - // the From field in the request, and the remote tag component of the - // dialog ID MUST be set to the tag in the To field of the response. A - // UAC MUST be prepared to receive a response without a tag in the To - // field, in which case the tag is considered to have a value of null. - // - // This is to maintain backwards compatibility with RFC 2543, which - // did not mandate To tags. - // - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - var localSequenceNumber = outgoingRequestMessage.cseq; - var remoteSequenceNumber = undefined; - var callId = outgoingRequestMessage.callId; - var localTag = outgoingRequestMessage.fromTag; - var remoteTag = incomingResponseMessage.toTag; - if (!callId) { // TODO: Review to make sure this will never happen - throw new Error("Call id undefined."); - } - if (!localTag) { // TODO: Review to make sure this will never happen - throw new Error("From tag undefined."); - } - if (!remoteTag) { // TODO: Review to make sure this will never happen - throw new Error("To tag undefined."); // FIXME: No backwards compatibility with RFC 2543 - } - // The remote URI MUST be set to the URI in the To field, and the local - // URI MUST be set to the URI in the From field. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - if (!outgoingRequestMessage.from) { // TODO: Review to make sure this will never happen - throw new Error("From undefined."); - } - if (!outgoingRequestMessage.to) { // TODO: Review to make sure this will never happen - throw new Error("To undefined."); - } - var localURI = outgoingRequestMessage.from.uri; - var remoteURI = outgoingRequestMessage.to.uri; - // A dialog can also be in the "early" state, which occurs when it is - // created with a provisional response, and then transition to the - // "confirmed" state when a 2xx final response arrives. - // https://tools.ietf.org/html/rfc3261#section-12 - if (!incomingResponseMessage.statusCode) { - throw new Error("Incoming response status code undefined."); - } - var early = incomingResponseMessage.statusCode < 200 ? true : false; - var dialogState = { - id: callId + localTag + remoteTag, - early: early, - callId: callId, - localTag: localTag, - remoteTag: remoteTag, - localSequenceNumber: localSequenceNumber, - remoteSequenceNumber: remoteSequenceNumber, - localURI: localURI, - remoteURI: remoteURI, - remoteTarget: remoteTarget, - routeSet: routeSet, - secure: secure - }; - return dialogState; - }; - /** - * The UAS then constructs the state of the dialog. This state MUST be - * maintained for the duration of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.1.1 - * @param incomingRequestMessage - Incoming request message creating dialog. - * @param toTag - Tag in the To field in the response to the incoming request. - */ - Dialog.initialDialogStateForUserAgentServer = function (incomingRequestMessage, toTag, early) { - if (early === void 0) { early = false; } - // If the request arrived over TLS, and the Request-URI contained a SIPS - // URI, the "secure" flag is set to TRUE. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - var secure = false; // FIXME: Currently no support for TLS. - // The route set MUST be set to the list of URIs in the Record-Route - // header field from the request, taken in order and preserving all URI - // parameters. If no Record-Route header field is present in the - // request, the route set MUST be set to the empty set. This route set, - // even if empty, overrides any pre-existing route set for future - // requests in this dialog. The remote target MUST be set to the URI - // from the Contact header field of the request. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - var routeSet = incomingRequestMessage.getHeaders("record-route"); - var contact = incomingRequestMessage.parseHeader("contact"); - if (!contact) { // TODO: Review to make sure this will never happen - throw new Error("Contact undefined."); - } - if (!(contact instanceof messages_1.NameAddrHeader)) { - throw new Error("Contact not instance of NameAddrHeader."); - } - var remoteTarget = contact.uri; - // The remote sequence number MUST be set to the value of the sequence - // number in the CSeq header field of the request. The local sequence - // number MUST be empty. The call identifier component of the dialog ID - // MUST be set to the value of the Call-ID in the request. The local - // tag component of the dialog ID MUST be set to the tag in the To field - // in the response to the request (which always includes a tag), and the - // remote tag component of the dialog ID MUST be set to the tag from the - // From field in the request. A UAS MUST be prepared to receive a - // request without a tag in the From field, in which case the tag is - // considered to have a value of null. - // - // This is to maintain backwards compatibility with RFC 2543, which - // did not mandate From tags. - // - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - var remoteSequenceNumber = incomingRequestMessage.cseq; - var localSequenceNumber = undefined; - var callId = incomingRequestMessage.callId; - var localTag = toTag; - var remoteTag = incomingRequestMessage.fromTag; - // The remote URI MUST be set to the URI in the From field, and the - // local URI MUST be set to the URI in the To field. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - var remoteURI = incomingRequestMessage.from.uri; - var localURI = incomingRequestMessage.to.uri; - var dialogState = { - id: callId + localTag + remoteTag, - early: early, - callId: callId, - localTag: localTag, - remoteTag: remoteTag, - localSequenceNumber: localSequenceNumber, - remoteSequenceNumber: remoteSequenceNumber, - localURI: localURI, - remoteURI: remoteURI, - remoteTarget: remoteTarget, - routeSet: routeSet, - secure: secure - }; - return dialogState; - }; - /** Destructor. */ - Dialog.prototype.dispose = function () { - this.core.dialogs.delete(this.id); - }; - Object.defineProperty(Dialog.prototype, "id", { - /** - * A dialog is identified at each UA with a dialog ID, which consists of - * a Call-ID value, a local tag and a remote tag. The dialog ID at each - * UA involved in the dialog is not the same. Specifically, the local - * tag at one UA is identical to the remote tag at the peer UA. The - * tags are opaque tokens that facilitate the generation of unique - * dialog IDs. - * https://tools.ietf.org/html/rfc3261#section-12 - */ - get: function () { - return this.dialogState.id; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "early", { - /** - * A dialog can also be in the "early" state, which occurs when it is - * created with a provisional response, and then it transition to the - * "confirmed" state when a 2xx final response received or is sent. - * - * Note: RFC 3261 is concise on when a dialog is "confirmed", but it - * can be a point of confusion if an INVITE dialog is "confirmed" after - * a 2xx is sent or after receiving the ACK for the 2xx response. - * With careful reading it can be inferred a dialog is always is - * "confirmed" when the 2xx is sent (regardless of type of dialog). - * However a INVITE dialog does have additional considerations - * when it is confirmed but an ACK has not yet been received (in - * particular with regard to a callee sending BYE requests). - */ - get: function () { - return this.dialogState.early; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "callId", { - /** Call identifier component of the dialog id. */ - get: function () { - return this.dialogState.callId; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "localTag", { - /** Local tag component of the dialog id. */ - get: function () { - return this.dialogState.localTag; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "remoteTag", { - /** Remote tag component of the dialog id. */ - get: function () { - return this.dialogState.remoteTag; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "localSequenceNumber", { - /** Local sequence number (used to order requests from the UA to its peer). */ - get: function () { - return this.dialogState.localSequenceNumber; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "remoteSequenceNumber", { - /** Remote sequence number (used to order requests from its peer to the UA). */ - get: function () { - return this.dialogState.remoteSequenceNumber; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "localURI", { - /** Local URI. */ - get: function () { - return this.dialogState.localURI; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "remoteURI", { - /** Remote URI. */ - get: function () { - return this.dialogState.remoteURI; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "remoteTarget", { - /** Remote target. */ - get: function () { - return this.dialogState.remoteTarget; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "routeSet", { - /** - * Route set, which is an ordered list of URIs. The route set is the - * list of servers that need to be traversed to send a request to the peer. - */ - get: function () { - return this.dialogState.routeSet; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "secure", { - /** - * If the request was sent over TLS, and the Request-URI contained - * a SIPS URI, the "secure" flag is set to true. *NOT IMPLEMENTED* - */ - get: function () { - return this.dialogState.secure; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "userAgentCore", { - /** The user agent core servicing this dialog. */ - get: function () { - return this.core; - }, - enumerable: true, - configurable: true - }); - /** Confirm the dialog. Only matters if dialog is currently early. */ - Dialog.prototype.confirm = function () { - this.dialogState.early = false; - }; - /** - * Requests sent within a dialog, as any other requests, are atomic. If - * a particular request is accepted by the UAS, all the state changes - * associated with it are performed. If the request is rejected, none - * of the state changes are performed. - * - * Note that some requests, such as INVITEs, affect several pieces of - * state. - * - * https://tools.ietf.org/html/rfc3261#section-12.2.2 - * @param message - Incoming request message within this dialog. - */ - Dialog.prototype.receiveRequest = function (message) { - // ACK guard. - // By convention, the handling of ACKs is the responsibility - // the particular dialog implementation. For example, see SessionDialog. - // Furthermore, ACKs have same sequence number as the associated INVITE. - if (message.method === messages_1.C.ACK) { - return; - } - // If the remote sequence number was not empty, but the sequence number - // of the request is lower than the remote sequence number, the request - // is out of order and MUST be rejected with a 500 (Server Internal - // Error) response. If the remote sequence number was not empty, and - // the sequence number of the request is greater than the remote - // sequence number, the request is in order. It is possible for the - // CSeq sequence number to be higher than the remote sequence number by - // more than one. This is not an error condition, and a UAS SHOULD be - // prepared to receive and process requests with CSeq values more than - // one higher than the previous received request. The UAS MUST then set - // the remote sequence number to the value of the sequence number in the - // CSeq header field value in the request. - // - // If a proxy challenges a request generated by the UAC, the UAC has - // to resubmit the request with credentials. The resubmitted request - // will have a new CSeq number. The UAS will never see the first - // request, and thus, it will notice a gap in the CSeq number space. - // Such a gap does not represent any error condition. - // - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (this.remoteSequenceNumber) { - if (message.cseq <= this.remoteSequenceNumber) { - throw new Error("Out of sequence in dialog request. Did you forget to call sequenceGuard()?"); - } - this.dialogState.remoteSequenceNumber = message.cseq; - } - // If the remote sequence number is empty, it MUST be set to the value - // of the sequence number in the CSeq header field value in the request. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (!this.remoteSequenceNumber) { - this.dialogState.remoteSequenceNumber = message.cseq; - } - // When a UAS receives a target refresh request, it MUST replace the - // dialog's remote target URI with the URI from the Contact header field - // in that request, if present. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - // Note: "target refresh request" processing delegated to sub-class. - }; - /** - * If the dialog identifier in the 2xx response matches the dialog - * identifier of an existing dialog, the dialog MUST be transitioned to - * the "confirmed" state, and the route set for the dialog MUST be - * recomputed based on the 2xx response using the procedures of Section - * 12.2.1.2. Otherwise, a new dialog in the "confirmed" state MUST be - * constructed using the procedures of Section 12.1.2. - * - * Note that the only piece of state that is recomputed is the route - * set. Other pieces of state such as the highest sequence numbers - * (remote and local) sent within the dialog are not recomputed. The - * route set only is recomputed for backwards compatibility. RFC - * 2543 did not mandate mirroring of the Record-Route header field in - * a 1xx, only 2xx. However, we cannot update the entire state of - * the dialog, since mid-dialog requests may have been sent within - * the early dialog, modifying the sequence numbers, for example. - * - * https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - */ - Dialog.prototype.recomputeRouteSet = function (message) { - this.dialogState.routeSet = message.getHeaders("record-route").reverse(); - }; - /** - * A request within a dialog is constructed by using many of the - * components of the state stored as part of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - * @param method - Outgoing request method. - */ - Dialog.prototype.createOutgoingRequestMessage = function (method, options) { - // The URI in the To field of the request MUST be set to the remote URI - // from the dialog state. The tag in the To header field of the request - // MUST be set to the remote tag of the dialog ID. The From URI of the - // request MUST be set to the local URI from the dialog state. The tag - // in the From header field of the request MUST be set to the local tag - // of the dialog ID. If the value of the remote or local tags is null, - // the tag parameter MUST be omitted from the To or From header fields, - // respectively. - // - // Usage of the URI from the To and From fields in the original - // request within subsequent requests is done for backwards - // compatibility with RFC 2543, which used the URI for dialog - // identification. In this specification, only the tags are used for - // dialog identification. It is expected that mandatory reflection - // of the original To and From URI in mid-dialog requests will be - // deprecated in a subsequent revision of this specification. - // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - var toUri = this.remoteURI; - var toTag = this.remoteTag; - var fromUri = this.localURI; - var fromTag = this.localTag; - // The Call-ID of the request MUST be set to the Call-ID of the dialog. - // Requests within a dialog MUST contain strictly monotonically - // increasing and contiguous CSeq sequence numbers (increasing-by-one) - // in each direction (excepting ACK and CANCEL of course, whose numbers - // equal the requests being acknowledged or cancelled). Therefore, if - // the local sequence number is not empty, the value of the local - // sequence number MUST be incremented by one, and this value MUST be - // placed into the CSeq header field. If the local sequence number is - // empty, an initial value MUST be chosen using the guidelines of - // Section 8.1.1.5. The method field in the CSeq header field value - // MUST match the method of the request. - // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - var callId = this.callId; - var cseq; - if (options && options.cseq) { - cseq = options.cseq; - } - else if (!this.dialogState.localSequenceNumber) { - cseq = this.dialogState.localSequenceNumber = 1; // https://tools.ietf.org/html/rfc3261#section-8.1.1.5 - } - else { - cseq = this.dialogState.localSequenceNumber += 1; - } - // The UAC uses the remote target and route set to build the Request-URI - // and Route header field of the request. - // - // If the route set is empty, the UAC MUST place the remote target URI - // into the Request-URI. The UAC MUST NOT add a Route header field to - // the request. - // - // If the route set is not empty, and the first URI in the route set - // contains the lr parameter (see Section 19.1.1), the UAC MUST place - // the remote target URI into the Request-URI and MUST include a Route - // header field containing the route set values in order, including all - // parameters. - // - // If the route set is not empty, and its first URI does not contain the - // lr parameter, the UAC MUST place the first URI from the route set - // into the Request-URI, stripping any parameters that are not allowed - // in a Request-URI. The UAC MUST add a Route header field containing - // the remainder of the route set values in order, including all - // parameters. The UAC MUST then place the remote target URI into the - // Route header field as the last value. - // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - // The lr parameter, when present, indicates that the element - // responsible for this resource implements the routing mechanisms - // specified in this document. This parameter will be used in the - // URIs proxies place into Record-Route header field values, and - // may appear in the URIs in a pre-existing route set. - // - // This parameter is used to achieve backwards compatibility with - // systems implementing the strict-routing mechanisms of RFC 2543 - // and the rfc2543bis drafts up to bis-05. An element preparing - // to send a request based on a URI not containing this parameter - // can assume the receiving element implements strict-routing and - // reformat the message to preserve the information in the - // Request-URI. - // https://tools.ietf.org/html/rfc3261#section-19.1.1 - // NOTE: Not backwards compatible with RFC 2543 (no support for strict-routing). - var ruri = this.remoteTarget; - var routeSet = this.routeSet; - var extraHeaders = options && options.extraHeaders; - var body = options && options.body; - // The relative order of header fields with different field names is not - // significant. However, it is RECOMMENDED that header fields which are - // needed for proxy processing (Via, Route, Record-Route, Proxy-Require, - // Max-Forwards, and Proxy-Authorization, for example) appear towards - // the top of the message to facilitate rapid parsing. - // https://tools.ietf.org/html/rfc3261#section-7.3.1 - var message = this.userAgentCore.makeOutgoingRequestMessage(method, ruri, fromUri, toUri, { - callId: callId, - cseq: cseq, - fromTag: fromTag, - toTag: toTag, - routeSet: routeSet - }, extraHeaders, body); - return message; - }; - /** - * If the remote sequence number was not empty, but the sequence number - * of the request is lower than the remote sequence number, the request - * is out of order and MUST be rejected with a 500 (Server Internal - * Error) response. - * https://tools.ietf.org/html/rfc3261#section-12.2.2 - * @param request - Incoming request to guard. - * @returns True if the program execution is to continue in the branch in question. - * Otherwise a 500 Server Internal Error was stateless sent and request processing must stop. - */ - Dialog.prototype.sequenceGuard = function (message) { - // ACK guard. - // By convention, handling of unexpected ACKs is responsibility - // the particular dialog implementation. For example, see SessionDialog. - // Furthermore, we cannot reply to an "out of sequence" ACK. - if (message.method === messages_1.C.ACK) { - return true; - } - // Note: We are rejecting on "less than or equal to" the remote - // sequence number (excepting ACK whose numbers equal the requests - // being acknowledged or cancelled), which is the correct thing to - // do in our case. The only time a request with the same sequence number - // will show up here if is a) it is a very late retransmission of a - // request we already handled or b) it is a different request with the - // same sequence number which would be violation of the standard. - // Request retransmissions are absorbed by the transaction layer, - // so any request with a duplicate sequence number getting here - // would have to be a retransmission after the transaction terminated - // or a broken request (with unique via branch value). - // Requests within a dialog MUST contain strictly monotonically - // increasing and contiguous CSeq sequence numbers (increasing-by-one) - // in each direction (excepting ACK and CANCEL of course, whose numbers - // equal the requests being acknowledged or cancelled). Therefore, if - // the local sequence number is not empty, the value of the local - // sequence number MUST be incremented by one, and this value MUST be - // placed into the CSeq header field. - // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - if (this.remoteSequenceNumber && message.cseq <= this.remoteSequenceNumber) { - this.core.replyStateless(message, { statusCode: 500 }); - return false; - } - return true; - }; - return Dialog; -}()); -exports.Dialog = Dialog; - - -/***/ }), -/* 5 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -// Directories -tslib_1.__exportStar(__webpack_require__(6), exports); -// Files -tslib_1.__exportStar(__webpack_require__(8), exports); -tslib_1.__exportStar(__webpack_require__(19), exports); -tslib_1.__exportStar(__webpack_require__(11), exports); -tslib_1.__exportStar(__webpack_require__(10), exports); -tslib_1.__exportStar(__webpack_require__(9), exports); -tslib_1.__exportStar(__webpack_require__(17), exports); -tslib_1.__exportStar(__webpack_require__(13), exports); -tslib_1.__exportStar(__webpack_require__(18), exports); -tslib_1.__exportStar(__webpack_require__(22), exports); -tslib_1.__exportStar(__webpack_require__(14), exports); -tslib_1.__exportStar(__webpack_require__(15), exports); - - -/***/ }), -/* 6 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -tslib_1.__exportStar(__webpack_require__(7), exports); - - -/***/ }), -/* 7 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * SIP Methods - * @internal - */ -var C; -(function (C) { - C.ACK = "ACK"; - C.BYE = "BYE"; - C.CANCEL = "CANCEL"; - C.INFO = "INFO"; - C.INVITE = "INVITE"; - C.MESSAGE = "MESSAGE"; - C.NOTIFY = "NOTIFY"; - C.OPTIONS = "OPTIONS"; - C.REGISTER = "REGISTER"; - C.UPDATE = "UPDATE"; - C.SUBSCRIBE = "SUBSCRIBE"; - C.PUBLISH = "PUBLISH"; - C.REFER = "REFER"; - C.PRACK = "PRACK"; -})(C = exports.C || (exports.C = {})); - - -/***/ }), -/* 8 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var incoming_request_message_1 = __webpack_require__(9); -var incoming_response_message_1 = __webpack_require__(17); -var outgoing_request_message_1 = __webpack_require__(18); -/** - * Create a Body given a legacy body type. - * @param bodyLegacy - Body Object - * @internal - */ -function fromBodyLegacy(bodyLegacy) { - var content = (typeof bodyLegacy === "string") ? bodyLegacy : bodyLegacy.body; - var contentType = (typeof bodyLegacy === "string") ? "application/sdp" : bodyLegacy.contentType; - var contentDisposition = contentTypeToContentDisposition(contentType); - var body = { contentDisposition: contentDisposition, contentType: contentType, content: content }; - return body; -} -exports.fromBodyLegacy = fromBodyLegacy; -/** - * Given a message, get a normalized body. - * The content disposition is inferred if not set. - * @param message - The message. - * @internal - */ -function getBody(message) { - var contentDisposition; - var contentType; - var content; - // We're in UAS role, receiving incoming request - if (message instanceof incoming_request_message_1.IncomingRequestMessage) { - if (message.body) { - // FIXME: Parsing needs typing - var parse = message.parseHeader("Content-Disposition"); - contentDisposition = parse ? parse.type : undefined; - contentType = message.parseHeader("Content-Type"); - content = message.body; - } - } - // We're in UAC role, receiving incoming response - if (message instanceof incoming_response_message_1.IncomingResponseMessage) { - if (message.body) { - // FIXME: Parsing needs typing - var parse = message.parseHeader("Content-Disposition"); - contentDisposition = parse ? parse.type : undefined; - contentType = message.parseHeader("Content-Type"); - content = message.body; - } - } - // We're in UAC role, sending outgoing request - if (message instanceof outgoing_request_message_1.OutgoingRequestMessage) { - if (message.body) { - contentDisposition = message.getHeader("Content-Disposition"); - contentType = message.getHeader("Content-Type"); - if (typeof message.body === "string") { - // FIXME: OutgoingRequest should not allow a "string" body without a "Content-Type" header. - if (!contentType) { - throw new Error("Header content type header does not equal body content type."); - } - content = message.body; - } - else { - // FIXME: OutgoingRequest should not allow the "Content-Type" header not to match th body content type - if (contentType && contentType !== message.body.contentType) { - throw new Error("Header content type header does not equal body content type."); - } - contentType = message.body.contentType; - content = message.body.body; - } - } - } - // We're in UAS role, sending outgoing response - if (isBody(message)) { - contentDisposition = message.contentDisposition; - contentType = message.contentType; - content = message.content; - } - // No content, no body. - if (!content) { - return undefined; - } - if (contentType && !contentDisposition) { - contentDisposition = contentTypeToContentDisposition(contentType); - } - if (!contentDisposition) { - throw new Error("Content disposition undefined."); - } - if (!contentType) { - throw new Error("Content type undefined."); - } - return { - contentDisposition: contentDisposition, - contentType: contentType, - content: content - }; -} -exports.getBody = getBody; -/** - * User-Defined Type Guard for Body. - * @param body - Body to check. - * @internal - */ -function isBody(body) { - return body && - typeof body.content === "string" && - typeof body.contentType === "string" && - body.contentDisposition === undefined ? true : typeof body.contentDisposition === "string"; -} -exports.isBody = isBody; -// If the Content-Disposition header field is missing, bodies of -// Content-Type application/sdp imply the disposition "session", while -// other content types imply "render". -// https://tools.ietf.org/html/rfc3261#section-13.2.1 -function contentTypeToContentDisposition(contentType) { - if (contentType === "application/sdp") { - return "session"; - } - else { - return "render"; - } -} - - -/***/ }), -/* 9 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var incoming_message_1 = __webpack_require__(10); -/** - * Incoming request message. - * @public - */ -var IncomingRequestMessage = /** @class */ (function (_super) { - tslib_1.__extends(IncomingRequestMessage, _super); - function IncomingRequestMessage() { - return _super.call(this) || this; - } - return IncomingRequestMessage; -}(incoming_message_1.IncomingMessage)); -exports.IncomingRequestMessage = IncomingRequestMessage; - - -/***/ }), -/* 10 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var grammar_1 = __webpack_require__(11); -var utils_1 = __webpack_require__(16); -/** - * Incoming message. - * @public - */ -var IncomingMessage = /** @class */ (function () { - function IncomingMessage() { - this.headers = {}; - } - /** - * Insert a header of the given name and value into the last position of the - * header array. - * @param name - header name - * @param value - header value - */ - IncomingMessage.prototype.addHeader = function (name, value) { - var header = { raw: value }; - name = utils_1.headerize(name); - if (this.headers[name]) { - this.headers[name].push(header); - } - else { - this.headers[name] = [header]; - } - }; - /** - * Get the value of the given header name at the given position. - * @param name - header name - * @returns Returns the specified header, undefined if header doesn't exist. - */ - IncomingMessage.prototype.getHeader = function (name) { - var header = this.headers[utils_1.headerize(name)]; - if (header) { - if (header[0]) { - return header[0].raw; - } - } - else { - return; - } - }; - /** - * Get the header/s of the given name. - * @param name - header name - * @returns Array - with all the headers of the specified name. - */ - IncomingMessage.prototype.getHeaders = function (name) { - var header = this.headers[utils_1.headerize(name)]; - var result = []; - if (!header) { - return []; - } - for (var _i = 0, header_1 = header; _i < header_1.length; _i++) { - var headerPart = header_1[_i]; - result.push(headerPart.raw); - } - return result; - }; - /** - * Verify the existence of the given header. - * @param name - header name - * @returns true if header with given name exists, false otherwise - */ - IncomingMessage.prototype.hasHeader = function (name) { - return !!this.headers[utils_1.headerize(name)]; - }; - /** - * Parse the given header on the given index. - * @param name - header name - * @param idx - header index - * @returns Parsed header object, undefined if the - * header is not present or in case of a parsing error. - */ - IncomingMessage.prototype.parseHeader = function (name, idx) { - if (idx === void 0) { idx = 0; } - name = utils_1.headerize(name); - if (!this.headers[name]) { - // this.logger.log("header '" + name + "' not present"); - return; - } - else if (idx >= this.headers[name].length) { - // this.logger.log("not so many '" + name + "' headers present"); - return; - } - var header = this.headers[name][idx]; - var value = header.raw; - if (header.parsed) { - return header.parsed; - } - // substitute '-' by '_' for grammar rule matching. - var parsed = grammar_1.Grammar.parse(value, name.replace(/-/g, "_")); - if (parsed === -1) { - this.headers[name].splice(idx, 1); // delete from headers - // this.logger.warn('error parsing "' + name + '" header field with value "' + value + '"'); - return; - } - else { - header.parsed = parsed; - return parsed; - } - }; - /** - * Message Header attribute selector. Alias of parseHeader. - * @param name - header name - * @param idx - header index - * @returns Parsed header object, undefined if the - * header is not present or in case of a parsing error. - * - * @example - * message.s('via',3).port - */ - IncomingMessage.prototype.s = function (name, idx) { - if (idx === void 0) { idx = 0; } - return this.parseHeader(name, idx); - }; - /** - * Replace the value of the given header by the value. - * @param name - header name - * @param value - header value - */ - IncomingMessage.prototype.setHeader = function (name, value) { - this.headers[utils_1.headerize(name)] = [{ raw: value }]; - }; - IncomingMessage.prototype.toString = function () { - return this.data; - }; - return IncomingMessage; -}()); -exports.IncomingMessage = IncomingMessage; - - -/***/ }), -/* 11 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var pegGrammar = tslib_1.__importStar(__webpack_require__(12)); -/** - * Grammar. - * @internal - */ -var Grammar; -(function (Grammar) { - /** - * Parse. - * @param input - - * @param startRule - - */ - function parse(input, startRule) { - var options = { startRule: startRule }; - try { - pegGrammar.parse(input, options); - } - catch (e) { - options.data = -1; - } - return options.data; - } - Grammar.parse = parse; - /** - * Parse the given string and returns a SIP.NameAddrHeader instance or undefined if - * it is an invalid NameAddrHeader. - * @param name_addr_header - - */ - function nameAddrHeaderParse(nameAddrHeader) { - var parsedNameAddrHeader = Grammar.parse(nameAddrHeader, "Name_Addr_Header"); - return parsedNameAddrHeader !== -1 ? parsedNameAddrHeader : undefined; - } - Grammar.nameAddrHeaderParse = nameAddrHeaderParse; - /** - * Parse the given string and returns a SIP.URI instance or undefined if - * it is an invalid URI. - * @param uri - - */ - function URIParse(uri) { - var parsedUri = Grammar.parse(uri, "SIP_URI"); - return parsedUri !== -1 ? parsedUri : undefined; - } - Grammar.URIParse = URIParse; -})(Grammar = exports.Grammar || (exports.Grammar = {})); - - -/***/ }), -/* 12 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// tslint:disable:interface-name -// tslint:disable: trailing-comma -// tslint:disable: object-literal-sort-keys -// tslint:disable: max-line-length -// tslint:disable: only-arrow-functions -// tslint:disable: one-variable-per-declaration -// tslint:disable: no-consecutive-blank-lines -// tslint:disable: align -// tslint:disable: radix -// tslint:disable: quotemark -// tslint:disable: semicolon -// tslint:disable: object-literal-shorthand -// tslint:disable: variable-name -// tslint:disable: no-var-keyword -// tslint:disable: whitespace -// tslint:disable: curly -// tslint:disable: prefer-const -// tslint:disable: object-literal-key-quotes -// tslint:disable: no-string-literal -// tslint:disable: one-line -// tslint:disable: no-unused-expression -// tslint:disable: space-before-function-paren -// tslint:disable: arrow-return-shorthand -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -// Generated by PEG.js v. 0.10.0 (ts-pegjs plugin v. 0.2.6 ) -// -// https://pegjs.org/ https://github.com/metadevpro/ts-pegjs -var name_addr_header_1 = __webpack_require__(13); -var uri_1 = __webpack_require__(15); -var SyntaxError = /** @class */ (function (_super) { - tslib_1.__extends(SyntaxError, _super); - function SyntaxError(message, expected, found, location) { - var _this = _super.call(this) || this; - _this.message = message; - _this.expected = expected; - _this.found = found; - _this.location = location; - _this.name = "SyntaxError"; - if (typeof Error.captureStackTrace === "function") { - Error.captureStackTrace(_this, SyntaxError); - } - return _this; - } - SyntaxError.buildMessage = function (expected, found) { - function hex(ch) { - return ch.charCodeAt(0).toString(16).toUpperCase(); - } - function literalEscape(s) { - return s - .replace(/\\/g, "\\\\") - .replace(/"/g, "\\\"") - .replace(/\0/g, "\\0") - .replace(/\t/g, "\\t") - .replace(/\n/g, "\\n") - .replace(/\r/g, "\\r") - .replace(/[\x00-\x0F]/g, function (ch) { return "\\x0" + hex(ch); }) - .replace(/[\x10-\x1F\x7F-\x9F]/g, function (ch) { return "\\x" + hex(ch); }); - } - function classEscape(s) { - return s - .replace(/\\/g, "\\\\") - .replace(/\]/g, "\\]") - .replace(/\^/g, "\\^") - .replace(/-/g, "\\-") - .replace(/\0/g, "\\0") - .replace(/\t/g, "\\t") - .replace(/\n/g, "\\n") - .replace(/\r/g, "\\r") - .replace(/[\x00-\x0F]/g, function (ch) { return "\\x0" + hex(ch); }) - .replace(/[\x10-\x1F\x7F-\x9F]/g, function (ch) { return "\\x" + hex(ch); }); - } - function describeExpectation(expectation) { - switch (expectation.type) { - case "literal": - return "\"" + literalEscape(expectation.text) + "\""; - case "class": - var escapedParts = expectation.parts.map(function (part) { - return Array.isArray(part) - ? classEscape(part[0]) + "-" + classEscape(part[1]) - : classEscape(part); - }); - return "[" + (expectation.inverted ? "^" : "") + escapedParts + "]"; - case "any": - return "any character"; - case "end": - return "end of input"; - case "other": - return expectation.description; - } - } - function describeExpected(expected1) { - var descriptions = expected1.map(describeExpectation); - var i; - var j; - descriptions.sort(); - if (descriptions.length > 0) { - for (i = 1, j = 1; i < descriptions.length; i++) { - if (descriptions[i - 1] !== descriptions[i]) { - descriptions[j] = descriptions[i]; - j++; - } - } - descriptions.length = j; - } - switch (descriptions.length) { - case 1: - return descriptions[0]; - case 2: - return descriptions[0] + " or " + descriptions[1]; - default: - return descriptions.slice(0, -1).join(", ") - + ", or " - + descriptions[descriptions.length - 1]; - } - } - function describeFound(found1) { - return found1 ? "\"" + literalEscape(found1) + "\"" : "end of input"; - } - return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found."; - }; - return SyntaxError; -}(Error)); -exports.SyntaxError = SyntaxError; -function peg$parse(input, options) { - options = options !== undefined ? options : {}; - var peg$FAILED = {}; - var peg$startRuleIndices = { Contact: 119, Name_Addr_Header: 156, Record_Route: 176, Request_Response: 81, SIP_URI: 45, Subscription_State: 186, Supported: 191, Require: 182, Via: 194, absoluteURI: 84, Call_ID: 118, Content_Disposition: 130, Content_Length: 135, Content_Type: 136, CSeq: 146, displayName: 122, Event: 149, From: 151, host: 52, Max_Forwards: 154, Min_SE: 213, Proxy_Authenticate: 157, quoted_string: 40, Refer_To: 178, Replaces: 179, Session_Expires: 210, stun_URI: 217, To: 192, turn_URI: 223, uuid: 226, WWW_Authenticate: 209, challenge: 158, sipfrag: 230, Referred_By: 231 }; - var peg$startRuleIndex = 119; - var peg$consts = [ - "\r\n", - peg$literalExpectation("\r\n", false), - /^[0-9]/, - peg$classExpectation([["0", "9"]], false, false), - /^[a-zA-Z]/, - peg$classExpectation([["a", "z"], ["A", "Z"]], false, false), - /^[0-9a-fA-F]/, - peg$classExpectation([["0", "9"], ["a", "f"], ["A", "F"]], false, false), - /^[\0-\xFF]/, - peg$classExpectation([["\0", "\xFF"]], false, false), - /^["]/, - peg$classExpectation(["\""], false, false), - " ", - peg$literalExpectation(" ", false), - "\t", - peg$literalExpectation("\t", false), - /^[a-zA-Z0-9]/, - peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"]], false, false), - ";", - peg$literalExpectation(";", false), - "/", - peg$literalExpectation("/", false), - "?", - peg$literalExpectation("?", false), - ":", - peg$literalExpectation(":", false), - "@", - peg$literalExpectation("@", false), - "&", - peg$literalExpectation("&", false), - "=", - peg$literalExpectation("=", false), - "+", - peg$literalExpectation("+", false), - "$", - peg$literalExpectation("$", false), - ",", - peg$literalExpectation(",", false), - "-", - peg$literalExpectation("-", false), - "_", - peg$literalExpectation("_", false), - ".", - peg$literalExpectation(".", false), - "!", - peg$literalExpectation("!", false), - "~", - peg$literalExpectation("~", false), - "*", - peg$literalExpectation("*", false), - "'", - peg$literalExpectation("'", false), - "(", - peg$literalExpectation("(", false), - ")", - peg$literalExpectation(")", false), - "%", - peg$literalExpectation("%", false), - function () { return " "; }, - function () { return ':'; }, - /^[!-~]/, - peg$classExpectation([["!", "~"]], false, false), - /^[\x80-\uFFFF]/, - peg$classExpectation([["\x80", "\uFFFF"]], false, false), - /^[\x80-\xBF]/, - peg$classExpectation([["\x80", "\xBF"]], false, false), - /^[a-f]/, - peg$classExpectation([["a", "f"]], false, false), - "`", - peg$literalExpectation("`", false), - "<", - peg$literalExpectation("<", false), - ">", - peg$literalExpectation(">", false), - "\\", - peg$literalExpectation("\\", false), - "[", - peg$literalExpectation("[", false), - "]", - peg$literalExpectation("]", false), - "{", - peg$literalExpectation("{", false), - "}", - peg$literalExpectation("}", false), - function () { return "*"; }, - function () { return "/"; }, - function () { return "="; }, - function () { return "("; }, - function () { return ")"; }, - function () { return ">"; }, - function () { return "<"; }, - function () { return ","; }, - function () { return ";"; }, - function () { return ":"; }, - function () { return "\""; }, - /^[!-']/, - peg$classExpectation([["!", "'"]], false, false), - /^[*-[]/, - peg$classExpectation([["*", "["]], false, false), - /^[\]-~]/, - peg$classExpectation([["]", "~"]], false, false), - function (contents) { - return contents; - }, - /^[#-[]/, - peg$classExpectation([["#", "["]], false, false), - /^[\0-\t]/, - peg$classExpectation([["\0", "\t"]], false, false), - /^[\x0B-\f]/, - peg$classExpectation([["\x0B", "\f"]], false, false), - /^[\x0E-\x7F]/, - peg$classExpectation([["\x0E", "\x7F"]], false, false), - function () { - options = options || { data: {} }; - options.data.uri = new uri_1.URI(options.data.scheme, options.data.user, options.data.host, options.data.port); - delete options.data.scheme; - delete options.data.user; - delete options.data.host; - delete options.data.host_type; - delete options.data.port; - }, - function () { - options = options || { data: {} }; - options.data.uri = new uri_1.URI(options.data.scheme, options.data.user, options.data.host, options.data.port, options.data.uri_params, options.data.uri_headers); - delete options.data.scheme; - delete options.data.user; - delete options.data.host; - delete options.data.host_type; - delete options.data.port; - delete options.data.uri_params; - if (options.startRule === 'SIP_URI') { - options.data = options.data.uri; - } - }, - "sips", - peg$literalExpectation("sips", true), - "sip", - peg$literalExpectation("sip", true), - function (uri_scheme) { - options = options || { data: {} }; - options.data.scheme = uri_scheme; - }, - function () { - options = options || { data: {} }; - options.data.user = decodeURIComponent(text().slice(0, -1)); - }, - function () { - options = options || { data: {} }; - options.data.password = text(); - }, - function () { - options = options || { data: {} }; - options.data.host = text(); - return options.data.host; - }, - function () { - options = options || { data: {} }; - options.data.host_type = 'domain'; - return text(); - }, - /^[a-zA-Z0-9_\-]/, - peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"], "_", "-"], false, false), - /^[a-zA-Z0-9\-]/, - peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"], "-"], false, false), - function () { - options = options || { data: {} }; - options.data.host_type = 'IPv6'; - return text(); - }, - "::", - peg$literalExpectation("::", false), - function () { - options = options || { data: {} }; - options.data.host_type = 'IPv6'; - return text(); - }, - function () { - options = options || { data: {} }; - options.data.host_type = 'IPv4'; - return text(); - }, - "25", - peg$literalExpectation("25", false), - /^[0-5]/, - peg$classExpectation([["0", "5"]], false, false), - "2", - peg$literalExpectation("2", false), - /^[0-4]/, - peg$classExpectation([["0", "4"]], false, false), - "1", - peg$literalExpectation("1", false), - /^[1-9]/, - peg$classExpectation([["1", "9"]], false, false), - function (port) { - options = options || { data: {} }; - port = parseInt(port.join('')); - options.data.port = port; - return port; - }, - "transport=", - peg$literalExpectation("transport=", true), - "udp", - peg$literalExpectation("udp", true), - "tcp", - peg$literalExpectation("tcp", true), - "sctp", - peg$literalExpectation("sctp", true), - "tls", - peg$literalExpectation("tls", true), - function (transport) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['transport'] = transport.toLowerCase(); - }, - "user=", - peg$literalExpectation("user=", true), - "phone", - peg$literalExpectation("phone", true), - "ip", - peg$literalExpectation("ip", true), - function (user) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['user'] = user.toLowerCase(); - }, - "method=", - peg$literalExpectation("method=", true), - function (method) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['method'] = method; - }, - "ttl=", - peg$literalExpectation("ttl=", true), - function (ttl) { - options = options || { data: {} }; - if (!options.data.params) - options.data.params = {}; - options.data.params['ttl'] = ttl; - }, - "maddr=", - peg$literalExpectation("maddr=", true), - function (maddr) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['maddr'] = maddr; - }, - "lr", - peg$literalExpectation("lr", true), - function () { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['lr'] = undefined; - }, - function (param, value) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - if (value === null) { - value = undefined; - } - else { - value = value[1]; - } - options.data.uri_params[param.toLowerCase()] = value; - }, - function (hname, hvalue) { - hname = hname.join('').toLowerCase(); - hvalue = hvalue.join(''); - options = options || { data: {} }; - if (!options.data.uri_headers) - options.data.uri_headers = {}; - if (!options.data.uri_headers[hname]) { - options.data.uri_headers[hname] = [hvalue]; - } - else { - options.data.uri_headers[hname].push(hvalue); - } - }, - function () { - options = options || { data: {} }; - // lots of tests fail if this isn't guarded... - if (options.startRule === 'Refer_To') { - options.data.uri = new uri_1.URI(options.data.scheme, options.data.user, options.data.host, options.data.port, options.data.uri_params, options.data.uri_headers); - delete options.data.scheme; - delete options.data.user; - delete options.data.host; - delete options.data.host_type; - delete options.data.port; - delete options.data.uri_params; - } - }, - "//", - peg$literalExpectation("//", false), - function () { - options = options || { data: {} }; - options.data.scheme = text(); - }, - peg$literalExpectation("SIP", true), - function () { - options = options || { data: {} }; - options.data.sip_version = text(); - }, - "INVITE", - peg$literalExpectation("INVITE", false), - "ACK", - peg$literalExpectation("ACK", false), - "VXACH", - peg$literalExpectation("VXACH", false), - "OPTIONS", - peg$literalExpectation("OPTIONS", false), - "BYE", - peg$literalExpectation("BYE", false), - "CANCEL", - peg$literalExpectation("CANCEL", false), - "REGISTER", - peg$literalExpectation("REGISTER", false), - "SUBSCRIBE", - peg$literalExpectation("SUBSCRIBE", false), - "NOTIFY", - peg$literalExpectation("NOTIFY", false), - "REFER", - peg$literalExpectation("REFER", false), - "PUBLISH", - peg$literalExpectation("PUBLISH", false), - function () { - options = options || { data: {} }; - options.data.method = text(); - return options.data.method; - }, - function (status_code) { - options = options || { data: {} }; - options.data.status_code = parseInt(status_code.join('')); - }, - function () { - options = options || { data: {} }; - options.data.reason_phrase = text(); - }, - function () { - options = options || { data: {} }; - options.data = text(); - }, - function () { - var idx, length; - options = options || { data: {} }; - length = options.data.multi_header.length; - for (idx = 0; idx < length; idx++) { - if (options.data.multi_header[idx].parsed === null) { - options.data = null; - break; - } - } - if (options.data !== null) { - options.data = options.data.multi_header; - } - else { - options.data = -1; - } - }, - function () { - var header; - options = options || { data: {} }; - if (!options.data.multi_header) - options.data.multi_header = []; - try { - header = new name_addr_header_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); - delete options.data.uri; - delete options.data.displayName; - delete options.data.params; - } - catch (e) { - header = null; - } - options.data.multi_header.push({ 'position': peg$currPos, - 'offset': location().start.offset, - 'parsed': header - }); - }, - function (displayName) { - displayName = text().trim(); - if (displayName[0] === '\"') { - displayName = displayName.substring(1, displayName.length - 1); - } - options = options || { data: {} }; - options.data.displayName = displayName; - }, - "q", - peg$literalExpectation("q", true), - function (q) { - options = options || { data: {} }; - if (!options.data.params) - options.data.params = {}; - options.data.params['q'] = q; - }, - "expires", - peg$literalExpectation("expires", true), - function (expires) { - options = options || { data: {} }; - if (!options.data.params) - options.data.params = {}; - options.data.params['expires'] = expires; - }, - function (delta_seconds) { - return parseInt(delta_seconds.join('')); - }, - "0", - peg$literalExpectation("0", false), - function () { - return parseFloat(text()); - }, - function (param, value) { - options = options || { data: {} }; - if (!options.data.params) - options.data.params = {}; - if (value === null) { - value = undefined; - } - else { - value = value[1]; - } - options.data.params[param.toLowerCase()] = value; - }, - "render", - peg$literalExpectation("render", true), - "session", - peg$literalExpectation("session", true), - "icon", - peg$literalExpectation("icon", true), - "alert", - peg$literalExpectation("alert", true), - function () { - options = options || { data: {} }; - if (options.startRule === 'Content_Disposition') { - options.data.type = text().toLowerCase(); - } - }, - "handling", - peg$literalExpectation("handling", true), - "optional", - peg$literalExpectation("optional", true), - "required", - peg$literalExpectation("required", true), - function (length) { - options = options || { data: {} }; - options.data = parseInt(length.join('')); - }, - function () { - options = options || { data: {} }; - options.data = text(); - }, - "text", - peg$literalExpectation("text", true), - "image", - peg$literalExpectation("image", true), - "audio", - peg$literalExpectation("audio", true), - "video", - peg$literalExpectation("video", true), - "application", - peg$literalExpectation("application", true), - "message", - peg$literalExpectation("message", true), - "multipart", - peg$literalExpectation("multipart", true), - "x-", - peg$literalExpectation("x-", true), - function (cseq_value) { - options = options || { data: {} }; - options.data.value = parseInt(cseq_value.join('')); - }, - function (expires) { options = options || { data: {} }; options.data = expires; }, - function (event_type) { - options = options || { data: {} }; - options.data.event = event_type.toLowerCase(); - }, - function () { - options = options || { data: {} }; - var tag = options.data.tag; - options.data = new name_addr_header_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); - if (tag) { - options.data.setParam('tag', tag); - } - }, - "tag", - peg$literalExpectation("tag", true), - function (tag) { options = options || { data: {} }; options.data.tag = tag; }, - function (forwards) { - options = options || { data: {} }; - options.data = parseInt(forwards.join('')); - }, - function (min_expires) { options = options || { data: {} }; options.data = min_expires; }, - function () { - options = options || { data: {} }; - options.data = new name_addr_header_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); - }, - "digest", - peg$literalExpectation("Digest", true), - "realm", - peg$literalExpectation("realm", true), - function (realm) { options = options || { data: {} }; options.data.realm = realm; }, - "domain", - peg$literalExpectation("domain", true), - "nonce", - peg$literalExpectation("nonce", true), - function (nonce) { options = options || { data: {} }; options.data.nonce = nonce; }, - "opaque", - peg$literalExpectation("opaque", true), - function (opaque) { options = options || { data: {} }; options.data.opaque = opaque; }, - "stale", - peg$literalExpectation("stale", true), - "true", - peg$literalExpectation("true", true), - function () { options = options || { data: {} }; options.data.stale = true; }, - "false", - peg$literalExpectation("false", true), - function () { options = options || { data: {} }; options.data.stale = false; }, - "algorithm", - peg$literalExpectation("algorithm", true), - "md5", - peg$literalExpectation("MD5", true), - "md5-sess", - peg$literalExpectation("MD5-sess", true), - function (algorithm) { - options = options || { data: {} }; - options.data.algorithm = algorithm.toUpperCase(); - }, - "qop", - peg$literalExpectation("qop", true), - "auth-int", - peg$literalExpectation("auth-int", true), - "auth", - peg$literalExpectation("auth", true), - function (qop_value) { - options = options || { data: {} }; - options.data.qop || (options.data.qop = []); - options.data.qop.push(qop_value.toLowerCase()); - }, - function (rack_value) { - options = options || { data: {} }; - options.data.value = parseInt(rack_value.join('')); - }, - function () { - var idx, length; - options = options || { data: {} }; - length = options.data.multi_header.length; - for (idx = 0; idx < length; idx++) { - if (options.data.multi_header[idx].parsed === null) { - options.data = null; - break; - } - } - if (options.data !== null) { - options.data = options.data.multi_header; - } - else { - options.data = -1; - } - }, - function () { - var header; - options = options || { data: {} }; - if (!options.data.multi_header) - options.data.multi_header = []; - try { - header = new name_addr_header_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); - delete options.data.uri; - delete options.data.displayName; - delete options.data.params; - } - catch (e) { - header = null; - } - options.data.multi_header.push({ 'position': peg$currPos, - 'offset': location().start.offset, - 'parsed': header - }); - }, - function () { - options = options || { data: {} }; - options.data = new name_addr_header_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); - }, - function () { - options = options || { data: {} }; - if (!(options.data.replaces_from_tag && options.data.replaces_to_tag)) { - options.data = -1; - } - }, - function () { - options = options || { data: {} }; - options.data = { - call_id: options.data - }; - }, - "from-tag", - peg$literalExpectation("from-tag", true), - function (from_tag) { - options = options || { data: {} }; - options.data.replaces_from_tag = from_tag; - }, - "to-tag", - peg$literalExpectation("to-tag", true), - function (to_tag) { - options = options || { data: {} }; - options.data.replaces_to_tag = to_tag; - }, - "early-only", - peg$literalExpectation("early-only", true), - function () { - options = options || { data: {} }; - options.data.early_only = true; - }, - function (head, r) { return r; }, - function (head, tail) { return list(head, tail); }, - function (value) { - options = options || { data: {} }; - if (options.startRule === 'Require') { - options.data = value || []; - } - }, - function (rseq_value) { - options = options || { data: {} }; - options.data.value = parseInt(rseq_value.join('')); - }, - "active", - peg$literalExpectation("active", true), - "pending", - peg$literalExpectation("pending", true), - "terminated", - peg$literalExpectation("terminated", true), - function () { - options = options || { data: {} }; - options.data.state = text(); - }, - "reason", - peg$literalExpectation("reason", true), - function (reason) { - options = options || { data: {} }; - if (typeof reason !== 'undefined') - options.data.reason = reason; - }, - function (expires) { - options = options || { data: {} }; - if (typeof expires !== 'undefined') - options.data.expires = expires; - }, - "retry_after", - peg$literalExpectation("retry_after", true), - function (retry_after) { - options = options || { data: {} }; - if (typeof retry_after !== 'undefined') - options.data.retry_after = retry_after; - }, - "deactivated", - peg$literalExpectation("deactivated", true), - "probation", - peg$literalExpectation("probation", true), - "rejected", - peg$literalExpectation("rejected", true), - "timeout", - peg$literalExpectation("timeout", true), - "giveup", - peg$literalExpectation("giveup", true), - "noresource", - peg$literalExpectation("noresource", true), - "invariant", - peg$literalExpectation("invariant", true), - function (value) { - options = options || { data: {} }; - if (options.startRule === 'Supported') { - options.data = value || []; - } - }, - function () { - options = options || { data: {} }; - var tag = options.data.tag; - options.data = new name_addr_header_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); - if (tag) { - options.data.setParam('tag', tag); - } - }, - "ttl", - peg$literalExpectation("ttl", true), - function (via_ttl_value) { - options = options || { data: {} }; - options.data.ttl = via_ttl_value; - }, - "maddr", - peg$literalExpectation("maddr", true), - function (via_maddr) { - options = options || { data: {} }; - options.data.maddr = via_maddr; - }, - "received", - peg$literalExpectation("received", true), - function (via_received) { - options = options || { data: {} }; - options.data.received = via_received; - }, - "branch", - peg$literalExpectation("branch", true), - function (via_branch) { - options = options || { data: {} }; - options.data.branch = via_branch; - }, - "rport", - peg$literalExpectation("rport", true), - function (response_port) { - options = options || { data: {} }; - if (typeof response_port !== 'undefined') - options.data.rport = response_port.join(''); - }, - function (via_protocol) { - options = options || { data: {} }; - options.data.protocol = via_protocol; - }, - peg$literalExpectation("UDP", true), - peg$literalExpectation("TCP", true), - peg$literalExpectation("TLS", true), - peg$literalExpectation("SCTP", true), - function (via_transport) { - options = options || { data: {} }; - options.data.transport = via_transport; - }, - function () { - options = options || { data: {} }; - options.data.host = text(); - }, - function (via_sent_by_port) { - options = options || { data: {} }; - options.data.port = parseInt(via_sent_by_port.join('')); - }, - function (ttl) { - return parseInt(ttl.join('')); - }, - function (deltaSeconds) { - options = options || { data: {} }; - if (options.startRule === 'Session_Expires') { - options.data.deltaSeconds = deltaSeconds; - } - }, - "refresher", - peg$literalExpectation("refresher", false), - "uas", - peg$literalExpectation("uas", false), - "uac", - peg$literalExpectation("uac", false), - function (endpoint) { - options = options || { data: {} }; - if (options.startRule === 'Session_Expires') { - options.data.refresher = endpoint; - } - }, - function (deltaSeconds) { - options = options || { data: {} }; - if (options.startRule === 'Min_SE') { - options.data = deltaSeconds; - } - }, - "stuns", - peg$literalExpectation("stuns", true), - "stun", - peg$literalExpectation("stun", true), - function (scheme) { - options = options || { data: {} }; - options.data.scheme = scheme; - }, - function (host) { - options = options || { data: {} }; - options.data.host = host; - }, - "?transport=", - peg$literalExpectation("?transport=", false), - "turns", - peg$literalExpectation("turns", true), - "turn", - peg$literalExpectation("turn", true), - function (transport) { - options = options || { data: {} }; - options.data.transport = transport; - }, - function () { - options = options || { data: {} }; - options.data = text(); - }, - "Referred-By", - peg$literalExpectation("Referred-By", false), - "b", - peg$literalExpectation("b", false), - "cid", - peg$literalExpectation("cid", false) - ]; - var peg$bytecode = [ - peg$decode("2 \"\"6 7!"), - peg$decode("4\"\"\"5!7#"), - peg$decode("4$\"\"5!7%"), - peg$decode("4&\"\"5!7'"), - peg$decode(";'.# &;("), - peg$decode("4(\"\"5!7)"), - peg$decode("4*\"\"5!7+"), - peg$decode("2,\"\"6,7-"), - peg$decode("2.\"\"6.7/"), - peg$decode("40\"\"5!71"), - peg$decode("22\"\"6273.\x89 &24\"\"6475.} &26\"\"6677.q &28\"\"6879.e &2:\"\"6:7;.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E"), - peg$decode(";).# &;,"), - peg$decode("2F\"\"6F7G.} &2H\"\"6H7I.q &2J\"\"6J7K.e &2L\"\"6L7M.Y &2N\"\"6N7O.M &2P\"\"6P7Q.A &2R\"\"6R7S.5 &2T\"\"6T7U.) &2V\"\"6V7W"), - peg$decode("%%2X\"\"6X7Y/5#;#/,$;#/#$+#)(#'#(\"'#&'#/\"!&,)"), - peg$decode("%%$;$0#*;$&/,#; /#$+\")(\"'#&'#.\" &\"/=#$;$/�#*;$&&&#/'$8\":Z\" )(\"'#&'#"), - peg$decode(";..\" &\""), - peg$decode("%$;'.# &;(0)*;'.# &;(&/?#28\"\"6879/0$;//'$8#:[# )(#'#(\"'#&'#"), - peg$decode("%%$;2/�#*;2&&&#/g#$%$;.0#*;.&/,#;2/#$+\")(\"'#&'#0=*%$;.0#*;.&/,#;2/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/\"!&,)"), - peg$decode("4\\\"\"5!7].# &;3"), - peg$decode("4^\"\"5!7_"), - peg$decode("4`\"\"5!7a"), - peg$decode(";!.) &4b\"\"5!7c"), - peg$decode("%$;).\x95 &2F\"\"6F7G.\x89 &2J\"\"6J7K.} &2L\"\"6L7M.q &2X\"\"6X7Y.e &2P\"\"6P7Q.Y &2H\"\"6H7I.M &2@\"\"6@7A.A &2d\"\"6d7e.5 &2R\"\"6R7S.) &2N\"\"6N7O/\x9E#0\x9B*;).\x95 &2F\"\"6F7G.\x89 &2J\"\"6J7K.} &2L\"\"6L7M.q &2X\"\"6X7Y.e &2P\"\"6P7Q.Y &2H\"\"6H7I.M &2@\"\"6@7A.A &2d\"\"6d7e.5 &2R\"\"6R7S.) &2N\"\"6N7O&&&#/\"!&,)"), - peg$decode("%$;).\x89 &2F\"\"6F7G.} &2L\"\"6L7M.q &2X\"\"6X7Y.e &2P\"\"6P7Q.Y &2H\"\"6H7I.M &2@\"\"6@7A.A &2d\"\"6d7e.5 &2R\"\"6R7S.) &2N\"\"6N7O/\x92#0\x8F*;).\x89 &2F\"\"6F7G.} &2L\"\"6L7M.q &2X\"\"6X7Y.e &2P\"\"6P7Q.Y &2H\"\"6H7I.M &2@\"\"6@7A.A &2d\"\"6d7e.5 &2R\"\"6R7S.) &2N\"\"6N7O&&&#/\"!&,)"), - peg$decode("2T\"\"6T7U.\xE3 &2V\"\"6V7W.\xD7 &2f\"\"6f7g.\xCB &2h\"\"6h7i.\xBF &2:\"\"6:7;.\xB3 &2D\"\"6D7E.\xA7 &22\"\"6273.\x9B &28\"\"6879.\x8F &2j\"\"6j7k.\x83 &;&.} &24\"\"6475.q &2l\"\"6l7m.e &2n\"\"6n7o.Y &26\"\"6677.M &2>\"\"6>7?.A &2p\"\"6p7q.5 &2r\"\"6r7s.) &;'.# &;("), - peg$decode("%$;).\u012B &2F\"\"6F7G.\u011F &2J\"\"6J7K.\u0113 &2L\"\"6L7M.\u0107 &2X\"\"6X7Y.\xFB &2P\"\"6P7Q.\xEF &2H\"\"6H7I.\xE3 &2@\"\"6@7A.\xD7 &2d\"\"6d7e.\xCB &2R\"\"6R7S.\xBF &2N\"\"6N7O.\xB3 &2T\"\"6T7U.\xA7 &2V\"\"6V7W.\x9B &2f\"\"6f7g.\x8F &2h\"\"6h7i.\x83 &28\"\"6879.w &2j\"\"6j7k.k &;&.e &24\"\"6475.Y &2l\"\"6l7m.M &2n\"\"6n7o.A &26\"\"6677.5 &2p\"\"6p7q.) &2r\"\"6r7s/\u0134#0\u0131*;).\u012B &2F\"\"6F7G.\u011F &2J\"\"6J7K.\u0113 &2L\"\"6L7M.\u0107 &2X\"\"6X7Y.\xFB &2P\"\"6P7Q.\xEF &2H\"\"6H7I.\xE3 &2@\"\"6@7A.\xD7 &2d\"\"6d7e.\xCB &2R\"\"6R7S.\xBF &2N\"\"6N7O.\xB3 &2T\"\"6T7U.\xA7 &2V\"\"6V7W.\x9B &2f\"\"6f7g.\x8F &2h\"\"6h7i.\x83 &28\"\"6879.w &2j\"\"6j7k.k &;&.e &24\"\"6475.Y &2l\"\"6l7m.M &2n\"\"6n7o.A &26\"\"6677.5 &2p\"\"6p7q.) &2r\"\"6r7s&&&#/\"!&,)"), - peg$decode("%;//?#2P\"\"6P7Q/0$;//'$8#:t# )(#'#(\"'#&'#"), - peg$decode("%;//?#24\"\"6475/0$;//'$8#:u# )(#'#(\"'#&'#"), - peg$decode("%;//?#2>\"\"6>7?/0$;//'$8#:v# )(#'#(\"'#&'#"), - peg$decode("%;//?#2T\"\"6T7U/0$;//'$8#:w# )(#'#(\"'#&'#"), - peg$decode("%;//?#2V\"\"6V7W/0$;//'$8#:x# )(#'#(\"'#&'#"), - peg$decode("%2h\"\"6h7i/0#;//'$8\":y\" )(\"'#&'#"), - peg$decode("%;//6#2f\"\"6f7g/'$8\":z\" )(\"'#&'#"), - peg$decode("%;//?#2D\"\"6D7E/0$;//'$8#:{# )(#'#(\"'#&'#"), - peg$decode("%;//?#22\"\"6273/0$;//'$8#:|# )(#'#(\"'#&'#"), - peg$decode("%;//?#28\"\"6879/0$;//'$8#:}# )(#'#(\"'#&'#"), - peg$decode("%;//0#;&/'$8\":~\" )(\"'#&'#"), - peg$decode("%;&/0#;//'$8\":~\" )(\"'#&'#"), - peg$decode("%;=/T#$;G.) &;K.# &;F0/*;G.) &;K.# &;F&/,$;>/#$+#)(#'#(\"'#&'#"), - peg$decode("4\x7F\"\"5!7\x80.A &4\x81\"\"5!7\x82.5 &4\x83\"\"5!7\x84.) &;3.# &;."), - peg$decode("%%;//Q#;&/H$$;J.# &;K0)*;J.# &;K&/,$;&/#$+$)($'#(#'#(\"'#&'#/\"!&,)"), - peg$decode("%;//]#;&/T$%$;J.# &;K0)*;J.# &;K&/\"!&,)/1$;&/($8$:\x85$!!)($'#(#'#(\"'#&'#"), - peg$decode(";..G &2L\"\"6L7M.; &4\x86\"\"5!7\x87./ &4\x83\"\"5!7\x84.# &;3"), - peg$decode("%2j\"\"6j7k/J#4\x88\"\"5!7\x89.5 &4\x8A\"\"5!7\x8B.) &4\x8C\"\"5!7\x8D/#$+\")(\"'#&'#"), - peg$decode("%;N/M#28\"\"6879/>$;O.\" &\"/0$;S/'$8$:\x8E$ )($'#(#'#(\"'#&'#"), - peg$decode("%;N/d#28\"\"6879/U$;O.\" &\"/G$;S/>$;_/5$;l.\" &\"/'$8&:\x8F& )(&'#(%'#($'#(#'#(\"'#&'#"), - peg$decode("%3\x90\"\"5$7\x91.) &3\x92\"\"5#7\x93/' 8!:\x94!! )"), - peg$decode("%;P/]#%28\"\"6879/,#;R/#$+\")(\"'#&'#.\" &\"/6$2:\"\"6:7;/'$8#:\x95# )(#'#(\"'#&'#"), - peg$decode("$;+.) &;-.# &;Q/2#0/*;+.) &;-.# &;Q&&&#"), - peg$decode("2<\"\"6<7=.q &2>\"\"6>7?.e &2@\"\"6@7A.Y &2B\"\"6B7C.M &2D\"\"6D7E.A &22\"\"6273.5 &26\"\"6677.) &24\"\"6475"), - peg$decode("%$;+._ &;-.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E0e*;+._ &;-.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E&/& 8!:\x96! )"), - peg$decode("%;T/J#%28\"\"6879/,#;^/#$+\")(\"'#&'#.\" &\"/#$+\")(\"'#&'#"), - peg$decode("%;U.) &;\\.# &;X/& 8!:\x97! )"), - peg$decode("%$%;V/2#2J\"\"6J7K/#$+\")(\"'#&'#0<*%;V/2#2J\"\"6J7K/#$+\")(\"'#&'#&/D#;W/;$2J\"\"6J7K.\" &\"/'$8#:\x98# )(#'#(\"'#&'#"), - peg$decode("$4\x99\"\"5!7\x9A/,#0)*4\x99\"\"5!7\x9A&&&#"), - peg$decode("%4$\"\"5!7%/?#$4\x9B\"\"5!7\x9C0)*4\x9B\"\"5!7\x9C&/#$+\")(\"'#&'#"), - peg$decode("%2l\"\"6l7m/?#;Y/6$2n\"\"6n7o/'$8#:\x9D# )(#'#(\"'#&'#"), - peg$decode("%%;Z/\xB3#28\"\"6879/\xA4$;Z/\x9B$28\"\"6879/\x8C$;Z/\x83$28\"\"6879/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+-)(-'#(,'#(+'#(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0790 &%2\x9E\"\"6\x9E7\x9F/\xA4#;Z/\x9B$28\"\"6879/\x8C$;Z/\x83$28\"\"6879/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+,)(,'#(+'#(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u06F9 &%2\x9E\"\"6\x9E7\x9F/\x8C#;Z/\x83$28\"\"6879/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+*)(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u067A &%2\x9E\"\"6\x9E7\x9F/t#;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+()(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0613 &%2\x9E\"\"6\x9E7\x9F/\\#;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+&)(&'#(%'#($'#(#'#(\"'#&'#.\u05C4 &%2\x9E\"\"6\x9E7\x9F/D#;Z/;$28\"\"6879/,$;[/#$+$)($'#(#'#(\"'#&'#.\u058D &%2\x9E\"\"6\x9E7\x9F/,#;[/#$+\")(\"'#&'#.\u056E &%2\x9E\"\"6\x9E7\x9F/,#;Z/#$+\")(\"'#&'#.\u054F &%;Z/\x9B#2\x9E\"\"6\x9E7\x9F/\x8C$;Z/\x83$28\"\"6879/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$++)(+'#(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u04C7 &%;Z/\xAA#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x83$2\x9E\"\"6\x9E7\x9F/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+*)(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0430 &%;Z/\xB9#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x92$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/k$2\x9E\"\"6\x9E7\x9F/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+))()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u038A &%;Z/\xC8#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xA1$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/z$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/S$2\x9E\"\"6\x9E7\x9F/D$;Z/;$28\"\"6879/,$;[/#$+()(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u02D5 &%;Z/\xD7#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xB0$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x89$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/b$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/;$2\x9E\"\"6\x9E7\x9F/,$;[/#$+')(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0211 &%;Z/\xFE#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xD7$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xB0$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x89$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/b$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/;$2\x9E\"\"6\x9E7\x9F/,$;Z/#$+()(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0126 &%;Z/\u011C#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xF5$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xCE$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xA7$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x80$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/Y$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/2$2\x9E\"\"6\x9E7\x9F/#$+()(('#(''#(&'#(%'#($'#(#'#(\"'#&'#/& 8!:\xA0! )"), - peg$decode("%;#/M#;#.\" &\"/?$;#.\" &\"/1$;#.\" &\"/#$+$)($'#(#'#(\"'#&'#"), - peg$decode("%;Z/;#28\"\"6879/,$;Z/#$+#)(#'#(\"'#&'#.# &;\\"), - peg$decode("%;]/o#2J\"\"6J7K/`$;]/W$2J\"\"6J7K/H$;]/?$2J\"\"6J7K/0$;]/'$8':\xA1' )(''#(&'#(%'#($'#(#'#(\"'#&'#"), - peg$decode("%2\xA2\"\"6\xA27\xA3/2#4\xA4\"\"5!7\xA5/#$+\")(\"'#&'#.\x98 &%2\xA6\"\"6\xA67\xA7/;#4\xA8\"\"5!7\xA9/,$;!/#$+#)(#'#(\"'#&'#.j &%2\xAA\"\"6\xAA7\xAB/5#;!/,$;!/#$+#)(#'#(\"'#&'#.B &%4\xAC\"\"5!7\xAD/,#;!/#$+\")(\"'#&'#.# &;!"), - peg$decode("%%;!.\" &\"/[#;!.\" &\"/M$;!.\" &\"/?$;!.\" &\"/1$;!.\" &\"/#$+%)(%'#($'#(#'#(\"'#&'#/' 8!:\xAE!! )"), - peg$decode("$%22\"\"6273/,#;`/#$+\")(\"'#&'#0<*%22\"\"6273/,#;`/#$+\")(\"'#&'#&"), - peg$decode(";a.A &;b.; &;c.5 &;d./ &;e.) &;f.# &;g"), - peg$decode("%3\xAF\"\"5*7\xB0/a#3\xB1\"\"5#7\xB2.G &3\xB3\"\"5#7\xB4.; &3\xB5\"\"5$7\xB6./ &3\xB7\"\"5#7\xB8.# &;6/($8\":\xB9\"! )(\"'#&'#"), - peg$decode("%3\xBA\"\"5%7\xBB/I#3\xBC\"\"5%7\xBD./ &3\xBE\"\"5\"7\xBF.# &;6/($8\":\xC0\"! )(\"'#&'#"), - peg$decode("%3\xC1\"\"5'7\xC2/1#;\x90/($8\":\xC3\"! )(\"'#&'#"), - peg$decode("%3\xC4\"\"5$7\xC5/1#;\xF0/($8\":\xC6\"! )(\"'#&'#"), - peg$decode("%3\xC7\"\"5&7\xC8/1#;T/($8\":\xC9\"! )(\"'#&'#"), - peg$decode("%3\xCA\"\"5\"7\xCB/N#%2>\"\"6>7?/,#;6/#$+\")(\"'#&'#.\" &\"/'$8\":\xCC\" )(\"'#&'#"), - peg$decode("%;h/P#%2>\"\"6>7?/,#;i/#$+\")(\"'#&'#.\" &\"/)$8\":\xCD\"\"! )(\"'#&'#"), - peg$decode("%$;j/�#*;j&&&#/\"!&,)"), - peg$decode("%$;j/�#*;j&&&#/\"!&,)"), - peg$decode(";k.) &;+.# &;-"), - peg$decode("2l\"\"6l7m.e &2n\"\"6n7o.Y &24\"\"6475.M &28\"\"6879.A &2<\"\"6<7=.5 &2@\"\"6@7A.) &2B\"\"6B7C"), - peg$decode("%26\"\"6677/n#;m/e$$%2<\"\"6<7=/,#;m/#$+\")(\"'#&'#0<*%2<\"\"6<7=/,#;m/#$+\")(\"'#&'#&/#$+#)(#'#(\"'#&'#"), - peg$decode("%;n/A#2>\"\"6>7?/2$;o/)$8#:\xCE#\"\" )(#'#(\"'#&'#"), - peg$decode("$;p.) &;+.# &;-/2#0/*;p.) &;+.# &;-&&&#"), - peg$decode("$;p.) &;+.# &;-0/*;p.) &;+.# &;-&"), - peg$decode("2l\"\"6l7m.e &2n\"\"6n7o.Y &24\"\"6475.M &26\"\"6677.A &28\"\"6879.5 &2@\"\"6@7A.) &2B\"\"6B7C"), - peg$decode(";\x91.# &;r"), - peg$decode("%;\x90/G#;'/>$;s/5$;'/,$;\x84/#$+%)(%'#($'#(#'#(\"'#&'#"), - peg$decode(";M.# &;t"), - peg$decode("%;\x7F/E#28\"\"6879/6$;u.# &;x/'$8#:\xCF# )(#'#(\"'#&'#"), - peg$decode("%;v.# &;w/J#%26\"\"6677/,#;\x83/#$+\")(\"'#&'#.\" &\"/#$+\")(\"'#&'#"), - peg$decode("%2\xD0\"\"6\xD07\xD1/:#;\x80/1$;w.\" &\"/#$+#)(#'#(\"'#&'#"), - peg$decode("%24\"\"6475/,#;{/#$+\")(\"'#&'#"), - peg$decode("%;z/3#$;y0#*;y&/#$+\")(\"'#&'#"), - peg$decode(";*.) &;+.# &;-"), - peg$decode(";+.\x8F &;-.\x89 &22\"\"6273.} &26\"\"6677.q &28\"\"6879.e &2:\"\"6:7;.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E"), - peg$decode("%;|/e#$%24\"\"6475/,#;|/#$+\")(\"'#&'#0<*%24\"\"6475/,#;|/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"), - peg$decode("%$;~0#*;~&/e#$%22\"\"6273/,#;}/#$+\")(\"'#&'#0<*%22\"\"6273/,#;}/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"), - peg$decode("$;~0#*;~&"), - peg$decode(";+.w &;-.q &28\"\"6879.e &2:\"\"6:7;.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E"), - peg$decode("%%;\"/\x87#$;\".G &;!.A &2@\"\"6@7A.5 &2F\"\"6F7G.) &2J\"\"6J7K0M*;\".G &;!.A &2@\"\"6@7A.5 &2F\"\"6F7G.) &2J\"\"6J7K&/#$+\")(\"'#&'#/& 8!:\xD2! )"), - peg$decode(";\x81.# &;\x82"), - peg$decode("%%;O/2#2:\"\"6:7;/#$+\")(\"'#&'#.\" &\"/,#;S/#$+\")(\"'#&'#.\" &\""), - peg$decode("$;+.\x83 &;-.} &2B\"\"6B7C.q &2D\"\"6D7E.e &22\"\"6273.Y &28\"\"6879.M &2:\"\"6:7;.A &2<\"\"6<7=.5 &2>\"\"6>7?.) &2@\"\"6@7A/\x8C#0\x89*;+.\x83 &;-.} &2B\"\"6B7C.q &2D\"\"6D7E.e &22\"\"6273.Y &28\"\"6879.M &2:\"\"6:7;.A &2<\"\"6<7=.5 &2>\"\"6>7?.) &2@\"\"6@7A&&&#"), - peg$decode("$;y0#*;y&"), - peg$decode("%3\x92\"\"5#7\xD3/q#24\"\"6475/b$$;!/�#*;!&&&#/L$2J\"\"6J7K/=$$;!/�#*;!&&&#/'$8%:\xD4% )(%'#($'#(#'#(\"'#&'#"), - peg$decode("2\xD5\"\"6\xD57\xD6"), - peg$decode("2\xD7\"\"6\xD77\xD8"), - peg$decode("2\xD9\"\"6\xD97\xDA"), - peg$decode("2\xDB\"\"6\xDB7\xDC"), - peg$decode("2\xDD\"\"6\xDD7\xDE"), - peg$decode("2\xDF\"\"6\xDF7\xE0"), - peg$decode("2\xE1\"\"6\xE17\xE2"), - peg$decode("2\xE3\"\"6\xE37\xE4"), - peg$decode("2\xE5\"\"6\xE57\xE6"), - peg$decode("2\xE7\"\"6\xE77\xE8"), - peg$decode("2\xE9\"\"6\xE97\xEA"), - peg$decode("%;\x85.Y &;\x86.S &;\x88.M &;\x89.G &;\x8A.A &;\x8B.; &;\x8C.5 &;\x8F./ &;\x8D.) &;\x8E.# &;6/& 8!:\xEB! )"), - peg$decode("%;\x84/G#;'/>$;\x92/5$;'/,$;\x94/#$+%)(%'#($'#(#'#(\"'#&'#"), - peg$decode("%;\x93/' 8!:\xEC!! )"), - peg$decode("%;!/5#;!/,$;!/#$+#)(#'#(\"'#&'#"), - peg$decode("%$;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(0G*;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(&/& 8!:\xED! )"), - peg$decode("%;\xB6/Y#$%;A/,#;\xB6/#$+\")(\"'#&'#06*%;A/,#;\xB6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"), - peg$decode("%;9/N#%2:\"\"6:7;/,#;9/#$+\")(\"'#&'#.\" &\"/'$8\":\xEE\" )(\"'#&'#"), - peg$decode("%;:.c &%;\x98/Y#$%;A/,#;\x98/#$+\")(\"'#&'#06*%;A/,#;\x98/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/& 8!:\xEF! )"), - peg$decode("%;L.# &;\x99/]#$%;B/,#;\x9B/#$+\")(\"'#&'#06*%;B/,#;\x9B/#$+\")(\"'#&'#&/'$8\":\xF0\" )(\"'#&'#"), - peg$decode("%;\x9A.\" &\"/>#;@/5$;M/,$;?/#$+$)($'#(#'#(\"'#&'#"), - peg$decode("%%;6/Y#$%;./,#;6/#$+\")(\"'#&'#06*%;./,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#.# &;H/' 8!:\xF1!! )"), - peg$decode(";\x9C.) &;\x9D.# &;\xA0"), - peg$decode("%3\xF2\"\"5!7\xF3/:#;$;\xCF/5$;./,$;\x90/#$+%)(%'#($'#(#'#(\"'#&'#"), - peg$decode("%$;!/�#*;!&&&#/' 8!:\u014B!! )"), - peg$decode("%;\xD1/]#$%;A/,#;\xD1/#$+\")(\"'#&'#06*%;A/,#;\xD1/#$+\")(\"'#&'#&/'$8\":\u014C\" )(\"'#&'#"), - peg$decode("%;\x99/]#$%;B/,#;\xA0/#$+\")(\"'#&'#06*%;B/,#;\xA0/#$+\")(\"'#&'#&/'$8\":\u014D\" )(\"'#&'#"), - peg$decode("%;L.O &;\x99.I &%;@.\" &\"/:#;t/1$;?.\" &\"/#$+#)(#'#(\"'#&'#/]#$%;B/,#;\xA0/#$+\")(\"'#&'#06*%;B/,#;\xA0/#$+\")(\"'#&'#&/'$8\":\u014E\" )(\"'#&'#"), - peg$decode("%;\xD4/]#$%;B/,#;\xD5/#$+\")(\"'#&'#06*%;B/,#;\xD5/#$+\")(\"'#&'#&/'$8\":\u014F\" )(\"'#&'#"), - peg$decode("%;\x96/& 8!:\u0150! )"), - peg$decode("%3\u0151\"\"5(7\u0152/:#;$;6/5$;;/,$;\xEC/#$+%)(%'#($'#(#'#(\"'#&'#"), - peg$decode("%3\x92\"\"5#7\xD3.# &;6/' 8!:\u018B!! )"), - peg$decode("%3\xB1\"\"5#7\u018C.G &3\xB3\"\"5#7\u018D.; &3\xB7\"\"5#7\u018E./ &3\xB5\"\"5$7\u018F.# &;6/' 8!:\u0190!! )"), - peg$decode("%;\xEE/D#%;C/,#;\xEF/#$+\")(\"'#&'#.\" &\"/#$+\")(\"'#&'#"), - peg$decode("%;U.) &;\\.# &;X/& 8!:\u0191! )"), - peg$decode("%%;!.\" &\"/[#;!.\" &\"/M$;!.\" &\"/?$;!.\" &\"/1$;!.\" &\"/#$+%)(%'#($'#(#'#(\"'#&'#/' 8!:\u0192!! )"), - peg$decode("%%;!/?#;!.\" &\"/1$;!.\" &\"/#$+#)(#'#(\"'#&'#/' 8!:\u0193!! )"), - peg$decode(";\xBE"), - peg$decode("%;\x9E/^#$%;B/,#;\xF3/#$+\")(\"'#&'#06*%;B/,#;\xF3/#$+\")(\"'#&'#&/($8\":\u0194\"!!)(\"'#&'#"), - peg$decode(";\xF4.# &;\xA0"), - peg$decode("%2\u0195\"\"6\u01957\u0196/L#;\"\"6>7?"), - peg$decode("%;\u0100/b#28\"\"6879/S$;\xFB/J$%2\u01A3\"\"6\u01A37\u01A4/,#;\xEC/#$+\")(\"'#&'#.\" &\"/#$+$)($'#(#'#(\"'#&'#"), - peg$decode("%3\u01A5\"\"5%7\u01A6.) &3\u01A7\"\"5$7\u01A8/' 8!:\u01A1!! )"), - peg$decode("%3\xB1\"\"5#7\xB2.6 &3\xB3\"\"5#7\xB4.* &$;+0#*;+&/' 8!:\u01A9!! )"), - peg$decode("%;\u0104/\x87#2F\"\"6F7G/x$;\u0103/o$2F\"\"6F7G/`$;\u0103/W$2F\"\"6F7G/H$;\u0103/?$2F\"\"6F7G/0$;\u0105/'$8):\u01AA) )()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#"), - peg$decode("%;#/>#;#/5$;#/,$;#/#$+$)($'#(#'#(\"'#&'#"), - peg$decode("%;\u0103/,#;\u0103/#$+\")(\"'#&'#"), - peg$decode("%;\u0103/5#;\u0103/,$;\u0103/#$+#)(#'#(\"'#&'#"), - peg$decode("%;q/T#$;m0#*;m&/D$%; /,#;\xF8/#$+\")(\"'#&'#.\" &\"/#$+#)(#'#(\"'#&'#"), - peg$decode("%2\u01AB\"\"6\u01AB7\u01AC.) &2\u01AD\"\"6\u01AD7\u01AE/w#;0/n$;\u0108/e$$%;B/2#;\u0109.# &;\xA0/#$+\")(\"'#&'#0<*%;B/2#;\u0109.# &;\xA0/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"), - peg$decode(";\x99.# &;L"), - peg$decode("%2\u01AF\"\"6\u01AF7\u01B0/5#; peg$maxFailPos) { - peg$maxFailPos = peg$currPos; - peg$maxFailExpected = []; - } - peg$maxFailExpected.push(expected1); - } - function peg$buildSimpleError(message, location1) { - return new SyntaxError(message, [], "", location1); - } - function peg$buildStructuredError(expected1, found, location1) { - return new SyntaxError(SyntaxError.buildMessage(expected1, found), expected1, found, location1); - } - function peg$decode(s) { - return s.split("").map(function (ch) { return ch.charCodeAt(0) - 32; }); - } - function peg$parseRule(index) { - var bc = peg$bytecode[index]; - var ip = 0; - var ips = []; - var end = bc.length; - var ends = []; - var stack = []; - var params; - while (true) { - while (ip < end) { - switch (bc[ip]) { - case 0: - stack.push(peg$consts[bc[ip + 1]]); - ip += 2; - break; - case 1: - stack.push(undefined); - ip++; - break; - case 2: - stack.push(null); - ip++; - break; - case 3: - stack.push(peg$FAILED); - ip++; - break; - case 4: - stack.push([]); - ip++; - break; - case 5: - stack.push(peg$currPos); - ip++; - break; - case 6: - stack.pop(); - ip++; - break; - case 7: - peg$currPos = stack.pop(); - ip++; - break; - case 8: - stack.length -= bc[ip + 1]; - ip += 2; - break; - case 9: - stack.splice(-2, 1); - ip++; - break; - case 10: - stack[stack.length - 2].push(stack.pop()); - ip++; - break; - case 11: - stack.push(stack.splice(stack.length - bc[ip + 1], bc[ip + 1])); - ip += 2; - break; - case 12: - stack.push(input.substring(stack.pop(), peg$currPos)); - ip++; - break; - case 13: - ends.push(end); - ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); - if (stack[stack.length - 1]) { - end = ip + 3 + bc[ip + 1]; - ip += 3; - } - else { - end = ip + 3 + bc[ip + 1] + bc[ip + 2]; - ip += 3 + bc[ip + 1]; - } - break; - case 14: - ends.push(end); - ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); - if (stack[stack.length - 1] === peg$FAILED) { - end = ip + 3 + bc[ip + 1]; - ip += 3; - } - else { - end = ip + 3 + bc[ip + 1] + bc[ip + 2]; - ip += 3 + bc[ip + 1]; - } - break; - case 15: - ends.push(end); - ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); - if (stack[stack.length - 1] !== peg$FAILED) { - end = ip + 3 + bc[ip + 1]; - ip += 3; - } - else { - end = ip + 3 + bc[ip + 1] + bc[ip + 2]; - ip += 3 + bc[ip + 1]; - } - break; - case 16: - if (stack[stack.length - 1] !== peg$FAILED) { - ends.push(end); - ips.push(ip); - end = ip + 2 + bc[ip + 1]; - ip += 2; - } - else { - ip += 2 + bc[ip + 1]; - } - break; - case 17: - ends.push(end); - ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); - if (input.length > peg$currPos) { - end = ip + 3 + bc[ip + 1]; - ip += 3; - } - else { - end = ip + 3 + bc[ip + 1] + bc[ip + 2]; - ip += 3 + bc[ip + 1]; - } - break; - case 18: - ends.push(end); - ips.push(ip + 4 + bc[ip + 2] + bc[ip + 3]); - if (input.substr(peg$currPos, peg$consts[bc[ip + 1]].length) === peg$consts[bc[ip + 1]]) { - end = ip + 4 + bc[ip + 2]; - ip += 4; - } - else { - end = ip + 4 + bc[ip + 2] + bc[ip + 3]; - ip += 4 + bc[ip + 2]; - } - break; - case 19: - ends.push(end); - ips.push(ip + 4 + bc[ip + 2] + bc[ip + 3]); - if (input.substr(peg$currPos, peg$consts[bc[ip + 1]].length).toLowerCase() === peg$consts[bc[ip + 1]]) { - end = ip + 4 + bc[ip + 2]; - ip += 4; - } - else { - end = ip + 4 + bc[ip + 2] + bc[ip + 3]; - ip += 4 + bc[ip + 2]; - } - break; - case 20: - ends.push(end); - ips.push(ip + 4 + bc[ip + 2] + bc[ip + 3]); - if (peg$consts[bc[ip + 1]].test(input.charAt(peg$currPos))) { - end = ip + 4 + bc[ip + 2]; - ip += 4; - } - else { - end = ip + 4 + bc[ip + 2] + bc[ip + 3]; - ip += 4 + bc[ip + 2]; - } - break; - case 21: - stack.push(input.substr(peg$currPos, bc[ip + 1])); - peg$currPos += bc[ip + 1]; - ip += 2; - break; - case 22: - stack.push(peg$consts[bc[ip + 1]]); - peg$currPos += peg$consts[bc[ip + 1]].length; - ip += 2; - break; - case 23: - stack.push(peg$FAILED); - if (peg$silentFails === 0) { - peg$fail(peg$consts[bc[ip + 1]]); - } - ip += 2; - break; - case 24: - peg$savedPos = stack[stack.length - 1 - bc[ip + 1]]; - ip += 2; - break; - case 25: - peg$savedPos = peg$currPos; - ip++; - break; - case 26: - params = bc.slice(ip + 4, ip + 4 + bc[ip + 3]) - .map(function (p) { return stack[stack.length - 1 - p]; }); - stack.splice(stack.length - bc[ip + 2], bc[ip + 2], peg$consts[bc[ip + 1]].apply(null, params)); - ip += 4 + bc[ip + 3]; - break; - case 27: - stack.push(peg$parseRule(bc[ip + 1])); - ip += 2; - break; - case 28: - peg$silentFails++; - ip++; - break; - case 29: - peg$silentFails--; - ip++; - break; - default: - throw new Error("Invalid opcode: " + bc[ip] + "."); - } - } - if (ends.length > 0) { - end = ends.pop(); - ip = ips.pop(); - } - else { - break; - } - } - return stack[0]; - } - options.data = {}; // Object to which header attributes will be assigned during parsing - function list(head, tail) { - return [head].concat(tail); - } - peg$result = peg$parseRule(peg$startRuleIndex); - if (peg$result !== peg$FAILED && peg$currPos === input.length) { - return peg$result; - } - else { - if (peg$result !== peg$FAILED && peg$currPos < input.length) { - peg$fail(peg$endExpectation()); - } - throw peg$buildStructuredError(peg$maxFailExpected, peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, peg$maxFailPos < input.length - ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) - : peg$computeLocation(peg$maxFailPos, peg$maxFailPos)); - } -} -exports.parse = peg$parse; - - -/***/ }), -/* 13 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var parameters_1 = __webpack_require__(14); -/** - * Name Address SIP header. - * @public - */ -var NameAddrHeader = /** @class */ (function (_super) { - tslib_1.__extends(NameAddrHeader, _super); - /** - * Constructor - * @param uri - - * @param displayName - - * @param parameters - - */ - function NameAddrHeader(uri, displayName, parameters) { - var _this = _super.call(this, parameters) || this; - _this.uri = uri; - _this._displayName = displayName; - return _this; - } - Object.defineProperty(NameAddrHeader.prototype, "friendlyName", { - get: function () { - return this.displayName || this.uri.aor; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(NameAddrHeader.prototype, "displayName", { - get: function () { return this._displayName; }, - set: function (value) { - this._displayName = value; - }, - enumerable: true, - configurable: true - }); - NameAddrHeader.prototype.clone = function () { - return new NameAddrHeader(this.uri.clone(), this._displayName, JSON.parse(JSON.stringify(this.parameters))); - }; - NameAddrHeader.prototype.toString = function () { - var body = (this.displayName || this.displayName === "0") ? '"' + this.displayName + '" ' : ""; - body += "<" + this.uri.toString() + ">"; - for (var parameter in this.parameters) { - if (this.parameters.hasOwnProperty(parameter)) { - body += ";" + parameter; - if (this.parameters[parameter] !== null) { - body += "=" + this.parameters[parameter]; - } - } - } - return body; - }; - return NameAddrHeader; -}(parameters_1.Parameters)); -exports.NameAddrHeader = NameAddrHeader; - - -/***/ }), -/* 14 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * @internal - */ -var Parameters = /** @class */ (function () { - function Parameters(parameters) { - this.parameters = {}; - for (var param in parameters) { - if (parameters.hasOwnProperty(param)) { - this.setParam(param, parameters[param]); - } - } - } - Parameters.prototype.setParam = function (key, value) { - if (key) { - this.parameters[key.toLowerCase()] = (typeof value === "undefined" || value === null) ? null : value.toString(); - } - }; - Parameters.prototype.getParam = function (key) { - if (key) { - return this.parameters[key.toLowerCase()]; - } - }; - Parameters.prototype.hasParam = function (key) { - if (key) { - return !!this.parameters.hasOwnProperty(key.toLowerCase()); - } - return false; - }; - Parameters.prototype.deleteParam = function (parameter) { - parameter = parameter.toLowerCase(); - if (this.parameters.hasOwnProperty(parameter)) { - var value = this.parameters[parameter]; - delete this.parameters[parameter]; - return value; - } - }; - Parameters.prototype.clearParams = function () { - this.parameters = {}; - }; - return Parameters; -}()); -exports.Parameters = Parameters; - - -/***/ }), -/* 15 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var parameters_1 = __webpack_require__(14); -/** - * URI. - * @public - */ -var URI = /** @class */ (function (_super) { - tslib_1.__extends(URI, _super); - /** - * Constructor - * @param scheme - - * @param user - - * @param host - - * @param port - - * @param parameters - - * @param headers - - */ - function URI(scheme, user, host, port, parameters, headers) { - var _this = _super.call(this, parameters) || this; - _this.headers = {}; - // Checks - if (!host) { - throw new TypeError('missing or invalid "host" parameter'); - } - // Initialize parameters - scheme = scheme || "sip"; - for (var header in headers) { - if (headers.hasOwnProperty(header)) { - _this.setHeader(header, headers[header]); - } - } - // Raw URI - _this.raw = { - scheme: scheme, - user: user, - host: host, - port: port - }; - // Normalized URI - _this.normal = { - scheme: scheme.toLowerCase(), - user: user, - host: host.toLowerCase(), - port: port - }; - return _this; - } - Object.defineProperty(URI.prototype, "scheme", { - get: function () { return this.normal.scheme; }, - set: function (value) { - this.raw.scheme = value; - this.normal.scheme = value.toLowerCase(); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(URI.prototype, "user", { - get: function () { return this.normal.user; }, - set: function (value) { - this.normal.user = this.raw.user = value; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(URI.prototype, "host", { - get: function () { return this.normal.host; }, - set: function (value) { - this.raw.host = value; - this.normal.host = value.toLowerCase(); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(URI.prototype, "aor", { - get: function () { return this.normal.user + "@" + this.normal.host; }, - enumerable: true, - configurable: true - }); - Object.defineProperty(URI.prototype, "port", { - get: function () { return this.normal.port; }, - set: function (value) { - this.normal.port = this.raw.port = value === 0 ? value : value; - }, - enumerable: true, - configurable: true - }); - URI.prototype.setHeader = function (name, value) { - this.headers[this.headerize(name)] = (value instanceof Array) ? value : [value]; - }; - URI.prototype.getHeader = function (name) { - if (name) { - return this.headers[this.headerize(name)]; - } - }; - URI.prototype.hasHeader = function (name) { - return !!name && !!this.headers.hasOwnProperty(this.headerize(name)); - }; - URI.prototype.deleteHeader = function (header) { - header = this.headerize(header); - if (this.headers.hasOwnProperty(header)) { - var value = this.headers[header]; - delete this.headers[header]; - return value; - } - }; - URI.prototype.clearHeaders = function () { - this.headers = {}; - }; - URI.prototype.clone = function () { - return new URI(this._raw.scheme, this._raw.user || "", this._raw.host, this._raw.port, JSON.parse(JSON.stringify(this.parameters)), JSON.parse(JSON.stringify(this.headers))); - }; - URI.prototype.toRaw = function () { - return this._toString(this._raw); - }; - URI.prototype.toString = function () { - return this._toString(this._normal); - }; - Object.defineProperty(URI.prototype, "_normal", { - get: function () { return this.normal; }, - enumerable: true, - configurable: true - }); - Object.defineProperty(URI.prototype, "_raw", { - get: function () { return this.raw; }, - enumerable: true, - configurable: true - }); - URI.prototype._toString = function (uri) { - var uriString = uri.scheme + ":"; - // add slashes if it's not a sip(s) URI - if (!uri.scheme.toLowerCase().match("^sips?$")) { - uriString += "//"; - } - if (uri.user) { - uriString += this.escapeUser(uri.user) + "@"; - } - uriString += uri.host; - if (uri.port || uri.port === 0) { - uriString += ":" + uri.port; - } - for (var parameter in this.parameters) { - if (this.parameters.hasOwnProperty(parameter)) { - uriString += ";" + parameter; - if (this.parameters[parameter] !== null) { - uriString += "=" + this.parameters[parameter]; - } - } - } - var headers = []; - for (var header in this.headers) { - if (this.headers.hasOwnProperty(header)) { - for (var idx in this.headers[header]) { - if (this.headers[header].hasOwnProperty(idx)) { - headers.push(header + "=" + this.headers[header][idx]); - } - } - } - } - if (headers.length > 0) { - uriString += "?" + headers.join("&"); - } - return uriString; - }; - /* - * Hex-escape a SIP URI user. - * @private - * @param {String} user - */ - URI.prototype.escapeUser = function (user) { - var decodedUser; - // FIXME: This is called by toString above which should never throw, but - // decodeURIComponent can throw and I've seen one case in production where - // it did throw resulting in a cascading failure. This class should be - // fixed so that decodeURIComponent is not called at this point (in toString). - // The user should be decoded when the URI is constructor or some other - // place where we can catch the error before the URI is created or somesuch. - try { - decodedUser = decodeURIComponent(user); - } - catch (error) { - throw error; - } - // Don't hex-escape ':' (%3A), '+' (%2B), '?' (%3F"), '/' (%2F). - return encodeURIComponent(decodedUser) - .replace(/%3A/ig, ":") - .replace(/%2B/ig, "+") - .replace(/%3F/ig, "?") - .replace(/%2F/ig, "/"); - }; - URI.prototype.headerize = function (str) { - var exceptions = { - "Call-Id": "Call-ID", - "Cseq": "CSeq", - "Min-Se": "Min-SE", - "Rack": "RAck", - "Rseq": "RSeq", - "Www-Authenticate": "WWW-Authenticate", - }; - var name = str.toLowerCase().replace(/_/g, "-").split("-"); - var parts = name.length; - var hname = ""; - for (var part = 0; part < parts; part++) { - if (part !== 0) { - hname += "-"; - } - hname += name[part].charAt(0).toUpperCase() + name[part].substring(1); - } - if (exceptions[hname]) { - hname = exceptions[hname]; - } - return hname; - }; - return URI; -}(parameters_1.Parameters)); -exports.URI = URI; - - -/***/ }), -/* 16 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * @param size - - * @param base - - * @internal - */ -function createRandomToken(size, base) { - if (base === void 0) { base = 32; } - var token = ""; - for (var i = 0; i < size; i++) { - var r = Math.floor(Math.random() * base); - token += r.toString(base); - } - return token; -} -exports.createRandomToken = createRandomToken; -/** - * @internal - */ -function getReasonPhrase(code) { - return REASON_PHRASE[code] || ""; -} -exports.getReasonPhrase = getReasonPhrase; -/** - * @internal - */ -function newTag() { - return createRandomToken(10); -} -exports.newTag = newTag; -/** - * @param str - - * @internal - */ -function headerize(str) { - var exceptions = { - "Call-Id": "Call-ID", - "Cseq": "CSeq", - "Min-Se": "Min-SE", - "Rack": "RAck", - "Rseq": "RSeq", - "Www-Authenticate": "WWW-Authenticate", - }; - var name = str.toLowerCase().replace(/_/g, "-").split("-"); - var parts = name.length; - var hname = ""; - for (var part = 0; part < parts; part++) { - if (part !== 0) { - hname += "-"; - } - hname += name[part].charAt(0).toUpperCase() + name[part].substring(1); - } - if (exceptions[hname]) { - hname = exceptions[hname]; - } - return hname; -} -exports.headerize = headerize; -/** - * @param str - - * @internal - */ -function str_utf8_length(str) { - return encodeURIComponent(str).replace(/%[A-F\d]{2}/g, "U").length; -} -exports.str_utf8_length = str_utf8_length; -/** - * SIP Response Reasons - * DOC: http://www.iana.org/assignments/sip-parameters - * @internal - */ -var REASON_PHRASE = { - 100: "Trying", - 180: "Ringing", - 181: "Call Is Being Forwarded", - 182: "Queued", - 183: "Session Progress", - 199: "Early Dialog Terminated", - 200: "OK", - 202: "Accepted", - 204: "No Notification", - 300: "Multiple Choices", - 301: "Moved Permanently", - 302: "Moved Temporarily", - 305: "Use Proxy", - 380: "Alternative Service", - 400: "Bad Request", - 401: "Unauthorized", - 402: "Payment Required", - 403: "Forbidden", - 404: "Not Found", - 405: "Method Not Allowed", - 406: "Not Acceptable", - 407: "Proxy Authentication Required", - 408: "Request Timeout", - 410: "Gone", - 412: "Conditional Request Failed", - 413: "Request Entity Too Large", - 414: "Request-URI Too Long", - 415: "Unsupported Media Type", - 416: "Unsupported URI Scheme", - 417: "Unknown Resource-Priority", - 420: "Bad Extension", - 421: "Extension Required", - 422: "Session Interval Too Small", - 423: "Interval Too Brief", - 428: "Use Identity Header", - 429: "Provide Referrer Identity", - 430: "Flow Failed", - 433: "Anonymity Disallowed", - 436: "Bad Identity-Info", - 437: "Unsupported Certificate", - 438: "Invalid Identity Header", - 439: "First Hop Lacks Outbound Support", - 440: "Max-Breadth Exceeded", - 469: "Bad Info Package", - 470: "Consent Needed", - 478: "Unresolvable Destination", - 480: "Temporarily Unavailable", - 481: "Call/Transaction Does Not Exist", - 482: "Loop Detected", - 483: "Too Many Hops", - 484: "Address Incomplete", - 485: "Ambiguous", - 486: "Busy Here", - 487: "Request Terminated", - 488: "Not Acceptable Here", - 489: "Bad Event", - 491: "Request Pending", - 493: "Undecipherable", - 494: "Security Agreement Required", - 500: "Internal Server Error", - 501: "Not Implemented", - 502: "Bad Gateway", - 503: "Service Unavailable", - 504: "Server Time-out", - 505: "Version Not Supported", - 513: "Message Too Large", - 580: "Precondition Failure", - 600: "Busy Everywhere", - 603: "Decline", - 604: "Does Not Exist Anywhere", - 606: "Not Acceptable" -}; - - -/***/ }), -/* 17 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var incoming_message_1 = __webpack_require__(10); -/** - * Incoming response message. - * @public - */ -var IncomingResponseMessage = /** @class */ (function (_super) { - tslib_1.__extends(IncomingResponseMessage, _super); - function IncomingResponseMessage() { - return _super.call(this) || this; - } - return IncomingResponseMessage; -}(incoming_message_1.IncomingMessage)); -exports.IncomingResponseMessage = IncomingResponseMessage; - - -/***/ }), -/* 18 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var name_addr_header_1 = __webpack_require__(13); -var utils_1 = __webpack_require__(16); -/** - * Outgoing SIP request message. - * @public - */ -var OutgoingRequestMessage = /** @class */ (function () { - function OutgoingRequestMessage(method, ruri, fromURI, toURI, options, extraHeaders, body) { - this.headers = {}; - this.extraHeaders = []; - this.options = OutgoingRequestMessage.getDefaultOptions(); - // Options - merge a deep copy - if (options) { - this.options = tslib_1.__assign({}, this.options, options); - if (this.options.optionTags && this.options.optionTags.length) { - this.options.optionTags = this.options.optionTags.slice(); - } - if (this.options.routeSet && this.options.routeSet.length) { - this.options.routeSet = this.options.routeSet.slice(); - } - } - // Extra headers - deep copy - if (extraHeaders && extraHeaders.length) { - this.extraHeaders = extraHeaders.slice(); - } - // Body - deep copy - if (body) { - // TODO: internal representation should be Body - // this.body = { ...body }; - this.body = { - body: body.content, - contentType: body.contentType - }; - } - // Method - this.method = method; - // RURI - this.ruri = ruri.clone(); - // From - this.fromURI = fromURI.clone(); - this.fromTag = this.options.fromTag ? this.options.fromTag : utils_1.newTag(); - this.from = OutgoingRequestMessage.makeNameAddrHeader(this.fromURI, this.options.fromDisplayName, this.fromTag); - // To - this.toURI = toURI.clone(); - this.toTag = this.options.toTag; - this.to = OutgoingRequestMessage.makeNameAddrHeader(this.toURI, this.options.toDisplayName, this.toTag); - // Call-ID - this.callId = this.options.callId ? this.options.callId : this.options.callIdPrefix + utils_1.createRandomToken(15); - // CSeq - this.cseq = this.options.cseq; - // The relative order of header fields with different field names is not - // significant. However, it is RECOMMENDED that header fields which are - // needed for proxy processing (Via, Route, Record-Route, Proxy-Require, - // Max-Forwards, and Proxy-Authorization, for example) appear towards - // the top of the message to facilitate rapid parsing. - // https://tools.ietf.org/html/rfc3261#section-7.3.1 - this.setHeader("route", this.options.routeSet); - this.setHeader("via", ""); - this.setHeader("to", this.to.toString()); - this.setHeader("from", this.from.toString()); - this.setHeader("cseq", this.cseq + " " + this.method); - this.setHeader("call-id", this.callId); - this.setHeader("max-forwards", "70"); - } - /** Get a copy of the default options. */ - OutgoingRequestMessage.getDefaultOptions = function () { - return { - callId: "", - callIdPrefix: "", - cseq: 1, - toDisplayName: "", - toTag: "", - fromDisplayName: "", - fromTag: "", - forceRport: false, - hackViaTcp: false, - optionTags: ["outbound"], - routeSet: [], - userAgentString: "sip.js", - viaHost: "" - }; - }; - OutgoingRequestMessage.makeNameAddrHeader = function (uri, displayName, tag) { - var parameters = {}; - if (tag) { - parameters.tag = tag; - } - return new name_addr_header_1.NameAddrHeader(uri, displayName, parameters); - }; - /** - * Get the value of the given header name at the given position. - * @param name - header name - * @returns Returns the specified header, undefined if header doesn't exist. - */ - OutgoingRequestMessage.prototype.getHeader = function (name) { - var header = this.headers[utils_1.headerize(name)]; - if (header) { - if (header[0]) { - return header[0]; - } - } - else { - var regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); - for (var _i = 0, _a = this.extraHeaders; _i < _a.length; _i++) { - var exHeader = _a[_i]; - if (regexp.test(exHeader)) { - return exHeader.substring(exHeader.indexOf(":") + 1).trim(); - } - } - } - return; - }; - /** - * Get the header/s of the given name. - * @param name - header name - * @returns Array with all the headers of the specified name. - */ - OutgoingRequestMessage.prototype.getHeaders = function (name) { - var result = []; - var headerArray = this.headers[utils_1.headerize(name)]; - if (headerArray) { - for (var _i = 0, headerArray_1 = headerArray; _i < headerArray_1.length; _i++) { - var headerPart = headerArray_1[_i]; - result.push(headerPart); - } - } - else { - var regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); - for (var _a = 0, _b = this.extraHeaders; _a < _b.length; _a++) { - var exHeader = _b[_a]; - if (regexp.test(exHeader)) { - result.push(exHeader.substring(exHeader.indexOf(":") + 1).trim()); - } - } - } - return result; - }; - /** - * Verify the existence of the given header. - * @param name - header name - * @returns true if header with given name exists, false otherwise - */ - OutgoingRequestMessage.prototype.hasHeader = function (name) { - if (this.headers[utils_1.headerize(name)]) { - return true; - } - else { - var regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); - for (var _i = 0, _a = this.extraHeaders; _i < _a.length; _i++) { - var extraHeader = _a[_i]; - if (regexp.test(extraHeader)) { - return true; - } - } - } - return false; - }; - /** - * Replace the the given header by the given value. - * @param name - header name - * @param value - header value - */ - OutgoingRequestMessage.prototype.setHeader = function (name, value) { - this.headers[utils_1.headerize(name)] = (value instanceof Array) ? value : [value]; - }; - /** - * The Via header field indicates the transport used for the transaction - * and identifies the location where the response is to be sent. A Via - * header field value is added only after the transport that will be - * used to reach the next hop has been selected (which may involve the - * usage of the procedures in [4]). - * - * When the UAC creates a request, it MUST insert a Via into that - * request. The protocol name and protocol version in the header field - * MUST be SIP and 2.0, respectively. The Via header field value MUST - * contain a branch parameter. This parameter is used to identify the - * transaction created by that request. This parameter is used by both - * the client and the server. - * https://tools.ietf.org/html/rfc3261#section-8.1.1.7 - * @param branchParameter - The branch parameter. - * @param scheme - The scheme. - */ - OutgoingRequestMessage.prototype.setViaHeader = function (branch, scheme) { - if (scheme === void 0) { scheme = "WSS"; } - // FIXME: Hack - if (this.options.hackViaTcp) { - scheme = "TCP"; - } - var via = "SIP/2.0/" + scheme; - via += " " + this.options.viaHost + ";branch=" + branch; - if (this.options.forceRport) { - via += ";rport"; - } - this.setHeader("via", via); - this.branch = branch; - }; - OutgoingRequestMessage.prototype.toString = function () { - var msg = ""; - msg += this.method + " " + this.ruri.toRaw() + " SIP/2.0\r\n"; - for (var header in this.headers) { - if (this.headers[header]) { - for (var _i = 0, _a = this.headers[header]; _i < _a.length; _i++) { - var headerPart = _a[_i]; - msg += header + ": " + headerPart + "\r\n"; - } - } - } - for (var _b = 0, _c = this.extraHeaders; _b < _c.length; _b++) { - var header = _c[_b]; - msg += header.trim() + "\r\n"; - } - msg += "Supported: " + this.options.optionTags.join(", ") + "\r\n"; - msg += "User-Agent: " + this.options.userAgentString + "\r\n"; - if (this.body) { - if (typeof this.body === "string") { - msg += "Content-Length: " + utils_1.str_utf8_length(this.body) + "\r\n\r\n"; - msg += this.body; - } - else { - if (this.body.body && this.body.contentType) { - msg += "Content-Type: " + this.body.contentType + "\r\n"; - msg += "Content-Length: " + utils_1.str_utf8_length(this.body.body) + "\r\n\r\n"; - msg += this.body.body; - } - else { - msg += "Content-Length: " + 0 + "\r\n\r\n"; - } - } - } - else { - msg += "Content-Length: " + 0 + "\r\n\r\n"; - } - return msg; - }; - return OutgoingRequestMessage; -}()); -exports.OutgoingRequestMessage = OutgoingRequestMessage; - - -/***/ }), -/* 19 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var md5_1 = tslib_1.__importDefault(__webpack_require__(20)); -var utils_1 = __webpack_require__(16); -/** - * Digest Authentication. - * @internal - */ -var DigestAuthentication = /** @class */ (function () { - /** - * Constructor. - * @param loggerFactory - LoggerFactory. - * @param username - Username. - * @param password - Password. - */ - function DigestAuthentication(loggerFactory, username, password) { - this.logger = loggerFactory.getLogger("sipjs.digestauthentication"); - this.username = username; - this.password = password; - this.nc = 0; - this.ncHex = "00000000"; - } - /** - * Performs Digest authentication given a SIP request and the challenge - * received in a response to that request. - * @param request - - * @param challenge - - * @returns true if credentials were successfully generated, false otherwise. - */ - DigestAuthentication.prototype.authenticate = function (request, challenge, body) { - // Inspect and validate the challenge. - this.algorithm = challenge.algorithm; - this.realm = challenge.realm; - this.nonce = challenge.nonce; - this.opaque = challenge.opaque; - this.stale = challenge.stale; - if (this.algorithm) { - if (this.algorithm !== "MD5") { - this.logger.warn("challenge with Digest algorithm different than 'MD5', authentication aborted"); - return false; - } - } - else { - this.algorithm = "MD5"; - } - if (!this.realm) { - this.logger.warn("challenge without Digest realm, authentication aborted"); - return false; - } - if (!this.nonce) { - this.logger.warn("challenge without Digest nonce, authentication aborted"); - return false; - } - // 'qop' can contain a list of values (Array). Let's choose just one. - if (challenge.qop) { - if (challenge.qop.indexOf("auth") > -1) { - this.qop = "auth"; - } - else if (challenge.qop.indexOf("auth-int") > -1) { - this.qop = "auth-int"; - } - else { - // Otherwise 'qop' is present but does not contain 'auth' or 'auth-int', so abort here. - this.logger.warn("challenge without Digest qop different than 'auth' or 'auth-int', authentication aborted"); - return false; - } - } - else { - this.qop = undefined; - } - // Fill other attributes. - this.method = request.method; - this.uri = request.ruri; - this.cnonce = utils_1.createRandomToken(12); - this.nc += 1; - this.updateNcHex(); - // nc-value = 8LHEX. Max value = 'FFFFFFFF'. - if (this.nc === 4294967296) { - this.nc = 1; - this.ncHex = "00000001"; - } - // Calculate the Digest "response" value. - this.calculateResponse(body); - return true; - }; - /** - * Return the Proxy-Authorization or WWW-Authorization header value. - */ - DigestAuthentication.prototype.toString = function () { - var authParams = []; - if (!this.response) { - throw new Error("response field does not exist, cannot generate Authorization header"); - } - authParams.push("algorithm=" + this.algorithm); - authParams.push('username="' + this.username + '"'); - authParams.push('realm="' + this.realm + '"'); - authParams.push('nonce="' + this.nonce + '"'); - authParams.push('uri="' + this.uri + '"'); - authParams.push('response="' + this.response + '"'); - if (this.opaque) { - authParams.push('opaque="' + this.opaque + '"'); - } - if (this.qop) { - authParams.push("qop=" + this.qop); - authParams.push('cnonce="' + this.cnonce + '"'); - authParams.push("nc=" + this.ncHex); - } - return "Digest " + authParams.join(", "); - }; - /** - * Generate the 'nc' value as required by Digest in this.ncHex by reading this.nc. - */ - DigestAuthentication.prototype.updateNcHex = function () { - var hex = Number(this.nc).toString(16); - this.ncHex = "00000000".substr(0, 8 - hex.length) + hex; - }; - /** - * Generate Digest 'response' value. - */ - DigestAuthentication.prototype.calculateResponse = function (body) { - var ha2; - // HA1 = MD5(A1) = MD5(username:realm:password) - var ha1 = md5_1.default(this.username + ":" + this.realm + ":" + this.password); - if (this.qop === "auth") { - // HA2 = MD5(A2) = MD5(method:digestURI) - ha2 = md5_1.default(this.method + ":" + this.uri); - // response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2) - this.response = md5_1.default(ha1 + ":" + this.nonce + ":" + this.ncHex + ":" + this.cnonce + ":auth:" + ha2); - } - else if (this.qop === "auth-int") { - // HA2 = MD5(A2) = MD5(method:digestURI:MD5(entityBody)) - ha2 = md5_1.default(this.method + ":" + this.uri + ":" + md5_1.default(body ? body : "")); - // response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2) - this.response = md5_1.default(ha1 + ":" + this.nonce + ":" + this.ncHex + ":" + this.cnonce + ":auth-int:" + ha2); - } - else if (this.qop === undefined) { - // HA2 = MD5(A2) = MD5(method:digestURI) - ha2 = md5_1.default(this.method + ":" + this.uri); - // response = MD5(HA1:nonce:HA2) - this.response = md5_1.default(ha1 + ":" + this.nonce + ":" + ha2); - } - }; - return DigestAuthentication; -}()); -exports.DigestAuthentication = DigestAuthentication; - - -/***/ }), -/* 20 */ -/***/ (function(module, exports, __webpack_require__) { - -;(function (root, factory) { - if (true) { - // CommonJS - module.exports = exports = factory(__webpack_require__(21)); - } - else {} -}(this, function (CryptoJS) { - - (function (Math) { - // Shortcuts - var C = CryptoJS; - var C_lib = C.lib; - var WordArray = C_lib.WordArray; - var Hasher = C_lib.Hasher; - var C_algo = C.algo; - - // Constants table - var T = []; - - // Compute constants - (function () { - for (var i = 0; i < 64; i++) { - T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0; - } - }()); - - /** - * MD5 hash algorithm. - */ - var MD5 = C_algo.MD5 = Hasher.extend({ - _doReset: function () { - this._hash = new WordArray.init([ - 0x67452301, 0xefcdab89, - 0x98badcfe, 0x10325476 - ]); - }, - - _doProcessBlock: function (M, offset) { - // Swap endian - for (var i = 0; i < 16; i++) { - // Shortcuts - var offset_i = offset + i; - var M_offset_i = M[offset_i]; - - M[offset_i] = ( - (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | - (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) - ); - } - - // Shortcuts - var H = this._hash.words; - - var M_offset_0 = M[offset + 0]; - var M_offset_1 = M[offset + 1]; - var M_offset_2 = M[offset + 2]; - var M_offset_3 = M[offset + 3]; - var M_offset_4 = M[offset + 4]; - var M_offset_5 = M[offset + 5]; - var M_offset_6 = M[offset + 6]; - var M_offset_7 = M[offset + 7]; - var M_offset_8 = M[offset + 8]; - var M_offset_9 = M[offset + 9]; - var M_offset_10 = M[offset + 10]; - var M_offset_11 = M[offset + 11]; - var M_offset_12 = M[offset + 12]; - var M_offset_13 = M[offset + 13]; - var M_offset_14 = M[offset + 14]; - var M_offset_15 = M[offset + 15]; - - // Working varialbes - var a = H[0]; - var b = H[1]; - var c = H[2]; - var d = H[3]; - - // Computation - a = FF(a, b, c, d, M_offset_0, 7, T[0]); - d = FF(d, a, b, c, M_offset_1, 12, T[1]); - c = FF(c, d, a, b, M_offset_2, 17, T[2]); - b = FF(b, c, d, a, M_offset_3, 22, T[3]); - a = FF(a, b, c, d, M_offset_4, 7, T[4]); - d = FF(d, a, b, c, M_offset_5, 12, T[5]); - c = FF(c, d, a, b, M_offset_6, 17, T[6]); - b = FF(b, c, d, a, M_offset_7, 22, T[7]); - a = FF(a, b, c, d, M_offset_8, 7, T[8]); - d = FF(d, a, b, c, M_offset_9, 12, T[9]); - c = FF(c, d, a, b, M_offset_10, 17, T[10]); - b = FF(b, c, d, a, M_offset_11, 22, T[11]); - a = FF(a, b, c, d, M_offset_12, 7, T[12]); - d = FF(d, a, b, c, M_offset_13, 12, T[13]); - c = FF(c, d, a, b, M_offset_14, 17, T[14]); - b = FF(b, c, d, a, M_offset_15, 22, T[15]); - - a = GG(a, b, c, d, M_offset_1, 5, T[16]); - d = GG(d, a, b, c, M_offset_6, 9, T[17]); - c = GG(c, d, a, b, M_offset_11, 14, T[18]); - b = GG(b, c, d, a, M_offset_0, 20, T[19]); - a = GG(a, b, c, d, M_offset_5, 5, T[20]); - d = GG(d, a, b, c, M_offset_10, 9, T[21]); - c = GG(c, d, a, b, M_offset_15, 14, T[22]); - b = GG(b, c, d, a, M_offset_4, 20, T[23]); - a = GG(a, b, c, d, M_offset_9, 5, T[24]); - d = GG(d, a, b, c, M_offset_14, 9, T[25]); - c = GG(c, d, a, b, M_offset_3, 14, T[26]); - b = GG(b, c, d, a, M_offset_8, 20, T[27]); - a = GG(a, b, c, d, M_offset_13, 5, T[28]); - d = GG(d, a, b, c, M_offset_2, 9, T[29]); - c = GG(c, d, a, b, M_offset_7, 14, T[30]); - b = GG(b, c, d, a, M_offset_12, 20, T[31]); - - a = HH(a, b, c, d, M_offset_5, 4, T[32]); - d = HH(d, a, b, c, M_offset_8, 11, T[33]); - c = HH(c, d, a, b, M_offset_11, 16, T[34]); - b = HH(b, c, d, a, M_offset_14, 23, T[35]); - a = HH(a, b, c, d, M_offset_1, 4, T[36]); - d = HH(d, a, b, c, M_offset_4, 11, T[37]); - c = HH(c, d, a, b, M_offset_7, 16, T[38]); - b = HH(b, c, d, a, M_offset_10, 23, T[39]); - a = HH(a, b, c, d, M_offset_13, 4, T[40]); - d = HH(d, a, b, c, M_offset_0, 11, T[41]); - c = HH(c, d, a, b, M_offset_3, 16, T[42]); - b = HH(b, c, d, a, M_offset_6, 23, T[43]); - a = HH(a, b, c, d, M_offset_9, 4, T[44]); - d = HH(d, a, b, c, M_offset_12, 11, T[45]); - c = HH(c, d, a, b, M_offset_15, 16, T[46]); - b = HH(b, c, d, a, M_offset_2, 23, T[47]); - - a = II(a, b, c, d, M_offset_0, 6, T[48]); - d = II(d, a, b, c, M_offset_7, 10, T[49]); - c = II(c, d, a, b, M_offset_14, 15, T[50]); - b = II(b, c, d, a, M_offset_5, 21, T[51]); - a = II(a, b, c, d, M_offset_12, 6, T[52]); - d = II(d, a, b, c, M_offset_3, 10, T[53]); - c = II(c, d, a, b, M_offset_10, 15, T[54]); - b = II(b, c, d, a, M_offset_1, 21, T[55]); - a = II(a, b, c, d, M_offset_8, 6, T[56]); - d = II(d, a, b, c, M_offset_15, 10, T[57]); - c = II(c, d, a, b, M_offset_6, 15, T[58]); - b = II(b, c, d, a, M_offset_13, 21, T[59]); - a = II(a, b, c, d, M_offset_4, 6, T[60]); - d = II(d, a, b, c, M_offset_11, 10, T[61]); - c = II(c, d, a, b, M_offset_2, 15, T[62]); - b = II(b, c, d, a, M_offset_9, 21, T[63]); - - // Intermediate hash value - H[0] = (H[0] + a) | 0; - H[1] = (H[1] + b) | 0; - H[2] = (H[2] + c) | 0; - H[3] = (H[3] + d) | 0; - }, - - _doFinalize: function () { - // Shortcuts - var data = this._data; - var dataWords = data.words; - - var nBitsTotal = this._nDataBytes * 8; - var nBitsLeft = data.sigBytes * 8; - - // Add padding - dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); - - var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000); - var nBitsTotalL = nBitsTotal; - dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = ( - (((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) | - (((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00) - ); - dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( - (((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) | - (((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00) - ); - - data.sigBytes = (dataWords.length + 1) * 4; - - // Hash final blocks - this._process(); - - // Shortcuts - var hash = this._hash; - var H = hash.words; - - // Swap endian - for (var i = 0; i < 4; i++) { - // Shortcut - var H_i = H[i]; - - H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | - (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); - } - - // Return final computed hash - return hash; - }, - - clone: function () { - var clone = Hasher.clone.call(this); - clone._hash = this._hash.clone(); - - return clone; - } - }); - - function FF(a, b, c, d, x, s, t) { - var n = a + ((b & c) | (~b & d)) + x + t; - return ((n << s) | (n >>> (32 - s))) + b; - } - - function GG(a, b, c, d, x, s, t) { - var n = a + ((b & d) | (c & ~d)) + x + t; - return ((n << s) | (n >>> (32 - s))) + b; - } - - function HH(a, b, c, d, x, s, t) { - var n = a + (b ^ c ^ d) + x + t; - return ((n << s) | (n >>> (32 - s))) + b; - } - - function II(a, b, c, d, x, s, t) { - var n = a + (c ^ (b | ~d)) + x + t; - return ((n << s) | (n >>> (32 - s))) + b; - } - - /** - * Shortcut function to the hasher's object interface. - * - * @param {WordArray|string} message The message to hash. - * - * @return {WordArray} The hash. - * - * @static - * - * @example - * - * var hash = CryptoJS.MD5('message'); - * var hash = CryptoJS.MD5(wordArray); - */ - C.MD5 = Hasher._createHelper(MD5); - - /** - * Shortcut function to the HMAC's object interface. - * - * @param {WordArray|string} message The message to hash. - * @param {WordArray|string} key The secret key. - * - * @return {WordArray} The HMAC. - * - * @static - * - * @example - * - * var hmac = CryptoJS.HmacMD5(message, key); - */ - C.HmacMD5 = Hasher._createHmacHelper(MD5); - }(Math)); - - - return CryptoJS.MD5; - -})); - -/***/ }), -/* 21 */ -/***/ (function(module, exports, __webpack_require__) { - -;(function (root, factory) { - if (true) { - // CommonJS - module.exports = exports = factory(); - } - else {} -}(this, function () { - - /** - * CryptoJS core components. - */ - var CryptoJS = CryptoJS || (function (Math, undefined) { - /* - * Local polyfil of Object.create - */ - var create = Object.create || (function () { - function F() {}; - - return function (obj) { - var subtype; - - F.prototype = obj; - - subtype = new F(); - - F.prototype = null; - - return subtype; - }; - }()) - - /** - * CryptoJS namespace. - */ - var C = {}; - - /** - * Library namespace. - */ - var C_lib = C.lib = {}; - - /** - * Base object for prototypal inheritance. - */ - var Base = C_lib.Base = (function () { - - - return { - /** - * Creates a new object that inherits from this object. - * - * @param {Object} overrides Properties to copy into the new object. - * - * @return {Object} The new object. - * - * @static - * - * @example - * - * var MyType = CryptoJS.lib.Base.extend({ - * field: 'value', - * - * method: function () { - * } - * }); - */ - extend: function (overrides) { - // Spawn - var subtype = create(this); - - // Augment - if (overrides) { - subtype.mixIn(overrides); - } - - // Create default initializer - if (!subtype.hasOwnProperty('init') || this.init === subtype.init) { - subtype.init = function () { - subtype.$super.init.apply(this, arguments); - }; - } - - // Initializer's prototype is the subtype object - subtype.init.prototype = subtype; - - // Reference supertype - subtype.$super = this; - - return subtype; - }, - - /** - * Extends this object and runs the init method. - * Arguments to create() will be passed to init(). - * - * @return {Object} The new object. - * - * @static - * - * @example - * - * var instance = MyType.create(); - */ - create: function () { - var instance = this.extend(); - instance.init.apply(instance, arguments); - - return instance; - }, - - /** - * Initializes a newly created object. - * Override this method to add some logic when your objects are created. - * - * @example - * - * var MyType = CryptoJS.lib.Base.extend({ - * init: function () { - * // ... - * } - * }); - */ - init: function () { - }, - - /** - * Copies properties into this object. - * - * @param {Object} properties The properties to mix in. - * - * @example - * - * MyType.mixIn({ - * field: 'value' - * }); - */ - mixIn: function (properties) { - for (var propertyName in properties) { - if (properties.hasOwnProperty(propertyName)) { - this[propertyName] = properties[propertyName]; - } - } - - // IE won't copy toString using the loop above - if (properties.hasOwnProperty('toString')) { - this.toString = properties.toString; - } - }, - - /** - * Creates a copy of this object. - * - * @return {Object} The clone. - * - * @example - * - * var clone = instance.clone(); - */ - clone: function () { - return this.init.prototype.extend(this); - } - }; - }()); - - /** - * An array of 32-bit words. - * - * @property {Array} words The array of 32-bit words. - * @property {number} sigBytes The number of significant bytes in this word array. - */ - var WordArray = C_lib.WordArray = Base.extend({ - /** - * Initializes a newly created word array. - * - * @param {Array} words (Optional) An array of 32-bit words. - * @param {number} sigBytes (Optional) The number of significant bytes in the words. - * - * @example - * - * var wordArray = CryptoJS.lib.WordArray.create(); - * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); - * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); - */ - init: function (words, sigBytes) { - words = this.words = words || []; - - if (sigBytes != undefined) { - this.sigBytes = sigBytes; - } else { - this.sigBytes = words.length * 4; - } - }, - - /** - * Converts this word array to a string. - * - * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex - * - * @return {string} The stringified word array. - * - * @example - * - * var string = wordArray + ''; - * var string = wordArray.toString(); - * var string = wordArray.toString(CryptoJS.enc.Utf8); - */ - toString: function (encoder) { - return (encoder || Hex).stringify(this); - }, - - /** - * Concatenates a word array to this word array. - * - * @param {WordArray} wordArray The word array to append. - * - * @return {WordArray} This word array. - * - * @example - * - * wordArray1.concat(wordArray2); - */ - concat: function (wordArray) { - // Shortcuts - var thisWords = this.words; - var thatWords = wordArray.words; - var thisSigBytes = this.sigBytes; - var thatSigBytes = wordArray.sigBytes; - - // Clamp excess bits - this.clamp(); - - // Concat - if (thisSigBytes % 4) { - // Copy one byte at a time - for (var i = 0; i < thatSigBytes; i++) { - var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; - thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); - } - } else { - // Copy one word at a time - for (var i = 0; i < thatSigBytes; i += 4) { - thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2]; - } - } - this.sigBytes += thatSigBytes; - - // Chainable - return this; - }, - - /** - * Removes insignificant bits. - * - * @example - * - * wordArray.clamp(); - */ - clamp: function () { - // Shortcuts - var words = this.words; - var sigBytes = this.sigBytes; - - // Clamp - words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); - words.length = Math.ceil(sigBytes / 4); - }, - - /** - * Creates a copy of this word array. - * - * @return {WordArray} The clone. - * - * @example - * - * var clone = wordArray.clone(); - */ - clone: function () { - var clone = Base.clone.call(this); - clone.words = this.words.slice(0); - - return clone; - }, - - /** - * Creates a word array filled with random bytes. - * - * @param {number} nBytes The number of random bytes to generate. - * - * @return {WordArray} The random word array. - * - * @static - * - * @example - * - * var wordArray = CryptoJS.lib.WordArray.random(16); - */ - random: function (nBytes) { - var words = []; - - var r = (function (m_w) { - var m_w = m_w; - var m_z = 0x3ade68b1; - var mask = 0xffffffff; - - return function () { - m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask; - m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask; - var result = ((m_z << 0x10) + m_w) & mask; - result /= 0x100000000; - result += 0.5; - return result * (Math.random() > .5 ? 1 : -1); - } - }); - - for (var i = 0, rcache; i < nBytes; i += 4) { - var _r = r((rcache || Math.random()) * 0x100000000); - - rcache = _r() * 0x3ade67b7; - words.push((_r() * 0x100000000) | 0); - } - - return new WordArray.init(words, nBytes); - } - }); - - /** - * Encoder namespace. - */ - var C_enc = C.enc = {}; - - /** - * Hex encoding strategy. - */ - var Hex = C_enc.Hex = { - /** - * Converts a word array to a hex string. - * - * @param {WordArray} wordArray The word array. - * - * @return {string} The hex string. - * - * @static - * - * @example - * - * var hexString = CryptoJS.enc.Hex.stringify(wordArray); - */ - stringify: function (wordArray) { - // Shortcuts - var words = wordArray.words; - var sigBytes = wordArray.sigBytes; - - // Convert - var hexChars = []; - for (var i = 0; i < sigBytes; i++) { - var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; - hexChars.push((bite >>> 4).toString(16)); - hexChars.push((bite & 0x0f).toString(16)); - } - - return hexChars.join(''); - }, - - /** - * Converts a hex string to a word array. - * - * @param {string} hexStr The hex string. - * - * @return {WordArray} The word array. - * - * @static - * - * @example - * - * var wordArray = CryptoJS.enc.Hex.parse(hexString); - */ - parse: function (hexStr) { - // Shortcut - var hexStrLength = hexStr.length; - - // Convert - var words = []; - for (var i = 0; i < hexStrLength; i += 2) { - words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); - } - - return new WordArray.init(words, hexStrLength / 2); - } - }; - - /** - * Latin1 encoding strategy. - */ - var Latin1 = C_enc.Latin1 = { - /** - * Converts a word array to a Latin1 string. - * - * @param {WordArray} wordArray The word array. - * - * @return {string} The Latin1 string. - * - * @static - * - * @example - * - * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); - */ - stringify: function (wordArray) { - // Shortcuts - var words = wordArray.words; - var sigBytes = wordArray.sigBytes; - - // Convert - var latin1Chars = []; - for (var i = 0; i < sigBytes; i++) { - var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; - latin1Chars.push(String.fromCharCode(bite)); - } - - return latin1Chars.join(''); - }, - - /** - * Converts a Latin1 string to a word array. - * - * @param {string} latin1Str The Latin1 string. - * - * @return {WordArray} The word array. - * - * @static - * - * @example - * - * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); - */ - parse: function (latin1Str) { - // Shortcut - var latin1StrLength = latin1Str.length; - - // Convert - var words = []; - for (var i = 0; i < latin1StrLength; i++) { - words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); - } - - return new WordArray.init(words, latin1StrLength); - } - }; - - /** - * UTF-8 encoding strategy. - */ - var Utf8 = C_enc.Utf8 = { - /** - * Converts a word array to a UTF-8 string. - * - * @param {WordArray} wordArray The word array. - * - * @return {string} The UTF-8 string. - * - * @static - * - * @example - * - * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); - */ - stringify: function (wordArray) { - try { - return decodeURIComponent(escape(Latin1.stringify(wordArray))); - } catch (e) { - throw new Error('Malformed UTF-8 data'); - } - }, - - /** - * Converts a UTF-8 string to a word array. - * - * @param {string} utf8Str The UTF-8 string. - * - * @return {WordArray} The word array. - * - * @static - * - * @example - * - * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); - */ - parse: function (utf8Str) { - return Latin1.parse(unescape(encodeURIComponent(utf8Str))); - } - }; - - /** - * Abstract buffered block algorithm template. - * - * The property blockSize must be implemented in a concrete subtype. - * - * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 - */ - var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ - /** - * Resets this block algorithm's data buffer to its initial state. - * - * @example - * - * bufferedBlockAlgorithm.reset(); - */ - reset: function () { - // Initial values - this._data = new WordArray.init(); - this._nDataBytes = 0; - }, - - /** - * Adds new data to this block algorithm's buffer. - * - * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. - * - * @example - * - * bufferedBlockAlgorithm._append('data'); - * bufferedBlockAlgorithm._append(wordArray); - */ - _append: function (data) { - // Convert string to WordArray, else assume WordArray already - if (typeof data == 'string') { - data = Utf8.parse(data); - } - - // Append - this._data.concat(data); - this._nDataBytes += data.sigBytes; - }, - - /** - * Processes available data blocks. - * - * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. - * - * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. - * - * @return {WordArray} The processed data. - * - * @example - * - * var processedData = bufferedBlockAlgorithm._process(); - * var processedData = bufferedBlockAlgorithm._process(!!'flush'); - */ - _process: function (doFlush) { - // Shortcuts - var data = this._data; - var dataWords = data.words; - var dataSigBytes = data.sigBytes; - var blockSize = this.blockSize; - var blockSizeBytes = blockSize * 4; - - // Count blocks ready - var nBlocksReady = dataSigBytes / blockSizeBytes; - if (doFlush) { - // Round up to include partial blocks - nBlocksReady = Math.ceil(nBlocksReady); - } else { - // Round down to include only full blocks, - // less the number of blocks that must remain in the buffer - nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); - } - - // Count words ready - var nWordsReady = nBlocksReady * blockSize; - - // Count bytes ready - var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); - - // Process blocks - if (nWordsReady) { - for (var offset = 0; offset < nWordsReady; offset += blockSize) { - // Perform concrete-algorithm logic - this._doProcessBlock(dataWords, offset); - } - - // Remove processed words - var processedWords = dataWords.splice(0, nWordsReady); - data.sigBytes -= nBytesReady; - } - - // Return processed words - return new WordArray.init(processedWords, nBytesReady); - }, - - /** - * Creates a copy of this object. - * - * @return {Object} The clone. - * - * @example - * - * var clone = bufferedBlockAlgorithm.clone(); - */ - clone: function () { - var clone = Base.clone.call(this); - clone._data = this._data.clone(); - - return clone; - }, - - _minBufferSize: 0 - }); - - /** - * Abstract hasher template. - * - * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) - */ - var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ - /** - * Configuration options. - */ - cfg: Base.extend(), - - /** - * Initializes a newly created hasher. - * - * @param {Object} cfg (Optional) The configuration options to use for this hash computation. - * - * @example - * - * var hasher = CryptoJS.algo.SHA256.create(); - */ - init: function (cfg) { - // Apply config defaults - this.cfg = this.cfg.extend(cfg); - - // Set initial values - this.reset(); - }, - - /** - * Resets this hasher to its initial state. - * - * @example - * - * hasher.reset(); - */ - reset: function () { - // Reset data buffer - BufferedBlockAlgorithm.reset.call(this); - - // Perform concrete-hasher logic - this._doReset(); - }, - - /** - * Updates this hasher with a message. - * - * @param {WordArray|string} messageUpdate The message to append. - * - * @return {Hasher} This hasher. - * - * @example - * - * hasher.update('message'); - * hasher.update(wordArray); - */ - update: function (messageUpdate) { - // Append - this._append(messageUpdate); - - // Update the hash - this._process(); - - // Chainable - return this; - }, - - /** - * Finalizes the hash computation. - * Note that the finalize operation is effectively a destructive, read-once operation. - * - * @param {WordArray|string} messageUpdate (Optional) A final message update. - * - * @return {WordArray} The hash. - * - * @example - * - * var hash = hasher.finalize(); - * var hash = hasher.finalize('message'); - * var hash = hasher.finalize(wordArray); - */ - finalize: function (messageUpdate) { - // Final message update - if (messageUpdate) { - this._append(messageUpdate); - } - - // Perform concrete-hasher logic - var hash = this._doFinalize(); - - return hash; - }, - - blockSize: 512/32, - - /** - * Creates a shortcut function to a hasher's object interface. - * - * @param {Hasher} hasher The hasher to create a helper for. - * - * @return {Function} The shortcut function. - * - * @static - * - * @example - * - * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); - */ - _createHelper: function (hasher) { - return function (message, cfg) { - return new hasher.init(cfg).finalize(message); - }; - }, - - /** - * Creates a shortcut function to the HMAC's object interface. - * - * @param {Hasher} hasher The hasher to use in this HMAC helper. - * - * @return {Function} The shortcut function. - * - * @static - * - * @example - * - * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); - */ - _createHmacHelper: function (hasher) { - return function (message, key) { - return new C_algo.HMAC.init(hasher, key).finalize(message); - }; - } - }); - - /** - * Algorithm namespace. - */ - var C_algo = C.algo = {}; - - return C; - }(Math)); - - - return CryptoJS; - -})); - -/***/ }), -/* 22 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var utils_1 = __webpack_require__(16); -/** - * When a UAS wishes to construct a response to a request, it follows - * the general procedures detailed in the following subsections. - * Additional behaviors specific to the response code in question, which - * are not detailed in this section, may also be required. - * https://tools.ietf.org/html/rfc3261#section-8.2.6 - * @internal - */ -function constructOutgoingResponse(message, options) { - var CRLF = "\r\n"; - if (options.statusCode < 100 || options.statusCode > 699) { - throw new TypeError("Invalid statusCode: " + options.statusCode); - } - var reasonPhrase = options.reasonPhrase ? options.reasonPhrase : utils_1.getReasonPhrase(options.statusCode); - // SIP responses are distinguished from requests by having a Status-Line - // as their start-line. A Status-Line consists of the protocol version - // followed by a numeric Status-Code and its associated textual phrase, - // with each element separated by a single SP character. - // https://tools.ietf.org/html/rfc3261#section-7.2 - var response = "SIP/2.0 " + options.statusCode + " " + reasonPhrase + CRLF; - // One largely non-method-specific guideline for the generation of - // responses is that UASs SHOULD NOT issue a provisional response for a - // non-INVITE request. Rather, UASs SHOULD generate a final response to - // a non-INVITE request as soon as possible. - // https://tools.ietf.org/html/rfc3261#section-8.2.6.1 - if (options.statusCode >= 100 && options.statusCode < 200) { - // TODO - } - // When a 100 (Trying) response is generated, any Timestamp header field - // present in the request MUST be copied into this 100 (Trying) - // response. If there is a delay in generating the response, the UAS - // SHOULD add a delay value into the Timestamp value in the response. - // This value MUST contain the difference between the time of sending of - // the response and receipt of the request, measured in seconds. - // https://tools.ietf.org/html/rfc3261#section-8.2.6.1 - if (options.statusCode === 100) { - // TODO - } - // The From field of the response MUST equal the From header field of - // the request. The Call-ID header field of the response MUST equal the - // Call-ID header field of the request. The CSeq header field of the - // response MUST equal the CSeq field of the request. The Via header - // field values in the response MUST equal the Via header field values - // in the request and MUST maintain the same ordering. - // https://tools.ietf.org/html/rfc3261#section-8.2.6.2 - var fromHeader = "From: " + message.getHeader("From") + CRLF; - var callIdHeader = "Call-ID: " + message.callId + CRLF; - var cSeqHeader = "CSeq: " + message.cseq + " " + message.method + CRLF; - var viaHeaders = message.getHeaders("via").reduce(function (previous, current) { - return previous + "Via: " + current + CRLF; - }, ""); - // If a request contained a To tag in the request, the To header field - // in the response MUST equal that of the request. However, if the To - // header field in the request did not contain a tag, the URI in the To - // header field in the response MUST equal the URI in the To header - // field; additionally, the UAS MUST add a tag to the To header field in - // the response (with the exception of the 100 (Trying) response, in - // which a tag MAY be present). This serves to identify the UAS that is - // responding, possibly resulting in a component of a dialog ID. The - // same tag MUST be used for all responses to that request, both final - // and provisional (again excepting the 100 (Trying)). - // https://tools.ietf.org/html/rfc3261#section-8.2.6.2 - var toHeader = "To: " + message.getHeader("to"); - if (options.statusCode > 100 && !message.parseHeader("to").hasParam("tag")) { - var toTag = options.toTag; - if (!toTag) { - // Stateless UAS Behavior... - // o To header tags MUST be generated for responses in a stateless - // manner - in a manner that will generate the same tag for the - // same request consistently. For information on tag construction - // see Section 19.3. - // https://tools.ietf.org/html/rfc3261#section-8.2.7 - toTag = utils_1.newTag(); // FIXME: newTag() currently generates random tags - } - toHeader += ";tag=" + toTag; - } - toHeader += CRLF; - // FIXME: TODO: needs review... moved to InviteUserAgentServer (as it is specific to that) - // let recordRouteHeaders = ""; - // if (request.method === C.INVITE && statusCode > 100 && statusCode <= 200) { - // recordRouteHeaders = request.getHeaders("record-route").reduce((previous, current) => { - // return previous + "Record-Route: " + current + CRLF; - // }, ""); - // } - // FIXME: TODO: needs review... - var supportedHeader = ""; - if (options.supported) { - supportedHeader = "Supported: " + options.supported.join(", ") + CRLF; - } - // FIXME: TODO: needs review... - var userAgentHeader = ""; - if (options.userAgent) { - userAgentHeader = "User-Agent: " + options.userAgent + CRLF; - } - var extensionHeaders = ""; - if (options.extraHeaders) { - extensionHeaders = options.extraHeaders.reduce(function (previous, current) { - return previous + current.trim() + CRLF; - }, ""); - } - // The relative order of header fields with different field names is not - // significant. However, it is RECOMMENDED that header fields which are - // needed for proxy processing (Via, Route, Record-Route, Proxy-Require, - // Max-Forwards, and Proxy-Authorization, for example) appear towards - // the top of the message to facilitate rapid parsing. - // https://tools.ietf.org/html/rfc3261#section-7.3.1 - // response += recordRouteHeaders; - response += viaHeaders; - response += fromHeader; - response += toHeader; - response += cSeqHeader; - response += callIdHeader; - response += supportedHeader; - response += userAgentHeader; - response += extensionHeaders; - if (options.body) { - response += "Content-Type: " + options.body.contentType + CRLF; - response += "Content-Length: " + utils_1.str_utf8_length(options.body.content) + CRLF + CRLF; - response += options.body.content; - } - else { - response += "Content-Length: " + 0 + CRLF + CRLF; - } - return { message: response }; -} -exports.constructOutgoingResponse = constructOutgoingResponse; - - -/***/ }), -/* 23 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var session_1 = __webpack_require__(24); -var timers_1 = __webpack_require__(26); -var transactions_1 = __webpack_require__(27); -var bye_user_agent_client_1 = __webpack_require__(41); -var bye_user_agent_server_1 = __webpack_require__(43); -var info_user_agent_client_1 = __webpack_require__(45); -var info_user_agent_server_1 = __webpack_require__(46); -var notify_user_agent_client_1 = __webpack_require__(47); -var notify_user_agent_server_1 = __webpack_require__(48); -var prack_user_agent_client_1 = __webpack_require__(49); -var prack_user_agent_server_1 = __webpack_require__(50); -var re_invite_user_agent_client_1 = __webpack_require__(51); -var re_invite_user_agent_server_1 = __webpack_require__(52); -var refer_user_agent_client_1 = __webpack_require__(53); -var refer_user_agent_server_1 = __webpack_require__(54); -var dialog_1 = __webpack_require__(4); -/** - * Session Dialog. - * @public - */ -var SessionDialog = /** @class */ (function (_super) { - tslib_1.__extends(SessionDialog, _super); - function SessionDialog(initialTransaction, core, state, delegate) { - var _this = _super.call(this, core, state) || this; - _this.initialTransaction = initialTransaction; - /** The state of the offer/answer exchange. */ - _this._signalingState = session_1.SignalingState.Initial; - /** True if waiting for an ACK to the initial transaction 2xx (UAS only). */ - _this.ackWait = false; - _this.delegate = delegate; - if (initialTransaction instanceof transactions_1.InviteServerTransaction) { - // If we're created by an invite server transaction, we're - // going to be waiting for an ACK if are to be confirmed. - _this.ackWait = true; - } - // If we're confirmed upon creation start the retransmitting whatever - // the 2xx final response was that confirmed us into existence. - if (!_this.early) { - _this.start2xxRetransmissionTimer(); - } - _this.signalingStateTransition(initialTransaction.request); - _this.logger = core.loggerFactory.getLogger("sip.invite-dialog"); - _this.logger.log("INVITE dialog " + _this.id + " constructed"); - return _this; - } - SessionDialog.prototype.dispose = function () { - _super.prototype.dispose.call(this); - this._signalingState = session_1.SignalingState.Closed; - this._offer = undefined; - this._answer = undefined; - if (this.invite2xxTimer) { - clearTimeout(this.invite2xxTimer); - this.invite2xxTimer = undefined; - } - // The UAS MUST still respond to any pending requests received for that - // dialog. It is RECOMMENDED that a 487 (Request Terminated) response - // be generated to those pending requests. - // https://tools.ietf.org/html/rfc3261#section-15.1.2 - // TODO: - // this.userAgentServers.forEach((uas) => uas.reply(487)); - this.logger.log("INVITE dialog " + this.id + " destroyed"); - }; - Object.defineProperty(SessionDialog.prototype, "sessionState", { - // FIXME: Need real state machine - get: function () { - if (this.early) { - return session_1.SessionState.Early; - } - else if (this.ackWait) { - return session_1.SessionState.AckWait; - } - else if (this._signalingState === session_1.SignalingState.Closed) { - return session_1.SessionState.Terminated; - } - else { - return session_1.SessionState.Confirmed; - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SessionDialog.prototype, "signalingState", { - /** The state of the offer/answer exchange. */ - get: function () { - return this._signalingState; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SessionDialog.prototype, "offer", { - /** The current offer. Undefined unless signaling state HaveLocalOffer, HaveRemoteOffer, of Stable. */ - get: function () { - return this._offer; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SessionDialog.prototype, "answer", { - /** The current answer. Undefined unless signaling state Stable. */ - get: function () { - return this._answer; - }, - enumerable: true, - configurable: true - }); - /** Confirm the dialog. Only matters if dialog is currently early. */ - SessionDialog.prototype.confirm = function () { - // When we're confirmed start the retransmitting whatever - // the 2xx final response that may have confirmed us. - if (this.early) { - this.start2xxRetransmissionTimer(); - } - _super.prototype.confirm.call(this); - }; - /** Re-confirm the dialog. Only matters if handling re-INVITE request. */ - SessionDialog.prototype.reConfirm = function () { - // When we're confirmed start the retransmitting whatever - // the 2xx final response that may have confirmed us. - if (this.reinviteUserAgentServer) { - this.startReInvite2xxRetransmissionTimer(); - } - }; - /** - * The UAC core MUST generate an ACK request for each 2xx received from - * the transaction layer. The header fields of the ACK are constructed - * in the same way as for any request sent within a dialog (see Section - * 12) with the exception of the CSeq and the header fields related to - * authentication. The sequence number of the CSeq header field MUST be - * the same as the INVITE being acknowledged, but the CSeq method MUST - * be ACK. The ACK MUST contain the same credentials as the INVITE. If - * the 2xx contains an offer (based on the rules above), the ACK MUST - * carry an answer in its body. If the offer in the 2xx response is not - * acceptable, the UAC core MUST generate a valid answer in the ACK and - * then send a BYE immediately. - * https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - * @param options - ACK options bucket. - */ - SessionDialog.prototype.ack = function (options) { - if (options === void 0) { options = {}; } - this.logger.log("INVITE dialog " + this.id + " sending ACK request"); - var transaction; - if (this.reinviteUserAgentClient) { - // We're sending ACK for a re-INVITE - if (!(this.reinviteUserAgentClient.transaction instanceof transactions_1.InviteClientTransaction)) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - transaction = this.reinviteUserAgentClient.transaction; - this.reinviteUserAgentClient = undefined; - } - else { - // We're sending ACK for the initial INVITE - if (!(this.initialTransaction instanceof transactions_1.InviteClientTransaction)) { - throw new Error("Initial transaction not instance of InviteClientTransaction."); - } - transaction = this.initialTransaction; - } - options.cseq = transaction.request.cseq; // ACK cseq is INVITE cseq - var message = this.createOutgoingRequestMessage(messages_1.C.ACK, options); - transaction.ackResponse(message); // See InviteClientTransaction for details. - this.signalingStateTransition(message); - return { message: message }; - }; - /** - * Terminating a Session - * - * This section describes the procedures for terminating a session - * established by SIP. The state of the session and the state of the - * dialog are very closely related. When a session is initiated with an - * INVITE, each 1xx or 2xx response from a distinct UAS creates a - * dialog, and if that response completes the offer/answer exchange, it - * also creates a session. As a result, each session is "associated" - * with a single dialog - the one which resulted in its creation. If an - * initial INVITE generates a non-2xx final response, that terminates - * all sessions (if any) and all dialogs (if any) that were created - * through responses to the request. By virtue of completing the - * transaction, a non-2xx final response also prevents further sessions - * from being created as a result of the INVITE. The BYE request is - * used to terminate a specific session or attempted session. In this - * case, the specific session is the one with the peer UA on the other - * side of the dialog. When a BYE is received on a dialog, any session - * associated with that dialog SHOULD terminate. A UA MUST NOT send a - * BYE outside of a dialog. The caller's UA MAY send a BYE for either - * confirmed or early dialogs, and the callee's UA MAY send a BYE on - * confirmed dialogs, but MUST NOT send a BYE on early dialogs. - * - * However, the callee's UA MUST NOT send a BYE on a confirmed dialog - * until it has received an ACK for its 2xx response or until the server - * transaction times out. If no SIP extensions have defined other - * application layer states associated with the dialog, the BYE also - * terminates the dialog. - * - * https://tools.ietf.org/html/rfc3261#section-15 - * FIXME: Make these proper Exceptions... - * @param options - BYE options bucket. - * @returns - * Throws `Error` if callee's UA attempts a BYE on an early dialog. - * Throws `Error` if callee's UA attempts a BYE on a confirmed dialog - * while it's waiting on the ACK for its 2xx response. - */ - SessionDialog.prototype.bye = function (delegate, options) { - this.logger.log("INVITE dialog " + this.id + " sending BYE request"); - // The caller's UA MAY send a BYE for either - // confirmed or early dialogs, and the callee's UA MAY send a BYE on - // confirmed dialogs, but MUST NOT send a BYE on early dialogs. - // - // However, the callee's UA MUST NOT send a BYE on a confirmed dialog - // until it has received an ACK for its 2xx response or until the server - // transaction times out. - // https://tools.ietf.org/html/rfc3261#section-15 - if (this.initialTransaction instanceof transactions_1.InviteServerTransaction) { - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("UAS MUST NOT send a BYE on early dialogs."); - } - if (this.ackWait && this.initialTransaction.state !== transactions_1.TransactionState.Terminated) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("UAS MUST NOT send a BYE on a confirmed dialog " + - "until it has received an ACK for its 2xx response " + - "or until the server transaction times out."); - } - } - // A BYE request is constructed as would any other request within a - // dialog, as described in Section 12. - // - // Once the BYE is constructed, the UAC core creates a new non-INVITE - // client transaction, and passes it the BYE request. The UAC MUST - // consider the session terminated (and therefore stop sending or - // listening for media) as soon as the BYE request is passed to the - // client transaction. If the response for the BYE is a 481 - // (Call/Transaction Does Not Exist) or a 408 (Request Timeout) or no - // response at all is received for the BYE (that is, a timeout is - // returned by the client transaction), the UAC MUST consider the - // session and the dialog terminated. - // https://tools.ietf.org/html/rfc3261#section-15.1.1 - return new bye_user_agent_client_1.ByeUserAgentClient(this, delegate, options); - }; - /** - * An INFO request can be associated with an Info Package (see - * Section 5), or associated with a legacy INFO usage (see Section 2). - * - * The construction of the INFO request is the same as any other - * non-target refresh request within an existing invite dialog usage as - * described in Section 12.2 of RFC 3261. - * https://tools.ietf.org/html/rfc6086#section-4.2.1 - * @param options - Options bucket. - */ - SessionDialog.prototype.info = function (delegate, options) { - this.logger.log("INVITE dialog " + this.id + " sending INFO request"); - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("Dialog not confirmed."); - } - return new info_user_agent_client_1.InfoUserAgentClient(this, delegate, options); - }; - /** - * Modifying an Existing Session - * - * A successful INVITE request (see Section 13) establishes both a - * dialog between two user agents and a session using the offer-answer - * model. Section 12 explains how to modify an existing dialog using a - * target refresh request (for example, changing the remote target URI - * of the dialog). This section describes how to modify the actual - * session. This modification can involve changing addresses or ports, - * adding a media stream, deleting a media stream, and so on. This is - * accomplished by sending a new INVITE request within the same dialog - * that established the session. An INVITE request sent within an - * existing dialog is known as a re-INVITE. - * - * Note that a single re-INVITE can modify the dialog and the - * parameters of the session at the same time. - * - * Either the caller or callee can modify an existing session. - * https://tools.ietf.org/html/rfc3261#section-14 - * @param options - Options bucket - */ - SessionDialog.prototype.invite = function (delegate, options) { - this.logger.log("INVITE dialog " + this.id + " sending INVITE request"); - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("Dialog not confirmed."); - } - // Note that a UAC MUST NOT initiate a new INVITE transaction within a - // dialog while another INVITE transaction is in progress in either - // direction. - // - // 1. If there is an ongoing INVITE client transaction, the TU MUST - // wait until the transaction reaches the completed or terminated - // state before initiating the new INVITE. - // - // 2. If there is an ongoing INVITE server transaction, the TU MUST - // wait until the transaction reaches the confirmed or terminated - // state before initiating the new INVITE. - // - // However, a UA MAY initiate a regular transaction while an INVITE - // transaction is in progress. A UA MAY also initiate an INVITE - // transaction while a regular transaction is in progress. - // https://tools.ietf.org/html/rfc3261#section-14.1 - if (this.reinviteUserAgentClient) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("There is an ongoing re-INVITE client transaction."); - } - if (this.reinviteUserAgentServer) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("There is an ongoing re-INVITE server transaction."); - } - return new re_invite_user_agent_client_1.ReInviteUserAgentClient(this, delegate, options); - }; - /** - * The NOTIFY mechanism defined in [2] MUST be used to inform the agent - * sending the REFER of the status of the reference. - * https://tools.ietf.org/html/rfc3515#section-2.4.4 - * @param options - Options bucket. - */ - SessionDialog.prototype.notify = function (delegate, options) { - this.logger.log("INVITE dialog " + this.id + " sending NOTIFY request"); - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("Dialog not confirmed."); - } - return new notify_user_agent_client_1.NotifyUserAgentClient(this, delegate, options); - }; - /** - * Assuming the response is to be transmitted reliably, the UAC MUST - * create a new request with method PRACK. This request is sent within - * the dialog associated with the provisional response (indeed, the - * provisional response may have created the dialog). PRACK requests - * MAY contain bodies, which are interpreted according to their type and - * disposition. - * https://tools.ietf.org/html/rfc3262#section-4 - * @param options - Options bucket. - */ - SessionDialog.prototype.prack = function (delegate, options) { - this.logger.log("INVITE dialog " + this.id + " sending PRACK request"); - return new prack_user_agent_client_1.PrackUserAgentClient(this, delegate, options); - }; - /** - * REFER is a SIP request and is constructed as defined in [1]. A REFER - * request MUST contain exactly one Refer-To header field value. - * https://tools.ietf.org/html/rfc3515#section-2.4.1 - * @param options - Options bucket. - */ - SessionDialog.prototype.refer = function (delegate, options) { - this.logger.log("INVITE dialog " + this.id + " sending REFER request"); - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("Dialog not confirmed."); - } - // FIXME: TODO: Validate Refer-To header field value. - return new refer_user_agent_client_1.ReferUserAgentClient(this, delegate, options); - }; - /** - * Requests sent within a dialog, as any other requests, are atomic. If - * a particular request is accepted by the UAS, all the state changes - * associated with it are performed. If the request is rejected, none - * of the state changes are performed. - * https://tools.ietf.org/html/rfc3261#section-12.2.2 - * @param message - Incoming request message within this dialog. - */ - SessionDialog.prototype.receiveRequest = function (message) { - this.logger.log("INVITE dialog " + this.id + " received " + message.method + " request"); - // Response retransmissions cease when an ACK request for the - // response is received. This is independent of whatever transport - // protocols are used to send the response. - // https://tools.ietf.org/html/rfc6026#section-8.1 - if (message.method === messages_1.C.ACK) { - // If ackWait is true, then this is the ACK to the initial INVITE, - // otherwise this is an ACK to an in dialog INVITE. In either case, - // guard to make sure the sequence number of the ACK matches the INVITE. - if (this.ackWait) { - if (this.initialTransaction instanceof transactions_1.InviteClientTransaction) { - this.logger.warn("INVITE dialog " + this.id + " received unexpected " + message.method + " request, dropping."); - return; - } - if (this.initialTransaction.request.cseq !== message.cseq) { - this.logger.warn("INVITE dialog " + this.id + " received unexpected " + message.method + " request, dropping."); - return; - } - // Update before the delegate has a chance to handle the - // message as delegate may callback into this dialog. - this.ackWait = false; - } - else { - if (!this.reinviteUserAgentServer) { - this.logger.warn("INVITE dialog " + this.id + " received unexpected " + message.method + " request, dropping."); - return; - } - if (this.reinviteUserAgentServer.transaction.request.cseq !== message.cseq) { - this.logger.warn("INVITE dialog " + this.id + " received unexpected " + message.method + " request, dropping."); - return; - } - this.reinviteUserAgentServer = undefined; - } - this.signalingStateTransition(message); - if (this.delegate && this.delegate.onAck) { - this.delegate.onAck({ message: message }); - } - return; - } - // Request within a dialog out of sequence guard. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (!this.sequenceGuard(message)) { - this.logger.log("INVITE dialog " + this.id + " rejected out of order " + message.method + " request."); - return; - } - if (message.method === messages_1.C.INVITE) { - // A UAS that receives a second INVITE before it sends the final - // response to a first INVITE with a lower CSeq sequence number on the - // same dialog MUST return a 500 (Server Internal Error) response to the - // second INVITE and MUST include a Retry-After header field with a - // randomly chosen value of between 0 and 10 seconds. - // https://tools.ietf.org/html/rfc3261#section-14.2 - if (this.reinviteUserAgentServer) { - // https://tools.ietf.org/html/rfc3261#section-20.33 - var retryAfter = Math.floor((Math.random() * 10)) + 1; - var extraHeaders = ["Retry-After: " + retryAfter]; - this.core.replyStateless(message, { statusCode: 500, extraHeaders: extraHeaders }); - return; - } - // A UAS that receives an INVITE on a dialog while an INVITE it had sent - // on that dialog is in progress MUST return a 491 (Request Pending) - // response to the received INVITE. - // https://tools.ietf.org/html/rfc3261#section-14.2 - if (this.reinviteUserAgentClient) { - this.core.replyStateless(message, { statusCode: 491 }); - return; - } - } - // Request within a dialog common processing. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - _super.prototype.receiveRequest.call(this, message); - // Requests within a dialog MAY contain Record-Route and Contact header - // fields. However, these requests do not cause the dialog's route set - // to be modified, although they may modify the remote target URI. - // Specifically, requests that are not target refresh requests do not - // modify the dialog's remote target URI, and requests that are target - // refresh requests do. For dialogs that have been established with an - // INVITE, the only target refresh request defined is re-INVITE (see - // Section 14). Other extensions may define different target refresh - // requests for dialogs established in other ways. - // - // Note that an ACK is NOT a target refresh request. - // - // Target refresh requests only update the dialog's remote target URI, - // and not the route set formed from the Record-Route. Updating the - // latter would introduce severe backwards compatibility problems with - // RFC 2543-compliant systems. - // https://tools.ietf.org/html/rfc3261#section-15 - if (message.method === messages_1.C.INVITE) { - // FIXME: parser needs to be typed... - var contact = message.parseHeader("contact"); - if (!contact) { // TODO: Review to make sure this will never happen - throw new Error("Contact undefined."); - } - if (!(contact instanceof messages_1.NameAddrHeader)) { - throw new Error("Contact not instance of NameAddrHeader."); - } - this.dialogState.remoteTarget = contact.uri; - } - // Switch on method and then delegate. - switch (message.method) { - case messages_1.C.BYE: - // A UAS core receiving a BYE request for an existing dialog MUST follow - // the procedures of Section 12.2.2 to process the request. Once done, - // the UAS SHOULD terminate the session (and therefore stop sending and - // listening for media). The only case where it can elect not to are - // multicast sessions, where participation is possible even if the other - // participant in the dialog has terminated its involvement in the - // session. Whether or not it ends its participation on the session, - // the UAS core MUST generate a 2xx response to the BYE, and MUST pass - // that to the server transaction for transmission. - // - // The UAS MUST still respond to any pending requests received for that - // dialog. It is RECOMMENDED that a 487 (Request Terminated) response - // be generated to those pending requests. - // https://tools.ietf.org/html/rfc3261#section-15.1.2 - { - var uas = new bye_user_agent_server_1.ByeUserAgentServer(this, message); - this.delegate && this.delegate.onBye ? - this.delegate.onBye(uas) : - uas.accept(); - this.dispose(); - } - break; - case messages_1.C.INFO: - // If a UA receives an INFO request associated with an Info Package that - // the UA has not indicated willingness to receive, the UA MUST send a - // 469 (Bad Info Package) response (see Section 11.6), which contains a - // Recv-Info header field with Info Packages for which the UA is willing - // to receive INFO requests. - { - var uas = new info_user_agent_server_1.InfoUserAgentServer(this, message); - this.delegate && this.delegate.onInfo ? - this.delegate.onInfo(uas) : - uas.reject({ - statusCode: 469, - extraHeaders: ["Recv-Info :"] - }); - } - break; - case messages_1.C.INVITE: - // If the new session description is not acceptable, the UAS can reject - // it by returning a 488 (Not Acceptable Here) response for the re- - // INVITE. This response SHOULD include a Warning header field. - // https://tools.ietf.org/html/rfc3261#section-14.2 - { - var uas = new re_invite_user_agent_server_1.ReInviteUserAgentServer(this, message); - this.signalingStateTransition(message); - this.delegate && this.delegate.onInvite ? - this.delegate.onInvite(uas) : - uas.reject({ statusCode: 488 }); // TODO: Warning header field. - } - break; - case messages_1.C.NOTIFY: - // https://tools.ietf.org/html/rfc3515#section-2.4.4 - { - var uas = new notify_user_agent_server_1.NotifyUserAgentServer(this, message); - this.delegate && this.delegate.onNotify ? - this.delegate.onNotify(uas) : - uas.accept(); - } - break; - case messages_1.C.PRACK: - // https://tools.ietf.org/html/rfc3262#section-4 - { - var uas = new prack_user_agent_server_1.PrackUserAgentServer(this, message); - this.delegate && this.delegate.onPrack ? - this.delegate.onPrack(uas) : - uas.accept(); - } - break; - case messages_1.C.REFER: - // https://tools.ietf.org/html/rfc3515#section-2.4.2 - { - var uas = new refer_user_agent_server_1.ReferUserAgentServer(this, message); - this.delegate && this.delegate.onRefer ? - this.delegate.onRefer(uas) : - uas.reject(); - } - break; - default: - { - this.logger.log("INVITE dialog " + this.id + " received unimplemented " + message.method + " request"); - this.core.replyStateless(message, { statusCode: 501 }); - } - break; - } - }; - SessionDialog.prototype.reliableSequenceGuard = function (message) { - var statusCode = message.statusCode; - if (!statusCode) { - throw new Error("Status code undefined"); - } - if (statusCode > 100 && statusCode < 200) { - // If a provisional response is received for an initial request, and - // that response contains a Require header field containing the option - // tag 100rel, the response is to be sent reliably. If the response is - // a 100 (Trying) (as opposed to 101 to 199), this option tag MUST be - // ignored, and the procedures below MUST NOT be used. - // https://tools.ietf.org/html/rfc3262#section-4 - var requireHeader = message.getHeader("require"); - var rseqHeader = message.getHeader("rseq"); - var rseq = requireHeader && requireHeader.includes("100rel") && rseqHeader ? Number(rseqHeader) : undefined; - if (rseq) { - // Handling of subsequent reliable provisional responses for the same - // initial request follows the same rules as above, with the following - // difference: reliable provisional responses are guaranteed to be in - // order. As a result, if the UAC receives another reliable provisional - // response to the same request, and its RSeq value is not one higher - // than the value of the sequence number, that response MUST NOT be - // acknowledged with a PRACK, and MUST NOT be processed further by the - // UAC. An implementation MAY discard the response, or MAY cache the - // response in the hopes of receiving the missing responses. - // https://tools.ietf.org/html/rfc3262#section-4 - if (this.rseq && this.rseq + 1 !== rseq) { - return false; - } - // Once a reliable provisional response is received, retransmissions of - // that response MUST be discarded. A response is a retransmission when - // its dialog ID, CSeq, and RSeq match the original response. The UAC - // MUST maintain a sequence number that indicates the most recently - // received in-order reliable provisional response for the initial - // request. This sequence number MUST be maintained until a final - // response is received for the initial request. Its value MUST be - // initialized to the RSeq header field in the first reliable - // provisional response received for the initial request. - // https://tools.ietf.org/html/rfc3262#section-4 - if (!this.rseq) { - this.rseq = rseq; - } - } - } - return true; - }; - /** - * If not in a stable signaling state, rollback to prior stable signaling state. - */ - SessionDialog.prototype.signalingStateRollback = function () { - if (this._signalingState === session_1.SignalingState.HaveLocalOffer || - this.signalingState === session_1.SignalingState.HaveRemoteOffer) { - if (this._rollbackOffer && this._rollbackAnswer) { - this._signalingState = session_1.SignalingState.Stable; - this._offer = this._rollbackOffer; - this._answer = this._rollbackAnswer; - } - } - }; - /** - * Update the signaling state of the dialog. - * @param message - The message to base the update off of. - */ - SessionDialog.prototype.signalingStateTransition = function (message) { - var body = messages_1.getBody(message); - // No body, no session. No, woman, no cry. - if (!body || body.contentDisposition !== "session") { - return; - } - // We've got an existing offer and answer which we may wish to rollback to - if (this._signalingState === session_1.SignalingState.Stable) { - this._rollbackOffer = this._offer; - this._rollbackAnswer = this._answer; - } - // We're in UAS role, receiving incoming request with session description - if (message instanceof messages_1.IncomingRequestMessage) { - switch (this._signalingState) { - case session_1.SignalingState.Initial: - case session_1.SignalingState.Stable: - this._signalingState = session_1.SignalingState.HaveRemoteOffer; - this._offer = body; - this._answer = undefined; - break; - case session_1.SignalingState.HaveLocalOffer: - this._signalingState = session_1.SignalingState.Stable; - this._answer = body; - break; - case session_1.SignalingState.HaveRemoteOffer: - // You cannot make a new offer while one is in progress. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // FIXME: What to do here? - break; - case session_1.SignalingState.Closed: - break; - default: - throw new Error("Unexpected signaling state."); - } - } - // We're in UAC role, receiving incoming response with session description - if (message instanceof messages_1.IncomingResponseMessage) { - switch (this._signalingState) { - case session_1.SignalingState.Initial: - case session_1.SignalingState.Stable: - this._signalingState = session_1.SignalingState.HaveRemoteOffer; - this._offer = body; - this._answer = undefined; - break; - case session_1.SignalingState.HaveLocalOffer: - this._signalingState = session_1.SignalingState.Stable; - this._answer = body; - break; - case session_1.SignalingState.HaveRemoteOffer: - // You cannot make a new offer while one is in progress. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // FIXME: What to do here? - break; - case session_1.SignalingState.Closed: - break; - default: - throw new Error("Unexpected signaling state."); - } - } - // We're in UAC role, sending outgoing request with session description - if (message instanceof messages_1.OutgoingRequestMessage) { - switch (this._signalingState) { - case session_1.SignalingState.Initial: - case session_1.SignalingState.Stable: - this._signalingState = session_1.SignalingState.HaveLocalOffer; - this._offer = body; - this._answer = undefined; - break; - case session_1.SignalingState.HaveLocalOffer: - // You cannot make a new offer while one is in progress. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // FIXME: What to do here? - break; - case session_1.SignalingState.HaveRemoteOffer: - this._signalingState = session_1.SignalingState.Stable; - this._answer = body; - break; - case session_1.SignalingState.Closed: - break; - default: - throw new Error("Unexpected signaling state."); - } - } - // We're in UAS role, sending outgoing response with session description - if (messages_1.isBody(message)) { - switch (this._signalingState) { - case session_1.SignalingState.Initial: - case session_1.SignalingState.Stable: - this._signalingState = session_1.SignalingState.HaveLocalOffer; - this._offer = body; - this._answer = undefined; - break; - case session_1.SignalingState.HaveLocalOffer: - // You cannot make a new offer while one is in progress. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // FIXME: What to do here? - break; - case session_1.SignalingState.HaveRemoteOffer: - this._signalingState = session_1.SignalingState.Stable; - this._answer = body; - break; - case session_1.SignalingState.Closed: - break; - default: - throw new Error("Unexpected signaling state."); - } - } - }; - SessionDialog.prototype.start2xxRetransmissionTimer = function () { - var _this = this; - if (this.initialTransaction instanceof transactions_1.InviteServerTransaction) { - var transaction_1 = this.initialTransaction; - // Once the response has been constructed, it is passed to the INVITE - // server transaction. In order to ensure reliable end-to-end - // transport of the response, it is necessary to periodically pass - // the response directly to the transport until the ACK arrives. The - // 2xx response is passed to the transport with an interval that - // starts at T1 seconds and doubles for each retransmission until it - // reaches T2 seconds (T1 and T2 are defined in Section 17). - // Response retransmissions cease when an ACK request for the - // response is received. This is independent of whatever transport - // protocols are used to send the response. - // https://tools.ietf.org/html/rfc6026#section-8.1 - var timeout_1 = timers_1.Timers.T1; - var retransmission_1 = function () { - if (!_this.ackWait) { - _this.invite2xxTimer = undefined; - return; - } - _this.logger.log("No ACK for 2xx response received, attempting retransmission"); - transaction_1.retransmitAcceptedResponse(); - timeout_1 = Math.min(timeout_1 * 2, timers_1.Timers.T2); - _this.invite2xxTimer = setTimeout(retransmission_1, timeout_1); - }; - this.invite2xxTimer = setTimeout(retransmission_1, timeout_1); - // If the server retransmits the 2xx response for 64*T1 seconds without - // receiving an ACK, the dialog is confirmed, but the session SHOULD be - // terminated. This is accomplished with a BYE, as described in Section 15. - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - var stateChanged_1 = function () { - if (transaction_1.state === transactions_1.TransactionState.Terminated) { - transaction_1.removeListener("stateChanged", stateChanged_1); - if (_this.invite2xxTimer) { - clearTimeout(_this.invite2xxTimer); - _this.invite2xxTimer = undefined; - } - if (_this.ackWait) { - if (_this.delegate && _this.delegate.onAckTimeout) { - _this.delegate.onAckTimeout(); - } - else { - _this.bye(); - } - } - } - }; - transaction_1.addListener("stateChanged", stateChanged_1); - } - }; - // FIXME: Refactor - SessionDialog.prototype.startReInvite2xxRetransmissionTimer = function () { - var _this = this; - if (this.reinviteUserAgentServer && this.reinviteUserAgentServer.transaction instanceof transactions_1.InviteServerTransaction) { - var transaction_2 = this.reinviteUserAgentServer.transaction; - // Once the response has been constructed, it is passed to the INVITE - // server transaction. In order to ensure reliable end-to-end - // transport of the response, it is necessary to periodically pass - // the response directly to the transport until the ACK arrives. The - // 2xx response is passed to the transport with an interval that - // starts at T1 seconds and doubles for each retransmission until it - // reaches T2 seconds (T1 and T2 are defined in Section 17). - // Response retransmissions cease when an ACK request for the - // response is received. This is independent of whatever transport - // protocols are used to send the response. - // https://tools.ietf.org/html/rfc6026#section-8.1 - var timeout_2 = timers_1.Timers.T1; - var retransmission_2 = function () { - if (!_this.reinviteUserAgentServer) { - _this.invite2xxTimer = undefined; - return; - } - _this.logger.log("No ACK for 2xx response received, attempting retransmission"); - transaction_2.retransmitAcceptedResponse(); - timeout_2 = Math.min(timeout_2 * 2, timers_1.Timers.T2); - _this.invite2xxTimer = setTimeout(retransmission_2, timeout_2); - }; - this.invite2xxTimer = setTimeout(retransmission_2, timeout_2); - // If the server retransmits the 2xx response for 64*T1 seconds without - // receiving an ACK, the dialog is confirmed, but the session SHOULD be - // terminated. This is accomplished with a BYE, as described in Section 15. - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - var stateChanged_2 = function () { - if (transaction_2.state === transactions_1.TransactionState.Terminated) { - transaction_2.removeListener("stateChanged", stateChanged_2); - if (_this.invite2xxTimer) { - clearTimeout(_this.invite2xxTimer); - _this.invite2xxTimer = undefined; - } - if (_this.reinviteUserAgentServer) { - // FIXME: TODO: What to do here - } - } - }; - transaction_2.addListener("stateChanged", stateChanged_2); - } - }; - return SessionDialog; -}(dialog_1.Dialog)); -exports.SessionDialog = SessionDialog; - - -/***/ }), -/* 24 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -tslib_1.__exportStar(__webpack_require__(25), exports); - - -/***/ }), -/* 25 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * Session state. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-13 - * @public - */ -var SessionState; -(function (SessionState) { - SessionState["Initial"] = "Initial"; - SessionState["Early"] = "Early"; - SessionState["AckWait"] = "AckWait"; - SessionState["Confirmed"] = "Confirmed"; - SessionState["Terminated"] = "Terminated"; -})(SessionState = exports.SessionState || (exports.SessionState = {})); -/** - * Offer/Answer state. - * @remarks - * ```txt - * Offer Answer RFC Ini Est Early - * ------------------------------------------------------------------- - * 1. INVITE Req. 2xx INVITE Resp. RFC 3261 Y Y N - * 2. 2xx INVITE Resp. ACK Req. RFC 3261 Y Y N - * 3. INVITE Req. 1xx-rel INVITE Resp. RFC 3262 Y Y N - * 4. 1xx-rel INVITE Resp. PRACK Req. RFC 3262 Y Y N - * 5. PRACK Req. 200 PRACK Resp. RFC 3262 N Y Y - * 6. UPDATE Req. 2xx UPDATE Resp. RFC 3311 N Y Y - * - * Table 1: Summary of SIP Usage of the Offer/Answer Model - * ``` - * https://tools.ietf.org/html/rfc6337#section-2.2 - * @public - */ -var SignalingState; -(function (SignalingState) { - SignalingState["Initial"] = "Initial"; - SignalingState["HaveLocalOffer"] = "HaveLocalOffer"; - SignalingState["HaveRemoteOffer"] = "HaveRemoteOffer"; - SignalingState["Stable"] = "Stable"; - SignalingState["Closed"] = "Closed"; -})(SignalingState = exports.SignalingState || (exports.SignalingState = {})); - - -/***/ }), -/* 26 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var T1 = 500; -var T2 = 4000; -var T4 = 5000; -/** - * Timers. - * @public - */ -exports.Timers = { - T1: T1, - T2: T2, - T4: T4, - TIMER_B: 64 * T1, - TIMER_D: 0 * T1, - TIMER_F: 64 * T1, - TIMER_H: 64 * T1, - TIMER_I: 0 * T4, - TIMER_J: 0 * T1, - TIMER_K: 0 * T4, - TIMER_L: 64 * T1, - TIMER_M: 64 * T1, - TIMER_N: 64 * T1, - PROVISIONAL_RESPONSE_INTERVAL: 60000 // See RFC 3261 Section 13.3.1.1 -}; - - -/***/ }), -/* 27 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -tslib_1.__exportStar(__webpack_require__(28), exports); -tslib_1.__exportStar(__webpack_require__(35), exports); -tslib_1.__exportStar(__webpack_require__(37), exports); -tslib_1.__exportStar(__webpack_require__(39), exports); -tslib_1.__exportStar(__webpack_require__(40), exports); -tslib_1.__exportStar(__webpack_require__(35), exports); -tslib_1.__exportStar(__webpack_require__(38), exports); -tslib_1.__exportStar(__webpack_require__(36), exports); -tslib_1.__exportStar(__webpack_require__(29), exports); - - -/***/ }), -/* 28 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transaction_1 = __webpack_require__(29); -/** - * Client Transaction. - * @remarks - * The client transaction provides its functionality through the - * maintenance of a state machine. - * - * The TU communicates with the client transaction through a simple - * interface. When the TU wishes to initiate a new transaction, it - * creates a client transaction and passes it the SIP request to send - * and an IP address, port, and transport to which to send it. The - * client transaction begins execution of its state machine. Valid - * responses are passed up to the TU from the client transaction. - * https://tools.ietf.org/html/rfc3261#section-17.1 - * @public - */ -var ClientTransaction = /** @class */ (function (_super) { - tslib_1.__extends(ClientTransaction, _super); - function ClientTransaction(_request, transport, user, state, loggerCategory) { - var _this = _super.call(this, transport, user, ClientTransaction.makeId(_request), state, loggerCategory) || this; - _this._request = _request; - _this.user = user; - // The Via header field indicates the transport used for the transaction - // and identifies the location where the response is to be sent. A Via - // header field value is added only after the transport that will be - // used to reach the next hop has been selected (which may involve the - // usage of the procedures in [4]). - // https://tools.ietf.org/html/rfc3261#section-8.1.1.7 - // FIXME: Transport's server property is not typed (as of writing this). - var scheme = transport.server && transport.server.scheme ? transport.server.scheme : undefined; - _request.setViaHeader(_this.id, scheme); - return _this; - } - ClientTransaction.makeId = function (request) { - if (request.method === "CANCEL") { - if (!request.branch) { - throw new Error("Outgoing CANCEL request without a branch."); - } - return request.branch; - } - else { - return "z9hG4bK" + Math.floor(Math.random() * 10000000); - } - }; - Object.defineProperty(ClientTransaction.prototype, "request", { - /** The outgoing request the transaction handling. */ - get: function () { - return this._request; - }, - enumerable: true, - configurable: true - }); - /** - * A 408 to non-INVITE will always arrive too late to be useful ([3]), - * The client already has full knowledge of the timeout. The only - * information this message would convey is whether or not the server - * believed the transaction timed out. However, with the current design - * of the NIT, a client cannot do anything with this knowledge. Thus, - * the 408 is simply wasting network resources and contributes to the - * response bombardment illustrated in [3]. - * https://tools.ietf.org/html/rfc4320#section-4.1 - */ - ClientTransaction.prototype.onRequestTimeout = function () { - if (this.user.onRequestTimeout) { - this.user.onRequestTimeout(); - } - }; - return ClientTransaction; -}(transaction_1.Transaction)); -exports.ClientTransaction = ClientTransaction; - - -/***/ }), -/* 29 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var events_1 = __webpack_require__(30); -var exceptions_1 = __webpack_require__(31); -/** - * Transaction. - * @remarks - * SIP is a transactional protocol: interactions between components take - * place in a series of independent message exchanges. Specifically, a - * SIP transaction consists of a single request and any responses to - * that request, which include zero or more provisional responses and - * one or more final responses. In the case of a transaction where the - * request was an INVITE (known as an INVITE transaction), the - * transaction also includes the ACK only if the final response was not - * a 2xx response. If the response was a 2xx, the ACK is not considered - * part of the transaction. - * https://tools.ietf.org/html/rfc3261#section-17 - * @public - */ -var Transaction = /** @class */ (function (_super) { - tslib_1.__extends(Transaction, _super); - function Transaction(_transport, _user, _id, _state, loggerCategory) { - var _this = _super.call(this) || this; - _this._transport = _transport; - _this._user = _user; - _this._id = _id; - _this._state = _state; - _this.logger = _user.loggerFactory.getLogger(loggerCategory, _id); - _this.logger.debug("Constructing " + _this.typeToString() + " with id " + _this.id + "."); - return _this; - } - /** - * Destructor. - * Once the transaction is in the "terminated" state, it is destroyed - * immediately and there is no need to call `dispose`. However, if a - * transaction needs to be ended prematurely, the transaction user may - * do so by calling this method (for example, perhaps the UA is shutting down). - * No state transition will occur upon calling this method, all outstanding - * transmission timers will be cancelled, and use of the transaction after - * calling `dispose` is undefined. - */ - Transaction.prototype.dispose = function () { - this.logger.debug("Destroyed " + this.typeToString() + " with id " + this.id + "."); - }; - Object.defineProperty(Transaction.prototype, "id", { - /** Transaction id. */ - get: function () { - return this._id; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Transaction.prototype, "kind", { - /** Transaction kind. Deprecated. */ - get: function () { - throw new Error("Invalid kind."); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Transaction.prototype, "state", { - /** Transaction state. */ - get: function () { - return this._state; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Transaction.prototype, "transport", { - /** Transaction transport. */ - get: function () { - return this._transport; - }, - enumerable: true, - configurable: true - }); - Transaction.prototype.on = function (name, callback) { return _super.prototype.on.call(this, name, callback); }; - Transaction.prototype.logTransportError = function (error, message) { - this.logger.error(error.message); - this.logger.error("Transport error occurred in " + this.typeToString() + " with id " + this.id + "."); - this.logger.error(message); - }; - /** - * Pass message to transport for transmission. If transport fails, - * the transaction user is notified by callback to onTransportError(). - * @returns - * Rejects with `TransportError` if transport fails. - */ - Transaction.prototype.send = function (message) { - var _this = this; - return this.transport.send(message).catch(function (error) { - // FIXME: Transport is not, yet, typed and it is not clear - // yet what send() may or may not send our way. So for now, - // make sure we convert it to a TransportError if need be. - if (error instanceof exceptions_1.TransportError) { - _this.onTransportError(error); - return; - } - var transportError; - if (error && typeof error.message === "string") { - transportError = new exceptions_1.TransportError(error.message); - } - else { - transportError = new exceptions_1.TransportError(); - } - _this.onTransportError(transportError); - throw transportError; - }); - }; - Transaction.prototype.setState = function (state) { - this.logger.debug("State change to \"" + state + "\" on " + this.typeToString() + " with id " + this.id + "."); - this._state = state; - if (this._user.onStateChange) { - this._user.onStateChange(state); - } - this.emit("stateChanged"); - }; - Transaction.prototype.typeToString = function () { - return "UnknownType"; - }; - return Transaction; -}(events_1.EventEmitter)); -exports.Transaction = Transaction; - - -/***/ }), -/* 30 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - -var R = typeof Reflect === 'object' ? Reflect : null -var ReflectApply = R && typeof R.apply === 'function' - ? R.apply - : function ReflectApply(target, receiver, args) { - return Function.prototype.apply.call(target, receiver, args); - } - -var ReflectOwnKeys -if (R && typeof R.ownKeys === 'function') { - ReflectOwnKeys = R.ownKeys -} else if (Object.getOwnPropertySymbols) { - ReflectOwnKeys = function ReflectOwnKeys(target) { - return Object.getOwnPropertyNames(target) - .concat(Object.getOwnPropertySymbols(target)); - }; -} else { - ReflectOwnKeys = function ReflectOwnKeys(target) { - return Object.getOwnPropertyNames(target); - }; -} - -function ProcessEmitWarning(warning) { - if (console && console.warn) console.warn(warning); -} - -var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { - return value !== value; -} - -function EventEmitter() { - EventEmitter.init.call(this); -} -module.exports = EventEmitter; - -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; - -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._eventsCount = 0; -EventEmitter.prototype._maxListeners = undefined; - -// By default EventEmitters will print a warning if more than 10 listeners are -// added to it. This is a useful default which helps finding memory leaks. -var defaultMaxListeners = 10; - -Object.defineProperty(EventEmitter, 'defaultMaxListeners', { - enumerable: true, - get: function() { - return defaultMaxListeners; - }, - set: function(arg) { - if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { - throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); - } - defaultMaxListeners = arg; - } -}); - -EventEmitter.init = function() { - - if (this._events === undefined || - this._events === Object.getPrototypeOf(this)._events) { - this._events = Object.create(null); - this._eventsCount = 0; - } - - this._maxListeners = this._maxListeners || undefined; -}; - -// Obviously not all Emitters should be limited to 10. This function allows -// that to be increased. Set to zero for unlimited. -EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { - if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { - throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); - } - this._maxListeners = n; - return this; -}; - -function $getMaxListeners(that) { - if (that._maxListeners === undefined) - return EventEmitter.defaultMaxListeners; - return that._maxListeners; -} - -EventEmitter.prototype.getMaxListeners = function getMaxListeners() { - return $getMaxListeners(this); -}; - -EventEmitter.prototype.emit = function emit(type) { - var args = []; - for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); - var doError = (type === 'error'); - - var events = this._events; - if (events !== undefined) - doError = (doError && events.error === undefined); - else if (!doError) - return false; - - // If there is no 'error' event listener then throw. - if (doError) { - var er; - if (args.length > 0) - er = args[0]; - if (er instanceof Error) { - // Note: The comments on the `throw` lines are intentional, they show - // up in Node's output if this results in an unhandled exception. - throw er; // Unhandled 'error' event - } - // At least give some kind of context to the user - var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); - err.context = er; - throw err; // Unhandled 'error' event - } - - var handler = events[type]; - - if (handler === undefined) - return false; - - if (typeof handler === 'function') { - ReflectApply(handler, this, args); - } else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - ReflectApply(listeners[i], this, args); - } - - return true; -}; - -function _addListener(target, type, listener, prepend) { - var m; - var events; - var existing; - - if (typeof listener !== 'function') { - throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); - } - - events = target._events; - if (events === undefined) { - events = target._events = Object.create(null); - target._eventsCount = 0; - } else { - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (events.newListener !== undefined) { - target.emit('newListener', type, - listener.listener ? listener.listener : listener); - - // Re-assign `events` because a newListener handler could have caused the - // this._events to be assigned to a new object - events = target._events; - } - existing = events[type]; - } - - if (existing === undefined) { - // Optimize the case of one listener. Don't need the extra array object. - existing = events[type] = listener; - ++target._eventsCount; - } else { - if (typeof existing === 'function') { - // Adding the second element, need to change to array. - existing = events[type] = - prepend ? [listener, existing] : [existing, listener]; - // If we've already got an array, just append. - } else if (prepend) { - existing.unshift(listener); - } else { - existing.push(listener); - } - - // Check for listener leak - m = $getMaxListeners(target); - if (m > 0 && existing.length > m && !existing.warned) { - existing.warned = true; - // No error code for this since it is a Warning - // eslint-disable-next-line no-restricted-syntax - var w = new Error('Possible EventEmitter memory leak detected. ' + - existing.length + ' ' + String(type) + ' listeners ' + - 'added. Use emitter.setMaxListeners() to ' + - 'increase limit'); - w.name = 'MaxListenersExceededWarning'; - w.emitter = target; - w.type = type; - w.count = existing.length; - ProcessEmitWarning(w); - } - } - - return target; -} - -EventEmitter.prototype.addListener = function addListener(type, listener) { - return _addListener(this, type, listener, false); -}; - -EventEmitter.prototype.on = EventEmitter.prototype.addListener; - -EventEmitter.prototype.prependListener = - function prependListener(type, listener) { - return _addListener(this, type, listener, true); - }; - -function onceWrapper() { - var args = []; - for (var i = 0; i < arguments.length; i++) args.push(arguments[i]); - if (!this.fired) { - this.target.removeListener(this.type, this.wrapFn); - this.fired = true; - ReflectApply(this.listener, this.target, args); - } -} - -function _onceWrap(target, type, listener) { - var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; - var wrapped = onceWrapper.bind(state); - wrapped.listener = listener; - state.wrapFn = wrapped; - return wrapped; -} - -EventEmitter.prototype.once = function once(type, listener) { - if (typeof listener !== 'function') { - throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); - } - this.on(type, _onceWrap(this, type, listener)); - return this; -}; - -EventEmitter.prototype.prependOnceListener = - function prependOnceListener(type, listener) { - if (typeof listener !== 'function') { - throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); - } - this.prependListener(type, _onceWrap(this, type, listener)); - return this; - }; - -// Emits a 'removeListener' event if and only if the listener was removed. -EventEmitter.prototype.removeListener = - function removeListener(type, listener) { - var list, events, position, i, originalListener; - - if (typeof listener !== 'function') { - throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); - } - - events = this._events; - if (events === undefined) - return this; - - list = events[type]; - if (list === undefined) - return this; - - if (list === listener || list.listener === listener) { - if (--this._eventsCount === 0) - this._events = Object.create(null); - else { - delete events[type]; - if (events.removeListener) - this.emit('removeListener', type, list.listener || listener); - } - } else if (typeof list !== 'function') { - position = -1; - - for (i = list.length - 1; i >= 0; i--) { - if (list[i] === listener || list[i].listener === listener) { - originalListener = list[i].listener; - position = i; - break; - } - } - - if (position < 0) - return this; - - if (position === 0) - list.shift(); - else { - spliceOne(list, position); - } - - if (list.length === 1) - events[type] = list[0]; - - if (events.removeListener !== undefined) - this.emit('removeListener', type, originalListener || listener); - } - - return this; - }; - -EventEmitter.prototype.off = EventEmitter.prototype.removeListener; - -EventEmitter.prototype.removeAllListeners = - function removeAllListeners(type) { - var listeners, events, i; - - events = this._events; - if (events === undefined) - return this; - - // not listening for removeListener, no need to emit - if (events.removeListener === undefined) { - if (arguments.length === 0) { - this._events = Object.create(null); - this._eventsCount = 0; - } else if (events[type] !== undefined) { - if (--this._eventsCount === 0) - this._events = Object.create(null); - else - delete events[type]; - } - return this; - } - - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - var keys = Object.keys(events); - var key; - for (i = 0; i < keys.length; ++i) { - key = keys[i]; - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = Object.create(null); - this._eventsCount = 0; - return this; - } - - listeners = events[type]; - - if (typeof listeners === 'function') { - this.removeListener(type, listeners); - } else if (listeners !== undefined) { - // LIFO order - for (i = listeners.length - 1; i >= 0; i--) { - this.removeListener(type, listeners[i]); - } - } - - return this; - }; - -function _listeners(target, type, unwrap) { - var events = target._events; - - if (events === undefined) - return []; - - var evlistener = events[type]; - if (evlistener === undefined) - return []; - - if (typeof evlistener === 'function') - return unwrap ? [evlistener.listener || evlistener] : [evlistener]; - - return unwrap ? - unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); -} - -EventEmitter.prototype.listeners = function listeners(type) { - return _listeners(this, type, true); -}; - -EventEmitter.prototype.rawListeners = function rawListeners(type) { - return _listeners(this, type, false); -}; - -EventEmitter.listenerCount = function(emitter, type) { - if (typeof emitter.listenerCount === 'function') { - return emitter.listenerCount(type); - } else { - return listenerCount.call(emitter, type); - } -}; - -EventEmitter.prototype.listenerCount = listenerCount; -function listenerCount(type) { - var events = this._events; - - if (events !== undefined) { - var evlistener = events[type]; - - if (typeof evlistener === 'function') { - return 1; - } else if (evlistener !== undefined) { - return evlistener.length; - } - } - - return 0; -} - -EventEmitter.prototype.eventNames = function eventNames() { - return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; -}; - -function arrayClone(arr, n) { - var copy = new Array(n); - for (var i = 0; i < n; ++i) - copy[i] = arr[i]; - return copy; -} - -function spliceOne(list, index) { - for (; index + 1 < list.length; index++) - list[index] = list[index + 1]; - list.pop(); -} - -function unwrapListeners(arr) { - var ret = new Array(arr.length); - for (var i = 0; i < ret.length; ++i) { - ret[i] = arr[i].listener || arr[i]; - } - return ret; -} - - -/***/ }), -/* 31 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -tslib_1.__exportStar(__webpack_require__(32), exports); -tslib_1.__exportStar(__webpack_require__(33), exports); -tslib_1.__exportStar(__webpack_require__(34), exports); - - -/***/ }), -/* 32 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -/** - * An Exception is considered a condition that a reasonable application may wish to catch. - * An Error indicates serious problems that a reasonable application should not try to catch. - * @public - */ -var Exception = /** @class */ (function (_super) { - tslib_1.__extends(Exception, _super); - function Exception(message) { - var _newTarget = this.constructor; - var _this = _super.call(this, message) || this; - Object.setPrototypeOf(_this, _newTarget.prototype); // restore prototype chain - return _this; - } - return Exception; -}(Error)); -exports.Exception = Exception; - - -/***/ }), -/* 33 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var exception_1 = __webpack_require__(32); -/** - * Indicates that the operation could not be completed given the current transaction state. - * @public - */ -var TransactionStateError = /** @class */ (function (_super) { - tslib_1.__extends(TransactionStateError, _super); - function TransactionStateError(message) { - return _super.call(this, message ? message : "Transaction state error.") || this; - } - return TransactionStateError; -}(exception_1.Exception)); -exports.TransactionStateError = TransactionStateError; - - -/***/ }), -/* 34 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var exception_1 = __webpack_require__(32); -/** - * Transport error. - * @public - */ -var TransportError = /** @class */ (function (_super) { - tslib_1.__extends(TransportError, _super); - function TransportError(message) { - return _super.call(this, message ? message : "Unspecified transport error.") || this; - } - return TransportError; -}(exception_1.Exception)); -exports.TransportError = TransportError; - - -/***/ }), -/* 35 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var timers_1 = __webpack_require__(26); -var client_transaction_1 = __webpack_require__(28); -var transaction_state_1 = __webpack_require__(36); -/** - * INVITE Client Transaction. - * @remarks - * The INVITE transaction consists of a three-way handshake. The client - * transaction sends an INVITE, the server transaction sends responses, - * and the client transaction sends an ACK. - * https://tools.ietf.org/html/rfc3261#section-17.1.1 - * @public - */ -var InviteClientTransaction = /** @class */ (function (_super) { - tslib_1.__extends(InviteClientTransaction, _super); - /** - * Constructor. - * Upon construction, the outgoing request's Via header is updated by calling `setViaHeader`. - * Then `toString` is called on the outgoing request and the message is sent via the transport. - * After construction the transaction will be in the "calling" state and the transaction id - * will equal the branch parameter set in the Via header of the outgoing request. - * https://tools.ietf.org/html/rfc3261#section-17.1.1 - * @param request - The outgoing INVITE request. - * @param transport - The transport. - * @param user - The transaction user. - */ - function InviteClientTransaction(request, transport, user) { - var _this = _super.call(this, request, transport, user, transaction_state_1.TransactionState.Calling, "sip.transaction.ict") || this; - /** - * Map of 2xx to-tag to ACK. - * If value is not undefined, value is the ACK which was sent. - * If key exists but value is undefined, a 2xx was received but the ACK not yet sent. - * Otherwise, a 2xx was not (yet) received for this transaction. - */ - _this.ackRetransmissionCache = new Map(); - // FIXME: Timer A for unreliable transport not implemented - // - // If an unreliable transport is being used, the client transaction - // MUST start timer A with a value of T1. If a reliable transport is being used, - // the client transaction SHOULD NOT start timer A (Timer A controls request retransmissions). - // For any transport, the client transaction MUST start timer B with a value - // of 64*T1 seconds (Timer B controls transaction timeouts). - // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - // - // While not spelled out in the RFC, Timer B is the maximum amount of time that a sender - // will wait for an INVITE message to be acknowledged (a SIP response message is received). - // So Timer B should be cleared when the transaction state proceeds from "Calling". - _this.B = setTimeout(function () { return _this.timer_B(); }, timers_1.Timers.TIMER_B); - _this.send(request.toString()).catch(function (error) { - _this.logTransportError(error, "Failed to send initial outgoing request."); - }); - return _this; - } - /** - * Destructor. - */ - InviteClientTransaction.prototype.dispose = function () { - if (this.B) { - clearTimeout(this.B); - this.B = undefined; - } - if (this.D) { - clearTimeout(this.D); - this.D = undefined; - } - if (this.M) { - clearTimeout(this.M); - this.M = undefined; - } - _super.prototype.dispose.call(this); - }; - Object.defineProperty(InviteClientTransaction.prototype, "kind", { - /** Transaction kind. Deprecated. */ - get: function () { - return "ict"; - }, - enumerable: true, - configurable: true - }); - /** - * ACK a 2xx final response. - * - * The transaction includes the ACK only if the final response was not a 2xx response (the - * transaction will generate and send the ACK to the transport automagically). If the - * final response was a 2xx, the ACK is not considered part of the transaction (the - * transaction user needs to generate and send the ACK). - * - * This library is not strictly RFC compliant with regard to ACK handling for 2xx final - * responses. Specifically, retransmissions of ACKs to a 2xx final responses is handled - * by the transaction layer (instead of the UAC core). The "standard" approach is for - * the UAC core to receive all 2xx responses and manage sending ACK retransmissions to - * the transport directly. Herein the transaction layer manages sending ACKs to 2xx responses - * and any retransmissions of those ACKs as needed. - * - * @param ack - The outgoing ACK request. - */ - InviteClientTransaction.prototype.ackResponse = function (ack) { - var _this = this; - var toTag = ack.toTag; - if (!toTag) { - throw new Error("To tag undefined."); - } - var id = "z9hG4bK" + Math.floor(Math.random() * 10000000); - // FIXME: Transport's server property is not typed (as of writing this). - var scheme = this.transport.server && this.transport.server.scheme ? this.transport.server.scheme : undefined; - ack.setViaHeader(id, scheme); - this.ackRetransmissionCache.set(toTag, ack); // Add to ACK retransmission cache - this.send(ack.toString()).catch(function (error) { - _this.logTransportError(error, "Failed to send ACK to 2xx response."); - }); - }; - /** - * Handler for incoming responses from the transport which match this transaction. - * @param response - The incoming response. - */ - InviteClientTransaction.prototype.receiveResponse = function (response) { - var _this = this; - var statusCode = response.statusCode; - if (!statusCode || statusCode < 100 || statusCode > 699) { - throw new Error("Invalid status code " + statusCode); - } - switch (this.state) { - case transaction_state_1.TransactionState.Calling: - // If the client transaction receives a provisional response while in - // the "Calling" state, it transitions to the "Proceeding" state. In the - // "Proceeding" state, the client transaction SHOULD NOT retransmit the - // request any longer. Furthermore, the provisional response MUST be - // passed to the TU. Any further provisional responses MUST be passed - // up to the TU while in the "Proceeding" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - if (statusCode >= 100 && statusCode <= 199) { - this.stateTransition(transaction_state_1.TransactionState.Proceeding); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // When a 2xx response is received while in either the "Calling" or - // "Proceeding" states, the client transaction MUST transition to - // the "Accepted" state... The 2xx response MUST be passed up to the TU. - // The client transaction MUST NOT generate an ACK to the 2xx response -- its - // handling is delegated to the TU. A UAC core will send an ACK to - // the 2xx response using a new transaction. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 200 && statusCode <= 299) { - this.ackRetransmissionCache.set(response.toTag, undefined); // Prime the ACK cache - this.stateTransition(transaction_state_1.TransactionState.Accepted); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // When in either the "Calling" or "Proceeding" states, reception of - // a response with status code from 300-699 MUST cause the client - // transaction to transition to "Completed". The client transaction - // MUST pass the received response up to the TU, and the client - // transaction MUST generate an ACK request, even if the transport is - // reliable (guidelines for constructing the ACK from the response - // are given in Section 17.1.1.3), and then pass the ACK to the - // transport layer for transmission. The ACK MUST be sent to the - // same address, port, and transport to which the original request was sent. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 300 && statusCode <= 699) { - this.stateTransition(transaction_state_1.TransactionState.Completed); - this.ack(response); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - break; - case transaction_state_1.TransactionState.Proceeding: - // In the "Proceeding" state, the client transaction SHOULD NOT retransmit the - // request any longer. Furthermore, the provisional response MUST be - // passed to the TU. Any further provisional responses MUST be passed - // up to the TU while in the "Proceeding" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - if (statusCode >= 100 && statusCode <= 199) { - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // When a 2xx response is received while in either the "Calling" or "Proceeding" states, - // the client transaction MUST transition to the "Accepted" state... - // The 2xx response MUST be passed up to the TU. The client - // transaction MUST NOT generate an ACK to the 2xx response -- its - // handling is delegated to the TU. A UAC core will send an ACK to - // the 2xx response using a new transaction. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 200 && statusCode <= 299) { - this.ackRetransmissionCache.set(response.toTag, undefined); // Prime the ACK cache - this.stateTransition(transaction_state_1.TransactionState.Accepted); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // When in either the "Calling" or "Proceeding" states, reception of - // a response with status code from 300-699 MUST cause the client - // transaction to transition to "Completed". The client transaction - // MUST pass the received response up to the TU, and the client - // transaction MUST generate an ACK request, even if the transport is - // reliable (guidelines for constructing the ACK from the response - // are given in Section 17.1.1.3), and then pass the ACK to the - // transport layer for transmission. The ACK MUST be sent to the - // same address, port, and transport to which the original request was sent. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 300 && statusCode <= 699) { - this.stateTransition(transaction_state_1.TransactionState.Completed); - this.ack(response); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - break; - case transaction_state_1.TransactionState.Accepted: - // The purpose of the "Accepted" state is to allow the client - // transaction to continue to exist to receive, and pass to the TU, - // any retransmissions of the 2xx response and any additional 2xx - // responses from other branches of the INVITE if it forked - // downstream. Timer M reflects the amount of time that the - // transaction user will wait for such messages. - // - // Any 2xx responses that match this client transaction and that are - // received while in the "Accepted" state MUST be passed up to the - // TU. The client transaction MUST NOT generate an ACK to the 2xx - // response. The client transaction takes no further action. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 200 && statusCode <= 299) { - // NOTE: This implementation herein is intentionally not RFC compliant. - // While the first 2xx response for a given branch is passed up to the TU, - // retransmissions of 2xx responses are absorbed and the ACK associated - // with the original response is resent. This approach is taken because - // our current transaction users are not currently in a good position to - // deal with 2xx retransmission. This SHOULD NOT cause any compliance issues - ;) - // - // If we don't have a cache hit, pass the response to the TU. - if (!this.ackRetransmissionCache.has(response.toTag)) { - this.ackRetransmissionCache.set(response.toTag, undefined); // Prime the ACK cache - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // If we have a cache hit, try pulling the ACK from cache and retransmitting it. - var ack = this.ackRetransmissionCache.get(response.toTag); - if (ack) { - this.send(ack.toString()).catch(function (error) { - _this.logTransportError(error, "Failed to send retransmission of ACK to 2xx response."); - }); - return; - } - // If an ACK was not found in cache then we have received a retransmitted 2xx - // response before the TU responded to the original response (we don't have an ACK yet). - // So discard this response under the assumption that the TU will eventually - // get us a ACK for the original response. - return; - } - break; - case transaction_state_1.TransactionState.Completed: - // Any retransmissions of a response with status code 300-699 that - // are received while in the "Completed" state MUST cause the ACK to - // be re-passed to the transport layer for retransmission, but the - // newly received response MUST NOT be passed up to the TU. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 300 && statusCode <= 699) { - this.ack(response); - return; - } - break; - case transaction_state_1.TransactionState.Terminated: - break; - default: - throw new Error("Invalid state " + this.state); - } - // Any response received that does not match an existing client - // transaction state machine is simply dropped. (Implementations are, - // of course, free to log or do other implementation-specific things - // with such responses, but the implementer should be sure to consider - // the impact of large numbers of malicious stray responses.) - // https://tools.ietf.org/html/rfc6026#section-7.2 - var message = "Received unexpected " + statusCode + " response while in state " + this.state + "."; - this.logger.warn(message); - return; - }; - /** - * The client transaction SHOULD inform the TU that a transport failure - * has occurred, and the client transaction SHOULD transition directly - * to the "Terminated" state. The TU will handle the failover - * mechanisms described in [4]. - * https://tools.ietf.org/html/rfc3261#section-17.1.4 - * @param error - The error. - */ - InviteClientTransaction.prototype.onTransportError = function (error) { - if (this.user.onTransportError) { - this.user.onTransportError(error); - } - this.stateTransition(transaction_state_1.TransactionState.Terminated, true); - }; - /** For logging. */ - InviteClientTransaction.prototype.typeToString = function () { - return "INVITE client transaction"; - }; - InviteClientTransaction.prototype.ack = function (response) { - var _this = this; - // The ACK request constructed by the client transaction MUST contain - // values for the Call-ID, From, and Request-URI that are equal to the - // values of those header fields in the request passed to the transport - // by the client transaction (call this the "original request"). The To - // header field in the ACK MUST equal the To header field in the - // response being acknowledged, and therefore will usually differ from - // the To header field in the original request by the addition of the - // tag parameter. The ACK MUST contain a single Via header field, and - // this MUST be equal to the top Via header field of the original - // request. The CSeq header field in the ACK MUST contain the same - // value for the sequence number as was present in the original request, - // but the method parameter MUST be equal to "ACK". - // - // If the INVITE request whose response is being acknowledged had Route - // header fields, those header fields MUST appear in the ACK. This is - // to ensure that the ACK can be routed properly through any downstream - // stateless proxies. - // https://tools.ietf.org/html/rfc3261#section-17.1.1.3 - var ruri = this.request.ruri; - var callId = this.request.callId; - var cseq = this.request.cseq; - var from = this.request.getHeader("from"); - var to = response.getHeader("to"); - var via = this.request.getHeader("via"); - var route = this.request.getHeader("route"); - if (!from) { - throw new Error("From undefined."); - } - if (!to) { - throw new Error("To undefined."); - } - if (!via) { - throw new Error("Via undefined."); - } - var ack = "ACK " + ruri + " SIP/2.0\r\n"; - if (route) { - ack += "Route: " + route + "\r\n"; - } - ack += "Via: " + via + "\r\n"; - ack += "To: " + to + "\r\n"; - ack += "From: " + from + "\r\n"; - ack += "Call-ID: " + callId + "\r\n"; - ack += "CSeq: " + cseq + " ACK\r\n"; - ack += "Max-Forwards: 70\r\n"; - ack += "Content-Length: 0\r\n\r\n"; - // TOOO: "User-Agent" header - this.send(ack).catch(function (error) { - _this.logTransportError(error, "Failed to send ACK to non-2xx response."); - }); - return; - }; - /** - * Execute a state transition. - * @param newState - New state. - */ - InviteClientTransaction.prototype.stateTransition = function (newState, dueToTransportError) { - var _this = this; - if (dueToTransportError === void 0) { dueToTransportError = false; } - // Assert valid state transitions. - var invalidStateTransition = function () { - throw new Error("Invalid state transition from " + _this.state + " to " + newState); - }; - switch (newState) { - case transaction_state_1.TransactionState.Calling: - invalidStateTransition(); - break; - case transaction_state_1.TransactionState.Proceeding: - if (this.state !== transaction_state_1.TransactionState.Calling) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Accepted: - case transaction_state_1.TransactionState.Completed: - if (this.state !== transaction_state_1.TransactionState.Calling && - this.state !== transaction_state_1.TransactionState.Proceeding) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Terminated: - if (this.state !== transaction_state_1.TransactionState.Calling && - this.state !== transaction_state_1.TransactionState.Accepted && - this.state !== transaction_state_1.TransactionState.Completed) { - if (!dueToTransportError) { - invalidStateTransition(); - } - } - break; - default: - invalidStateTransition(); - } - // While not spelled out in the RFC, Timer B is the maximum amount of time that a sender - // will wait for an INVITE message to be acknowledged (a SIP response message is received). - // So Timer B should be cleared when the transaction state proceeds from "Calling". - if (this.B) { - clearTimeout(this.B); - this.B = undefined; - } - if (newState === transaction_state_1.TransactionState.Proceeding) { - // Timers have no effect on "Proceeding" state. - // In the "Proceeding" state, the client transaction - // SHOULD NOT retransmit the request any longer. - // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - } - // The client transaction MUST start Timer D when it enters the "Completed" state - // for any reason, with a value of at least 32 seconds for unreliable transports, - // and a value of zero seconds for reliable transports. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (newState === transaction_state_1.TransactionState.Completed) { - this.D = setTimeout(function () { return _this.timer_D(); }, timers_1.Timers.TIMER_D); - } - // The client transaction MUST transition to the "Accepted" state, - // and Timer M MUST be started with a value of 64*T1. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (newState === transaction_state_1.TransactionState.Accepted) { - this.M = setTimeout(function () { return _this.timer_M(); }, timers_1.Timers.TIMER_M); - } - // Once the transaction is in the "Terminated" state, it MUST be destroyed immediately. - // https://tools.ietf.org/html/rfc6026#section-8.7 - if (newState === transaction_state_1.TransactionState.Terminated) { - this.dispose(); - } - // Update state. - this.setState(newState); - }; - /** - * When timer A fires, the client transaction MUST retransmit the - * request by passing it to the transport layer, and MUST reset the - * timer with a value of 2*T1. - * When timer A fires 2*T1 seconds later, the request MUST be - * retransmitted again (assuming the client transaction is still in this - * state). This process MUST continue so that the request is - * retransmitted with intervals that double after each transmission. - * These retransmissions SHOULD only be done while the client - * transaction is in the "Calling" state. - * https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - */ - InviteClientTransaction.prototype.timer_A = function () { - // TODO - }; - /** - * If the client transaction is still in the "Calling" state when timer - * B fires, the client transaction SHOULD inform the TU that a timeout - * has occurred. The client transaction MUST NOT generate an ACK. - * https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - */ - InviteClientTransaction.prototype.timer_B = function () { - this.logger.debug("Timer B expired for INVITE client transaction " + this.id + "."); - if (this.state === transaction_state_1.TransactionState.Calling) { - this.onRequestTimeout(); - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - /** - * If Timer D fires while the client transaction is in the "Completed" state, - * the client transaction MUST move to the "Terminated" state. - * https://tools.ietf.org/html/rfc6026#section-8.4 - */ - InviteClientTransaction.prototype.timer_D = function () { - this.logger.debug("Timer D expired for INVITE client transaction " + this.id + "."); - if (this.state === transaction_state_1.TransactionState.Completed) { - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - /** - * If Timer M fires while the client transaction is in the "Accepted" - * state, the client transaction MUST move to the "Terminated" state. - * https://tools.ietf.org/html/rfc6026#section-8.4 - */ - InviteClientTransaction.prototype.timer_M = function () { - this.logger.debug("Timer M expired for INVITE client transaction " + this.id + "."); - if (this.state === transaction_state_1.TransactionState.Accepted) { - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - return InviteClientTransaction; -}(client_transaction_1.ClientTransaction)); -exports.InviteClientTransaction = InviteClientTransaction; - - -/***/ }), -/* 36 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * Transaction state. - * @public - */ -var TransactionState; -(function (TransactionState) { - TransactionState["Accepted"] = "Accepted"; - TransactionState["Calling"] = "Calling"; - TransactionState["Completed"] = "Completed"; - TransactionState["Confirmed"] = "Confirmed"; - TransactionState["Proceeding"] = "Proceeding"; - TransactionState["Terminated"] = "Terminated"; - TransactionState["Trying"] = "Trying"; -})(TransactionState = exports.TransactionState || (exports.TransactionState = {})); - - -/***/ }), -/* 37 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var timers_1 = __webpack_require__(26); -var server_transaction_1 = __webpack_require__(38); -var transaction_state_1 = __webpack_require__(36); -/** - * INVITE Server Transaction. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - * @public - */ -var InviteServerTransaction = /** @class */ (function (_super) { - tslib_1.__extends(InviteServerTransaction, _super); - /** - * Constructor. - * Upon construction, a "100 Trying" reply will be immediately sent. - * After construction the transaction will be in the "proceeding" state and the transaction - * `id` will equal the branch parameter set in the Via header of the incoming request. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - * @param request - Incoming INVITE request from the transport. - * @param transport - The transport. - * @param user - The transaction user. - */ - function InviteServerTransaction(request, transport, user) { - return _super.call(this, request, transport, user, transaction_state_1.TransactionState.Proceeding, "sip.transaction.ist") || this; - } - /** - * Destructor. - */ - InviteServerTransaction.prototype.dispose = function () { - this.stopProgressExtensionTimer(); - if (this.H) { - clearTimeout(this.H); - this.H = undefined; - } - if (this.I) { - clearTimeout(this.I); - this.I = undefined; - } - if (this.L) { - clearTimeout(this.L); - this.L = undefined; - } - _super.prototype.dispose.call(this); - }; - Object.defineProperty(InviteServerTransaction.prototype, "kind", { - /** Transaction kind. Deprecated. */ - get: function () { - return "ist"; - }, - enumerable: true, - configurable: true - }); - /** - * Receive requests from transport matching this transaction. - * @param request - Request matching this transaction. - */ - InviteServerTransaction.prototype.receiveRequest = function (request) { - var _this = this; - switch (this.state) { - case transaction_state_1.TransactionState.Proceeding: - // If a request retransmission is received while in the "Proceeding" state, the most - // recent provisional response that was received from the TU MUST be passed to the - // transport layer for retransmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (request.method === messages_1.C.INVITE) { - if (this.lastProvisionalResponse) { - this.send(this.lastProvisionalResponse).catch(function (error) { - _this.logTransportError(error, "Failed to send retransmission of provisional response."); - }); - } - return; - } - break; - case transaction_state_1.TransactionState.Accepted: - // While in the "Accepted" state, any retransmissions of the INVITE - // received will match this transaction state machine and will be - // absorbed by the machine without changing its state. These - // retransmissions are not passed onto the TU. - // https://tools.ietf.org/html/rfc6026#section-7.1 - if (request.method === messages_1.C.INVITE) { - return; - } - break; - case transaction_state_1.TransactionState.Completed: - // Furthermore, while in the "Completed" state, if a request retransmission is - // received, the server SHOULD pass the response to the transport for retransmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (request.method === messages_1.C.INVITE) { - if (!this.lastFinalResponse) { - throw new Error("Last final response undefined."); - } - this.send(this.lastFinalResponse).catch(function (error) { - _this.logTransportError(error, "Failed to send retransmission of final response."); - }); - return; - } - // If an ACK is received while the server transaction is in the "Completed" state, - // the server transaction MUST transition to the "Confirmed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (request.method === messages_1.C.ACK) { - this.stateTransition(transaction_state_1.TransactionState.Confirmed); - return; - } - break; - case transaction_state_1.TransactionState.Confirmed: - // The purpose of the "Confirmed" state is to absorb any additional ACK messages that arrive, - // triggered from retransmissions of the final response. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (request.method === messages_1.C.INVITE || request.method === messages_1.C.ACK) { - return; - } - break; - case transaction_state_1.TransactionState.Terminated: - // For good measure absorb any additional messages that arrive (should not happen). - if (request.method === messages_1.C.INVITE || request.method === messages_1.C.ACK) { - return; - } - break; - default: - throw new Error("Invalid state " + this.state); - } - var message = "INVITE server transaction received unexpected " + request.method + " request while in state " + this.state + "."; - this.logger.warn(message); - return; - }; - /** - * Receive responses from TU for this transaction. - * @param statusCode - Status code of response. - * @param response - Response. - */ - InviteServerTransaction.prototype.receiveResponse = function (statusCode, response) { - var _this = this; - if (statusCode < 100 || statusCode > 699) { - throw new Error("Invalid status code " + statusCode); - } - switch (this.state) { - case transaction_state_1.TransactionState.Proceeding: - // The TU passes any number of provisional responses to the server - // transaction. So long as the server transaction is in the - // "Proceeding" state, each of these MUST be passed to the transport - // layer for transmission. They are not sent reliably by the - // transaction layer (they are not retransmitted by it) and do not cause - // a change in the state of the server transaction. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (statusCode >= 100 && statusCode <= 199) { - this.lastProvisionalResponse = response; - // Start the progress extension timer only for a non-100 provisional response. - if (statusCode > 100) { - this.startProgressExtensionTimer(); // FIXME: remove - } - this.send(response).catch(function (error) { - _this.logTransportError(error, "Failed to send 1xx response."); - }); - return; - } - // If, while in the "Proceeding" state, the TU passes a 2xx response - // to the server transaction, the server transaction MUST pass this - // response to the transport layer for transmission. It is not - // retransmitted by the server transaction; retransmissions of 2xx - // responses are handled by the TU. The server transaction MUST then - // transition to the "Accepted" state. - // https://tools.ietf.org/html/rfc6026#section-8.5 - if (statusCode >= 200 && statusCode <= 299) { - this.lastFinalResponse = response; - this.stateTransition(transaction_state_1.TransactionState.Accepted); - this.send(response).catch(function (error) { - _this.logTransportError(error, "Failed to send 2xx response."); - }); - return; - } - // While in the "Proceeding" state, if the TU passes a response with - // status code from 300 to 699 to the server transaction, the response - // MUST be passed to the transport layer for transmission, and the state - // machine MUST enter the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (statusCode >= 300 && statusCode <= 699) { - this.lastFinalResponse = response; - this.stateTransition(transaction_state_1.TransactionState.Completed); - this.send(response).catch(function (error) { - _this.logTransportError(error, "Failed to send non-2xx final response."); - }); - return; - } - break; - case transaction_state_1.TransactionState.Accepted: - // While in the "Accepted" state, if the TU passes a 2xx response, - // the server transaction MUST pass the response to the transport layer for transmission. - // https://tools.ietf.org/html/rfc6026#section-8.7 - if (statusCode >= 200 && statusCode <= 299) { - this.send(response).catch(function (error) { - _this.logTransportError(error, "Failed to send 2xx response."); - }); - return; - } - break; - case transaction_state_1.TransactionState.Completed: - break; - case transaction_state_1.TransactionState.Confirmed: - break; - case transaction_state_1.TransactionState.Terminated: - break; - default: - throw new Error("Invalid state " + this.state); - } - var message = "INVITE server transaction received unexpected " + statusCode + " response from TU while in state " + this.state + "."; - this.logger.error(message); - throw new Error(message); - }; - /** - * Retransmit the last 2xx response. This is a noop if not in the "accepted" state. - */ - InviteServerTransaction.prototype.retransmitAcceptedResponse = function () { - var _this = this; - if (this.state === transaction_state_1.TransactionState.Accepted && this.lastFinalResponse) { - this.send(this.lastFinalResponse).catch(function (error) { - _this.logTransportError(error, "Failed to send 2xx response."); - }); - } - }; - /** - * First, the procedures in [4] are followed, which attempt to deliver the response to a backup. - * If those should all fail, based on the definition of failure in [4], the server transaction SHOULD - * inform the TU that a failure has occurred, and MUST remain in the current state. - * https://tools.ietf.org/html/rfc6026#section-8.8 - */ - InviteServerTransaction.prototype.onTransportError = function (error) { - if (this.user.onTransportError) { - this.user.onTransportError(error); - } - }; - /** For logging. */ - InviteServerTransaction.prototype.typeToString = function () { - return "INVITE server transaction"; - }; - /** - * Execute a state transition. - * @param newState - New state. - */ - InviteServerTransaction.prototype.stateTransition = function (newState) { - var _this = this; - // Assert valid state transitions. - var invalidStateTransition = function () { - throw new Error("Invalid state transition from " + _this.state + " to " + newState); - }; - switch (newState) { - case transaction_state_1.TransactionState.Proceeding: - invalidStateTransition(); - break; - case transaction_state_1.TransactionState.Accepted: - case transaction_state_1.TransactionState.Completed: - if (this.state !== transaction_state_1.TransactionState.Proceeding) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Confirmed: - if (this.state !== transaction_state_1.TransactionState.Completed) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Terminated: - if (this.state !== transaction_state_1.TransactionState.Accepted && - this.state !== transaction_state_1.TransactionState.Completed && - this.state !== transaction_state_1.TransactionState.Confirmed) { - invalidStateTransition(); - } - break; - default: - invalidStateTransition(); - } - // On any state transition, stop resending provisonal responses - this.stopProgressExtensionTimer(); - // The purpose of the "Accepted" state is to absorb retransmissions of an accepted INVITE request. - // Any such retransmissions are absorbed entirely within the server transaction. - // They are not passed up to the TU since any downstream UAS cores that accepted the request have - // taken responsibility for reliability and will already retransmit their 2xx responses if necessary. - // https://tools.ietf.org/html/rfc6026#section-8.7 - if (newState === transaction_state_1.TransactionState.Accepted) { - this.L = setTimeout(function () { return _this.timer_L(); }, timers_1.Timers.TIMER_L); - } - // When the "Completed" state is entered, timer H MUST be set to fire in 64*T1 seconds for all transports. - // Timer H determines when the server transaction abandons retransmitting the response. - // If an ACK is received while the server transaction is in the "Completed" state, - // the server transaction MUST transition to the "Confirmed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (newState === transaction_state_1.TransactionState.Completed) { - // FIXME: Missing timer G for unreliable transports. - this.H = setTimeout(function () { return _this.timer_H(); }, timers_1.Timers.TIMER_H); - } - // The purpose of the "Confirmed" state is to absorb any additional ACK messages that arrive, - // triggered from retransmissions of the final response. When this state is entered, timer I - // is set to fire in T4 seconds for unreliable transports, and zero seconds for reliable - // transports. Once timer I fires, the server MUST transition to the "Terminated" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (newState === transaction_state_1.TransactionState.Confirmed) { - // FIXME: This timer is not getting set correctly for unreliable transports. - this.I = setTimeout(function () { return _this.timer_I(); }, timers_1.Timers.TIMER_I); - } - // Once the transaction is in the "Terminated" state, it MUST be destroyed immediately. - // https://tools.ietf.org/html/rfc6026#section-8.7 - if (newState === transaction_state_1.TransactionState.Terminated) { - this.dispose(); - } - // Update state. - this.setState(newState); - }; - /** - * FIXME: UAS Provisional Retransmission Timer. See RFC 3261 Section 13.3.1.1 - * This is in the wrong place. This is not a transaction level thing. It's a UAS level thing. - */ - InviteServerTransaction.prototype.startProgressExtensionTimer = function () { - var _this = this; - // Start the progress extension timer only for the first non-100 provisional response. - if (this.progressExtensionTimer === undefined) { - this.progressExtensionTimer = setInterval(function () { - _this.logger.debug("Progress extension timer expired for INVITE server transaction " + _this.id + "."); - if (!_this.lastProvisionalResponse) { - throw new Error("Last provisional response undefined."); - } - _this.send(_this.lastProvisionalResponse).catch(function (error) { - _this.logTransportError(error, "Failed to send retransmission of provisional response."); - }); - }, timers_1.Timers.PROVISIONAL_RESPONSE_INTERVAL); - } - }; - /** - * FIXME: UAS Provisional Retransmission Timer id. See RFC 3261 Section 13.3.1.1 - * This is in the wrong place. This is not a transaction level thing. It's a UAS level thing. - */ - InviteServerTransaction.prototype.stopProgressExtensionTimer = function () { - if (this.progressExtensionTimer !== undefined) { - clearInterval(this.progressExtensionTimer); - this.progressExtensionTimer = undefined; - } - }; - /** - * While in the "Proceeding" state, if the TU passes a response with status code - * from 300 to 699 to the server transaction, the response MUST be passed to the - * transport layer for transmission, and the state machine MUST enter the "Completed" state. - * For unreliable transports, timer G is set to fire in T1 seconds, and is not set to fire for - * reliable transports. If timer G fires, the response is passed to the transport layer once - * more for retransmission, and timer G is set to fire in MIN(2*T1, T2) seconds. From then on, - * when timer G fires, the response is passed to the transport again for transmission, and - * timer G is reset with a value that doubles, unless that value exceeds T2, in which case - * it is reset with the value of T2. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - */ - InviteServerTransaction.prototype.timer_G = function () { - // TODO - }; - /** - * If timer H fires while in the "Completed" state, it implies that the ACK was never received. - * In this case, the server transaction MUST transition to the "Terminated" state, and MUST - * indicate to the TU that a transaction failure has occurred. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - */ - InviteServerTransaction.prototype.timer_H = function () { - this.logger.debug("Timer H expired for INVITE server transaction " + this.id + "."); - if (this.state === transaction_state_1.TransactionState.Completed) { - this.logger.warn("ACK to negative final response was never received, terminating transaction."); - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - /** - * Once timer I fires, the server MUST transition to the "Terminated" state. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - */ - InviteServerTransaction.prototype.timer_I = function () { - this.logger.debug("Timer I expired for INVITE server transaction " + this.id + "."); - this.stateTransition(transaction_state_1.TransactionState.Terminated); - }; - /** - * When Timer L fires and the state machine is in the "Accepted" state, the machine MUST - * transition to the "Terminated" state. Once the transaction is in the "Terminated" state, - * it MUST be destroyed immediately. Timer L reflects the amount of time the server - * transaction could receive 2xx responses for retransmission from the - * TU while it is waiting to receive an ACK. - * https://tools.ietf.org/html/rfc6026#section-7.1 - * https://tools.ietf.org/html/rfc6026#section-8.7 - */ - InviteServerTransaction.prototype.timer_L = function () { - this.logger.debug("Timer L expired for INVITE server transaction " + this.id + "."); - if (this.state === transaction_state_1.TransactionState.Accepted) { - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - return InviteServerTransaction; -}(server_transaction_1.ServerTransaction)); -exports.InviteServerTransaction = InviteServerTransaction; - - -/***/ }), -/* 38 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transaction_1 = __webpack_require__(29); -/** - * Server Transaction. - * @remarks - * The server transaction is responsible for the delivery of requests to - * the TU and the reliable transmission of responses. It accomplishes - * this through a state machine. Server transactions are created by the - * core when a request is received, and transaction handling is desired - * for that request (this is not always the case). - * https://tools.ietf.org/html/rfc3261#section-17.2 - * @public - */ -var ServerTransaction = /** @class */ (function (_super) { - tslib_1.__extends(ServerTransaction, _super); - function ServerTransaction(_request, transport, user, state, loggerCategory) { - var _this = _super.call(this, transport, user, _request.viaBranch, state, loggerCategory) || this; - _this._request = _request; - _this.user = user; - return _this; - } - Object.defineProperty(ServerTransaction.prototype, "request", { - /** The incoming request the transaction handling. */ - get: function () { - return this._request; - }, - enumerable: true, - configurable: true - }); - return ServerTransaction; -}(transaction_1.Transaction)); -exports.ServerTransaction = ServerTransaction; - - -/***/ }), -/* 39 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var timers_1 = __webpack_require__(26); -var client_transaction_1 = __webpack_require__(28); -var transaction_state_1 = __webpack_require__(36); -/** - * Non-INVITE Client Transaction. - * @remarks - * Non-INVITE transactions do not make use of ACK. - * They are simple request-response interactions. - * https://tools.ietf.org/html/rfc3261#section-17.1.2 - * @public - */ -var NonInviteClientTransaction = /** @class */ (function (_super) { - tslib_1.__extends(NonInviteClientTransaction, _super); - /** - * Constructor - * Upon construction, the outgoing request's Via header is updated by calling `setViaHeader`. - * Then `toString` is called on the outgoing request and the message is sent via the transport. - * After construction the transaction will be in the "calling" state and the transaction id - * will equal the branch parameter set in the Via header of the outgoing request. - * https://tools.ietf.org/html/rfc3261#section-17.1.2 - * @param request - The outgoing Non-INVITE request. - * @param transport - The transport. - * @param user - The transaction user. - */ - function NonInviteClientTransaction(request, transport, user) { - var _this = _super.call(this, request, transport, user, transaction_state_1.TransactionState.Trying, "sip.transaction.nict") || this; - // FIXME: Timer E for unreliable transports not implemented. - // - // The "Trying" state is entered when the TU initiates a new client - // transaction with a request. When entering this state, the client - // transaction SHOULD set timer F to fire in 64*T1 seconds. The request - // MUST be passed to the transport layer for transmission. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - _this.F = setTimeout(function () { return _this.timer_F(); }, timers_1.Timers.TIMER_F); - _this.send(request.toString()).catch(function (error) { - _this.logTransportError(error, "Failed to send initial outgoing request."); - }); - return _this; - } - /** - * Destructor. - */ - NonInviteClientTransaction.prototype.dispose = function () { - if (this.F) { - clearTimeout(this.F); - this.F = undefined; - } - if (this.K) { - clearTimeout(this.K); - this.K = undefined; - } - _super.prototype.dispose.call(this); - }; - Object.defineProperty(NonInviteClientTransaction.prototype, "kind", { - /** Transaction kind. Deprecated. */ - get: function () { - return "nict"; - }, - enumerable: true, - configurable: true - }); - /** - * Handler for incoming responses from the transport which match this transaction. - * @param response - The incoming response. - */ - NonInviteClientTransaction.prototype.receiveResponse = function (response) { - var statusCode = response.statusCode; - if (!statusCode || statusCode < 100 || statusCode > 699) { - throw new Error("Invalid status code " + statusCode); - } - switch (this.state) { - case transaction_state_1.TransactionState.Trying: - // If a provisional response is received while in the "Trying" state, the - // response MUST be passed to the TU, and then the client transaction - // SHOULD move to the "Proceeding" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (statusCode >= 100 && statusCode <= 199) { - this.stateTransition(transaction_state_1.TransactionState.Proceeding); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // If a final response (status codes 200-699) is received while in the - // "Trying" state, the response MUST be passed to the TU, and the - // client transaction MUST transition to the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (statusCode >= 200 && statusCode <= 699) { - this.stateTransition(transaction_state_1.TransactionState.Completed); - if (statusCode === 408) { - this.onRequestTimeout(); - return; - } - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - break; - case transaction_state_1.TransactionState.Proceeding: - // If a provisional response is received while in the "Proceeding" state, - // the response MUST be passed to the TU. (From Figure 6) - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (statusCode >= 100 && statusCode <= 199) { - if (this.user.receiveResponse) { - return this.user.receiveResponse(response); - } - } - // If a final response (status codes 200-699) is received while in the - // "Proceeding" state, the response MUST be passed to the TU, and the - // client transaction MUST transition to the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (statusCode >= 200 && statusCode <= 699) { - this.stateTransition(transaction_state_1.TransactionState.Completed); - if (statusCode === 408) { - this.onRequestTimeout(); - return; - } - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - case transaction_state_1.TransactionState.Completed: - // The "Completed" state exists to buffer any additional response - // retransmissions that may be received (which is why the client - // transaction remains there only for unreliable transports). - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - return; - case transaction_state_1.TransactionState.Terminated: - // For good measure just absorb additional response retransmissions. - return; - default: - throw new Error("Invalid state " + this.state); - } - var message = "Non-INVITE client transaction received unexpected " + statusCode + " response while in state " + this.state + "."; - this.logger.warn(message); - return; - }; - /** - * The client transaction SHOULD inform the TU that a transport failure has occurred, - * and the client transaction SHOULD transition directly to the "Terminated" state. - * The TU will handle the failover mechanisms described in [4]. - * https://tools.ietf.org/html/rfc3261#section-17.1.4 - * @param error - Trasnsport error - */ - NonInviteClientTransaction.prototype.onTransportError = function (error) { - if (this.user.onTransportError) { - this.user.onTransportError(error); - } - this.stateTransition(transaction_state_1.TransactionState.Terminated, true); - }; - /** For logging. */ - NonInviteClientTransaction.prototype.typeToString = function () { - return "non-INVITE client transaction"; - }; - /** - * Execute a state transition. - * @param newState - New state. - */ - NonInviteClientTransaction.prototype.stateTransition = function (newState, dueToTransportError) { - var _this = this; - if (dueToTransportError === void 0) { dueToTransportError = false; } - // Assert valid state transitions. - var invalidStateTransition = function () { - throw new Error("Invalid state transition from " + _this.state + " to " + newState); - }; - switch (newState) { - case transaction_state_1.TransactionState.Trying: - invalidStateTransition(); - break; - case transaction_state_1.TransactionState.Proceeding: - if (this.state !== transaction_state_1.TransactionState.Trying) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Completed: - if (this.state !== transaction_state_1.TransactionState.Trying && - this.state !== transaction_state_1.TransactionState.Proceeding) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Terminated: - if (this.state !== transaction_state_1.TransactionState.Trying && - this.state !== transaction_state_1.TransactionState.Proceeding && - this.state !== transaction_state_1.TransactionState.Completed) { - if (!dueToTransportError) { - invalidStateTransition(); - } - } - break; - default: - invalidStateTransition(); - } - // Once the client transaction enters the "Completed" state, it MUST set - // Timer K to fire in T4 seconds for unreliable transports, and zero - // seconds for reliable transports The "Completed" state exists to - // buffer any additional response retransmissions that may be received - // (which is why the client transaction remains there only for unreliable transports). - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (newState === transaction_state_1.TransactionState.Completed) { - if (this.F) { - clearTimeout(this.F); - this.F = undefined; - } - this.K = setTimeout(function () { return _this.timer_K(); }, timers_1.Timers.TIMER_K); - } - // Once the transaction is in the terminated state, it MUST be destroyed immediately. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (newState === transaction_state_1.TransactionState.Terminated) { - this.dispose(); - } - // Update state. - this.setState(newState); - }; - /** - * If Timer F fires while the client transaction is still in the - * "Trying" state, the client transaction SHOULD inform the TU about the - * timeout, and then it SHOULD enter the "Terminated" state. - * If timer F fires while in the "Proceeding" state, the TU MUST be informed of - * a timeout, and the client transaction MUST transition to the terminated state. - * https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - */ - NonInviteClientTransaction.prototype.timer_F = function () { - this.logger.debug("Timer F expired for non-INVITE client transaction " + this.id + "."); - if (this.state === transaction_state_1.TransactionState.Trying || this.state === transaction_state_1.TransactionState.Proceeding) { - this.onRequestTimeout(); - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - /** - * If Timer K fires while in this (COMPLETED) state, the client transaction - * MUST transition to the "Terminated" state. - * https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - */ - NonInviteClientTransaction.prototype.timer_K = function () { - if (this.state === transaction_state_1.TransactionState.Completed) { - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - return NonInviteClientTransaction; -}(client_transaction_1.ClientTransaction)); -exports.NonInviteClientTransaction = NonInviteClientTransaction; - - -/***/ }), -/* 40 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var timers_1 = __webpack_require__(26); -var server_transaction_1 = __webpack_require__(38); -var transaction_state_1 = __webpack_require__(36); -/** - * Non-INVITE Server Transaction. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-17.2.2 - * @public - */ -var NonInviteServerTransaction = /** @class */ (function (_super) { - tslib_1.__extends(NonInviteServerTransaction, _super); - /** - * Constructor. - * After construction the transaction will be in the "trying": state and the transaction - * `id` will equal the branch parameter set in the Via header of the incoming request. - * https://tools.ietf.org/html/rfc3261#section-17.2.2 - * @param request - Incoming Non-INVITE request from the transport. - * @param transport - The transport. - * @param user - The transaction user. - */ - function NonInviteServerTransaction(request, transport, user) { - return _super.call(this, request, transport, user, transaction_state_1.TransactionState.Trying, "sip.transaction.nist") || this; - } - /** - * Destructor. - */ - NonInviteServerTransaction.prototype.dispose = function () { - if (this.J) { - clearTimeout(this.J); - this.J = undefined; - } - _super.prototype.dispose.call(this); - }; - Object.defineProperty(NonInviteServerTransaction.prototype, "kind", { - /** Transaction kind. Deprecated. */ - get: function () { - return "nist"; - }, - enumerable: true, - configurable: true - }); - /** - * Receive requests from transport matching this transaction. - * @param request - Request matching this transaction. - */ - NonInviteServerTransaction.prototype.receiveRequest = function (request) { - var _this = this; - switch (this.state) { - case transaction_state_1.TransactionState.Trying: - // Once in the "Trying" state, any further request retransmissions are discarded. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - break; - case transaction_state_1.TransactionState.Proceeding: - // If a retransmission of the request is received while in the "Proceeding" state, - // the most recently sent provisional response MUST be passed to the transport layer for retransmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - if (!this.lastResponse) { - throw new Error("Last response undefined."); - } - this.send(this.lastResponse).catch(function (error) { - _this.logTransportError(error, "Failed to send retransmission of provisional response."); - }); - break; - case transaction_state_1.TransactionState.Completed: - // While in the "Completed" state, the server transaction MUST pass the final response to the transport - // layer for retransmission whenever a retransmission of the request is received. Any other final responses - // passed by the TU to the server transaction MUST be discarded while in the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - if (!this.lastResponse) { - throw new Error("Last response undefined."); - } - this.send(this.lastResponse).catch(function (error) { - _this.logTransportError(error, "Failed to send retransmission of final response."); - }); - break; - case transaction_state_1.TransactionState.Terminated: - break; - default: - throw new Error("Invalid state " + this.state); - } - }; - /** - * Receive responses from TU for this transaction. - * @param statusCode - Status code of repsonse. 101-199 not allowed per RFC 4320. - * @param response - Response to send. - */ - NonInviteServerTransaction.prototype.receiveResponse = function (statusCode, response) { - var _this = this; - if (statusCode < 100 || statusCode > 699) { - throw new Error("Invalid status code " + statusCode); - } - // An SIP element MUST NOT send any provisional response with a - // Status-Code other than 100 to a non-INVITE request. - // An SIP element MUST NOT respond to a non-INVITE request with a - // Status-Code of 100 over any unreliable transport, such as UDP, - // before the amount of time it takes a client transaction's Timer E to be reset to T2. - // An SIP element MAY respond to a non-INVITE request with a - // Status-Code of 100 over a reliable transport at any time. - // https://tools.ietf.org/html/rfc4320#section-4.1 - if (statusCode > 100 && statusCode <= 199) { - throw new Error("Provisional response other than 100 not allowed."); - } - switch (this.state) { - case transaction_state_1.TransactionState.Trying: - // While in the "Trying" state, if the TU passes a provisional response - // to the server transaction, the server transaction MUST enter the "Proceeding" state. - // The response MUST be passed to the transport layer for transmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - this.lastResponse = response; - if (statusCode >= 100 && statusCode < 200) { - this.stateTransition(transaction_state_1.TransactionState.Proceeding); - this.send(response).catch(function (error) { - _this.logTransportError(error, "Failed to send provisional response."); - }); - return; - } - if (statusCode >= 200 && statusCode <= 699) { - this.stateTransition(transaction_state_1.TransactionState.Completed); - this.send(response).catch(function (error) { - _this.logTransportError(error, "Failed to send final response."); - }); - return; - } - break; - case transaction_state_1.TransactionState.Proceeding: - // Any further provisional responses that are received from the TU while - // in the "Proceeding" state MUST be passed to the transport layer for transmission. - // If the TU passes a final response (status codes 200-699) to the server while in - // the "Proceeding" state, the transaction MUST enter the "Completed" state, and - // the response MUST be passed to the transport layer for transmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - this.lastResponse = response; - if (statusCode >= 200 && statusCode <= 699) { - this.stateTransition(transaction_state_1.TransactionState.Completed); - this.send(response).catch(function (error) { - _this.logTransportError(error, "Failed to send final response."); - }); - return; - } - break; - case transaction_state_1.TransactionState.Completed: - // Any other final responses passed by the TU to the server - // transaction MUST be discarded while in the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - return; - case transaction_state_1.TransactionState.Terminated: - break; - default: - throw new Error("Invalid state " + this.state); - } - var message = "Non-INVITE server transaction received unexpected " + statusCode + " response from TU while in state " + this.state + "."; - this.logger.error(message); - throw new Error(message); - }; - /** - * First, the procedures in [4] are followed, which attempt to deliver the response to a backup. - * If those should all fail, based on the definition of failure in [4], the server transaction SHOULD - * inform the TU that a failure has occurred, and SHOULD transition to the terminated state. - * https://tools.ietf.org/html/rfc3261#section-17.2.4 - */ - NonInviteServerTransaction.prototype.onTransportError = function (error) { - if (this.user.onTransportError) { - this.user.onTransportError(error); - } - this.stateTransition(transaction_state_1.TransactionState.Terminated, true); - }; - /** For logging. */ - NonInviteServerTransaction.prototype.typeToString = function () { - return "non-INVITE server transaction"; - }; - NonInviteServerTransaction.prototype.stateTransition = function (newState, dueToTransportError) { - var _this = this; - if (dueToTransportError === void 0) { dueToTransportError = false; } - // Assert valid state transitions. - var invalidStateTransition = function () { - throw new Error("Invalid state transition from " + _this.state + " to " + newState); - }; - switch (newState) { - case transaction_state_1.TransactionState.Trying: - invalidStateTransition(); - break; - case transaction_state_1.TransactionState.Proceeding: - if (this.state !== transaction_state_1.TransactionState.Trying) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Completed: - if (this.state !== transaction_state_1.TransactionState.Trying && this.state !== transaction_state_1.TransactionState.Proceeding) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Terminated: - if (this.state !== transaction_state_1.TransactionState.Proceeding && this.state !== transaction_state_1.TransactionState.Completed) { - if (!dueToTransportError) { - invalidStateTransition(); - } - } - break; - default: - invalidStateTransition(); - } - // When the server transaction enters the "Completed" state, it MUST set Timer J to fire - // in 64*T1 seconds for unreliable transports, and zero seconds for reliable transports. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - if (newState === transaction_state_1.TransactionState.Completed) { - this.J = setTimeout(function () { return _this.timer_J(); }, timers_1.Timers.TIMER_J); - } - // The server transaction MUST be destroyed the instant it enters the "Terminated" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - if (newState === transaction_state_1.TransactionState.Terminated) { - this.dispose(); - } - this.setState(newState); - }; - /** - * The server transaction remains in this state until Timer J fires, - * at which point it MUST transition to the "Terminated" state. - * https://tools.ietf.org/html/rfc3261#section-17.2.2 - */ - NonInviteServerTransaction.prototype.timer_J = function () { - this.logger.debug("Timer J expired for NON-INVITE server transaction " + this.id + "."); - if (this.state === transaction_state_1.TransactionState.Completed) { - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - return NonInviteServerTransaction; -}(server_transaction_1.ServerTransaction)); -exports.NonInviteServerTransaction = NonInviteServerTransaction; - - -/***/ }), -/* 41 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * BYE UAC. - * @public - */ -var ByeUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(ByeUserAgentClient, _super); - function ByeUserAgentClient(dialog, delegate, options) { - var _this = this; - var message = dialog.createOutgoingRequestMessage(messages_1.C.BYE, options); - _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; - dialog.dispose(); - return _this; - } - return ByeUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.ByeUserAgentClient = ByeUserAgentClient; - - -/***/ }), -/* 42 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var messages_1 = __webpack_require__(5); -var transactions_1 = __webpack_require__(27); -/** - * User Agent Client (UAC). - * @remarks - * A user agent client is a logical entity - * that creates a new request, and then uses the client - * transaction state machinery to send it. The role of UAC lasts - * only for the duration of that transaction. In other words, if - * a piece of software initiates a request, it acts as a UAC for - * the duration of that transaction. If it receives a request - * later, it assumes the role of a user agent server for the - * processing of that transaction. - * https://tools.ietf.org/html/rfc3261#section-6 - * @public - */ -var UserAgentClient = /** @class */ (function () { - function UserAgentClient(transactionConstructor, core, message, delegate) { - this.transactionConstructor = transactionConstructor; - this.core = core; - this.message = message; - this.delegate = delegate; - this.challenged = false; - this.stale = false; - this.logger = this.loggerFactory.getLogger("sip.user-agent-client"); - this.init(); - } - UserAgentClient.prototype.dispose = function () { - this.transaction.dispose(); - }; - Object.defineProperty(UserAgentClient.prototype, "loggerFactory", { - get: function () { - return this.core.loggerFactory; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(UserAgentClient.prototype, "transaction", { - /** The transaction associated with this request. */ - get: function () { - if (!this._transaction) { - throw new Error("Transaction undefined."); - } - return this._transaction; - }, - enumerable: true, - configurable: true - }); - /** - * Since requests other than INVITE are responded to immediately, sending a - * CANCEL for a non-INVITE request would always create a race condition. - * A CANCEL request SHOULD NOT be sent to cancel a request other than INVITE. - * https://tools.ietf.org/html/rfc3261#section-9.1 - * @param options - Cancel options bucket. - */ - UserAgentClient.prototype.cancel = function (reason, options) { - var _this = this; - if (options === void 0) { options = {}; } - if (!this.transaction) { - throw new Error("Transaction undefined."); - } - if (!this.message.to) { - throw new Error("To undefined."); - } - if (!this.message.from) { - throw new Error("From undefined."); - } - // The following procedures are used to construct a CANCEL request. The - // Request-URI, Call-ID, To, the numeric part of CSeq, and From header - // fields in the CANCEL request MUST be identical to those in the - // request being cancelled, including tags. A CANCEL constructed by a - // client MUST have only a single Via header field value matching the - // top Via value in the request being cancelled. Using the same values - // for these header fields allows the CANCEL to be matched with the - // request it cancels (Section 9.2 indicates how such matching occurs). - // However, the method part of the CSeq header field MUST have a value - // of CANCEL. This allows it to be identified and processed as a - // transaction in its own right (See Section 17). - // https://tools.ietf.org/html/rfc3261#section-9.1 - var message = this.core.makeOutgoingRequestMessage(messages_1.C.CANCEL, this.message.ruri, this.message.from.uri, this.message.to.uri, { - toTag: this.message.toTag, - fromTag: this.message.fromTag, - callId: this.message.callId, - cseq: this.message.cseq - }, options.extraHeaders); - // TODO: Revisit this. - // The CANCEL needs to use the same branch parameter so that - // it matches the INVITE transaction, but this is a hacky way to do this. - // Or at the very least not well documented. If the the branch parameter - // is set on the outgoing request, the transaction will use it. - // Otherwise the transaction will make a new one. - message.branch = this.message.branch; - if (this.message.headers.Route) { - message.headers.Route = this.message.headers.Route; - } - if (reason) { - message.setHeader("Reason", reason); - } - // If no provisional response has been received, the CANCEL request MUST - // NOT be sent; rather, the client MUST wait for the arrival of a - // provisional response before sending the request. If the original - // request has generated a final response, the CANCEL SHOULD NOT be - // sent, as it is an effective no-op, since CANCEL has no effect on - // requests that have already generated a final response. - // https://tools.ietf.org/html/rfc3261#section-9.1 - if (this.transaction.state === transactions_1.TransactionState.Proceeding) { - var uac = new UserAgentClient(transactions_1.NonInviteClientTransaction, this.core, message); - } - else { - this.transaction.once("stateChanged", function () { - if (_this.transaction && _this.transaction.state === transactions_1.TransactionState.Proceeding) { - var uac = new UserAgentClient(transactions_1.NonInviteClientTransaction, _this.core, message); - } - }); - } - return message; - }; - /** - * If a 401 (Unauthorized) or 407 (Proxy Authentication Required) - * response is received, the UAC SHOULD follow the authorization - * procedures of Section 22.2 and Section 22.3 to retry the request with - * credentials. - * https://tools.ietf.org/html/rfc3261#section-8.1.3.5 - * 22 Usage of HTTP Authentication - * https://tools.ietf.org/html/rfc3261#section-22 - * 22.1 Framework - * https://tools.ietf.org/html/rfc3261#section-22.1 - * 22.2 User-to-User Authentication - * https://tools.ietf.org/html/rfc3261#section-22.2 - * 22.3 Proxy-to-User Authentication - * https://tools.ietf.org/html/rfc3261#section-22.3 - * - * FIXME: This "guard for and retry the request with credentials" - * implementation is not complete and at best minimally passable. - * @param response - The incoming response to guard. - * @returns True if the program execution is to continue in the branch in question. - * Otherwise the request is retried with credentials and current request processing must stop. - */ - UserAgentClient.prototype.authenticationGuard = function (message) { - var statusCode = message.statusCode; - if (!statusCode) { - throw new Error("Response status code undefined."); - } - // If a 401 (Unauthorized) or 407 (Proxy Authentication Required) - // response is received, the UAC SHOULD follow the authorization - // procedures of Section 22.2 and Section 22.3 to retry the request with - // credentials. - // https://tools.ietf.org/html/rfc3261#section-8.1.3.5 - if (statusCode !== 401 && statusCode !== 407) { - return true; - } - // Get and parse the appropriate WWW-Authenticate or Proxy-Authenticate header. - var challenge; - var authorizationHeaderName; - if (statusCode === 401) { - challenge = message.parseHeader("www-authenticate"); - authorizationHeaderName = "authorization"; - } - else { - challenge = message.parseHeader("proxy-authenticate"); - authorizationHeaderName = "proxy-authorization"; - } - // Verify it seems a valid challenge. - if (!challenge) { - this.logger.warn(statusCode + " with wrong or missing challenge, cannot authenticate"); - return true; - } - // Avoid infinite authentications. - if (this.challenged && (this.stale || challenge.stale !== true)) { - this.logger.warn(statusCode + " apparently in authentication loop, cannot authenticate"); - return true; - } - // Get credentials. - if (!this.credentials) { - this.credentials = this.core.configuration.authenticationFactory(); - if (!this.credentials) { - this.logger.warn("Unable to obtain credentials, cannot authenticate"); - return true; - } - } - // Verify that the challenge is really valid. - if (!this.credentials.authenticate(this.message, challenge)) { - return true; - } - this.challenged = true; - if (challenge.stale) { - this.stale = true; - } - var cseq = this.message.cseq += 1; - this.message.setHeader("cseq", cseq + " " + this.message.method); - this.message.setHeader(authorizationHeaderName, this.credentials.toString()); - // Calling init (again) will swap out our existing client transaction with a new one. - // FIXME: HACK: An assumption is being made here that there is nothing that needs to - // be cleaned up beyond the client transaction which is being replaced. For example, - // it is assumed that no early dialogs have been created. - this.init(); - return false; - }; - /** - * Receive a response from the transaction layer. - * @param message - Incoming response message. - */ - UserAgentClient.prototype.receiveResponse = function (message) { - if (!this.authenticationGuard(message)) { - return; - } - var statusCode = message.statusCode ? message.statusCode.toString() : ""; - if (!statusCode) { - throw new Error("Response status code undefined."); - } - switch (true) { - case /^100$/.test(statusCode): - if (this.delegate && this.delegate.onTrying) { - this.delegate.onTrying({ message: message }); - } - break; - case /^1[0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onProgress) { - this.delegate.onProgress({ message: message }); - } - break; - case /^2[0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onAccept) { - this.delegate.onAccept({ message: message }); - } - break; - case /^3[0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onRedirect) { - this.delegate.onRedirect({ message: message }); - } - break; - case /^[4-6][0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onReject) { - this.delegate.onReject({ message: message }); - } - break; - default: - throw new Error("Invalid status code " + statusCode); - } - }; - UserAgentClient.prototype.init = function () { - var _this = this; - // We are the transaction user. - var user = { - loggerFactory: this.loggerFactory, - onRequestTimeout: function () { return _this.onRequestTimeout(); }, - onStateChange: function (newState) { - if (newState === transactions_1.TransactionState.Terminated) { - // Remove the terminated transaction from the core. - _this.core.userAgentClients.delete(userAgentClientId); - // FIXME: HACK: Our transaction may have been swapped out with a new one - // post authentication (see above), so make sure to only to dispose of - // ourselves if this terminating transaction is our current transaction. - if (transaction === _this._transaction) { - _this.dispose(); - } - } - }, - onTransportError: function (error) { return _this.onTransportError(error); }, - receiveResponse: function (message) { return _this.receiveResponse(message); } - }; - // Create a new transaction with us as the user. - var transaction = new this.transactionConstructor(this.message, this.core.transport, user); - this._transaction = transaction; - // Add the new transaction to the core. - var userAgentClientId = transaction.id + transaction.request.method; - this.core.userAgentClients.set(userAgentClientId, this); - }; - /** - * 8.1.3.1 Transaction Layer Errors - * In some cases, the response returned by the transaction layer will - * not be a SIP message, but rather a transaction layer error. When a - * timeout error is received from the transaction layer, it MUST be - * treated as if a 408 (Request Timeout) status code has been received. - * If a fatal transport error is reported by the transport layer - * (generally, due to fatal ICMP errors in UDP or connection failures in - * TCP), the condition MUST be treated as a 503 (Service Unavailable) - * status code. - * https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - */ - UserAgentClient.prototype.onRequestTimeout = function () { - this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout."); - var message = new messages_1.IncomingResponseMessage(); - message.statusCode = 408; - message.reasonPhrase = "Request Timeout"; - this.receiveResponse(message); - return; - }; - /** - * 8.1.3.1 Transaction Layer Errors - * In some cases, the response returned by the transaction layer will - * not be a SIP message, but rather a transaction layer error. When a - * timeout error is received from the transaction layer, it MUST be - * treated as if a 408 (Request Timeout) status code has been received. - * If a fatal transport error is reported by the transport layer - * (generally, due to fatal ICMP errors in UDP or connection failures in - * TCP), the condition MUST be treated as a 503 (Service Unavailable) - * status code. - * https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - */ - UserAgentClient.prototype.onTransportError = function (error) { - this.logger.error(error.message); - this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable."); - var message = new messages_1.IncomingResponseMessage(); - message.statusCode = 503; - message.reasonPhrase = "Service Unavailable"; - this.receiveResponse(message); - }; - return UserAgentClient; -}()); -exports.UserAgentClient = UserAgentClient; - - -/***/ }), -/* 43 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * BYE UAS. - * @public - */ -var ByeUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(ByeUserAgentServer, _super); - function ByeUserAgentServer(dialog, message, delegate) { - return _super.call(this, transactions_1.NonInviteServerTransaction, dialog.userAgentCore, message, delegate) || this; - } - return ByeUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.ByeUserAgentServer = ByeUserAgentServer; - - -/***/ }), -/* 44 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var exceptions_1 = __webpack_require__(31); -var messages_1 = __webpack_require__(5); -var utils_1 = __webpack_require__(16); -var transactions_1 = __webpack_require__(27); -/** - * User Agent Server (UAS). - * @remarks - * A user agent server is a logical entity - * that generates a response to a SIP request. The response - * accepts, rejects, or redirects the request. This role lasts - * only for the duration of that transaction. In other words, if - * a piece of software responds to a request, it acts as a UAS for - * the duration of that transaction. If it generates a request - * later, it assumes the role of a user agent client for the - * processing of that transaction. - * https://tools.ietf.org/html/rfc3261#section-6 - * @public - */ -var UserAgentServer = /** @class */ (function () { - function UserAgentServer(transactionConstructor, core, message, delegate) { - this.transactionConstructor = transactionConstructor; - this.core = core; - this.message = message; - this.delegate = delegate; - this.logger = this.loggerFactory.getLogger("sip.user-agent-server"); - this.toTag = message.toTag ? message.toTag : utils_1.newTag(); - this.init(); - } - UserAgentServer.prototype.dispose = function () { - this.transaction.dispose(); - }; - Object.defineProperty(UserAgentServer.prototype, "loggerFactory", { - get: function () { - return this.core.loggerFactory; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(UserAgentServer.prototype, "transaction", { - /** The transaction associated with this request. */ - get: function () { - if (!this._transaction) { - throw new Error("Transaction undefined."); - } - return this._transaction; - }, - enumerable: true, - configurable: true - }); - UserAgentServer.prototype.accept = function (options) { - if (options === void 0) { options = { statusCode: 200 }; } - if (!this.acceptable) { - throw new exceptions_1.TransactionStateError(this.message.method + " not acceptable in state " + this.transaction.state + "."); - } - var statusCode = options.statusCode; - if (statusCode < 200 || statusCode > 299) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - var response = this.reply(options); - return response; - }; - UserAgentServer.prototype.progress = function (options) { - if (options === void 0) { options = { statusCode: 180 }; } - if (!this.progressable) { - throw new exceptions_1.TransactionStateError(this.message.method + " not progressable in state " + this.transaction.state + "."); - } - var statusCode = options.statusCode; - if (statusCode < 101 || statusCode > 199) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - var response = this.reply(options); - return response; - }; - UserAgentServer.prototype.redirect = function (contacts, options) { - if (options === void 0) { options = { statusCode: 302 }; } - if (!this.redirectable) { - throw new exceptions_1.TransactionStateError(this.message.method + " not redirectable in state " + this.transaction.state + "."); - } - var statusCode = options.statusCode; - if (statusCode < 300 || statusCode > 399) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - var contactHeaders = new Array(); - contacts.forEach(function (contact) { return contactHeaders.push("Contact: " + contact.toString()); }); - options.extraHeaders = (options.extraHeaders || []).concat(contactHeaders); - var response = this.reply(options); - return response; - }; - UserAgentServer.prototype.reject = function (options) { - if (options === void 0) { options = { statusCode: 480 }; } - if (!this.rejectable) { - throw new exceptions_1.TransactionStateError(this.message.method + " not rejectable in state " + this.transaction.state + "."); - } - var statusCode = options.statusCode; - if (statusCode < 400 || statusCode > 699) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - var response = this.reply(options); - return response; - }; - UserAgentServer.prototype.trying = function (options) { - if (!this.tryingable) { - throw new exceptions_1.TransactionStateError(this.message.method + " not tryingable in state " + this.transaction.state + "."); - } - var response = this.reply({ statusCode: 100 }); - return response; - }; - /** - * If the UAS did not find a matching transaction for the CANCEL - * according to the procedure above, it SHOULD respond to the CANCEL - * with a 481 (Call Leg/Transaction Does Not Exist). If the transaction - * for the original request still exists, the behavior of the UAS on - * receiving a CANCEL request depends on whether it has already sent a - * final response for the original request. If it has, the CANCEL - * request has no effect on the processing of the original request, no - * effect on any session state, and no effect on the responses generated - * for the original request. If the UAS has not issued a final response - * for the original request, its behavior depends on the method of the - * original request. If the original request was an INVITE, the UAS - * SHOULD immediately respond to the INVITE with a 487 (Request - * Terminated). A CANCEL request has no impact on the processing of - * transactions with any other method defined in this specification. - * https://tools.ietf.org/html/rfc3261#section-9.2 - * @param request - Incoming CANCEL request. - */ - UserAgentServer.prototype.receiveCancel = function (message) { - // Note: Currently CANCEL is being handled as a special case. - // No UAS is created to handle the CANCEL and the response to - // it CANCEL is being handled statelessly by the user agent core. - // As such, there is currently no way to externally impact the - // response to the a CANCEL request. - if (this.delegate && this.delegate.onCancel) { - this.delegate.onCancel(message); - } - }; - Object.defineProperty(UserAgentServer.prototype, "acceptable", { - get: function () { - if (this.transaction instanceof transactions_1.InviteServerTransaction) { - return (this.transaction.state === transactions_1.TransactionState.Proceeding || - this.transaction.state === transactions_1.TransactionState.Accepted); - } - if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { - return (this.transaction.state === transactions_1.TransactionState.Trying || - this.transaction.state === transactions_1.TransactionState.Proceeding); - } - throw new Error("Unknown transaction type."); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(UserAgentServer.prototype, "progressable", { - get: function () { - if (this.transaction instanceof transactions_1.InviteServerTransaction) { - return this.transaction.state === transactions_1.TransactionState.Proceeding; - } - if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { - return false; // https://tools.ietf.org/html/rfc4320#section-4.1 - } - throw new Error("Unknown transaction type."); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(UserAgentServer.prototype, "redirectable", { - get: function () { - if (this.transaction instanceof transactions_1.InviteServerTransaction) { - return this.transaction.state === transactions_1.TransactionState.Proceeding; - } - if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { - return (this.transaction.state === transactions_1.TransactionState.Trying || - this.transaction.state === transactions_1.TransactionState.Proceeding); - } - throw new Error("Unknown transaction type."); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(UserAgentServer.prototype, "rejectable", { - get: function () { - if (this.transaction instanceof transactions_1.InviteServerTransaction) { - return this.transaction.state === transactions_1.TransactionState.Proceeding; - } - if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { - return (this.transaction.state === transactions_1.TransactionState.Trying || - this.transaction.state === transactions_1.TransactionState.Proceeding); - } - throw new Error("Unknown transaction type."); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(UserAgentServer.prototype, "tryingable", { - get: function () { - if (this.transaction instanceof transactions_1.InviteServerTransaction) { - return this.transaction.state === transactions_1.TransactionState.Proceeding; - } - if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { - return this.transaction.state === transactions_1.TransactionState.Trying; - } - throw new Error("Unknown transaction type."); - }, - enumerable: true, - configurable: true - }); - /** - * When a UAS wishes to construct a response to a request, it follows - * the general procedures detailed in the following subsections. - * Additional behaviors specific to the response code in question, which - * are not detailed in this section, may also be required. - * - * Once all procedures associated with the creation of a response have - * been completed, the UAS hands the response back to the server - * transaction from which it received the request. - * https://tools.ietf.org/html/rfc3261#section-8.2.6 - * @param statusCode - Status code to reply with. - * @param options - Reply options bucket. - */ - UserAgentServer.prototype.reply = function (options) { - if (!options.toTag && options.statusCode !== 100) { - options.toTag = this.toTag; - } - options.userAgent = options.userAgent || this.core.configuration.userAgentHeaderFieldValue; - options.supported = options.supported || this.core.configuration.supportedOptionTagsResponse; - var response = messages_1.constructOutgoingResponse(this.message, options); - this.transaction.receiveResponse(options.statusCode, response.message); - return response; - }; - UserAgentServer.prototype.init = function () { - var _this = this; - // We are the transaction user. - var user = { - loggerFactory: this.loggerFactory, - onStateChange: function (newState) { - if (newState === transactions_1.TransactionState.Terminated) { - // Remove the terminated transaction from the core. - _this.core.userAgentServers.delete(userAgentServerId); - _this.dispose(); - } - }, - onTransportError: function (error) { - _this.logger.error(error.message); - if (_this.delegate && _this.delegate.onTransportError) { - _this.delegate.onTransportError(error); - } - else { - _this.logger.error("User agent server response transport error."); - } - } - }; - // Create a new transaction with us as the user. - var transaction = new this.transactionConstructor(this.message, this.core.transport, user); - this._transaction = transaction; - // Add the new transaction to the core. - var userAgentServerId = transaction.id; - this.core.userAgentServers.set(transaction.id, this); - }; - return UserAgentServer; -}()); -exports.UserAgentServer = UserAgentServer; - - -/***/ }), -/* 45 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * INFO UAC. - * @public - */ -var InfoUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(InfoUserAgentClient, _super); - function InfoUserAgentClient(dialog, delegate, options) { - var _this = this; - var message = dialog.createOutgoingRequestMessage(messages_1.C.INFO, options); - _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; - return _this; - } - return InfoUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.InfoUserAgentClient = InfoUserAgentClient; - - -/***/ }), -/* 46 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * INFO UAS. - * @public - */ -var InfoUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(InfoUserAgentServer, _super); - function InfoUserAgentServer(dialog, message, delegate) { - return _super.call(this, transactions_1.NonInviteServerTransaction, dialog.userAgentCore, message, delegate) || this; - } - return InfoUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.InfoUserAgentServer = InfoUserAgentServer; - - -/***/ }), -/* 47 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * NOTIFY UAS. - * @public - */ -var NotifyUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(NotifyUserAgentClient, _super); - function NotifyUserAgentClient(dialog, delegate, options) { - var _this = this; - var message = dialog.createOutgoingRequestMessage(messages_1.C.NOTIFY, options); - _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; - return _this; - } - return NotifyUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.NotifyUserAgentClient = NotifyUserAgentClient; - - -/***/ }), -/* 48 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * NOTIFY UAS. - * @public - */ -var NotifyUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(NotifyUserAgentServer, _super); - /** - * NOTIFY UAS constructor. - * @param dialogOrCore - Dialog for in dialog NOTIFY, UserAgentCore for out of dialog NOTIFY (deprecated). - * @param message - Incoming NOTIFY request message. - */ - function NotifyUserAgentServer(dialogOrCore, message, delegate) { - var _this = this; - var userAgentCore = instanceOfDialog(dialogOrCore) ? - dialogOrCore.userAgentCore : - dialogOrCore; - _this = _super.call(this, transactions_1.NonInviteServerTransaction, userAgentCore, message, delegate) || this; - return _this; - } - return NotifyUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.NotifyUserAgentServer = NotifyUserAgentServer; -function instanceOfDialog(object) { - return object.userAgentCore !== undefined; -} - - -/***/ }), -/* 49 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * PRACK UAC. - * @public - */ -var PrackUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(PrackUserAgentClient, _super); - function PrackUserAgentClient(dialog, delegate, options) { - var _this = this; - var message = dialog.createOutgoingRequestMessage(messages_1.C.PRACK, options); - _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; - dialog.signalingStateTransition(message); - return _this; - } - return PrackUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.PrackUserAgentClient = PrackUserAgentClient; - - -/***/ }), -/* 50 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * PRACK UAS. - * @public - */ -var PrackUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(PrackUserAgentServer, _super); - function PrackUserAgentServer(dialog, message, delegate) { - var _this = _super.call(this, transactions_1.NonInviteServerTransaction, dialog.userAgentCore, message, delegate) || this; - // Update dialog signaling state with offer/answer in body - dialog.signalingStateTransition(message); - _this.dialog = dialog; - return _this; - } - /** - * Update the dialog signaling state on a 2xx response. - * @param options - Options bucket. - */ - PrackUserAgentServer.prototype.accept = function (options) { - if (options === void 0) { options = { statusCode: 200 }; } - if (options.body) { - // Update dialog signaling state with offer/answer in body - this.dialog.signalingStateTransition(options.body); - } - return _super.prototype.accept.call(this, options); - }; - return PrackUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.PrackUserAgentServer = PrackUserAgentServer; - - -/***/ }), -/* 51 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * Re-INVITE UAC. - * @remarks - * 14 Modifying an Existing Session - * https://tools.ietf.org/html/rfc3261#section-14 - * 14.1 UAC Behavior - * https://tools.ietf.org/html/rfc3261#section-14.1 - * @public - */ -var ReInviteUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(ReInviteUserAgentClient, _super); - function ReInviteUserAgentClient(dialog, delegate, options) { - var _this = this; - var message = dialog.createOutgoingRequestMessage(messages_1.C.INVITE, options); - _this = _super.call(this, transactions_1.InviteClientTransaction, dialog.userAgentCore, message, delegate) || this; - _this.delegate = delegate; - dialog.signalingStateTransition(message); - // FIXME: TODO: next line obviously needs to be improved... - dialog.reinviteUserAgentClient = _this; // let the dialog know re-invite request sent - _this.dialog = dialog; - return _this; - } - ReInviteUserAgentClient.prototype.receiveResponse = function (message) { - var _this = this; - var statusCode = message.statusCode ? message.statusCode.toString() : ""; - if (!statusCode) { - throw new Error("Response status code undefined."); - } - switch (true) { - case /^100$/.test(statusCode): - if (this.delegate && this.delegate.onTrying) { - this.delegate.onTrying({ message: message }); - } - break; - case /^1[0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onProgress) { - this.delegate.onProgress({ - message: message, - session: this.dialog, - prack: function (options) { - throw new Error("Unimplemented."); - } - }); - } - break; - case /^2[0-9]{2}$/.test(statusCode): - // Update dialog signaling state with offer/answer in body - this.dialog.signalingStateTransition(message); - if (this.delegate && this.delegate.onAccept) { - this.delegate.onAccept({ - message: message, - session: this.dialog, - ack: function (options) { - var outgoingAckRequest = _this.dialog.ack(options); - return outgoingAckRequest; - } - }); - } - break; - case /^3[0-9]{2}$/.test(statusCode): - this.dialog.signalingStateRollback(); - this.dialog.reinviteUserAgentClient = undefined; // ACK was handled by transaction - if (this.delegate && this.delegate.onRedirect) { - this.delegate.onRedirect({ message: message }); - } - break; - case /^[4-6][0-9]{2}$/.test(statusCode): - this.dialog.signalingStateRollback(); - this.dialog.reinviteUserAgentClient = undefined; // ACK was handled by transaction - if (this.delegate && this.delegate.onReject) { - this.delegate.onReject({ message: message }); - } - else { - // If a UA receives a non-2xx final response to a re-INVITE, the session - // parameters MUST remain unchanged, as if no re-INVITE had been issued. - // Note that, as stated in Section 12.2.1.2, if the non-2xx final - // response is a 481 (Call/Transaction Does Not Exist), or a 408 - // (Request Timeout), or no response at all is received for the re- - // INVITE (that is, a timeout is returned by the INVITE client - // transaction), the UAC will terminate the dialog. - // - // If a UAC receives a 491 response to a re-INVITE, it SHOULD start a - // timer with a value T chosen as follows: - // - // 1. If the UAC is the owner of the Call-ID of the dialog ID - // (meaning it generated the value), T has a randomly chosen value - // between 2.1 and 4 seconds in units of 10 ms. - // - // 2. If the UAC is not the owner of the Call-ID of the dialog ID, T - // has a randomly chosen value of between 0 and 2 seconds in units - // of 10 ms. - // - // When the timer fires, the UAC SHOULD attempt the re-INVITE once more, - // if it still desires for that session modification to take place. For - // example, if the call was already hung up with a BYE, the re-INVITE - // would not take place. - // https://tools.ietf.org/html/rfc3261#section-14.1 - // FIXME: TODO: The above. - } - break; - default: - throw new Error("Invalid status code " + statusCode); - } - }; - return ReInviteUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.ReInviteUserAgentClient = ReInviteUserAgentClient; - - -/***/ }), -/* 52 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * Re-INVITE UAS. - * @remarks - * 14 Modifying an Existing Session - * https://tools.ietf.org/html/rfc3261#section-14 - * 14.2 UAS Behavior - * https://tools.ietf.org/html/rfc3261#section-14.2 - * @public - */ -var ReInviteUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(ReInviteUserAgentServer, _super); - function ReInviteUserAgentServer(dialog, message, delegate) { - var _this = _super.call(this, transactions_1.InviteServerTransaction, dialog.userAgentCore, message, delegate) || this; - dialog.reinviteUserAgentServer = _this; - _this.dialog = dialog; - return _this; - } - /** - * Update the dialog signaling state on a 2xx response. - * @param options - Options bucket. - */ - ReInviteUserAgentServer.prototype.accept = function (options) { - if (options === void 0) { options = { statusCode: 200 }; } - // FIXME: The next two lines SHOULD go away, but I suppose it's technically harmless... - // These are here because some versions of SIP.js prior to 0.13.8 set the route set - // of all in dialog ACKs based on the Record-Route headers in the associated 2xx - // response. While this worked for dialog forming 2xx responses, it was technically - // broken for re-INVITE ACKS as it only worked if the UAS populated the Record-Route - // headers in the re-INVITE 2xx response (which is not required and a waste of bandwidth - // as the should be ignored if present in re-INVITE ACKS) and the UAS populated - // the Record-Route headers with the correct values (would be weird not too, but...). - // Anyway, for now the technically useless Record-Route headers are being added - // to maintain "backwards compatibility" with the older broken versions of SIP.js. - options.extraHeaders = options.extraHeaders || []; - options.extraHeaders = options.extraHeaders.concat(this.dialog.routeSet.map(function (route) { return "Record-Route: " + route; })); - // Send and return the response - var response = _super.prototype.accept.call(this, options); - var session = this.dialog; - var result = tslib_1.__assign({}, response, { session: session }); - if (options.body) { - // Update dialog signaling state with offer/answer in body - this.dialog.signalingStateTransition(options.body); - } - // Update dialog - this.dialog.reConfirm(); - return result; - }; - /** - * Update the dialog signaling state on a 1xx response. - * @param options - Progress options bucket. - */ - ReInviteUserAgentServer.prototype.progress = function (options) { - if (options === void 0) { options = { statusCode: 180 }; } - // Send and return the response - var response = _super.prototype.progress.call(this, options); - var session = this.dialog; - var result = tslib_1.__assign({}, response, { session: session }); - // Update dialog signaling state - if (options.body) { - this.dialog.signalingStateTransition(options.body); - } - return result; - }; - /** - * TODO: Not Yet Supported - * @param contacts - Contacts to redirect to. - * @param options - Redirect options bucket. - */ - ReInviteUserAgentServer.prototype.redirect = function (contacts, options) { - if (options === void 0) { options = { statusCode: 302 }; } - this.dialog.signalingStateRollback(); - this.dialog.reinviteUserAgentServer = undefined; // ACK will be handled by transaction - throw new Error("Unimplemented."); - }; - /** - * 3.1 Background on Re-INVITE Handling by UASs - * An error response to a re-INVITE has the following semantics. As - * specified in Section 12.2.2 of RFC 3261 [RFC3261], if a re-INVITE is - * rejected, no state changes are performed. - * https://tools.ietf.org/html/rfc6141#section-3.1 - * @param options - Reject options bucket. - */ - ReInviteUserAgentServer.prototype.reject = function (options) { - if (options === void 0) { options = { statusCode: 488 }; } - this.dialog.signalingStateRollback(); - this.dialog.reinviteUserAgentServer = undefined; // ACK will be handled by transaction - return _super.prototype.reject.call(this, options); - }; - return ReInviteUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.ReInviteUserAgentServer = ReInviteUserAgentServer; - - -/***/ }), -/* 53 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * REFER UAC. - * @public - */ -var ReferUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(ReferUserAgentClient, _super); - function ReferUserAgentClient(dialog, delegate, options) { - var _this = this; - var message = dialog.createOutgoingRequestMessage(messages_1.C.REFER, options); - _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; - return _this; - } - return ReferUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.ReferUserAgentClient = ReferUserAgentClient; - - -/***/ }), -/* 54 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * REFER UAS. - * @public - */ -var ReferUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(ReferUserAgentServer, _super); - /** - * REFER UAS constructor. - * @param dialogOrCore - Dialog for in dialog REFER, UserAgentCore for out of dialog REFER. - * @param message - Incoming REFER request message. - */ - function ReferUserAgentServer(dialogOrCore, message, delegate) { - var _this = this; - var userAgentCore = instanceOfSessionDialog(dialogOrCore) ? - dialogOrCore.userAgentCore : - dialogOrCore; - _this = _super.call(this, transactions_1.NonInviteServerTransaction, userAgentCore, message, delegate) || this; - return _this; - } - return ReferUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.ReferUserAgentServer = ReferUserAgentServer; -function instanceOfSessionDialog(object) { - return object.userAgentCore !== undefined; -} - - -/***/ }), -/* 55 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var subscription_1 = __webpack_require__(56); -var timers_1 = __webpack_require__(26); -var allowed_methods_1 = __webpack_require__(58); -var notify_user_agent_server_1 = __webpack_require__(48); -var re_subscribe_user_agent_client_1 = __webpack_require__(59); -var dialog_1 = __webpack_require__(4); -/** - * Subscription Dialog. - * @remarks - * SIP-Specific Event Notification - * - * Abstract - * - * This document describes an extension to the Session Initiation - * Protocol (SIP) defined by RFC 3261. The purpose of this extension is - * to provide an extensible framework by which SIP nodes can request - * notification from remote nodes indicating that certain events have - * occurred. - * - * Note that the event notification mechanisms defined herein are NOT - * intended to be a general-purpose infrastructure for all classes of - * event subscription and notification. - * - * This document represents a backwards-compatible improvement on the - * original mechanism described by RFC 3265, taking into account several - * years of implementation experience. Accordingly, this document - * obsoletes RFC 3265. This document also updates RFC 4660 slightly to - * accommodate some small changes to the mechanism that were discussed - * in that document. - * - * https://tools.ietf.org/html/rfc6665 - * @public - */ -var SubscriptionDialog = /** @class */ (function (_super) { - tslib_1.__extends(SubscriptionDialog, _super); - function SubscriptionDialog(subscriptionEvent, subscriptionExpires, subscriptionState, core, state, delegate) { - var _this = _super.call(this, core, state) || this; - _this.delegate = delegate; - _this._autoRefresh = false; - _this._subscriptionEvent = subscriptionEvent; - _this._subscriptionExpires = subscriptionExpires; - _this._subscriptionExpiresInitial = subscriptionExpires; - _this._subscriptionExpiresLastSet = Math.floor(Date.now() / 1000); - _this._subscriptionRefresh = undefined; - _this._subscriptionRefreshLastSet = undefined; - _this._subscriptionState = subscriptionState; - _this.logger = core.loggerFactory.getLogger("sip.subscribe-dialog"); - _this.logger.log("SUBSCRIBE dialog " + _this.id + " constructed"); - return _this; - } - /** - * When a UAC receives a response that establishes a dialog, it - * constructs the state of the dialog. This state MUST be maintained - * for the duration of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.1.2 - * @param outgoingRequestMessage - Outgoing request message for dialog. - * @param incomingResponseMessage - Incoming response message creating dialog. - */ - SubscriptionDialog.initialDialogStateForSubscription = function (outgoingSubscribeRequestMessage, incomingNotifyRequestMessage) { - // If the request was sent over TLS, and the Request-URI contained a - // SIPS URI, the "secure" flag is set to TRUE. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - var secure = false; // FIXME: Currently no support for TLS. - // The route set MUST be set to the list of URIs in the Record-Route - // header field from the response, taken in reverse order and preserving - // all URI parameters. If no Record-Route header field is present in - // the response, the route set MUST be set to the empty set. This route - // set, even if empty, overrides any pre-existing route set for future - // requests in this dialog. The remote target MUST be set to the URI - // from the Contact header field of the response. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - var routeSet = incomingNotifyRequestMessage.getHeaders("record-route"); - var contact = incomingNotifyRequestMessage.parseHeader("contact"); - if (!contact) { // TODO: Review to make sure this will never happen - throw new Error("Contact undefined."); - } - if (!(contact instanceof messages_1.NameAddrHeader)) { - throw new Error("Contact not instance of NameAddrHeader."); - } - var remoteTarget = contact.uri; - // The local sequence number MUST be set to the value of the sequence - // number in the CSeq header field of the request. The remote sequence - // number MUST be empty (it is established when the remote UA sends a - // request within the dialog). The call identifier component of the - // dialog ID MUST be set to the value of the Call-ID in the request. - // The local tag component of the dialog ID MUST be set to the tag in - // the From field in the request, and the remote tag component of the - // dialog ID MUST be set to the tag in the To field of the response. A - // UAC MUST be prepared to receive a response without a tag in the To - // field, in which case the tag is considered to have a value of null. - // - // This is to maintain backwards compatibility with RFC 2543, which - // did not mandate To tags. - // - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - var localSequenceNumber = outgoingSubscribeRequestMessage.cseq; - var remoteSequenceNumber = undefined; - var callId = outgoingSubscribeRequestMessage.callId; - var localTag = outgoingSubscribeRequestMessage.fromTag; - var remoteTag = incomingNotifyRequestMessage.fromTag; - if (!callId) { // TODO: Review to make sure this will never happen - throw new Error("Call id undefined."); - } - if (!localTag) { // TODO: Review to make sure this will never happen - throw new Error("From tag undefined."); - } - if (!remoteTag) { // TODO: Review to make sure this will never happen - throw new Error("To tag undefined."); // FIXME: No backwards compatibility with RFC 2543 - } - // The remote URI MUST be set to the URI in the To field, and the local - // URI MUST be set to the URI in the From field. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - if (!outgoingSubscribeRequestMessage.from) { // TODO: Review to make sure this will never happen - throw new Error("From undefined."); - } - if (!outgoingSubscribeRequestMessage.to) { // TODO: Review to make sure this will never happen - throw new Error("To undefined."); - } - var localURI = outgoingSubscribeRequestMessage.from.uri; - var remoteURI = outgoingSubscribeRequestMessage.to.uri; - // A dialog can also be in the "early" state, which occurs when it is - // created with a provisional response, and then transition to the - // "confirmed" state when a 2xx final response arrives. - // https://tools.ietf.org/html/rfc3261#section-12 - var early = false; - var dialogState = { - id: callId + localTag + remoteTag, - early: early, - callId: callId, - localTag: localTag, - remoteTag: remoteTag, - localSequenceNumber: localSequenceNumber, - remoteSequenceNumber: remoteSequenceNumber, - localURI: localURI, - remoteURI: remoteURI, - remoteTarget: remoteTarget, - routeSet: routeSet, - secure: secure - }; - return dialogState; - }; - SubscriptionDialog.prototype.dispose = function () { - _super.prototype.dispose.call(this); - if (this.N) { - clearTimeout(this.N); - this.N = undefined; - } - this.refreshTimerClear(); - this.logger.log("SUBSCRIBE dialog " + this.id + " destroyed"); - }; - Object.defineProperty(SubscriptionDialog.prototype, "autoRefresh", { - get: function () { - return this._autoRefresh; - }, - set: function (autoRefresh) { - this._autoRefresh = true; - this.refreshTimerSet(); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SubscriptionDialog.prototype, "subscriptionEvent", { - get: function () { - return this._subscriptionEvent; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SubscriptionDialog.prototype, "subscriptionExpires", { - /** Number of seconds until subscription expires. */ - get: function () { - var secondsSinceLastSet = Math.floor(Date.now() / 1000) - this._subscriptionExpiresLastSet; - var secondsUntilExpires = this._subscriptionExpires - secondsSinceLastSet; - return Math.max(secondsUntilExpires, 0); - }, - set: function (expires) { - if (expires < 0) { - throw new Error("Expires must be greater than or equal to zero."); - } - this._subscriptionExpires = expires; - this._subscriptionExpiresLastSet = Math.floor(Date.now() / 1000); - if (this.autoRefresh) { - var refresh = this.subscriptionRefresh; - if (refresh === undefined || refresh >= expires) { - this.refreshTimerSet(); - } - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SubscriptionDialog.prototype, "subscriptionExpiresInitial", { - get: function () { - return this._subscriptionExpiresInitial; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SubscriptionDialog.prototype, "subscriptionRefresh", { - /** Number of seconds until subscription auto refresh. */ - get: function () { - if (this._subscriptionRefresh === undefined || this._subscriptionRefreshLastSet === undefined) { - return undefined; - } - var secondsSinceLastSet = Math.floor(Date.now() / 1000) - this._subscriptionRefreshLastSet; - var secondsUntilExpires = this._subscriptionRefresh - secondsSinceLastSet; - return Math.max(secondsUntilExpires, 0); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SubscriptionDialog.prototype, "subscriptionState", { - get: function () { - return this._subscriptionState; - }, - enumerable: true, - configurable: true - }); - /** - * Receive in dialog request message from transport. - * @param message - The incoming request message. - */ - SubscriptionDialog.prototype.receiveRequest = function (message) { - this.logger.log("SUBSCRIBE dialog " + this.id + " received " + message.method + " request"); - // Request within a dialog out of sequence guard. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (!this.sequenceGuard(message)) { - this.logger.log("SUBSCRIBE dialog " + this.id + " rejected out of order " + message.method + " request."); - return; - } - // Request within a dialog common processing. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - _super.prototype.receiveRequest.call(this, message); - // Switch on method and then delegate. - switch (message.method) { - case messages_1.C.NOTIFY: - this.onNotify(message); - break; - default: - this.logger.log("SUBSCRIBE dialog " + this.id + " received unimplemented " + message.method + " request"); - this.core.replyStateless(message, { statusCode: 501 }); - break; - } - }; - /** - * 4.1.2.2. Refreshing of Subscriptions - * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - */ - SubscriptionDialog.prototype.refresh = function () { - var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); - var options = {}; - options.extraHeaders = (options.extraHeaders || []).slice(); - options.extraHeaders.push(allowHeader); - options.extraHeaders.push("Event: " + this.subscriptionEvent); - options.extraHeaders.push("Expires: " + this.subscriptionExpiresInitial); - options.extraHeaders.push("Contact: " + this.core.configuration.contact.toString()); - return this.subscribe(undefined, options); - }; - /** - * 4.1.2.2. Refreshing of Subscriptions - * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - * @param delegate - Delegate to handle responses. - * @param options - Options bucket. - */ - SubscriptionDialog.prototype.subscribe = function (delegate, options) { - var _this = this; - if (options === void 0) { options = {}; } - if (this.subscriptionState !== subscription_1.SubscriptionState.Pending && this.subscriptionState !== subscription_1.SubscriptionState.Active) { - // FIXME: This needs to be a proper exception - throw new Error("Invalid state " + this.subscriptionState + ". May only re-subscribe while in state \"pending\" or \"active\"."); - } - this.logger.log("SUBSCRIBE dialog " + this.id + " sending SUBSCRIBE request"); - var uac = new re_subscribe_user_agent_client_1.ReSubscribeUserAgentClient(this, delegate, options); - // When refreshing a subscription, a subscriber starts Timer N, set to - // 64*T1, when it sends the SUBSCRIBE request. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - this.N = setTimeout(function () { return _this.timer_N(); }, timers_1.Timers.TIMER_N); - return uac; - }; - /** - * 4.4.1. Dialog Creation and Termination - * A subscription is destroyed after a notifier sends a NOTIFY request - * with a "Subscription-State" of "terminated", or in certain error - * situations described elsewhere in this document. - * https://tools.ietf.org/html/rfc6665#section-4.4.1 - */ - SubscriptionDialog.prototype.terminate = function () { - this.stateTransition(subscription_1.SubscriptionState.Terminated); - this.onTerminated(); - }; - /** - * 4.1.2.3. Unsubscribing - * https://tools.ietf.org/html/rfc6665#section-4.1.2.3 - */ - SubscriptionDialog.prototype.unsubscribe = function () { - var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); - var options = {}; - options.extraHeaders = (options.extraHeaders || []).slice(); - options.extraHeaders.push(allowHeader); - options.extraHeaders.push("Event: " + this.subscriptionEvent); - options.extraHeaders.push("Expires: 0"); - options.extraHeaders.push("Contact: " + this.core.configuration.contact.toString()); - return this.subscribe(undefined, options); - }; - /** - * Handle in dialog NOTIFY requests. - * This does not include the first NOTIFY which created the dialog. - * @param message - The incoming NOTIFY request message. - */ - SubscriptionDialog.prototype.onNotify = function (message) { - // If, for some reason, the event package designated in the "Event" - // header field of the NOTIFY request is not supported, the subscriber - // will respond with a 489 (Bad Event) response. - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - var event = message.parseHeader("Event").event; - if (!event || event !== this.subscriptionEvent) { - this.core.replyStateless(message, { statusCode: 489 }); - return; - } - // In the state diagram, "Re-subscription times out" means that an - // attempt to refresh or update the subscription using a new SUBSCRIBE - // request does not result in a NOTIFY request before the corresponding - // Timer N expires. - // https://tools.ietf.org/html/rfc6665#section-4.1.2 - if (this.N) { - clearTimeout(this.N); - this.N = undefined; - } - // NOTIFY requests MUST contain "Subscription-State" header fields that - // indicate the status of the subscription. - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - var subscriptionState = message.parseHeader("Subscription-State"); - if (!subscriptionState || !subscriptionState.state) { - this.core.replyStateless(message, { statusCode: 489 }); - return; - } - var state = subscriptionState.state; - var expires = subscriptionState.expires ? Math.max(subscriptionState.expires, 0) : undefined; - // Update our state and expiration. - switch (state) { - case "pending": - this.stateTransition(subscription_1.SubscriptionState.Pending, expires); - break; - case "active": - this.stateTransition(subscription_1.SubscriptionState.Active, expires); - break; - case "terminated": - this.stateTransition(subscription_1.SubscriptionState.Terminated, expires); - break; - default: - this.logger.warn("Unrecognized subscription state."); - break; - } - // Delegate remainder of NOTIFY handling. - var uas = new notify_user_agent_server_1.NotifyUserAgentServer(this, message); - if (this.delegate && this.delegate.onNotify) { - this.delegate.onNotify(uas); - } - else { - uas.accept(); - } - }; - SubscriptionDialog.prototype.onRefresh = function (request) { - if (this.delegate && this.delegate.onRefresh) { - this.delegate.onRefresh(request); - } - }; - SubscriptionDialog.prototype.onTerminated = function () { - if (this.delegate && this.delegate.onTerminated) { - this.delegate.onTerminated(); - } - }; - SubscriptionDialog.prototype.refreshTimerClear = function () { - if (this.refreshTimer) { - clearTimeout(this.refreshTimer); - this.refreshTimer = undefined; - } - }; - SubscriptionDialog.prototype.refreshTimerSet = function () { - var _this = this; - this.refreshTimerClear(); - if (this.autoRefresh && this.subscriptionExpires > 0) { - var refresh = this.subscriptionExpires * 900; - this._subscriptionRefresh = Math.floor(refresh / 1000); - this._subscriptionRefreshLastSet = Math.floor(Date.now() / 1000); - this.refreshTimer = setTimeout(function () { - _this.refreshTimer = undefined; - _this._subscriptionRefresh = undefined; - _this._subscriptionRefreshLastSet = undefined; - _this.onRefresh(_this.refresh()); - }, refresh); - } - }; - SubscriptionDialog.prototype.stateTransition = function (newState, newExpires) { - var _this = this; - // Assert valid state transitions. - var invalidStateTransition = function () { - _this.logger.warn("Invalid subscription state transition from " + _this.subscriptionState + " to " + newState); - }; - switch (newState) { - case subscription_1.SubscriptionState.Initial: - invalidStateTransition(); - return; - case subscription_1.SubscriptionState.NotifyWait: - invalidStateTransition(); - return; - case subscription_1.SubscriptionState.Pending: - if (this.subscriptionState !== subscription_1.SubscriptionState.NotifyWait && - this.subscriptionState !== subscription_1.SubscriptionState.Pending) { - invalidStateTransition(); - return; - } - break; - case subscription_1.SubscriptionState.Active: - if (this.subscriptionState !== subscription_1.SubscriptionState.NotifyWait && - this.subscriptionState !== subscription_1.SubscriptionState.Pending && - this.subscriptionState !== subscription_1.SubscriptionState.Active) { - invalidStateTransition(); - return; - } - break; - case subscription_1.SubscriptionState.Terminated: - if (this.subscriptionState !== subscription_1.SubscriptionState.NotifyWait && - this.subscriptionState !== subscription_1.SubscriptionState.Pending && - this.subscriptionState !== subscription_1.SubscriptionState.Active) { - invalidStateTransition(); - return; - } - break; - default: - invalidStateTransition(); - return; - } - // If the "Subscription-State" value is "pending", the subscription has - // been received by the notifier, but there is insufficient policy - // information to grant or deny the subscription yet. If the header - // field also contains an "expires" parameter, the subscriber SHOULD - // take it as the authoritative subscription duration and adjust - // accordingly. No further action is necessary on the part of the - // subscriber. The "retry-after" and "reason" parameters have no - // semantics for "pending". - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - if (newState === subscription_1.SubscriptionState.Pending) { - if (newExpires) { - this.subscriptionExpires = newExpires; - } - } - // If the "Subscription-State" header field value is "active", it means - // that the subscription has been accepted and (in general) has been - // authorized. If the header field also contains an "expires" - // parameter, the subscriber SHOULD take it as the authoritative - // subscription duration and adjust accordingly. The "retry-after" and - // "reason" parameters have no semantics for "active". - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - if (newState === subscription_1.SubscriptionState.Active) { - if (newExpires) { - this.subscriptionExpires = newExpires; - } - } - // If the "Subscription-State" value is "terminated", the subscriber - // MUST consider the subscription terminated. The "expires" parameter - // has no semantics for "terminated" -- notifiers SHOULD NOT include an - // "expires" parameter on a "Subscription-State" header field with a - // value of "terminated", and subscribers MUST ignore any such - // parameter, if present. - if (newState === subscription_1.SubscriptionState.Terminated) { - this.dispose(); - } - this._subscriptionState = newState; - }; - /** - * When refreshing a subscription, a subscriber starts Timer N, set to - * 64*T1, when it sends the SUBSCRIBE request. If this Timer N expires - * prior to the receipt of a NOTIFY request, the subscriber considers - * the subscription terminated. If the subscriber receives a success - * response to the SUBSCRIBE request that indicates that no NOTIFY - * request will be generated -- such as the 204 response defined for use - * with the optional extension described in [RFC5839] -- then it MUST - * cancel Timer N. - * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - */ - SubscriptionDialog.prototype.timer_N = function () { - if (this.subscriptionState !== subscription_1.SubscriptionState.Terminated) { - this.stateTransition(subscription_1.SubscriptionState.Terminated); - this.onTerminated(); - } - }; - return SubscriptionDialog; -}(dialog_1.Dialog)); -exports.SubscriptionDialog = SubscriptionDialog; - - -/***/ }), -/* 56 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -tslib_1.__exportStar(__webpack_require__(57), exports); - - -/***/ }), -/* 57 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * Subscription state. - * @remarks - * https://tools.ietf.org/html/rfc6665#section-4.1.2 - * @public - */ -var SubscriptionState; -(function (SubscriptionState) { - SubscriptionState["Initial"] = "Initial"; - SubscriptionState["NotifyWait"] = "NotifyWait"; - SubscriptionState["Pending"] = "Pending"; - SubscriptionState["Active"] = "Active"; - SubscriptionState["Terminated"] = "Terminated"; -})(SubscriptionState = exports.SubscriptionState || (exports.SubscriptionState = {})); - - -/***/ }), -/* 58 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var messages_1 = __webpack_require__(5); -/** - * FIXME: TODO: Should be configurable/variable. - */ -exports.AllowedMethods = [ - messages_1.C.ACK, - messages_1.C.BYE, - messages_1.C.CANCEL, - messages_1.C.INFO, - messages_1.C.INVITE, - messages_1.C.MESSAGE, - messages_1.C.NOTIFY, - messages_1.C.OPTIONS, - messages_1.C.PRACK, - messages_1.C.REFER, - messages_1.C.REGISTER, - messages_1.C.SUBSCRIBE -]; - - -/***/ }), -/* 59 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * Re-SUBSCRIBE UAC. - * @public - */ -var ReSubscribeUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(ReSubscribeUserAgentClient, _super); - function ReSubscribeUserAgentClient(dialog, delegate, options) { - var _this = this; - var message = dialog.createOutgoingRequestMessage(messages_1.C.SUBSCRIBE, options); - _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; - _this.dialog = dialog; - return _this; - } - ReSubscribeUserAgentClient.prototype.waitNotifyStop = function () { - // TODO: Placeholder. Not utilized currently. - return; - }; - /** - * Receive a response from the transaction layer. - * @param message - Incoming response message. - */ - ReSubscribeUserAgentClient.prototype.receiveResponse = function (message) { - if (message.statusCode && message.statusCode >= 200 && message.statusCode < 300) { - // The "Expires" header field in a 200-class response to SUBSCRIBE - // request indicates the actual duration for which the subscription will - // remain active (unless refreshed). The received value might be - // smaller than the value indicated in the SUBSCRIBE request but cannot - // be larger; see Section 4.2.1 for details. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - var expires = message.getHeader("Expires"); - if (!expires) { - this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE"); - } - else { - var subscriptionExpiresReceived = Number(expires); - if (this.dialog.subscriptionExpires > subscriptionExpiresReceived) { - this.dialog.subscriptionExpires = subscriptionExpiresReceived; - } - } - } - if (message.statusCode && message.statusCode >= 400 && message.statusCode < 700) { - // If a SUBSCRIBE request to refresh a subscription receives a 404, 405, - // 410, 416, 480-485, 489, 501, or 604 response, the subscriber MUST - // consider the subscription terminated. (See [RFC5057] for further - // details and notes about the effect of error codes on dialogs and - // usages within dialog, such as subscriptions). If the subscriber - // wishes to re-subscribe to the state, he does so by composing an - // unrelated initial SUBSCRIBE request with a freshly generated Call-ID - // and a new, unique "From" tag (see Section 4.1.2.1). - // https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - var errorCodes = [404, 405, 410, 416, 480, 481, 482, 483, 484, 485, 489, 501, 604]; - if (errorCodes.includes(message.statusCode)) { - this.dialog.terminate(); - } - // If a SUBSCRIBE request to refresh a subscription fails with any error - // code other than those listed above, the original subscription is - // still considered valid for the duration of the most recently known - // "Expires" value as negotiated by the most recent successful SUBSCRIBE - // transaction, or as communicated by a NOTIFY request in its - // "Subscription-State" header field "expires" parameter. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - } - _super.prototype.receiveResponse.call(this, message); - }; - return ReSubscribeUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.ReSubscribeUserAgentClient = ReSubscribeUserAgentClient; - - -/***/ }), -/* 60 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -tslib_1.__exportStar(__webpack_require__(61), exports); -tslib_1.__exportStar(__webpack_require__(62), exports); -tslib_1.__exportStar(__webpack_require__(63), exports); - - -/***/ }), -/* 61 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * Log levels. - * @public - */ -var Levels; -(function (Levels) { - Levels[Levels["error"] = 0] = "error"; - Levels[Levels["warn"] = 1] = "warn"; - Levels[Levels["log"] = 2] = "log"; - Levels[Levels["debug"] = 3] = "debug"; -})(Levels = exports.Levels || (exports.Levels = {})); - - -/***/ }), -/* 62 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var levels_1 = __webpack_require__(61); -var logger_1 = __webpack_require__(63); -/** - * Logger. - * @public - */ -var LoggerFactory = /** @class */ (function () { - function LoggerFactory() { - this.builtinEnabled = true; - this._level = levels_1.Levels.log; - this.loggers = {}; - this.logger = this.getLogger("sip:loggerfactory"); - } - Object.defineProperty(LoggerFactory.prototype, "level", { - get: function () { return this._level; }, - set: function (newLevel) { - if (newLevel >= 0 && newLevel <= 3) { - this._level = newLevel; - } - else if (newLevel > 3) { - this._level = 3; - } - else if (levels_1.Levels.hasOwnProperty(newLevel)) { - this._level = newLevel; - } - else { - this.logger.error("invalid 'level' parameter value: " + JSON.stringify(newLevel)); - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(LoggerFactory.prototype, "connector", { - get: function () { - return this._connector; - }, - set: function (value) { - if (!value) { - this._connector = undefined; - } - else if (typeof value === "function") { - this._connector = value; - } - else { - this.logger.error("invalid 'connector' parameter value: " + JSON.stringify(value)); - } - }, - enumerable: true, - configurable: true - }); - LoggerFactory.prototype.getLogger = function (category, label) { - if (label && this.level === 3) { - return new logger_1.Logger(this, category, label); - } - else if (this.loggers[category]) { - return this.loggers[category]; - } - else { - var logger = new logger_1.Logger(this, category); - this.loggers[category] = logger; - return logger; - } - }; - LoggerFactory.prototype.genericLog = function (levelToLog, category, label, content) { - if (this.level >= levelToLog) { - if (this.builtinEnabled) { - this.print(levelToLog, category, label, content); - } - } - if (this.connector) { - this.connector(levels_1.Levels[levelToLog], category, label, content); - } - }; - LoggerFactory.prototype.print = function (levelToLog, category, label, content) { - if (typeof content === "string") { - var prefix = [new Date(), category]; - if (label) { - prefix.push(label); - } - content = prefix.concat(content).join(" | "); - } - switch (levelToLog) { - case levels_1.Levels.error: - // tslint:disable-next-line:no-console - console.error(content); - break; - case levels_1.Levels.warn: - // tslint:disable-next-line:no-console - console.warn(content); - break; - case levels_1.Levels.log: - // tslint:disable-next-line:no-console - console.log(content); - break; - case levels_1.Levels.debug: - // tslint:disable-next-line:no-console - console.debug(content); - break; - default: - break; - } - }; - return LoggerFactory; -}()); -exports.LoggerFactory = LoggerFactory; - - -/***/ }), -/* 63 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var levels_1 = __webpack_require__(61); -/** - * Logger. - * @public - */ -var Logger = /** @class */ (function () { - function Logger(logger, category, label) { - this.logger = logger; - this.category = category; - this.label = label; - } - Logger.prototype.error = function (content) { this.genericLog(levels_1.Levels.error, content); }; - Logger.prototype.warn = function (content) { this.genericLog(levels_1.Levels.warn, content); }; - Logger.prototype.log = function (content) { this.genericLog(levels_1.Levels.log, content); }; - Logger.prototype.debug = function (content) { this.genericLog(levels_1.Levels.debug, content); }; - Logger.prototype.genericLog = function (level, content) { - this.logger.genericLog(level, this.category, this.label, content); - }; - return Logger; -}()); -exports.Logger = Logger; - - -/***/ }), -/* 64 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -tslib_1.__exportStar(__webpack_require__(65), exports); - - -/***/ }), -/* 65 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var messages_1 = __webpack_require__(5); -var transactions_1 = __webpack_require__(27); -var user_agents_1 = __webpack_require__(66); -var allowed_methods_1 = __webpack_require__(58); -/** - * This is ported from UA.C.ACCEPTED_BODY_TYPES. - * FIXME: TODO: Should be configurable/variable. - */ -var acceptedBodyTypes = [ - "application/sdp", - "application/dtmf-relay" -]; -/** - * User Agent Core. - * @remarks - * Core designates the functions specific to a particular type - * of SIP entity, i.e., specific to either a stateful or stateless - * proxy, a user agent or registrar. All cores, except those for - * the stateless proxy, are transaction users. - * https://tools.ietf.org/html/rfc3261#section-6 - * - * UAC Core: The set of processing functions required of a UAC that - * reside above the transaction and transport layers. - * https://tools.ietf.org/html/rfc3261#section-6 - * - * UAS Core: The set of processing functions required at a UAS that - * resides above the transaction and transport layers. - * https://tools.ietf.org/html/rfc3261#section-6 - * @public - */ -var UserAgentCore = /** @class */ (function () { - /** - * Constructor. - * @param configuration - Configuration. - * @param delegate - Delegate. - */ - function UserAgentCore(configuration, delegate) { - if (delegate === void 0) { delegate = {}; } - /** UACs. */ - this.userAgentClients = new Map(); - /** UASs. */ - this.userAgentServers = new Map(); - this.configuration = configuration; - this.delegate = delegate; - this.dialogs = new Map(); - this.subscribers = new Map(); - this.logger = configuration.loggerFactory.getLogger("sip.user-agent-core"); - } - /** Destructor. */ - UserAgentCore.prototype.dispose = function () { - this.reset(); - }; - /** Reset. */ - UserAgentCore.prototype.reset = function () { - this.dialogs.forEach(function (dialog) { return dialog.dispose(); }); - this.dialogs.clear(); - this.subscribers.forEach(function (subscriber) { return subscriber.dispose(); }); - this.subscribers.clear(); - this.userAgentClients.forEach(function (uac) { return uac.dispose(); }); - this.userAgentClients.clear(); - this.userAgentServers.forEach(function (uac) { return uac.dispose(); }); - this.userAgentServers.clear(); - }; - Object.defineProperty(UserAgentCore.prototype, "loggerFactory", { - /** Logger factory. */ - get: function () { - return this.configuration.loggerFactory; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(UserAgentCore.prototype, "transport", { - /** Transport. */ - get: function () { - var transport = this.configuration.transportAccessor(); - if (!transport) { - throw new Error("Transport undefined."); - } - return transport; - }, - enumerable: true, - configurable: true - }); - /** - * Send INVITE. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - UserAgentCore.prototype.invite = function (request, delegate) { - return new user_agents_1.InviteUserAgentClient(this, request, delegate); - }; - /** - * Send MESSAGE. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - UserAgentCore.prototype.message = function (request, delegate) { - return new user_agents_1.MessageUserAgentClient(this, request, delegate); - }; - /** - * Send PUBLISH. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - UserAgentCore.prototype.publish = function (request, delegate) { - return new user_agents_1.PublishUserAgentClient(this, request, delegate); - }; - /** - * Send REGISTER. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - UserAgentCore.prototype.register = function (request, delegate) { - return new user_agents_1.RegisterUserAgentClient(this, request, delegate); - }; - /** - * Send SUBSCRIBE. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - UserAgentCore.prototype.subscribe = function (request, delegate) { - return new user_agents_1.SubscribeUserAgentClient(this, request, delegate); - }; - /** - * Send a request. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - UserAgentCore.prototype.request = function (request, delegate) { - return new user_agents_1.UserAgentClient(transactions_1.NonInviteClientTransaction, this, request, delegate); - }; - /** - * Outgoing request message factory function. - * @param method - Method. - * @param requestURI - Request-URI. - * @param fromURI - From URI. - * @param toURI - To URI. - * @param options - Request options. - * @param extraHeaders - Extra headers to add. - * @param body - Message body. - */ - UserAgentCore.prototype.makeOutgoingRequestMessage = function (method, requestURI, fromURI, toURI, options, extraHeaders, body) { - // default values from user agent configuration - var callIdPrefix = this.configuration.sipjsId; - var fromDisplayName = this.configuration.displayName; - var forceRport = this.configuration.viaForceRport; - var hackViaTcp = this.configuration.hackViaTcp; - var optionTags = this.configuration.supportedOptionTags.slice(); - if (method === messages_1.C.REGISTER) { - optionTags.push("path", "gruu"); - } - if (method === messages_1.C.INVITE && (this.configuration.contact.pubGruu || this.configuration.contact.tempGruu)) { - optionTags.push("gruu"); - } - var routeSet = this.configuration.routeSet; - var userAgentString = this.configuration.userAgentHeaderFieldValue; - var viaHost = this.configuration.viaHost; - var defaultOptions = { - callIdPrefix: callIdPrefix, - forceRport: forceRport, - fromDisplayName: fromDisplayName, - hackViaTcp: hackViaTcp, - optionTags: optionTags, - routeSet: routeSet, - userAgentString: userAgentString, - viaHost: viaHost, - }; - // merge provided options with default options - var requestOptions = tslib_1.__assign({}, defaultOptions, options); - return new messages_1.OutgoingRequestMessage(method, requestURI, fromURI, toURI, requestOptions, extraHeaders, body); - }; - /** - * Handle an incoming request message from the transport. - * @param message - Incoming request message from transport layer. - */ - UserAgentCore.prototype.receiveIncomingRequestFromTransport = function (message) { - this.receiveRequestFromTransport(message); - }; - /** - * Handle an incoming response message from the transport. - * @param message - Incoming response message from transport layer. - */ - UserAgentCore.prototype.receiveIncomingResponseFromTransport = function (message) { - this.receiveResponseFromTransport(message); - }; - /** - * A stateless UAS is a UAS that does not maintain transaction state. - * It replies to requests normally, but discards any state that would - * ordinarily be retained by a UAS after a response has been sent. If a - * stateless UAS receives a retransmission of a request, it regenerates - * the response and re-sends it, just as if it were replying to the first - * instance of the request. A UAS cannot be stateless unless the request - * processing for that method would always result in the same response - * if the requests are identical. This rules out stateless registrars, - * for example. Stateless UASs do not use a transaction layer; they - * receive requests directly from the transport layer and send responses - * directly to the transport layer. - * https://tools.ietf.org/html/rfc3261#section-8.2.7 - * @param message - Incoming request message to reply to. - * @param statusCode - Status code to reply with. - */ - UserAgentCore.prototype.replyStateless = function (message, options) { - var userAgent = this.configuration.userAgentHeaderFieldValue; - var supported = this.configuration.supportedOptionTagsResponse; - options = tslib_1.__assign({}, options, { userAgent: userAgent, supported: supported }); - var response = messages_1.constructOutgoingResponse(message, options); - this.transport.send(response.message); - return response; - }; - /** - * In Section 18.2.1, replace the last paragraph with: - * - * Next, the server transport attempts to match the request to a - * server transaction. It does so using the matching rules described - * in Section 17.2.3. If a matching server transaction is found, the - * request is passed to that transaction for processing. If no match - * is found, the request is passed to the core, which may decide to - * construct a new server transaction for that request. - * https://tools.ietf.org/html/rfc6026#section-8.10 - * @param message - Incoming request message from transport layer. - */ - UserAgentCore.prototype.receiveRequestFromTransport = function (message) { - // When a request is received from the network by the server, it has to - // be matched to an existing transaction. This is accomplished in the - // following manner. - // - // The branch parameter in the topmost Via header field of the request - // is examined. If it is present and begins with the magic cookie - // "z9hG4bK", the request was generated by a client transaction - // compliant to this specification. Therefore, the branch parameter - // will be unique across all transactions sent by that client. The - // request matches a transaction if: - // - // 1. the branch parameter in the request is equal to the one in the - // top Via header field of the request that created the - // transaction, and - // - // 2. the sent-by value in the top Via of the request is equal to the - // one in the request that created the transaction, and - // - // 3. the method of the request matches the one that created the - // transaction, except for ACK, where the method of the request - // that created the transaction is INVITE. - // - // This matching rule applies to both INVITE and non-INVITE transactions - // alike. - // - // The sent-by value is used as part of the matching process because - // there could be accidental or malicious duplication of branch - // parameters from different clients. - // https://tools.ietf.org/html/rfc3261#section-17.2.3 - var transactionId = message.viaBranch; // FIXME: Currently only using rule 1... - var uas = this.userAgentServers.get(transactionId); - // When receiving an ACK that matches an existing INVITE server - // transaction and that does not contain a branch parameter containing - // the magic cookie defined in RFC 3261, the matching transaction MUST - // be checked to see if it is in the "Accepted" state. If it is, then - // the ACK must be passed directly to the transaction user instead of - // being absorbed by the transaction state machine. This is necessary - // as requests from RFC 2543 clients will not include a unique branch - // parameter, and the mechanisms for calculating the transaction ID from - // such a request will be the same for both INVITE and ACKs. - // https://tools.ietf.org/html/rfc6026#section-6 - // Any ACKs received from the network while in the "Accepted" state MUST be - // passed directly to the TU and not absorbed. - // https://tools.ietf.org/html/rfc6026#section-7.1 - if (message.method === messages_1.C.ACK) { - if (uas && uas.transaction.state === transactions_1.TransactionState.Accepted) { - if (uas instanceof user_agents_1.InviteUserAgentServer) { - // These are ACKs matching an INVITE server transaction. - // These should never happen with RFC 3261 compliant user agents - // (would be a broken ACK to negative final response or something) - // but is apparently how RFC 2543 user agents do things. - // We are not currently supporting this case. - // NOTE: Not backwards compatible with RFC 2543 (no support for strict-routing). - this.logger.warn("Discarding out of dialog ACK after 2xx response sent on transaction " + transactionId + "."); - return; - } - } - } - // The CANCEL method requests that the TU at the server side cancel a - // pending transaction. The TU determines the transaction to be - // cancelled by taking the CANCEL request, and then assuming that the - // request method is anything but CANCEL or ACK and applying the - // transaction matching procedures of Section 17.2.3. The matching - // transaction is the one to be cancelled. - // https://tools.ietf.org/html/rfc3261#section-9.2 - if (message.method === messages_1.C.CANCEL) { - if (uas) { - // Regardless of the method of the original request, as long as the - // CANCEL matched an existing transaction, the UAS answers the CANCEL - // request itself with a 200 (OK) response. - // https://tools.ietf.org/html/rfc3261#section-9.2 - this.replyStateless(message, { statusCode: 200 }); - // If the transaction for the original request still exists, the behavior - // of the UAS on receiving a CANCEL request depends on whether it has already - // sent a final response for the original request. If it has, the CANCEL - // request has no effect on the processing of the original request, no - // effect on any session state, and no effect on the responses generated - // for the original request. If the UAS has not issued a final response - // for the original request, its behavior depends on the method of the - // original request. If the original request was an INVITE, the UAS - // SHOULD immediately respond to the INVITE with a 487 (Request - // Terminated). - // https://tools.ietf.org/html/rfc3261#section-9.2 - if (uas.transaction instanceof transactions_1.InviteServerTransaction && - uas.transaction.state === transactions_1.TransactionState.Proceeding) { - if (uas instanceof user_agents_1.InviteUserAgentServer) { - uas.receiveCancel(message); - } - // A CANCEL request has no impact on the processing of - // transactions with any other method defined in this specification. - // https://tools.ietf.org/html/rfc3261#section-9.2 - } - } - else { - // If the UAS did not find a matching transaction for the CANCEL - // according to the procedure above, it SHOULD respond to the CANCEL - // with a 481 (Call Leg/Transaction Does Not Exist). - // https://tools.ietf.org/html/rfc3261#section-9.2 - this.replyStateless(message, { statusCode: 481 }); - } - return; - } - // If a matching server transaction is found, the request is passed to that - // transaction for processing. - // https://tools.ietf.org/html/rfc6026#section-8.10 - if (uas) { - uas.transaction.receiveRequest(message); - return; - } - // If no match is found, the request is passed to the core, which may decide to - // construct a new server transaction for that request. - // https://tools.ietf.org/html/rfc6026#section-8.10 - this.receiveRequest(message); - return; - }; - /** - * UAC and UAS procedures depend strongly on two factors. First, based - * on whether the request or response is inside or outside of a dialog, - * and second, based on the method of a request. Dialogs are discussed - * thoroughly in Section 12; they represent a peer-to-peer relationship - * between user agents and are established by specific SIP methods, such - * as INVITE. - * @param message - Incoming request message. - */ - UserAgentCore.prototype.receiveRequest = function (message) { - // 8.2 UAS Behavior - // UASs SHOULD process the requests in the order of the steps that - // follow in this section (that is, starting with authentication, then - // inspecting the method, the header fields, and so on throughout the - // remainder of this section). - // https://tools.ietf.org/html/rfc3261#section-8.2 - // 8.2.1 Method Inspection - // Once a request is authenticated (or authentication is skipped), the - // UAS MUST inspect the method of the request. If the UAS recognizes - // but does not support the method of a request, it MUST generate a 405 - // (Method Not Allowed) response. Procedures for generating responses - // are described in Section 8.2.6. The UAS MUST also add an Allow - // header field to the 405 (Method Not Allowed) response. The Allow - // header field MUST list the set of methods supported by the UAS - // generating the message. - // https://tools.ietf.org/html/rfc3261#section-8.2.1 - if (!allowed_methods_1.AllowedMethods.includes(message.method)) { - var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); - this.replyStateless(message, { - statusCode: 405, - extraHeaders: [allowHeader] - }); - return; - } - // 8.2.2 Header Inspection - // https://tools.ietf.org/html/rfc3261#section-8.2.2 - if (!message.ruri) { // FIXME: A request message should always have an ruri - throw new Error("Request-URI undefined."); - } - // 8.2.2.1 To and Request-URI - // If the Request-URI uses a scheme not supported by the UAS, it SHOULD - // reject the request with a 416 (Unsupported URI Scheme) response. - // https://tools.ietf.org/html/rfc3261#section-8.2.2.1 - if (message.ruri.scheme !== "sip") { - this.replyStateless(message, { statusCode: 416 }); - return; - } - // 8.2.2.1 To and Request-URI - // If the Request-URI does not identify an address that the - // UAS is willing to accept requests for, it SHOULD reject - // the request with a 404 (Not Found) response. - // https://tools.ietf.org/html/rfc3261#section-8.2.2.1 - var ruri = message.ruri; - var ruriMatches = function (uri) { - return !!uri && uri.user === ruri.user; - }; - if (!ruriMatches(this.configuration.aor) && - !(ruriMatches(this.configuration.contact.uri) || - ruriMatches(this.configuration.contact.pubGruu) || - ruriMatches(this.configuration.contact.tempGruu))) { - this.logger.warn("Request-URI does not point to us."); - if (message.method !== messages_1.C.ACK) { - this.replyStateless(message, { statusCode: 404 }); - } - return; - } - // 8.2.2.1 To and Request-URI - // Other potential sources of received Request-URIs include - // the Contact header fields of requests and responses sent by the UA - // that establish or refresh dialogs. - // https://tools.ietf.org/html/rfc3261#section-8.2.2.1 - if (message.method === messages_1.C.INVITE) { - if (!message.hasHeader("Contact")) { - this.replyStateless(message, { - statusCode: 400, - reasonPhrase: "Missing Contact Header" - }); - return; - } - } - // 8.2.2.2 Merged Requests - // If the request has no tag in the To header field, the UAS core MUST - // check the request against ongoing transactions. If the From tag, - // Call-ID, and CSeq exactly match those associated with an ongoing - // transaction, but the request does not match that transaction (based - // on the matching rules in Section 17.2.3), the UAS core SHOULD - // generate a 482 (Loop Detected) response and pass it to the server - // transaction. - // - // The same request has arrived at the UAS more than once, following - // different paths, most likely due to forking. The UAS processes - // the first such request received and responds with a 482 (Loop - // Detected) to the rest of them. - // https://tools.ietf.org/html/rfc3261#section-8.2.2.2 - if (!message.toTag) { - var transactionId = message.viaBranch; - if (!this.userAgentServers.has(transactionId)) { - var mergedRequest = Array.from(this.userAgentServers.values()) - .some(function (uas) { - return uas.transaction.request.fromTag === message.fromTag && - uas.transaction.request.callId === message.callId && - uas.transaction.request.cseq === message.cseq; - }); - if (mergedRequest) { - this.replyStateless(message, { statusCode: 482 }); - return; - } - } - } - // 8.2.2.3 Require - // https://tools.ietf.org/html/rfc3261#section-8.2.2.3 - // TODO - // 8.2.3 Content Processing - // https://tools.ietf.org/html/rfc3261#section-8.2.3 - // TODO - // 8.2.4 Applying Extensions - // https://tools.ietf.org/html/rfc3261#section-8.2.4 - // TODO - // 8.2.5 Processing the Request - // Assuming all of the checks in the previous subsections are passed, - // the UAS processing becomes method-specific. - // https://tools.ietf.org/html/rfc3261#section-8.2.5 - // The UAS will receive the request from the transaction layer. If the - // request has a tag in the To header field, the UAS core computes the - // dialog identifier corresponding to the request and compares it with - // existing dialogs. If there is a match, this is a mid-dialog request. - // In that case, the UAS first applies the same processing rules for - // requests outside of a dialog, discussed in Section 8.2. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (message.toTag) { - this.receiveInsideDialogRequest(message); - } - else { - this.receiveOutsideDialogRequest(message); - } - return; - }; - /** - * Once a dialog has been established between two UAs, either of them - * MAY initiate new transactions as needed within the dialog. The UA - * sending the request will take the UAC role for the transaction. The - * UA receiving the request will take the UAS role. Note that these may - * be different roles than the UAs held during the transaction that - * established the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.2 - * @param message - Incoming request message. - */ - UserAgentCore.prototype.receiveInsideDialogRequest = function (message) { - // NOTIFY requests are matched to such SUBSCRIBE requests if they - // contain the same "Call-ID", a "To" header field "tag" parameter that - // matches the "From" header field "tag" parameter of the SUBSCRIBE - // request, and the same "Event" header field. Rules for comparisons of - // the "Event" header fields are described in Section 8.2.1. - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - if (message.method === messages_1.C.NOTIFY) { - var event_1 = message.parseHeader("Event"); - if (!event_1 || !event_1.event) { - this.replyStateless(message, { statusCode: 489 }); - return; - } - // FIXME: Subscriber id should also matching on event id. - var subscriberId = message.callId + message.toTag + event_1.event; - var subscriber = this.subscribers.get(subscriberId); - if (subscriber) { - var uas = new user_agents_1.NotifyUserAgentServer(this, message); - subscriber.onNotify(uas); - return; - } - } - // Requests sent within a dialog, as any other requests, are atomic. If - // a particular request is accepted by the UAS, all the state changes - // associated with it are performed. If the request is rejected, none - // of the state changes are performed. - // - // Note that some requests, such as INVITEs, affect several pieces of - // state. - // - // The UAS will receive the request from the transaction layer. If the - // request has a tag in the To header field, the UAS core computes the - // dialog identifier corresponding to the request and compares it with - // existing dialogs. If there is a match, this is a mid-dialog request. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - var dialogId = message.callId + message.toTag + message.fromTag; - var dialog = this.dialogs.get(dialogId); - if (dialog) { - // [Sip-implementors] Reg. SIP reinvite, UPDATE and OPTIONS - // You got the question right. - // - // And you got the right answer too. :-) - // - // Thanks, - // Paul - // - // Robert Sparks wrote: - // > So I've lost track of the question during the musing. - // > - // > I _think_ the fundamental question being asked is this: - // > - // > Is an endpoint required to reject (with a 481) an OPTIONS request that - // > arrives with at to-tag but does not match any existing dialog state. - // > (Assuming some earlier requirement hasn't forced another error code). Or - // > is it OK if it just sends - // > a 200 OK anyhow. - // > - // > My take on the collection of specs is that its _not_ ok for it to send - // > the 200 OK anyhow and that it is required to send - // > the 481. I base this primarily on these sentences from 11.2 in 3261: - // > - // > The response to an OPTIONS is constructed using the standard rules - // > for a SIP response as discussed in Section 8.2.6. The response code - // > chosen MUST be the same that would have been chosen had the request - // > been an INVITE. - // > - // > Did I miss the point of the question? - // > - // > On May 15, 2008, at 12:48 PM, Paul Kyzivat wrote: - // > - // >> [Including Robert in hopes of getting his insight on this.] - // https://lists.cs.columbia.edu/pipermail/sip-implementors/2008-May/019178.html - // - // Requests that do not change in any way the state of a dialog may be - // received within a dialog (for example, an OPTIONS request). They are - // processed as if they had been received outside the dialog. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (message.method === messages_1.C.OPTIONS) { - var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); - var acceptHeader = "Accept: " + acceptedBodyTypes.toString(); - this.replyStateless(message, { - statusCode: 200, - extraHeaders: [allowHeader, acceptHeader] - }); - return; - } - // Pass the incoming request to the dialog for further handling. - dialog.receiveRequest(message); - return; - } - // The most important behaviors of a stateless UAS are the following: - // ... - // o A stateless UAS MUST ignore ACK requests. - // ... - // https://tools.ietf.org/html/rfc3261#section-8.2.7 - if (message.method === messages_1.C.ACK) { - // If a final response to an INVITE was sent statelessly, - // the corresponding ACK: - // - will not match an existing transaction - // - may have tag in the To header field - // - not not match any existing dialogs - // Absorb unmatched ACKs. - return; - } - // If the request has a tag in the To header field, but the dialog - // identifier does not match any existing dialogs, the UAS may have - // crashed and restarted, or it may have received a request for a - // different (possibly failed) UAS (the UASs can construct the To tags - // so that a UAS can identify that the tag was for a UAS for which it is - // providing recovery). Another possibility is that the incoming - // request has been simply mis-routed. Based on the To tag, the UAS MAY - // either accept or reject the request. Accepting the request for - // acceptable To tags provides robustness, so that dialogs can persist - // even through crashes. UAs wishing to support this capability must - // take into consideration some issues such as choosing monotonically - // increasing CSeq sequence numbers even across reboots, reconstructing - // the route set, and accepting out-of-range RTP timestamps and sequence - // numbers. - // - // If the UAS wishes to reject the request because it does not wish to - // recreate the dialog, it MUST respond to the request with a 481 - // (Call/Transaction Does Not Exist) status code and pass that to the - // server transaction. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - this.replyStateless(message, { statusCode: 481 }); - return; - }; - /** - * Assuming all of the checks in the previous subsections are passed, - * the UAS processing becomes method-specific. - * https://tools.ietf.org/html/rfc3261#section-8.2.5 - * @param message - Incoming request message. - */ - UserAgentCore.prototype.receiveOutsideDialogRequest = function (message) { - switch (message.method) { - case messages_1.C.ACK: - // Absorb stray out of dialog ACKs - break; - case messages_1.C.BYE: - // If the BYE does not match an existing dialog, the UAS core SHOULD - // generate a 481 (Call/Transaction Does Not Exist) response and pass - // that to the server transaction. This rule means that a BYE sent - // without tags by a UAC will be rejected. - // https://tools.ietf.org/html/rfc3261#section-15.1.2 - this.replyStateless(message, { statusCode: 481 }); - break; - case messages_1.C.CANCEL: - throw new Error("Unexpected out of dialog request method " + message.method + "."); - break; - case messages_1.C.INFO: - // Use of the INFO method does not constitute a separate dialog usage. - // INFO messages are always part of, and share the fate of, an invite - // dialog usage [RFC5057]. INFO messages cannot be sent as part of - // other dialog usages, or outside an existing dialog. - // https://tools.ietf.org/html/rfc6086#section-1 - this.replyStateless(message, { statusCode: 405 }); // Should never happen - break; - case messages_1.C.INVITE: - // https://tools.ietf.org/html/rfc3261#section-13.3.1 - { - var uas = new user_agents_1.InviteUserAgentServer(this, message); - this.delegate.onInvite ? - this.delegate.onInvite(uas) : - uas.reject(); - } - break; - case messages_1.C.MESSAGE: - // MESSAGE requests are discouraged inside a dialog. Implementations - // are restricted from creating a usage for the purpose of carrying a - // sequence of MESSAGE requests (though some implementations use it that - // way, against the standard recommendation). - // https://tools.ietf.org/html/rfc5057#section-5.3 - { - var uas = new user_agents_1.MessageUserAgentServer(this, message); - this.delegate.onMessage ? - this.delegate.onMessage(uas) : - uas.accept(); - } - break; - case messages_1.C.NOTIFY: - // Obsoleted by: RFC 6665 - // If any non-SUBSCRIBE mechanisms are defined to create subscriptions, - // it is the responsibility of the parties defining those mechanisms to - // ensure that correlation of a NOTIFY message to the corresponding - // subscription is possible. Designers of such mechanisms are also - // warned to make a distinction between sending a NOTIFY message to a - // subscriber who is aware of the subscription, and sending a NOTIFY - // message to an unsuspecting node. The latter behavior is invalid, and - // MUST receive a "481 Subscription does not exist" response (unless - // some other 400- or 500-class error code is more applicable), as - // described in section 3.2.4. In other words, knowledge of a - // subscription must exist in both the subscriber and the notifier to be - // valid, even if installed via a non-SUBSCRIBE mechanism. - // https://tools.ietf.org/html/rfc3265#section-3.2 - // - // NOTIFY requests are sent to inform subscribers of changes in state to - // which the subscriber has a subscription. Subscriptions are created - // using the SUBSCRIBE method. In legacy implementations, it is - // possible that other means of subscription creation have been used. - // However, this specification does not allow the creation of - // subscriptions except through SUBSCRIBE requests and (for backwards- - // compatibility) REFER requests [RFC3515]. - // https://tools.ietf.org/html/rfc6665#section-3.2 - { - var uas = new user_agents_1.NotifyUserAgentServer(this, message); - this.delegate.onNotify ? - this.delegate.onNotify(uas) : - uas.reject({ statusCode: 405 }); - } - break; - case messages_1.C.OPTIONS: - // https://tools.ietf.org/html/rfc3261#section-11.2 - { - var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); - var acceptHeader = "Accept: " + acceptedBodyTypes.toString(); - this.replyStateless(message, { - statusCode: 200, - extraHeaders: [allowHeader, acceptHeader] - }); - } - break; - case messages_1.C.REFER: - // https://tools.ietf.org/html/rfc3515#section-2.4.2 - { - var uas = new user_agents_1.ReferUserAgentServer(this, message); - this.delegate.onRefer ? - this.delegate.onRefer(uas) : - uas.reject({ statusCode: 405 }); - } - break; - case messages_1.C.REGISTER: - // https://tools.ietf.org/html/rfc3261#section-10.3 - { - var uas = new user_agents_1.RegisterUserAgentServer(this, message); - this.delegate.onRegister ? - this.delegate.onRegister(uas) : - uas.reject({ statusCode: 405 }); - } - break; - case messages_1.C.SUBSCRIBE: - // https://tools.ietf.org/html/rfc6665#section-4.2 - { - var uas = new user_agents_1.SubscribeUserAgentServer(this, message); - this.delegate.onSubscribe ? - this.delegate.onSubscribe(uas) : - uas.reject({ statusCode: 480 }); - } - break; - default: - throw new Error("Unexpected out of dialog request method " + message.method + "."); - } - return; - }; - /** - * Responses are first processed by the transport layer and then passed - * up to the transaction layer. The transaction layer performs its - * processing and then passes the response up to the TU. The majority - * of response processing in the TU is method specific. However, there - * are some general behaviors independent of the method. - * https://tools.ietf.org/html/rfc3261#section-8.1.3 - * @param message - Incoming response message from transport layer. - */ - UserAgentCore.prototype.receiveResponseFromTransport = function (message) { - // 8.1.3.1 Transaction Layer Errors - // https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - // Handled by transaction layer callbacks. - // 8.1.3.2 Unrecognized Responses - // https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - // TODO - // 8.1.3.3 Vias - // https://tools.ietf.org/html/rfc3261#section-8.1.3.3 - if (message.getHeaders("via").length > 1) { - this.logger.warn("More than one Via header field present in the response, dropping"); - return; - } - // 8.1.3.4 Processing 3xx Responses - // https://tools.ietf.org/html/rfc3261#section-8.1.3.4 - // TODO - // 8.1.3.5 Processing 4xx Responses - // https://tools.ietf.org/html/rfc3261#section-8.1.3.5 - // TODO - // When the transport layer in the client receives a response, it has to - // determine which client transaction will handle the response, so that - // the processing of Sections 17.1.1 and 17.1.2 can take place. The - // branch parameter in the top Via header field is used for this - // purpose. A response matches a client transaction under two - // conditions: - // - // 1. If the response has the same value of the branch parameter in - // the top Via header field as the branch parameter in the top - // Via header field of the request that created the transaction. - // - // 2. If the method parameter in the CSeq header field matches the - // method of the request that created the transaction. The - // method is needed since a CANCEL request constitutes a - // different transaction, but shares the same value of the branch - // parameter. - // https://tools.ietf.org/html/rfc3261#section-17.1.3 - var userAgentClientId = message.viaBranch + message.method; - var userAgentClient = this.userAgentClients.get(userAgentClientId); - // The client transport uses the matching procedures of Section - // 17.1.3 to attempt to match the response to an existing - // transaction. If there is a match, the response MUST be passed to - // that transaction. Otherwise, any element other than a stateless - // proxy MUST silently discard the response. - // https://tools.ietf.org/html/rfc6026#section-8.9 - if (userAgentClient) { - userAgentClient.transaction.receiveResponse(message); - } - else { - this.logger.warn("Discarding unmatched " + message.statusCode + " response to " + message.method + " " + userAgentClientId + "."); - } - }; - return UserAgentCore; -}()); -exports.UserAgentCore = UserAgentCore; - - -/***/ }), -/* 66 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -tslib_1.__exportStar(__webpack_require__(41), exports); -tslib_1.__exportStar(__webpack_require__(43), exports); -tslib_1.__exportStar(__webpack_require__(67), exports); -tslib_1.__exportStar(__webpack_require__(45), exports); -tslib_1.__exportStar(__webpack_require__(46), exports); -tslib_1.__exportStar(__webpack_require__(68), exports); -tslib_1.__exportStar(__webpack_require__(69), exports); -tslib_1.__exportStar(__webpack_require__(70), exports); -tslib_1.__exportStar(__webpack_require__(71), exports); -tslib_1.__exportStar(__webpack_require__(47), exports); -tslib_1.__exportStar(__webpack_require__(48), exports); -tslib_1.__exportStar(__webpack_require__(72), exports); -tslib_1.__exportStar(__webpack_require__(49), exports); -tslib_1.__exportStar(__webpack_require__(50), exports); -tslib_1.__exportStar(__webpack_require__(51), exports); -tslib_1.__exportStar(__webpack_require__(52), exports); -tslib_1.__exportStar(__webpack_require__(59), exports); -tslib_1.__exportStar(__webpack_require__(73), exports); -tslib_1.__exportStar(__webpack_require__(53), exports); -tslib_1.__exportStar(__webpack_require__(54), exports); -tslib_1.__exportStar(__webpack_require__(74), exports); -tslib_1.__exportStar(__webpack_require__(75), exports); -tslib_1.__exportStar(__webpack_require__(76), exports); -tslib_1.__exportStar(__webpack_require__(77), exports); -tslib_1.__exportStar(__webpack_require__(42), exports); -tslib_1.__exportStar(__webpack_require__(44), exports); - - -/***/ }), -/* 67 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * CANCEL UAC. - * @public - */ -var CancelUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(CancelUserAgentClient, _super); - function CancelUserAgentClient(core, message, delegate) { - return _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; - } - return CancelUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.CancelUserAgentClient = CancelUserAgentClient; - - -/***/ }), -/* 68 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var dialogs_1 = __webpack_require__(3); -var session_1 = __webpack_require__(24); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * INVITE UAC. - * @remarks - * 13 Initiating a Session - * https://tools.ietf.org/html/rfc3261#section-13 - * 13.1 Overview - * https://tools.ietf.org/html/rfc3261#section-13.1 - * 13.2 UAC Processing - * https://tools.ietf.org/html/rfc3261#section-13.2 - * @public - */ -var InviteUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(InviteUserAgentClient, _super); - function InviteUserAgentClient(core, message, delegate) { - var _this = _super.call(this, transactions_1.InviteClientTransaction, core, message, delegate) || this; - _this.confirmedDialogAcks = new Map(); - _this.confirmedDialogs = new Map(); - _this.earlyDialogs = new Map(); - _this.delegate = delegate; - return _this; - } - InviteUserAgentClient.prototype.dispose = function () { - // The UAC core considers the INVITE transaction completed 64*T1 seconds - // after the reception of the first 2xx response. At this point all the - // early dialogs that have not transitioned to established dialogs are - // terminated. Once the INVITE transaction is considered completed by - // the UAC core, no more new 2xx responses are expected to arrive. - // - // If, after acknowledging any 2xx response to an INVITE, the UAC does - // not want to continue with that dialog, then the UAC MUST terminate - // the dialog by sending a BYE request as described in Section 15. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - this.earlyDialogs.forEach(function (earlyDialog) { return earlyDialog.dispose(); }); - this.earlyDialogs.clear(); - _super.prototype.dispose.call(this); - }; - /** - * Once the INVITE has been passed to the INVITE client transaction, the - * UAC waits for responses for the INVITE. - * https://tools.ietf.org/html/rfc3261#section-13.2.2 - * @param incomingResponse - Incoming response to INVITE request. - */ - InviteUserAgentClient.prototype.receiveResponse = function (message) { - var _this = this; - if (!this.authenticationGuard(message)) { - return; - } - var statusCode = message.statusCode ? message.statusCode.toString() : ""; - if (!statusCode) { - throw new Error("Response status code undefined."); - } - switch (true) { - case /^100$/.test(statusCode): - if (this.delegate && this.delegate.onTrying) { - this.delegate.onTrying({ message: message }); - } - return; - case /^1[0-9]{2}$/.test(statusCode): - // Zero, one or multiple provisional responses may arrive before one or - // more final responses are received. Provisional responses for an - // INVITE request can create "early dialogs". If a provisional response - // has a tag in the To field, and if the dialog ID of the response does - // not match an existing dialog, one is constructed using the procedures - // defined in Section 12.1.2. - // - // The early dialog will only be needed if the UAC needs to send a - // request to its peer within the dialog before the initial INVITE - // transaction completes. Header fields present in a provisional - // response are applicable as long as the dialog is in the early state - // (for example, an Allow header field in a provisional response - // contains the methods that can be used in the dialog while this is in - // the early state). - // https://tools.ietf.org/html/rfc3261#section-13.2.2.1 - { - // Provisional without to tag, no dialog to create. - if (!message.toTag) { - this.logger.warn("Non-100 1xx INVITE response received without a to tag, dropping."); - return; - } - // Compute dialog state. - var dialogState = dialogs_1.Dialog.initialDialogStateForUserAgentClient(this.message, message); - // Have existing early dialog or create a new one. - var earlyDialog = this.earlyDialogs.get(dialogState.id); - if (!earlyDialog) { - var transaction = this.transaction; - if (!(transaction instanceof transactions_1.InviteClientTransaction)) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - earlyDialog = new dialogs_1.SessionDialog(transaction, this.core, dialogState); - this.earlyDialogs.set(earlyDialog.id, earlyDialog); - } - // Guard against out of order reliable provisional responses. - // Note that this is where the rseq tracking is done. - if (!earlyDialog.reliableSequenceGuard(message)) { - this.logger.warn("1xx INVITE reliable response received out of order, dropping."); - return; - } - // If the initial offer is in an INVITE, the answer MUST be in a - // reliable non-failure message from UAS back to UAC which is - // correlated to that INVITE. For this specification, that is - // only the final 2xx response to that INVITE. That same exact - // answer MAY also be placed in any provisional responses sent - // prior to the answer. The UAC MUST treat the first session - // description it receives as the answer, and MUST ignore any - // session descriptions in subsequent responses to the initial - // INVITE. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - if (earlyDialog.signalingState === session_1.SignalingState.Initial || - earlyDialog.signalingState === session_1.SignalingState.HaveLocalOffer) { - earlyDialog.signalingStateTransition(message); - } - // Pass response to delegate. - var session_2 = earlyDialog; - if (this.delegate && this.delegate.onProgress) { - this.delegate.onProgress({ - message: message, - session: session_2, - prack: function (options) { - var outgoingPrackRequest = session_2.prack(undefined, options); - return outgoingPrackRequest; - } - }); - } - } - return; - case /^2[0-9]{2}$/.test(statusCode): - // Multiple 2xx responses may arrive at the UAC for a single INVITE - // request due to a forking proxy. Each response is distinguished by - // the tag parameter in the To header field, and each represents a - // distinct dialog, with a distinct dialog identifier. - // - // If the dialog identifier in the 2xx response matches the dialog - // identifier of an existing dialog, the dialog MUST be transitioned to - // the "confirmed" state, and the route set for the dialog MUST be - // recomputed based on the 2xx response using the procedures of Section - // 12.2.1.2. Otherwise, a new dialog in the "confirmed" state MUST be - // constructed using the procedures of Section 12.1.2. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - { - // Compute dialog state. - var dialogState = dialogs_1.Dialog.initialDialogStateForUserAgentClient(this.message, message); - // NOTE: Currently our transaction layer is caching the 2xx ACKs and - // handling retransmissions of the ACK which is an approach which is - // not to spec. In any event, this block is intended to provide a to - // spec implementation of ACK retransmissions, but it should not be - // hit currently. - var dialog = this.confirmedDialogs.get(dialogState.id); - if (dialog) { - // Once the ACK has been constructed, the procedures of [4] are used to - // determine the destination address, port and transport. However, the - // request is passed to the transport layer directly for transmission, - // rather than a client transaction. This is because the UAC core - // handles retransmissions of the ACK, not the transaction layer. The - // ACK MUST be passed to the client transport every time a - // retransmission of the 2xx final response that triggered the ACK - // arrives. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - var outgoingAckRequest = this.confirmedDialogAcks.get(dialogState.id); - if (outgoingAckRequest) { - var transaction = this.transaction; - if (!(transaction instanceof transactions_1.InviteClientTransaction)) { - throw new Error("Client transaction not instance of InviteClientTransaction."); - } - transaction.ackResponse(outgoingAckRequest.message); - } - else { - // If still waiting for an ACK, drop the retransmission of the 2xx final response. - } - return; - } - // If the dialog identifier in the 2xx response matches the dialog - // identifier of an existing dialog, the dialog MUST be transitioned to - // the "confirmed" state, and the route set for the dialog MUST be - // recomputed based on the 2xx response using the procedures of Section - // 12.2.1.2. Otherwise, a new dialog in the "confirmed" state MUST be - // constructed using the procedures of Section 12.1.2. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - dialog = this.earlyDialogs.get(dialogState.id); - if (dialog) { - dialog.confirm(); - dialog.recomputeRouteSet(message); - this.earlyDialogs.delete(dialog.id); - this.confirmedDialogs.set(dialog.id, dialog); - } - else { - var transaction = this.transaction; - if (!(transaction instanceof transactions_1.InviteClientTransaction)) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - dialog = new dialogs_1.SessionDialog(transaction, this.core, dialogState); - this.confirmedDialogs.set(dialog.id, dialog); - } - // If the initial offer is in an INVITE, the answer MUST be in a - // reliable non-failure message from UAS back to UAC which is - // correlated to that INVITE. For this specification, that is - // only the final 2xx response to that INVITE. That same exact - // answer MAY also be placed in any provisional responses sent - // prior to the answer. The UAC MUST treat the first session - // description it receives as the answer, and MUST ignore any - // session descriptions in subsequent responses to the initial - // INVITE. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - if (dialog.signalingState === session_1.SignalingState.Initial || - dialog.signalingState === session_1.SignalingState.HaveLocalOffer) { - dialog.signalingStateTransition(message); - } - // Session Initiated! :) - var session_3 = dialog; - // The UAC core MUST generate an ACK request for each 2xx received from - // the transaction layer. The header fields of the ACK are constructed - // in the same way as for any request sent within a dialog (see Section - // 12) with the exception of the CSeq and the header fields related to - // authentication. The sequence number of the CSeq header field MUST be - // the same as the INVITE being acknowledged, but the CSeq method MUST - // be ACK. The ACK MUST contain the same credentials as the INVITE. If - // the 2xx contains an offer (based on the rules above), the ACK MUST - // carry an answer in its body. If the offer in the 2xx response is not - // acceptable, the UAC core MUST generate a valid answer in the ACK and - // then send a BYE immediately. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - if (this.delegate && this.delegate.onAccept) { - this.delegate.onAccept({ - message: message, - session: session_3, - ack: function (options) { - var outgoingAckRequest = session_3.ack(options); - _this.confirmedDialogAcks.set(session_3.id, outgoingAckRequest); - return outgoingAckRequest; - } - }); - } - else { - var outgoingAckRequest = session_3.ack(); - this.confirmedDialogAcks.set(session_3.id, outgoingAckRequest); - } - } - return; - case /^3[0-9]{2}$/.test(statusCode): - // 12.3 Termination of a Dialog - // - // Independent of the method, if a request outside of a dialog generates - // a non-2xx final response, any early dialogs created through - // provisional responses to that request are terminated. The mechanism - // for terminating confirmed dialogs is method specific. In this - // specification, the BYE method terminates a session and the dialog - // associated with it. See Section 15 for details. - // https://tools.ietf.org/html/rfc3261#section-12.3 - // All early dialogs are considered terminated upon reception of the - // non-2xx final response. - // - // After having received the non-2xx final response the UAC core - // considers the INVITE transaction completed. The INVITE client - // transaction handles the generation of ACKs for the response (see - // Section 17). - // https://tools.ietf.org/html/rfc3261#section-13.2.2.3 - this.earlyDialogs.forEach(function (earlyDialog) { return earlyDialog.dispose(); }); - this.earlyDialogs.clear(); - // A 3xx response may contain one or more Contact header field values - // providing new addresses where the callee might be reachable. - // Depending on the status code of the 3xx response (see Section 21.3), - // the UAC MAY choose to try those new addresses. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.2 - if (this.delegate && this.delegate.onRedirect) { - this.delegate.onRedirect({ message: message }); - } - return; - case /^[4-6][0-9]{2}$/.test(statusCode): - // 12.3 Termination of a Dialog - // - // Independent of the method, if a request outside of a dialog generates - // a non-2xx final response, any early dialogs created through - // provisional responses to that request are terminated. The mechanism - // for terminating confirmed dialogs is method specific. In this - // specification, the BYE method terminates a session and the dialog - // associated with it. See Section 15 for details. - // https://tools.ietf.org/html/rfc3261#section-12.3 - // All early dialogs are considered terminated upon reception of the - // non-2xx final response. - // - // After having received the non-2xx final response the UAC core - // considers the INVITE transaction completed. The INVITE client - // transaction handles the generation of ACKs for the response (see - // Section 17). - // https://tools.ietf.org/html/rfc3261#section-13.2.2.3 - this.earlyDialogs.forEach(function (earlyDialog) { return earlyDialog.dispose(); }); - this.earlyDialogs.clear(); - // A single non-2xx final response may be received for the INVITE. 4xx, - // 5xx and 6xx responses may contain a Contact header field value - // indicating the location where additional information about the error - // can be found. Subsequent final responses (which would only arrive - // under error conditions) MUST be ignored. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.3 - if (this.delegate && this.delegate.onReject) { - this.delegate.onReject({ message: message }); - } - return; - default: - throw new Error("Invalid status code " + statusCode); - } - throw new Error("Executing what should be an unreachable code path receiving " + statusCode + " response."); - }; - return InviteUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.InviteUserAgentClient = InviteUserAgentClient; - - -/***/ }), -/* 69 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var dialogs_1 = __webpack_require__(3); -var exceptions_1 = __webpack_require__(31); -var session_1 = __webpack_require__(24); -var transactions_1 = __webpack_require__(27); -var allowed_methods_1 = __webpack_require__(58); -var user_agent_server_1 = __webpack_require__(44); -/** - * INVITE UAS. - * @remarks - * 13 Initiating a Session - * https://tools.ietf.org/html/rfc3261#section-13 - * 13.1 Overview - * https://tools.ietf.org/html/rfc3261#section-13.1 - * 13.3 UAS Processing - * https://tools.ietf.org/html/rfc3261#section-13.3 - * @public - */ -var InviteUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(InviteUserAgentServer, _super); - function InviteUserAgentServer(core, message, delegate) { - var _this = _super.call(this, transactions_1.InviteServerTransaction, core, message, delegate) || this; - _this.core = core; - return _this; - } - InviteUserAgentServer.prototype.dispose = function () { - if (this.earlyDialog) { - this.earlyDialog.dispose(); - } - _super.prototype.dispose.call(this); - }; - /** - * 13.3.1.4 The INVITE is Accepted - * The UAS core generates a 2xx response. This response establishes a - * dialog, and therefore follows the procedures of Section 12.1.1 in - * addition to those of Section 8.2.6. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - * @param options - Accept options bucket. - */ - InviteUserAgentServer.prototype.accept = function (options) { - if (options === void 0) { options = { statusCode: 200 }; } - if (!this.acceptable) { - throw new exceptions_1.TransactionStateError(this.message.method + " not acceptable in state " + this.transaction.state + "."); - } - // This response establishes a dialog... - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - if (!this.confirmedDialog) { - if (this.earlyDialog) { - this.earlyDialog.confirm(); - this.confirmedDialog = this.earlyDialog; - this.earlyDialog = undefined; - } - else { - var transaction = this.transaction; - if (!(transaction instanceof transactions_1.InviteServerTransaction)) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - var state = dialogs_1.Dialog.initialDialogStateForUserAgentServer(this.message, this.toTag); - this.confirmedDialog = new dialogs_1.SessionDialog(transaction, this.core, state); - } - } - // When a UAS responds to a request with a response that establishes a - // dialog (such as a 2xx to INVITE), the UAS MUST copy all Record-Route - // header field values from the request into the response (including the - // URIs, URI parameters, and any Record-Route header field parameters, - // whether they are known or unknown to the UAS) and MUST maintain the - // order of those values. The UAS MUST add a Contact header field to - // the response. The Contact header field contains an address where the - // UAS would like to be contacted for subsequent requests in the dialog - // (which includes the ACK for a 2xx response in the case of an INVITE). - // Generally, the host portion of this URI is the IP address or FQDN of - // the host. The URI provided in the Contact header field MUST be a SIP - // or SIPS URI. If the request that initiated the dialog contained a - // SIPS URI in the Request-URI or in the top Record-Route header field - // value, if there was any, or the Contact header field if there was no - // Record-Route header field, the Contact header field in the response - // MUST be a SIPS URI. The URI SHOULD have global scope (that is, the - // same URI can be used in messages outside this dialog). The same way, - // the scope of the URI in the Contact header field of the INVITE is not - // limited to this dialog either. It can therefore be used in messages - // to the UAC even outside this dialog. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - var recordRouteHeader = this.message - .getHeaders("record-route") - .map(function (header) { return "Record-Route: " + header; }); - var contactHeader = "Contact: " + this.core.configuration.contact.toString(); - // A 2xx response to an INVITE SHOULD contain the Allow header field and - // the Supported header field, and MAY contain the Accept header field. - // Including these header fields allows the UAC to determine the - // features and extensions supported by the UAS for the duration of the - // call, without probing. - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - // FIXME: TODO: This should not be hard coded. - var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); - // FIXME: TODO: Supported header (see reply()) - // FIXME: TODO: Accept header - // If the INVITE request contained an offer, and the UAS had not yet - // sent an answer, the 2xx MUST contain an answer. If the INVITE did - // not contain an offer, the 2xx MUST contain an offer if the UAS had - // not yet sent an offer. - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - if (!options.body) { - if (this.confirmedDialog.signalingState === session_1.SignalingState.Stable) { - options.body = this.confirmedDialog.answer; // resend the answer sent in provisional response - } - else if (this.confirmedDialog.signalingState === session_1.SignalingState.Initial || - this.confirmedDialog.signalingState === session_1.SignalingState.HaveRemoteOffer) { - throw new Error("Response must have a body."); - } - } - options.statusCode = options.statusCode || 200; - options.extraHeaders = options.extraHeaders || []; - options.extraHeaders = options.extraHeaders.concat(recordRouteHeader); - options.extraHeaders.push(allowHeader); - options.extraHeaders.push(contactHeader); - var response = _super.prototype.accept.call(this, options); - var session = this.confirmedDialog; - var result = tslib_1.__assign({}, response, { session: session }); - // Update dialog signaling state - if (options.body) { - // Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - if (this.confirmedDialog.signalingState !== session_1.SignalingState.Stable) { - this.confirmedDialog.signalingStateTransition(options.body); - } - } - return result; - }; - /** - * 13.3.1.1 Progress - * If the UAS is not able to answer the invitation immediately, it can - * choose to indicate some kind of progress to the UAC (for example, an - * indication that a phone is ringing). This is accomplished with a - * provisional response between 101 and 199. These provisional - * responses establish early dialogs and therefore follow the procedures - * of Section 12.1.1 in addition to those of Section 8.2.6. A UAS MAY - * send as many provisional responses as it likes. Each of these MUST - * indicate the same dialog ID. However, these will not be delivered - * reliably. - * - * If the UAS desires an extended period of time to answer the INVITE, - * it will need to ask for an "extension" in order to prevent proxies - * from canceling the transaction. A proxy has the option of canceling - * a transaction when there is a gap of 3 minutes between responses in a - * transaction. To prevent cancellation, the UAS MUST send a non-100 - * provisional response at every minute, to handle the possibility of - * lost provisional responses. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.1 - * @param options - Progress options bucket. - */ - InviteUserAgentServer.prototype.progress = function (options) { - if (options === void 0) { options = { statusCode: 180 }; } - if (!this.progressable) { - throw new exceptions_1.TransactionStateError(this.message.method + " not progressable in state " + this.transaction.state + "."); - } - // This response establishes a dialog... - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - if (!this.earlyDialog) { - var transaction = this.transaction; - if (!(transaction instanceof transactions_1.InviteServerTransaction)) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - var state = dialogs_1.Dialog.initialDialogStateForUserAgentServer(this.message, this.toTag, true); - this.earlyDialog = new dialogs_1.SessionDialog(transaction, this.core, state); - } - // When a UAS responds to a request with a response that establishes a - // dialog (such as a 2xx to INVITE), the UAS MUST copy all Record-Route - // header field values from the request into the response (including the - // URIs, URI parameters, and any Record-Route header field parameters, - // whether they are known or unknown to the UAS) and MUST maintain the - // order of those values. The UAS MUST add a Contact header field to - // the response. The Contact header field contains an address where the - // UAS would like to be contacted for subsequent requests in the dialog - // (which includes the ACK for a 2xx response in the case of an INVITE). - // Generally, the host portion of this URI is the IP address or FQDN of - // the host. The URI provided in the Contact header field MUST be a SIP - // or SIPS URI. If the request that initiated the dialog contained a - // SIPS URI in the Request-URI or in the top Record-Route header field - // value, if there was any, or the Contact header field if there was no - // Record-Route header field, the Contact header field in the response - // MUST be a SIPS URI. The URI SHOULD have global scope (that is, the - // same URI can be used in messages outside this dialog). The same way, - // the scope of the URI in the Contact header field of the INVITE is not - // limited to this dialog either. It can therefore be used in messages - // to the UAC even outside this dialog. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - var recordRouteHeader = this.message - .getHeaders("record-route") - .map(function (header) { return "Record-Route: " + header; }); - var contactHeader = "Contact: " + this.core.configuration.contact; - options.extraHeaders = options.extraHeaders || []; - options.extraHeaders = options.extraHeaders.concat(recordRouteHeader); - options.extraHeaders.push(contactHeader); - var response = _super.prototype.progress.call(this, options); - var session = this.earlyDialog; - var result = tslib_1.__assign({}, response, { session: session }); - // Update dialog signaling state - if (options.body) { - // Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - if (this.earlyDialog.signalingState !== session_1.SignalingState.Stable) { - this.earlyDialog.signalingStateTransition(options.body); - } - } - return result; - }; - /** - * 13.3.1.2 The INVITE is Redirected - * If the UAS decides to redirect the call, a 3xx response is sent. A - * 300 (Multiple Choices), 301 (Moved Permanently) or 302 (Moved - * Temporarily) response SHOULD contain a Contact header field - * containing one or more URIs of new addresses to be tried. The - * response is passed to the INVITE server transaction, which will deal - * with its retransmissions. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.2 - * @param contacts - Contacts to redirect to. - * @param options - Redirect options bucket. - */ - InviteUserAgentServer.prototype.redirect = function (contacts, options) { - if (options === void 0) { options = { statusCode: 302 }; } - return _super.prototype.redirect.call(this, contacts, options); - }; - /** - * 13.3.1.3 The INVITE is Rejected - * A common scenario occurs when the callee is currently not willing or - * able to take additional calls at this end system. A 486 (Busy Here) - * SHOULD be returned in such a scenario. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.3 - * @param options - Reject options bucket. - */ - InviteUserAgentServer.prototype.reject = function (options) { - if (options === void 0) { options = { statusCode: 486 }; } - return _super.prototype.reject.call(this, options); - }; - return InviteUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.InviteUserAgentServer = InviteUserAgentServer; - - -/***/ }), -/* 70 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * MESSAGE UAS. - * @public - */ -var MessageUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(MessageUserAgentClient, _super); - function MessageUserAgentClient(core, message, delegate) { - return _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; - } - return MessageUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.MessageUserAgentClient = MessageUserAgentClient; - - -/***/ }), -/* 71 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * MESSAGE UAS. - * @public - */ -var MessageUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(MessageUserAgentServer, _super); - function MessageUserAgentServer(core, message, delegate) { - var _this = _super.call(this, transactions_1.NonInviteServerTransaction, core, message, delegate) || this; - _this.core = core; - return _this; - } - return MessageUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.MessageUserAgentServer = MessageUserAgentServer; - - -/***/ }), -/* 72 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * PUBLISH UAC. - * @public - */ -var PublishUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(PublishUserAgentClient, _super); - function PublishUserAgentClient(core, message, delegate) { - return _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; - } - return PublishUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.PublishUserAgentClient = PublishUserAgentClient; - - -/***/ }), -/* 73 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * Re-SUBSCRIBE UAS. - * @public - */ -var ReSubscribeUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(ReSubscribeUserAgentServer, _super); - function ReSubscribeUserAgentServer(dialog, message, delegate) { - return _super.call(this, transactions_1.NonInviteServerTransaction, dialog.userAgentCore, message, delegate) || this; - } - return ReSubscribeUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.ReSubscribeUserAgentServer = ReSubscribeUserAgentServer; - - -/***/ }), -/* 74 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * REGISTER UAC. - * @public - */ -var RegisterUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(RegisterUserAgentClient, _super); - function RegisterUserAgentClient(core, message, delegate) { - return _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; - } - return RegisterUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.RegisterUserAgentClient = RegisterUserAgentClient; - - -/***/ }), -/* 75 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * REGISTER UAS. - * @public - */ -var RegisterUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(RegisterUserAgentServer, _super); - function RegisterUserAgentServer(core, message, delegate) { - var _this = _super.call(this, transactions_1.NonInviteServerTransaction, core, message, delegate) || this; - _this.core = core; - return _this; - } - return RegisterUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.RegisterUserAgentServer = RegisterUserAgentServer; - - -/***/ }), -/* 76 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var subscription_dialog_1 = __webpack_require__(55); -var subscription_1 = __webpack_require__(56); -var timers_1 = __webpack_require__(26); -var transactions_1 = __webpack_require__(27); -var user_agent_client_1 = __webpack_require__(42); -/** - * SUBSCRIBE UAC. - * @remarks - * 4.1. Subscriber Behavior - * https://tools.ietf.org/html/rfc6665#section-4.1 - * - * User agent client for installation of a single subscription per SUBSCRIBE request. - * TODO: Support for installation of multiple subscriptions on forked SUBSCRIBE reqeuests. - * @public - */ -var SubscribeUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(SubscribeUserAgentClient, _super); - function SubscribeUserAgentClient(core, message, delegate) { - var _this = this; - // Get event from request message. - var event = message.getHeader("Event"); - if (!event) { - throw new Error("Event undefined"); - } - // Get expires from reqeust message. - var expires = message.getHeader("Expires"); - if (!expires) { - throw new Error("Expires undefined"); - } - _this = _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; - _this.delegate = delegate; - // FIXME: Subscriber id should also be matching on event id. - _this.subscriberId = message.callId + message.fromTag + event; - _this.subscriptionExpiresRequested = _this.subscriptionExpires = Number(expires); - _this.subscriptionEvent = event; - _this.subscriptionState = subscription_1.SubscriptionState.NotifyWait; - // Start waiting for a NOTIFY we can use to create a subscription. - _this.waitNotifyStart(); - return _this; - } - /** - * Destructor. - * Note that Timer N may live on waiting for an initial NOTIFY and - * the delegate may still receive that NOTIFY. If you don't want - * that behavior then either clear the delegate so the delegate - * doesn't get called (a 200 will be sent in response to the NOTIFY) - * or call `waitNotifyStop` which will clear Timer N and remove this - * UAC from the core (a 481 will be sent in response to the NOTIFY). - */ - SubscribeUserAgentClient.prototype.dispose = function () { - _super.prototype.dispose.call(this); - }; - /** - * Handle out of dialog NOTIFY assoicated with SUBSCRIBE request. - * This is the first NOTIFY received after the SUBSCRIBE request. - * @param uas - User agent server handling the subscription creating NOTIFY. - */ - SubscribeUserAgentClient.prototype.onNotify = function (uas) { - // NOTIFY requests are matched to such SUBSCRIBE requests if they - // contain the same "Call-ID", a "To" header field "tag" parameter that - // matches the "From" header field "tag" parameter of the SUBSCRIBE - // request, and the same "Event" header field. Rules for comparisons of - // the "Event" header fields are described in Section 8.2.1. - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - var event = uas.message.parseHeader("Event").event; - if (!event || event !== this.subscriptionEvent) { - this.logger.warn("Failed to parse event."); - uas.reject({ statusCode: 489 }); - return; - } - // NOTIFY requests MUST contain "Subscription-State" header fields that - // indicate the status of the subscription. - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - var subscriptionState = uas.message.parseHeader("Subscription-State"); - if (!subscriptionState || !subscriptionState.state) { - this.logger.warn("Failed to parse subscription state."); - uas.reject({ statusCode: 489 }); - return; - } - // Validate subscription state. - var state = subscriptionState.state; - switch (state) { - case "pending": - break; - case "active": - break; - case "terminated": - break; - default: - this.logger.warn("Invalid subscription state " + state); - uas.reject({ statusCode: 489 }); - return; - } - // Dialogs usages are created upon completion of a NOTIFY transaction - // for a new subscription, unless the NOTIFY request contains a - // "Subscription-State" of "terminated." - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - if (state !== "terminated") { - // The Contact header field MUST be present and contain exactly one SIP - // or SIPS URI in any request that can result in the establishment of a - // dialog. - // https://tools.ietf.org/html/rfc3261#section-8.1.1.8 - var contact = uas.message.parseHeader("contact"); - if (!contact) { - this.logger.warn("Failed to parse contact."); - uas.reject({ statusCode: 489 }); - return; - } - } - // In accordance with the rules for proxying non-INVITE requests as - // defined in [RFC3261], successful SUBSCRIBE requests will receive only - // one 200-class response; however, due to forking, the subscription may - // have been accepted by multiple nodes. The subscriber MUST therefore - // be prepared to receive NOTIFY requests with "From:" tags that differ - // from the "To:" tag received in the SUBSCRIBE 200-class response. - // - // If multiple NOTIFY requests are received in different dialogs in - // response to a single SUBSCRIBE request, each dialog represents a - // different destination to which the SUBSCRIBE request was forked. - // Subscriber handling in such situations varies by event package; see - // Section 5.4.9 for details. - // https://tools.ietf.org/html/rfc6665#section-4.1.4 - // Each event package MUST specify whether forked SUBSCRIBE requests are - // allowed to install multiple subscriptions. - // - // If such behavior is not allowed, the first potential dialog- - // establishing message will create a dialog. All subsequent NOTIFY - // requests that correspond to the SUBSCRIBE request (i.e., have - // matching "To", "From", "Call-ID", and "Event" header fields, as well - // as "From" header field "tag" parameter and "Event" header field "id" - // parameter) but that do not match the dialog would be rejected with a - // 481 response. Note that the 200-class response to the SUBSCRIBE - // request can arrive after a matching NOTIFY request has been received; - // such responses might not correlate to the same dialog established by - // the NOTIFY request. Except as required to complete the SUBSCRIBE - // transaction, such non-matching 200-class responses are ignored. - // - // If installing of multiple subscriptions by way of a single forked - // SUBSCRIBE request is allowed, the subscriber establishes a new dialog - // towards each notifier by returning a 200-class response to each - // NOTIFY request. Each dialog is then handled as its own entity and is - // refreshed independently of the other dialogs. - // - // In the case that multiple subscriptions are allowed, the event - // package MUST specify whether merging of the notifications to form a - // single state is required, and how such merging is to be performed. - // Note that it is possible that some event packages may be defined in - // such a way that each dialog is tied to a mutually exclusive state - // that is unaffected by the other dialogs; this MUST be clearly stated - // if it is the case. - // https://tools.ietf.org/html/rfc6665#section-5.4.9 - // *** NOTE: This implementation is only for event packages which - // do not allow forked requests to install muliple subscriptions. - // As such and in accordance with the specificaiton, we stop waiting - // and any future NOTIFY requests will be rejected with a 481. - if (this.dialog) { - throw new Error("Dialog already created. This implementation only supports install of single subscriptions."); - } - this.waitNotifyStop(); - // Update expires. - this.subscriptionExpires = - subscriptionState.expires ? - Math.min(this.subscriptionExpires, Math.max(subscriptionState.expires, 0)) : - this.subscriptionExpires; - // Update subscriptoin state. - switch (state) { - case "pending": - this.subscriptionState = subscription_1.SubscriptionState.Pending; - break; - case "active": - this.subscriptionState = subscription_1.SubscriptionState.Active; - break; - case "terminated": - this.subscriptionState = subscription_1.SubscriptionState.Terminated; - break; - default: - throw new Error("Unrecognized state " + state + "."); - } - // Dialogs usages are created upon completion of a NOTIFY transaction - // for a new subscription, unless the NOTIFY request contains a - // "Subscription-State" of "terminated." - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - if (this.subscriptionState !== subscription_1.SubscriptionState.Terminated) { - // Because the dialog usage is established by the NOTIFY request, the - // route set at the subscriber is taken from the NOTIFY request itself, - // as opposed to the route set present in the 200-class response to the - // SUBSCRIBE request. - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - var dialogState = subscription_dialog_1.SubscriptionDialog.initialDialogStateForSubscription(this.message, uas.message); - // Subscription Initiated! :) - this.dialog = new subscription_dialog_1.SubscriptionDialog(this.subscriptionEvent, this.subscriptionExpires, this.subscriptionState, this.core, dialogState); - } - // Delegate. - if (this.delegate && this.delegate.onNotify) { - var request = uas; - var subscription = this.dialog; - this.delegate.onNotify({ request: request, subscription: subscription }); - } - else { - uas.accept(); - } - }; - SubscribeUserAgentClient.prototype.waitNotifyStart = function () { - var _this = this; - if (!this.N) { - // Add ourselves to the core's subscriber map. - // This allows the core to route out of dialog NOTIFY messages to us. - this.core.subscribers.set(this.subscriberId, this); - this.N = setTimeout(function () { return _this.timer_N(); }, timers_1.Timers.TIMER_N); - } - }; - SubscribeUserAgentClient.prototype.waitNotifyStop = function () { - if (this.N) { - // Remove ourselves to the core's subscriber map. - // Any future out of dialog NOTIFY messages will be rejected with a 481. - this.core.subscribers.delete(this.subscriberId); - clearTimeout(this.N); - this.N = undefined; - } - }; - /** - * Receive a response from the transaction layer. - * @param message - Incoming response message. - */ - SubscribeUserAgentClient.prototype.receiveResponse = function (message) { - if (!this.authenticationGuard(message)) { - return; - } - if (message.statusCode && message.statusCode >= 200 && message.statusCode < 300) { - // The "Expires" header field in a 200-class response to SUBSCRIBE - // request indicates the actual duration for which the subscription will - // remain active (unless refreshed). The received value might be - // smaller than the value indicated in the SUBSCRIBE request but cannot - // be larger; see Section 4.2.1 for details. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - // The "Expires" values present in SUBSCRIBE 200-class responses behave - // in the same way as they do in REGISTER responses: the server MAY - // shorten the interval but MUST NOT lengthen it. - // - // If the duration specified in a SUBSCRIBE request is unacceptably - // short, the notifier may be able to send a 423 response, as - // described earlier in this section. - // - // 200-class responses to SUBSCRIBE requests will not generally contain - // any useful information beyond subscription duration; their primary - // purpose is to serve as a reliability mechanism. State information - // will be communicated via a subsequent NOTIFY request from the - // notifier. - // https://tools.ietf.org/html/rfc6665#section-4.2.1.1 - var expires = message.getHeader("Expires"); - if (!expires) { - this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE"); - } - else { - var subscriptionExpiresReceived = Number(expires); - if (subscriptionExpiresReceived > this.subscriptionExpiresRequested) { - this.logger.warn("Expires header in a 200-class response to SUBSCRIBE with a higher value than the one in the request"); - } - if (subscriptionExpiresReceived < this.subscriptionExpires) { - this.subscriptionExpires = subscriptionExpiresReceived; - } - } - // If a NOTIFY arrived before 200-class response a dialog may have been created. - // Updated the dialogs expiration only if this indicates earlier expiration. - if (this.dialog) { - if (this.dialog.subscriptionExpires > this.subscriptionExpires) { - this.dialog.subscriptionExpires = this.subscriptionExpires; - } - } - } - if (message.statusCode && message.statusCode >= 300 && message.statusCode < 700) { - this.waitNotifyStop(); // No NOTIFY will be sent after a negative final response. - } - _super.prototype.receiveResponse.call(this, message); - }; - /** - * To ensure that subscribers do not wait indefinitely for a - * subscription to be established, a subscriber starts a Timer N, set to - * 64*T1, when it sends a SUBSCRIBE request. If this Timer N expires - * prior to the receipt of a NOTIFY request, the subscriber considers - * the subscription failed, and cleans up any state associated with the - * subscription attempt. - * https://tools.ietf.org/html/rfc6665#section-4.1.2.4 - */ - SubscribeUserAgentClient.prototype.timer_N = function () { - this.logger.warn("Timer N expired for SUBSCRIBE user agent client. Timed out waiting for NOTIFY."); - this.waitNotifyStop(); - if (this.delegate && this.delegate.onNotifyTimeout) { - this.delegate.onNotifyTimeout(); - } - }; - return SubscribeUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.SubscribeUserAgentClient = SubscribeUserAgentClient; - - -/***/ }), -/* 77 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var transactions_1 = __webpack_require__(27); -var user_agent_server_1 = __webpack_require__(44); -/** - * SUBSCRIBE UAS. - * @public - */ -var SubscribeUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(SubscribeUserAgentServer, _super); - function SubscribeUserAgentServer(core, message, delegate) { - var _this = _super.call(this, transactions_1.NonInviteServerTransaction, core, message, delegate) || this; - _this.core = core; - return _this; - } - return SubscribeUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.SubscribeUserAgentServer = SubscribeUserAgentServer; - - -/***/ }), -/* 78 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var events_1 = __webpack_require__(30); -/** - * Transport. - * @remarks - * Abstract transport layer base class. - * @public - */ -var Transport = /** @class */ (function (_super) { - tslib_1.__extends(Transport, _super); - /** - * Constructor - * @param logger - Logger. - * @param options - Options bucket. - */ - function Transport(logger, options) { - var _this = _super.call(this) || this; - _this.logger = logger; - return _this; - } - /** - * Returns the promise designated by the child layer then emits a connected event. - * Automatically emits an event upon resolution, unless overrideEvent is set. If you - * override the event in this fashion, you should emit it in your implementation of connectPromise - * @param options - Options bucket. - */ - Transport.prototype.connect = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - return this.connectPromise(options).then(function (data) { - if (!data.overrideEvent) { - _this.emit("connected"); - } - }); - }; - /** - * Sends a message then emits a 'messageSent' event. Automatically emits an - * event upon resolution, unless data.overrideEvent is set. If you override - * the event in this fashion, you should emit it in your implementation of sendPromise - * @param msg - Message. - * @param options - Options bucket. - */ - Transport.prototype.send = function (msg, options) { - var _this = this; - if (options === void 0) { options = {}; } - return this.sendPromise(msg).then(function (data) { - if (!data.overrideEvent) { - _this.emit("messageSent", data.msg); - } - }); - }; - /** - * Returns the promise designated by the child layer then emits a - * disconnected event. Automatically emits an event upon resolution, - * unless overrideEvent is set. If you override the event in this fashion, - * you should emit it in your implementation of disconnectPromise - * @param options - Options bucket - */ - Transport.prototype.disconnect = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - return this.disconnectPromise(options).then(function (data) { - if (!data.overrideEvent) { - _this.emit("disconnected"); - } - }); - }; - Transport.prototype.afterConnected = function (callback) { - if (this.isConnected()) { - callback(); - } - else { - this.once("connected", callback); - } - }; - /** - * Returns a promise which resolves once the UA is connected. DEPRECATION WARNING: just use afterConnected() - */ - Transport.prototype.waitForConnected = function () { - var _this = this; - // tslint:disable-next-line:no-console - console.warn("DEPRECATION WARNING Transport.waitForConnected(): use afterConnected() instead"); - return new Promise(function (resolve) { - _this.afterConnected(resolve); - }); - }; - return Transport; -}(events_1.EventEmitter)); -exports.Transport = Transport; - - -/***/ }), -/* 79 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var events_1 = __webpack_require__(30); -var Constants_1 = __webpack_require__(80); -var core_1 = __webpack_require__(2); -var Enums_1 = __webpack_require__(82); -var Utils_1 = __webpack_require__(83); -var ClientContext = /** @class */ (function (_super) { - tslib_1.__extends(ClientContext, _super); - function ClientContext(ua, method, target, options) { - var _this = _super.call(this) || this; - _this.data = {}; - ClientContext.initializer(_this, ua, method, target, options); - return _this; - } - ClientContext.initializer = function (objToConstruct, ua, method, originalTarget, options) { - objToConstruct.type = Enums_1.TypeStrings.ClientContext; - // Validate arguments - if (originalTarget === undefined) { - throw new TypeError("Not enough arguments"); - } - objToConstruct.ua = ua; - objToConstruct.logger = ua.getLogger("sip.clientcontext"); - objToConstruct.method = method; - var target = ua.normalizeTarget(originalTarget); - if (!target) { - throw new TypeError("Invalid target: " + originalTarget); - } - var fromURI = ua.userAgentCore.configuration.aor; - if (options && options.params && options.params.fromUri) { - fromURI = - (typeof options.params.fromUri === "string") ? - core_1.Grammar.URIParse(options.params.fromUri) : - options.params.fromUri; - if (!fromURI) { - throw new TypeError("Invalid from URI: " + options.params.fromUri); - } - } - var toURI = target; - if (options && options.params && options.params.toUri) { - toURI = - (typeof options.params.toUri === "string") ? - core_1.Grammar.URIParse(options.params.toUri) : - options.params.toUri; - if (!toURI) { - throw new TypeError("Invalid to URI: " + options.params.toUri); - } - } - /* Options - * - extraHeaders - * - params - * - contentType - * - body - */ - options = Object.create(options || Object.prototype); - options = options || {}; - var extraHeaders = (options.extraHeaders || []).slice(); - var params = options.params || {}; - var bodyObj; - if (options.body) { - bodyObj = { - body: options.body, - contentType: options.contentType ? options.contentType : "application/sdp" - }; - objToConstruct.body = bodyObj; - } - var body; - if (bodyObj) { - body = Utils_1.Utils.fromBodyObj(bodyObj); - } - // Build the request - objToConstruct.request = ua.userAgentCore.makeOutgoingRequestMessage(method, target, fromURI, toURI, params, extraHeaders, body); - /* Set other properties from the request */ - if (objToConstruct.request.from) { - objToConstruct.localIdentity = objToConstruct.request.from; - } - if (objToConstruct.request.to) { - objToConstruct.remoteIdentity = objToConstruct.request.to; - } - }; - ClientContext.prototype.send = function () { - var _this = this; - this.ua.userAgentCore.request(this.request, { - onAccept: function (response) { return _this.receiveResponse(response.message); }, - onProgress: function (response) { return _this.receiveResponse(response.message); }, - onRedirect: function (response) { return _this.receiveResponse(response.message); }, - onReject: function (response) { return _this.receiveResponse(response.message); }, - onTrying: function (response) { return _this.receiveResponse(response.message); } - }); - return this; - }; - ClientContext.prototype.receiveResponse = function (response) { - var statusCode = response.statusCode || 0; - var cause = Utils_1.Utils.getReasonPhrase(statusCode); - switch (true) { - case /^1[0-9]{2}$/.test(statusCode.toString()): - this.emit("progress", response, cause); - break; - case /^2[0-9]{2}$/.test(statusCode.toString()): - if (this.ua.applicants[this.toString()]) { - delete this.ua.applicants[this.toString()]; - } - this.emit("accepted", response, cause); - break; - default: - if (this.ua.applicants[this.toString()]) { - delete this.ua.applicants[this.toString()]; - } - this.emit("rejected", response, cause); - this.emit("failed", response, cause); - break; - } - }; - ClientContext.prototype.onRequestTimeout = function () { - this.emit("failed", undefined, Constants_1.C.causes.REQUEST_TIMEOUT); - }; - ClientContext.prototype.onTransportError = function () { - this.emit("failed", undefined, Constants_1.C.causes.CONNECTION_ERROR); - }; - return ClientContext; -}(events_1.EventEmitter)); -exports.ClientContext = ClientContext; - - -/***/ }), -/* 80 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var version_1 = __webpack_require__(81); -var C; -(function (C) { - C.version = version_1.LIBRARY_VERSION; - C.USER_AGENT = "SIP.js/" + version_1.LIBRARY_VERSION; - // SIP scheme - C.SIP = "sip"; - C.SIPS = "sips"; - // End and Failure causes - var causes; - (function (causes) { - // Generic error causes - causes["CONNECTION_ERROR"] = "Connection Error"; - causes["INTERNAL_ERROR"] = "Internal Error"; - causes["REQUEST_TIMEOUT"] = "Request Timeout"; - causes["SIP_FAILURE_CODE"] = "SIP Failure Code"; - // SIP error causes - causes["ADDRESS_INCOMPLETE"] = "Address Incomplete"; - causes["AUTHENTICATION_ERROR"] = "Authentication Error"; - causes["BUSY"] = "Busy"; - causes["DIALOG_ERROR"] = "Dialog Error"; - causes["INCOMPATIBLE_SDP"] = "Incompatible SDP"; - causes["NOT_FOUND"] = "Not Found"; - causes["REDIRECTED"] = "Redirected"; - causes["REJECTED"] = "Rejected"; - causes["UNAVAILABLE"] = "Unavailable"; - // Session error causes - causes["BAD_MEDIA_DESCRIPTION"] = "Bad Media Description"; - causes["CANCELED"] = "Canceled"; - causes["EXPIRES"] = "Expires"; - causes["NO_ACK"] = "No ACK"; - causes["NO_ANSWER"] = "No Answer"; - causes["NO_PRACK"] = "No PRACK"; - causes["RTP_TIMEOUT"] = "RTP Timeout"; - causes["USER_DENIED_MEDIA_ACCESS"] = "User Denied Media Access"; - causes["WEBRTC_ERROR"] = "WebRTC Error"; - causes["WEBRTC_NOT_SUPPORTED"] = "WebRTC Not Supported"; - })(causes = C.causes || (C.causes = {})); - var supported; - (function (supported) { - supported["REQUIRED"] = "required"; - supported["SUPPORTED"] = "supported"; - supported["UNSUPPORTED"] = "none"; - })(supported = C.supported || (C.supported = {})); - C.SIP_ERROR_CAUSES = { - ADDRESS_INCOMPLETE: [484], - AUTHENTICATION_ERROR: [401, 407], - BUSY: [486, 600], - INCOMPATIBLE_SDP: [488, 606], - NOT_FOUND: [404, 604], - REDIRECTED: [300, 301, 302, 305, 380], - REJECTED: [403, 603], - UNAVAILABLE: [480, 410, 408, 430] - }; - // SIP Methods - C.ACK = "ACK"; - C.BYE = "BYE"; - C.CANCEL = "CANCEL"; - C.INFO = "INFO"; - C.INVITE = "INVITE"; - C.MESSAGE = "MESSAGE"; - C.NOTIFY = "NOTIFY"; - C.OPTIONS = "OPTIONS"; - C.REGISTER = "REGISTER"; - C.UPDATE = "UPDATE"; - C.SUBSCRIBE = "SUBSCRIBE"; - C.PUBLISH = "PUBLISH"; - C.REFER = "REFER"; - C.PRACK = "PRACK"; - /* SIP Response Reasons - * DOC: http://www.iana.org/assignments/sip-parameters - * Copied from https://github.com/versatica/OverSIP/blob/master/lib/oversip/sip/constants.rb#L7 - */ - C.REASON_PHRASE = { - 100: "Trying", - 180: "Ringing", - 181: "Call Is Being Forwarded", - 182: "Queued", - 183: "Session Progress", - 199: "Early Dialog Terminated", - 200: "OK", - 202: "Accepted", - 204: "No Notification", - 300: "Multiple Choices", - 301: "Moved Permanently", - 302: "Moved Temporarily", - 305: "Use Proxy", - 380: "Alternative Service", - 400: "Bad Request", - 401: "Unauthorized", - 402: "Payment Required", - 403: "Forbidden", - 404: "Not Found", - 405: "Method Not Allowed", - 406: "Not Acceptable", - 407: "Proxy Authentication Required", - 408: "Request Timeout", - 410: "Gone", - 412: "Conditional Request Failed", - 413: "Request Entity Too Large", - 414: "Request-URI Too Long", - 415: "Unsupported Media Type", - 416: "Unsupported URI Scheme", - 417: "Unknown Resource-Priority", - 420: "Bad Extension", - 421: "Extension Required", - 422: "Session Interval Too Small", - 423: "Interval Too Brief", - 428: "Use Identity Header", - 429: "Provide Referrer Identity", - 430: "Flow Failed", - 433: "Anonymity Disallowed", - 436: "Bad Identity-Info", - 437: "Unsupported Certificate", - 438: "Invalid Identity Header", - 439: "First Hop Lacks Outbound Support", - 440: "Max-Breadth Exceeded", - 469: "Bad Info Package", - 470: "Consent Needed", - 478: "Unresolvable Destination", - 480: "Temporarily Unavailable", - 481: "Call/Transaction Does Not Exist", - 482: "Loop Detected", - 483: "Too Many Hops", - 484: "Address Incomplete", - 485: "Ambiguous", - 486: "Busy Here", - 487: "Request Terminated", - 488: "Not Acceptable Here", - 489: "Bad Event", - 491: "Request Pending", - 493: "Undecipherable", - 494: "Security Agreement Required", - 500: "Internal Server Error", - 501: "Not Implemented", - 502: "Bad Gateway", - 503: "Service Unavailable", - 504: "Server Time-out", - 505: "Version Not Supported", - 513: "Message Too Large", - 580: "Precondition Failure", - 600: "Busy Everywhere", - 603: "Decline", - 604: "Does Not Exist Anywhere", - 606: "Not Acceptable" - }; - /* SIP Option Tags - * DOC: http://www.iana.org/assignments/sip-parameters/sip-parameters.xhtml#sip-parameters-4 - */ - C.OPTION_TAGS = { - "100rel": true, - "199": true, - "answermode": true, - "early-session": true, - "eventlist": true, - "explicitsub": true, - "from-change": true, - "geolocation-http": true, - "geolocation-sip": true, - "gin": true, - "gruu": true, - "histinfo": true, - "ice": true, - "join": true, - "multiple-refer": true, - "norefersub": true, - "nosub": true, - "outbound": true, - "path": true, - "policy": true, - "precondition": true, - "pref": true, - "privacy": true, - "recipient-list-invite": true, - "recipient-list-message": true, - "recipient-list-subscribe": true, - "replaces": true, - "resource-priority": true, - "sdp-anat": true, - "sec-agree": true, - "tdialog": true, - "timer": true, - "uui": true // RFC 7433 - }; - var dtmfType; - (function (dtmfType) { - dtmfType["INFO"] = "info"; - dtmfType["RTP"] = "rtp"; - })(dtmfType = C.dtmfType || (C.dtmfType = {})); -})(C = exports.C || (exports.C = {})); - - -/***/ }), -/* 81 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.LIBRARY_VERSION = "0.15.5"; - - -/***/ }), -/* 82 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// enums can't really be declared, so they are set here. -// pulled out of individual files to avoid circular dependencies -Object.defineProperty(exports, "__esModule", { value: true }); -var DialogStatus; -(function (DialogStatus) { - DialogStatus[DialogStatus["STATUS_EARLY"] = 1] = "STATUS_EARLY"; - DialogStatus[DialogStatus["STATUS_CONFIRMED"] = 2] = "STATUS_CONFIRMED"; -})(DialogStatus = exports.DialogStatus || (exports.DialogStatus = {})); -var SessionStatus; -(function (SessionStatus) { - // Session states - SessionStatus[SessionStatus["STATUS_NULL"] = 0] = "STATUS_NULL"; - SessionStatus[SessionStatus["STATUS_INVITE_SENT"] = 1] = "STATUS_INVITE_SENT"; - SessionStatus[SessionStatus["STATUS_1XX_RECEIVED"] = 2] = "STATUS_1XX_RECEIVED"; - SessionStatus[SessionStatus["STATUS_INVITE_RECEIVED"] = 3] = "STATUS_INVITE_RECEIVED"; - SessionStatus[SessionStatus["STATUS_WAITING_FOR_ANSWER"] = 4] = "STATUS_WAITING_FOR_ANSWER"; - SessionStatus[SessionStatus["STATUS_ANSWERED"] = 5] = "STATUS_ANSWERED"; - SessionStatus[SessionStatus["STATUS_WAITING_FOR_PRACK"] = 6] = "STATUS_WAITING_FOR_PRACK"; - SessionStatus[SessionStatus["STATUS_WAITING_FOR_ACK"] = 7] = "STATUS_WAITING_FOR_ACK"; - SessionStatus[SessionStatus["STATUS_CANCELED"] = 8] = "STATUS_CANCELED"; - SessionStatus[SessionStatus["STATUS_TERMINATED"] = 9] = "STATUS_TERMINATED"; - SessionStatus[SessionStatus["STATUS_ANSWERED_WAITING_FOR_PRACK"] = 10] = "STATUS_ANSWERED_WAITING_FOR_PRACK"; - SessionStatus[SessionStatus["STATUS_EARLY_MEDIA"] = 11] = "STATUS_EARLY_MEDIA"; - SessionStatus[SessionStatus["STATUS_CONFIRMED"] = 12] = "STATUS_CONFIRMED"; -})(SessionStatus = exports.SessionStatus || (exports.SessionStatus = {})); -var TypeStrings; -(function (TypeStrings) { - TypeStrings[TypeStrings["ClientContext"] = 0] = "ClientContext"; - TypeStrings[TypeStrings["ConfigurationError"] = 1] = "ConfigurationError"; - TypeStrings[TypeStrings["Dialog"] = 2] = "Dialog"; - TypeStrings[TypeStrings["DigestAuthentication"] = 3] = "DigestAuthentication"; - TypeStrings[TypeStrings["DTMF"] = 4] = "DTMF"; - TypeStrings[TypeStrings["IncomingMessage"] = 5] = "IncomingMessage"; - TypeStrings[TypeStrings["IncomingRequest"] = 6] = "IncomingRequest"; - TypeStrings[TypeStrings["IncomingResponse"] = 7] = "IncomingResponse"; - TypeStrings[TypeStrings["InvalidStateError"] = 8] = "InvalidStateError"; - TypeStrings[TypeStrings["InviteClientContext"] = 9] = "InviteClientContext"; - TypeStrings[TypeStrings["InviteServerContext"] = 10] = "InviteServerContext"; - TypeStrings[TypeStrings["Logger"] = 11] = "Logger"; - TypeStrings[TypeStrings["LoggerFactory"] = 12] = "LoggerFactory"; - TypeStrings[TypeStrings["MethodParameterError"] = 13] = "MethodParameterError"; - TypeStrings[TypeStrings["NameAddrHeader"] = 14] = "NameAddrHeader"; - TypeStrings[TypeStrings["NotSupportedError"] = 15] = "NotSupportedError"; - TypeStrings[TypeStrings["OutgoingRequest"] = 16] = "OutgoingRequest"; - TypeStrings[TypeStrings["Parameters"] = 17] = "Parameters"; - TypeStrings[TypeStrings["PublishContext"] = 18] = "PublishContext"; - TypeStrings[TypeStrings["ReferClientContext"] = 19] = "ReferClientContext"; - TypeStrings[TypeStrings["ReferServerContext"] = 20] = "ReferServerContext"; - TypeStrings[TypeStrings["RegisterContext"] = 21] = "RegisterContext"; - TypeStrings[TypeStrings["RenegotiationError"] = 22] = "RenegotiationError"; - TypeStrings[TypeStrings["RequestSender"] = 23] = "RequestSender"; - TypeStrings[TypeStrings["ServerContext"] = 24] = "ServerContext"; - TypeStrings[TypeStrings["Session"] = 25] = "Session"; - TypeStrings[TypeStrings["SessionDescriptionHandler"] = 26] = "SessionDescriptionHandler"; - TypeStrings[TypeStrings["SessionDescriptionHandlerError"] = 27] = "SessionDescriptionHandlerError"; - TypeStrings[TypeStrings["SessionDescriptionHandlerObserver"] = 28] = "SessionDescriptionHandlerObserver"; - TypeStrings[TypeStrings["Subscription"] = 29] = "Subscription"; - TypeStrings[TypeStrings["Transport"] = 30] = "Transport"; - TypeStrings[TypeStrings["UA"] = 31] = "UA"; - TypeStrings[TypeStrings["URI"] = 32] = "URI"; -})(TypeStrings = exports.TypeStrings || (exports.TypeStrings = {})); -// UA status codes -var UAStatus; -(function (UAStatus) { - UAStatus[UAStatus["STATUS_INIT"] = 0] = "STATUS_INIT"; - UAStatus[UAStatus["STATUS_STARTING"] = 1] = "STATUS_STARTING"; - UAStatus[UAStatus["STATUS_READY"] = 2] = "STATUS_READY"; - UAStatus[UAStatus["STATUS_USER_CLOSED"] = 3] = "STATUS_USER_CLOSED"; - UAStatus[UAStatus["STATUS_NOT_READY"] = 4] = "STATUS_NOT_READY"; -})(UAStatus = exports.UAStatus || (exports.UAStatus = {})); - - -/***/ }), -/* 83 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var Constants_1 = __webpack_require__(80); -var grammar_1 = __webpack_require__(11); -var uri_1 = __webpack_require__(15); -var Utils; -(function (Utils) { - function defer() { - var deferred = {}; - deferred.promise = new Promise(function (resolve, reject) { - deferred.resolve = resolve; - deferred.reject = reject; - }); - return deferred; - } - Utils.defer = defer; - function reducePromises(arr, val) { - return arr.reduce(function (acc, fn) { - acc = acc.then(fn); - return acc; - }, Promise.resolve(val)); - } - Utils.reducePromises = reducePromises; - function str_utf8_length(str) { - return encodeURIComponent(str).replace(/%[A-F\d]{2}/g, "U").length; - } - Utils.str_utf8_length = str_utf8_length; - function generateFakeSDP(body) { - if (!body) { - return; - } - var start = body.indexOf("o="); - var end = body.indexOf("\r\n", start); - return "v=0\r\n" + body.slice(start, end) + "\r\ns=-\r\nt=0 0\r\nc=IN IP4 0.0.0.0"; - } - Utils.generateFakeSDP = generateFakeSDP; - function isDecimal(num) { - var numAsNum = parseInt(num, 10); - return !isNaN(numAsNum) && (parseFloat(num) === numAsNum); - } - Utils.isDecimal = isDecimal; - function createRandomToken(size, base) { - if (base === void 0) { base = 32; } - var token = ""; - for (var i = 0; i < size; i++) { - var r = Math.floor(Math.random() * base); - token += r.toString(base); - } - return token; - } - Utils.createRandomToken = createRandomToken; - function newTag() { - // used to use the constant in UA - return Utils.createRandomToken(10); - } - Utils.newTag = newTag; - // http://stackoverflow.com/users/109538/broofa - function newUUID() { - var UUID = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) { - var r = Math.floor(Math.random() * 16); - var v = c === "x" ? r : (r % 4 + 8); - return v.toString(16); - }); - return UUID; - } - Utils.newUUID = newUUID; - /* - * Normalize SIP URI. - * NOTE: It does not allow a SIP URI without username. - * Accepts 'sip', 'sips' and 'tel' URIs and convert them into 'sip'. - * Detects the domain part (if given) and properly hex-escapes the user portion. - * If the user portion has only 'tel' number symbols the user portion is clean of 'tel' visual separators. - * @private - * @param {String} target - * @param {String} [domain] - */ - function normalizeTarget(target, domain) { - // If no target is given then raise an error. - if (!target) { - return; - // If a SIP.URI instance is given then return it. - } - else if (target instanceof uri_1.URI) { - return target; - // If a string is given split it by '@': - // - Last fragment is the desired domain. - // - Otherwise append the given domain argument. - } - else if (typeof target === "string") { - var targetArray = target.split("@"); - var targetUser = void 0; - var targetDomain = void 0; - switch (targetArray.length) { - case 1: - if (!domain) { - return; - } - targetUser = target; - targetDomain = domain; - break; - case 2: - targetUser = targetArray[0]; - targetDomain = targetArray[1]; - break; - default: - targetUser = targetArray.slice(0, targetArray.length - 1).join("@"); - targetDomain = targetArray[targetArray.length - 1]; - } - // Remove the URI scheme (if present). - targetUser = targetUser.replace(/^(sips?|tel):/i, ""); - // Remove 'tel' visual separators if the user portion just contains 'tel' number symbols. - if (/^[\-\.\(\)]*\+?[0-9\-\.\(\)]+$/.test(targetUser)) { - targetUser = targetUser.replace(/[\-\.\(\)]/g, ""); - } - // Build the complete SIP URI. - target = Constants_1.C.SIP + ":" + Utils.escapeUser(targetUser) + "@" + targetDomain; - // Finally parse the resulting URI. - return grammar_1.Grammar.URIParse(target); - } - else { - return; - } - } - Utils.normalizeTarget = normalizeTarget; - /* - * Hex-escape a SIP URI user. - * @private - * @param {String} user - */ - function escapeUser(user) { - // Don't hex-escape ':' (%3A), '+' (%2B), '?' (%3F"), '/' (%2F). - return encodeURIComponent(decodeURIComponent(user)) - .replace(/%3A/ig, ":") - .replace(/%2B/ig, "+") - .replace(/%3F/ig, "?") - .replace(/%2F/ig, "/"); - } - Utils.escapeUser = escapeUser; - function headerize(str) { - var exceptions = { - "Call-Id": "Call-ID", - "Cseq": "CSeq", - "Min-Se": "Min-SE", - "Rack": "RAck", - "Rseq": "RSeq", - "Www-Authenticate": "WWW-Authenticate", - }; - var name = str.toLowerCase().replace(/_/g, "-").split("-"); - var parts = name.length; - var hname = ""; - for (var part = 0; part < parts; part++) { - if (part !== 0) { - hname += "-"; - } - hname += name[part].charAt(0).toUpperCase() + name[part].substring(1); - } - if (exceptions[hname]) { - hname = exceptions[hname]; - } - return hname; - } - Utils.headerize = headerize; - function sipErrorCause(statusCode) { - for (var cause in Constants_1.C.SIP_ERROR_CAUSES) { - if (Constants_1.C.SIP_ERROR_CAUSES[cause].indexOf(statusCode) !== -1) { - return Constants_1.C.causes[cause]; - } - } - return Constants_1.C.causes.SIP_FAILURE_CODE; - } - Utils.sipErrorCause = sipErrorCause; - function getReasonPhrase(code, specific) { - return specific || Constants_1.C.REASON_PHRASE[code] || ""; - } - Utils.getReasonPhrase = getReasonPhrase; - function getReasonHeaderValue(code, reason) { - reason = Utils.getReasonPhrase(code, reason); - return "SIP;cause=" + code + ';text="' + reason + '"'; - } - Utils.getReasonHeaderValue = getReasonHeaderValue; - function getCancelReason(code, reason) { - if (code && code < 200 || code > 699) { - throw new TypeError("Invalid statusCode: " + code); - } - else if (code) { - return Utils.getReasonHeaderValue(code, reason); - } - } - Utils.getCancelReason = getCancelReason; - function buildStatusLine(code, reason) { - // Validate code and reason values - if (!code || (code < 100 || code > 699)) { - throw new TypeError("Invalid statusCode: " + code); - } - else if (reason && typeof reason !== "string" && !(reason instanceof String)) { - throw new TypeError("Invalid reason: " + reason); - } - reason = Utils.getReasonPhrase(code, reason); - return "SIP/2.0 " + code + " " + reason + "\r\n"; - } - Utils.buildStatusLine = buildStatusLine; - /** - * Create a Body given a BodyObj. - * @param bodyObj Body Object - */ - function fromBodyObj(bodyObj) { - var content = bodyObj.body; - var contentType = bodyObj.contentType; - var contentDisposition = contentTypeToContentDisposition(contentType); - var body = { contentDisposition: contentDisposition, contentType: contentType, content: content }; - return body; - } - Utils.fromBodyObj = fromBodyObj; - /** - * Create a BodyObj given a Body. - * @param bodyObj Body Object - */ - function toBodyObj(body) { - var bodyObj = { - body: body.content, - contentType: body.contentType - }; - return bodyObj; - } - Utils.toBodyObj = toBodyObj; - // If the Content-Disposition header field is missing, bodies of - // Content-Type application/sdp imply the disposition "session", while - // other content types imply "render". - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - function contentTypeToContentDisposition(contentType) { - if (contentType === "application/sdp") { - return "session"; - } - else { - return "render"; - } - } -})(Utils = exports.Utils || (exports.Utils = {})); - - -/***/ }), -/* 84 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var core_1 = __webpack_require__(2); -var Enums_1 = __webpack_require__(82); -// tslint:disable:max-classes-per-file -var Exceptions; -(function (Exceptions) { - /** - * Indicates the session description handler has closed. - * Occurs when getDescription() or setDescription() are called after close() has been called. - * Occurs when close() is called while getDescription() or setDescription() are in progress. - */ - var ClosedSessionDescriptionHandlerError = /** @class */ (function (_super) { - tslib_1.__extends(ClosedSessionDescriptionHandlerError, _super); - function ClosedSessionDescriptionHandlerError() { - return _super.call(this, "The session description handler has closed.") || this; - } - return ClosedSessionDescriptionHandlerError; - }(core_1.Exception)); - Exceptions.ClosedSessionDescriptionHandlerError = ClosedSessionDescriptionHandlerError; - /** - * Indicates the session terminated before the action completed. - */ - var TerminatedSessionError = /** @class */ (function (_super) { - tslib_1.__extends(TerminatedSessionError, _super); - function TerminatedSessionError() { - return _super.call(this, "The session has terminated.") || this; - } - return TerminatedSessionError; - }(core_1.Exception)); - Exceptions.TerminatedSessionError = TerminatedSessionError; - /** - * Unsupported session description content type. - */ - var UnsupportedSessionDescriptionContentTypeError = /** @class */ (function (_super) { - tslib_1.__extends(UnsupportedSessionDescriptionContentTypeError, _super); - function UnsupportedSessionDescriptionContentTypeError(message) { - return _super.call(this, message ? message : "Unsupported session description content type.") || this; - } - return UnsupportedSessionDescriptionContentTypeError; - }(core_1.Exception)); - Exceptions.UnsupportedSessionDescriptionContentTypeError = UnsupportedSessionDescriptionContentTypeError; -})(Exceptions = exports.Exceptions || (exports.Exceptions = {})); -/** - * DEPRECATED: The original implementation of exceptions in this library attempted to - * deal with the lack of type checking in JavaScript by adding a "type" attribute - * to objects and using that to discriminate. On top of that it layered allcoated - * "code" numbers and constant "name" strings. All of that is unnecessary when using - * TypeScript, inheriting from Error and properly setting up the prototype chain... - */ -var LegacyException = /** @class */ (function (_super) { - tslib_1.__extends(LegacyException, _super); - function LegacyException(code, name, message) { - var _this = _super.call(this, message) || this; - _this.code = code; - _this.name = name; - _this.message = message; - return _this; - } - return LegacyException; -}(core_1.Exception)); -(function (Exceptions) { - var ConfigurationError = /** @class */ (function (_super) { - tslib_1.__extends(ConfigurationError, _super); - function ConfigurationError(parameter, value) { - var _this = _super.call(this, 1, "CONFIGURATION_ERROR", (!value) ? "Missing parameter: " + parameter : - "Invalid value " + JSON.stringify(value) + " for parameter '" + parameter + "'") || this; - _this.type = Enums_1.TypeStrings.ConfigurationError; - _this.parameter = parameter; - _this.value = value; - return _this; - } - return ConfigurationError; - }(LegacyException)); - Exceptions.ConfigurationError = ConfigurationError; - var InvalidStateError = /** @class */ (function (_super) { - tslib_1.__extends(InvalidStateError, _super); - function InvalidStateError(status) { - var _this = _super.call(this, 2, "INVALID_STATE_ERROR", "Invalid status: " + status) || this; - _this.type = Enums_1.TypeStrings.InvalidStateError; - _this.status = status; - return _this; - } - return InvalidStateError; - }(LegacyException)); - Exceptions.InvalidStateError = InvalidStateError; - var NotSupportedError = /** @class */ (function (_super) { - tslib_1.__extends(NotSupportedError, _super); - function NotSupportedError(message) { - var _this = _super.call(this, 3, "NOT_SUPPORTED_ERROR", message) || this; - _this.type = Enums_1.TypeStrings.NotSupportedError; - return _this; - } - return NotSupportedError; - }(LegacyException)); - Exceptions.NotSupportedError = NotSupportedError; - // 4 was GetDescriptionError, which was deprecated and now removed - var RenegotiationError = /** @class */ (function (_super) { - tslib_1.__extends(RenegotiationError, _super); - function RenegotiationError(message) { - var _this = _super.call(this, 5, "RENEGOTIATION_ERROR", message) || this; - _this.type = Enums_1.TypeStrings.RenegotiationError; - return _this; - } - return RenegotiationError; - }(LegacyException)); - Exceptions.RenegotiationError = RenegotiationError; - var MethodParameterError = /** @class */ (function (_super) { - tslib_1.__extends(MethodParameterError, _super); - function MethodParameterError(method, parameter, value) { - var _this = _super.call(this, 6, "METHOD_PARAMETER_ERROR", (!value) ? - "Missing parameter: " + parameter : - "Invalid value " + JSON.stringify(value) + " for parameter '" + parameter + "'") || this; - _this.type = Enums_1.TypeStrings.MethodParameterError; - _this.method = method; - _this.parameter = parameter; - _this.value = value; - return _this; - } - return MethodParameterError; - }(LegacyException)); - Exceptions.MethodParameterError = MethodParameterError; - // 7 was TransportError, which was replaced - var SessionDescriptionHandlerError = /** @class */ (function (_super) { - tslib_1.__extends(SessionDescriptionHandlerError, _super); - function SessionDescriptionHandlerError(method, error, message) { - var _this = _super.call(this, 8, "SESSION_DESCRIPTION_HANDLER_ERROR", message || "Error with Session Description Handler") || this; - _this.type = Enums_1.TypeStrings.SessionDescriptionHandlerError; - _this.method = method; - _this.error = error; - return _this; - } - return SessionDescriptionHandlerError; - }(LegacyException)); - Exceptions.SessionDescriptionHandlerError = SessionDescriptionHandlerError; -})(Exceptions = exports.Exceptions || (exports.Exceptions = {})); - - -/***/ }), -/* 85 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var core_1 = __webpack_require__(2); -/** - * Extract and parse every header of a SIP message. - * @namespace - */ -var Parser; -(function (Parser) { - function getHeader(data, headerStart) { - // 'start' position of the header. - var start = headerStart; - // 'end' position of the header. - var end = 0; - // 'partial end' position of the header. - var partialEnd = 0; - // End of message. - if (data.substring(start, start + 2).match(/(^\r\n)/)) { - return -2; - } - while (end === 0) { - // Partial End of Header. - partialEnd = data.indexOf("\r\n", start); - // 'indexOf' returns -1 if the value to be found never occurs. - if (partialEnd === -1) { - return partialEnd; - } - if (!data.substring(partialEnd + 2, partialEnd + 4).match(/(^\r\n)/) && - data.charAt(partialEnd + 2).match(/(^\s+)/)) { - // Not the end of the message. Continue from the next position. - start = partialEnd + 2; - } - else { - end = partialEnd; - } - } - return end; - } - Parser.getHeader = getHeader; - function parseHeader(message, data, headerStart, headerEnd) { - var hcolonIndex = data.indexOf(":", headerStart); - var headerName = data.substring(headerStart, hcolonIndex).trim(); - var headerValue = data.substring(hcolonIndex + 1, headerEnd).trim(); - var parsed; - // If header-field is well-known, parse it. - switch (headerName.toLowerCase()) { - case "via": - case "v": - message.addHeader("via", headerValue); - if (message.getHeaders("via").length === 1) { - parsed = message.parseHeader("Via"); - if (parsed) { - message.via = parsed; - message.viaBranch = parsed.branch; - } - } - else { - parsed = 0; - } - break; - case "from": - case "f": - message.setHeader("from", headerValue); - parsed = message.parseHeader("from"); - if (parsed) { - message.from = parsed; - message.fromTag = parsed.getParam("tag"); - } - break; - case "to": - case "t": - message.setHeader("to", headerValue); - parsed = message.parseHeader("to"); - if (parsed) { - message.to = parsed; - message.toTag = parsed.getParam("tag"); - } - break; - case "record-route": - parsed = core_1.Grammar.parse(headerValue, "Record_Route"); - if (parsed === -1) { - parsed = undefined; - break; - } - for (var header in parsed) { - if (parsed[header]) { - message.addHeader("record-route", headerValue.substring(parsed[header].position, parsed[header].offset)); - message.headers["Record-Route"][message.getHeaders("record-route").length - 1].parsed = - parsed[header].parsed; - } - } - break; - case "call-id": - case "i": - message.setHeader("call-id", headerValue); - parsed = message.parseHeader("call-id"); - if (parsed) { - message.callId = headerValue; - } - break; - case "contact": - case "m": - parsed = core_1.Grammar.parse(headerValue, "Contact"); - if (parsed === -1) { - parsed = undefined; - break; - } - if (!(parsed instanceof Array)) { - parsed = undefined; - break; - } - parsed.forEach(function (header) { - message.addHeader("contact", headerValue.substring(header.position, header.offset)); - message.headers.Contact[message.getHeaders("contact").length - 1].parsed = header.parsed; - }); - break; - case "content-length": - case "l": - message.setHeader("content-length", headerValue); - parsed = message.parseHeader("content-length"); - break; - case "content-type": - case "c": - message.setHeader("content-type", headerValue); - parsed = message.parseHeader("content-type"); - break; - case "cseq": - message.setHeader("cseq", headerValue); - parsed = message.parseHeader("cseq"); - if (parsed) { - message.cseq = parsed.value; - } - if (message instanceof core_1.IncomingResponseMessage) { - message.method = parsed.method; - } - break; - case "max-forwards": - message.setHeader("max-forwards", headerValue); - parsed = message.parseHeader("max-forwards"); - break; - case "www-authenticate": - message.setHeader("www-authenticate", headerValue); - parsed = message.parseHeader("www-authenticate"); - break; - case "proxy-authenticate": - message.setHeader("proxy-authenticate", headerValue); - parsed = message.parseHeader("proxy-authenticate"); - break; - case "refer-to": - case "r": - message.setHeader("refer-to", headerValue); - parsed = message.parseHeader("refer-to"); - if (parsed) { - message.referTo = parsed; - } - break; - default: - // Do not parse this header. - message.addHeader(headerName.toLowerCase(), headerValue); - parsed = 0; - } - if (parsed === undefined) { - return { - error: "error parsing header '" + headerName + "'" - }; - } - else { - return true; - } - } - Parser.parseHeader = parseHeader; - /** Parse SIP Message - * @function - * @param {String} message SIP message. - * @param {Object} logger object. - * @returns {SIP.IncomingRequest|SIP.IncomingResponse|undefined} - */ - function parseMessage(data, logger) { - var headerStart = 0; - var headerEnd = data.indexOf("\r\n"); - if (headerEnd === -1) { - logger.warn("no CRLF found, not a SIP message, discarded"); - return; - } - // Parse first line. Check if it is a Request or a Reply. - var firstLine = data.substring(0, headerEnd); - var parsed = core_1.Grammar.parse(firstLine, "Request_Response"); - var message; - if (parsed === -1) { - logger.warn('error parsing first line of SIP message: "' + firstLine + '"'); - return; - } - else if (!parsed.status_code) { - message = new core_1.IncomingRequestMessage(); - message.method = parsed.method; - message.ruri = parsed.uri; - } - else { - message = new core_1.IncomingResponseMessage(); - message.statusCode = parsed.status_code; - message.reasonPhrase = parsed.reason_phrase; - } - message.data = data; - headerStart = headerEnd + 2; - /* Loop over every line in data. Detect the end of each header and parse - * it or simply add to the headers collection. - */ - var bodyStart; - while (true) { - headerEnd = getHeader(data, headerStart); - // The SIP message has normally finished. - if (headerEnd === -2) { - bodyStart = headerStart + 2; - break; - } - else if (headerEnd === -1) { - // data.indexOf returned -1 due to a malformed message. - logger.error("malformed message"); - return; - } - var parsedHeader = parseHeader(message, data, headerStart, headerEnd); - if (parsedHeader !== true) { - logger.error(parsed.error); - return; - } - headerStart = headerEnd + 2; - } - /* RFC3261 18.3. - * If there are additional bytes in the transport packet - * beyond the end of the body, they MUST be discarded. - */ - if (message.hasHeader("content-length")) { - message.body = data.substr(bodyStart, Number(message.getHeader("content-length"))); - } - else { - message.body = data.substring(bodyStart); - } - return message; - } - Parser.parseMessage = parseMessage; -})(Parser = exports.Parser || (exports.Parser = {})); - - -/***/ }), -/* 86 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var ClientContext_1 = __webpack_require__(79); -var Constants_1 = __webpack_require__(80); -var core_1 = __webpack_require__(2); -var Enums_1 = __webpack_require__(82); -var Exceptions_1 = __webpack_require__(84); -var Utils_1 = __webpack_require__(83); -/** - * SIP Publish (SIP Extension for Event State Publication RFC3903) - * @class Class creating a SIP PublishContext. - */ -var PublishContext = /** @class */ (function (_super) { - tslib_1.__extends(PublishContext, _super); - function PublishContext(ua, target, event, options) { - if (options === void 0) { options = {}; } - var _this = this; - options.extraHeaders = (options.extraHeaders || []).slice(); - options.contentType = (options.contentType || "text/plain"); - if (typeof options.expires !== "number" || (options.expires % 1) !== 0) { - options.expires = 3600; - } - else { - options.expires = Number(options.expires); - } - if (typeof (options.unpublishOnClose) !== "boolean") { - options.unpublishOnClose = true; - } - if (target === undefined || target === null || target === "") { - throw new Exceptions_1.Exceptions.MethodParameterError("Publish", "Target", target); - } - else { - target = ua.normalizeTarget(target); - if (target === undefined) { - throw new Exceptions_1.Exceptions.MethodParameterError("Publish", "Target", target); - } - } - _this = _super.call(this, ua, Constants_1.C.PUBLISH, target, options) || this; - _this.type = Enums_1.TypeStrings.PublishContext; - _this.options = options; - _this.target = target; - if (event === undefined || event === null || event === "") { - throw new Exceptions_1.Exceptions.MethodParameterError("Publish", "Event", event); - } - else { - _this.event = event; - } - _this.logger = ua.getLogger("sip.publish"); - _this.pubRequestExpires = _this.options.expires; - return _this; - } - /** - * Publish - * @param {string} Event body to publish, optional - */ - PublishContext.prototype.publish = function (body) { - // Clean up before the run - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - // is Inital or Modify request - this.options.body = body; - this.pubRequestBody = this.options.body; - if (this.pubRequestExpires === 0) { - // This is Initial request after unpublish - this.pubRequestExpires = this.options.expires; - this.pubRequestEtag = undefined; - } - if (!(this.ua.publishers[this.target.toString() + ":" + this.event])) { - this.ua.publishers[this.target.toString() + ":" + this.event] = this; - } - this.sendPublishRequest(); - }; - /** - * Unpublish - */ - PublishContext.prototype.unpublish = function () { - // Clean up before the run - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - this.pubRequestBody = undefined; - this.pubRequestExpires = 0; - if (this.pubRequestEtag !== undefined) { - this.sendPublishRequest(); - } - }; - /** - * Close - */ - PublishContext.prototype.close = function () { - // Send unpublish, if requested - if (this.options.unpublishOnClose) { - this.unpublish(); - } - else { - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - this.pubRequestBody = undefined; - this.pubRequestExpires = 0; - this.pubRequestEtag = undefined; - } - if (this.ua.publishers[this.target.toString() + ":" + this.event]) { - delete this.ua.publishers[this.target.toString() + ":" + this.event]; - } - }; - PublishContext.prototype.onRequestTimeout = function () { - _super.prototype.onRequestTimeout.call(this); - this.emit("unpublished", undefined, Constants_1.C.causes.REQUEST_TIMEOUT); - }; - PublishContext.prototype.onTransportError = function () { - _super.prototype.onTransportError.call(this); - this.emit("unpublished", undefined, Constants_1.C.causes.CONNECTION_ERROR); - }; - PublishContext.prototype.receiveResponse = function (response) { - var _this = this; - var statusCode = response.statusCode || 0; - var cause = Utils_1.Utils.getReasonPhrase(statusCode); - switch (true) { - case /^1[0-9]{2}$/.test(statusCode.toString()): - this.emit("progress", response, cause); - break; - case /^2[0-9]{2}$/.test(statusCode.toString()): - // Set SIP-Etag - if (response.hasHeader("SIP-ETag")) { - this.pubRequestEtag = response.getHeader("SIP-ETag"); - } - else { - this.logger.warn("SIP-ETag header missing in a 200-class response to PUBLISH"); - } - // Update Expire - if (response.hasHeader("Expires")) { - var expires = Number(response.getHeader("Expires")); - if (typeof expires === "number" && expires >= 0 && expires <= this.pubRequestExpires) { - this.pubRequestExpires = expires; - } - else { - this.logger.warn("Bad Expires header in a 200-class response to PUBLISH"); - } - } - else { - this.logger.warn("Expires header missing in a 200-class response to PUBLISH"); - } - if (this.pubRequestExpires !== 0) { - // Schedule refresh - this.publishRefreshTimer = setTimeout(function () { return _this.refreshRequest(); }, this.pubRequestExpires * 900); - this.emit("published", response, cause); - } - else { - this.emit("unpublished", response, cause); - } - break; - case /^412$/.test(statusCode.toString()): - // 412 code means no matching ETag - possibly the PUBLISH expired - // Resubmit as new request, if the current request is not a "remove" - if (this.pubRequestEtag !== undefined && this.pubRequestExpires !== 0) { - this.logger.warn("412 response to PUBLISH, recovering"); - this.pubRequestEtag = undefined; - this.emit("progress", response, cause); - this.publish(this.options.body); - } - else { - this.logger.warn("412 response to PUBLISH, recovery failed"); - this.pubRequestExpires = 0; - this.emit("failed", response, cause); - this.emit("unpublished", response, cause); - } - break; - case /^423$/.test(statusCode.toString()): - // 423 code means we need to adjust the Expires interval up - if (this.pubRequestExpires !== 0 && response.hasHeader("Min-Expires")) { - var minExpires = Number(response.getHeader("Min-Expires")); - if (typeof minExpires === "number" || minExpires > this.pubRequestExpires) { - this.logger.warn("423 code in response to PUBLISH, adjusting the Expires value and trying to recover"); - this.pubRequestExpires = minExpires; - this.emit("progress", response, cause); - this.publish(this.options.body); - } - else { - this.logger.warn("Bad 423 response Min-Expires header received for PUBLISH"); - this.pubRequestExpires = 0; - this.emit("failed", response, cause); - this.emit("unpublished", response, cause); - } - } - else { - this.logger.warn("423 response to PUBLISH, recovery failed"); - this.pubRequestExpires = 0; - this.emit("failed", response, cause); - this.emit("unpublished", response, cause); - } - break; - default: - this.pubRequestExpires = 0; - this.emit("failed", response, cause); - this.emit("unpublished", response, cause); - break; - } - // Do the cleanup - if (this.pubRequestExpires === 0) { - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - this.pubRequestBody = undefined; - this.pubRequestEtag = undefined; - } - }; - PublishContext.prototype.send = function () { - var _this = this; - this.ua.userAgentCore.publish(this.request, { - onAccept: function (response) { return _this.receiveResponse(response.message); }, - onProgress: function (response) { return _this.receiveResponse(response.message); }, - onRedirect: function (response) { return _this.receiveResponse(response.message); }, - onReject: function (response) { return _this.receiveResponse(response.message); }, - onTrying: function (response) { return _this.receiveResponse(response.message); } - }); - return this; - }; - PublishContext.prototype.refreshRequest = function () { - // Clean up before the run - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - // This is Refresh request - this.pubRequestBody = undefined; - if (this.pubRequestEtag === undefined) { - // Request not valid - throw new Exceptions_1.Exceptions.MethodParameterError("Publish", "Body", undefined); - } - if (this.pubRequestExpires === 0) { - // Request not valid - throw new Exceptions_1.Exceptions.MethodParameterError("Publish", "Expire", this.pubRequestExpires); - } - this.sendPublishRequest(); - }; - PublishContext.prototype.sendPublishRequest = function () { - var reqOptions = Object.create(this.options || Object.prototype); - reqOptions.extraHeaders = (this.options.extraHeaders || []).slice(); - reqOptions.extraHeaders.push("Event: " + this.event); - reqOptions.extraHeaders.push("Expires: " + this.pubRequestExpires); - if (this.pubRequestEtag !== undefined) { - reqOptions.extraHeaders.push("SIP-If-Match: " + this.pubRequestEtag); - } - var ruri = this.target instanceof core_1.URI ? this.target : this.ua.normalizeTarget(this.target); - if (!ruri) { - throw new Error("ruri undefined."); - } - var params = this.options.params || {}; - var bodyObj; - if (this.pubRequestBody !== undefined) { - bodyObj = { - body: this.pubRequestBody, - contentType: this.options.contentType - }; - } - var body; - if (bodyObj) { - body = Utils_1.Utils.fromBodyObj(bodyObj); - } - this.request = this.ua.userAgentCore.makeOutgoingRequestMessage(Constants_1.C.PUBLISH, ruri, params.fromUri ? params.fromUri : this.ua.userAgentCore.configuration.aor, params.toUri ? params.toUri : this.target, params, reqOptions.extraHeaders, body); - this.send(); - }; - return PublishContext; -}(ClientContext_1.ClientContext)); -exports.PublishContext = PublishContext; - - -/***/ }), -/* 87 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var ClientContext_1 = __webpack_require__(79); -var Constants_1 = __webpack_require__(80); -var core_1 = __webpack_require__(2); -var Enums_1 = __webpack_require__(82); -var Exceptions_1 = __webpack_require__(84); -var ServerContext_1 = __webpack_require__(88); -// tslint:disable-next-line:max-classes-per-file -var ReferClientContext = /** @class */ (function (_super) { - tslib_1.__extends(ReferClientContext, _super); - function ReferClientContext(ua, applicant, target, options) { - if (options === void 0) { options = {}; } - var _this = this; - if (ua === undefined || applicant === undefined || target === undefined) { - throw new TypeError("Not enough arguments"); - } - _this = _super.call(this, ua, Constants_1.C.REFER, applicant.remoteIdentity.uri.toString(), options) || this; - _this.type = Enums_1.TypeStrings.ReferClientContext; - _this.options = options; - _this.extraHeaders = (_this.options.extraHeaders || []).slice(); - _this.applicant = applicant; - _this.target = _this.initReferTo(target); - if (_this.ua) { - _this.extraHeaders.push("Referred-By: <" + _this.ua.configuration.uri + ">"); - } - // TODO: Check that this is correct isc/icc - _this.extraHeaders.push("Contact: " + applicant.contact); - // this is UA.C.ALLOWED_METHODS, removed to get around circular dependency - _this.extraHeaders.push("Allow: " + [ - "ACK", - "CANCEL", - "INVITE", - "MESSAGE", - "BYE", - "OPTIONS", - "INFO", - "NOTIFY", - "REFER" - ].toString()); - _this.extraHeaders.push("Refer-To: " + _this.target); - _this.errorListener = _this.onTransportError.bind(_this); - if (ua.transport) { - ua.transport.on("transportError", _this.errorListener); - } - return _this; - } - ReferClientContext.prototype.refer = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - var extraHeaders = (this.extraHeaders || []).slice(); - if (options.extraHeaders) { - extraHeaders.concat(options.extraHeaders); - } - this.applicant.sendRequest(Constants_1.C.REFER, { - extraHeaders: this.extraHeaders, - receiveResponse: function (response) { - var statusCode = response && response.statusCode ? response.statusCode.toString() : ""; - if (/^1[0-9]{2}$/.test(statusCode)) { - _this.emit("referRequestProgress", _this); - } - else if (/^2[0-9]{2}$/.test(statusCode)) { - _this.emit("referRequestAccepted", _this); - } - else if (/^[4-6][0-9]{2}$/.test(statusCode)) { - _this.emit("referRequestRejected", _this); - } - if (options.receiveResponse) { - options.receiveResponse(response); - } - } - }); - return this; - }; - ReferClientContext.prototype.receiveNotify = function (request) { - // If we can correctly handle this, then we need to send a 200 OK! - var contentType = request.message.hasHeader("Content-Type") ? - request.message.getHeader("Content-Type") : undefined; - if (contentType && contentType.search(/^message\/sipfrag/) !== -1) { - var messageBody = core_1.Grammar.parse(request.message.body, "sipfrag"); - if (messageBody === -1) { - request.reject({ - statusCode: 489, - reasonPhrase: "Bad Event" - }); - return; - } - switch (true) { - case (/^1[0-9]{2}$/.test(messageBody.status_code)): - this.emit("referProgress", this); - break; - case (/^2[0-9]{2}$/.test(messageBody.status_code)): - this.emit("referAccepted", this); - if (!this.options.activeAfterTransfer && this.applicant.terminate) { - this.applicant.terminate(); - } - break; - default: - this.emit("referRejected", this); - break; - } - request.accept(); - this.emit("notify", request.message); - return; - } - request.reject({ - statusCode: 489, - reasonPhrase: "Bad Event" - }); - }; - ReferClientContext.prototype.initReferTo = function (target) { - var stringOrURI; - if (typeof target === "string") { - // REFER without Replaces (Blind Transfer) - var targetString = core_1.Grammar.parse(target, "Refer_To"); - stringOrURI = targetString && targetString.uri ? targetString.uri : target; - // Check target validity - var targetUri = this.ua.normalizeTarget(target); - if (!targetUri) { - throw new TypeError("Invalid target: " + target); - } - stringOrURI = targetUri; - } - else { - // REFER with Replaces (Attended Transfer) - if (!target.session) { - throw new Error("Session undefined."); - } - var displayName = target.remoteIdentity.friendlyName; - var remoteTarget = target.session.remoteTarget.toString(); - var callId = target.session.callId; - var remoteTag = target.session.remoteTag; - var localTag = target.session.localTag; - var replaces = encodeURIComponent(callId + ";to-tag=" + remoteTag + ";from-tag=" + localTag); - stringOrURI = "\"" + displayName + "\" <" + remoteTarget + "?Replaces=" + replaces + ">"; - } - return stringOrURI; - }; - return ReferClientContext; -}(ClientContext_1.ClientContext)); -exports.ReferClientContext = ReferClientContext; -// tslint:disable-next-line:max-classes-per-file -var ReferServerContext = /** @class */ (function (_super) { - tslib_1.__extends(ReferServerContext, _super); - function ReferServerContext(ua, incomingRequest, session) { - var _this = _super.call(this, ua, incomingRequest) || this; - _this.session = session; - _this.type = Enums_1.TypeStrings.ReferServerContext; - _this.ua = ua; - _this.status = Enums_1.SessionStatus.STATUS_INVITE_RECEIVED; - _this.fromTag = _this.request.fromTag; - _this.id = _this.request.callId + _this.fromTag; - _this.contact = _this.ua.contact.toString(); - _this.logger = ua.getLogger("sip.referservercontext", _this.id); - // Needed to send the NOTIFY's - _this.cseq = Math.floor(Math.random() * 10000); - _this.callId = _this.request.callId; - _this.fromUri = _this.request.to.uri; - _this.fromTag = _this.request.to.parameters.tag; - _this.remoteTarget = _this.request.headers.Contact[0].parsed.uri; - _this.toUri = _this.request.from.uri; - _this.toTag = _this.request.fromTag; - _this.routeSet = _this.request.getHeaders("record-route"); - // RFC 3515 2.4.1 - if (!_this.request.hasHeader("refer-to")) { - _this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting refer."); - _this.reject(); - return _this; - } - _this.referTo = _this.request.parseHeader("refer-to"); - // TODO: Must set expiration timer and send 202 if there is no response by then - _this.referredSession = _this.ua.findSession(_this.request); - if (_this.request.hasHeader("referred-by")) { - _this.referredBy = _this.request.getHeader("referred-by"); - } - if (_this.referTo.uri.hasHeader("replaces")) { - _this.replaces = _this.referTo.uri.getHeader("replaces"); - } - _this.errorListener = _this.onTransportError.bind(_this); - if (ua.transport) { - ua.transport.on("transportError", _this.errorListener); - } - _this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER; - return _this; - } - ReferServerContext.prototype.progress = function () { - if (this.status !== Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER) { - throw new Exceptions_1.Exceptions.InvalidStateError(this.status); - } - this.incomingRequest.trying(); - }; - ReferServerContext.prototype.reject = function (options) { - if (options === void 0) { options = {}; } - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - throw new Exceptions_1.Exceptions.InvalidStateError(this.status); - } - this.logger.log("Rejecting refer"); - this.status = Enums_1.SessionStatus.STATUS_TERMINATED; - _super.prototype.reject.call(this, options); - this.emit("referRequestRejected", this); - }; - ReferServerContext.prototype.accept = function (options, modifiers) { - var _this = this; - if (options === void 0) { options = {}; } - if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER) { - this.status = Enums_1.SessionStatus.STATUS_ANSWERED; - } - else { - throw new Exceptions_1.Exceptions.InvalidStateError(this.status); - } - this.incomingRequest.accept({ - statusCode: 202, - reasonPhrase: "Accepted" - }); - this.emit("referRequestAccepted", this); - if (options.followRefer) { - this.logger.log("Accepted refer, attempting to automatically follow it"); - var target = this.referTo.uri; - if (!target.scheme || !target.scheme.match("^sips?$")) { - this.logger.error("SIP.js can only automatically follow SIP refer target"); - this.reject(); - return; - } - var inviteOptions = options.inviteOptions || {}; - var extraHeaders = (inviteOptions.extraHeaders || []).slice(); - if (this.replaces) { - // decodeURIComponent is a holdover from 2c086eb4. Not sure that it is actually necessary - extraHeaders.push("Replaces: " + decodeURIComponent(this.replaces)); - } - if (this.referredBy) { - extraHeaders.push("Referred-By: " + this.referredBy); - } - inviteOptions.extraHeaders = extraHeaders; - target.clearHeaders(); - this.targetSession = this.ua.invite(target.toString(), inviteOptions, modifiers); - this.emit("referInviteSent", this); - if (this.targetSession) { - this.targetSession.once("progress", function (response) { - var statusCode = response.statusCode || 100; - var reasonPhrase = response.reasonPhrase; - _this.sendNotify(("SIP/2.0 " + statusCode + " " + reasonPhrase).trim()); - _this.emit("referProgress", _this); - if (_this.referredSession) { - _this.referredSession.emit("referProgress", _this); - } - }); - this.targetSession.once("accepted", function () { - _this.logger.log("Successfully followed the refer"); - _this.sendNotify("SIP/2.0 200 OK"); - _this.emit("referAccepted", _this); - if (_this.referredSession) { - _this.referredSession.emit("referAccepted", _this); - } - }); - var referFailed = function (response) { - if (_this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return; // No throw here because it is possible this gets called multiple times - } - _this.logger.log("Refer was not successful. Resuming session"); - if (response && response.statusCode === 429) { - _this.logger.log("Alerting referrer that identity is required."); - _this.sendNotify("SIP/2.0 429 Provide Referrer Identity"); - return; - } - _this.sendNotify("SIP/2.0 603 Declined"); - // Must change the status after sending the final Notify or it will not send due to check - _this.status = Enums_1.SessionStatus.STATUS_TERMINATED; - _this.emit("referRejected", _this); - if (_this.referredSession) { - _this.referredSession.emit("referRejected"); - } - }; - this.targetSession.once("rejected", referFailed); - this.targetSession.once("failed", referFailed); - } - } - else { - this.logger.log("Accepted refer, but did not automatically follow it"); - this.sendNotify("SIP/2.0 200 OK"); - this.emit("referAccepted", this); - if (this.referredSession) { - this.referredSession.emit("referAccepted", this); - } - } - }; - ReferServerContext.prototype.sendNotify = function (bodyStr) { - // FIXME: Ported this. Clean it up. Session knows its state. - if (this.status !== Enums_1.SessionStatus.STATUS_ANSWERED) { - throw new Exceptions_1.Exceptions.InvalidStateError(this.status); - } - if (core_1.Grammar.parse(bodyStr, "sipfrag") === -1) { - throw new Error("sipfrag body is required to send notify for refer"); - } - var body = { - contentDisposition: "render", - contentType: "message/sipfrag", - content: bodyStr - }; - // NOTIFY requests sent in same dialog as in dialog REFER. - if (this.session) { - this.session.notify(undefined, { - extraHeaders: [ - "Event: refer", - "Subscription-State: terminated", - ], - body: body - }); - return; - } - // The implicit subscription created by a REFER is the same as a - // subscription created with a SUBSCRIBE request. The agent issuing the - // REFER can terminate this subscription prematurely by unsubscribing - // using the mechanisms described in [2]. Terminating a subscription, - // either by explicitly unsubscribing or rejecting NOTIFY, is not an - // indication that the referenced request should be withdrawn or - // abandoned. - // https://tools.ietf.org/html/rfc3515#section-2.4.4 - // NOTIFY requests sent in new dialog for out of dialog REFER. - // FIXME: TODO: This should be done in a subscribe dialog to satisfy the above. - var request = this.ua.userAgentCore.makeOutgoingRequestMessage(Constants_1.C.NOTIFY, this.remoteTarget, this.fromUri, this.toUri, { - cseq: this.cseq += 1, - callId: this.callId, - fromTag: this.fromTag, - toTag: this.toTag, - routeSet: this.routeSet - }, [ - "Event: refer", - "Subscription-State: terminated", - "Content-Type: message/sipfrag" - ], body); - var transport = this.ua.transport; - if (!transport) { - throw new Error("Transport undefined."); - } - var user = { - loggerFactory: this.ua.getLoggerFactory() - }; - var nic = new core_1.NonInviteClientTransaction(request, transport, user); - }; - ReferServerContext.prototype.on = function (name, callback) { return _super.prototype.on.call(this, name, callback); }; - return ReferServerContext; -}(ServerContext_1.ServerContext)); -exports.ReferServerContext = ReferServerContext; - - -/***/ }), -/* 88 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var events_1 = __webpack_require__(30); -var Constants_1 = __webpack_require__(80); -var core_1 = __webpack_require__(2); -var Enums_1 = __webpack_require__(82); -var Utils_1 = __webpack_require__(83); -var ServerContext = /** @class */ (function (_super) { - tslib_1.__extends(ServerContext, _super); - function ServerContext(ua, incomingRequest) { - var _this = _super.call(this) || this; - _this.incomingRequest = incomingRequest; - _this.data = {}; - ServerContext.initializer(_this, ua, incomingRequest); - return _this; - } - // hack to get around our multiple inheritance issues - ServerContext.initializer = function (objectToConstruct, ua, incomingRequest) { - var request = incomingRequest.message; - objectToConstruct.type = Enums_1.TypeStrings.ServerContext; - objectToConstruct.ua = ua; - objectToConstruct.logger = ua.getLogger("sip.servercontext"); - objectToConstruct.request = request; - if (request.body) { - objectToConstruct.body = request.body; - } - if (request.hasHeader("Content-Type")) { - objectToConstruct.contentType = request.getHeader("Content-Type"); - } - objectToConstruct.method = request.method; - objectToConstruct.localIdentity = request.to; - objectToConstruct.remoteIdentity = request.from; - var hasAssertedIdentity = request.hasHeader("P-Asserted-Identity"); - if (hasAssertedIdentity) { - var assertedIdentity = request.getHeader("P-Asserted-Identity"); - if (assertedIdentity) { - objectToConstruct.assertedIdentity = core_1.Grammar.nameAddrHeaderParse(assertedIdentity); - } - } - }; - ServerContext.prototype.progress = function (options) { - if (options === void 0) { options = {}; } - options.statusCode = options.statusCode || 180; - options.minCode = 100; - options.maxCode = 199; - options.events = ["progress"]; - return this.reply(options); - }; - ServerContext.prototype.accept = function (options) { - if (options === void 0) { options = {}; } - options.statusCode = options.statusCode || 200; - options.minCode = 200; - options.maxCode = 299; - options.events = ["accepted"]; - return this.reply(options); - }; - ServerContext.prototype.reject = function (options) { - if (options === void 0) { options = {}; } - options.statusCode = options.statusCode || 480; - options.minCode = 300; - options.maxCode = 699; - options.events = ["rejected", "failed"]; - return this.reply(options); - }; - ServerContext.prototype.reply = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - var statusCode = options.statusCode || 100; - var minCode = options.minCode || 100; - var maxCode = options.maxCode || 699; - var reasonPhrase = Utils_1.Utils.getReasonPhrase(statusCode, options.reasonPhrase); - var extraHeaders = options.extraHeaders || []; - var body = options.body ? core_1.fromBodyLegacy(options.body) : undefined; - var events = options.events || []; - if (statusCode < minCode || statusCode > maxCode) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - var responseOptions = { - statusCode: statusCode, - reasonPhrase: reasonPhrase, - extraHeaders: extraHeaders, - body: body - }; - var response; - var statusCodeString = statusCode.toString(); - switch (true) { - case /^100$/.test(statusCodeString): - response = this.incomingRequest.trying(responseOptions).message; - break; - case /^1[0-9]{2}$/.test(statusCodeString): - response = this.incomingRequest.progress(responseOptions).message; - break; - case /^2[0-9]{2}$/.test(statusCodeString): - response = this.incomingRequest.accept(responseOptions).message; - break; - case /^3[0-9]{2}$/.test(statusCodeString): - response = this.incomingRequest.redirect([], responseOptions).message; - break; - case /^[4-6][0-9]{2}$/.test(statusCodeString): - response = this.incomingRequest.reject(responseOptions).message; - break; - default: - throw new Error("Invalid status code " + statusCode); - } - events.forEach(function (event) { - _this.emit(event, response, reasonPhrase); - }); - return this; - }; - ServerContext.prototype.onRequestTimeout = function () { - this.emit("failed", undefined, Constants_1.C.causes.REQUEST_TIMEOUT); - }; - ServerContext.prototype.onTransportError = function () { - this.emit("failed", undefined, Constants_1.C.causes.CONNECTION_ERROR); - }; - return ServerContext; -}(events_1.EventEmitter)); -exports.ServerContext = ServerContext; - - -/***/ }), -/* 89 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var ClientContext_1 = __webpack_require__(79); -var Constants_1 = __webpack_require__(80); -var core_1 = __webpack_require__(2); -var Enums_1 = __webpack_require__(82); -var Exceptions_1 = __webpack_require__(84); -var Utils_1 = __webpack_require__(83); -/** - * Configuration load. - * @private - * returns {any} - */ -function loadConfig(configuration) { - var settings = { - expires: 600, - extraContactHeaderParams: [], - instanceId: undefined, - params: {}, - regId: undefined, - registrar: undefined, - }; - var configCheck = getConfigurationCheck(); - // Check Mandatory parameters - for (var parameter in configCheck.mandatory) { - if (!configuration.hasOwnProperty(parameter)) { - throw new Exceptions_1.Exceptions.ConfigurationError(parameter); - } - else { - var value = configuration[parameter]; - var checkedValue = configCheck.mandatory[parameter](value); - if (checkedValue !== undefined) { - settings[parameter] = checkedValue; - } - else { - throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); - } - } - } - // Check Optional parameters - for (var parameter in configCheck.optional) { - if (configuration.hasOwnProperty(parameter)) { - var value = configuration[parameter]; - // If the parameter value is an empty array, but shouldn't be, apply its default value. - if (value instanceof Array && value.length === 0) { - continue; - } - // If the parameter value is null, empty string, or undefined then apply its default value. - // If it's a number with NaN value then also apply its default value. - // NOTE: JS does not allow "value === NaN", the following does the work: - if (value === null || value === "" || value === undefined || - (typeof (value) === "number" && isNaN(value))) { - continue; - } - var checkedValue = configCheck.optional[parameter](value); - if (checkedValue !== undefined) { - settings[parameter] = checkedValue; - } - else { - throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); - } - } - } - return settings; -} -function getConfigurationCheck() { - return { - mandatory: {}, - optional: { - expires: function (expires) { - if (Utils_1.Utils.isDecimal(expires)) { - var value = Number(expires); - if (value >= 0) { - return value; - } - } - }, - extraContactHeaderParams: function (extraContactHeaderParams) { - if (extraContactHeaderParams instanceof Array) { - return extraContactHeaderParams.filter(function (contactHeaderParam) { return (typeof contactHeaderParam === "string"); }); - } - }, - instanceId: function (instanceId) { - if (typeof instanceId !== "string") { - return; - } - if ((/^uuid:/i.test(instanceId))) { - instanceId = instanceId.substr(5); - } - if (core_1.Grammar.parse(instanceId, "uuid") === -1) { - return; - } - else { - return instanceId; - } - }, - params: function (params) { - if (typeof params === "object") { - return params; - } - }, - regId: function (regId) { - if (Utils_1.Utils.isDecimal(regId)) { - var value = Number(regId); - if (value >= 0) { - return value; - } - } - }, - registrar: function (registrar) { - if (typeof registrar !== "string") { - return; - } - if (!/^sip:/i.test(registrar)) { - registrar = Constants_1.C.SIP + ":" + registrar; - } - var parsed = core_1.Grammar.URIParse(registrar); - if (!parsed) { - return; - } - else if (parsed.user) { - return; - } - else { - return parsed; - } - } - } - }; -} -var RegisterContext = /** @class */ (function (_super) { - tslib_1.__extends(RegisterContext, _super); - function RegisterContext(ua, options) { - if (options === void 0) { options = {}; } - var _this = this; - var settings = loadConfig(options); - if (settings.regId && !settings.instanceId) { - settings.instanceId = Utils_1.Utils.newUUID(); - } - else if (!settings.regId && settings.instanceId) { - settings.regId = 1; - } - settings.params.toUri = settings.params.toUri || ua.configuration.uri; - settings.params.toDisplayName = settings.params.toDisplayName || ua.configuration.displayName; - settings.params.callId = settings.params.callId || Utils_1.Utils.createRandomToken(22); - settings.params.cseq = settings.params.cseq || Math.floor(Math.random() * 10000); - /* If no 'registrarServer' is set use the 'uri' value without user portion. */ - if (!settings.registrar) { - var registrarServer = {}; - if (typeof ua.configuration.uri === "object") { - registrarServer = ua.configuration.uri.clone(); - registrarServer.user = undefined; - } - else { - registrarServer = ua.configuration.uri; - } - settings.registrar = registrarServer; - } - _this = _super.call(this, ua, Constants_1.C.REGISTER, settings.registrar, settings) || this; - _this.type = Enums_1.TypeStrings.RegisterContext; - _this.options = settings; - _this.logger = ua.getLogger("sip.registercontext"); - _this.logger.log("configuration parameters for RegisterContext after validation:"); - for (var parameter in settings) { - if (settings.hasOwnProperty(parameter)) { - _this.logger.log("· " + parameter + ": " + JSON.stringify(settings[parameter])); - } - } - // Registration expires - _this.expires = settings.expires; - // Contact header - _this.contact = ua.contact.toString(); - // Set status - _this.registered = false; - ua.transport.on("disconnected", function () { return _this.onTransportDisconnected(); }); - return _this; - } - RegisterContext.prototype.register = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - // Handle Options - this.options = tslib_1.__assign({}, this.options, options); - var extraHeaders = (this.options.extraHeaders || []).slice(); - extraHeaders.push("Contact: " + this.generateContactHeader(this.expires)); - // this is UA.C.ALLOWED_METHODS, removed to get around circular dependency - extraHeaders.push("Allow: " + [ - "ACK", - "CANCEL", - "INVITE", - "MESSAGE", - "BYE", - "OPTIONS", - "INFO", - "NOTIFY", - "REFER" - ].toString()); - // Save original extraHeaders to be used in .close - this.closeHeaders = this.options.closeWithHeaders ? - (this.options.extraHeaders || []).slice() : []; - this.receiveResponse = function (response) { - // Discard responses to older REGISTER/un-REGISTER requests. - if (response.cseq !== _this.request.cseq) { - return; - } - // Clear registration timer - if (_this.registrationTimer !== undefined) { - clearTimeout(_this.registrationTimer); - _this.registrationTimer = undefined; - } - var statusCode = (response.statusCode || 0).toString(); - switch (true) { - case /^1[0-9]{2}$/.test(statusCode): - _this.emit("progress", response); - break; - case /^2[0-9]{2}$/.test(statusCode): - _this.emit("accepted", response); - var expires = void 0; - if (response.hasHeader("expires")) { - expires = Number(response.getHeader("expires")); - } - if (_this.registrationExpiredTimer !== undefined) { - clearTimeout(_this.registrationExpiredTimer); - _this.registrationExpiredTimer = undefined; - } - // Search the Contact pointing to us and update the expires value accordingly. - var contacts = response.getHeaders("contact").length; - if (!contacts) { - _this.logger.warn("no Contact header in response to REGISTER, response ignored"); - break; - } - var contact = void 0; - while (contacts--) { - contact = response.parseHeader("contact", contacts); - if (contact.uri.user === _this.ua.contact.uri.user) { - expires = contact.getParam("expires"); - break; - } - else { - contact = undefined; - } - } - if (!contact) { - _this.logger.warn("no Contact header pointing to us, response ignored"); - break; - } - if (expires === undefined) { - expires = _this.expires; - } - // Re-Register before the expiration interval has elapsed. - // For that, decrease the expires value. ie: 3 seconds - _this.registrationTimer = setTimeout(function () { - _this.registrationTimer = undefined; - _this.register(_this.options); - }, (expires * 1000) - 3000); - _this.registrationExpiredTimer = setTimeout(function () { - _this.logger.warn("registration expired"); - if (_this.registered) { - _this.unregistered(undefined, Constants_1.C.causes.EXPIRES); - } - }, expires * 1000); - // Save gruu values - if (contact.hasParam("temp-gruu")) { - _this.ua.contact.tempGruu = core_1.Grammar.URIParse(contact.getParam("temp-gruu").replace(/"/g, "")); - } - if (contact.hasParam("pub-gruu")) { - _this.ua.contact.pubGruu = core_1.Grammar.URIParse(contact.getParam("pub-gruu").replace(/"/g, "")); - } - _this.registered = true; - _this.emit("registered", response || undefined); - break; - // Interval too brief RFC3261 10.2.8 - case /^423$/.test(statusCode): - if (response.hasHeader("min-expires")) { - // Increase our registration interval to the suggested minimum - _this.expires = Number(response.getHeader("min-expires")); - // Attempt the registration again immediately - _this.register(_this.options); - } - else { // This response MUST contain a Min-Expires header field - _this.logger.warn("423 response received for REGISTER without Min-Expires"); - _this.registrationFailure(response, Constants_1.C.causes.SIP_FAILURE_CODE); - } - break; - default: - _this.registrationFailure(response, Utils_1.Utils.sipErrorCause(response.statusCode || 0)); - } - }; - this.onRequestTimeout = function () { - _this.registrationFailure(undefined, Constants_1.C.causes.REQUEST_TIMEOUT); - }; - this.onTransportError = function () { - _this.registrationFailure(undefined, Constants_1.C.causes.CONNECTION_ERROR); - }; - this.request.cseq++; - this.request.setHeader("cseq", this.request.cseq + " REGISTER"); - this.request.extraHeaders = extraHeaders; - this.send(); - }; - RegisterContext.prototype.close = function () { - var options = { - all: false, - extraHeaders: this.closeHeaders - }; - this.registeredBefore = this.registered; - if (this.registered) { - this.unregister(options); - } - }; - RegisterContext.prototype.unregister = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - if (!this.registered && !options.all) { - this.logger.warn("Already unregistered, but sending an unregister anyways."); - } - var extraHeaders = (options.extraHeaders || []).slice(); - this.registered = false; - // Clear the registration timer. - if (this.registrationTimer !== undefined) { - clearTimeout(this.registrationTimer); - this.registrationTimer = undefined; - } - if (options.all) { - extraHeaders.push("Contact: *"); - extraHeaders.push("Expires: 0"); - } - else { - extraHeaders.push("Contact: " + this.generateContactHeader(0)); - } - this.receiveResponse = function (response) { - var statusCode = (response && response.statusCode) ? response.statusCode.toString() : ""; - switch (true) { - case /^1[0-9]{2}$/.test(statusCode): - _this.emit("progress", response); - break; - case /^2[0-9]{2}$/.test(statusCode): - _this.emit("accepted", response); - if (_this.registrationExpiredTimer !== undefined) { - clearTimeout(_this.registrationExpiredTimer); - _this.registrationExpiredTimer = undefined; - } - _this.unregistered(response); - break; - default: - _this.unregistered(response, Utils_1.Utils.sipErrorCause(response.statusCode || 0)); - } - }; - this.onRequestTimeout = function () { - // Not actually unregistered... - // this.unregistered(undefined, SIP.C.causes.REQUEST_TIMEOUT); - }; - this.request.cseq++; - this.request.setHeader("cseq", this.request.cseq + " REGISTER"); - this.request.extraHeaders = extraHeaders; - this.send(); - }; - RegisterContext.prototype.unregistered = function (response, cause) { - this.registered = false; - this.emit("unregistered", response || undefined, cause || undefined); - }; - RegisterContext.prototype.send = function () { - var _this = this; - this.ua.userAgentCore.register(this.request, { - onAccept: function (response) { return _this.receiveResponse(response.message); }, - onProgress: function (response) { return _this.receiveResponse(response.message); }, - onRedirect: function (response) { return _this.receiveResponse(response.message); }, - onReject: function (response) { return _this.receiveResponse(response.message); }, - onTrying: function (response) { return _this.receiveResponse(response.message); } - }); - return this; - }; - RegisterContext.prototype.registrationFailure = function (response, cause) { - this.emit("failed", response || undefined, cause || undefined); - }; - RegisterContext.prototype.onTransportDisconnected = function () { - this.registeredBefore = this.registered; - if (this.registrationTimer !== undefined) { - clearTimeout(this.registrationTimer); - this.registrationTimer = undefined; - } - if (this.registrationExpiredTimer !== undefined) { - clearTimeout(this.registrationExpiredTimer); - this.registrationExpiredTimer = undefined; - } - if (this.registered) { - this.unregistered(undefined, Constants_1.C.causes.CONNECTION_ERROR); - } - }; - /** - * Helper Function to generate Contact Header - * @private - * returns {String} - */ - RegisterContext.prototype.generateContactHeader = function (expires) { - if (expires === void 0) { expires = 0; } - var contact = this.contact; - if (this.options.regId && this.options.instanceId) { - contact += ";reg-id=" + this.options.regId; - contact += ';+sip.instance=""'; - } - if (this.options.extraContactHeaderParams) { - this.options.extraContactHeaderParams.forEach(function (header) { - contact += ";" + header; - }); - } - contact += ";expires=" + expires; - return contact; - }; - return RegisterContext; -}(ClientContext_1.ClientContext)); -exports.RegisterContext = RegisterContext; - - -/***/ }), -/* 90 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var events_1 = __webpack_require__(30); -var ClientContext_1 = __webpack_require__(79); -var Constants_1 = __webpack_require__(80); -var core_1 = __webpack_require__(2); -var Enums_1 = __webpack_require__(82); -var Exceptions_1 = __webpack_require__(84); -var ReferContext_1 = __webpack_require__(87); -var ServerContext_1 = __webpack_require__(88); -var DTMF_1 = __webpack_require__(91); -var Utils_1 = __webpack_require__(83); -/* - * @param {function returning SIP.sessionDescriptionHandler} [sessionDescriptionHandlerFactory] - * (See the documentation for the sessionDescriptionHandlerFactory argument of the UA constructor.) - */ -var Session = /** @class */ (function (_super) { - tslib_1.__extends(Session, _super); - function Session(sessionDescriptionHandlerFactory) { - var _this = _super.call(this) || this; - _this.data = {}; - _this.type = Enums_1.TypeStrings.Session; - if (!sessionDescriptionHandlerFactory) { - throw new Exceptions_1.Exceptions.SessionDescriptionHandlerError("A session description handler is required for the session to function"); - } - _this.status = Session.C.STATUS_NULL; - _this.pendingReinvite = false; - _this.sessionDescriptionHandlerFactory = sessionDescriptionHandlerFactory; - _this.hasOffer = false; - _this.hasAnswer = false; - // Session Timers - _this.timers = { - ackTimer: undefined, - expiresTimer: undefined, - invite2xxTimer: undefined, - userNoAnswerTimer: undefined, - rel1xxTimer: undefined, - prackTimer: undefined - }; - // Session info - _this.startTime = undefined; - _this.endTime = undefined; - _this.tones = undefined; - // Hold state - _this.localHold = false; - _this.earlySdp = undefined; - _this.rel100 = Constants_1.C.supported.UNSUPPORTED; - return _this; - } - Session.prototype.dtmf = function (tones, options) { - var _this = this; - if (options === void 0) { options = {}; } - // Check Session Status - if (this.status !== Enums_1.SessionStatus.STATUS_CONFIRMED && this.status !== Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK) { - throw new Exceptions_1.Exceptions.InvalidStateError(this.status); - } - // Check tones - if (!tones || !tones.toString().match(/^[0-9A-D#*,]+$/i)) { - throw new TypeError("Invalid tones: " + tones); - } - var sendDTMF = function () { - if (_this.status === Enums_1.SessionStatus.STATUS_TERMINATED || !_this.tones || _this.tones.length === 0) { - // Stop sending DTMF - _this.tones = undefined; - return; - } - var dtmf = _this.tones.shift(); - var timeout; - if (dtmf.tone === ",") { - timeout = 2000; - } - else { - dtmf.on("failed", function () { _this.tones = undefined; }); - dtmf.send(options); - timeout = dtmf.duration + dtmf.interToneGap; - } - // Set timeout for the next tone - setTimeout(sendDTMF, timeout); - }; - tones = tones.toString(); - var dtmfType = this.ua.configuration.dtmfType; - if (this.sessionDescriptionHandler && dtmfType === Constants_1.C.dtmfType.RTP) { - var sent = this.sessionDescriptionHandler.sendDtmf(tones, options); - if (!sent) { - this.logger.warn("Attempt to use dtmfType 'RTP' has failed, falling back to INFO packet method"); - dtmfType = Constants_1.C.dtmfType.INFO; - } - } - if (dtmfType === Constants_1.C.dtmfType.INFO) { - var dtmfs = []; - var tonesArray = tones.split(""); - while (tonesArray.length > 0) { - dtmfs.push(new DTMF_1.DTMF(this, tonesArray.shift(), options)); - } - if (this.tones) { - // Tones are already queued, just add to the queue - this.tones = this.tones.concat(dtmfs); - return this; - } - this.tones = dtmfs; - sendDTMF(); - } - return this; - }; - Session.prototype.bye = function (options) { - if (options === void 0) { options = {}; } - // Check Session Status - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - this.logger.error("Error: Attempted to send BYE in a terminated session."); - return this; - } - this.logger.log("terminating Session"); - var statusCode = options.statusCode; - if (statusCode && (statusCode < 200 || statusCode >= 700)) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - options.receiveResponse = function () { }; - return this.sendRequest(Constants_1.C.BYE, options).terminated(); - }; - Session.prototype.refer = function (target, options) { - if (options === void 0) { options = {}; } - // Check Session Status - if (this.status !== Enums_1.SessionStatus.STATUS_CONFIRMED) { - throw new Exceptions_1.Exceptions.InvalidStateError(this.status); - } - this.referContext = new ReferContext_1.ReferClientContext(this.ua, this, target, options); - this.emit("referRequested", this.referContext); - this.referContext.refer(options); - return this.referContext; - }; - /** - * Sends in dialog request. - * @param method Request method. - * @param options Options bucket. - */ - Session.prototype.sendRequest = function (method, options) { - if (options === void 0) { options = {}; } - if (!this.session) { - throw new Error("Session undefined."); - } - // Convert any "body" option to a Body. - if (options.body) { - options.body = Utils_1.Utils.fromBodyObj(options.body); - } - // Convert any "receiveResponse" callback option passed to an OutgoingRequestDelegate. - var delegate; - var callback = options.receiveResponse; - if (callback) { - delegate = { - onAccept: function (response) { return callback(response.message); }, - onProgress: function (response) { return callback(response.message); }, - onRedirect: function (response) { return callback(response.message); }, - onReject: function (response) { return callback(response.message); }, - onTrying: function (response) { return callback(response.message); } - }; - } - var request; - var requestOptions = options; - switch (method) { - case Constants_1.C.BYE: - request = this.session.bye(delegate, requestOptions); - break; - case Constants_1.C.INVITE: - request = this.session.invite(delegate, requestOptions); - break; - case Constants_1.C.REFER: - request = this.session.refer(delegate, requestOptions); - break; - default: - throw new Error("Unexpected " + method + ". Method not implemented by user agent core."); - } - // Ported - Emit the request event - this.emit(method.toLowerCase(), request.message); - return this; - }; - Session.prototype.close = function () { - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return this; - } - this.logger.log("closing INVITE session " + this.id); - // 1st Step. Terminate media. - if (this.sessionDescriptionHandler) { - this.sessionDescriptionHandler.close(); - } - // 2nd Step. Terminate signaling. - // Clear session timers - for (var timer in this.timers) { - if (this.timers[timer]) { - clearTimeout(this.timers[timer]); - } - } - this.status = Enums_1.SessionStatus.STATUS_TERMINATED; - if (this.ua.transport) { - this.ua.transport.removeListener("transportError", this.errorListener); - } - delete this.ua.sessions[this.id]; - return this; - }; - Session.prototype.hold = function (options, modifiers) { - if (options === void 0) { options = {}; } - if (modifiers === void 0) { modifiers = []; } - if (this.status !== Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK && this.status !== Enums_1.SessionStatus.STATUS_CONFIRMED) { - throw new Exceptions_1.Exceptions.InvalidStateError(this.status); - } - if (this.localHold) { - this.logger.log("Session is already on hold, cannot put it on hold again"); - return; - } - options.modifiers = modifiers; - if (this.sessionDescriptionHandler) { - options.modifiers.push(this.sessionDescriptionHandler.holdModifier); - } - this.localHold = true; - this.sendReinvite(options); - }; - Session.prototype.unhold = function (options, modifiers) { - if (options === void 0) { options = {}; } - if (modifiers === void 0) { modifiers = []; } - if (this.status !== Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK && this.status !== Enums_1.SessionStatus.STATUS_CONFIRMED) { - throw new Exceptions_1.Exceptions.InvalidStateError(this.status); - } - if (!this.localHold) { - this.logger.log("Session is not on hold, cannot unhold it"); - return; - } - options.modifiers = modifiers; - this.localHold = false; - this.sendReinvite(options); - }; - Session.prototype.reinvite = function (options, modifiers) { - if (options === void 0) { options = {}; } - if (modifiers === void 0) { modifiers = []; } - options.modifiers = modifiers; - return this.sendReinvite(options); - }; - Session.prototype.terminate = function (options) { - // here for types and to be overridden - return this; - }; - Session.prototype.onTransportError = function () { - if (this.status !== Enums_1.SessionStatus.STATUS_CONFIRMED && this.status !== Enums_1.SessionStatus.STATUS_TERMINATED) { - this.failed(undefined, Constants_1.C.causes.CONNECTION_ERROR); - } - }; - Session.prototype.onRequestTimeout = function () { - if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { - this.terminated(undefined, Constants_1.C.causes.REQUEST_TIMEOUT); - } - else if (this.status !== Enums_1.SessionStatus.STATUS_TERMINATED) { - this.failed(undefined, Constants_1.C.causes.REQUEST_TIMEOUT); - this.terminated(undefined, Constants_1.C.causes.REQUEST_TIMEOUT); - } - }; - Session.prototype.onDialogError = function (response) { - if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { - this.terminated(response, Constants_1.C.causes.DIALOG_ERROR); - } - else if (this.status !== Enums_1.SessionStatus.STATUS_TERMINATED) { - this.failed(response, Constants_1.C.causes.DIALOG_ERROR); - this.terminated(response, Constants_1.C.causes.DIALOG_ERROR); - } - }; - Session.prototype.on = function (name, callback) { - return _super.prototype.on.call(this, name, callback); - }; - Session.prototype.onAck = function (incomingRequest) { - var _this = this; - var confirmSession = function () { - clearTimeout(_this.timers.ackTimer); - clearTimeout(_this.timers.invite2xxTimer); - _this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; - var contentDisp = incomingRequest.message.getHeader("Content-Disposition"); - if (contentDisp && contentDisp.type === "render") { - _this.renderbody = incomingRequest.message.body; - _this.rendertype = incomingRequest.message.getHeader("Content-Type"); - } - _this.emit("confirmed", incomingRequest.message); - }; - if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK) { - if (this.sessionDescriptionHandler && - this.sessionDescriptionHandler.hasDescription(incomingRequest.message.getHeader("Content-Type") || "")) { - this.hasAnswer = true; - this.sessionDescriptionHandler.setDescription(incomingRequest.message.body, this.sessionDescriptionHandlerOptions, this.modifiers).catch(function (e) { - _this.logger.warn(e); - _this.terminate({ - statusCode: "488", - reasonPhrase: "Bad Media Description" - }); - _this.failed(incomingRequest.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - _this.terminated(incomingRequest.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - throw e; - }).then(function () { return confirmSession(); }); - } - else { - confirmSession(); - } - } - }; - Session.prototype.receiveRequest = function (incomingRequest) { - switch (incomingRequest.message.method) { // TODO: This needs a default case - case Constants_1.C.BYE: - incomingRequest.accept(); - if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { - this.emit("bye", incomingRequest.message); - this.terminated(incomingRequest.message, Constants_1.C.BYE); - } - break; - case Constants_1.C.INVITE: - if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { - this.logger.log("re-INVITE received"); - this.receiveReinvite(incomingRequest); - } - break; - case Constants_1.C.INFO: - if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED || this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK) { - if (this.onInfo) { - return this.onInfo(incomingRequest.message); - } - var contentType = incomingRequest.message.getHeader("content-type"); - if (contentType) { - if (contentType.match(/^application\/dtmf-relay/i)) { - if (incomingRequest.message.body) { - var body = incomingRequest.message.body.split("\r\n", 2); - if (body.length === 2) { - var tone = void 0; - var duration = void 0; - var regTone = /^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/; - if (regTone.test(body[0])) { - tone = body[0].replace(regTone, "$2"); - } - var regDuration = /^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/; - if (regDuration.test(body[1])) { - duration = parseInt(body[1].replace(regDuration, "$2"), 10); - } - if (tone && duration) { - new DTMF_1.DTMF(this, tone, { duration: duration }).init_incoming(incomingRequest); - } - } - } - } - else { - incomingRequest.reject({ - statusCode: 415, - extraHeaders: ["Accept: application/dtmf-relay"] - }); - } - } - } - break; - case Constants_1.C.REFER: - if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { - this.logger.log("REFER received"); - this.referContext = new ReferContext_1.ReferServerContext(this.ua, incomingRequest, this.session); - if (this.listeners("referRequested").length) { - this.emit("referRequested", this.referContext); - } - else { - this.logger.log("No referRequested listeners, automatically accepting and following the refer"); - var options = { followRefer: true }; - if (this.passedOptions) { - options.inviteOptions = this.passedOptions; - } - this.referContext.accept(options, this.modifiers); - } - } - break; - case Constants_1.C.NOTIFY: - if (this.referContext && - this.referContext.type === Enums_1.TypeStrings.ReferClientContext && - incomingRequest.message.hasHeader("event") && - /^refer(;.*)?$/.test(incomingRequest.message.getHeader("event"))) { - this.referContext.receiveNotify(incomingRequest); - return; - } - incomingRequest.accept(); - this.emit("notify", incomingRequest.message); - break; - } - }; - // In dialog INVITE Reception - Session.prototype.receiveReinvite = function (incomingRequest) { - // TODO: Should probably check state of the session - var _this = this; - this.emit("reinvite", this, incomingRequest.message); - if (incomingRequest.message.hasHeader("P-Asserted-Identity")) { - this.assertedIdentity = - core_1.Grammar.nameAddrHeaderParse(incomingRequest.message.getHeader("P-Asserted-Identity")); - } - var promise; - if (!this.sessionDescriptionHandler) { - this.logger.warn("No SessionDescriptionHandler to reinvite"); - return; - } - if (incomingRequest.message.getHeader("Content-Length") === "0" && - !incomingRequest.message.getHeader("Content-Type")) { // Invite w/o SDP - promise = this.sessionDescriptionHandler.getDescription(this.sessionDescriptionHandlerOptions, this.modifiers); - } - else if (this.sessionDescriptionHandler.hasDescription(incomingRequest.message.getHeader("Content-Type") || "")) { - // Invite w/ SDP - promise = this.sessionDescriptionHandler.setDescription(incomingRequest.message.body, this.sessionDescriptionHandlerOptions, this.modifiers).then(this.sessionDescriptionHandler.getDescription.bind(this.sessionDescriptionHandler, this.sessionDescriptionHandlerOptions, this.modifiers)); - } - else { // Bad Packet (should never get hit) - incomingRequest.reject({ statusCode: 415 }); - this.emit("reinviteFailed", this); - return; - } - promise.catch(function (e) { - var statusCode; - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - statusCode = 500; - } - else if (e.type === Enums_1.TypeStrings.RenegotiationError) { - _this.emit("renegotiationError", e); - _this.logger.warn(e.toString()); - statusCode = 488; - } - else { - _this.logger.error(e); - statusCode = 488; - } - incomingRequest.reject({ statusCode: statusCode }); - _this.emit("reinviteFailed", _this); - // TODO: This could be better - throw e; - }).then(function (description) { - var extraHeaders = ["Contact: " + _this.contact]; - incomingRequest.accept({ - statusCode: 200, - extraHeaders: extraHeaders, - body: Utils_1.Utils.fromBodyObj(description) - }); - _this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK; - _this.emit("reinviteAccepted", _this); - }); - }; - Session.prototype.sendReinvite = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - if (this.pendingReinvite) { - this.logger.warn("Reinvite in progress. Please wait until complete, then try again."); - return; - } - if (!this.sessionDescriptionHandler) { - this.logger.warn("No SessionDescriptionHandler, can't reinvite.."); - return; - } - this.pendingReinvite = true; - options.modifiers = options.modifiers || []; - var extraHeaders = (options.extraHeaders || []).slice(); - extraHeaders.push("Contact: " + this.contact); - // this is UA.C.ALLOWED_METHODS, removed to get around circular dependency - extraHeaders.push("Allow: " + [ - "ACK", - "CANCEL", - "INVITE", - "MESSAGE", - "BYE", - "OPTIONS", - "INFO", - "NOTIFY", - "REFER" - ].toString()); - this.sessionDescriptionHandler.getDescription(options.sessionDescriptionHandlerOptions, options.modifiers) - .then(function (description) { - if (!_this.session) { - throw new Error("Session undefined."); - } - var delegate = { - onAccept: function (response) { - if (_this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - _this.logger.error("Received reinvite response, but in STATUS_TERMINATED"); - // TODO: Do we need to send a SIP response? - return; - } - if (!_this.pendingReinvite) { - _this.logger.error("Received reinvite response, but have no pending reinvite"); - // TODO: Do we need to send a SIP response? - return; - } - // FIXME: Why is this set here? - _this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; - // 17.1.1.1 - For each final response that is received at the client transaction, - // the client transaction sends an ACK, - _this.emit("ack", response.ack()); - _this.pendingReinvite = false; - // TODO: All of these timers should move into the Transaction layer - clearTimeout(_this.timers.invite2xxTimer); - if (!_this.sessionDescriptionHandler || - !_this.sessionDescriptionHandler.hasDescription(response.message.getHeader("Content-Type") || "")) { - _this.logger.error("2XX response received to re-invite but did not have a description"); - _this.emit("reinviteFailed", _this); - _this.emit("renegotiationError", new Exceptions_1.Exceptions.RenegotiationError("2XX response received to re-invite but did not have a description")); - return; - } - _this.sessionDescriptionHandler - .setDescription(response.message.body, _this.sessionDescriptionHandlerOptions, _this.modifiers) - .catch(function (e) { - _this.logger.error("Could not set the description in 2XX response"); - _this.logger.error(e); - _this.emit("reinviteFailed", _this); - _this.emit("renegotiationError", e); - _this.sendRequest(Constants_1.C.BYE, { - extraHeaders: ["Reason: " + Utils_1.Utils.getReasonHeaderValue(488, "Not Acceptable Here")] - }); - _this.terminated(undefined, Constants_1.C.causes.INCOMPATIBLE_SDP); - throw e; - }) - .then(function () { - _this.emit("reinviteAccepted", _this); - }); - }, - onProgress: function (response) { - return; - }, - onRedirect: function (response) { - // FIXME: Does ACK need to be sent? - _this.pendingReinvite = false; - _this.logger.log("Received a non 1XX or 2XX response to a re-invite"); - _this.emit("reinviteFailed", _this); - _this.emit("renegotiationError", new Exceptions_1.Exceptions.RenegotiationError("Invalid response to a re-invite")); - }, - onReject: function (response) { - // FIXME: Does ACK need to be sent? - _this.pendingReinvite = false; - _this.logger.log("Received a non 1XX or 2XX response to a re-invite"); - _this.emit("reinviteFailed", _this); - _this.emit("renegotiationError", new Exceptions_1.Exceptions.RenegotiationError("Invalid response to a re-invite")); - }, - onTrying: function (response) { - return; - } - }; - var requestOptions = { - extraHeaders: extraHeaders, - body: Utils_1.Utils.fromBodyObj(description) - }; - _this.session.invite(delegate, requestOptions); - }).catch(function (e) { - if (e.type === Enums_1.TypeStrings.RenegotiationError) { - _this.pendingReinvite = false; - _this.emit("renegotiationError", e); - _this.logger.warn("Renegotiation Error"); - _this.logger.warn(e.toString()); - throw e; - } - _this.logger.error("sessionDescriptionHandler error"); - _this.logger.error(e); - throw e; - }); - }; - Session.prototype.failed = function (response, cause) { - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return this; - } - this.emit("failed", response, cause); - return this; - }; - Session.prototype.rejected = function (response, cause) { - this.emit("rejected", response, cause); - return this; - }; - Session.prototype.canceled = function () { - if (this.sessionDescriptionHandler) { - this.sessionDescriptionHandler.close(); - } - this.emit("cancel"); - return this; - }; - Session.prototype.accepted = function (response, cause) { - if (!(response instanceof String)) { - cause = Utils_1.Utils.getReasonPhrase((response && response.statusCode) || 0, cause); - } - this.startTime = new Date(); - if (this.replacee) { - this.replacee.emit("replaced", this); - this.replacee.terminate(); - } - this.emit("accepted", response, cause); - return this; - }; - Session.prototype.terminated = function (message, cause) { - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return this; - } - this.endTime = new Date(); - this.close(); - this.emit("terminated", message, cause); - return this; - }; - Session.prototype.connecting = function (request) { - this.emit("connecting", { request: request }); - return this; - }; - Session.C = Enums_1.SessionStatus; - return Session; -}(events_1.EventEmitter)); -exports.Session = Session; -// tslint:disable-next-line:max-classes-per-file -var InviteServerContext = /** @class */ (function (_super) { - tslib_1.__extends(InviteServerContext, _super); - function InviteServerContext(ua, incomingInviteRequest) { - var _this = this; - if (!ua.configuration.sessionDescriptionHandlerFactory) { - ua.logger.warn("Can't build ISC without SDH Factory"); - throw new Error("ISC Constructor Failed"); - } - _this = _super.call(this, ua.configuration.sessionDescriptionHandlerFactory) || this; - _this._canceled = false; - _this.rseq = Math.floor(Math.random() * 10000); - _this.incomingRequest = incomingInviteRequest; - var request = incomingInviteRequest.message; - ServerContext_1.ServerContext.initializer(_this, ua, incomingInviteRequest); - _this.type = Enums_1.TypeStrings.InviteServerContext; - var contentDisp = request.parseHeader("Content-Disposition"); - if (contentDisp && contentDisp.type === "render") { - _this.renderbody = request.body; - _this.rendertype = request.getHeader("Content-Type"); - } - _this.status = Enums_1.SessionStatus.STATUS_INVITE_RECEIVED; - _this.fromTag = request.fromTag; - _this.id = request.callId + _this.fromTag; - _this.request = request; - _this.contact = _this.ua.contact.toString(); - _this.logger = ua.getLogger("sip.inviteservercontext", _this.id); - // Save the session into the ua sessions collection. - _this.ua.sessions[_this.id] = _this; - // Set 100rel if necessary - var set100rel = function (header, relSetting) { - if (request.hasHeader(header) && request.getHeader(header).toLowerCase().indexOf("100rel") >= 0) { - _this.rel100 = relSetting; - } - }; - set100rel("require", Constants_1.C.supported.REQUIRED); - set100rel("supported", Constants_1.C.supported.SUPPORTED); - // Set the toTag on the incoming request to the toTag which - // will be used in the response to the incoming request!!! - // FIXME: HACK: This is a hack to port an existing behavior. - // The behavior being ported appears to be a hack itself, - // so this is a hack to port a hack. At least one test spec - // relies on it (which is yet another hack). - _this.request.toTag = incomingInviteRequest.toTag; - _this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER; - // Set userNoAnswerTimer - _this.timers.userNoAnswerTimer = setTimeout(function () { - incomingInviteRequest.reject({ statusCode: 408 }); - _this.failed(request, Constants_1.C.causes.NO_ANSWER); - _this.terminated(request, Constants_1.C.causes.NO_ANSWER); - }, _this.ua.configuration.noAnswerTimeout || 60); - /* Set expiresTimer - * RFC3261 13.3.1 - */ - // Get the Expires header value if exists - if (request.hasHeader("expires")) { - var expires = Number(request.getHeader("expires") || 0) * 1000; - _this.timers.expiresTimer = setTimeout(function () { - if (_this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER) { - incomingInviteRequest.reject({ statusCode: 487 }); - _this.failed(request, Constants_1.C.causes.EXPIRES); - _this.terminated(request, Constants_1.C.causes.EXPIRES); - } - }, expires); - } - _this.errorListener = _this.onTransportError.bind(_this); - if (ua.transport) { - ua.transport.on("transportError", _this.errorListener); - } - return _this; - } - Object.defineProperty(InviteServerContext.prototype, "autoSendAnInitialProvisionalResponse", { - /** - * If true, a first provisional response after the 100 Trying - * will be sent automatically. This is false it the UAC required - * reliable provisional responses (100rel in Require header), - * otherwise it is true. The provisional is sent by calling - * `progress()` without any options. - * - * FIXME: TODO: It seems reasonable that the ISC user should - * be able to optionally disable this behavior. As the provisional - * is sent prior to the "invite" event being emitted, it's a known - * issue that the ISC user cannot register listeners or do any other - * setup prior to the call to `progress()`. As an example why this is - * an issue, setting `ua.configuration.rel100` to REQUIRED will result - * in an attempt by `progress()` to send a 183 with SDP produced by - * calling `getDescription()` on a session description handler, but - * the ISC user cannot perform any potentially required session description - * handler initialization (thus preventing the utilization of setting - * `ua.configuration.rel100` to REQUIRED). That begs the question of - * why this behavior is disabled when the UAC requires 100rel but not - * when the UAS requires 100rel? But ignoring that, it's just one example - * of a class of cases where the ISC user needs to do something prior - * to the first call to `progress()` and is unable to do so. - */ - get: function () { - return this.rel100 === Constants_1.C.supported.REQUIRED ? false : true; - }, - enumerable: true, - configurable: true - }); - // type hack for servercontext interface - InviteServerContext.prototype.reply = function (options) { - if (options === void 0) { options = {}; } - return this; - }; - // typing note: this was the only function using its super in ServerContext - // so the bottom half of this function is copied and paired down from that - InviteServerContext.prototype.reject = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - // Check Session Status - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - throw new Exceptions_1.Exceptions.InvalidStateError(this.status); - } - this.logger.log("rejecting RTCSession"); - var statusCode = options.statusCode || 480; - var reasonPhrase = Utils_1.Utils.getReasonPhrase(statusCode, options.reasonPhrase); - var extraHeaders = options.extraHeaders || []; - if (statusCode < 300 || statusCode > 699) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - var body = options.body ? core_1.fromBodyLegacy(options.body) : undefined; - // FIXME: Need to redirect to someplae - var response = statusCode < 400 ? - this.incomingRequest.redirect([], { statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }) : - this.incomingRequest.reject({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); - (["rejected", "failed"]).forEach(function (event) { - _this.emit(event, response.message, reasonPhrase); - }); - return this.terminated(); - }; - /** - * Accept the incoming INVITE request to start a Session. - * Replies to the INVITE request with a 200 Ok response. - * @param options Options bucket. - */ - InviteServerContext.prototype.accept = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - // FIXME: Need guard against calling more than once. - this._accept(options) - .then(function (_a) { - var message = _a.message, session = _a.session; - session.delegate = { - onAck: function (ackRequest) { return _this.onAck(ackRequest); }, - onAckTimeout: function () { return _this.onAckTimeout(); }, - onBye: function (byeRequest) { return _this.receiveRequest(byeRequest); }, - onInfo: function (infoRequest) { return _this.receiveRequest(infoRequest); }, - onInvite: function (inviteRequest) { return _this.receiveRequest(inviteRequest); }, - onNotify: function (notifyRequest) { return _this.receiveRequest(notifyRequest); }, - onPrack: function (prackRequest) { return _this.receiveRequest(prackRequest); }, - onRefer: function (referRequest) { return _this.receiveRequest(referRequest); } - }; - _this.session = session; - _this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK; - _this.accepted(message, Utils_1.Utils.getReasonPhrase(200)); - }) - .catch(function (error) { - _this.onContextError(error); - // FIXME: Assuming error due to async race on CANCEL and eating error. - if (!_this._canceled) { - throw error; - } - }); - return this; - }; - /** - * Report progress to the the caller. - * Replies to the INVITE request with a 1xx provisional response. - * @param options Options bucket. - */ - InviteServerContext.prototype.progress = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - // Ported - var statusCode = options.statusCode || 180; - if (statusCode < 100 || statusCode > 199) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - // Ported - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - this.logger.warn("Unexpected call for progress while terminated, ignoring"); - return this; - } - // Added - if (this.status === Enums_1.SessionStatus.STATUS_ANSWERED) { - this.logger.warn("Unexpected call for progress while answered, ignoring"); - return this; - } - // Added - if (this.status === Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK) { - this.logger.warn("Unexpected call for progress while answered (waiting for prack), ignoring"); - return this; - } - // After the first reliable provisional response for a request has been - // acknowledged, the UAS MAY send additional reliable provisional - // responses. The UAS MUST NOT send a second reliable provisional - // response until the first is acknowledged. After the first, it is - // RECOMMENDED that the UAS not send an additional reliable provisional - // response until the previous is acknowledged. The first reliable - // provisional response receives special treatment because it conveys - // the initial sequence number. If additional reliable provisional - // responses were sent before the first was acknowledged, the UAS could - // not be certain these were received in order. - // https://tools.ietf.org/html/rfc3262#section-3 - if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK) { - this.logger.warn("Unexpected call for progress while waiting for prack, ignoring"); - return this; - } - // Ported - if (options.statusCode === 100) { - try { - this.incomingRequest.trying(); - } - catch (error) { - this.onContextError(error); - // FIXME: Assuming error due to async race on CANCEL and eating error. - if (!this._canceled) { - throw error; - } - } - return this; - } - // Standard provisional response. - if (!(this.rel100 === Constants_1.C.supported.REQUIRED) && - !(this.rel100 === Constants_1.C.supported.SUPPORTED && options.rel100) && - !(this.rel100 === Constants_1.C.supported.SUPPORTED && this.ua.configuration.rel100 === Constants_1.C.supported.REQUIRED)) { - this._progress(options) - .catch(function (error) { - _this.onContextError(error); - // FIXME: Assuming error due to async race on CANCEL and eating error. - if (!_this._canceled) { - throw error; - } - }); - return this; - } - // Reliable provisional response. - this._reliableProgressWaitForPrack(options) - .catch(function (error) { - _this.onContextError(error); - // FIXME: Assuming error due to async race on CANCEL and eating error. - if (!_this._canceled) { - throw error; - } - }); - return this; - }; - /** - * Reject an unaccepted incoming INVITE request or send BYE if established session. - * @param options Options bucket. FIXME: This options bucket needs to be typed. - */ - InviteServerContext.prototype.terminate = function (options) { - // The caller's UA MAY send a BYE for either confirmed or early dialogs, - // and the callee's UA MAY send a BYE on confirmed dialogs, but MUST NOT - // send a BYE on early dialogs. However, the callee's UA MUST NOT send a - // BYE on a confirmed dialog until it has received an ACK for its 2xx - // response or until the server transaction times out. - // https://tools.ietf.org/html/rfc3261#section-15 - var _this = this; - if (options === void 0) { options = {}; } - // We don't yet have a dialog, so reject request. - if (!this.session) { - this.reject(options); - return this; - } - switch (this.session.sessionState) { - case core_1.SessionState.Initial: - this.reject(options); - return this; - case core_1.SessionState.Early: - this.reject(options); - return this; - case core_1.SessionState.AckWait: - this.session.delegate = { - // When ACK shows up, say BYE. - onAck: function () { - _this.sendRequest(Constants_1.C.BYE, options); - }, - // Or the server transaction times out before the ACK arrives. - onAckTimeout: function () { - _this.sendRequest(Constants_1.C.BYE, options); - } - }; - // Ported - this.emit("bye", this.request); - this.terminated(); - return this; - case core_1.SessionState.Confirmed: - this.bye(options); - return this; - case core_1.SessionState.Terminated: - return this; - default: - return this; - } - }; - InviteServerContext.prototype.onCancel = function (message) { - if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER || - this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK || - this.status === Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK || - this.status === Enums_1.SessionStatus.STATUS_EARLY_MEDIA || - this.status === Enums_1.SessionStatus.STATUS_ANSWERED) { - this.status = Enums_1.SessionStatus.STATUS_CANCELED; - this.incomingRequest.reject({ statusCode: 487 }); - this.canceled(); - this.rejected(message, Constants_1.C.causes.CANCELED); - this.failed(message, Constants_1.C.causes.CANCELED); - this.terminated(message, Constants_1.C.causes.CANCELED); - } - }; - InviteServerContext.prototype.receiveRequest = function (incomingRequest) { - var _this = this; - switch (incomingRequest.message.method) { - case Constants_1.C.PRACK: - if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK || - this.status === Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK) { - if (!this.hasAnswer) { - this.sessionDescriptionHandler = this.setupSessionDescriptionHandler(); - this.emit("SessionDescriptionHandler-created", this.sessionDescriptionHandler); - if (this.sessionDescriptionHandler.hasDescription(incomingRequest.message.getHeader("Content-Type") || "")) { - this.hasAnswer = true; - this.sessionDescriptionHandler.setDescription(incomingRequest.message.body, this.sessionDescriptionHandlerOptions, this.modifiers).then(function () { - clearTimeout(_this.timers.rel1xxTimer); - clearTimeout(_this.timers.prackTimer); - incomingRequest.accept(); - if (_this.status === Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK) { - _this.status = Enums_1.SessionStatus.STATUS_EARLY_MEDIA; - _this.accept(); - } - _this.status = Enums_1.SessionStatus.STATUS_EARLY_MEDIA; - }, function (e) { - _this.logger.warn(e); - _this.terminate({ - statusCode: "488", - reasonPhrase: "Bad Media Description" - }); - _this.failed(incomingRequest.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - _this.terminated(incomingRequest.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - }); - } - else { - this.terminate({ - statusCode: "488", - reasonPhrase: "Bad Media Description" - }); - this.failed(incomingRequest.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - this.terminated(incomingRequest.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - } - } - else { - clearTimeout(this.timers.rel1xxTimer); - clearTimeout(this.timers.prackTimer); - incomingRequest.accept(); - if (this.status === Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK) { - this.status = Enums_1.SessionStatus.STATUS_EARLY_MEDIA; - this.accept(); - } - this.status = Enums_1.SessionStatus.STATUS_EARLY_MEDIA; - } - } - else if (this.status === Enums_1.SessionStatus.STATUS_EARLY_MEDIA) { - incomingRequest.accept(); - } - break; - default: - _super.prototype.receiveRequest.call(this, incomingRequest); - break; - } - }; - // Internal Function to setup the handler consistently - InviteServerContext.prototype.setupSessionDescriptionHandler = function () { - if (this.sessionDescriptionHandler) { - return this.sessionDescriptionHandler; - } - return this.sessionDescriptionHandlerFactory(this, this.ua.configuration.sessionDescriptionHandlerFactoryOptions); - }; - InviteServerContext.prototype.generateResponseOfferAnswer = function (options) { - if (!this.session) { - var body = core_1.getBody(this.incomingRequest.message); - if (!body || body.contentDisposition !== "session") { - return this.getOffer(options); - } - else { - return this.setOfferAndGetAnswer(body, options); - } - } - else { - switch (this.session.signalingState) { - case core_1.SignalingState.Initial: - return this.getOffer(options); - case core_1.SignalingState.Stable: - return Promise.resolve(undefined); - case core_1.SignalingState.HaveLocalOffer: - // o Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - return Promise.resolve(undefined); - case core_1.SignalingState.HaveRemoteOffer: - if (!this.session.offer) { - throw new Error("Session offer undefined"); - } - return this.setOfferAndGetAnswer(this.session.offer, options); - case core_1.SignalingState.Closed: - throw new Error("Invalid signaling state " + this.session.signalingState + "."); - default: - throw new Error("Invalid signaling state " + this.session.signalingState + "."); - } - } - }; - InviteServerContext.prototype.handlePrackOfferAnswer = function (request, options) { - if (!this.session) { - throw new Error("Session undefined."); - } - // If the PRACK doesn't have an offer/answer, nothing to be done. - var body = core_1.getBody(request.message); - if (!body || body.contentDisposition !== "session") { - return Promise.resolve(undefined); - } - // If the UAC receives a reliable provisional response with an offer - // (this would occur if the UAC sent an INVITE without an offer, in - // which case the first reliable provisional response will contain the - // offer), it MUST generate an answer in the PRACK. If the UAC receives - // a reliable provisional response with an answer, it MAY generate an - // additional offer in the PRACK. If the UAS receives a PRACK with an - // offer, it MUST place the answer in the 2xx to the PRACK. - // https://tools.ietf.org/html/rfc3262#section-5 - switch (this.session.signalingState) { - case core_1.SignalingState.Initial: - // State should never be reached as first reliable provisional response must have answer/offer. - throw new Error("Invalid signaling state " + this.session.signalingState + "."); - case core_1.SignalingState.Stable: - // Receved answer. - return this.setAnswer(body, options).then(function () { return undefined; }); - case core_1.SignalingState.HaveLocalOffer: - // State should never be reached as local offer would be answered by this PRACK - throw new Error("Invalid signaling state " + this.session.signalingState + "."); - case core_1.SignalingState.HaveRemoteOffer: - // Receved offer, generate answer. - return this.setOfferAndGetAnswer(body, options); - case core_1.SignalingState.Closed: - throw new Error("Invalid signaling state " + this.session.signalingState + "."); - default: - throw new Error("Invalid signaling state " + this.session.signalingState + "."); - } - }; - /** - * Called when session canceled. - */ - InviteServerContext.prototype.canceled = function () { - this._canceled = true; - return _super.prototype.canceled.call(this); - }; - /** - * Called when session terminated. - * Using it here just for the PRACK timeout. - */ - InviteServerContext.prototype.terminated = function (message, cause) { - this.prackNeverArrived(); - return _super.prototype.terminated.call(this, message, cause); - }; - /** - * A version of `accept` which resolves a session when the 200 Ok response is sent. - * @param options Options bucket. - * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. - * @throws {TransactionStateError} The transaction state does not allow for `accept()` to be called. - * Note that the transaction state can change while this call is in progress. - */ - InviteServerContext.prototype._accept = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - // FIXME: Ported - callback for in dialog INFO requests. - // Turns out accept() can be called more than once if we are waiting - // for a PRACK in which case "options" get completely tossed away. - // So this is broken in that case (and potentially other uses of options). - // Tempted to just try to fix it now, but leaving it broken for the moment. - this.onInfo = options.onInfo; - // The UAS MAY send a final response to the initial request before - // having received PRACKs for all unacknowledged reliable provisional - // responses, unless the final response is 2xx and any of the - // unacknowledged reliable provisional responses contained a session - // description. In that case, it MUST NOT send a final response until - // those provisional responses are acknowledged. If the UAS does send a - // final response when reliable responses are still unacknowledged, it - // SHOULD NOT continue to retransmit the unacknowledged reliable - // provisional responses, but it MUST be prepared to process PRACK - // requests for those outstanding responses. A UAS MUST NOT send new - // reliable provisional responses (as opposed to retransmissions of - // unacknowledged ones) after sending a final response to a request. - // https://tools.ietf.org/html/rfc3262#section-3 - if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK) { - this.status = Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK; - return this.waitForArrivalOfPrack() - .then(function () { - _this.status = Enums_1.SessionStatus.STATUS_ANSWERED; - clearTimeout(_this.timers.userNoAnswerTimer); // Ported - }) - .then(function () { return _this.generateResponseOfferAnswer(options); }) - .then(function (body) { return _this.incomingRequest.accept({ statusCode: 200, body: body }); }); - } - // Ported - if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER) { - this.status = Enums_1.SessionStatus.STATUS_ANSWERED; - } - else { - return Promise.reject(new Exceptions_1.Exceptions.InvalidStateError(this.status)); - } - this.status = Enums_1.SessionStatus.STATUS_ANSWERED; - clearTimeout(this.timers.userNoAnswerTimer); // Ported - return this.generateResponseOfferAnswer(options) - .then(function (body) { return _this.incomingRequest.accept({ statusCode: 200, body: body }); }); - }; - /** - * A version of `progress` which resolves when the provisional response is sent. - * @param options Options bucket. - * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. - * @throws {TransactionStateError} The transaction state does not allow for `progress()` to be called. - * Note that the transaction state can change while this call is in progress. - */ - InviteServerContext.prototype._progress = function (options) { - if (options === void 0) { options = {}; } - // Ported - var statusCode = options.statusCode || 180; - var reasonPhrase = options.reasonPhrase; - var extraHeaders = (options.extraHeaders || []).slice(); - var body = options.body ? core_1.fromBodyLegacy(options.body) : undefined; - // The 183 (Session Progress) response is used to convey information - // about the progress of the call that is not otherwise classified. The - // Reason-Phrase, header fields, or message body MAY be used to convey - // more details about the call progress. - // https://tools.ietf.org/html/rfc3261#section-21.1.5 - // It is the de facto industry standard to utilize 183 with SDP to provide "early media". - // While it is unlikely someone would want to send a 183 without SDP, so it should be an option. - if (statusCode === 183 && !body) { - return this._progressWithSDP(options); - } - try { - var progressResponse = this.incomingRequest.progress({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); - this.emit("progress", progressResponse.message, reasonPhrase); // Ported - this.session = progressResponse.session; - return Promise.resolve(progressResponse); - } - catch (error) { - return Promise.reject(error); - } - }; - /** - * A version of `progress` which resolves when the provisional response with sdp is sent. - * @param options Options bucket. - * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. - * @throws {TransactionStateError} The transaction state does not allow for `progress()` to be called. - * Note that the transaction state can change while this call is in progress. - */ - InviteServerContext.prototype._progressWithSDP = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - var statusCode = options.statusCode || 183; - var reasonPhrase = options.reasonPhrase; - var extraHeaders = (options.extraHeaders || []).slice(); - // Get an offer/answer and send a reply. - return this.generateResponseOfferAnswer(options) - .then(function (body) { return _this.incomingRequest.progress({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); }) - .then(function (progressResponse) { - _this.emit("progress", progressResponse.message, reasonPhrase); // Ported - _this.session = progressResponse.session; - return progressResponse; - }); - }; - /** - * A version of `progress` which resolves when the reliable provisional response is sent. - * @param options Options bucket. - * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. - * @throws {TransactionStateError} The transaction state does not allow for `progress()` to be called. - * Note that the transaction state can change while this call is in progress. - */ - InviteServerContext.prototype._reliableProgress = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - var statusCode = options.statusCode || 183; - var reasonPhrase = options.reasonPhrase; - var extraHeaders = (options.extraHeaders || []).slice(); - extraHeaders.push("Require: 100rel"); - extraHeaders.push("RSeq: " + Math.floor(Math.random() * 10000)); - // Get an offer/answer and send a reply. - return this.generateResponseOfferAnswer(options) - .then(function (body) { return _this.incomingRequest.progress({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); }) - .then(function (progressResponse) { - _this.emit("progress", progressResponse.message, reasonPhrase); // Ported - _this.session = progressResponse.session; - return progressResponse; - }); - }; - /** - * A version of `progress` which resolves when the reliable provisional response is acknowledged. - * @param options Options bucket. - * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. - * @throws {TransactionStateError} The transaction state does not allow for `progress()` to be called. - * Note that the transaction state can change while this call is in progress. - */ - InviteServerContext.prototype._reliableProgressWaitForPrack = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - var statusCode = options.statusCode || 183; - var reasonPhrase = options.reasonPhrase; - var extraHeaders = (options.extraHeaders || []).slice(); - extraHeaders.push("Require: 100rel"); - extraHeaders.push("RSeq: " + this.rseq++); - var body; - // Ported - set status. - this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK; - return new Promise(function (resolve, reject) { - var waitingForPrack = true; - return _this.generateResponseOfferAnswer(options) - .then(function (offerAnswer) { - body = offerAnswer; - return _this.incomingRequest.progress({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); - }) - .then(function (progressResponse) { - _this.emit("progress", progressResponse.message, reasonPhrase); // Ported - _this.session = progressResponse.session; - var prackRequest; - var prackResponse; - progressResponse.session.delegate = { - onPrack: function (request) { - prackRequest = request; - clearTimeout(prackWaitTimeoutTimer); - clearTimeout(rel1xxRetransmissionTimer); - if (!waitingForPrack) { - return; - } - waitingForPrack = false; - _this.handlePrackOfferAnswer(prackRequest, options) - .then(function (prackResponseBody) { - try { - prackResponse = prackRequest.accept({ statusCode: 200, body: prackResponseBody }); - // Ported - set status. - if (_this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK) { - _this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER; - } - _this.prackArrived(); - resolve({ prackRequest: prackRequest, prackResponse: prackResponse, progressResponse: progressResponse }); - } - catch (error) { - reject(error); - } - }); - } - }; - // https://tools.ietf.org/html/rfc3262#section-3 - var prackWaitTimeout = function () { - if (!waitingForPrack) { - return; - } - waitingForPrack = false; - _this.logger.warn("No PRACK received, rejecting INVITE."); - clearTimeout(rel1xxRetransmissionTimer); - try { - _this.incomingRequest.reject({ statusCode: 504 }); - _this.terminated(undefined, Constants_1.C.causes.NO_PRACK); - reject(new Exceptions_1.Exceptions.TerminatedSessionError()); - } - catch (error) { - reject(error); - } - }; - var prackWaitTimeoutTimer = setTimeout(prackWaitTimeout, core_1.Timers.T1 * 64); - // https://tools.ietf.org/html/rfc3262#section-3 - var rel1xxRetransmission = function () { - try { - _this.incomingRequest.progress({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); - } - catch (error) { - waitingForPrack = false; - reject(error); - return; - } - rel1xxRetransmissionTimer = setTimeout(rel1xxRetransmission, timeout *= 2); - }; - var timeout = core_1.Timers.T1; - var rel1xxRetransmissionTimer = setTimeout(rel1xxRetransmission, timeout); - }); - }); - }; - /** - * Callback for when ACK for a 2xx response is never received. - * @param session Session the ACK never arrived for - */ - InviteServerContext.prototype.onAckTimeout = function () { - if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK) { - this.logger.log("no ACK received for an extended period of time, terminating the call"); - if (!this.session) { - throw new Error("Session undefined."); - } - this.session.bye(); - this.terminated(undefined, Constants_1.C.causes.NO_ACK); - } - }; - /** - * FIXME: TODO: The current library interface presents async methods without a - * proper async error handling mechanism. Arguably a promise based interface - * would be an improvement over the pattern of returning `this`. The approach has - * been generally along the lines of log a error and terminate. - */ - InviteServerContext.prototype.onContextError = function (error) { - var statusCode = 480; - if (error instanceof core_1.Exception) { // There might be interest in catching these Exceptions. - if (error instanceof Exceptions_1.Exceptions.SessionDescriptionHandlerError) { - this.logger.error(error.message); - if (error.error) { - this.logger.error(error.error); - } - } - else if (error instanceof Exceptions_1.Exceptions.TerminatedSessionError) { - // PRACK never arrived, so we timed out waiting for it. - this.logger.warn("Incoming session terminated while waiting for PRACK."); - } - else if (error instanceof Exceptions_1.Exceptions.UnsupportedSessionDescriptionContentTypeError) { - statusCode = 415; - } - else if (error instanceof core_1.Exception) { - this.logger.error(error.message); - } - } - else if (error instanceof Error) { // Other Errors hould go uncaught. - this.logger.error(error.message); - } - else { - // We don't actually know what a session description handler implementation might throw - // our way, so as a last resort, just assume we are getting an "any" and log it. - this.logger.error("An error occurred in the session description handler."); - this.logger.error(error); - } - try { - this.incomingRequest.reject({ statusCode: statusCode }); // "Temporarily Unavailable" - this.failed(this.incomingRequest.message, error.message); - this.terminated(this.incomingRequest.message, error.message); - } - catch (error) { - return; - } - }; - InviteServerContext.prototype.prackArrived = function () { - if (this.waitingForPrackResolve) { - this.waitingForPrackResolve(); - } - this.waitingForPrackPromise = undefined; - this.waitingForPrackResolve = undefined; - this.waitingForPrackReject = undefined; - }; - InviteServerContext.prototype.prackNeverArrived = function () { - if (this.waitingForPrackReject) { - this.waitingForPrackReject(new Exceptions_1.Exceptions.TerminatedSessionError()); - } - this.waitingForPrackPromise = undefined; - this.waitingForPrackResolve = undefined; - this.waitingForPrackReject = undefined; - }; - /** - * @throws {Exceptions.TerminatedSessionError} The session terminated before being accepted (i.e. cancel arrived). - */ - InviteServerContext.prototype.waitForArrivalOfPrack = function () { - var _this = this; - if (this.waitingForPrackPromise) { - throw new Error("Already waiting for PRACK"); - } - this.waitingForPrackPromise = new Promise(function (resolve, reject) { - _this.waitingForPrackResolve = resolve; - _this.waitingForPrackReject = reject; - }); - return this.waitingForPrackPromise; - }; - InviteServerContext.prototype.getOffer = function (options) { - this.hasOffer = true; - var sdh = this.getSessionDescriptionHandler(); - return sdh - .getDescription(options.sessionDescriptionHandlerOptions, options.modifiers) - .then(function (bodyObj) { return Utils_1.Utils.fromBodyObj(bodyObj); }); - }; - InviteServerContext.prototype.setAnswer = function (answer, options) { - this.hasAnswer = true; - var sdh = this.getSessionDescriptionHandler(); - if (!sdh.hasDescription(answer.contentType)) { - return Promise.reject(new Exceptions_1.Exceptions.UnsupportedSessionDescriptionContentTypeError()); - } - return sdh - .setDescription(answer.content, options.sessionDescriptionHandlerOptions, options.modifiers); - }; - InviteServerContext.prototype.setOfferAndGetAnswer = function (offer, options) { - this.hasOffer = true; - this.hasAnswer = true; - var sdh = this.getSessionDescriptionHandler(); - if (!sdh.hasDescription(offer.contentType)) { - return Promise.reject(new Exceptions_1.Exceptions.UnsupportedSessionDescriptionContentTypeError()); - } - return sdh - .setDescription(offer.content, options.sessionDescriptionHandlerOptions, options.modifiers) - .then(function () { return sdh.getDescription(options.sessionDescriptionHandlerOptions, options.modifiers); }) - .then(function (bodyObj) { return Utils_1.Utils.fromBodyObj(bodyObj); }); - }; - InviteServerContext.prototype.getSessionDescriptionHandler = function () { - // Create our session description handler if not already done so... - var sdh = this.sessionDescriptionHandler = this.setupSessionDescriptionHandler(); - // FIXME: Ported - this can get emitted multiple times even when only created once... don't we care? - this.emit("SessionDescriptionHandler-created", this.sessionDescriptionHandler); - // Return. - return sdh; - }; - return InviteServerContext; -}(Session)); -exports.InviteServerContext = InviteServerContext; -// tslint:disable-next-line:max-classes-per-file -var InviteClientContext = /** @class */ (function (_super) { - tslib_1.__extends(InviteClientContext, _super); - function InviteClientContext(ua, target, options, modifiers) { - if (options === void 0) { options = {}; } - if (modifiers === void 0) { modifiers = []; } - var _this = this; - if (!ua.configuration.sessionDescriptionHandlerFactory) { - ua.logger.warn("Can't build ISC without SDH Factory"); - throw new Error("ICC Constructor Failed"); - } - options.params = options.params || {}; - var anonymous = options.anonymous || false; - var fromTag = Utils_1.Utils.newTag(); - options.params.fromTag = fromTag; - /* Do not add ;ob in initial forming dialog requests if the registration over - * the current connection got a GRUU URI. - */ - var contact = ua.contact.toString({ - anonymous: anonymous, - outbound: anonymous ? !ua.contact.tempGruu : !ua.contact.pubGruu - }); - var extraHeaders = (options.extraHeaders || []).slice(); - if (anonymous && ua.configuration.uri) { - options.params.fromDisplayName = "Anonymous"; - options.params.fromUri = "sip:anonymous@anonymous.invalid"; - extraHeaders.push("P-Preferred-Identity: " + ua.configuration.uri.toString()); - extraHeaders.push("Privacy: id"); - } - extraHeaders.push("Contact: " + contact); - // this is UA.C.ALLOWED_METHODS, removed to get around circular dependency - extraHeaders.push("Allow: " + [ - "ACK", - "CANCEL", - "INVITE", - "MESSAGE", - "BYE", - "OPTIONS", - "INFO", - "NOTIFY", - "REFER" - ].toString()); - if (ua.configuration.rel100 === Constants_1.C.supported.REQUIRED) { - extraHeaders.push("Require: 100rel"); - } - if (ua.configuration.replaces === Constants_1.C.supported.REQUIRED) { - extraHeaders.push("Require: replaces"); - } - options.extraHeaders = extraHeaders; - _this = _super.call(this, ua.configuration.sessionDescriptionHandlerFactory) || this; - ClientContext_1.ClientContext.initializer(_this, ua, Constants_1.C.INVITE, target, options); - _this.earlyMediaSessionDescriptionHandlers = new Map(); - _this.type = Enums_1.TypeStrings.InviteClientContext; - _this.passedOptions = options; // Save for later to use with refer - _this.sessionDescriptionHandlerOptions = options.sessionDescriptionHandlerOptions || {}; - _this.modifiers = modifiers; - _this.inviteWithoutSdp = options.inviteWithoutSdp || false; - // Set anonymous property - _this.anonymous = options.anonymous || false; - // Custom data to be sent either in INVITE or in ACK - _this.renderbody = options.renderbody || undefined; - _this.rendertype = options.rendertype || "text/plain"; - // Session parameter initialization - _this.fromTag = fromTag; - _this.contact = contact; - // Check Session Status - if (_this.status !== Enums_1.SessionStatus.STATUS_NULL) { - throw new Exceptions_1.Exceptions.InvalidStateError(_this.status); - } - // OutgoingSession specific parameters - _this.isCanceled = false; - _this.received100 = false; - _this.method = Constants_1.C.INVITE; - _this.logger = ua.getLogger("sip.inviteclientcontext"); - ua.applicants[_this.toString()] = _this; - _this.id = _this.request.callId + _this.fromTag; - _this.onInfo = options.onInfo; - _this.errorListener = _this.onTransportError.bind(_this); - if (ua.transport) { - ua.transport.on("transportError", _this.errorListener); - } - return _this; - } - InviteClientContext.prototype.receiveResponse = function (response) { - throw new Error("Unimplemented."); - }; - // hack for getting around ClientContext interface - InviteClientContext.prototype.send = function () { - this.sendInvite(); - return this; - }; - InviteClientContext.prototype.invite = function () { - var _this = this; - // Save the session into the ua sessions collection. - // Note: placing in constructor breaks call to request.cancel on close... User does not need this anyway - this.ua.sessions[this.id] = this; - // This should allow the function to return so that listeners can be set up for these events - Promise.resolve().then(function () { - // FIXME: There is a race condition where cancel (or terminate) can be called synchronously after invite. - if (_this.isCanceled || _this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return; - } - if (_this.inviteWithoutSdp) { - // just send an invite with no sdp... - if (_this.renderbody && _this.rendertype) { - _this.request.body = { - body: _this.renderbody, - contentType: _this.rendertype - }; - } - _this.status = Enums_1.SessionStatus.STATUS_INVITE_SENT; - _this.send(); - } - else { - // Initialize Media Session - _this.sessionDescriptionHandler = _this.sessionDescriptionHandlerFactory(_this, _this.ua.configuration.sessionDescriptionHandlerFactoryOptions || {}); - _this.emit("SessionDescriptionHandler-created", _this.sessionDescriptionHandler); - _this.sessionDescriptionHandler.getDescription(_this.sessionDescriptionHandlerOptions, _this.modifiers) - .then(function (description) { - // FIXME: There is a race condition where cancel (or terminate) can be called (a)synchronously after invite. - if (_this.isCanceled || _this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return; - } - _this.hasOffer = true; - _this.request.body = description; - _this.status = Enums_1.SessionStatus.STATUS_INVITE_SENT; - _this.send(); - }, function (err) { - if (err.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - _this.logger.log(err.message); - if (err.error) { - _this.logger.log(err.error); - } - } - if (_this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return; - } - _this.failed(undefined, Constants_1.C.causes.WEBRTC_ERROR); - _this.terminated(undefined, Constants_1.C.causes.WEBRTC_ERROR); - }); - } - }); - return this; - }; - InviteClientContext.prototype.cancel = function (options) { - if (options === void 0) { options = {}; } - // Check Session Status - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED || this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { - throw new Exceptions_1.Exceptions.InvalidStateError(this.status); - } - if (this.isCanceled) { - throw new Exceptions_1.Exceptions.InvalidStateError(Enums_1.SessionStatus.STATUS_CANCELED); - } - this.isCanceled = true; - this.logger.log("Canceling session"); - var cancelReason = Utils_1.Utils.getCancelReason(options.statusCode, options.reasonPhrase); - options.extraHeaders = (options.extraHeaders || []).slice(); - if (this.outgoingInviteRequest) { - this.logger.warn("Canceling session before it was created"); - this.outgoingInviteRequest.cancel(cancelReason, options); - } - return this.canceled(); - }; - InviteClientContext.prototype.terminate = function (options) { - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return this; - } - if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK || this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { - this.bye(options); - } - else { - this.cancel(options); - } - return this; - }; - /** - * 13.2.1 Creating the Initial INVITE - * - * Since the initial INVITE represents a request outside of a dialog, - * its construction follows the procedures of Section 8.1.1. Additional - * processing is required for the specific case of INVITE. - * - * An Allow header field (Section 20.5) SHOULD be present in the INVITE. - * It indicates what methods can be invoked within a dialog, on the UA - * sending the INVITE, for the duration of the dialog. For example, a - * UA capable of receiving INFO requests within a dialog [34] SHOULD - * include an Allow header field listing the INFO method. - * - * A Supported header field (Section 20.37) SHOULD be present in the - * INVITE. It enumerates all the extensions understood by the UAC. - * - * An Accept (Section 20.1) header field MAY be present in the INVITE. - * It indicates which Content-Types are acceptable to the UA, in both - * the response received by it, and in any subsequent requests sent to - * it within dialogs established by the INVITE. The Accept header field - * is especially useful for indicating support of various session - * description formats. - * - * The UAC MAY add an Expires header field (Section 20.19) to limit the - * validity of the invitation. If the time indicated in the Expires - * header field is reached and no final answer for the INVITE has been - * received, the UAC core SHOULD generate a CANCEL request for the - * INVITE, as per Section 9. - * - * A UAC MAY also find it useful to add, among others, Subject (Section - * 20.36), Organization (Section 20.25) and User-Agent (Section 20.41) - * header fields. They all contain information related to the INVITE. - * - * The UAC MAY choose to add a message body to the INVITE. Section - * 8.1.1.10 deals with how to construct the header fields -- Content- - * Type among others -- needed to describe the message body. - * - * https://tools.ietf.org/html/rfc3261#section-13.2.1 - */ - InviteClientContext.prototype.sendInvite = function () { - // There are special rules for message bodies that contain a session - // description - their corresponding Content-Disposition is "session". - // SIP uses an offer/answer model where one UA sends a session - // description, called the offer, which contains a proposed description - // of the session. The offer indicates the desired communications means - // (audio, video, games), parameters of those means (such as codec - // types) and addresses for receiving media from the answerer. The - // other UA responds with another session description, called the - // answer, which indicates which communications means are accepted, the - // parameters that apply to those means, and addresses for receiving - // media from the offerer. An offer/answer exchange is within the - // context of a dialog, so that if a SIP INVITE results in multiple - // dialogs, each is a separate offer/answer exchange. The offer/answer - // model defines restrictions on when offers and answers can be made - // (for example, you cannot make a new offer while one is in progress). - // This results in restrictions on where the offers and answers can - // appear in SIP messages. In this specification, offers and answers - // can only appear in INVITE requests and responses, and ACK. The usage - // of offers and answers is further restricted. For the initial INVITE - // transaction, the rules are: - // - // o The initial offer MUST be in either an INVITE or, if not there, - // in the first reliable non-failure message from the UAS back to - // the UAC. In this specification, that is the final 2xx - // response. - // - // o If the initial offer is in an INVITE, the answer MUST be in a - // reliable non-failure message from UAS back to UAC which is - // correlated to that INVITE. For this specification, that is - // only the final 2xx response to that INVITE. That same exact - // answer MAY also be placed in any provisional responses sent - // prior to the answer. The UAC MUST treat the first session - // description it receives as the answer, and MUST ignore any - // session descriptions in subsequent responses to the initial - // INVITE. - // - // o If the initial offer is in the first reliable non-failure - // message from the UAS back to UAC, the answer MUST be in the - // acknowledgement for that message (in this specification, ACK - // for a 2xx response). - // - // o After having sent or received an answer to the first offer, the - // UAC MAY generate subsequent offers in requests based on rules - // specified for that method, but only if it has received answers - // to any previous offers, and has not sent any offers to which it - // hasn't gotten an answer. - // - // o Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - var _this = this; - // 5 The Offer/Answer Model and PRACK - // - // RFC 3261 describes guidelines for the sets of messages in which - // offers and answers [3] can appear. Based on those guidelines, this - // extension provides additional opportunities for offer/answer - // exchanges. - // If the INVITE contained an offer, the UAS MAY generate an answer in a - // reliable provisional response (assuming these are supported by the - // UAC). That results in the establishment of the session before - // completion of the call. Similarly, if a reliable provisional - // response is the first reliable message sent back to the UAC, and the - // INVITE did not contain an offer, one MUST appear in that reliable - // provisional response. - // If the UAC receives a reliable provisional response with an offer - // (this would occur if the UAC sent an INVITE without an offer, in - // which case the first reliable provisional response will contain the - // offer), it MUST generate an answer in the PRACK. If the UAC receives - // a reliable provisional response with an answer, it MAY generate an - // additional offer in the PRACK. If the UAS receives a PRACK with an - // offer, it MUST place the answer in the 2xx to the PRACK. - // Once an answer has been sent or received, the UA SHOULD establish the - // session based on the parameters of the offer and answer, even if the - // original INVITE itself has not been responded to. - // If the UAS had placed a session description in any reliable - // provisional response that is unacknowledged when the INVITE is - // accepted, the UAS MUST delay sending the 2xx until the provisional - // response is acknowledged. Otherwise, the reliability of the 1xx - // cannot be guaranteed, and reliability is needed for proper operation - // of the offer/answer exchange. - // All user agents that support this extension MUST support all - // offer/answer exchanges that are possible based on the rules in - // Section 13.2 of RFC 3261, based on the existence of INVITE and PRACK - // as requests, and 2xx and reliable 1xx as non-failure reliable - // responses. - // - // https://tools.ietf.org/html/rfc3262#section-5 - //// - // The Offer/Answer Model Implementation - // - // The offer/answer model is straight forward, but one MUST READ the specifications... - // - // 13.2.1 Creating the Initial INVITE (paragraph 8 in particular) - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // - // 5 The Offer/Answer Model and PRACK - // https://tools.ietf.org/html/rfc3262#section-5 - // - // Session Initiation Protocol (SIP) Usage of the Offer/Answer Model - // https://tools.ietf.org/html/rfc6337 - // - // *** IMPORTANT IMPLEMENTATION CHOICES *** - // - // TLDR... - // - // 1) Only one offer/answer exchange permitted during initial INVITE. - // 2) No "early media" if the initial offer is in an INVITE. - // - // - // 1) Initial Offer/Answer Restriction. - // - // Our implementation replaces the following bullet point... - // - // o After having sent or received an answer to the first offer, the - // UAC MAY generate subsequent offers in requests based on rules - // specified for that method, but only if it has received answers - // to any previous offers, and has not sent any offers to which it - // hasn't gotten an answer. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // - // ...with... - // - // o After having sent or received an answer to the first offer, the - // UAC MUST NOT generate subsequent offers in requests based on rules - // specified for that method. - // - // ...which in combination with this bullet point... - // - // o Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // - // ...ensures that EXACTLY ONE offer/answer exchange will occur - // during an initial out of dialog INVITE request made by our UAC. - // - // - // 2) Early Media Restriction. - // - // While our implementation adheres to the following bullet point... - // - // o If the initial offer is in an INVITE, the answer MUST be in a - // reliable non-failure message from UAS back to UAC which is - // correlated to that INVITE. For this specification, that is - // only the final 2xx response to that INVITE. That same exact - // answer MAY also be placed in any provisional responses sent - // prior to the answer. The UAC MUST treat the first session - // description it receives as the answer, and MUST ignore any - // session descriptions in subsequent responses to the initial - // INVITE. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // - // We have made the following implementation decision with regard to early media... - // - // o If the initial offer is in the INVITE, the answer from the - // UAS back to the UAC will establish a media session only - // only after the final 2xx response to that INVITE is received. - // - // The reason for this decision is rooted in a restriction currently - // inherent in WebRTC. Specifically, while a SIP INVITE request with an - // initial offer may fork resulting in more than one provisional answer, - // there is currently no easy/good way to to "fork" an offer generated - // by a peer connection. In particular, a WebRTC offer currently may only - // be matched with one answer and we have no good way to know which - // "provisional answer" is going to be the "final answer". So we have - // decided to punt and not create any "early media" sessions in this case. - // - // The upshot is that if you want "early media", you must not put the - // initial offer in the INVITE. Instead, force the UAS to provide the - // initial offer by sending an INVITE without an offer. In the WebRTC - // case this allows us to create a unique peer connection with a unique - // answer for every provisional offer with "early media" on all of them. - //// - //// - // ROADMAP: The Offer/Answer Model Implementation - // - // The "no early media if offer in INVITE" implementation is not a - // welcome one. The masses want it. The want it and they want it - // to work for WebRTC (so they want to have their cake and eat too). - // - // So while we currently cannot make the offer in INVITE+forking+webrtc - // case work, we decided to do the following... - // - // 1) modify SDH Factory to provide an initial offer without giving us the SDH, and then... - // 2) stick that offer in the initial INVITE, and when 183 with initial answer is received... - // 3) ask SDH Factory if it supports "earlyRemoteAnswer" - // a) if true, ask SDH Factory to createSDH(localOffer).then((sdh) => sdh.setDescription(remoteAnswer) - // b) if false, defer getting a SDH until 2xx response is received - // - // Our supplied WebRTC SDH will default to behavior 3b which works in forking environment (without) - // early media if initial offer is in the INVITE). We will, however, provide an "inviteWillNotFork" - // option which if set to "true" will have our supplied WebRTC SDH behave in the 3a manner. - // That will result in - // - early media working with initial offer in the INVITE, and... - // - if the INVITE forks, the session terminating with an ERROR that reads like - // "You set 'inviteWillNotFork' to true but the INVITE forked. You can't eat your cake, and have it too." - // - furthermore, we accept that users will report that error to us as "bug" regardless - // - // So, SDH Factory is going to end up with a new interface along the lines of... - // - // interface SessionDescriptionHandlerFactory { - // makeLocalOffer(): Promise; - // makeSessionDescriptionHandler( - // initialOffer: ContentTypeAndBody, offerType: "local" | "remote" - // ): Promise; - // supportsEarlyRemoteAnswer: boolean; - // supportsContentType(contentType: string): boolean; - // getDescription(description: ContentTypeAndBody): Promise - // setDescription(description: ContentTypeAndBody): Promise - // } - // - // We should be able to get rid of all the hasOffer/hasAnswer tracking code and otherwise code - // it up to the same interaction with the SDH Factory and SDH regardless of signaling scenario. - //// - // Send the INVITE request. - this.outgoingInviteRequest = this.ua.userAgentCore.invite(this.request, { - onAccept: function (inviteResponse) { return _this.onAccept(inviteResponse); }, - onProgress: function (inviteResponse) { return _this.onProgress(inviteResponse); }, - onRedirect: function (inviteResponse) { return _this.onRedirect(inviteResponse); }, - onReject: function (inviteResponse) { return _this.onReject(inviteResponse); }, - onTrying: function (inviteResponse) { return _this.onTrying(inviteResponse); } - }); - }; - InviteClientContext.prototype.ackAndBye = function (inviteResponse, session, statusCode, reasonPhrase) { - if (!this.ua.userAgentCore) { - throw new Error("Method requires user agent core."); - } - var extraHeaders = []; - if (statusCode) { - extraHeaders.push("Reason: " + Utils_1.Utils.getReasonHeaderValue(statusCode, reasonPhrase)); - } - var outgoingAckRequest = inviteResponse.ack(); - this.emit("ack", outgoingAckRequest.message); - var outgoingByeRequest = session.bye(undefined, { extraHeaders: extraHeaders }); - this.emit("bye", outgoingByeRequest.message); - }; - InviteClientContext.prototype.disposeEarlyMedia = function () { - if (!this.earlyMediaSessionDescriptionHandlers) { - throw new Error("Early media session description handlers undefined."); - } - this.earlyMediaSessionDescriptionHandlers.forEach(function (sessionDescriptionHandler) { - sessionDescriptionHandler.close(); - }); - }; - /** - * Handle final response to initial INVITE. - * @param inviteResponse 2xx response. - */ - InviteClientContext.prototype.onAccept = function (inviteResponse) { - var _this = this; - if (!this.earlyMediaSessionDescriptionHandlers) { - throw new Error("Early media session description handlers undefined."); - } - var response = inviteResponse.message; - var session = inviteResponse.session; - // Our transaction layer is "non-standard" in that it will only - // pass us a 2xx response once per branch, so there is no need to - // worry about dealing with 2xx retransmissions. However, we can - // and do still get 2xx responses for multiple branches (when an - // INVITE is forked) which may create multiple confirmed dialogs. - // Herein we are acking and sending a bye to any confirmed dialogs - // which arrive beyond the first one. This is the desired behavior - // for most applications (but certainly not all). - // If we already received a confirmed dialog, ack & bye this session. - if (this.session) { - this.ackAndBye(inviteResponse, session); - return; - } - // If the user requested cancellation, ack & bye this session. - if (this.isCanceled) { - this.ackAndBye(inviteResponse, session); - this.emit("bye", this.request); // FIXME: Ported this odd second "bye" emit - return; - } - // Ported behavior. - if (response.hasHeader("P-Asserted-Identity")) { - this.assertedIdentity = core_1.Grammar.nameAddrHeaderParse(response.getHeader("P-Asserted-Identity")); - } - // We have a confirmed dialog. - this.session = session; - this.session.delegate = { - onAck: function (ackRequest) { return _this.onAck(ackRequest); }, - onBye: function (byeRequest) { return _this.receiveRequest(byeRequest); }, - onInfo: function (infoRequest) { return _this.receiveRequest(infoRequest); }, - onInvite: function (inviteRequest) { return _this.receiveRequest(inviteRequest); }, - onNotify: function (notifyRequest) { return _this.receiveRequest(notifyRequest); }, - onPrack: function (prackRequest) { return _this.receiveRequest(prackRequest); }, - onRefer: function (referRequest) { return _this.receiveRequest(referRequest); } - }; - switch (session.signalingState) { - case core_1.SignalingState.Initial: - // INVITE without Offer, so MUST have Offer at this point, so invalid state. - this.ackAndBye(inviteResponse, session, 400, "Missing session description"); - this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - break; - case core_1.SignalingState.HaveLocalOffer: - // INVITE with Offer, so MUST have Answer at this point, so invalid state. - this.ackAndBye(inviteResponse, session, 400, "Missing session description"); - this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - break; - case core_1.SignalingState.HaveRemoteOffer: - // INVITE without Offer, received offer in 2xx, so MUST send Answer in ACK. - var sdh_1 = this.sessionDescriptionHandlerFactory(this, this.ua.configuration.sessionDescriptionHandlerFactoryOptions || {}); - this.sessionDescriptionHandler = sdh_1; - this.emit("SessionDescriptionHandler-created", this.sessionDescriptionHandler); - if (!sdh_1.hasDescription(response.getHeader("Content-Type") || "")) { - this.ackAndBye(inviteResponse, session, 400, "Missing session description"); - this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - break; - } - this.hasOffer = true; - sdh_1 - .setDescription(response.body, this.sessionDescriptionHandlerOptions, this.modifiers) - .then(function () { return sdh_1.getDescription(_this.sessionDescriptionHandlerOptions, _this.modifiers); }) - .then(function (description) { - if (_this.isCanceled || _this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return; - } - _this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; - _this.hasAnswer = true; - var body = { - contentDisposition: "session", contentType: description.contentType, content: description.body - }; - var ackRequest = inviteResponse.ack({ body: body }); - _this.emit("ack", ackRequest.message); - _this.accepted(response); - }) - .catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - _this.logger.warn("invalid description"); - _this.logger.warn(e.toString()); - // TODO: This message is inconsistent - _this.ackAndBye(inviteResponse, session, 488, "Invalid session description"); - _this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - } - else { - throw e; - } - }); - break; - case core_1.SignalingState.Stable: - // This session has completed an initial offer/answer exchange... - var options_1; - if (this.renderbody && this.rendertype) { - options_1 = { body: { contentDisposition: "render", contentType: this.rendertype, content: this.renderbody } }; - } - // If INVITE with Offer and we have been waiting till now to apply the answer. - if (this.hasOffer && !this.hasAnswer) { - if (!this.sessionDescriptionHandler) { - throw new Error("Session description handler undefined."); - } - var answer = session.answer; - if (!answer) { - throw new Error("Answer is undefined."); - } - this.sessionDescriptionHandler - .setDescription(answer.content, this.sessionDescriptionHandlerOptions, this.modifiers) - .then(function () { - _this.hasAnswer = true; - _this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; - var ackRequest = inviteResponse.ack(options_1); - _this.emit("ack", ackRequest.message); - _this.accepted(response); - }) - .catch(function (error) { - _this.logger.error(error); - _this.ackAndBye(inviteResponse, session, 488, "Not Acceptable Here"); - _this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - // FIME: DON'T EAT UNHANDLED ERRORS! - }); - } - else { - // Otherwise INVITE with or without Offer and we have already completed the initial exchange. - this.sessionDescriptionHandler = this.earlyMediaSessionDescriptionHandlers.get(session.id); - if (!this.sessionDescriptionHandler) { - throw new Error("Session description handler undefined."); - } - this.earlyMediaSessionDescriptionHandlers.delete(session.id); - this.hasOffer = true; - this.hasAnswer = true; - this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; - var ackRequest = inviteResponse.ack(); - this.emit("ack", ackRequest.message); - this.accepted(response); - } - break; - case core_1.SignalingState.Closed: - // Dialog has terminated. - break; - default: - throw new Error("Unknown session signaling state."); - } - this.disposeEarlyMedia(); - }; - /** - * Handle provisional response to initial INVITE. - * @param inviteResponse 1xx response. - */ - InviteClientContext.prototype.onProgress = function (inviteResponse) { - var _this = this; - // Ported - User requested cancellation. - if (this.isCanceled) { - return; - } - if (!this.outgoingInviteRequest) { - throw new Error("Outgoing INVITE request undefined."); - } - if (!this.earlyMediaSessionDescriptionHandlers) { - throw new Error("Early media session description handlers undefined."); - } - var response = inviteResponse.message; - var session = inviteResponse.session; - // Ported - Set status. - this.status = Enums_1.SessionStatus.STATUS_1XX_RECEIVED; - // Ported - Set assertedIdentity. - if (response.hasHeader("P-Asserted-Identity")) { - this.assertedIdentity = core_1.Grammar.nameAddrHeaderParse(response.getHeader("P-Asserted-Identity")); - } - // The provisional response MUST establish a dialog if one is not yet created. - // https://tools.ietf.org/html/rfc3262#section-4 - if (!session) { - // A response with a to tag MUST create a session (should never get here). - throw new Error("Session undefined."); - } - // If a provisional response is received for an initial request, and - // that response contains a Require header field containing the option - // tag 100rel, the response is to be sent reliably. If the response is - // a 100 (Trying) (as opposed to 101 to 199), this option tag MUST be - // ignored, and the procedures below MUST NOT be used. - // https://tools.ietf.org/html/rfc3262#section-4 - var requireHeader = response.getHeader("require"); - var rseqHeader = response.getHeader("rseq"); - var rseq = requireHeader && requireHeader.includes("100rel") && rseqHeader ? Number(rseqHeader) : undefined; - var responseReliable = !!rseq; - var extraHeaders = []; - if (responseReliable) { - extraHeaders.push("RAck: " + response.getHeader("rseq") + " " + response.getHeader("cseq")); - } - // INVITE without Offer and session still has no offer (and no answer). - if (session.signalingState === core_1.SignalingState.Initial) { - // Similarly, if a reliable provisional - // response is the first reliable message sent back to the UAC, and the - // INVITE did not contain an offer, one MUST appear in that reliable - // provisional response. - // https://tools.ietf.org/html/rfc3262#section-5 - if (responseReliable) { - this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."); - // FIXME: Known popular UA's currently end up here... - inviteResponse.prack({ extraHeaders: extraHeaders }); - } - this.emit("progress", response); - return; - } - // INVITE with Offer and session only has that initial local offer. - if (session.signalingState === core_1.SignalingState.HaveLocalOffer) { - if (responseReliable) { - inviteResponse.prack({ extraHeaders: extraHeaders }); - } - this.emit("progress", response); - return; - } - // INVITE without Offer and received initial offer in provisional response - if (session.signalingState === core_1.SignalingState.HaveRemoteOffer) { - // The initial offer MUST be in either an INVITE or, if not there, - // in the first reliable non-failure message from the UAS back to - // the UAC. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // According to Section 13.2.1 of [RFC3261], 'The first reliable - // non-failure message' must have an offer if there is no offer in the - // INVITE request. This means that the User Agent (UA) that receives - // the INVITE request without an offer must include an offer in the - // first reliable response with 100rel extension. If no reliable - // provisional response has been sent, the User Agent Server (UAS) must - // include an offer when sending 2xx response. - // https://tools.ietf.org/html/rfc6337#section-2.2 - if (!responseReliable) { - this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response."); - return; - } - // If the initial offer is in the first reliable non-failure - // message from the UAS back to UAC, the answer MUST be in the - // acknowledgement for that message - var sdh_2 = this.sessionDescriptionHandlerFactory(this, this.ua.configuration.sessionDescriptionHandlerFactoryOptions || {}); - this.emit("SessionDescriptionHandler-created", sdh_2); - this.earlyMediaSessionDescriptionHandlers.set(session.id, sdh_2); - sdh_2 - .setDescription(response.body, this.sessionDescriptionHandlerOptions, this.modifiers) - .then(function () { return sdh_2.getDescription(_this.sessionDescriptionHandlerOptions, _this.modifiers); }) - .then(function (description) { - var body = { - contentDisposition: "session", contentType: description.contentType, content: description.body - }; - inviteResponse.prack({ extraHeaders: extraHeaders, body: body }); - _this.status = Enums_1.SessionStatus.STATUS_EARLY_MEDIA; - _this.emit("progress", response); - }) - .catch(function (error) { - if (_this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return; - } - _this.failed(undefined, Constants_1.C.causes.WEBRTC_ERROR); - _this.terminated(undefined, Constants_1.C.causes.WEBRTC_ERROR); - }); - return; - } - // This session has completed an initial offer/answer exchange, so... - // - INVITE with SDP and this provisional response MAY be reliable - // - INVITE without SDP and this provisional response MAY be reliable - if (session.signalingState === core_1.SignalingState.Stable) { - if (responseReliable) { - inviteResponse.prack({ extraHeaders: extraHeaders }); - } - // Note: As documented, no early media if offer was in INVITE, so nothing to be done. - // FIXME: TODO: Add a flag/hack to allow early media in this case. There are people - // in non-forking environments (think straight to FreeSWITCH) who want - // early media on a 183. Not sure how to actually make it work, basically - // something like... - if (false) {} - this.emit("progress", response); - return; - } - }; - /** - * Handle final response to initial INVITE. - * @param inviteResponse 3xx response. - */ - InviteClientContext.prototype.onRedirect = function (inviteResponse) { - this.disposeEarlyMedia(); - var response = inviteResponse.message; - var statusCode = response.statusCode; - var cause = Utils_1.Utils.sipErrorCause(statusCode || 0); - this.rejected(response, cause); - this.failed(response, cause); - this.terminated(response, cause); - }; - /** - * Handle final response to initial INVITE. - * @param inviteResponse 4xx, 5xx, or 6xx response. - */ - InviteClientContext.prototype.onReject = function (inviteResponse) { - this.disposeEarlyMedia(); - var response = inviteResponse.message; - var statusCode = response.statusCode; - var cause = Utils_1.Utils.sipErrorCause(statusCode || 0); - this.rejected(response, cause); - this.failed(response, cause); - this.terminated(response, cause); - }; - /** - * Handle final response to initial INVITE. - * @param inviteResponse 100 response. - */ - InviteClientContext.prototype.onTrying = function (inviteResponse) { - this.received100 = true; - this.emit("progress", inviteResponse.message); - }; - return InviteClientContext; -}(Session)); -exports.InviteClientContext = InviteClientContext; - - -/***/ }), -/* 91 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var events_1 = __webpack_require__(30); -var Constants_1 = __webpack_require__(80); -var Enums_1 = __webpack_require__(82); -var Exceptions_1 = __webpack_require__(84); -var Utils_1 = __webpack_require__(83); -/** - * @class DTMF - * @param {SIP.Session} session - */ -var DTMF = /** @class */ (function (_super) { - tslib_1.__extends(DTMF, _super); - function DTMF(session, tone, options) { - if (options === void 0) { options = {}; } - var _this = _super.call(this) || this; - _this.C = { - MIN_DURATION: 70, - MAX_DURATION: 6000, - DEFAULT_DURATION: 100, - MIN_INTER_TONE_GAP: 50, - DEFAULT_INTER_TONE_GAP: 500 - }; - _this.type = Enums_1.TypeStrings.DTMF; - if (tone === undefined) { - throw new TypeError("Not enough arguments"); - } - _this.logger = session.ua.getLogger("sip.invitecontext.dtmf", session.id); - _this.owner = session; - // Check tone type - if (typeof tone === "string") { - tone = tone.toUpperCase(); - } - else if (typeof tone === "number") { - tone = tone.toString(); - } - else { - throw new TypeError("Invalid tone: " + tone); - } - // Check tone value - if (!tone.match(/^[0-9A-D#*]$/)) { - throw new TypeError("Invalid tone: " + tone); - } - else { - _this.tone = tone; - } - var duration = options.duration; - var interToneGap = options.interToneGap; - // Check duration - if (duration && !Utils_1.Utils.isDecimal(duration)) { - throw new TypeError("Invalid tone duration: " + duration); - } - else if (!duration) { - duration = _this.C.DEFAULT_DURATION; - } - else if (duration < _this.C.MIN_DURATION) { - _this.logger.warn("'duration' value is lower than the minimum allowed, setting it to " + - _this.C.MIN_DURATION + " milliseconds"); - duration = _this.C.MIN_DURATION; - } - else if (duration > _this.C.MAX_DURATION) { - _this.logger.warn("'duration' value is greater than the maximum allowed, setting it to " + - _this.C.MAX_DURATION + " milliseconds"); - duration = _this.C.MAX_DURATION; - } - else { - duration = Math.abs(duration); - } - _this.duration = duration; - // Check interToneGap - if (interToneGap && !Utils_1.Utils.isDecimal(interToneGap)) { - throw new TypeError("Invalid interToneGap: " + interToneGap); - } - else if (!interToneGap) { - interToneGap = _this.C.DEFAULT_INTER_TONE_GAP; - } - else if (interToneGap < _this.C.MIN_INTER_TONE_GAP) { - _this.logger.warn("'interToneGap' value is lower than the minimum allowed, setting it to " + - _this.C.MIN_INTER_TONE_GAP + " milliseconds"); - interToneGap = _this.C.MIN_INTER_TONE_GAP; - } - else { - interToneGap = Math.abs(interToneGap); - } - _this.interToneGap = interToneGap; - return _this; - } - DTMF.prototype.send = function (options) { - if (options === void 0) { options = {}; } - // Check RTCSession Status - if (this.owner.status !== Enums_1.SessionStatus.STATUS_CONFIRMED && - this.owner.status !== Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK) { - throw new Exceptions_1.Exceptions.InvalidStateError(this.owner.status); - } - // Get DTMF options - var extraHeaders = options.extraHeaders ? options.extraHeaders.slice() : []; - var body = { - contentType: "application/dtmf-relay", - body: "Signal= " + this.tone + "\r\nDuration= " + this.duration - }; - if (this.owner.session) { - var request = this.owner.session.info(undefined, { - extraHeaders: extraHeaders, - body: Utils_1.Utils.fromBodyObj(body) - }); - this.owner.emit("dtmf", request.message, this); - return; - } - }; - DTMF.prototype.init_incoming = function (request) { - request.accept(); - if (!this.tone || !this.duration) { - this.logger.warn("invalid INFO DTMF received, discarded"); - } - else { - this.owner.emit("dtmf", request.message, this); - } - }; - DTMF.prototype.receiveResponse = function (response) { - var statusCode = response && response.statusCode ? response.statusCode : 0; - switch (true) { - case /^1[0-9]{2}$/.test(statusCode.toString()): - // Ignore provisional responses. - break; - case /^2[0-9]{2}$/.test(statusCode.toString()): - this.emit("succeeded", { - originator: "remote", - response: response - }); - break; - default: - var cause = Utils_1.Utils.sipErrorCause(statusCode); - this.emit("failed", response, cause); - break; - } - }; - DTMF.prototype.onRequestTimeout = function () { - this.emit("failed", undefined, Constants_1.C.causes.REQUEST_TIMEOUT); - this.owner.onRequestTimeout(); - }; - DTMF.prototype.onTransportError = function () { - this.emit("failed", undefined, Constants_1.C.causes.CONNECTION_ERROR); - this.owner.onTransportError(); - }; - DTMF.prototype.onDialogError = function (response) { - this.emit("failed", response, Constants_1.C.causes.DIALOG_ERROR); - this.owner.onDialogError(response); - }; - return DTMF; -}(events_1.EventEmitter)); -exports.DTMF = DTMF; - - -/***/ }), -/* 92 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var events_1 = __webpack_require__(30); -var Constants_1 = __webpack_require__(80); -var core_1 = __webpack_require__(2); -var allowed_methods_1 = __webpack_require__(58); -var Enums_1 = __webpack_require__(82); -var Utils_1 = __webpack_require__(83); -/** - * While this class is named `Subscription`, it is closer to - * an implementation of a "subscriber" as defined in RFC 6665 - * "SIP-Specific Event Notifications". - * https://tools.ietf.org/html/rfc6665 - * @class Class creating a SIP Subscriber. - */ -var Subscription = /** @class */ (function (_super) { - tslib_1.__extends(Subscription, _super); - /** - * Constructor. - * @param ua User agent. - * @param target Subscription target. - * @param event Subscription event. - * @param options Options bucket. - */ - function Subscription(ua, target, event, options) { - if (options === void 0) { options = {}; } - var _this = _super.call(this) || this; - _this.data = {}; - _this.method = Constants_1.C.SUBSCRIBE; - _this.body = undefined; - // ClientContext interface - _this.type = Enums_1.TypeStrings.Subscription; - _this.ua = ua; - _this.logger = ua.getLogger("sip.subscription"); - if (options.body) { - _this.body = { - body: options.body, - contentType: options.contentType ? options.contentType : "application/sdp" - }; - } - // Target URI - var uri = ua.normalizeTarget(target); - if (!uri) { - throw new TypeError("Invalid target: " + target); - } - _this.uri = uri; - // Subscription event - _this.event = event; - // Subscription expires - if (options.expires === undefined) { - _this.expires = 3600; - } - else if (typeof options.expires !== "number") { // pre-typescript type guard - ua.logger.warn("Option \"expires\" must be a number. Using default of 3600."); - _this.expires = 3600; - } - else { - _this.expires = options.expires; - } - // Subscription extra headers - _this.extraHeaders = (options.extraHeaders || []).slice(); - // Subscription context. - _this.context = _this.initContext(); - _this.disposed = false; - // ClientContext interface - _this.request = _this.context.message; - if (!_this.request.from) { - throw new Error("From undefined."); - } - if (!_this.request.to) { - throw new Error("From undefined."); - } - _this.localIdentity = _this.request.from; - _this.remoteIdentity = _this.request.to; - // Add to UA's collection - _this.id = _this.request.callId + _this.request.from.parameters.tag + _this.event; - _this.ua.subscriptions[_this.id] = _this; - return _this; - } - /** - * Destructor. - */ - Subscription.prototype.dispose = function () { - if (this.disposed) { - return; - } - if (this.retryAfterTimer) { - clearTimeout(this.retryAfterTimer); - this.retryAfterTimer = undefined; - } - this.context.dispose(); - this.disposed = true; - // Remove from UA's collection - delete this.ua.subscriptions[this.id]; - }; - Subscription.prototype.on = function (name, callback) { - return _super.prototype.on.call(this, name, callback); - }; - Subscription.prototype.emit = function (event) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - return _super.prototype.emit.apply(this, [event].concat(args)); - }; - /** - * Gracefully terminate. - */ - Subscription.prototype.close = function () { - if (this.disposed) { - return; - } - this.dispose(); - switch (this.context.state) { - case core_1.SubscriptionState.Initial: - this.onTerminated(); - break; - case core_1.SubscriptionState.NotifyWait: - this.onTerminated(); - break; - case core_1.SubscriptionState.Pending: - this.unsubscribe(); - break; - case core_1.SubscriptionState.Active: - this.unsubscribe(); - break; - case core_1.SubscriptionState.Terminated: - this.onTerminated(); - break; - default: - break; - } - }; - /** - * Send a re-SUBSCRIBE request if there is an "active" subscription. - */ - Subscription.prototype.refresh = function () { - var _this = this; - switch (this.context.state) { - case core_1.SubscriptionState.Initial: - break; - case core_1.SubscriptionState.NotifyWait: - break; - case core_1.SubscriptionState.Pending: - break; - case core_1.SubscriptionState.Active: - if (this.subscription) { - var request = this.subscription.refresh(); - request.delegate = { - onAccept: (function (response) { return _this.onAccepted(response); }), - onRedirect: (function (response) { return _this.onFailed(response); }), - onReject: (function (response) { return _this.onFailed(response); }), - }; - } - break; - case core_1.SubscriptionState.Terminated: - break; - default: - break; - } - }; - /** - * Send an initial SUBSCRIBE request if no subscription. - * Send a re-SUBSCRIBE request if there is an "active" subscription. - */ - Subscription.prototype.subscribe = function () { - var _this = this; - switch (this.context.state) { - case core_1.SubscriptionState.Initial: - this.context.subscribe().then(function (result) { - if (result.success) { - if (result.success.subscription) { - _this.subscription = result.success.subscription; - _this.subscription.delegate = { - onNotify: function (request) { return _this.onNotify(request); }, - onRefresh: function (request) { return _this.onRefresh(request); }, - onTerminated: function () { return _this.close(); } - }; - } - _this.onNotify(result.success.request); - } - else if (result.failure) { - _this.onFailed(result.failure.response); - } - }); - break; - case core_1.SubscriptionState.NotifyWait: - break; - case core_1.SubscriptionState.Pending: - break; - case core_1.SubscriptionState.Active: - this.refresh(); - break; - case core_1.SubscriptionState.Terminated: - break; - default: - break; - } - return this; - }; - /** - * Send a re-SUBSCRIBE request if there is a "pending" or "active" subscription. - */ - Subscription.prototype.unsubscribe = function () { - this.dispose(); - switch (this.context.state) { - case core_1.SubscriptionState.Initial: - break; - case core_1.SubscriptionState.NotifyWait: - break; - case core_1.SubscriptionState.Pending: - if (this.subscription) { - this.subscription.unsubscribe(); - // responses intentionally ignored - } - break; - case core_1.SubscriptionState.Active: - if (this.subscription) { - this.subscription.unsubscribe(); - // responses intentionally ignored - } - break; - case core_1.SubscriptionState.Terminated: - break; - default: - break; - } - this.onTerminated(); - }; - Subscription.prototype.onAccepted = function (response) { - var statusCode = response.message.statusCode ? response.message.statusCode : 0; - var cause = Utils_1.Utils.getReasonPhrase(statusCode); - this.emit("accepted", response.message, cause); - }; - Subscription.prototype.onFailed = function (response) { - this.close(); - if (response) { - var statusCode = response.message.statusCode ? response.message.statusCode : 0; - var cause = Utils_1.Utils.getReasonPhrase(statusCode); - this.emit("failed", response.message, cause); - this.emit("rejected", response.message, cause); - } - }; - Subscription.prototype.onNotify = function (request) { - var _this = this; - request.accept(); // Send 200 response. - this.emit("notify", { request: request.message }); - // If we've set state to done, no further processing should take place - // and we are only interested in cleaning up after the appropriate NOTIFY. - if (this.disposed) { - return; - } - // If the "Subscription-State" value is "terminated", the subscriber - // MUST consider the subscription terminated. The "expires" parameter - // has no semantics for "terminated" -- notifiers SHOULD NOT include an - // "expires" parameter on a "Subscription-State" header field with a - // value of "terminated", and subscribers MUST ignore any such - // parameter, if present. If a reason code is present, the client - // should behave as described below. If no reason code or an unknown - // reason code is present, the client MAY attempt to re-subscribe at any - // time (unless a "retry-after" parameter is present, in which case the - // client SHOULD NOT attempt re-subscription until after the number of - // seconds specified by the "retry-after" parameter). The reason codes - // defined by this document are: - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - var subscriptionState = request.message.parseHeader("Subscription-State"); - if (subscriptionState && subscriptionState.state) { - switch (subscriptionState.state) { - case "terminated": - if (subscriptionState.reason) { - this.logger.log("Terminated subscription with reason " + subscriptionState.reason); - switch (subscriptionState.reason) { - case "deactivated": - case "timeout": - this.initContext(); - this.subscribe(); - return; - case "probation": - case "giveup": - this.initContext(); - if (subscriptionState.params && subscriptionState.params["retry-after"]) { - this.retryAfterTimer = setTimeout(function () { return _this.subscribe(); }, subscriptionState.params["retry-after"]); - } - else { - this.subscribe(); - } - return; - case "rejected": - case "noresource": - case "invariant": - break; - } - } - this.close(); - break; - default: - break; - } - } - }; - Subscription.prototype.onRefresh = function (request) { - var _this = this; - request.delegate = { - onAccept: function (response) { return _this.onAccepted(response); } - }; - }; - Subscription.prototype.onTerminated = function () { - this.emit("terminated"); - }; - Subscription.prototype.initContext = function () { - var _this = this; - var options = { - extraHeaders: this.extraHeaders, - body: this.body ? Utils_1.Utils.fromBodyObj(this.body) : undefined - }; - this.context = new SubscribeClientContext(this.ua.userAgentCore, this.uri, this.event, this.expires, options); - this.context.delegate = { - onAccept: (function (response) { return _this.onAccepted(response); }) - }; - return this.context; - }; - return Subscription; -}(events_1.EventEmitter)); -exports.Subscription = Subscription; -// tslint:disable-next-line:max-classes-per-file -var SubscribeClientContext = /** @class */ (function () { - function SubscribeClientContext(core, target, event, expires, options, delegate) { - this.core = core; - this.target = target; - this.event = event; - this.expires = expires; - this.subscribed = false; - this.logger = core.loggerFactory.getLogger("sip.subscription"); - this.delegate = delegate; - var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); - var extraHeaders = (options && options.extraHeaders || []).slice(); - extraHeaders.push(allowHeader); - extraHeaders.push("Event: " + this.event); - extraHeaders.push("Expires: " + this.expires); - extraHeaders.push("Contact: " + this.core.configuration.contact.toString()); - var body = options && options.body; - this.message = core.makeOutgoingRequestMessage(Constants_1.C.SUBSCRIBE, this.target, this.core.configuration.aor, this.target, {}, extraHeaders, body); - } - /** Destructor. */ - SubscribeClientContext.prototype.dispose = function () { - if (this.subscription) { - this.subscription.dispose(); - } - if (this.request) { - this.request.waitNotifyStop(); - this.request.dispose(); - } - }; - Object.defineProperty(SubscribeClientContext.prototype, "state", { - /** Subscription state. */ - get: function () { - if (this.subscription) { - return this.subscription.subscriptionState; - } - else if (this.subscribed) { - return core_1.SubscriptionState.NotifyWait; - } - else { - return core_1.SubscriptionState.Initial; - } - }, - enumerable: true, - configurable: true - }); - /** - * Establish subscription. - * @param options Options bucket. - */ - SubscribeClientContext.prototype.subscribe = function () { - var _this = this; - if (this.subscribed) { - return Promise.reject(new Error("Not in initial state. Did you call subscribe more than once?")); - } - this.subscribed = true; - return new Promise(function (resolve, reject) { - if (!_this.message) { - throw new Error("Message undefined."); - } - _this.request = _this.core.subscribe(_this.message, { - // This SUBSCRIBE request will be confirmed with a final response. - // 200-class responses indicate that the subscription has been accepted - // and that a NOTIFY request will be sent immediately. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - onAccept: function (response) { - if (_this.delegate && _this.delegate.onAccept) { - _this.delegate.onAccept(response); - } - }, - // Due to the potential for out-of-order messages, packet loss, and - // forking, the subscriber MUST be prepared to receive NOTIFY requests - // before the SUBSCRIBE transaction has completed. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.4 - onNotify: function (requestWithSubscription) { - _this.subscription = requestWithSubscription.subscription; - if (_this.subscription) { - _this.subscription.autoRefresh = true; - } - resolve({ success: requestWithSubscription }); - }, - // If this Timer N expires prior to the receipt of a NOTIFY request, - // the subscriber considers the subscription failed, and cleans up - // any state associated with the subscription attempt. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.4 - onNotifyTimeout: function () { - resolve({ failure: {} }); - }, - // This SUBSCRIBE request will be confirmed with a final response. - // Non-200-class final responses indicate that no subscription or new - // dialog usage has been created, and no subsequent NOTIFY request will - // be sent. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - onRedirect: function (response) { - resolve({ failure: { response: response } }); - }, - // This SUBSCRIBE request will be confirmed with a final response. - // Non-200-class final responses indicate that no subscription or new - // dialog usage has been created, and no subsequent NOTIFY request will - // be sent. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - onReject: function (response) { - resolve({ failure: { response: response } }); - } - }); - }); - }; - return SubscribeClientContext; -}()); - - -/***/ }), -/* 93 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var events_1 = __webpack_require__(30); -var ClientContext_1 = __webpack_require__(79); -var Constants_1 = __webpack_require__(80); -var core_1 = __webpack_require__(2); -var Enums_1 = __webpack_require__(82); -var Exceptions_1 = __webpack_require__(84); -var Parser_1 = __webpack_require__(85); -var PublishContext_1 = __webpack_require__(86); -var ReferContext_1 = __webpack_require__(87); -var RegisterContext_1 = __webpack_require__(89); -var ServerContext_1 = __webpack_require__(88); -var Session_1 = __webpack_require__(90); -var Subscription_1 = __webpack_require__(92); -var Utils_1 = __webpack_require__(83); -var SessionDescriptionHandler_1 = __webpack_require__(94); -var Transport_1 = __webpack_require__(103); -/** - * @class Class creating a SIP User Agent. - * @param {function returning SIP.sessionDescriptionHandler} [configuration.sessionDescriptionHandlerFactory] - * A function will be invoked by each of the UA's Sessions to build the sessionDescriptionHandler for that Session. - * If no (or a falsy) value is provided, each Session will use a default (WebRTC) sessionDescriptionHandler. - */ -var UA = /** @class */ (function (_super) { - tslib_1.__extends(UA, _super); - function UA(configuration) { - var _this = _super.call(this) || this; - /** Unload listener. */ - _this.unloadListener = (function () { _this.stop(); }); - _this.type = Enums_1.TypeStrings.UA; - _this.log = new core_1.LoggerFactory(); - _this.logger = _this.getLogger("sip.ua"); - _this.configuration = {}; - // User actions outside any session/dialog (MESSAGE) - _this.applicants = {}; - _this.data = {}; - _this.sessions = {}; - _this.subscriptions = {}; - _this.publishers = {}; - _this.status = Enums_1.UAStatus.STATUS_INIT; - /** - * Load configuration - * - * @throws {SIP.Exceptions.ConfigurationError} - * @throws {TypeError} - */ - if (configuration === undefined) { - configuration = {}; - } - else if (typeof configuration === "string" || configuration instanceof String) { - configuration = { - uri: configuration - }; - } - // Apply log configuration if present - if (configuration.log) { - _this.log.builtinEnabled = configuration.log.builtinEnabled; - if (configuration.log.hasOwnProperty("connector")) { - _this.log.connector = configuration.log.connector; - } - if (configuration.log.hasOwnProperty("level")) { - var level = configuration.log.level; - var normalized = void 0; - if (typeof level === "string") { - switch (level) { - case "error": - normalized = core_1.Levels.error; - break; - case "warn": - normalized = core_1.Levels.warn; - break; - case "log": - normalized = core_1.Levels.log; - break; - case "debug": - normalized = core_1.Levels.debug; - break; - default: - break; - } - } - else { - switch (level) { - case 0: - normalized = core_1.Levels.error; - break; - case 1: - normalized = core_1.Levels.warn; - break; - case 2: - normalized = core_1.Levels.log; - break; - case 3: - normalized = core_1.Levels.debug; - break; - default: - break; - } - } - // avoid setting level when invalid, use default level instead - if (normalized === undefined) { - _this.logger.error("Invalid \"level\" parameter value: " + JSON.stringify(level)); - } - else { - _this.log.level = normalized; - } - } - } - var deprecatedMessage = "The UA class has been deprecated and will no longer be available starting with SIP.js release 0.16.0. " + - "The UA has been replaced by the UserAgent class. Please update accordingly."; - _this.logger.warn(deprecatedMessage); - try { - _this.loadConfig(configuration); - } - catch (e) { - _this.status = Enums_1.UAStatus.STATUS_NOT_READY; - _this.error = UA.C.CONFIGURATION_ERROR; - throw e; - } - if (!_this.configuration.transportConstructor) { - throw new core_1.TransportError("Transport constructor not set"); - } - _this.transport = new _this.configuration.transportConstructor(_this.getLogger("sip.transport"), _this.configuration.transportOptions); - var userAgentCoreConfiguration = makeUserAgentCoreConfigurationFromUA(_this); - // The Replaces header contains information used to match an existing - // SIP dialog (call-id, to-tag, and from-tag). Upon receiving an INVITE - // with a Replaces header, the User Agent (UA) attempts to match this - // information with a confirmed or early dialog. - // https://tools.ietf.org/html/rfc3891#section-3 - var handleInviteWithReplacesHeader = function (context, request) { - if (_this.configuration.replaces !== Constants_1.C.supported.UNSUPPORTED) { - var replaces = request.parseHeader("replaces"); - if (replaces) { - var targetSession = _this.sessions[replaces.call_id + replaces.replaces_from_tag] || - _this.sessions[replaces.call_id + replaces.replaces_to_tag] || - undefined; - if (!targetSession) { - _this.userAgentCore.replyStateless(request, { statusCode: 481 }); - return; - } - if (targetSession.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - _this.userAgentCore.replyStateless(request, { statusCode: 603 }); - return; - } - var targetDialogId = replaces.call_id + replaces.replaces_to_tag + replaces.replaces_from_tag; - var targetDialog = _this.userAgentCore.dialogs.get(targetDialogId); - if (!targetDialog) { - _this.userAgentCore.replyStateless(request, { statusCode: 481 }); - return; - } - if (!targetDialog.early && replaces.early_only) { - _this.userAgentCore.replyStateless(request, { statusCode: 486 }); - return; - } - context.replacee = targetSession; - } - } - }; - var userAgentCoreDelegate = { - onInvite: function (incomingInviteRequest) { - // FIXME: Ported - 100 Trying send should be configurable. - // Only required if TU will not respond in 200ms. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - incomingInviteRequest.trying(); - incomingInviteRequest.delegate = { - onCancel: function (cancel) { - context.onCancel(cancel); - }, - onTransportError: function (error) { - context.onTransportError(); - } - }; - var context = new Session_1.InviteServerContext(_this, incomingInviteRequest); - // Ported - handling of out of dialog INVITE with Replaces. - handleInviteWithReplacesHeader(context, incomingInviteRequest.message); - // Ported - make the first call to progress automatically. - if (context.autoSendAnInitialProvisionalResponse) { - context.progress(); - } - _this.emit("invite", context); - }, - onMessage: function (incomingMessageRequest) { - // Ported - handling of out of dialog MESSAGE. - var serverContext = new ServerContext_1.ServerContext(_this, incomingMessageRequest); - serverContext.body = incomingMessageRequest.message.body; - serverContext.contentType = incomingMessageRequest.message.getHeader("Content-Type") || "text/plain"; - incomingMessageRequest.accept(); - _this.emit("message", serverContext); // TODO: Review. Why is a "ServerContext" emitted? What use it is? - }, - onNotify: function (incomingNotifyRequest) { - // DEPRECATED: Out of dialog NOTIFY is an obsolete usage. - // Ported - handling of out of dialog NOTIFY. - if (_this.configuration.allowLegacyNotifications && _this.listeners("notify").length > 0) { - incomingNotifyRequest.accept(); - _this.emit("notify", { request: incomingNotifyRequest.message }); - } - else { - incomingNotifyRequest.reject({ statusCode: 481 }); - } - }, - onRefer: function (incomingReferRequest) { - // Ported - handling of out of dialog REFER. - _this.logger.log("Received an out of dialog refer"); - if (!_this.configuration.allowOutOfDialogRefers) { - incomingReferRequest.reject({ statusCode: 405 }); - } - _this.logger.log("Allow out of dialog refers is enabled on the UA"); - var referContext = new ReferContext_1.ReferServerContext(_this, incomingReferRequest); - if (_this.listeners("outOfDialogReferRequested").length) { - _this.emit("outOfDialogReferRequested", referContext); - } - else { - _this.logger.log("No outOfDialogReferRequest listeners, automatically accepting and following the out of dialog refer"); - referContext.accept({ followRefer: true }); - } - }, - onSubscribe: function (incomingSubscribeRequest) { - _this.emit("subscribe", incomingSubscribeRequest); - }, - }; - _this.userAgentCore = new core_1.UserAgentCore(userAgentCoreConfiguration, userAgentCoreDelegate); - // Initialize registerContext - _this.registerContext = new RegisterContext_1.RegisterContext(_this, configuration.registerOptions); - _this.registerContext.on("failed", _this.emit.bind(_this, "registrationFailed")); - _this.registerContext.on("registered", _this.emit.bind(_this, "registered")); - _this.registerContext.on("unregistered", _this.emit.bind(_this, "unregistered")); - if (_this.configuration.autostart) { - _this.start(); - } - return _this; - } - // ================= - // High Level API - // ================= - UA.prototype.register = function (options) { - if (options === void 0) { options = {}; } - if (options.register) { - this.configuration.register = true; - } - this.registerContext.register(options); - return this; - }; - /** - * Unregister. - * - * @param {Boolean} [all] unregister all user bindings. - * - */ - UA.prototype.unregister = function (options) { - var _this = this; - this.configuration.register = false; - this.transport.afterConnected(function () { - _this.registerContext.unregister(options); - }); - return this; - }; - UA.prototype.isRegistered = function () { - return this.registerContext.registered; - }; - /** - * Make an outgoing call. - * - * @param {String} target - * @param {Object} views - * @param {Object} [options.media] gets passed to SIP.sessionDescriptionHandler.getDescription as mediaHint - * - * @throws {TypeError} - * - */ - UA.prototype.invite = function (target, options, modifiers) { - var _this = this; - var context = new Session_1.InviteClientContext(this, target, options, modifiers); - // Delay sending actual invite until the next 'tick' if we are already - // connected, so that API consumers can register to events fired by the - // the session. - this.transport.afterConnected(function () { - context.invite(); - _this.emit("inviteSent", context); - }); - return context; - }; - UA.prototype.subscribe = function (target, event, options) { - var sub = new Subscription_1.Subscription(this, target, event, options); - this.transport.afterConnected(function () { return sub.subscribe(); }); - return sub; - }; - /** - * Send PUBLISH Event State Publication (RFC3903) - * - * @param {String} target - * @param {String} event - * @param {String} body - * @param {Object} [options] - * - * @throws {SIP.Exceptions.MethodParameterError} - */ - UA.prototype.publish = function (target, event, body, options) { - var pub = new PublishContext_1.PublishContext(this, target, event, options); - this.transport.afterConnected(function () { - pub.publish(body); - }); - return pub; - }; - /** - * Send a message. - * - * @param {String} target - * @param {String} body - * @param {Object} [options] - * - * @throws {TypeError} - */ - UA.prototype.message = function (target, body, options) { - if (options === void 0) { options = {}; } - if (body === undefined) { - throw new TypeError("Not enough arguments"); - } - // There is no Message module, so it is okay that the UA handles defaults here. - options.contentType = options.contentType || "text/plain"; - options.body = body; - return this.request(Constants_1.C.MESSAGE, target, options); - }; - UA.prototype.request = function (method, target, options) { - var req = new ClientContext_1.ClientContext(this, method, target, options); - this.transport.afterConnected(function () { return req.send(); }); - return req; - }; - /** - * Gracefully close. - */ - UA.prototype.stop = function () { - this.logger.log("user requested closure..."); - if (this.status === Enums_1.UAStatus.STATUS_USER_CLOSED) { - this.logger.warn("UA already closed"); - return this; - } - // Close registerContext - this.logger.log("closing registerContext"); - this.registerContext.close(); - // Run terminate on every Session - for (var session in this.sessions) { - if (this.sessions[session]) { - this.logger.log("closing session " + session); - this.sessions[session].terminate(); - } - } - // Run unsubscribe on every Subscription - for (var subscription in this.subscriptions) { - if (this.subscriptions[subscription]) { - this.logger.log("unsubscribe " + subscription); - this.subscriptions[subscription].unsubscribe(); - } - } - // Run close on every Publisher - for (var publisher in this.publishers) { - if (this.publishers[publisher]) { - this.logger.log("unpublish " + publisher); - this.publishers[publisher].close(); - } - } - // Run close on every applicant - for (var applicant in this.applicants) { - if (this.applicants[applicant]) { - this.applicants[applicant].close(); - } - } - this.status = Enums_1.UAStatus.STATUS_USER_CLOSED; - // Disconnect the transport and reset user agent core - this.transport.disconnect(); - this.userAgentCore.reset(); - if (this.configuration.autostop) { - // Google Chrome Packaged Apps don't allow 'unload' listeners: unload is not available in packaged apps - var googleChromePackagedApp = typeof chrome !== "undefined" && chrome.app && chrome.app.runtime ? true : false; - if (typeof window !== "undefined" && - typeof window.removeEventListener === "function" && - !googleChromePackagedApp) { - window.removeEventListener("unload", this.unloadListener); - } - } - return this; - }; - /** - * Connect to the WS server if status = STATUS_INIT. - * Resume UA after being closed. - * - */ - UA.prototype.start = function () { - this.logger.log("user requested startup..."); - if (this.status === Enums_1.UAStatus.STATUS_INIT) { - this.status = Enums_1.UAStatus.STATUS_STARTING; - this.setTransportListeners(); - this.emit("transportCreated", this.transport); - this.transport.connect(); - } - else if (this.status === Enums_1.UAStatus.STATUS_USER_CLOSED) { - this.logger.log("resuming"); - this.status = Enums_1.UAStatus.STATUS_READY; - this.transport.connect(); - } - else if (this.status === Enums_1.UAStatus.STATUS_STARTING) { - this.logger.log("UA is in STARTING status, not opening new connection"); - } - else if (this.status === Enums_1.UAStatus.STATUS_READY) { - this.logger.log("UA is in READY status, not resuming"); - } - else { - this.logger.error("Connection is down. Auto-Recovery system is trying to connect"); - } - if (this.configuration.autostop) { - // Google Chrome Packaged Apps don't allow 'unload' listeners: unload is not available in packaged apps - var googleChromePackagedApp = typeof chrome !== "undefined" && chrome.app && chrome.app.runtime ? true : false; - if (typeof window !== "undefined" && - typeof window.addEventListener === "function" && - !googleChromePackagedApp) { - window.addEventListener("unload", this.unloadListener); - } - } - return this; - }; - /** - * Normalize a string into a valid SIP request URI - * - * @param {String} target - * - * @returns {SIP.URI|undefined} - */ - UA.prototype.normalizeTarget = function (target) { - return Utils_1.Utils.normalizeTarget(target, this.configuration.hostportParams); - }; - UA.prototype.getLogger = function (category, label) { - return this.log.getLogger(category, label); - }; - UA.prototype.getLoggerFactory = function () { - return this.log; - }; - UA.prototype.getSupportedResponseOptions = function () { - var optionTags = []; - if (this.contact.pubGruu || this.contact.tempGruu) { - optionTags.push("gruu"); - } - if (this.configuration.rel100 === Constants_1.C.supported.SUPPORTED) { - optionTags.push("100rel"); - } - if (this.configuration.replaces === Constants_1.C.supported.SUPPORTED) { - optionTags.push("replaces"); - } - optionTags.push("outbound"); - optionTags = optionTags.concat(this.configuration.extraSupported || []); - var allowUnregistered = this.configuration.hackAllowUnregisteredOptionTags || false; - var optionTagSet = {}; - optionTags = optionTags.filter(function (optionTag) { - var registered = Constants_1.C.OPTION_TAGS[optionTag]; - var unique = !optionTagSet[optionTag]; - optionTagSet[optionTag] = true; - return (registered || allowUnregistered) && unique; - }); - return optionTags; - }; - /** - * Get the session to which the request belongs to, if any. - * @param {SIP.IncomingRequest} request. - * @returns {SIP.OutgoingSession|SIP.IncomingSession|undefined} - */ - UA.prototype.findSession = function (request) { - return this.sessions[request.callId + request.fromTag] || - this.sessions[request.callId + request.toTag] || - undefined; - }; - UA.prototype.on = function (name, callback) { return _super.prototype.on.call(this, name, callback); }; - // ============================== - // Event Handlers - // ============================== - UA.prototype.onTransportError = function () { - if (this.status === Enums_1.UAStatus.STATUS_USER_CLOSED) { - return; - } - if (!this.error || this.error !== UA.C.NETWORK_ERROR) { - this.status = Enums_1.UAStatus.STATUS_NOT_READY; - this.error = UA.C.NETWORK_ERROR; - } - }; - /** - * Helper function. Sets transport listeners - */ - UA.prototype.setTransportListeners = function () { - var _this = this; - this.transport.on("connected", function () { return _this.onTransportConnected(); }); - this.transport.on("message", function (message) { return _this.onTransportReceiveMsg(message); }); - this.transport.on("transportError", function () { return _this.onTransportError(); }); - }; - /** - * Transport connection event. - * @event - * @param {SIP.Transport} transport. - */ - UA.prototype.onTransportConnected = function () { - var _this = this; - if (this.configuration.register) { - // In an effor to maintain behavior from when we "initialized" an - // authentication factory, this is in a Promise.then - Promise.resolve().then(function () { return _this.registerContext.register(); }); - } - }; - /** - * Handle SIP message received from the transport. - * @param messageString The message. - */ - UA.prototype.onTransportReceiveMsg = function (messageString) { - var _this = this; - var message = Parser_1.Parser.parseMessage(messageString, this.getLogger("sip.parser")); - if (!message) { - this.logger.warn("UA failed to parse incoming SIP message - discarding."); - return; - } - if (this.status === Enums_1.UAStatus.STATUS_USER_CLOSED && message instanceof core_1.IncomingRequestMessage) { - this.logger.warn("UA received message when status = USER_CLOSED - aborting"); - return; - } - // A valid SIP request formulated by a UAC MUST, at a minimum, contain - // the following header fields: To, From, CSeq, Call-ID, Max-Forwards, - // and Via; all of these header fields are mandatory in all SIP - // requests. - // https://tools.ietf.org/html/rfc3261#section-8.1.1 - var hasMinimumHeaders = function () { - var mandatoryHeaders = ["from", "to", "call_id", "cseq", "via"]; - for (var _i = 0, mandatoryHeaders_1 = mandatoryHeaders; _i < mandatoryHeaders_1.length; _i++) { - var header = mandatoryHeaders_1[_i]; - if (!message.hasHeader(header)) { - _this.logger.warn("Missing mandatory header field : " + header + "."); - return false; - } - } - return true; - }; - // Request Checks - if (message instanceof core_1.IncomingRequestMessage) { - // This is port of SanityCheck.minimumHeaders(). - if (!hasMinimumHeaders()) { - this.logger.warn("Request missing mandatory header field. Dropping."); - return; - } - // FIXME: This is non-standard and should be a configruable behavior (desirable regardless). - // Custom SIP.js check to reject request from ourself (this instance of SIP.js). - // This is port of SanityCheck.rfc3261_16_3_4(). - if (!message.toTag && message.callId.substr(0, 5) === this.configuration.sipjsId) { - this.userAgentCore.replyStateless(message, { statusCode: 482 }); - return; - } - // FIXME: This should be Transport check before we get here (Section 18). - // Custom SIP.js check to reject requests if body length wrong. - // This is port of SanityCheck.rfc3261_18_3_request(). - var len = Utils_1.Utils.str_utf8_length(message.body); - var contentLength = message.getHeader("content-length"); - if (contentLength && len < Number(contentLength)) { - this.userAgentCore.replyStateless(message, { statusCode: 400 }); - return; - } - } - // Reponse Checks - if (message instanceof core_1.IncomingResponseMessage) { - // This is port of SanityCheck.minimumHeaders(). - if (!hasMinimumHeaders()) { - this.logger.warn("Response missing mandatory header field. Dropping."); - return; - } - // Custom SIP.js check to drop responses if multiple Via headers. - // This is port of SanityCheck.rfc3261_8_1_3_3(). - if (message.getHeaders("via").length > 1) { - this.logger.warn("More than one Via header field present in the response. Dropping."); - return; - } - // FIXME: This should be Transport check before we get here (Section 18). - // Custom SIP.js check to drop responses if bad Via header. - // This is port of SanityCheck.rfc3261_18_1_2(). - if (message.via.host !== this.configuration.viaHost || message.via.port !== undefined) { - this.logger.warn("Via sent-by in the response does not match UA Via host value. Dropping."); - return; - } - // FIXME: This should be Transport check before we get here (Section 18). - // Custom SIP.js check to reject requests if body length wrong. - // This is port of SanityCheck.rfc3261_18_3_response(). - var len = Utils_1.Utils.str_utf8_length(message.body); - var contentLength = message.getHeader("content-length"); - if (contentLength && len < Number(contentLength)) { - this.logger.warn("Message body length is lower than the value in Content-Length header field. Dropping."); - return; - } - } - // Handle Request - if (message instanceof core_1.IncomingRequestMessage) { - this.userAgentCore.receiveIncomingRequestFromTransport(message); - return; - } - // Handle Response - if (message instanceof core_1.IncomingResponseMessage) { - this.userAgentCore.receiveIncomingResponseFromTransport(message); - return; - } - throw new Error("Invalid message type."); - }; - // ================= - // Utils - // ================= - UA.prototype.checkAuthenticationFactory = function (authenticationFactory) { - if (!(authenticationFactory instanceof Function)) { - return; - } - if (!authenticationFactory.initialize) { - authenticationFactory.initialize = function () { - return Promise.resolve(); - }; - } - return authenticationFactory; - }; - /** - * Configuration load. - * returns {void} - */ - UA.prototype.loadConfig = function (configuration) { - var _this = this; - // Settings and default values - var settings = { - /* Host address - * Value to be set in Via sent_by and host part of Contact FQDN - */ - viaHost: Utils_1.Utils.createRandomToken(12) + ".invalid", - uri: new core_1.URI("sip", "anonymous." + Utils_1.Utils.createRandomToken(6), "anonymous.invalid", undefined, undefined), - // Custom Configuration Settings - custom: {}, - // Display name - displayName: "", - // Password - password: undefined, - register: true, - // Registration parameters - registerOptions: {}, - // Transport related parameters - transportConstructor: Transport_1.Transport, - transportOptions: {}, - usePreloadedRoute: false, - // string to be inserted into User-Agent request header - userAgentString: Constants_1.C.USER_AGENT, - // Session parameters - noAnswerTimeout: 60, - // Hacks - hackViaTcp: false, - hackIpInContact: false, - hackWssInTransport: false, - hackAllowUnregisteredOptionTags: false, - // Session Description Handler Options - sessionDescriptionHandlerFactoryOptions: { - constraints: {}, - peerConnectionOptions: {} - }, - extraSupported: [], - contactName: Utils_1.Utils.createRandomToken(8), - contactTransport: "ws", - forceRport: false, - // autostarting - autostart: true, - autostop: true, - // Reliable Provisional Responses - rel100: Constants_1.C.supported.UNSUPPORTED, - // DTMF type: 'info' or 'rtp' (RFC 4733) - // RTP Payload Spec: https://tools.ietf.org/html/rfc4733 - // WebRTC Audio Spec: https://tools.ietf.org/html/rfc7874 - dtmfType: Constants_1.C.dtmfType.INFO, - // Replaces header (RFC 3891) - // http://tools.ietf.org/html/rfc3891 - replaces: Constants_1.C.supported.UNSUPPORTED, - sessionDescriptionHandlerFactory: SessionDescriptionHandler_1.SessionDescriptionHandler.defaultFactory, - authenticationFactory: this.checkAuthenticationFactory(function (ua) { - return new core_1.DigestAuthentication(ua.getLoggerFactory(), _this.configuration.authorizationUser, _this.configuration.password); - }), - allowLegacyNotifications: false, - allowOutOfDialogRefers: false, - experimentalFeatures: false - }; - var configCheck = this.getConfigurationCheck(); - // Check Mandatory parameters - for (var parameter in configCheck.mandatory) { - if (!configuration.hasOwnProperty(parameter)) { - throw new Exceptions_1.Exceptions.ConfigurationError(parameter); - } - else { - var value = configuration[parameter]; - var checkedValue = configCheck.mandatory[parameter](value); - if (checkedValue !== undefined) { - settings[parameter] = checkedValue; - } - else { - throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); - } - } - } - // Check Optional parameters - for (var parameter in configCheck.optional) { - if (configuration.hasOwnProperty(parameter)) { - var value = configuration[parameter]; - // If the parameter value is an empty array, but shouldn't be, apply its default value. - // If the parameter value is null, empty string, or undefined then apply its default value. - // If it's a number with NaN value then also apply its default value. - // NOTE: JS does not allow "value === NaN", the following does the work: - if ((value instanceof Array && value.length === 0) || - (value === null || value === "" || value === undefined) || - (typeof (value) === "number" && isNaN(value))) { - continue; - } - var checkedValue = configCheck.optional[parameter](value); - if (checkedValue !== undefined) { - settings[parameter] = checkedValue; - } - else { - throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); - } - } - } - // Post Configuration Process - // Allow passing 0 number as displayName. - if (settings.displayName === 0) { - settings.displayName = "0"; - } - // sipjsId instance parameter. Static random tag of length 5 - settings.sipjsId = Utils_1.Utils.createRandomToken(5); - // String containing settings.uri without scheme and user. - var hostportParams = settings.uri.clone(); - hostportParams.user = undefined; - settings.hostportParams = hostportParams.toRaw().replace(/^sip:/i, ""); - /* Check whether authorizationUser is explicitly defined. - * Take 'settings.uri.user' value if not. - */ - if (!settings.authorizationUser) { - settings.authorizationUser = settings.uri.user; - } - // User noAnswerTimeout - settings.noAnswerTimeout = settings.noAnswerTimeout * 1000; - // Via Host - if (settings.hackIpInContact) { - if (typeof settings.hackIpInContact === "boolean") { - var from = 1; - var to = 254; - var octet = Math.floor(Math.random() * (to - from + 1) + from); - // random Test-Net IP (http://tools.ietf.org/html/rfc5735) - settings.viaHost = "192.0.2." + octet; - } - else if (typeof settings.hackIpInContact === "string") { - settings.viaHost = settings.hackIpInContact; - } - } - // Contact transport parameter - if (settings.hackWssInTransport) { - settings.contactTransport = "wss"; - } - this.contact = { - pubGruu: undefined, - tempGruu: undefined, - uri: new core_1.URI("sip", settings.contactName, settings.viaHost, undefined, { transport: settings.contactTransport }), - toString: function (options) { - if (options === void 0) { options = {}; } - var anonymous = options.anonymous || false; - var outbound = options.outbound || false; - var contact = "<"; - if (anonymous) { - contact += (_this.contact.tempGruu || - ("sip:anonymous@anonymous.invalid;transport=" + settings.contactTransport)).toString(); - } - else { - contact += (_this.contact.pubGruu || _this.contact.uri).toString(); - } - if (outbound) { - contact += ";ob"; - } - contact += ">"; - return contact; - } - }; - var skeleton = {}; - // Fill the value of the configuration_skeleton - for (var parameter in settings) { - if (settings.hasOwnProperty(parameter)) { - skeleton[parameter] = settings[parameter]; - } - } - Object.assign(this.configuration, skeleton); - this.logger.log("configuration parameters after validation:"); - for (var parameter in settings) { - if (settings.hasOwnProperty(parameter)) { - switch (parameter) { - case "uri": - case "sessionDescriptionHandlerFactory": - this.logger.log("· " + parameter + ": " + settings[parameter]); - break; - case "password": - this.logger.log("· " + parameter + ": " + "NOT SHOWN"); - break; - case "transportConstructor": - this.logger.log("· " + parameter + ": " + settings[parameter].name); - break; - default: - this.logger.log("· " + parameter + ": " + JSON.stringify(settings[parameter])); - } - } - } - return; - }; - /** - * Configuration checker. - * @return {Boolean} - */ - UA.prototype.getConfigurationCheck = function () { - return { - mandatory: {}, - optional: { - uri: function (uri) { - if (!(/^sip:/i).test(uri)) { - uri = Constants_1.C.SIP + ":" + uri; - } - var parsed = core_1.Grammar.URIParse(uri); - if (!parsed || !parsed.user) { - return; - } - else { - return parsed; - } - }, - transportConstructor: function (transportConstructor) { - if (transportConstructor instanceof Function) { - return transportConstructor; - } - }, - transportOptions: function (transportOptions) { - if (typeof transportOptions === "object") { - return transportOptions; - } - }, - authorizationUser: function (authorizationUser) { - if (core_1.Grammar.parse('"' + authorizationUser + '"', "quoted_string") === -1) { - return; - } - else { - return authorizationUser; - } - }, - displayName: function (displayName) { - if (core_1.Grammar.parse('"' + displayName + '"', "displayName") === -1) { - return; - } - else { - return displayName; - } - }, - dtmfType: function (dtmfType) { - switch (dtmfType) { - case Constants_1.C.dtmfType.RTP: - return Constants_1.C.dtmfType.RTP; - case Constants_1.C.dtmfType.INFO: - // Fall through - default: - return Constants_1.C.dtmfType.INFO; - } - }, - hackViaTcp: function (hackViaTcp) { - if (typeof hackViaTcp === "boolean") { - return hackViaTcp; - } - }, - hackIpInContact: function (hackIpInContact) { - if (typeof hackIpInContact === "boolean") { - return hackIpInContact; - } - else if (typeof hackIpInContact === "string" && core_1.Grammar.parse(hackIpInContact, "host") !== -1) { - return hackIpInContact; - } - }, - hackWssInTransport: function (hackWssInTransport) { - if (typeof hackWssInTransport === "boolean") { - return hackWssInTransport; - } - }, - hackAllowUnregisteredOptionTags: function (hackAllowUnregisteredOptionTags) { - if (typeof hackAllowUnregisteredOptionTags === "boolean") { - return hackAllowUnregisteredOptionTags; - } - }, - contactTransport: function (contactTransport) { - if (typeof contactTransport === "string") { - return contactTransport; - } - }, - extraSupported: function (optionTags) { - if (!(optionTags instanceof Array)) { - return; - } - for (var _i = 0, optionTags_1 = optionTags; _i < optionTags_1.length; _i++) { - var tag = optionTags_1[_i]; - if (typeof tag !== "string") { - return; - } - } - return optionTags; - }, - forceRport: function (forceRport) { - if (typeof forceRport === "boolean") { - return forceRport; - } - }, - noAnswerTimeout: function (noAnswerTimeout) { - if (Utils_1.Utils.isDecimal(noAnswerTimeout)) { - var value = Number(noAnswerTimeout); - if (value > 0) { - return value; - } - } - }, - password: function (password) { - return String(password); - }, - rel100: function (rel100) { - if (rel100 === Constants_1.C.supported.REQUIRED) { - return Constants_1.C.supported.REQUIRED; - } - else if (rel100 === Constants_1.C.supported.SUPPORTED) { - return Constants_1.C.supported.SUPPORTED; - } - else { - return Constants_1.C.supported.UNSUPPORTED; - } - }, - replaces: function (replaces) { - if (replaces === Constants_1.C.supported.REQUIRED) { - return Constants_1.C.supported.REQUIRED; - } - else if (replaces === Constants_1.C.supported.SUPPORTED) { - return Constants_1.C.supported.SUPPORTED; - } - else { - return Constants_1.C.supported.UNSUPPORTED; - } - }, - register: function (register) { - if (typeof register === "boolean") { - return register; - } - }, - registerOptions: function (registerOptions) { - if (typeof registerOptions === "object") { - return registerOptions; - } - }, - usePreloadedRoute: function (usePreloadedRoute) { - if (typeof usePreloadedRoute === "boolean") { - return usePreloadedRoute; - } - }, - userAgentString: function (userAgentString) { - if (typeof userAgentString === "string") { - return userAgentString; - } - }, - autostart: function (autostart) { - if (typeof autostart === "boolean") { - return autostart; - } - }, - autostop: function (autostop) { - if (typeof autostop === "boolean") { - return autostop; - } - }, - sessionDescriptionHandlerFactory: function (sessionDescriptionHandlerFactory) { - if (sessionDescriptionHandlerFactory instanceof Function) { - return sessionDescriptionHandlerFactory; - } - }, - sessionDescriptionHandlerFactoryOptions: function (options) { - if (typeof options === "object") { - return options; - } - }, - authenticationFactory: this.checkAuthenticationFactory, - allowLegacyNotifications: function (allowLegacyNotifications) { - if (typeof allowLegacyNotifications === "boolean") { - return allowLegacyNotifications; - } - }, - custom: function (custom) { - if (typeof custom === "object") { - return custom; - } - }, - contactName: function (contactName) { - if (typeof contactName === "string") { - return contactName; - } - }, - experimentalFeatures: function (experimentalFeatures) { - if (typeof experimentalFeatures === "boolean") { - return experimentalFeatures; - } - }, - } - }; - }; - UA.C = { - // UA status codes - STATUS_INIT: 0, - STATUS_STARTING: 1, - STATUS_READY: 2, - STATUS_USER_CLOSED: 3, - STATUS_NOT_READY: 4, - // UA error codes - CONFIGURATION_ERROR: 1, - NETWORK_ERROR: 2, - ALLOWED_METHODS: [ - "ACK", - "CANCEL", - "INVITE", - "MESSAGE", - "BYE", - "OPTIONS", - "INFO", - "NOTIFY", - "REFER" - ], - ACCEPTED_BODY_TYPES: [ - "application/sdp", - "application/dtmf-relay" - ], - MAX_FORWARDS: 70, - TAG_LENGTH: 10 - }; - return UA; -}(events_1.EventEmitter)); -exports.UA = UA; -(function (UA) { - var DtmfType; - (function (DtmfType) { - DtmfType["RTP"] = "rtp"; - DtmfType["INFO"] = "info"; - })(DtmfType = UA.DtmfType || (UA.DtmfType = {})); -})(UA = exports.UA || (exports.UA = {})); -exports.UA = UA; -/** - * Factory function to generate configuration give a UA. - * @param ua UA - */ -function makeUserAgentCoreConfigurationFromUA(ua) { - // FIXME: Configuration URI is a bad mix of types currently. It also needs to exist. - if (!(ua.configuration.uri instanceof core_1.URI)) { - throw new Error("Configuration URI not instance of URI."); - } - var aor = ua.configuration.uri; - var contact = ua.contact; - var displayName = ua.configuration.displayName ? ua.configuration.displayName : ""; - var hackViaTcp = ua.configuration.hackViaTcp ? true : false; - var routeSet = ua.configuration.usePreloadedRoute && ua.transport.server && ua.transport.server.sipUri ? - [ua.transport.server.sipUri] : - []; - var sipjsId = ua.configuration.sipjsId || Utils_1.Utils.createRandomToken(5); - var supportedOptionTags = []; - supportedOptionTags.push("outbound"); // TODO: is this really supported? - if (ua.configuration.rel100 === Constants_1.C.supported.SUPPORTED) { - supportedOptionTags.push("100rel"); - } - if (ua.configuration.replaces === Constants_1.C.supported.SUPPORTED) { - supportedOptionTags.push("replaces"); - } - if (ua.configuration.extraSupported) { - supportedOptionTags.push.apply(supportedOptionTags, ua.configuration.extraSupported); - } - if (!ua.configuration.hackAllowUnregisteredOptionTags) { - supportedOptionTags = supportedOptionTags.filter(function (optionTag) { return Constants_1.C.OPTION_TAGS[optionTag]; }); - } - supportedOptionTags = Array.from(new Set(supportedOptionTags)); // array of unique values - var supportedOptionTagsResponse = ua.getSupportedResponseOptions(); - var userAgentHeaderFieldValue = ua.configuration.userAgentString || "sipjs"; - if (!(ua.configuration.viaHost)) { - throw new Error("Configuration via host undefined"); - } - var viaForceRport = ua.configuration.forceRport ? true : false; - var viaHost = ua.configuration.viaHost; - var configuration = { - aor: aor, - contact: contact, - displayName: displayName, - hackViaTcp: hackViaTcp, - loggerFactory: ua.getLoggerFactory(), - routeSet: routeSet, - sipjsId: sipjsId, - supportedOptionTags: supportedOptionTags, - supportedOptionTagsResponse: supportedOptionTagsResponse, - userAgentHeaderFieldValue: userAgentHeaderFieldValue, - viaForceRport: viaForceRport, - viaHost: viaHost, - authenticationFactory: function () { - if (ua.configuration.authenticationFactory) { - return ua.configuration.authenticationFactory(ua); - } - return undefined; - }, - transportAccessor: function () { return ua.transport; } - }; - return configuration; -} -exports.makeUserAgentCoreConfigurationFromUA = makeUserAgentCoreConfigurationFromUA; - - -/***/ }), -/* 94 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var events_1 = __webpack_require__(30); -var session_1 = __webpack_require__(95); -var Enums_1 = __webpack_require__(82); -var Exceptions_1 = __webpack_require__(84); -var Utils_1 = __webpack_require__(83); -var Modifiers = tslib_1.__importStar(__webpack_require__(101)); -var SessionDescriptionHandlerObserver_1 = __webpack_require__(102); -/* SessionDescriptionHandler - * @class PeerConnection helper Class. - * @param {SIP.Session} session - * @param {Object} [options] - */ -var SessionDescriptionHandler = /** @class */ (function (_super) { - tslib_1.__extends(SessionDescriptionHandler, _super); - function SessionDescriptionHandler(logger, observer, options) { - var _this = _super.call(this) || this; - _this.type = Enums_1.TypeStrings.SessionDescriptionHandler; - // TODO: Validate the options - _this.options = options || {}; - _this.logger = logger; - _this.observer = observer; - _this.dtmfSender = undefined; - _this.shouldAcquireMedia = true; - _this.CONTENT_TYPE = "application/sdp"; - _this.C = { - DIRECTION: { - NULL: null, - SENDRECV: "sendrecv", - SENDONLY: "sendonly", - RECVONLY: "recvonly", - INACTIVE: "inactive" - } - }; - _this.logger.log("SessionDescriptionHandlerOptions: " + JSON.stringify(_this.options)); - _this.direction = _this.C.DIRECTION.NULL; - _this.modifiers = _this.options.modifiers || []; - if (!Array.isArray(_this.modifiers)) { - _this.modifiers = [_this.modifiers]; - } - _this.iceGatheringTimeout = false; - _this.initPeerConnection(_this.options.peerConnectionOptions); - _this.constraints = _this.checkAndDefaultConstraints(_this.options.constraints); - return _this; - } - /** - * @param {SIP.Session} session - * @param {Object} [options] - */ - SessionDescriptionHandler.defaultFactory = function (session, options) { - var logger = (session instanceof session_1.Session) ? - session.userAgent.getLogger("sip.sessionDescriptionHandler", session.id) : - session.ua.getLogger("sip.invitecontext.sessionDescriptionHandler", session.id); - var observer = new SessionDescriptionHandlerObserver_1.SessionDescriptionHandlerObserver(session, options); - return new SessionDescriptionHandler(logger, observer, options); - }; - // Functions the sesssion can use - /** - * Destructor - */ - SessionDescriptionHandler.prototype.close = function () { - this.logger.log("closing PeerConnection"); - // have to check signalingState since this.close() gets called multiple times - if (this.peerConnection && this.peerConnection.signalingState !== "closed") { - if (this.peerConnection.getSenders) { - this.peerConnection.getSenders().forEach(function (sender) { - if (sender.track) { - sender.track.stop(); - } - }); - } - else { - this.logger.warn("Using getLocalStreams which is deprecated"); - this.peerConnection.getLocalStreams().forEach(function (stream) { - stream.getTracks().forEach(function (track) { - track.stop(); - }); - }); - } - if (this.peerConnection.getReceivers) { - this.peerConnection.getReceivers().forEach(function (receiver) { - if (receiver.track) { - receiver.track.stop(); - } - }); - } - else { - this.logger.warn("Using getRemoteStreams which is deprecated"); - this.peerConnection.getRemoteStreams().forEach(function (stream) { - stream.getTracks().forEach(function (track) { - track.stop(); - }); - }); - } - this.resetIceGatheringComplete(); - this.peerConnection.close(); - } - }; - /** - * Gets the local description from the underlying media implementation - * @param {Object} [options] Options object to be used by getDescription - * @param {MediaStreamConstraints} [options.constraints] MediaStreamConstraints - * https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints - * @param {Object} [options.peerConnectionOptions] If this is set it will recreate the peer - * connection with the new options - * @param {Array} [modifiers] Array with one time use description modifiers - * @returns {Promise} Promise that resolves with the local description to be used for the session - */ - SessionDescriptionHandler.prototype.getDescription = function (options, modifiers) { - var _this = this; - if (options === void 0) { options = {}; } - if (modifiers === void 0) { modifiers = []; } - if (options.peerConnectionOptions) { - this.initPeerConnection(options.peerConnectionOptions); - } - // Merge passed constraints with saved constraints and save - var newConstraints = Object.assign({}, this.constraints, options.constraints); - newConstraints = this.checkAndDefaultConstraints(newConstraints); - if (JSON.stringify(newConstraints) !== JSON.stringify(this.constraints)) { - this.constraints = newConstraints; - this.shouldAcquireMedia = true; - } - if (!Array.isArray(modifiers)) { - modifiers = [modifiers]; - } - modifiers = modifiers.concat(this.modifiers); - return Promise.resolve().then(function () { - if (_this.shouldAcquireMedia) { - return _this.acquire(_this.constraints).then(function () { - _this.shouldAcquireMedia = false; - }); - } - }).then(function () { return _this.createOfferOrAnswer(options.RTCOfferOptions, modifiers); }) - .then(function (description) { - if (description.sdp === undefined) { - throw new Exceptions_1.Exceptions.SessionDescriptionHandlerError("getDescription", undefined, "SDP undefined"); - } - _this.emit("getDescription", description); - return { - body: description.sdp, - contentType: _this.CONTENT_TYPE - }; - }); - }; - /** - * Check if the Session Description Handler can handle the Content-Type described by a SIP Message - * @param {String} contentType The content type that is in the SIP Message - * @returns {boolean} - */ - SessionDescriptionHandler.prototype.hasDescription = function (contentType) { - return contentType === this.CONTENT_TYPE; - }; - /** - * The modifier that should be used when the session would like to place the call on hold - * @param {String} [sdp] The description that will be modified - * @returns {Promise} Promise that resolves with modified SDP - */ - SessionDescriptionHandler.prototype.holdModifier = function (description) { - if (!description.sdp) { - return Promise.resolve(description); - } - if (!(/a=(sendrecv|sendonly|recvonly|inactive)/).test(description.sdp)) { - description.sdp = description.sdp.replace(/(m=[^\r]*\r\n)/g, "$1a=sendonly\r\n"); - } - else { - description.sdp = description.sdp.replace(/a=sendrecv\r\n/g, "a=sendonly\r\n"); - description.sdp = description.sdp.replace(/a=recvonly\r\n/g, "a=inactive\r\n"); - } - return Promise.resolve(description); - }; - /** - * Set the remote description to the underlying media implementation - * @param {String} sessionDescription The description provided by a SIP message to be set on the media implementation - * @param {Object} [options] Options object to be used by getDescription - * @param {MediaStreamConstraints} [options.constraints] MediaStreamConstraints - * https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints - * @param {Object} [options.peerConnectionOptions] If this is set it will recreate the peer - * connection with the new options - * @param {Array} [modifiers] Array with one time use description modifiers - * @returns {Promise} Promise that resolves once the description is set - */ - SessionDescriptionHandler.prototype.setDescription = function (sessionDescription, options, modifiers) { - var _this = this; - if (options === void 0) { options = {}; } - if (modifiers === void 0) { modifiers = []; } - if (options.peerConnectionOptions) { - this.initPeerConnection(options.peerConnectionOptions); - } - if (!Array.isArray(modifiers)) { - modifiers = [modifiers]; - } - modifiers = modifiers.concat(this.modifiers); - var description = { - type: this.hasOffer("local") ? "answer" : "offer", - sdp: sessionDescription - }; - return Promise.resolve().then(function () { - // Media should be acquired in getDescription unless we need to do it sooner for some reason (FF61+) - if (_this.shouldAcquireMedia && _this.options.alwaysAcquireMediaFirst) { - return _this.acquire(_this.constraints).then(function () { - _this.shouldAcquireMedia = false; - }); - } - }).then(function () { return Utils_1.Utils.reducePromises(modifiers, description); }) - .catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("setDescription", e, "The modifiers did not resolve successfully"); - _this.logger.error(error.message); - _this.emit("peerConnection-setRemoteDescriptionFailed", error); - throw error; - }).then(function (modifiedDescription) { - _this.emit("setDescription", modifiedDescription); - return _this.peerConnection.setRemoteDescription(modifiedDescription); - }).catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - // Check the original SDP for video, and ensure that we have want to do audio fallback - if ((/^m=video.+$/gm).test(sessionDescription) && !options.disableAudioFallback) { - // Do not try to audio fallback again - options.disableAudioFallback = true; - // Remove video first, then do the other modifiers - return _this.setDescription(sessionDescription, options, [Modifiers.stripVideo].concat(modifiers)); - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("setDescription", e); - if (error.error) { - _this.logger.error(error.error); - } - _this.emit("peerConnection-setRemoteDescriptionFailed", error); - throw error; - }).then(function () { - if (_this.peerConnection.getReceivers) { - _this.emit("setRemoteDescription", _this.peerConnection.getReceivers()); - } - else { - _this.emit("setRemoteDescription", _this.peerConnection.getRemoteStreams()); - } - _this.emit("confirmed", _this); - }); - }; - /** - * Send DTMF via RTP (RFC 4733) - * @param {String} tones A string containing DTMF digits - * @param {Object} [options] Options object to be used by sendDtmf - * @returns {boolean} true if DTMF send is successful, false otherwise - */ - SessionDescriptionHandler.prototype.sendDtmf = function (tones, options) { - if (options === void 0) { options = {}; } - if (!this.dtmfSender && this.hasBrowserGetSenderSupport()) { - var senders = this.peerConnection.getSenders(); - if (senders.length > 0) { - this.dtmfSender = senders[0].dtmf; - } - } - if (!this.dtmfSender && this.hasBrowserTrackSupport()) { - var streams = this.peerConnection.getLocalStreams(); - if (streams.length > 0) { - var audioTracks = streams[0].getAudioTracks(); - if (audioTracks.length > 0) { - this.dtmfSender = this.peerConnection.createDTMFSender(audioTracks[0]); - } - } - } - if (!this.dtmfSender) { - return false; - } - try { - this.dtmfSender.insertDTMF(tones, options.duration, options.interToneGap); - } - catch (e) { - if (e.type === "InvalidStateError" || e.type === "InvalidCharacterError") { - this.logger.error(e); - return false; - } - else { - throw e; - } - } - this.logger.log("DTMF sent via RTP: " + tones.toString()); - return true; - }; - /** - * Get the direction of the session description - * @returns {String} direction of the description - */ - SessionDescriptionHandler.prototype.getDirection = function () { - return this.direction; - }; - SessionDescriptionHandler.prototype.on = function (name, callback) { return _super.prototype.on.call(this, name, callback); }; - SessionDescriptionHandler.prototype.getMediaStream = function (constraints) { - return navigator.mediaDevices.getUserMedia(constraints); - }; - // Internal functions - SessionDescriptionHandler.prototype.createOfferOrAnswer = function (RTCOfferOptions, modifiers) { - var _this = this; - if (RTCOfferOptions === void 0) { RTCOfferOptions = {}; } - if (modifiers === void 0) { modifiers = []; } - var methodName = this.hasOffer("remote") ? "createAnswer" : "createOffer"; - var pc = this.peerConnection; - this.logger.log(methodName); - var method = this.hasOffer("remote") ? pc.createAnswer : pc.createOffer; - return method.apply(pc, RTCOfferOptions).catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer", e, "peerConnection-" + methodName + "Failed"); - _this.emit("peerConnection-" + methodName + "Failed", error); - throw error; - }).then(function (sdp) { - return Utils_1.Utils.reducePromises(modifiers, _this.createRTCSessionDescriptionInit(sdp)); - }).then(function (sdp) { - _this.resetIceGatheringComplete(); - _this.logger.log("Setting local sdp."); - _this.logger.log("sdp is " + sdp.sdp || false); - return pc.setLocalDescription(sdp); - }).catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer", e, "peerConnection-SetLocalDescriptionFailed"); - _this.emit("peerConnection-SetLocalDescriptionFailed", error); - throw error; - }).then(function () { return _this.waitForIceGatheringComplete(); }) - .then(function () { - if (!_this.peerConnection.localDescription) { - throw new Exceptions_1.Exceptions.SessionDescriptionHandlerError("Missing local description"); - } - var localDescription = _this.createRTCSessionDescriptionInit(_this.peerConnection.localDescription); - return Utils_1.Utils.reducePromises(modifiers, localDescription); - }).then(function (localDescription) { - _this.setDirection(localDescription.sdp || ""); - return localDescription; - }).catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer", e); - _this.logger.error(error.toString()); - throw error; - }); - }; - // Creates an RTCSessionDescriptionInit from an RTCSessionDescription - SessionDescriptionHandler.prototype.createRTCSessionDescriptionInit = function (RTCSessionDescription) { - return { - type: RTCSessionDescription.type, - sdp: RTCSessionDescription.sdp - }; - }; - SessionDescriptionHandler.prototype.addDefaultIceCheckingTimeout = function (peerConnectionOptions) { - if (peerConnectionOptions.iceCheckingTimeout === undefined) { - peerConnectionOptions.iceCheckingTimeout = 5000; - } - return peerConnectionOptions; - }; - SessionDescriptionHandler.prototype.addDefaultIceServers = function (rtcConfiguration) { - if (!rtcConfiguration.iceServers) { - rtcConfiguration.iceServers = [{ urls: "stun:stun.l.google.com:19302" }]; - } - return rtcConfiguration; - }; - SessionDescriptionHandler.prototype.checkAndDefaultConstraints = function (constraints) { - var defaultConstraints = { audio: true, video: !this.options.alwaysAcquireMediaFirst }; - constraints = constraints || defaultConstraints; - // Empty object check - if (Object.keys(constraints).length === 0 && constraints.constructor === Object) { - return defaultConstraints; - } - return constraints; - }; - SessionDescriptionHandler.prototype.hasBrowserTrackSupport = function () { - return Boolean(this.peerConnection.addTrack); - }; - SessionDescriptionHandler.prototype.hasBrowserGetSenderSupport = function () { - return Boolean(this.peerConnection.getSenders); - }; - SessionDescriptionHandler.prototype.initPeerConnection = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - options = this.addDefaultIceCheckingTimeout(options); - options.rtcConfiguration = options.rtcConfiguration || {}; - options.rtcConfiguration = this.addDefaultIceServers(options.rtcConfiguration); - this.logger.log("initPeerConnection"); - if (this.peerConnection) { - this.logger.log("Already have a peer connection for this session. Tearing down."); - this.resetIceGatheringComplete(); - this.peerConnection.close(); - } - this.peerConnection = new RTCPeerConnection(options.rtcConfiguration); - this.logger.log("New peer connection created"); - if ("ontrack" in this.peerConnection) { - this.peerConnection.addEventListener("track", function (e) { - _this.logger.log("track added"); - _this.observer.trackAdded(); - _this.emit("addTrack", e); - }); - } - else { - this.logger.warn("Using onaddstream which is deprecated"); - this.peerConnection.onaddstream = function (e) { - _this.logger.log("stream added"); - _this.emit("addStream", e); - }; - } - this.peerConnection.onicecandidate = function (e) { - _this.emit("iceCandidate", e); - if (e.candidate) { - _this.logger.log("ICE candidate received: " + - (e.candidate.candidate === null ? null : e.candidate.candidate.trim())); - } - else if (e.candidate === null) { - // indicates the end of candidate gathering - _this.logger.log("ICE candidate gathering complete"); - _this.triggerIceGatheringComplete(); - } - }; - this.peerConnection.onicegatheringstatechange = function () { - _this.logger.log("RTCIceGatheringState changed: " + _this.peerConnection.iceGatheringState); - switch (_this.peerConnection.iceGatheringState) { - case "gathering": - _this.emit("iceGathering", _this); - if (!_this.iceGatheringTimer && options.iceCheckingTimeout) { - _this.iceGatheringTimeout = false; - _this.iceGatheringTimer = setTimeout(function () { - _this.logger.log("RTCIceChecking Timeout Triggered after " + options.iceCheckingTimeout + " milliseconds"); - _this.iceGatheringTimeout = true; - _this.triggerIceGatheringComplete(); - }, options.iceCheckingTimeout); - } - break; - case "complete": - _this.triggerIceGatheringComplete(); - break; - } - }; - this.peerConnection.oniceconnectionstatechange = function () { - var stateEvent; - switch (_this.peerConnection.iceConnectionState) { - case "new": - stateEvent = "iceConnection"; - break; - case "checking": - stateEvent = "iceConnectionChecking"; - break; - case "connected": - stateEvent = "iceConnectionConnected"; - break; - case "completed": - stateEvent = "iceConnectionCompleted"; - break; - case "failed": - stateEvent = "iceConnectionFailed"; - break; - case "disconnected": - stateEvent = "iceConnectionDisconnected"; - break; - case "closed": - stateEvent = "iceConnectionClosed"; - break; - default: - _this.logger.warn("Unknown iceConnection state: " + _this.peerConnection.iceConnectionState); - return; - } - _this.logger.log("ICE Connection State changed to " + stateEvent); - _this.emit(stateEvent, _this); - }; - }; - SessionDescriptionHandler.prototype.acquire = function (constraints) { - var _this = this; - // Default audio & video to true - constraints = this.checkAndDefaultConstraints(constraints); - return new Promise(function (resolve, reject) { - /* - * Make the call asynchronous, so that ICCs have a chance - * to define callbacks to `userMediaRequest` - */ - _this.logger.log("acquiring local media"); - _this.emit("userMediaRequest", constraints); - if (constraints.audio || constraints.video) { - _this.getMediaStream(constraints).then(function (streams) { - _this.observer.trackAdded(); - _this.emit("userMedia", streams); - resolve(streams); - }).catch(function (e) { - _this.emit("userMediaFailed", e); - reject(e); - }); - } - else { - // Local streams were explicitly excluded. - resolve([]); - } - }).catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("acquire", e, "unable to acquire streams"); - _this.logger.error(error.message); - if (error.error) { - _this.logger.error(error.error); - } - throw error; - }).then(function (streams) { - _this.logger.log("acquired local media streams"); - // Remove old tracks - if (_this.peerConnection.removeTrack) { - _this.peerConnection.getSenders().forEach(function (sender) { - _this.peerConnection.removeTrack(sender); - }); - } - return streams; - }).catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("acquire", e, "error removing streams"); - _this.logger.error(error.message); - if (error.error) { - _this.logger.error(error.error); - } - throw error; - }).then(function (streams) { - var streamsArr = [].concat(streams); - streamsArr.forEach(function (stream) { - if (_this.peerConnection.addTrack) { - stream.getTracks().forEach(function (track) { - _this.peerConnection.addTrack(track, stream); - }); - } - else { - // Chrome 59 does not support addTrack - _this.peerConnection.addStream(stream); - } - }); - return Promise.resolve(); - }).catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("acquire", e, "error adding stream"); - _this.logger.error(error.message); - if (error.error) { - _this.logger.error(error.error); - } - throw error; - }); - }; - SessionDescriptionHandler.prototype.hasOffer = function (where) { - var offerState = "have-" + where + "-offer"; - return this.peerConnection.signalingState === offerState; - }; - // ICE gathering state handling - SessionDescriptionHandler.prototype.isIceGatheringComplete = function () { - return this.peerConnection.iceGatheringState === "complete" || this.iceGatheringTimeout; - }; - SessionDescriptionHandler.prototype.resetIceGatheringComplete = function () { - this.iceGatheringTimeout = false; - this.logger.log("resetIceGatheringComplete"); - if (this.iceGatheringTimer) { - clearTimeout(this.iceGatheringTimer); - this.iceGatheringTimer = undefined; - } - if (this.iceGatheringDeferred) { - this.iceGatheringDeferred.reject(); - this.iceGatheringDeferred = undefined; - } - }; - SessionDescriptionHandler.prototype.setDirection = function (sdp) { - var match = sdp.match(/a=(sendrecv|sendonly|recvonly|inactive)/); - if (match === null) { - this.direction = this.C.DIRECTION.NULL; - this.observer.directionChanged(); - return; - } - var direction = match[1]; - switch (direction) { - case this.C.DIRECTION.SENDRECV: - case this.C.DIRECTION.SENDONLY: - case this.C.DIRECTION.RECVONLY: - case this.C.DIRECTION.INACTIVE: - this.direction = direction; - break; - default: - this.direction = this.C.DIRECTION.NULL; - break; - } - this.observer.directionChanged(); - }; - SessionDescriptionHandler.prototype.triggerIceGatheringComplete = function () { - if (this.isIceGatheringComplete()) { - this.emit("iceGatheringComplete", this); - if (this.iceGatheringTimer) { - clearTimeout(this.iceGatheringTimer); - this.iceGatheringTimer = undefined; - } - if (this.iceGatheringDeferred) { - this.iceGatheringDeferred.resolve(); - this.iceGatheringDeferred = undefined; - } - } - }; - SessionDescriptionHandler.prototype.waitForIceGatheringComplete = function () { - this.logger.log("waitForIceGatheringComplete"); - if (this.isIceGatheringComplete()) { - this.logger.log("ICE is already complete. Return resolved."); - return Promise.resolve(); - } - else if (!this.iceGatheringDeferred) { - this.iceGatheringDeferred = Utils_1.Utils.defer(); - } - this.logger.log("ICE is not complete. Returning promise"); - return this.iceGatheringDeferred ? this.iceGatheringDeferred.promise : Promise.resolve(); - }; - return SessionDescriptionHandler; -}(events_1.EventEmitter)); -exports.SessionDescriptionHandler = SessionDescriptionHandler; - - -/***/ }), -/* 95 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var events_1 = __webpack_require__(30); -var Constants_1 = __webpack_require__(80); -var core_1 = __webpack_require__(2); -var allowed_methods_1 = __webpack_require__(58); -var Enums_1 = __webpack_require__(82); -var Exceptions_1 = __webpack_require__(84); -var Utils_1 = __webpack_require__(83); -var emitter_1 = __webpack_require__(96); -var info_1 = __webpack_require__(97); -var notification_1 = __webpack_require__(98); -var referral_1 = __webpack_require__(99); -var session_state_1 = __webpack_require__(100); -/** - * A session provides real time communication between one or more participants. - * @public - */ -var Session = /** @class */ (function (_super) { - tslib_1.__extends(Session, _super); - /** - * Constructor. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @internal - */ - function Session(userAgent, options) { - if (options === void 0) { options = {}; } - var _this = _super.call(this) || this; - // Property overlap with ClientContext & ServerContext Interfaces - /** @internal */ - _this.type = Enums_1.TypeStrings.Session; - /** @internal */ - _this.method = Constants_1.C.INVITE; - /** @internal */ - _this.localHold = false; - /** DEPRECATED: Session status */ - /** @internal */ - _this.status = Enums_1.SessionStatus.STATUS_NULL; - /** True if an error caused session termination. */ - /** @internal */ - _this.isFailed = false; - /** @internal */ - _this.rel100 = Constants_1.C.supported.UNSUPPORTED; - /** @internal */ - _this.expiresTimer = undefined; - /** @internal */ - _this.userNoAnswerTimer = undefined; - _this._state = session_state_1.SessionState.Initial; - _this._stateEventEmitter = new events_1.EventEmitter(); - _this.pendingReinvite = false; - _this.tones = undefined; - _this.userAgent = userAgent; - _this.delegate = options.delegate; - _this.logger = userAgent.getLogger("sip.session"); - _this.errorListener = _this.onTransportError.bind(_this); - if (userAgent.transport) { - userAgent.transport.on("transportError", _this.errorListener); - } - return _this; - } - /** - * @deprecated Legacy state transition. - * @internal - */ - Session.prototype.on = function (name, callback) { - return _super.prototype.on.call(this, name, callback); - }; - /** - * @deprecated Legacy state transition. - * @internal - */ - Session.prototype.emit = function (event) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - return _super.prototype.emit.apply(this, [event].concat(args)); - }; - Object.defineProperty(Session.prototype, "sessionDescriptionHandler", { - /** - * Session description handler. - */ - get: function () { - return this._sessionDescriptionHandler; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Session.prototype, "sessionDescriptionHandlerFactory", { - /** - * Session description handler factory. - */ - get: function () { - return this.userAgent.configuration.sessionDescriptionHandlerFactory; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Session.prototype, "state", { - /** - * Session state. - */ - get: function () { - return this._state; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Session.prototype, "stateChange", { - /** - * Session state change emitter. - */ - get: function () { - return emitter_1.makeEmitter(this._stateEventEmitter); - }, - enumerable: true, - configurable: true - }); - /** - * Renegotiate the session. Sends a re-INVITE. - * @param options - Options bucket. - */ - Session.prototype.invite = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - this.logger.log("Session.invite"); - if (this.state !== session_state_1.SessionState.Established) { - return Promise.reject(new Error("Invalid session state " + this.state)); - } - if (this.pendingReinvite) { - return Promise.reject(new Error("Reinvite in progress. Please wait until complete, then try again.")); - } - if (!this._sessionDescriptionHandler) { - throw new Error("Session description handler undefined."); - } - this.pendingReinvite = true; - var delegate = { - onAccept: function (response) { - // A re-INVITE transaction has an offer/answer [RFC3264] exchange - // associated with it. The UAC (User Agent Client) generating a given - // re-INVITE can act as the offerer or as the answerer. A UAC willing - // to act as the offerer includes an offer in the re-INVITE. The UAS - // (User Agent Server) then provides an answer in a response to the - // re-INVITE. A UAC willing to act as answerer does not include an - // offer in the re-INVITE. The UAS then provides an offer in a response - // to the re-INVITE becoming, thus, the offerer. - // https://tools.ietf.org/html/rfc6141#section-1 - var body = core_1.getBody(response.message); - if (!body) { - // No way to recover, so terminate session and mark as failed. - _this.logger.error("Received 2xx response to re-INVITE without a session description"); - _this.ackAndBye(response, 400, "Missing session description"); - _this.stateTransition(session_state_1.SessionState.Terminated); - _this.isFailed = true; - _this.pendingReinvite = false; - return; - } - if (options.withoutSdp) { - // INVITE without SDP - set remote offer and send an answer in the ACK - // FIXME: SDH options & SDH modifiers options are applied somewhat ambiguously - // This behavior was ported from legacy code and the issue punted down the road. - var answerOptions = { - sessionDescriptionHandlerOptions: options.sessionDescriptionHandlerOptions, - sessionDescriptionHandlerModifiers: options.sessionDescriptionHandlerModifiers - }; - _this.setOfferAndGetAnswer(body, answerOptions) - .then(function (answerBody) { - var request = response.ack({ body: answerBody }); - }) - .catch(function (error) { - // No way to recover, so terminate session and mark as failed. - _this.logger.error(error.message); - _this.logger.error("Failed to handle offer in 2xx response to re-INVITE"); - _this.ackAndBye(response, 488, "Bad Media Description"); - _this.stateTransition(session_state_1.SessionState.Terminated); - _this.isFailed = true; - }) - .then(function () { - _this.pendingReinvite = false; - if (options.requestDelegate && options.requestDelegate.onAccept) { - options.requestDelegate.onAccept(response); - } - }); - } - else { - // INVITE with SDP - set remote answer and send an ACK - // FIXME: SDH options & SDH modifiers options are applied somewhat ambiguously - // This behavior was ported from legacy code and the issue punted down the road. - var answerOptions = { - sessionDescriptionHandlerOptions: _this.sessionDescriptionHandlerOptions, - sessionDescriptionHandlerModifiers: _this.sessionDescriptionHandlerModifiers - }; - _this.setAnswer(body, answerOptions) - .then(function () { - var request = response.ack(); - }) - .catch(function (error) { - // No way to recover, so terminate session and mark as failed. - _this.logger.error(error.message); - _this.logger.error("Failed to handle answer in 2xx response to re-INVITE"); - _this.ackAndBye(response, 488, "Bad Media Description"); - _this.stateTransition(session_state_1.SessionState.Terminated); - _this.isFailed = true; - }) - .then(function () { - _this.pendingReinvite = false; - if (options.requestDelegate && options.requestDelegate.onAccept) { - options.requestDelegate.onAccept(response); - } - }); - } - }, - onProgress: function (response) { - return; - }, - onRedirect: function (response) { - return; - }, - onReject: function (response) { - _this.logger.warn("Received a non-2xx response to re-INVITE"); - _this.pendingReinvite = false; - if (options.withoutSdp) { - if (options.requestDelegate && options.requestDelegate.onReject) { - options.requestDelegate.onReject(response); - } - } - else { - _this.rollbackOffer() - .catch(function (error) { - // No way to recover, so terminate session and mark as failed. - _this.logger.error(error.message); - _this.logger.error("Failed to rollback offer on non-2xx response to re-INVITE"); - // Note that the ACK was already sent by the transaction, so just need to send BYE - if (!_this.dialog) { - throw new Error("Dialog undefined."); - } - var extraHeaders = []; - extraHeaders.push("Reason: " + Utils_1.Utils.getReasonHeaderValue(500, "Internal Server Error")); - var outgoingByeRequest = _this.dialog.bye(undefined, { extraHeaders: extraHeaders }); - _this.stateTransition(session_state_1.SessionState.Terminated); - _this.isFailed = true; - }) - .then(function () { - if (options.requestDelegate && options.requestDelegate.onReject) { - options.requestDelegate.onReject(response); - } - }); - } - }, - onTrying: function (response) { - return; - } - }; - var requestOptions = options.requestOptions || {}; - requestOptions.extraHeaders = (requestOptions.extraHeaders || []).slice(); - requestOptions.extraHeaders.push("Allow: " + allowed_methods_1.AllowedMethods.toString()); - requestOptions.extraHeaders.push("Contact: " + this.contact); - // Just send an INVITE with no sdp... - if (options.withoutSdp) { - if (!this.dialog) { - this.pendingReinvite = false; - return Promise.reject(new Error("Dialog undefined.")); - } - return Promise.resolve(this.dialog.invite(delegate, requestOptions)); - } - // Get an offer and send it in an INVITE - // FIXME: SDH options & SDH modifiers options are applied somewhat ambiguously - // This behavior was ported from legacy code and the issue punted down the road. - var offerOptions = { - sessionDescriptionHandlerOptions: options.sessionDescriptionHandlerOptions, - sessionDescriptionHandlerModifiers: options.sessionDescriptionHandlerModifiers - }; - return this.getOffer(offerOptions) - .then(function (offerBody) { - if (!_this.dialog) { - _this.pendingReinvite = false; - throw new Error("Dialog undefined."); - } - requestOptions.body = offerBody; - return _this.dialog.invite(delegate, requestOptions); - }) - .catch(function (error) { - _this.logger.error(error.message); - _this.logger.error("Failed to send re-INVITE"); - _this.pendingReinvite = false; - throw error; - }); - }; - /** - * TODO: This is awkward. - * Helper function - * @internal - */ - Session.prototype.byePending = function () { - this.stateTransition(session_state_1.SessionState.Terminating); - this.terminated(); - }; - /** - * TODO: This is awkward. - * Helper function - * @internal - */ - Session.prototype.byeSent = function (request) { - this.emit("bye", request.message); - this.stateTransition(session_state_1.SessionState.Terminated); - this.terminated(); - }; - /** - * Send BYE. - * @param delegate - Request delegate. - * @param options - Request options bucket. - * @internal - */ - Session.prototype.bye = function (delegate, options) { - var _this = this; - // Using core session dialog - if (!this.dialog) { - return Promise.reject(new Error("Session dialog undefined.")); - } - var dialog = this.dialog; - // The caller's UA MAY send a BYE for either confirmed or early dialogs, - // and the callee's UA MAY send a BYE on confirmed dialogs, but MUST NOT - // send a BYE on early dialogs. However, the callee's UA MUST NOT send a - // BYE on a confirmed dialog until it has received an ACK for its 2xx - // response or until the server transaction times out. - // https://tools.ietf.org/html/rfc3261#section-15 - switch (dialog.sessionState) { - case core_1.SessionState.Initial: - throw new Error("Invalid dialog state " + dialog.sessionState); - case core_1.SessionState.Early: // Implementation choice - not sending BYE for early dialogs. - throw new Error("Invalid dialog state " + dialog.sessionState); - case core_1.SessionState.AckWait: { // This state only occurs if we are the callee. - this.byePending(); - return new Promise(function (resolve, reject) { - dialog.delegate = { - // When ACK shows up, say BYE. - onAck: function () { - var request = dialog.bye(delegate, options); - _this.byeSent(request); - resolve(request); - }, - // Or the server transaction times out before the ACK arrives. - onAckTimeout: function () { - var request = dialog.bye(delegate, options); - _this.byeSent(request); - resolve(request); - } - }; - }); - } - case core_1.SessionState.Confirmed: { - var request = dialog.bye(delegate, options); - this.byeSent(request); - return Promise.resolve(request); - } - case core_1.SessionState.Terminated: - throw new Error("Invalid dialog state " + dialog.sessionState); - default: - throw new Error("Unrecognized state."); - } - }; - /** - * Send INFO. - * @param delegate - Request delegate. - * @param options - Request options bucket. - * @internal - */ - Session.prototype.info = function (delegate, options) { - // Using core session dialog - if (!this.dialog) { - return Promise.reject(new Error("Session dialog undefined.")); - } - return Promise.resolve(this.dialog.info(delegate, options)); - }; - /** - * Send REFER. - * @param delegate - Request delegate. - * @param options - Request options bucket. - * @internal - */ - Session.prototype.refer = function (referrer, delegate, options) { - // Using core session dialog - if (!this.dialog) { - return Promise.reject(new Error("Session dialog undefined.")); - } - // If the session has a referrer, it will receive any in-dialog NOTIFY requests. - this.referrer = referrer; - return Promise.resolve(this.dialog.refer(delegate, options)); - }; - /** - * @internal - */ - Session.prototype.close = function () { - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return; - } - this.logger.log("closing INVITE session " + this.id); - // 1st Step. Terminate media. - if (this._sessionDescriptionHandler) { - this._sessionDescriptionHandler.close(); - } - // 2nd Step. Terminate signaling. - // Clear session timers - if (this.expiresTimer) { - clearTimeout(this.expiresTimer); - } - if (this.userNoAnswerTimer) { - clearTimeout(this.userNoAnswerTimer); - } - this.status = Enums_1.SessionStatus.STATUS_TERMINATED; - if (this.userAgent.transport) { - this.userAgent.transport.removeListener("transportError", this.errorListener); - } - if (!this.id) { - throw new Error("Session id undefined."); - } - delete this.userAgent.sessions[this.id]; - return; - }; - /** - * @internal - */ - Session.prototype.onRequestTimeout = function () { - if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { - this.terminated(undefined, Constants_1.C.causes.REQUEST_TIMEOUT); - } - else if (this.status !== Enums_1.SessionStatus.STATUS_TERMINATED) { - this.failed(undefined, Constants_1.C.causes.REQUEST_TIMEOUT); - this.terminated(undefined, Constants_1.C.causes.REQUEST_TIMEOUT); - } - }; - /** - * @internal - */ - Session.prototype.onTransportError = function () { - if (this.status !== Enums_1.SessionStatus.STATUS_CONFIRMED && this.status !== Enums_1.SessionStatus.STATUS_TERMINATED) { - this.failed(undefined, Constants_1.C.causes.CONNECTION_ERROR); - } - }; - /** - * Send ACK and then BYE. There are unrecoverable errors which can occur - * while handling dialog forming and in-dialog INVITE responses and when - * they occur we ACK the response and terminate the session. - * @param inviteResponse - The response causing the error. - * @param statusCode - Status code for he reason phrase. - * @param reasonPhrase - Reason phrase for the BYE. - * @internal - */ - Session.prototype.ackAndBye = function (response, statusCode, reasonPhrase) { - var outgoingAckRequest = response.ack(); - var extraHeaders = []; - if (statusCode) { - extraHeaders.push("Reason: " + Utils_1.Utils.getReasonHeaderValue(statusCode, reasonPhrase)); - } - var outgoingByeRequest = response.session.bye(undefined, { extraHeaders: extraHeaders }); - this.emit("bye", outgoingByeRequest.message); - }; - /** - * Handle in dialog ACK request. - * @internal - */ - Session.prototype.onAckRequest = function (request) { - var _this = this; - this.logger.log("Session.onAckRequest"); - if (this.state !== session_state_1.SessionState.Initial && - this.state !== session_state_1.SessionState.Establishing && - this.state !== session_state_1.SessionState.Established && - this.state !== session_state_1.SessionState.Terminating) { - this.logger.error("ACK received while in state " + this.state + ", dropping request"); - return; - } - // FIXME: Review is this ever true? We're "Established" when dialog created in accept(). - if (this.state === session_state_1.SessionState.Initial || this.state === session_state_1.SessionState.Establishing) { - this.stateTransition(session_state_1.SessionState.Established); - } - var dialog = this.dialog; - if (!dialog) { - throw new Error("Dialog undefined."); - } - // Helper function. - var confirmSession = function () { - _this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; - _this.emit("confirmed", request.message); - }; - // If the ACK doesn't have an offer/answer, nothing to be done. - var body = core_1.getBody(request.message); - if (!body) { - confirmSession(); - return; - } - if (body.contentDisposition === "render") { - this.renderbody = body.content; - this.rendertype = body.contentType; - confirmSession(); - return; - } - if (body.contentDisposition !== "session") { - confirmSession(); - return; - } - var options = { - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers - }; - switch (dialog.signalingState) { - case core_1.SignalingState.Initial: - // State should never be reached as first reliable response must have answer/offer. - throw new Error("Invalid signaling state " + dialog.signalingState + "."); - case core_1.SignalingState.Stable: - // Receved answer. - this.setAnswer(body, options) - .then(function () { return confirmSession(); }) - .catch(function (error) { - // FIXME: TODO - need to do something to handle this error - _this.logger.error(error); - var extraHeaders = ["Reason: " + Utils_1.Utils.getReasonHeaderValue(488, "Bad Media Description")]; - _this.bye(undefined, { extraHeaders: extraHeaders }); - _this.failed(request.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - _this.terminated(request.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - throw error; - }); - return; - case core_1.SignalingState.HaveLocalOffer: - // State should never be reached as local offer would be answered by this ACK - throw new Error("Invalid signaling state " + dialog.signalingState + "."); - case core_1.SignalingState.HaveRemoteOffer: - // State should never be reached as remote offer would be answered in first reliable response. - throw new Error("Invalid signaling state " + dialog.signalingState + "."); - case core_1.SignalingState.Closed: - throw new Error("Invalid signaling state " + dialog.signalingState + "."); - default: - throw new Error("Invalid signaling state " + dialog.signalingState + "."); - } - }; - /** - * Handle in dialog BYE request. - * @internal - */ - Session.prototype.onByeRequest = function (request) { - this.logger.log("Session.onByeRequest"); - if (this.state !== session_state_1.SessionState.Established) { - this.logger.error("BYE received while in state " + this.state + ", dropping request"); - return; - } - request.accept(); - this.stateTransition(session_state_1.SessionState.Terminated); - if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { - this.emit("bye", request.message); - this.terminated(request.message, Constants_1.C.BYE); - } - }; - /** - * Handle in dialog INFO request. - * @internal - */ - Session.prototype.onInfoRequest = function (request) { - this.logger.log("Session.onInfoRequest"); - if (this.state !== session_state_1.SessionState.Established) { - this.logger.error("INFO received while in state " + this.state + ", dropping request"); - return; - } - if (this.delegate && this.delegate.onInfo) { - var info = new info_1.Info(request); - this.delegate.onInfo(info); - } - else { - request.accept(); - } - }; - /** - * Handle in dialog INVITE request. - * @internal - */ - Session.prototype.onInviteRequest = function (request) { - var _this = this; - this.logger.log("Session.onInviteRequest"); - if (this.state !== session_state_1.SessionState.Established) { - this.logger.error("INVITE received while in state " + this.state + ", dropping request"); - return; - } - // TODO: would be nice to have core track and set the Contact header, - // but currently the session which is setting it is holding onto it. - var extraHeaders = ["Contact: " + this.contact]; - // Check testing hooks - if (this.delegate && this.delegate.onReinviteTest) { - var test = this.delegate.onReinviteTest(); - if (test === "acceptWithoutDescription") { - request.accept({ statusCode: 200, extraHeaders: extraHeaders }); - return; - } - if (test === "reject488") { - request.reject({ statusCode: 488 }); - return; - } - } - // Handle P-Asserted-Identity - if (request.message.hasHeader("P-Asserted-Identity")) { - var header = request.message.getHeader("P-Asserted-Identity"); - if (!header) { - throw new Error("Header undefined."); - } - this.assertedIdentity = core_1.Grammar.nameAddrHeaderParse(header); - } - // FIXME: SDH options & SDH modifiers options are applied somewhat ambiguously - // This behavior was ported from legacy code and the issue punted down the road. - var options = { - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers - }; - this.generateResponseOfferAnswerInDialog(options) - .then(function (body) { - var outgoingResponse = request.accept({ statusCode: 200, extraHeaders: extraHeaders, body: body }); - if (_this.delegate && _this.delegate.onInvite) { - _this.delegate.onInvite(request.message, outgoingResponse.message, 200); - } - }) - .catch(function (error) { - _this.logger.error(error.message); - _this.logger.error("Failed to handle to re-INVITE request"); - if (!_this.dialog) { - throw new Error("Dialog undefined."); - } - _this.logger.error(_this.dialog.signalingState); - // If we don't have a local/remote offer... - if (_this.dialog.signalingState === core_1.SignalingState.Stable) { - var outgoingResponse = request.reject({ statusCode: 488 }); // Not Acceptable Here - if (_this.delegate && _this.delegate.onInvite) { - _this.delegate.onInvite(request.message, outgoingResponse.message, 488); - } - return; - } - // Otherwise rollback - _this.rollbackOffer() - .then(function () { - var outgoingResponse = request.reject({ statusCode: 488 }); // Not Acceptable Here - if (_this.delegate && _this.delegate.onInvite) { - _this.delegate.onInvite(request.message, outgoingResponse.message, 488); - } - }) - .catch(function (errorRollback) { - // No way to recover, so terminate session and mark as failed. - _this.logger.error(errorRollback.message); - _this.logger.error("Failed to rollback offer on re-INVITE request"); - var outgoingResponse = request.reject({ statusCode: 488 }); // Not Acceptable Here - var extraHeadersBye = []; - extraHeadersBye.push("Reason: " + Utils_1.Utils.getReasonHeaderValue(500, "Internal Server Error")); - if (!_this.dialog) { - throw new Error("Dialog undefined."); - } - var outgoingByeRequest = _this.dialog.bye(undefined, { extraHeaders: extraHeaders }); - _this.stateTransition(session_state_1.SessionState.Terminated); - _this.isFailed = true; - if (_this.delegate && _this.delegate.onInvite) { - _this.delegate.onInvite(request.message, outgoingResponse.message, 488); - } - }); - }); - }; - /** - * Handle in dialog NOTIFY request. - * @internal - */ - Session.prototype.onNotifyRequest = function (request) { - this.logger.log("Session.onNotifyRequest"); - if (this.state !== session_state_1.SessionState.Established) { - this.logger.error("NOTIFY received while in state " + this.state + ", dropping request"); - return; - } - // DEPRECATED BEGIN - // ReferClientContext is deprecated - // if ( - // this.referContext && - // this.referContext.type === TypeStrings.ReferClientContext && - // incomingRequest.message.hasHeader("event") && - // /^refer(;.*)?$/.test(incomingRequest.message.getHeader("event") as string) - // ) { - // this.referContext.receiveNotify(incomingRequest); - // return; - // } - // DEPRECATED END - // If this a NOTIFY associated with the progress of a REFER, - // look to delegate handling to the associated Referrer. - if (this.referrer && this.referrer.delegate && this.referrer.delegate.onNotify) { - var notification = new notification_1.Notification(request); - this.referrer.delegate.onNotify(notification); - return; - } - // Otherwise accept the NOTIFY. - if (this.delegate && this.delegate.onNotify) { - var notification = new notification_1.Notification(request); - this.delegate.onNotify(notification); - } - else { - request.accept(); - } - this.emit("notify", request.message); - }; - /** - * Handle in dialog PRACK request. - * @internal - */ - Session.prototype.onPrackRequest = function (request) { - this.logger.log("Session.onPrackRequest"); - if (this.state !== session_state_1.SessionState.Established) { - this.logger.error("PRACK received while in state " + this.state + ", dropping request"); - return; - } - throw new Error("Unimplemented."); - }; - /** - * Handle in dialog REFER request. - * @internal - */ - Session.prototype.onReferRequest = function (request) { - var _this = this; - this.logger.log("Session.onReferRequest"); - if (this.state !== session_state_1.SessionState.Established) { - this.logger.error("REFER received while in state " + this.state + ", dropping request"); - return; - } - if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { - // RFC 3515 2.4.1 - if (!request.message.hasHeader("refer-to")) { - this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting."); - request.reject(); - return; - } - // DEPRECATED BEGIN - // // ReferServerContext is deprecated - // if (this.listeners("referRequested").length) { - // const referContext = new ReferServerContext(this.ua, incomingRequest, this.dialog); - // this.emit("referRequested", referContext); - // return; - // } - // DEPRECATED END - var referral_2 = new referral_1.Referral(request, this); - if (this.delegate && this.delegate.onRefer) { - this.delegate.onRefer(referral_2); - } - else { - this.logger.log("No delegate available to handle REFER, automatically accepting and following."); - referral_2 - .accept() - .then(function () { return referral_2 - .makeInviter(_this.passedOptions) - .invite(); }) - .catch(function (error) { - // FIXME: logging and eating error... - _this.logger.error(error.message); - }); - } - } - }; - /** - * @deprecated Legacy state transition. - * @internal - */ - Session.prototype.connecting = function (request) { - this.emit("connecting", { request: request }); - }; - /** - * @deprecated Legacy state transition. - * @internal - */ - Session.prototype.failed = function (response, cause) { - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return; - } - this.emit("failed", response, cause); - }; - /** - * @deprecated Legacy state transition. - * @internal - */ - Session.prototype.rejected = function (response, cause) { - this.emit("rejected", response, cause); - }; - /** - * @deprecated Legacy state transition. - * @internal - */ - Session.prototype.terminated = function (message, cause) { - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return; - } - this.endTime = new Date(); - this.close(); - this.emit("terminated", message, cause); - }; - /** - * Generate an offer or answer for a response to an INVITE request. - * If a remote offer was provided in the request, set the remote - * description and get a local answer. If a remote offer was not - * provided, generates a local offer. - * @internal - */ - Session.prototype.generateResponseOfferAnswer = function (request, options) { - if (this.dialog) { - return this.generateResponseOfferAnswerInDialog(options); - } - var body = core_1.getBody(request.message); - if (!body || body.contentDisposition !== "session") { - return this.getOffer(options); - } - else { - return this.setOfferAndGetAnswer(body, options); - } - }; - /** - * Generate an offer or answer for a response to an INVITE request - * when a dialog (early or otherwise) has already been established. - * This method may NOT be called if a dialog has yet to be established. - * @internal - */ - Session.prototype.generateResponseOfferAnswerInDialog = function (options) { - if (!this.dialog) { - throw new Error("Dialog undefined."); - } - switch (this.dialog.signalingState) { - case core_1.SignalingState.Initial: - return this.getOffer(options); - case core_1.SignalingState.HaveLocalOffer: - // o Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - return Promise.resolve(undefined); - case core_1.SignalingState.HaveRemoteOffer: - if (!this.dialog.offer) { - throw new Error("Session offer undefined in signaling state " + this.dialog.signalingState + "."); - } - return this.setOfferAndGetAnswer(this.dialog.offer, options); - case core_1.SignalingState.Stable: - // o Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - if (this.state !== session_state_1.SessionState.Established) { - return Promise.resolve(undefined); - } - // In dialog INVITE without offer, get an offer for the response. - return this.getOffer(options); - case core_1.SignalingState.Closed: - throw new Error("Invalid signaling state " + this.dialog.signalingState + "."); - default: - throw new Error("Invalid signaling state " + this.dialog.signalingState + "."); - } - }; - /** - * Get local offer. - * @internal - */ - Session.prototype.getOffer = function (options) { - var sdh = this.setupSessionDescriptionHandler(); - var sdhOptions = options.sessionDescriptionHandlerOptions; - var sdhModifiers = options.sessionDescriptionHandlerModifiers; - return sdh.getDescription(sdhOptions, sdhModifiers) - .then(function (bodyAndContentType) { return Utils_1.Utils.fromBodyObj(bodyAndContentType); }) - .catch(function (error) { - throw (error instanceof Error ? error : new Error(error)); - }); - }; - /** - * Rollback local/remote offer. - * @internal - */ - Session.prototype.rollbackOffer = function () { - var sdh = this.setupSessionDescriptionHandler(); - if (!sdh.rollbackDescription) { - return Promise.resolve(); - } - return sdh.rollbackDescription() - .catch(function (error) { - throw (error instanceof Error ? error : new Error(error)); - }); - }; - /** - * Set remote answer. - * @internal - */ - Session.prototype.setAnswer = function (answer, options) { - var sdh = this.setupSessionDescriptionHandler(); - var sdhOptions = options.sessionDescriptionHandlerOptions; - var sdhModifiers = options.sessionDescriptionHandlerModifiers; - if (!sdh.hasDescription(answer.contentType)) { - return Promise.reject(new Exceptions_1.Exceptions.UnsupportedSessionDescriptionContentTypeError()); - } - return sdh.setDescription(answer.content, sdhOptions, sdhModifiers) - .catch(function (error) { - throw (error instanceof Error ? error : new Error(error)); - }); - }; - /** - * Set remote offer and get local answer. - * @internal - */ - Session.prototype.setOfferAndGetAnswer = function (offer, options) { - var sdh = this.setupSessionDescriptionHandler(); - var sdhOptions = options.sessionDescriptionHandlerOptions; - var sdhModifiers = options.sessionDescriptionHandlerModifiers; - if (!sdh.hasDescription(offer.contentType)) { - return Promise.reject(new Exceptions_1.Exceptions.UnsupportedSessionDescriptionContentTypeError()); - } - return sdh.setDescription(offer.content, sdhOptions, sdhModifiers) - .then(function () { return sdh.getDescription(sdhOptions, sdhModifiers); }) - .then(function (bodyAndContentType) { return Utils_1.Utils.fromBodyObj(bodyAndContentType); }) - .catch(function (error) { - throw (error instanceof Error ? error : new Error(error)); - }); - }; - /** - * SDH for confirmed dialog. - * @internal - */ - Session.prototype.setSessionDescriptionHandler = function (sdh) { - if (this._sessionDescriptionHandler) { - throw new Error("Sessionn description handler defined."); - } - this._sessionDescriptionHandler = sdh; - }; - /** - * SDH for confirmed dialog. - * @internal - */ - Session.prototype.setupSessionDescriptionHandler = function () { - if (this._sessionDescriptionHandler) { - return this._sessionDescriptionHandler; - } - this._sessionDescriptionHandler = - this.sessionDescriptionHandlerFactory(this, this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions); - this.emit("SessionDescriptionHandler-created", this._sessionDescriptionHandler); - return this._sessionDescriptionHandler; - }; - /** - * Transition session state. - * @internal - */ - Session.prototype.stateTransition = function (newState) { - var _this = this; - var invalidTransition = function () { - throw new Error("Invalid state transition from " + _this._state + " to " + newState); - }; - // Validate transition - switch (this._state) { - case session_state_1.SessionState.Initial: - if (newState !== session_state_1.SessionState.Establishing && - newState !== session_state_1.SessionState.Established && - newState !== session_state_1.SessionState.Terminating && - newState !== session_state_1.SessionState.Terminated) { - invalidTransition(); - } - break; - case session_state_1.SessionState.Establishing: - if (newState !== session_state_1.SessionState.Established && - newState !== session_state_1.SessionState.Terminating && - newState !== session_state_1.SessionState.Terminated) { - invalidTransition(); - } - break; - case session_state_1.SessionState.Established: - if (newState !== session_state_1.SessionState.Terminating && - newState !== session_state_1.SessionState.Terminated) { - invalidTransition(); - } - break; - case session_state_1.SessionState.Terminating: - if (newState !== session_state_1.SessionState.Terminated) { - invalidTransition(); - } - break; - case session_state_1.SessionState.Terminated: - invalidTransition(); - break; - default: - throw new Error("Unrecognized state."); - } - // Deprecated legacy ported behavior - if (newState === session_state_1.SessionState.Established) { - this.startTime = new Date(); - } - // Transition - this._state = newState; - this.logger.log("Session " + this.id + " transitioned to state " + this._state); - this._stateEventEmitter.emit("event", this._state); - }; - // DEPRECATED - /** @internal */ - Session.C = Enums_1.SessionStatus; - return Session; -}(events_1.EventEmitter)); -exports.Session = Session; - - -/***/ }), -/* 96 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * Creates an {@link Emitter}. - * @param eventEmitter - An event emitter. - * @param eventName - Event name. - * @internal - */ -function makeEmitter(eventEmitter, eventName) { - if (eventName === void 0) { eventName = "event"; } - return { - on: function (listener) { - eventEmitter.on(eventName, listener); - }, - off: function (listener) { - eventEmitter.removeListener(eventName, listener); - }, - once: function (listener) { - eventEmitter.once(eventName, listener); - } - }; -} -exports.makeEmitter = makeEmitter; - - -/***/ }), -/* 97 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * An exchange of information (incoming INFO). - * @public - */ -var Info = /** @class */ (function () { - /** @internal */ - function Info(incomingInfoRequest) { - this.incomingInfoRequest = incomingInfoRequest; - } - Object.defineProperty(Info.prototype, "request", { - /** Incoming MESSAGE request message. */ - get: function () { - return this.incomingInfoRequest.message; - }, - enumerable: true, - configurable: true - }); - /** Accept the request. */ - Info.prototype.accept = function (options) { - this.incomingInfoRequest.accept(options); - return Promise.resolve(); - }; - /** Reject the request. */ - Info.prototype.reject = function (options) { - this.incomingInfoRequest.reject(options); - return Promise.resolve(); - }; - return Info; -}()); -exports.Info = Info; - - -/***/ }), -/* 98 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * A notification of an event (incoming NOTIFY). - * @public - */ -var Notification = /** @class */ (function () { - /** @internal */ - function Notification(incomingNotifyRequest) { - this.incomingNotifyRequest = incomingNotifyRequest; - } - Object.defineProperty(Notification.prototype, "request", { - /** Incoming NOTIFY request message. */ - get: function () { - return this.incomingNotifyRequest.message; - }, - enumerable: true, - configurable: true - }); - /** Accept the request. */ - Notification.prototype.accept = function (options) { - this.incomingNotifyRequest.accept(options); - return Promise.resolve(); - }; - /** Reject the request. */ - Notification.prototype.reject = function (options) { - this.incomingNotifyRequest.reject(options); - return Promise.resolve(); - }; - return Notification; -}()); -exports.Notification = Notification; - - -/***/ }), -/* 99 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var core_1 = __webpack_require__(2); -/** - * A request to establish a {@link Session} elsewhere (incoming REFER). - * @public - */ -var Referral = /** @class */ (function () { - /** @internal */ - function Referral(incomingReferRequest, session) { - this.incomingReferRequest = incomingReferRequest; - this.session = session; - } - Object.defineProperty(Referral.prototype, "referTo", { - get: function () { - var referTo = this.incomingReferRequest.message.parseHeader("refer-to"); - if (!(referTo instanceof core_1.NameAddrHeader)) { - throw new Error("Failed to parse Refer-To header."); - } - return referTo; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Referral.prototype, "referredBy", { - get: function () { - return this.incomingReferRequest.message.getHeader("referred-by"); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Referral.prototype, "replaces", { - get: function () { - return this.referTo.uri.getHeader("replaces"); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Referral.prototype, "request", { - /** Incoming REFER request message. */ - get: function () { - return this.incomingReferRequest.message; - }, - enumerable: true, - configurable: true - }); - /** Accept the request. */ - Referral.prototype.accept = function (options) { - if (options === void 0) { options = { statusCode: 202 }; } - this.incomingReferRequest.accept(options); - return Promise.resolve(); - }; - /** Reject the request. */ - Referral.prototype.reject = function (options) { - this.incomingReferRequest.reject(options); - return Promise.resolve(); - }; - /** - * Creates an inviter which may be used to send an out of dialog INVITE request. - * - * @remarks - * This a helper method to create an Inviter which will execute the referral - * of the `Session` which was referred. The appropriate headers are set and - * the referred `Session` is linked to the new `Session`. Note that only a - * single instance of the `Inviter` will be created and returned (if called - * more than once a reference to the same `Inviter` will be returned every time). - * - * @param options - Options bucket. - * @param modifiers - Session description handler modifiers. - */ - Referral.prototype.makeInviter = function (options) { - if (this.inviter) { - return this.inviter; - } - var targetURI = this.referTo.uri.clone(); - targetURI.clearHeaders(); - options = options || {}; - var extraHeaders = (options.extraHeaders || []).slice(); - var replaces = this.replaces; - if (replaces) { - // decodeURIComponent is a holdover from 2c086eb4. Not sure that it is actually necessary - extraHeaders.push("Replaces: " + decodeURIComponent(replaces)); - } - var referredBy = this.referredBy; - if (referredBy) { - extraHeaders.push("Referred-By: " + referredBy); - } - options.extraHeaders = extraHeaders; - this.inviter = this.session.userAgent.makeInviter(targetURI, options); - this.inviter.referred = this.session; - this.session.referral = this.inviter; - return this.inviter; - }; - return Referral; -}()); -exports.Referral = Referral; - - -/***/ }), -/* 100 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * {@link Session} state. - * @remarks - * Valid state transitions: - * ``` - * 1. "initial" --> "establishing" (before INVITE sent on outgoing, before OK sent on incoming) - * 2. "initial" --> "established" (after ACK is sent on outgoing, after OK sent on incoming) - * 4. "initial" --> "terminating" - * 4. "initial" --> "terminated" - * 5. "establishing" --> "established" - * 6. "establishing" --> "terminating" - * 7. "establishing" --> "terminated" - * 8. "established" --> "terminating" - * 9. "established" --> "terminated" - * 10. "terminating" --> "terminated" - * ``` - * @public - */ -var SessionState; -(function (SessionState) { - SessionState["Initial"] = "Initial"; - SessionState["Establishing"] = "Establishing"; - SessionState["Established"] = "Established"; - SessionState["Terminating"] = "Terminating"; - SessionState["Terminated"] = "Terminated"; -})(SessionState = exports.SessionState || (exports.SessionState = {})); - - -/***/ }), -/* 101 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var stripPayload = function (sdp, payload) { - var mediaDescs = []; - var lines = sdp.split(/\r\n/); - var currentMediaDesc; - for (var i = 0; i < lines.length;) { - var line = lines[i]; - if (/^m=(?:audio|video)/.test(line)) { - currentMediaDesc = { - index: i, - stripped: [] - }; - mediaDescs.push(currentMediaDesc); - } - else if (currentMediaDesc) { - var rtpmap = /^a=rtpmap:(\d+) ([^/]+)\//.exec(line); - if (rtpmap && payload === rtpmap[2]) { - lines.splice(i, 1); - currentMediaDesc.stripped.push(rtpmap[1]); - continue; // Don't increment 'i' - } - } - i++; - } - for (var _i = 0, mediaDescs_1 = mediaDescs; _i < mediaDescs_1.length; _i++) { - var mediaDesc = mediaDescs_1[_i]; - var mline = lines[mediaDesc.index].split(" "); - // Ignore the first 3 parameters of the mline. The codec information is after that - for (var j = 3; j < mline.length;) { - if (mediaDesc.stripped.indexOf(mline[j]) !== -1) { - mline.splice(j, 1); - continue; - } - j++; - } - lines[mediaDesc.index] = mline.join(" "); - } - return lines.join("\r\n"); -}; -var stripMediaDescription = function (sdp, description) { - var descriptionRegExp = new RegExp("m=" + description + ".*$", "gm"); - var groupRegExp = new RegExp("^a=group:.*$", "gm"); - if (descriptionRegExp.test(sdp)) { - var midLineToRemove_1; - sdp = sdp.split(/^m=/gm).filter(function (section) { - if (section.substr(0, description.length) === description) { - midLineToRemove_1 = section.match(/^a=mid:.*$/gm); - if (midLineToRemove_1) { - var step = midLineToRemove_1[0].match(/:.+$/g); - if (step) { - midLineToRemove_1 = step[0].substr(1); - } - } - return false; - } - return true; - }).join("m="); - var groupLine = sdp.match(groupRegExp); - if (groupLine && groupLine.length === 1) { - var groupLinePortion = groupLine[0]; - var groupRegExpReplace = new RegExp("\ *" + midLineToRemove_1 + "[^\ ]*", "g"); - groupLinePortion = groupLinePortion.replace(groupRegExpReplace, ""); - sdp = sdp.split(groupRegExp).join(groupLinePortion); - } - } - return sdp; -}; -function stripTcpCandidates(description) { - description.sdp = (description.sdp || "").replace(/^a=candidate:\d+ \d+ tcp .*?\r\n/img, ""); - return Promise.resolve(description); -} -exports.stripTcpCandidates = stripTcpCandidates; -function stripTelephoneEvent(description) { - description.sdp = stripPayload(description.sdp || "", "telephone-event"); - return Promise.resolve(description); -} -exports.stripTelephoneEvent = stripTelephoneEvent; -function cleanJitsiSdpImageattr(description) { - description.sdp = (description.sdp || "").replace(/^(a=imageattr:.*?)(x|y)=\[0-/gm, "$1$2=[1:"); - return Promise.resolve(description); -} -exports.cleanJitsiSdpImageattr = cleanJitsiSdpImageattr; -function stripG722(description) { - description.sdp = stripPayload(description.sdp || "", "G722"); - return Promise.resolve(description); -} -exports.stripG722 = stripG722; -function stripRtpPayload(payload) { - return function (description) { - description.sdp = stripPayload(description.sdp || "", payload); - return Promise.resolve(description); - }; -} -exports.stripRtpPayload = stripRtpPayload; -function stripVideo(description) { - description.sdp = stripMediaDescription(description.sdp || "", "video"); - return Promise.resolve(description); -} -exports.stripVideo = stripVideo; -function addMidLines(description) { - var sdp = description.sdp || ""; - if (sdp.search(/^a=mid.*$/gm) === -1) { - var mlines_1 = sdp.match(/^m=.*$/gm); - var sdpArray_1 = sdp.split(/^m=.*$/gm); - if (mlines_1) { - mlines_1.forEach(function (elem, idx) { - mlines_1[idx] = elem + "\na=mid:" + idx; - }); - } - sdpArray_1.forEach(function (elem, idx) { - if (mlines_1 && mlines_1[idx]) { - sdpArray_1[idx] = elem + mlines_1[idx]; - } - }); - sdp = sdpArray_1.join(""); - description.sdp = sdp; - } - return Promise.resolve(description); -} -exports.addMidLines = addMidLines; - - -/***/ }), -/* 102 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var Enums_1 = __webpack_require__(82); -/* SessionDescriptionHandlerObserver - * @class SessionDescriptionHandler Observer Class. - * @param {SIP.Session} session - * @param {Object} [options] - */ -var SessionDescriptionHandlerObserver = /** @class */ (function () { - function SessionDescriptionHandlerObserver(session, options) { - this.type = Enums_1.TypeStrings.SessionDescriptionHandlerObserver; - this.session = session; - this.options = options; - } - SessionDescriptionHandlerObserver.prototype.trackAdded = function () { - this.session.emit("trackAdded"); - }; - SessionDescriptionHandlerObserver.prototype.directionChanged = function () { - this.session.emit("directionChanged"); - }; - return SessionDescriptionHandlerObserver; -}()); -exports.SessionDescriptionHandlerObserver = SessionDescriptionHandlerObserver; - - -/***/ }), -/* 103 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var core_1 = __webpack_require__(2); -var Enums_1 = __webpack_require__(82); -var Exceptions_1 = __webpack_require__(84); -var Utils_1 = __webpack_require__(83); -var TransportStatus; -(function (TransportStatus) { - TransportStatus[TransportStatus["STATUS_CONNECTING"] = 0] = "STATUS_CONNECTING"; - TransportStatus[TransportStatus["STATUS_OPEN"] = 1] = "STATUS_OPEN"; - TransportStatus[TransportStatus["STATUS_CLOSING"] = 2] = "STATUS_CLOSING"; - TransportStatus[TransportStatus["STATUS_CLOSED"] = 3] = "STATUS_CLOSED"; -})(TransportStatus = exports.TransportStatus || (exports.TransportStatus = {})); -/** - * Compute an amount of time in seconds to wait before sending another - * keep-alive. - * @returns {Number} - */ -var computeKeepAliveTimeout = function (upperBound) { - var lowerBound = upperBound * 0.8; - return 1000 * (Math.random() * (upperBound - lowerBound) + lowerBound); -}; -/** - * @class Transport - * @param {Object} options - */ -var Transport = /** @class */ (function (_super) { - tslib_1.__extends(Transport, _super); - function Transport(logger, options) { - if (options === void 0) { options = {}; } - var _this = _super.call(this, logger, options) || this; - _this.type = Enums_1.TypeStrings.Transport; - _this.reconnectionAttempts = 0; - _this.status = TransportStatus.STATUS_CONNECTING; - _this.configuration = _this.loadConfig(options); - _this.server = _this.configuration.wsServers[0]; - return _this; - } - /** - * @returns {Boolean} - */ - Transport.prototype.isConnected = function () { - return this.status === TransportStatus.STATUS_OPEN; - }; - /** - * Send a message. - * @param {SIP.OutgoingRequest|String} msg - * @param {Object} [options] - * @returns {Promise} - */ - Transport.prototype.sendPromise = function (msg, options) { - if (options === void 0) { options = {}; } - if (!this.statusAssert(TransportStatus.STATUS_OPEN, options.force)) { - this.onError("unable to send message - WebSocket not open"); - return Promise.reject(); - } - var message = msg.toString(); - if (this.ws) { - if (this.configuration.traceSip === true) { - this.logger.log("sending WebSocket message:\n\n" + message + "\n"); - } - this.ws.send(message); - return Promise.resolve({ msg: message }); - } - else { - this.onError("unable to send message - WebSocket does not exist"); - return Promise.reject(); - } - }; - /** - * Disconnect socket. - */ - Transport.prototype.disconnectPromise = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - if (this.disconnectionPromise) { // Already disconnecting. Just return this. - return this.disconnectionPromise; - } - options.code = options.code || 1000; - if (!this.statusTransition(TransportStatus.STATUS_CLOSING, options.force)) { - if (this.status === TransportStatus.STATUS_CLOSED) { // Websocket is already closed - return Promise.resolve({ overrideEvent: true }); - } - else if (this.connectionPromise) { // Websocket is connecting, cannot move to disconneting yet - return this.connectionPromise.then(function () { return Promise.reject("The websocket did not disconnect"); }) - .catch(function () { return Promise.resolve({ overrideEvent: true }); }); - } - else { - // Cannot move to disconnecting, but not in connecting state. - return Promise.reject("The websocket did not disconnect"); - } - } - this.emit("disconnecting"); - this.disconnectionPromise = new Promise(function (resolve, reject) { - _this.disconnectDeferredResolve = resolve; - if (_this.reconnectTimer) { - clearTimeout(_this.reconnectTimer); - _this.reconnectTimer = undefined; - } - if (_this.ws) { - _this.stopSendingKeepAlives(); - _this.logger.log("closing WebSocket " + _this.server.wsUri); - _this.ws.close(options.code, options.reason); - } - else { - reject("Attempted to disconnect but the websocket doesn't exist"); - } - }); - return this.disconnectionPromise; - }; - /** - * Connect socket. - */ - Transport.prototype.connectPromise = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - if (this.status === TransportStatus.STATUS_CLOSING && !options.force) { - return Promise.reject("WebSocket " + this.server.wsUri + " is closing"); - } - if (this.connectionPromise) { - return this.connectionPromise; - } - this.server = this.server || this.getNextWsServer(options.force); - this.connectionPromise = new Promise(function (resolve, reject) { - if ((_this.status === TransportStatus.STATUS_OPEN || _this.status === TransportStatus.STATUS_CLOSING) - && !options.force) { - _this.logger.warn("WebSocket " + _this.server.wsUri + " is already connected"); - reject("Failed status check - attempted to open a connection but already open/closing"); - return; - } - _this.connectDeferredResolve = resolve; - _this.connectDeferredReject = reject; - _this.status = TransportStatus.STATUS_CONNECTING; - _this.emit("connecting"); - _this.logger.log("connecting to WebSocket " + _this.server.wsUri); - _this.disposeWs(); - try { - _this.ws = new WebSocket(_this.server.wsUri, "sip"); - } - catch (e) { - _this.ws = null; - _this.statusTransition(TransportStatus.STATUS_CLOSED, true); - _this.onError("error connecting to WebSocket " + _this.server.wsUri + ":" + e); - reject("Failed to create a websocket"); - _this.connectDeferredResolve = undefined; - _this.connectDeferredReject = undefined; - return; - } - if (!_this.ws) { - reject("Unexpected instance websocket not set"); - _this.connectDeferredResolve = undefined; - _this.connectDeferredReject = undefined; - return; - } - _this.connectionTimeout = setTimeout(function () { - _this.statusTransition(TransportStatus.STATUS_CLOSED); - _this.logger.warn("took too long to connect - exceeded time set in configuration.connectionTimeout: " + - _this.configuration.connectionTimeout + "s"); - _this.emit("disconnected", { code: 1000 }); - _this.connectionPromise = undefined; - reject("Connection timeout"); - _this.connectDeferredResolve = undefined; - _this.connectDeferredReject = undefined; - var ws = _this.ws; - _this.disposeWs(); - ws.close(1000); - }, _this.configuration.connectionTimeout * 1000); - _this.boundOnOpen = _this.onOpen.bind(_this); - _this.boundOnMessage = _this.onMessage.bind(_this); - _this.boundOnClose = _this.onClose.bind(_this); - _this.boundOnError = _this.onWebsocketError.bind(_this); - _this.ws.addEventListener("open", _this.boundOnOpen); - _this.ws.addEventListener("message", _this.boundOnMessage); - _this.ws.addEventListener("close", _this.boundOnClose); - _this.ws.addEventListener("error", _this.boundOnError); - }); - return this.connectionPromise; - }; - /** - * @event - * @param {event} e - */ - Transport.prototype.onMessage = function (e) { - var data = e.data; - var finishedData; - // CRLF Keep Alive response from server. Clear our keep alive timeout. - if (/^(\r\n)+$/.test(data)) { - this.clearKeepAliveTimeout(); - if (this.configuration.traceSip === true) { - this.logger.log("received WebSocket message with CRLF Keep Alive response"); - } - return; - } - else if (!data) { - this.logger.warn("received empty message, message discarded"); - return; - } - else if (typeof data !== "string") { // WebSocket binary message. - try { - // the UInt8Data was here prior to types, and doesn't check - finishedData = String.fromCharCode.apply(null, new Uint8Array(data)); - } - catch (err) { - this.logger.warn("received WebSocket binary message failed to be converted into string, message discarded"); - return; - } - if (this.configuration.traceSip === true) { - this.logger.log("received WebSocket binary message:\n\n" + data + "\n"); - } - } - else { // WebSocket text message. - if (this.configuration.traceSip === true) { - this.logger.log("received WebSocket text message:\n\n" + data + "\n"); - } - finishedData = data; - } - this.emit("message", finishedData); - }; - // Transport Event Handlers - /** - * @event - * @param {event} e - */ - Transport.prototype.onOpen = function () { - if (this.status === TransportStatus.STATUS_CLOSED) { // Indicated that the transport thinks the ws is dead already - var ws = this.ws; - this.disposeWs(); - ws.close(1000); - return; - } - this.statusTransition(TransportStatus.STATUS_OPEN, true); - this.emit("connected"); - if (this.connectionTimeout) { - clearTimeout(this.connectionTimeout); - this.connectionTimeout = undefined; - } - this.logger.log("WebSocket " + this.server.wsUri + " connected"); - // Clear reconnectTimer since we are not disconnected - if (this.reconnectTimer !== undefined) { - clearTimeout(this.reconnectTimer); - this.reconnectTimer = undefined; - } - // Reset reconnectionAttempts - this.reconnectionAttempts = 0; - // Reset disconnection promise so we can disconnect from a fresh state - this.disconnectionPromise = undefined; - this.disconnectDeferredResolve = undefined; - // Start sending keep-alives - this.startSendingKeepAlives(); - if (this.connectDeferredResolve) { - this.connectDeferredResolve({ overrideEvent: true }); - this.connectDeferredResolve = undefined; - this.connectDeferredReject = undefined; - } - else { - this.logger.warn("Unexpected websocket.onOpen with no connectDeferredResolve"); - } - }; - /** - * @event - * @param {event} e - */ - Transport.prototype.onClose = function (e) { - this.logger.log("WebSocket disconnected (code: " + e.code + (e.reason ? "| reason: " + e.reason : "") + ")"); - if (this.status !== TransportStatus.STATUS_CLOSING) { - this.logger.warn("WebSocket closed without SIP.js requesting it"); - this.emit("transportError"); - } - this.stopSendingKeepAlives(); - // Clean up connection variables so we can connect again from a fresh state - if (this.connectionTimeout) { - clearTimeout(this.connectionTimeout); - } - if (this.connectDeferredReject) { - this.connectDeferredReject("Websocket Closed"); - } - this.connectionTimeout = undefined; - this.connectionPromise = undefined; - this.connectDeferredResolve = undefined; - this.connectDeferredReject = undefined; - // Check whether the user requested to close. - if (this.disconnectDeferredResolve) { - this.disconnectDeferredResolve({ overrideEvent: true }); - this.statusTransition(TransportStatus.STATUS_CLOSED); - this.disconnectDeferredResolve = undefined; - return; - } - this.statusTransition(TransportStatus.STATUS_CLOSED, true); - this.emit("disconnected", { code: e.code, reason: e.reason }); - this.disposeWs(); - this.reconnect(); - }; - /** - * Removes event listeners and clears the instance ws - */ - Transport.prototype.disposeWs = function () { - if (this.ws) { - this.ws.removeEventListener("open", this.boundOnOpen); - this.ws.removeEventListener("message", this.boundOnMessage); - this.ws.removeEventListener("close", this.boundOnClose); - this.ws.removeEventListener("error", this.boundOnError); - this.ws = undefined; - } - }; - /** - * @event - * @param {string} e - */ - Transport.prototype.onError = function (e) { - this.logger.warn("Transport error: " + e); - this.emit("transportError"); - }; - /** - * @event - * @private - */ - Transport.prototype.onWebsocketError = function () { - this.onError("The Websocket had an error"); - }; - /** - * Reconnection attempt logic. - */ - Transport.prototype.reconnect = function () { - var _this = this; - if (this.reconnectionAttempts > 0) { - this.logger.log("Reconnection attempt " + this.reconnectionAttempts + " failed"); - } - if (this.noAvailableServers()) { - this.logger.warn("attempted to get next ws server but there are no available ws servers left"); - this.logger.warn("no available ws servers left - going to closed state"); - this.statusTransition(TransportStatus.STATUS_CLOSED, true); - this.emit("closed"); - this.resetServerErrorStatus(); - return; - } - if (this.isConnected()) { - this.logger.warn("attempted to reconnect while connected - forcing disconnect"); - this.disconnect({ force: true }); - } - this.reconnectionAttempts += 1; - if (this.reconnectionAttempts > this.configuration.maxReconnectionAttempts) { - this.logger.warn("maximum reconnection attempts for WebSocket " + this.server.wsUri); - this.logger.log("transport " + this.server.wsUri + " failed | connection state set to 'error'"); - this.server.isError = true; - this.emit("transportError"); - if (!this.noAvailableServers()) { - this.server = this.getNextWsServer(); - } - // When there are no available servers, the reconnect function ends on the next recursive call - // after checking for no available servers again. - this.reconnectionAttempts = 0; - this.reconnect(); - } - else { - this.logger.log("trying to reconnect to WebSocket " + - this.server.wsUri + " (reconnection attempt " + this.reconnectionAttempts + ")"); - this.reconnectTimer = setTimeout(function () { - _this.connect(); - _this.reconnectTimer = undefined; - }, (this.reconnectionAttempts === 1) ? 0 : this.configuration.reconnectionTimeout * 1000); - } - }; - /** - * Resets the error state of all servers in the configuration - */ - Transport.prototype.resetServerErrorStatus = function () { - for (var _i = 0, _a = this.configuration.wsServers; _i < _a.length; _i++) { - var websocket = _a[_i]; - websocket.isError = false; - } - }; - /** - * Retrieve the next server to which connect. - * @param {Boolean} force allows bypass of server error status checking - * @returns {Object} WsServer - */ - Transport.prototype.getNextWsServer = function (force) { - if (force === void 0) { force = false; } - if (this.noAvailableServers()) { - this.logger.warn("attempted to get next ws server but there are no available ws servers left"); - throw new Error("Attempted to get next ws server, but there are no available ws servers left."); - } - // Order servers by weight - var candidates = []; - for (var _i = 0, _a = this.configuration.wsServers; _i < _a.length; _i++) { - var wsServer = _a[_i]; - if (wsServer.isError && !force) { - continue; - } - else if (candidates.length === 0) { - candidates.push(wsServer); - } - else if (wsServer.weight > candidates[0].weight) { - candidates = [wsServer]; - } - else if (wsServer.weight === candidates[0].weight) { - candidates.push(wsServer); - } - } - var idx = Math.floor(Math.random() * candidates.length); - return candidates[idx]; - }; - /** - * Checks all configuration servers, returns true if all of them have isError: true and false otherwise - * @returns {Boolean} - */ - Transport.prototype.noAvailableServers = function () { - for (var _i = 0, _a = this.configuration.wsServers; _i < _a.length; _i++) { - var server = _a[_i]; - if (!server.isError) { - return false; - } - } - return true; - }; - // ============================== - // KeepAlive Stuff - // ============================== - /** - * Send a keep-alive (a double-CRLF sequence). - * @returns {Boolean} - */ - Transport.prototype.sendKeepAlive = function () { - var _this = this; - if (this.keepAliveDebounceTimeout) { - // We already have an outstanding keep alive, do not send another. - return; - } - this.keepAliveDebounceTimeout = setTimeout(function () { - _this.emit("keepAliveDebounceTimeout"); - _this.clearKeepAliveTimeout(); - }, this.configuration.keepAliveDebounce * 1000); - return this.send("\r\n\r\n"); - }; - Transport.prototype.clearKeepAliveTimeout = function () { - if (this.keepAliveDebounceTimeout) { - clearTimeout(this.keepAliveDebounceTimeout); - } - this.keepAliveDebounceTimeout = undefined; - }; - /** - * Start sending keep-alives. - */ - Transport.prototype.startSendingKeepAlives = function () { - var _this = this; - if (this.configuration.keepAliveInterval && !this.keepAliveInterval) { - this.keepAliveInterval = setInterval(function () { - _this.sendKeepAlive(); - _this.startSendingKeepAlives(); - }, computeKeepAliveTimeout(this.configuration.keepAliveInterval)); - } - }; - /** - * Stop sending keep-alives. - */ - Transport.prototype.stopSendingKeepAlives = function () { - if (this.keepAliveInterval) { - clearInterval(this.keepAliveInterval); - } - if (this.keepAliveDebounceTimeout) { - clearTimeout(this.keepAliveDebounceTimeout); - } - this.keepAliveInterval = undefined; - this.keepAliveDebounceTimeout = undefined; - }; - // ============================== - // Status Stuff - // ============================== - /** - * Checks given status against instance current status. Returns true if they match - * @param {Number} status - * @param {Boolean} [force] - * @returns {Boolean} - */ - Transport.prototype.statusAssert = function (status, force) { - if (status === this.status) { - return true; - } - else { - if (force) { - this.logger.warn("Attempted to assert " + - Object.keys(TransportStatus)[this.status] + " as " + - Object.keys(TransportStatus)[status] + "- continuing with option: 'force'"); - return true; - } - else { - this.logger.warn("Tried to assert " + - Object.keys(TransportStatus)[status] + " but is currently " + - Object.keys(TransportStatus)[this.status]); - return false; - } - } - }; - /** - * Transitions the status. Checks for legal transition via assertion beforehand - * @param {Number} status - * @param {Boolean} [force] - * @returns {Boolean} - */ - Transport.prototype.statusTransition = function (status, force) { - if (force === void 0) { force = false; } - this.logger.log("Attempting to transition status from " + - Object.keys(TransportStatus)[this.status] + " to " + - Object.keys(TransportStatus)[status]); - if ((status === TransportStatus.STATUS_CONNECTING && this.statusAssert(TransportStatus.STATUS_CLOSED, force)) || - (status === TransportStatus.STATUS_OPEN && this.statusAssert(TransportStatus.STATUS_CONNECTING, force)) || - (status === TransportStatus.STATUS_CLOSING && this.statusAssert(TransportStatus.STATUS_OPEN, force)) || - (status === TransportStatus.STATUS_CLOSED)) { - this.status = status; - return true; - } - else { - this.logger.warn("Status transition failed - result: no-op - reason:" + - " either gave an nonexistent status or attempted illegal transition"); - return false; - } - }; - // ============================== - // Configuration Handling - // ============================== - /** - * Configuration load. - * returns {Configuration} - */ - Transport.prototype.loadConfig = function (configuration) { - var settings = { - wsServers: [{ - scheme: "WSS", - sipUri: "", - weight: 0, - wsUri: "wss://edge.sip.onsip.com", - isError: false - }], - connectionTimeout: 5, - maxReconnectionAttempts: 3, - reconnectionTimeout: 4, - keepAliveInterval: 0, - keepAliveDebounce: 10, - // Logging - traceSip: false - }; - var configCheck = this.getConfigurationCheck(); - // Check Mandatory parameters - for (var parameter in configCheck.mandatory) { - if (!configuration.hasOwnProperty(parameter)) { - throw new Exceptions_1.Exceptions.ConfigurationError(parameter); - } - else { - var value = configuration[parameter]; - var checkedValue = configCheck.mandatory[parameter](value); - if (checkedValue !== undefined) { - settings[parameter] = checkedValue; - } - else { - throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); - } - } - } - // Check Optional parameters - for (var parameter in configCheck.optional) { - if (configuration.hasOwnProperty(parameter)) { - var value = configuration[parameter]; - // If the parameter value is an empty array, but shouldn't be, apply its default value. - // If the parameter value is null, empty string, or undefined then apply its default value. - // If it's a number with NaN value then also apply its default value. - // NOTE: JS does not allow "value === NaN", the following does the work: - if ((value instanceof Array && value.length === 0) || - (value === null || value === "" || value === undefined) || - (typeof (value) === "number" && isNaN(value))) { - continue; - } - var checkedValue = configCheck.optional[parameter](value); - if (checkedValue !== undefined) { - settings[parameter] = checkedValue; - } - else { - throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); - } - } - } - var skeleton = {}; // Fill the value of the configuration_skeleton - for (var parameter in settings) { - if (settings.hasOwnProperty(parameter)) { - skeleton[parameter] = { - value: settings[parameter], - }; - } - } - var returnConfiguration = Object.defineProperties({}, skeleton); - this.logger.log("configuration parameters after validation:"); - for (var parameter in settings) { - if (settings.hasOwnProperty(parameter)) { - this.logger.log("· " + parameter + ": " + JSON.stringify(settings[parameter])); - } - } - return returnConfiguration; - }; - /** - * Configuration checker. - * @return {Boolean} - */ - Transport.prototype.getConfigurationCheck = function () { - return { - mandatory: {}, - optional: { - // Note: this function used to call 'this.logger.error' but calling 'this' with anything here is invalid - wsServers: function (wsServers) { - /* Allow defining wsServers parameter as: - * String: "host" - * Array of Strings: ["host1", "host2"] - * Array of Objects: [{wsUri:"host1", weight:1}, {wsUri:"host2", weight:0}] - * Array of Objects and Strings: [{wsUri:"host1"}, "host2"] - */ - if (typeof wsServers === "string") { - wsServers = [{ wsUri: wsServers }]; - } - else if (wsServers instanceof Array) { - for (var idx = 0; idx < wsServers.length; idx++) { - if (typeof wsServers[idx] === "string") { - wsServers[idx] = { wsUri: wsServers[idx] }; - } - } - } - else { - return; - } - if (wsServers.length === 0) { - return false; - } - for (var _i = 0, wsServers_1 = wsServers; _i < wsServers_1.length; _i++) { - var wsServer = wsServers_1[_i]; - if (!wsServer.wsUri) { - return; - } - if (wsServer.weight && !Number(wsServer.weight)) { - return; - } - var url = core_1.Grammar.parse(wsServer.wsUri, "absoluteURI"); - if (url === -1) { - return; - } - else if (["wss", "ws", "udp"].indexOf(url.scheme) < 0) { - return; - } - else { - wsServer.sipUri = ""; - if (!wsServer.weight) { - wsServer.weight = 0; - } - wsServer.isError = false; - wsServer.scheme = url.scheme.toUpperCase(); - } - } - return wsServers; - }, - keepAliveInterval: function (keepAliveInterval) { - if (Utils_1.Utils.isDecimal(keepAliveInterval)) { - var value = Number(keepAliveInterval); - if (value > 0) { - return value; - } - } - }, - keepAliveDebounce: function (keepAliveDebounce) { - if (Utils_1.Utils.isDecimal(keepAliveDebounce)) { - var value = Number(keepAliveDebounce); - if (value > 0) { - return value; - } - } - }, - traceSip: function (traceSip) { - if (typeof traceSip === "boolean") { - return traceSip; - } - }, - connectionTimeout: function (connectionTimeout) { - if (Utils_1.Utils.isDecimal(connectionTimeout)) { - var value = Number(connectionTimeout); - if (value > 0) { - return value; - } - } - }, - maxReconnectionAttempts: function (maxReconnectionAttempts) { - if (Utils_1.Utils.isDecimal(maxReconnectionAttempts)) { - var value = Number(maxReconnectionAttempts); - if (value >= 0) { - return value; - } - } - }, - reconnectionTimeout: function (reconnectionTimeout) { - if (Utils_1.Utils.isDecimal(reconnectionTimeout)) { - var value = Number(reconnectionTimeout); - if (value > 0) { - return value; - } - } - } - } - }; - }; - Transport.C = TransportStatus; - return Transport; -}(core_1.Transport)); -exports.Transport = Transport; - - -/***/ }), -/* 104 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var Modifiers = tslib_1.__importStar(__webpack_require__(101)); -exports.Modifiers = Modifiers; -var Simple_1 = __webpack_require__(105); -exports.Simple = Simple_1.Simple; -var SessionDescriptionHandler_1 = __webpack_require__(94); -exports.SessionDescriptionHandler = SessionDescriptionHandler_1.SessionDescriptionHandler; -var Transport_1 = __webpack_require__(103); -exports.Transport = Transport_1.Transport; - - -/***/ }), -/* 105 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = __webpack_require__(1); -var events_1 = __webpack_require__(30); -var UA_1 = __webpack_require__(93); -var Modifiers = tslib_1.__importStar(__webpack_require__(101)); -/* Simple - * @class Simple - */ -var SimpleStatus; -(function (SimpleStatus) { - SimpleStatus[SimpleStatus["STATUS_NULL"] = 0] = "STATUS_NULL"; - SimpleStatus[SimpleStatus["STATUS_NEW"] = 1] = "STATUS_NEW"; - SimpleStatus[SimpleStatus["STATUS_CONNECTING"] = 2] = "STATUS_CONNECTING"; - SimpleStatus[SimpleStatus["STATUS_CONNECTED"] = 3] = "STATUS_CONNECTED"; - SimpleStatus[SimpleStatus["STATUS_COMPLETED"] = 4] = "STATUS_COMPLETED"; -})(SimpleStatus = exports.SimpleStatus || (exports.SimpleStatus = {})); -var Simple = /** @class */ (function (_super) { - tslib_1.__extends(Simple, _super); - function Simple(options) { - var _this = _super.call(this) || this; - /* - * { - * media: { - * remote: { - * audio: , - * video: - * }, - * local: { - * video: - * } - * }, - * ua: { - * - * } - * } - */ - if (options.media.remote.video) { - _this.video = true; - } - else { - _this.video = false; - } - if (options.media.remote.audio) { - _this.audio = true; - } - else { - _this.audio = false; - } - if (!_this.audio && !_this.video) { - // Need to do at least audio or video - // Error - throw new Error("At least one remote audio or video element is required for Simple."); - } - _this.options = options; - // https://stackoverflow.com/questions/7944460/detect-safari-browser - var browserUa = navigator.userAgent.toLowerCase(); - var isSafari = false; - var isFirefox = false; - if (browserUa.indexOf("safari") > -1 && browserUa.indexOf("chrome") < 0) { - isSafari = true; - } - else if (browserUa.indexOf("firefox") > -1 && browserUa.indexOf("chrome") < 0) { - isFirefox = true; - } - var sessionDescriptionHandlerFactoryOptions = {}; - if (isSafari) { - sessionDescriptionHandlerFactoryOptions.modifiers = [Modifiers.stripG722]; - } - if (isFirefox) { - sessionDescriptionHandlerFactoryOptions.alwaysAcquireMediaFirst = true; - } - if (!_this.options.ua.uri) { - _this.anonymous = true; - } - else { - _this.anonymous = false; - } - _this.ua = new UA_1.UA({ - // User Configurable Options - uri: _this.options.ua.uri, - authorizationUser: _this.options.ua.authorizationUser, - password: _this.options.ua.password, - displayName: _this.options.ua.displayName, - // Undocumented "Advanced" Options - userAgentString: _this.options.ua.userAgentString, - // Fixed Options - register: true, - sessionDescriptionHandlerFactoryOptions: sessionDescriptionHandlerFactoryOptions, - transportOptions: { - traceSip: _this.options.ua.traceSip, - wsServers: _this.options.ua.wsServers - } - }); - _this.state = SimpleStatus.STATUS_NULL; - _this.logger = _this.ua.getLogger("sip.simple"); - _this.ua.on("registered", function () { - _this.emit("registered", _this.ua); - }); - _this.ua.on("unregistered", function () { - _this.emit("unregistered", _this.ua); - }); - _this.ua.on("registrationFailed", function () { - _this.emit("unregistered", _this.ua); - }); - _this.ua.on("invite", function (session) { - // If there is already an active session reject the incoming session - if (_this.state !== SimpleStatus.STATUS_NULL && _this.state !== SimpleStatus.STATUS_COMPLETED) { - _this.logger.warn("Rejecting incoming call. Simple only supports 1 call at a time"); - session.reject(); - return; - } - _this.session = session; - _this.setupSession(); - _this.emit("ringing", _this.session); - }); - _this.ua.on("message", function (message) { - _this.emit("message", message); - }); - return _this; - } - Simple.prototype.call = function (destination) { - if (!this.ua || !this.checkRegistration()) { - this.logger.warn("A registered UA is required for calling"); - return; - } - if (this.state !== SimpleStatus.STATUS_NULL && this.state !== SimpleStatus.STATUS_COMPLETED) { - this.logger.warn("Cannot make more than a single call with Simple"); - return; - } - // Safari hack, because you cannot call .play() from a non user action - if (this.options.media.remote.audio) { - this.options.media.remote.audio.autoplay = true; - } - if (this.options.media.remote.video) { - this.options.media.remote.video.autoplay = true; - } - if (this.options.media.local && this.options.media.local.video) { - this.options.media.local.video.autoplay = true; - this.options.media.local.video.volume = 0; - } - this.session = this.ua.invite(destination, { - sessionDescriptionHandlerOptions: { - constraints: { - audio: this.audio, - video: this.video - } - } - }); - this.setupSession(); - return this.session; - }; - Simple.prototype.answer = function () { - if (this.state !== SimpleStatus.STATUS_NEW && this.state !== SimpleStatus.STATUS_CONNECTING) { - this.logger.warn("No call to answer"); - return; - } - // Safari hack, because you cannot call .play() from a non user action - if (this.options.media.remote.audio) { - this.options.media.remote.audio.autoplay = true; - } - if (this.options.media.remote.video) { - this.options.media.remote.video.autoplay = true; - } - return this.session.accept({ - sessionDescriptionHandlerOptions: { - constraints: { - audio: this.audio, - video: this.video - } - } - }); - // emit call is active - }; - Simple.prototype.reject = function () { - if (this.state !== SimpleStatus.STATUS_NEW && this.state !== SimpleStatus.STATUS_CONNECTING) { - this.logger.warn("Call is already answered"); - return; - } - return this.session.reject(); - }; - Simple.prototype.hangup = function () { - if (this.state !== SimpleStatus.STATUS_CONNECTED && - this.state !== SimpleStatus.STATUS_CONNECTING && - this.state !== SimpleStatus.STATUS_NEW) { - this.logger.warn("No active call to hang up on"); - return; - } - if (this.state !== SimpleStatus.STATUS_CONNECTED) { - return this.session.cancel(); - } - else if (this.session) { - return this.session.bye(); - } - }; - Simple.prototype.hold = function () { - if (this.state !== SimpleStatus.STATUS_CONNECTED || !this.session || this.session.localHold) { - this.logger.warn("Cannot put call on hold"); - return; - } - this.mute(); - this.logger.log("Placing session on hold"); - return this.session.hold(); - }; - Simple.prototype.unhold = function () { - if (this.state !== SimpleStatus.STATUS_CONNECTED || !this.session || !this.session.localHold) { - this.logger.warn("Cannot unhold a call that is not on hold"); - return; - } - this.unmute(); - this.logger.log("Placing call off hold"); - return this.session.unhold(); - }; - Simple.prototype.mute = function () { - if (this.state !== SimpleStatus.STATUS_CONNECTED) { - this.logger.warn("An acitve call is required to mute audio"); - return; - } - this.logger.log("Muting Audio"); - this.toggleMute(true); - this.emit("mute", this); - }; - Simple.prototype.unmute = function () { - if (this.state !== SimpleStatus.STATUS_CONNECTED) { - this.logger.warn("An active call is required to unmute audio"); - return; - } - this.logger.log("Unmuting Audio"); - this.toggleMute(false); - this.emit("unmute", this); - }; - Simple.prototype.sendDTMF = function (tone) { - if (this.state !== SimpleStatus.STATUS_CONNECTED || !this.session) { - this.logger.warn("An active call is required to send a DTMF tone"); - return; - } - this.logger.log("Sending DTMF tone: " + tone); - this.session.dtmf(tone); - }; - Simple.prototype.message = function (destination, message) { - if (!this.ua || !this.checkRegistration()) { - this.logger.warn("A registered UA is required to send a message"); - return; - } - if (!destination || !message) { - this.logger.warn("A destination and message are required to send a message"); - return; - } - this.ua.message(destination, message); - }; - // Private Helpers - Simple.prototype.checkRegistration = function () { - return (this.anonymous || (this.ua && this.ua.isRegistered())); - }; - Simple.prototype.setupRemoteMedia = function () { - var _this = this; - if (!this.session) { - this.logger.warn("No session to set remote media on"); - return; - } - // If there is a video track, it will attach the video and audio to the same element - var pc = this.session.sessionDescriptionHandler.peerConnection; - var remoteStream; - if (pc.getReceivers) { - remoteStream = new MediaStream(); - pc.getReceivers().forEach(function (receiver) { - var track = receiver.track; - if (track) { - remoteStream.addTrack(track); - } - }); - } - else { - remoteStream = pc.getRemoteStreams()[0]; - } - if (this.video) { - this.options.media.remote.video.srcObject = remoteStream; - this.options.media.remote.video.play().catch(function () { - _this.logger.log("play was rejected"); - }); - } - else if (this.audio) { - this.options.media.remote.audio.srcObject = remoteStream; - this.options.media.remote.audio.play().catch(function () { - _this.logger.log("play was rejected"); - }); - } - }; - Simple.prototype.setupLocalMedia = function () { - if (!this.session) { - this.logger.warn("No session to set local media on"); - return; - } - if (this.video && this.options.media.local && this.options.media.local.video) { - var pc = this.session.sessionDescriptionHandler.peerConnection; - var localStream_1; - if (pc.getSenders) { - localStream_1 = new MediaStream(); - pc.getSenders().forEach(function (sender) { - var track = sender.track; - if (track && track.kind === "video") { - localStream_1.addTrack(track); - } - }); - } - else { - localStream_1 = pc.getLocalStreams()[0]; - } - this.options.media.local.video.srcObject = localStream_1; - this.options.media.local.video.volume = 0; - this.options.media.local.video.play(); - } - }; - Simple.prototype.cleanupMedia = function () { - if (this.video) { - this.options.media.remote.video.srcObject = null; - this.options.media.remote.video.pause(); - if (this.options.media.local && this.options.media.local.video) { - this.options.media.local.video.srcObject = null; - this.options.media.local.video.pause(); - } - } - if (this.audio) { - this.options.media.remote.audio.srcObject = null; - this.options.media.remote.audio.pause(); - } - }; - Simple.prototype.setupSession = function () { - var _this = this; - if (!this.session) { - this.logger.warn("No session to set up"); - return; - } - this.state = SimpleStatus.STATUS_NEW; - this.emit("new", this.session); - this.session.on("progress", function () { return _this.onProgress(); }); - this.session.on("accepted", function () { return _this.onAccepted(); }); - this.session.on("rejected", function () { return _this.onEnded(); }); - this.session.on("failed", function () { return _this.onFailed(); }); - this.session.on("terminated", function () { return _this.onEnded(); }); - }; - Simple.prototype.destroyMedia = function () { - if (this.session && this.session.sessionDescriptionHandler) { - this.session.sessionDescriptionHandler.close(); - } - }; - Simple.prototype.toggleMute = function (mute) { - if (!this.session) { - this.logger.warn("No session to toggle mute"); - return; - } - var pc = this.session.sessionDescriptionHandler.peerConnection; - if (pc.getSenders) { - pc.getSenders().forEach(function (sender) { - if (sender.track) { - sender.track.enabled = !mute; - } - }); - } - else { - pc.getLocalStreams().forEach(function (stream) { - stream.getAudioTracks().forEach(function (track) { - track.enabled = !mute; - }); - stream.getVideoTracks().forEach(function (track) { - track.enabled = !mute; - }); - }); - } - }; - Simple.prototype.onAccepted = function () { - var _this = this; - if (!this.session) { - this.logger.warn("No session for accepting"); - return; - } - this.state = SimpleStatus.STATUS_CONNECTED; - this.emit("connected", this.session); - this.setupLocalMedia(); - this.setupRemoteMedia(); - if (this.session.sessionDescriptionHandler) { - this.session.sessionDescriptionHandler.on("addTrack", function () { - _this.logger.log("A track has been added, triggering new remoteMedia setup"); - _this.setupRemoteMedia(); - }); - this.session.sessionDescriptionHandler.on("addStream", function () { - _this.logger.log("A stream has been added, trigger new remoteMedia setup"); - _this.setupRemoteMedia(); - }); - } - this.session.on("dtmf", function (request, dtmf) { - _this.emit("dtmf", dtmf.tone); - }); - this.session.on("bye", function () { return _this.onEnded(); }); - }; - Simple.prototype.onProgress = function () { - this.state = SimpleStatus.STATUS_CONNECTING; - this.emit("connecting", this.session); - }; - Simple.prototype.onFailed = function () { - this.onEnded(); - }; - Simple.prototype.onEnded = function () { - this.state = SimpleStatus.STATUS_COMPLETED; - this.emit("ended", this.session); - this.cleanupMedia(); - }; - Simple.C = SimpleStatus; - return Simple; -}(events_1.EventEmitter)); -exports.Simple = Simple; - - -/***/ }) -/******/ ]); -}); \ No newline at end of file diff --git a/dist/sip.min.js b/dist/sip.min.js deleted file mode 100644 index 8f48d4f07..000000000 --- a/dist/sip.min.js +++ /dev/null @@ -1 +0,0 @@ -!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.SIP=t():e.SIP=t()}(this,(function(){return function(e){var t={};function r(i){if(t[i])return t[i].exports;var n=t[i]={i:i,l:!1,exports:{}};return e[i].call(n.exports,n,n.exports,r),n.l=!0,n.exports}return r.m=e,r.c=t,r.d=function(e,t,i){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:i})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var i=Object.create(null);if(r.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var n in e)r.d(i,n,function(t){return e[t]}.bind(null,n));return i},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=109)}([function(e,t,r){"use strict";r.r(t),r.d(t,"__extends",(function(){return n})),r.d(t,"__assign",(function(){return s})),r.d(t,"__rest",(function(){return o})),r.d(t,"__decorate",(function(){return a})),r.d(t,"__param",(function(){return c})),r.d(t,"__metadata",(function(){return u})),r.d(t,"__awaiter",(function(){return d})),r.d(t,"__generator",(function(){return p})),r.d(t,"__exportStar",(function(){return h})),r.d(t,"__values",(function(){return l})),r.d(t,"__read",(function(){return g})),r.d(t,"__spread",(function(){return f})),r.d(t,"__spreadArrays",(function(){return m})),r.d(t,"__await",(function(){return v})),r.d(t,"__asyncGenerator",(function(){return S})),r.d(t,"__asyncDelegator",(function(){return T})),r.d(t,"__asyncValues",(function(){return y})),r.d(t,"__makeTemplateObject",(function(){return E})),r.d(t,"__importStar",(function(){return b})),r.d(t,"__importDefault",(function(){return C}));var i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};function n(e,t){function r(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var s=function(){return(s=Object.assign||function(e){for(var t,r=1,i=arguments.length;r=0;a--)(n=e[a])&&(o=(s<3?n(o):s>3?n(t,r,o):n(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o}function c(e,t){return function(r,i){t(r,i,e)}}function u(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function d(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){e.done?n(e.value):new r((function(t){t(e.value)})).then(o,a)}c((i=i.apply(e,t||[])).next())}))}function p(e,t){var r,i,n,s,o={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;o;)try{if(r=1,i&&(n=2&s[0]?i.return:s[0]?i.throw||((n=i.return)&&n.call(i),0):i.next)&&!(n=n.call(i,s[1])).done)return n;switch(i=0,n&&(s=[2&s[0],n.value]),s[0]){case 0:case 1:n=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,i=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!(n=(n=o.trys).length>0&&n[n.length-1])&&(6===s[0]||2===s[0])){o=0;continue}if(3===s[0]&&(!n||s[1]>n[0]&&s[1]=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}function g(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var i,n,s=r.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(i=s.next()).done;)o.push(i.value)}catch(e){n={error:e}}finally{try{i&&!i.done&&(r=s.return)&&r.call(s)}finally{if(n)throw n.error}}return o}function f(){for(var e=[],t=0;t1||a(e,t)}))})}function a(e,t){try{(r=n[e](t)).value instanceof v?Promise.resolve(r.value.v).then(c,u):d(s[0][2],r)}catch(e){d(s[0][3],e)}var r}function c(e){a("next",e)}function u(e){a("throw",e)}function d(e,t){e(t),s.shift(),s.length&&a(s[0][0],s[0][1])}}function T(e){var t,r;return t={},i("next"),i("throw",(function(e){throw e})),i("return"),t[Symbol.iterator]=function(){return this},t;function i(i,n){t[i]=e[i]?function(t){return(r=!r)?{value:v(e[i](t)),done:"return"===i}:n?n(t):t}:n}}function y(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=l(e),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(r){t[r]=e[r]&&function(t){return new Promise((function(i,n){(function(e,t,r,i){Promise.resolve(i).then((function(t){e({value:t,done:r})}),t)})(i,n,(t=e[r](t)).done,t.value)}))}}}function E(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}function b(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function C(e){return e&&e.__esModule?e:{default:e}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0);i.__exportStar(r(22),t),i.__exportStar(r(35),t),i.__exportStar(r(67),t),i.__exportStar(r(68),t),i.__exportStar(r(69),t),i.__exportStar(r(35),t),i.__exportStar(r(25),t),i.__exportStar(r(13),t),i.__exportStar(r(23),t)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0);i.__exportStar(r(55),t),i.__exportStar(r(57),t),i.__exportStar(r(59),t),i.__exportStar(r(29),t),i.__exportStar(r(19),t),i.__exportStar(r(32),t),i.__exportStar(r(33),t),i.__exportStar(r(20),t),i.__exportStar(r(34),t),i.__exportStar(r(62),t),i.__exportStar(r(21),t),i.__exportStar(r(30),t)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(2),n=r(1),s=function(){function e(e,t,r,i){this.transactionConstructor=e,this.core=t,this.message=r,this.delegate=i,this.challenged=!1,this.stale=!1,this.logger=this.loggerFactory.getLogger("sip.user-agent-client"),this.init()}return e.prototype.dispose=function(){this.transaction.dispose()},Object.defineProperty(e.prototype,"loggerFactory",{get:function(){return this.core.loggerFactory},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"transaction",{get:function(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction},enumerable:!0,configurable:!0}),e.prototype.cancel=function(t,r){var s=this;if(void 0===r&&(r={}),!this.transaction)throw new Error("Transaction undefined.");if(!this.message.to)throw new Error("To undefined.");if(!this.message.from)throw new Error("From undefined.");var o=this.core.makeOutgoingRequestMessage(i.C.CANCEL,this.message.ruri,this.message.from.uri,this.message.to.uri,{toTag:this.message.toTag,fromTag:this.message.fromTag,callId:this.message.callId,cseq:this.message.cseq},r.extraHeaders);if(o.branch=this.message.branch,this.message.headers.Route&&(o.headers.Route=this.message.headers.Route),t&&o.setHeader("Reason",t),this.transaction.state===n.TransactionState.Proceeding)new e(n.NonInviteClientTransaction,this.core,o);else this.transaction.once("stateChanged",(function(){if(s.transaction&&s.transaction.state===n.TransactionState.Proceeding)new e(n.NonInviteClientTransaction,s.core,o)}));return o},e.prototype.authenticationGuard=function(e){var t,r,i=e.statusCode;if(!i)throw new Error("Response status code undefined.");if(401!==i&&407!==i)return!0;if(401===i?(t=e.parseHeader("www-authenticate"),r="authorization"):(t=e.parseHeader("proxy-authenticate"),r="proxy-authorization"),!t)return this.logger.warn(i+" with wrong or missing challenge, cannot authenticate"),!0;if(this.challenged&&(this.stale||!0!==t.stale))return this.logger.warn(i+" apparently in authentication loop, cannot authenticate"),!0;if(!this.credentials&&(this.credentials=this.core.configuration.authenticationFactory(),!this.credentials))return this.logger.warn("Unable to obtain credentials, cannot authenticate"),!0;if(!this.credentials.authenticate(this.message,t))return!0;this.challenged=!0,t.stale&&(this.stale=!0);var n=this.message.cseq+=1;return this.message.setHeader("cseq",n+" "+this.message.method),this.message.setHeader(r,this.credentials.toString()),this.init(),!1},e.prototype.receiveResponse=function(e){if(this.authenticationGuard(e)){var t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e});break;case/^1[0-9]{2}$/.test(t):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e});break;case/^2[0-9]{2}$/.test(t):this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e});break;case/^3[0-9]{2}$/.test(t):this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e});break;case/^[4-6][0-9]{2}$/.test(t):this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e});break;default:throw new Error("Invalid status code "+t)}}},e.prototype.init=function(){var e=this,t={loggerFactory:this.loggerFactory,onRequestTimeout:function(){return e.onRequestTimeout()},onStateChange:function(t){t===n.TransactionState.Terminated&&(e.core.userAgentClients.delete(i),r===e._transaction&&e.dispose())},onTransportError:function(t){return e.onTransportError(t)},receiveResponse:function(t){return e.receiveResponse(t)}},r=new this.transactionConstructor(this.message,this.core.transport,t);this._transaction=r;var i=r.id+r.request.method;this.core.userAgentClients.set(i,this)},e.prototype.onRequestTimeout=function(){this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout.");var e=new i.IncomingResponseMessage;e.statusCode=408,e.reasonPhrase="Request Timeout",this.receiveResponse(e)},e.prototype.onTransportError=function(e){this.logger.error(e.message),this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable.");var t=new i.IncomingResponseMessage;t.statusCode=503,t.reasonPhrase="Service Unavailable",this.receiveResponse(t)},e}();t.UserAgentClient=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(16),n=r(2),s=r(10),o=r(1),a=function(){function e(e,t,r,i){this.transactionConstructor=e,this.core=t,this.message=r,this.delegate=i,this.logger=this.loggerFactory.getLogger("sip.user-agent-server"),this.toTag=r.toTag?r.toTag:s.newTag(),this.init()}return e.prototype.dispose=function(){this.transaction.dispose()},Object.defineProperty(e.prototype,"loggerFactory",{get:function(){return this.core.loggerFactory},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"transaction",{get:function(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction},enumerable:!0,configurable:!0}),e.prototype.accept=function(e){if(void 0===e&&(e={statusCode:200}),!this.acceptable)throw new i.TransactionStateError(this.message.method+" not acceptable in state "+this.transaction.state+".");var t=e.statusCode;if(t<200||t>299)throw new TypeError("Invalid statusCode: "+t);return this.reply(e)},e.prototype.progress=function(e){if(void 0===e&&(e={statusCode:180}),!this.progressable)throw new i.TransactionStateError(this.message.method+" not progressable in state "+this.transaction.state+".");var t=e.statusCode;if(t<101||t>199)throw new TypeError("Invalid statusCode: "+t);return this.reply(e)},e.prototype.redirect=function(e,t){if(void 0===t&&(t={statusCode:302}),!this.redirectable)throw new i.TransactionStateError(this.message.method+" not redirectable in state "+this.transaction.state+".");var r=t.statusCode;if(r<300||r>399)throw new TypeError("Invalid statusCode: "+r);var n=new Array;return e.forEach((function(e){return n.push("Contact: "+e.toString())})),t.extraHeaders=(t.extraHeaders||[]).concat(n),this.reply(t)},e.prototype.reject=function(e){if(void 0===e&&(e={statusCode:480}),!this.rejectable)throw new i.TransactionStateError(this.message.method+" not rejectable in state "+this.transaction.state+".");var t=e.statusCode;if(t<400||t>699)throw new TypeError("Invalid statusCode: "+t);return this.reply(e)},e.prototype.trying=function(e){if(!this.tryingable)throw new i.TransactionStateError(this.message.method+" not tryingable in state "+this.transaction.state+".");return this.reply({statusCode:100})},e.prototype.receiveCancel=function(e){this.delegate&&this.delegate.onCancel&&this.delegate.onCancel(e)},Object.defineProperty(e.prototype,"acceptable",{get:function(){if(this.transaction instanceof o.InviteServerTransaction)return this.transaction.state===o.TransactionState.Proceeding||this.transaction.state===o.TransactionState.Accepted;if(this.transaction instanceof o.NonInviteServerTransaction)return this.transaction.state===o.TransactionState.Trying||this.transaction.state===o.TransactionState.Proceeding;throw new Error("Unknown transaction type.")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"progressable",{get:function(){if(this.transaction instanceof o.InviteServerTransaction)return this.transaction.state===o.TransactionState.Proceeding;if(this.transaction instanceof o.NonInviteServerTransaction)return!1;throw new Error("Unknown transaction type.")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"redirectable",{get:function(){if(this.transaction instanceof o.InviteServerTransaction)return this.transaction.state===o.TransactionState.Proceeding;if(this.transaction instanceof o.NonInviteServerTransaction)return this.transaction.state===o.TransactionState.Trying||this.transaction.state===o.TransactionState.Proceeding;throw new Error("Unknown transaction type.")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rejectable",{get:function(){if(this.transaction instanceof o.InviteServerTransaction)return this.transaction.state===o.TransactionState.Proceeding;if(this.transaction instanceof o.NonInviteServerTransaction)return this.transaction.state===o.TransactionState.Trying||this.transaction.state===o.TransactionState.Proceeding;throw new Error("Unknown transaction type.")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"tryingable",{get:function(){if(this.transaction instanceof o.InviteServerTransaction)return this.transaction.state===o.TransactionState.Proceeding;if(this.transaction instanceof o.NonInviteServerTransaction)return this.transaction.state===o.TransactionState.Trying;throw new Error("Unknown transaction type.")},enumerable:!0,configurable:!0}),e.prototype.reply=function(e){e.toTag||100===e.statusCode||(e.toTag=this.toTag),e.userAgent=e.userAgent||this.core.configuration.userAgentHeaderFieldValue,e.supported=e.supported||this.core.configuration.supportedOptionTagsResponse;var t=n.constructOutgoingResponse(this.message,e);return this.transaction.receiveResponse(e.statusCode,t.message),t},e.prototype.init=function(){var e=this,t={loggerFactory:this.loggerFactory,onStateChange:function(t){t===o.TransactionState.Terminated&&(e.core.userAgentServers.delete(i),e.dispose())},onTransportError:function(t){e.logger.error(t.message),e.delegate&&e.delegate.onTransportError?e.delegate.onTransportError(t):e.logger.error("User agent server response transport error.")}},r=new this.transactionConstructor(this.message,this.core.transport,t);this._transaction=r;var i=r.id;this.core.userAgentServers.set(r.id,this)},e}();t.UserAgentServer=a},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0);i.__exportStar(r(17),t),i.__exportStar(r(16),t),i.__exportStar(r(71),t),i.__exportStar(r(2),t),i.__exportStar(r(15),t),i.__exportStar(r(27),t),i.__exportStar(r(1),t),i.__exportStar(r(73),t),i.__exportStar(r(50),t),i.__exportStar(r(6),t),i.__exportStar(r(86),t)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=500;t.Timers={T1:i,T2:4e3,T4:5e3,TIMER_B:32e3,TIMER_D:0,TIMER_F:32e3,TIMER_H:32e3,TIMER_I:0,TIMER_J:0,TIMER_K:0,TIMER_L:32e3,TIMER_M:32e3,TIMER_N:32e3,PROVISIONAL_RESPONSE_INTERVAL:6e4}},function(e,t,r){"use strict";var i,n="object"==typeof Reflect?Reflect:null,s=n&&"function"==typeof n.apply?n.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};i=n&&"function"==typeof n.ownKeys?n.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var o=Number.isNaN||function(e){return e!=e};function a(){a.init.call(this)}e.exports=a,a.EventEmitter=a,a.prototype._events=void 0,a.prototype._eventsCount=0,a.prototype._maxListeners=void 0;var c=10;function u(e){return void 0===e._maxListeners?a.defaultMaxListeners:e._maxListeners}function d(e,t,r,i){var n,s,o,a;if("function"!=typeof r)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof r);if(void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),s=e._events),o=s[t]),void 0===o)o=s[t]=r,++e._eventsCount;else if("function"==typeof o?o=s[t]=i?[r,o]:[o,r]:i?o.unshift(r):o.push(r),(n=u(e))>0&&o.length>n&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=o.length,a=c,console&&console.warn&&console.warn(a)}return e}function p(){for(var e=[],t=0;t0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=n[e];if(void 0===c)return!1;if("function"==typeof c)s(c,this,t);else{var u=c.length,d=f(c,u);for(r=0;r=0;s--)if(r[s]===t||r[s].listener===t){o=r[s].listener,n=s;break}if(n<0)return this;0===n?r.shift():function(e,t){for(;t+1=0;i--)this.removeListener(e,t[i]);return this},a.prototype.listeners=function(e){return l(this,e,!0)},a.prototype.rawListeners=function(e){return l(this,e,!1)},a.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):g.call(e,t)},a.prototype.listenerCount=g,a.prototype.eventNames=function(){return this._eventsCount>0?i(this._events):[]}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e){e[e.STATUS_EARLY=1]="STATUS_EARLY",e[e.STATUS_CONFIRMED=2]="STATUS_CONFIRMED"}(t.DialogStatus||(t.DialogStatus={})),function(e){e[e.STATUS_NULL=0]="STATUS_NULL",e[e.STATUS_INVITE_SENT=1]="STATUS_INVITE_SENT",e[e.STATUS_1XX_RECEIVED=2]="STATUS_1XX_RECEIVED",e[e.STATUS_INVITE_RECEIVED=3]="STATUS_INVITE_RECEIVED",e[e.STATUS_WAITING_FOR_ANSWER=4]="STATUS_WAITING_FOR_ANSWER",e[e.STATUS_ANSWERED=5]="STATUS_ANSWERED",e[e.STATUS_WAITING_FOR_PRACK=6]="STATUS_WAITING_FOR_PRACK",e[e.STATUS_WAITING_FOR_ACK=7]="STATUS_WAITING_FOR_ACK",e[e.STATUS_CANCELED=8]="STATUS_CANCELED",e[e.STATUS_TERMINATED=9]="STATUS_TERMINATED",e[e.STATUS_ANSWERED_WAITING_FOR_PRACK=10]="STATUS_ANSWERED_WAITING_FOR_PRACK",e[e.STATUS_EARLY_MEDIA=11]="STATUS_EARLY_MEDIA",e[e.STATUS_CONFIRMED=12]="STATUS_CONFIRMED"}(t.SessionStatus||(t.SessionStatus={})),function(e){e[e.ClientContext=0]="ClientContext",e[e.ConfigurationError=1]="ConfigurationError",e[e.Dialog=2]="Dialog",e[e.DigestAuthentication=3]="DigestAuthentication",e[e.DTMF=4]="DTMF",e[e.IncomingMessage=5]="IncomingMessage",e[e.IncomingRequest=6]="IncomingRequest",e[e.IncomingResponse=7]="IncomingResponse",e[e.InvalidStateError=8]="InvalidStateError",e[e.InviteClientContext=9]="InviteClientContext",e[e.InviteServerContext=10]="InviteServerContext",e[e.Logger=11]="Logger",e[e.LoggerFactory=12]="LoggerFactory",e[e.MethodParameterError=13]="MethodParameterError",e[e.NameAddrHeader=14]="NameAddrHeader",e[e.NotSupportedError=15]="NotSupportedError",e[e.OutgoingRequest=16]="OutgoingRequest",e[e.Parameters=17]="Parameters",e[e.PublishContext=18]="PublishContext",e[e.ReferClientContext=19]="ReferClientContext",e[e.ReferServerContext=20]="ReferServerContext",e[e.RegisterContext=21]="RegisterContext",e[e.RenegotiationError=22]="RenegotiationError",e[e.RequestSender=23]="RequestSender",e[e.ServerContext=24]="ServerContext",e[e.Session=25]="Session",e[e.SessionDescriptionHandler=26]="SessionDescriptionHandler",e[e.SessionDescriptionHandlerError=27]="SessionDescriptionHandlerError",e[e.SessionDescriptionHandlerObserver=28]="SessionDescriptionHandlerObserver",e[e.Subscription=29]="Subscription",e[e.Transport=30]="Transport",e[e.UA=31]="UA",e[e.URI=32]="URI"}(t.TypeStrings||(t.TypeStrings={})),function(e){e[e.STATUS_INIT=0]="STATUS_INIT",e[e.STATUS_STARTING=1]="STATUS_STARTING",e[e.STATUS_READY=2]="STATUS_READY",e[e.STATUS_USER_CLOSED=3]="STATUS_USER_CLOSED",e[e.STATUS_NOT_READY=4]="STATUS_NOT_READY"}(t.UAStatus||(t.UAStatus={}))},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(11),n=r(29),s=r(30);!function(e){e.defer=function(){var e={};return e.promise=new Promise((function(t,r){e.resolve=t,e.reject=r})),e},e.reducePromises=function(e,t){return e.reduce((function(e,t){return e=e.then(t)}),Promise.resolve(t))},e.str_utf8_length=function(e){return encodeURIComponent(e).replace(/%[A-F\d]{2}/g,"U").length},e.generateFakeSDP=function(e){if(e){var t=e.indexOf("o="),r=e.indexOf("\r\n",t);return"v=0\r\n"+e.slice(t,r)+"\r\ns=-\r\nt=0 0\r\nc=IN IP4 0.0.0.0"}},e.isDecimal=function(e){var t=parseInt(e,10);return!isNaN(t)&&parseFloat(e)===t},e.createRandomToken=function(e,t){void 0===t&&(t=32);for(var r="",i=0;i699)throw new TypeError("Invalid statusCode: "+t);if(t)return e.getReasonHeaderValue(t,r)},e.buildStatusLine=function(t,r){if(!t||t<100||t>699)throw new TypeError("Invalid statusCode: "+t);if(r&&"string"!=typeof r&&!(r instanceof String))throw new TypeError("Invalid reason: "+r);return"SIP/2.0 "+t+" "+(r=e.getReasonPhrase(t,r))+"\r\n"},e.fromBodyObj=function(e){var t=e.body,r=e.contentType;return{contentDisposition:function(e){return"application/sdp"===e?"session":"render"}(r),contentType:r,content:t}},e.toBodyObj=function(e){return{body:e.content,contentType:e.contentType}}}(t.Utils||(t.Utils={}))},function(e,t,r){"use strict";function i(e,t){void 0===t&&(t=32);for(var r="",i=0;i=this.headers[e].length)){var r=this.headers[e][t],s=r.raw;if(r.parsed)return r.parsed;var o=i.Grammar.parse(s,e.replace(/-/g,"_"));return-1===o?void this.headers[e].splice(t,1):(r.parsed=o,o)}},e.prototype.s=function(e,t){return void 0===t&&(t=0),this.parseHeader(e,t)},e.prototype.setHeader=function(e,t){this.headers[n.headerize(e)]=[{raw:t}]},e.prototype.toString=function(){return this.data},e}();t.IncomingMessage=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=function(e){function t(t,r,i){var n=e.call(this,i)||this;return n.uri=t,n._displayName=r,n}return i.__extends(t,e),Object.defineProperty(t.prototype,"friendlyName",{get:function(){return this.displayName||this.uri.aor},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"displayName",{get:function(){return this._displayName},set:function(e){this._displayName=e},enumerable:!0,configurable:!0}),t.prototype.clone=function(){return new t(this.uri.clone(),this._displayName,JSON.parse(JSON.stringify(this.parameters)))},t.prototype.toString=function(){var e=this.displayName||"0"===this.displayName?'"'+this.displayName+'" ':"";for(var t in e+="<"+this.uri.toString()+">",this.parameters)this.parameters.hasOwnProperty(t)&&(e+=";"+t,null!==this.parameters[t]&&(e+="="+this.parameters[t]));return e},t}(r(21).Parameters);t.NameAddrHeader=n},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e){for(var t in this.parameters={},e)e.hasOwnProperty(t)&&this.setParam(t,e[t])}return e.prototype.setParam=function(e,t){e&&(this.parameters[e.toLowerCase()]=null==t?null:t.toString())},e.prototype.getParam=function(e){if(e)return this.parameters[e.toLowerCase()]},e.prototype.hasParam=function(e){return!!e&&!!this.parameters.hasOwnProperty(e.toLowerCase())},e.prototype.deleteParam=function(e){if(e=e.toLowerCase(),this.parameters.hasOwnProperty(e)){var t=this.parameters[e];return delete this.parameters[e],t}},e.prototype.clearParams=function(){this.parameters={}},e}();t.Parameters=i},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=function(e){function t(r,i,n,s,o){var a=e.call(this,i,n,t.makeId(r),s,o)||this;a._request=r,a.user=n;var c=i.server&&i.server.scheme?i.server.scheme:void 0;return r.setViaHeader(a.id,c),a}return i.__extends(t,e),t.makeId=function(e){if("CANCEL"===e.method){if(!e.branch)throw new Error("Outgoing CANCEL request without a branch.");return e.branch}return"z9hG4bK"+Math.floor(1e7*Math.random())},Object.defineProperty(t.prototype,"request",{get:function(){return this._request},enumerable:!0,configurable:!0}),t.prototype.onRequestTimeout=function(){this.user.onRequestTimeout&&this.user.onRequestTimeout()},t}(r(23).Transaction);t.ClientTransaction=n},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(7),s=r(16),o=function(e){function t(t,r,i,n,s){var o=e.call(this)||this;return o._transport=t,o._user=r,o._id=i,o._state=n,o.logger=r.loggerFactory.getLogger(s,i),o.logger.debug("Constructing "+o.typeToString()+" with id "+o.id+"."),o}return i.__extends(t,e),t.prototype.dispose=function(){this.logger.debug("Destroyed "+this.typeToString()+" with id "+this.id+".")},Object.defineProperty(t.prototype,"id",{get:function(){return this._id},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"kind",{get:function(){throw new Error("Invalid kind.")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"state",{get:function(){return this._state},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"transport",{get:function(){return this._transport},enumerable:!0,configurable:!0}),t.prototype.on=function(t,r){return e.prototype.on.call(this,t,r)},t.prototype.logTransportError=function(e,t){this.logger.error(e.message),this.logger.error("Transport error occurred in "+this.typeToString()+" with id "+this.id+"."),this.logger.error(t)},t.prototype.send=function(e){var t=this;return this.transport.send(e).catch((function(e){var r;if(!(e instanceof s.TransportError))throw r=e&&"string"==typeof e.message?new s.TransportError(e.message):new s.TransportError,t.onTransportError(r),r;t.onTransportError(e)}))},t.prototype.setState=function(e){this.logger.debug('State change to "'+e+'" on '+this.typeToString()+" with id "+this.id+"."),this._state=e,this._user.onStateChange&&this._user.onStateChange(e),this.emit("stateChanged")},t.prototype.typeToString=function(){return"UnknownType"},t}(n.EventEmitter);t.Transaction=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=function(e){function t(t){var r=this.constructor,i=e.call(this,t)||this;return Object.setPrototypeOf(i,r.prototype),i}return i.__extends(t,e),t}(Error);t.Exception=n},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=function(e){function t(t,r,i,n,s){var o=e.call(this,r,i,t.viaBranch,n,s)||this;return o._request=t,o.user=i,o}return i.__extends(t,e),Object.defineProperty(t.prototype,"request",{get:function(){return this._request},enumerable:!0,configurable:!0}),t}(r(23).Transaction);t.ServerTransaction=n},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){var s=void 0!==t.userAgentCore?t.userAgentCore:t;return e.call(this,n.NonInviteServerTransaction,s,r,i)||this}return i.__extends(t,e),t}(r(4).UserAgentServer);t.NotifyUserAgentServer=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),r(0).__exportStar(r(70),t)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e){e[e.error=0]="error",e[e.warn=1]="warn",e[e.log=2]="log",e[e.debug=3]="debug"}(t.Levels||(t.Levels={}))},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0).__importStar(r(58));!function(e){e.parse=function(e,t){var r={startRule:t};try{i.parse(e,r)}catch(e){r.data=-1}return r.data},e.nameAddrHeaderParse=function(t){var r=e.parse(t,"Name_Addr_Header");return-1!==r?r:void 0},e.URIParse=function(t){var r=e.parse(t,"SIP_URI");return-1!==r?r:void 0}}(t.Grammar||(t.Grammar={}))},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=function(e){function t(t,r,i,n,s,o){var a=e.call(this,s)||this;if(a.headers={},!i)throw new TypeError('missing or invalid "host" parameter');for(var c in t=t||"sip",o)o.hasOwnProperty(c)&&a.setHeader(c,o[c]);return a.raw={scheme:t,user:r,host:i,port:n},a.normal={scheme:t.toLowerCase(),user:r,host:i.toLowerCase(),port:n},a}return i.__extends(t,e),Object.defineProperty(t.prototype,"scheme",{get:function(){return this.normal.scheme},set:function(e){this.raw.scheme=e,this.normal.scheme=e.toLowerCase()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"user",{get:function(){return this.normal.user},set:function(e){this.normal.user=this.raw.user=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"host",{get:function(){return this.normal.host},set:function(e){this.raw.host=e,this.normal.host=e.toLowerCase()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"aor",{get:function(){return this.normal.user+"@"+this.normal.host},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"port",{get:function(){return this.normal.port},set:function(e){this.normal.port=this.raw.port=e},enumerable:!0,configurable:!0}),t.prototype.setHeader=function(e,t){this.headers[this.headerize(e)]=t instanceof Array?t:[t]},t.prototype.getHeader=function(e){if(e)return this.headers[this.headerize(e)]},t.prototype.hasHeader=function(e){return!!e&&!!this.headers.hasOwnProperty(this.headerize(e))},t.prototype.deleteHeader=function(e){if(e=this.headerize(e),this.headers.hasOwnProperty(e)){var t=this.headers[e];return delete this.headers[e],t}},t.prototype.clearHeaders=function(){this.headers={}},t.prototype.clone=function(){return new t(this._raw.scheme,this._raw.user||"",this._raw.host,this._raw.port,JSON.parse(JSON.stringify(this.parameters)),JSON.parse(JSON.stringify(this.headers)))},t.prototype.toRaw=function(){return this._toString(this._raw)},t.prototype.toString=function(){return this._toString(this._normal)},Object.defineProperty(t.prototype,"_normal",{get:function(){return this.normal},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"_raw",{get:function(){return this.raw},enumerable:!0,configurable:!0}),t.prototype._toString=function(e){var t=e.scheme+":";for(var r in e.scheme.toLowerCase().match("^sips?$")||(t+="//"),e.user&&(t+=this.escapeUser(e.user)+"@"),t+=e.host,(e.port||0===e.port)&&(t+=":"+e.port),this.parameters)this.parameters.hasOwnProperty(r)&&(t+=";"+r,null!==this.parameters[r]&&(t+="="+this.parameters[r]));var i=[];for(var n in this.headers)if(this.headers.hasOwnProperty(n))for(var s in this.headers[n])this.headers[n].hasOwnProperty(s)&&i.push(n+"="+this.headers[n][s]);return i.length>0&&(t+="?"+i.join("&")),t},t.prototype.escapeUser=function(e){var t;try{t=decodeURIComponent(e)}catch(e){throw e}return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%2B/gi,"+").replace(/%3F/gi,"?").replace(/%2F/gi,"/")},t.prototype.headerize=function(e){for(var t={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},r=e.toLowerCase().replace(/_/g,"-").split("-"),i=r.length,n="",s=0;s699)throw new Error("Invalid status code "+r);switch(this.state){case o.TransactionState.Calling:if(r>=100&&r<=199)return this.stateTransition(o.TransactionState.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(r>=200&&r<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(o.TransactionState.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(r>=300&&r<=699)return this.stateTransition(o.TransactionState.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case o.TransactionState.Proceeding:if(r>=100&&r<=199)return void(this.user.receiveResponse&&this.user.receiveResponse(e));if(r>=200&&r<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(o.TransactionState.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(r>=300&&r<=699)return this.stateTransition(o.TransactionState.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case o.TransactionState.Accepted:if(r>=200&&r<=299){if(!this.ackRetransmissionCache.has(e.toTag))return this.ackRetransmissionCache.set(e.toTag,void 0),void(this.user.receiveResponse&&this.user.receiveResponse(e));var i=this.ackRetransmissionCache.get(e.toTag);return i?void this.send(i.toString()).catch((function(e){t.logTransportError(e,"Failed to send retransmission of ACK to 2xx response.")})):void 0}break;case o.TransactionState.Completed:if(r>=300&&r<=699)return void this.ack(e);break;case o.TransactionState.Terminated:break;default:throw new Error("Invalid state "+this.state)}var n="Received unexpected "+r+" response while in state "+this.state+".";this.logger.warn(n)},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(o.TransactionState.Terminated,!0)},t.prototype.typeToString=function(){return"INVITE client transaction"},t.prototype.ack=function(e){var t=this,r=this.request.ruri,i=this.request.callId,n=this.request.cseq,s=this.request.getHeader("from"),o=e.getHeader("to"),a=this.request.getHeader("via"),c=this.request.getHeader("route");if(!s)throw new Error("From undefined.");if(!o)throw new Error("To undefined.");if(!a)throw new Error("Via undefined.");var u="ACK "+r+" SIP/2.0\r\n";c&&(u+="Route: "+c+"\r\n"),u+="Via: "+a+"\r\n",u+="To: "+o+"\r\n",u+="From: "+s+"\r\n",u+="Call-ID: "+i+"\r\n",u+="CSeq: "+n+" ACK\r\n",u+="Max-Forwards: 70\r\n",u+="Content-Length: 0\r\n\r\n",this.send(u).catch((function(e){t.logTransportError(e,"Failed to send ACK to non-2xx response.")}))},t.prototype.stateTransition=function(e,t){var r=this;void 0===t&&(t=!1);var i=function(){throw new Error("Invalid state transition from "+r.state+" to "+e)};switch(e){case o.TransactionState.Calling:i();break;case o.TransactionState.Proceeding:this.state!==o.TransactionState.Calling&&i();break;case o.TransactionState.Accepted:case o.TransactionState.Completed:this.state!==o.TransactionState.Calling&&this.state!==o.TransactionState.Proceeding&&i();break;case o.TransactionState.Terminated:this.state!==o.TransactionState.Calling&&this.state!==o.TransactionState.Accepted&&this.state!==o.TransactionState.Completed&&(t||i());break;default:i()}this.B&&(clearTimeout(this.B),this.B=void 0),o.TransactionState.Proceeding,e===o.TransactionState.Completed&&(this.D=setTimeout((function(){return r.timer_D()}),n.Timers.TIMER_D)),e===o.TransactionState.Accepted&&(this.M=setTimeout((function(){return r.timer_M()}),n.Timers.TIMER_M)),e===o.TransactionState.Terminated&&this.dispose(),this.setState(e)},t.prototype.timer_A=function(){},t.prototype.timer_B=function(){this.logger.debug("Timer B expired for INVITE client transaction "+this.id+"."),this.state===o.TransactionState.Calling&&(this.onRequestTimeout(),this.stateTransition(o.TransactionState.Terminated))},t.prototype.timer_D=function(){this.logger.debug("Timer D expired for INVITE client transaction "+this.id+"."),this.state===o.TransactionState.Completed&&this.stateTransition(o.TransactionState.Terminated)},t.prototype.timer_M=function(){this.logger.debug("Timer M expired for INVITE client transaction "+this.id+"."),this.state===o.TransactionState.Accepted&&this.stateTransition(o.TransactionState.Terminated)},t}(s.ClientTransaction);t.InviteClientTransaction=a},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(2),s=r(1),o=function(e){function t(t,r,i){var o,a=t.createOutgoingRequestMessage(n.C.BYE,i);return o=e.call(this,s.NonInviteClientTransaction,t.userAgentCore,a,r)||this,t.dispose(),o}return i.__extends(t,e),t}(r(3).UserAgentClient);t.ByeUserAgentClient=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){return e.call(this,n.NonInviteServerTransaction,t.userAgentCore,r,i)||this}return i.__extends(t,e),t}(r(4).UserAgentServer);t.ByeUserAgentServer=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(2),s=r(1),o=function(e){function t(t,r,i){var o=t.createOutgoingRequestMessage(n.C.INFO,i);return e.call(this,s.NonInviteClientTransaction,t.userAgentCore,o,r)||this}return i.__extends(t,e),t}(r(3).UserAgentClient);t.InfoUserAgentClient=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){return e.call(this,n.NonInviteServerTransaction,t.userAgentCore,r,i)||this}return i.__extends(t,e),t}(r(4).UserAgentServer);t.InfoUserAgentServer=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(2),s=r(1),o=function(e){function t(t,r,i){var o=t.createOutgoingRequestMessage(n.C.NOTIFY,i);return e.call(this,s.NonInviteClientTransaction,t.userAgentCore,o,r)||this}return i.__extends(t,e),t}(r(3).UserAgentClient);t.NotifyUserAgentClient=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(2),s=r(1),o=function(e){function t(t,r,i){var o,a=t.createOutgoingRequestMessage(n.C.PRACK,i);return o=e.call(this,s.NonInviteClientTransaction,t.userAgentCore,a,r)||this,t.signalingStateTransition(a),o}return i.__extends(t,e),t}(r(3).UserAgentClient);t.PrackUserAgentClient=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){var s=e.call(this,n.NonInviteServerTransaction,t.userAgentCore,r,i)||this;return t.signalingStateTransition(r),s.dialog=t,s}return i.__extends(t,e),t.prototype.accept=function(t){return void 0===t&&(t={statusCode:200}),t.body&&this.dialog.signalingStateTransition(t.body),e.prototype.accept.call(this,t)},t}(r(4).UserAgentServer);t.PrackUserAgentServer=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(2),s=r(1),o=function(e){function t(t,r,i){var o=this,a=t.createOutgoingRequestMessage(n.C.INVITE,i);return(o=e.call(this,s.InviteClientTransaction,t.userAgentCore,a,r)||this).delegate=r,t.signalingStateTransition(a),t.reinviteUserAgentClient=o,o.dialog=t,o}return i.__extends(t,e),t.prototype.receiveResponse=function(e){var t=this,r=e.statusCode?e.statusCode.toString():"";if(!r)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(r):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e});break;case/^1[0-9]{2}$/.test(r):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:this.dialog,prack:function(e){throw new Error("Unimplemented.")}});break;case/^2[0-9]{2}$/.test(r):this.dialog.signalingStateTransition(e),this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e,session:this.dialog,ack:function(e){return t.dialog.ack(e)}});break;case/^3[0-9]{2}$/.test(r):this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentClient=void 0,this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e});break;case/^[4-6][0-9]{2}$/.test(r):this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentClient=void 0,this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e});break;default:throw new Error("Invalid status code "+r)}},t}(r(3).UserAgentClient);t.ReInviteUserAgentClient=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){var s=e.call(this,n.InviteServerTransaction,t.userAgentCore,r,i)||this;return t.reinviteUserAgentServer=s,s.dialog=t,s}return i.__extends(t,e),t.prototype.accept=function(t){void 0===t&&(t={statusCode:200}),t.extraHeaders=t.extraHeaders||[],t.extraHeaders=t.extraHeaders.concat(this.dialog.routeSet.map((function(e){return"Record-Route: "+e})));var r=e.prototype.accept.call(this,t),n=this.dialog,s=i.__assign({},r,{session:n});return t.body&&this.dialog.signalingStateTransition(t.body),this.dialog.reConfirm(),s},t.prototype.progress=function(t){void 0===t&&(t={statusCode:180});var r=e.prototype.progress.call(this,t),n=this.dialog,s=i.__assign({},r,{session:n});return t.body&&this.dialog.signalingStateTransition(t.body),s},t.prototype.redirect=function(e,t){throw void 0===t&&(t={statusCode:302}),this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,new Error("Unimplemented.")},t.prototype.reject=function(t){return void 0===t&&(t={statusCode:488}),this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,e.prototype.reject.call(this,t)},t}(r(4).UserAgentServer);t.ReInviteUserAgentServer=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(2),s=r(1),o=function(e){function t(t,r,i){var o=t.createOutgoingRequestMessage(n.C.REFER,i);return e.call(this,s.NonInviteClientTransaction,t.userAgentCore,o,r)||this}return i.__extends(t,e),t}(r(3).UserAgentClient);t.ReferUserAgentClient=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){var s=void 0!==t.userAgentCore?t.userAgentCore:t;return e.call(this,n.NonInviteServerTransaction,s,r,i)||this}return i.__extends(t,e),t}(r(4).UserAgentServer);t.ReferUserAgentServer=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(2),s=r(27),o=r(6),a=r(14),c=r(26),u=r(48),d=function(e){function t(t,r,i,n,s,o){var a=e.call(this,n,s)||this;return a.delegate=o,a._autoRefresh=!1,a._subscriptionEvent=t,a._subscriptionExpires=r,a._subscriptionExpiresInitial=r,a._subscriptionExpiresLastSet=Math.floor(Date.now()/1e3),a._subscriptionRefresh=void 0,a._subscriptionRefreshLastSet=void 0,a._subscriptionState=i,a.logger=n.loggerFactory.getLogger("sip.subscribe-dialog"),a.logger.log("SUBSCRIBE dialog "+a.id+" constructed"),a}return i.__extends(t,e),t.initialDialogStateForSubscription=function(e,t){var r=t.getHeaders("record-route"),i=t.parseHeader("contact");if(!i)throw new Error("Contact undefined.");if(!(i instanceof n.NameAddrHeader))throw new Error("Contact not instance of NameAddrHeader.");var s=i.uri,o=e.cseq,a=e.callId,c=e.fromTag,u=t.fromTag;if(!a)throw new Error("Call id undefined.");if(!c)throw new Error("From tag undefined.");if(!u)throw new Error("To tag undefined.");if(!e.from)throw new Error("From undefined.");if(!e.to)throw new Error("To undefined.");return{id:a+c+u,early:!1,callId:a,localTag:c,remoteTag:u,localSequenceNumber:o,remoteSequenceNumber:void 0,localURI:e.from.uri,remoteURI:e.to.uri,remoteTarget:s,routeSet:r,secure:!1}},t.prototype.dispose=function(){e.prototype.dispose.call(this),this.N&&(clearTimeout(this.N),this.N=void 0),this.refreshTimerClear(),this.logger.log("SUBSCRIBE dialog "+this.id+" destroyed")},Object.defineProperty(t.prototype,"autoRefresh",{get:function(){return this._autoRefresh},set:function(e){this._autoRefresh=!0,this.refreshTimerSet()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionEvent",{get:function(){return this._subscriptionEvent},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionExpires",{get:function(){var e=Math.floor(Date.now()/1e3)-this._subscriptionExpiresLastSet,t=this._subscriptionExpires-e;return Math.max(t,0)},set:function(e){if(e<0)throw new Error("Expires must be greater than or equal to zero.");if(this._subscriptionExpires=e,this._subscriptionExpiresLastSet=Math.floor(Date.now()/1e3),this.autoRefresh){var t=this.subscriptionRefresh;(void 0===t||t>=e)&&this.refreshTimerSet()}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionExpiresInitial",{get:function(){return this._subscriptionExpiresInitial},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionRefresh",{get:function(){if(void 0!==this._subscriptionRefresh&&void 0!==this._subscriptionRefreshLastSet){var e=Math.floor(Date.now()/1e3)-this._subscriptionRefreshLastSet,t=this._subscriptionRefresh-e;return Math.max(t,0)}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionState",{get:function(){return this._subscriptionState},enumerable:!0,configurable:!0}),t.prototype.receiveRequest=function(t){if(this.logger.log("SUBSCRIBE dialog "+this.id+" received "+t.method+" request"),this.sequenceGuard(t))switch(e.prototype.receiveRequest.call(this,t),t.method){case n.C.NOTIFY:this.onNotify(t);break;default:this.logger.log("SUBSCRIBE dialog "+this.id+" received unimplemented "+t.method+" request"),this.core.replyStateless(t,{statusCode:501})}else this.logger.log("SUBSCRIBE dialog "+this.id+" rejected out of order "+t.method+" request.")},t.prototype.refresh=function(){var e="Allow: "+a.AllowedMethods.toString(),t={};return t.extraHeaders=(t.extraHeaders||[]).slice(),t.extraHeaders.push(e),t.extraHeaders.push("Event: "+this.subscriptionEvent),t.extraHeaders.push("Expires: "+this.subscriptionExpiresInitial),t.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,t)},t.prototype.subscribe=function(e,t){var r=this;if(void 0===t&&(t={}),this.subscriptionState!==s.SubscriptionState.Pending&&this.subscriptionState!==s.SubscriptionState.Active)throw new Error("Invalid state "+this.subscriptionState+'. May only re-subscribe while in state "pending" or "active".');this.logger.log("SUBSCRIBE dialog "+this.id+" sending SUBSCRIBE request");var i=new u.ReSubscribeUserAgentClient(this,e,t);return this.N=setTimeout((function(){return r.timer_N()}),o.Timers.TIMER_N),i},t.prototype.terminate=function(){this.stateTransition(s.SubscriptionState.Terminated),this.onTerminated()},t.prototype.unsubscribe=function(){var e="Allow: "+a.AllowedMethods.toString(),t={};return t.extraHeaders=(t.extraHeaders||[]).slice(),t.extraHeaders.push(e),t.extraHeaders.push("Event: "+this.subscriptionEvent),t.extraHeaders.push("Expires: 0"),t.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,t)},t.prototype.onNotify=function(e){var t=e.parseHeader("Event").event;if(t&&t===this.subscriptionEvent){this.N&&(clearTimeout(this.N),this.N=void 0);var r=e.parseHeader("Subscription-State");if(r&&r.state){var i=r.state,n=r.expires?Math.max(r.expires,0):void 0;switch(i){case"pending":this.stateTransition(s.SubscriptionState.Pending,n);break;case"active":this.stateTransition(s.SubscriptionState.Active,n);break;case"terminated":this.stateTransition(s.SubscriptionState.Terminated,n);break;default:this.logger.warn("Unrecognized subscription state.")}var o=new c.NotifyUserAgentServer(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(o):o.accept()}else this.core.replyStateless(e,{statusCode:489})}else this.core.replyStateless(e,{statusCode:489})},t.prototype.onRefresh=function(e){this.delegate&&this.delegate.onRefresh&&this.delegate.onRefresh(e)},t.prototype.onTerminated=function(){this.delegate&&this.delegate.onTerminated&&this.delegate.onTerminated()},t.prototype.refreshTimerClear=function(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=void 0)},t.prototype.refreshTimerSet=function(){var e=this;if(this.refreshTimerClear(),this.autoRefresh&&this.subscriptionExpires>0){var t=900*this.subscriptionExpires;this._subscriptionRefresh=Math.floor(t/1e3),this._subscriptionRefreshLastSet=Math.floor(Date.now()/1e3),this.refreshTimer=setTimeout((function(){e.refreshTimer=void 0,e._subscriptionRefresh=void 0,e._subscriptionRefreshLastSet=void 0,e.onRefresh(e.refresh())}),t)}},t.prototype.stateTransition=function(e,t){var r=this,i=function(){r.logger.warn("Invalid subscription state transition from "+r.subscriptionState+" to "+e)};switch(e){case s.SubscriptionState.Initial:case s.SubscriptionState.NotifyWait:return void i();case s.SubscriptionState.Pending:if(this.subscriptionState!==s.SubscriptionState.NotifyWait&&this.subscriptionState!==s.SubscriptionState.Pending)return void i();break;case s.SubscriptionState.Active:case s.SubscriptionState.Terminated:if(this.subscriptionState!==s.SubscriptionState.NotifyWait&&this.subscriptionState!==s.SubscriptionState.Pending&&this.subscriptionState!==s.SubscriptionState.Active)return void i();break;default:return void i()}e===s.SubscriptionState.Pending&&t&&(this.subscriptionExpires=t),e===s.SubscriptionState.Active&&t&&(this.subscriptionExpires=t),e===s.SubscriptionState.Terminated&&this.dispose(),this._subscriptionState=e},t.prototype.timer_N=function(){this.subscriptionState!==s.SubscriptionState.Terminated&&(this.stateTransition(s.SubscriptionState.Terminated),this.onTerminated())},t}(r(18).Dialog);t.SubscriptionDialog=d},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(2),s=r(1),o=function(e){function t(t,r,i){var o=this,a=t.createOutgoingRequestMessage(n.C.SUBSCRIBE,i);return(o=e.call(this,s.NonInviteClientTransaction,t.userAgentCore,a,r)||this).dialog=t,o}return i.__extends(t,e),t.prototype.waitNotifyStop=function(){},t.prototype.receiveResponse=function(t){if(t.statusCode&&t.statusCode>=200&&t.statusCode<300){var r=t.getHeader("Expires");if(r){var i=Number(r);this.dialog.subscriptionExpires>i&&(this.dialog.subscriptionExpires=i)}else this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE")}if(t.statusCode&&t.statusCode>=400&&t.statusCode<700){[404,405,410,416,480,481,482,483,484,485,489,501,604].includes(t.statusCode)&&this.dialog.terminate()}e.prototype.receiveResponse.call(this,t)},t}(r(3).UserAgentClient);t.ReSubscribeUserAgentClient=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(28),n=function(){function e(e,t,r){this.logger=e,this.category=t,this.label=r}return e.prototype.error=function(e){this.genericLog(i.Levels.error,e)},e.prototype.warn=function(e){this.genericLog(i.Levels.warn,e)},e.prototype.log=function(e){this.genericLog(i.Levels.log,e)},e.prototype.debug=function(e){this.genericLog(i.Levels.debug,e)},e.prototype.genericLog=function(e,t){this.logger.genericLog(e,this.category,this.label,t)},e}();t.Logger=n},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0);i.__exportStar(r(36),t),i.__exportStar(r(37),t),i.__exportStar(r(75),t),i.__exportStar(r(38),t),i.__exportStar(r(39),t),i.__exportStar(r(76),t),i.__exportStar(r(77),t),i.__exportStar(r(78),t),i.__exportStar(r(79),t),i.__exportStar(r(40),t),i.__exportStar(r(26),t),i.__exportStar(r(80),t),i.__exportStar(r(41),t),i.__exportStar(r(42),t),i.__exportStar(r(43),t),i.__exportStar(r(44),t),i.__exportStar(r(48),t),i.__exportStar(r(81),t),i.__exportStar(r(45),t),i.__exportStar(r(46),t),i.__exportStar(r(82),t),i.__exportStar(r(83),t),i.__exportStar(r(84),t),i.__exportStar(r(85),t),i.__exportStar(r(3),t),i.__exportStar(r(4),t)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(7),s=r(11),o=r(5),a=r(8),c=r(9),u=function(e){function t(r,i,n,s){var o=e.call(this)||this;return o.data={},t.initializer(o,r,i,n,s),o}return i.__extends(t,e),t.initializer=function(e,t,r,i,n){if(e.type=a.TypeStrings.ClientContext,void 0===i)throw new TypeError("Not enough arguments");e.ua=t,e.logger=t.getLogger("sip.clientcontext"),e.method=r;var s=t.normalizeTarget(i);if(!s)throw new TypeError("Invalid target: "+i);var u=t.userAgentCore.configuration.aor;if(n&&n.params&&n.params.fromUri&&!(u="string"==typeof n.params.fromUri?o.Grammar.URIParse(n.params.fromUri):n.params.fromUri))throw new TypeError("Invalid from URI: "+n.params.fromUri);var d=s;if(n&&n.params&&n.params.toUri&&!(d="string"==typeof n.params.toUri?o.Grammar.URIParse(n.params.toUri):n.params.toUri))throw new TypeError("Invalid to URI: "+n.params.toUri);var p,h,l=((n=(n=Object.create(n||Object.prototype))||{}).extraHeaders||[]).slice(),g=n.params||{};n.body&&(p={body:n.body,contentType:n.contentType?n.contentType:"application/sdp"},e.body=p),p&&(h=c.Utils.fromBodyObj(p)),e.request=t.userAgentCore.makeOutgoingRequestMessage(r,s,u,d,g,l,h),e.request.from&&(e.localIdentity=e.request.from),e.request.to&&(e.remoteIdentity=e.request.to)},t.prototype.send=function(){var e=this;return this.ua.userAgentCore.request(this.request,{onAccept:function(t){return e.receiveResponse(t.message)},onProgress:function(t){return e.receiveResponse(t.message)},onRedirect:function(t){return e.receiveResponse(t.message)},onReject:function(t){return e.receiveResponse(t.message)},onTrying:function(t){return e.receiveResponse(t.message)}}),this},t.prototype.receiveResponse=function(e){var t=e.statusCode||0,r=c.Utils.getReasonPhrase(t);switch(!0){case/^1[0-9]{2}$/.test(t.toString()):this.emit("progress",e,r);break;case/^2[0-9]{2}$/.test(t.toString()):this.ua.applicants[this.toString()]&&delete this.ua.applicants[this.toString()],this.emit("accepted",e,r);break;default:this.ua.applicants[this.toString()]&&delete this.ua.applicants[this.toString()],this.emit("rejected",e,r),this.emit("failed",e,r)}},t.prototype.onRequestTimeout=function(){this.emit("failed",void 0,s.C.causes.REQUEST_TIMEOUT)},t.prototype.onTransportError=function(){this.emit("failed",void 0,s.C.causes.CONNECTION_ERROR)},t}(n.EventEmitter);t.ClientContext=u},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(7),s=r(11),o=r(5),a=r(14),c=r(8),u=r(12),d=r(9),p=r(53),h=r(92),l=r(54),g=r(93),f=r(31),m=function(e){function t(t,r){void 0===r&&(r={});var i=e.call(this)||this;return i.type=c.TypeStrings.Session,i.method=s.C.INVITE,i.localHold=!1,i.status=c.SessionStatus.STATUS_NULL,i.isFailed=!1,i.rel100=s.C.supported.UNSUPPORTED,i.expiresTimer=void 0,i.userNoAnswerTimer=void 0,i._state=f.SessionState.Initial,i._stateEventEmitter=new n.EventEmitter,i.pendingReinvite=!1,i.tones=void 0,i.userAgent=t,i.delegate=r.delegate,i.logger=t.getLogger("sip.session"),i.errorListener=i.onTransportError.bind(i),t.transport&&t.transport.on("transportError",i.errorListener),i}return i.__extends(t,e),t.prototype.on=function(t,r){return e.prototype.on.call(this,t,r)},t.prototype.emit=function(t){for(var r=[],i=1;i0){for(t=1,r=1;t",T(">",!1),"\\",T("\\",!1),"[",T("[",!1),"]",T("]",!1),"{",T("{",!1),"}",T("}",!1),function(){return"*"},function(){return"/"},function(){return"="},function(){return"("},function(){return")"},function(){return">"},function(){return"<"},function(){return","},function(){return";"},function(){return":"},function(){return'"'},/^[!-']/,y([["!","'"]],!1,!1),/^[*-[]/,y([["*","["]],!1,!1),/^[\]-~]/,y([["]","~"]],!1,!1),function(e){return e},/^[#-[]/,y([["#","["]],!1,!1),/^[\0-\t]/,y([["\0","\t"]],!1,!1),/^[\x0B-\f]/,y([["\v","\f"]],!1,!1),/^[\x0E-\x7F]/,y([["\x0e","\x7f"]],!1,!1),function(){(t=t||{data:{}}).data.uri=new s.URI(t.data.scheme,t.data.user,t.data.host,t.data.port),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port},function(){(t=t||{data:{}}).data.uri=new s.URI(t.data.scheme,t.data.user,t.data.host,t.data.port,t.data.uri_params,t.data.uri_headers),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port,delete t.data.uri_params,"SIP_URI"===t.startRule&&(t.data=t.data.uri)},"sips",T("sips",!0),"sip",T("sip",!0),function(e){(t=t||{data:{}}).data.scheme=e},function(){(t=t||{data:{}}).data.user=decodeURIComponent(v().slice(0,-1))},function(){(t=t||{data:{}}).data.password=v()},function(){return(t=t||{data:{}}).data.host=v(),t.data.host},function(){return(t=t||{data:{}}).data.host_type="domain",v()},/^[a-zA-Z0-9_\-]/,y([["a","z"],["A","Z"],["0","9"],"_","-"],!1,!1),/^[a-zA-Z0-9\-]/,y([["a","z"],["A","Z"],["0","9"],"-"],!1,!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",v()},"::",T("::",!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",v()},function(){return(t=t||{data:{}}).data.host_type="IPv4",v()},"25",T("25",!1),/^[0-5]/,y([["0","5"]],!1,!1),"2",T("2",!1),/^[0-4]/,y([["0","4"]],!1,!1),"1",T("1",!1),/^[1-9]/,y([["1","9"]],!1,!1),function(e){return t=t||{data:{}},e=parseInt(e.join("")),t.data.port=e,e},"transport=",T("transport=",!0),"udp",T("udp",!0),"tcp",T("tcp",!0),"sctp",T("sctp",!0),"tls",T("tls",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.transport=e.toLowerCase()},"user=",T("user=",!0),"phone",T("phone",!0),"ip",T("ip",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.user=e.toLowerCase()},"method=",T("method=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.method=e},"ttl=",T("ttl=",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.ttl=e},"maddr=",T("maddr=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.maddr=e},"lr",T("lr",!0),function(){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.lr=void 0},function(e,r){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),r=null===r?void 0:r[1],t.data.uri_params[e.toLowerCase()]=r},function(e,r){e=e.join("").toLowerCase(),r=r.join(""),(t=t||{data:{}}).data.uri_headers||(t.data.uri_headers={}),t.data.uri_headers[e]?t.data.uri_headers[e].push(r):t.data.uri_headers[e]=[r]},function(){"Refer_To"===(t=t||{data:{}}).startRule&&(t.data.uri=new s.URI(t.data.scheme,t.data.user,t.data.host,t.data.port,t.data.uri_params,t.data.uri_headers),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port,delete t.data.uri_params)},"//",T("//",!1),function(){(t=t||{data:{}}).data.scheme=v()},T("SIP",!0),function(){(t=t||{data:{}}).data.sip_version=v()},"INVITE",T("INVITE",!1),"ACK",T("ACK",!1),"VXACH",T("VXACH",!1),"OPTIONS",T("OPTIONS",!1),"BYE",T("BYE",!1),"CANCEL",T("CANCEL",!1),"REGISTER",T("REGISTER",!1),"SUBSCRIBE",T("SUBSCRIBE",!1),"NOTIFY",T("NOTIFY",!1),"REFER",T("REFER",!1),"PUBLISH",T("PUBLISH",!1),function(){return(t=t||{data:{}}).data.method=v(),t.data.method},function(e){(t=t||{data:{}}).data.status_code=parseInt(e.join(""))},function(){(t=t||{data:{}}).data.reason_phrase=v()},function(){(t=t||{data:{}}).data=v()},function(){var e,r;for(r=(t=t||{data:{}}).data.multi_header.length,e=0;e""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),_(";).# &;,"),_('2F""6F7G.} &2H""6H7I.q &2J""6J7K.e &2L""6L7M.Y &2N""6N7O.M &2P""6P7Q.A &2R""6R7S.5 &2T""6T7U.) &2V""6V7W'),_('%%2X""6X7Y/5#;#/,$;#/#$+#)(#\'#("\'#&\'#/"!&,)'),_('%%$;$0#*;$&/,#; /#$+")("\'#&\'#." &"/=#$;$/�#*;$&&&#/\'$8":Z" )("\'#&\'#'),_(';.." &"'),_("%$;'.# &;(0)*;'.# &;(&/?#28\"\"6879/0$;//'$8#:[# )(#'#(\"'#&'#"),_('%%$;2/�#*;2&&&#/g#$%$;.0#*;.&/,#;2/#$+")("\'#&\'#0=*%$;.0#*;.&/,#;2/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),_('4\\""5!7].# &;3'),_('4^""5!7_'),_('4`""5!7a'),_(';!.) &4b""5!7c'),_('%$;).\x95 &2F""6F7G.\x89 &2J""6J7K.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O/\x9e#0\x9b*;).\x95 &2F""6F7G.\x89 &2J""6J7K.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O&&&#/"!&,)'),_('%$;).\x89 &2F""6F7G.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O/\x92#0\x8f*;).\x89 &2F""6F7G.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O&&&#/"!&,)'),_('2T""6T7U.\xe3 &2V""6V7W.\xd7 &2f""6f7g.\xcb &2h""6h7i.\xbf &2:""6:7;.\xb3 &2D""6D7E.\xa7 &22""6273.\x9b &28""6879.\x8f &2j""6j7k.\x83 &;&.} &24""6475.q &2l""6l7m.e &2n""6n7o.Y &26""6677.M &2>""6>7?.A &2p""6p7q.5 &2r""6r7s.) &;\'.# &;('),_('%$;).\u012b &2F""6F7G.\u011f &2J""6J7K.\u0113 &2L""6L7M.\u0107 &2X""6X7Y.\xfb &2P""6P7Q.\xef &2H""6H7I.\xe3 &2@""6@7A.\xd7 &2d""6d7e.\xcb &2R""6R7S.\xbf &2N""6N7O.\xb3 &2T""6T7U.\xa7 &2V""6V7W.\x9b &2f""6f7g.\x8f &2h""6h7i.\x83 &28""6879.w &2j""6j7k.k &;&.e &24""6475.Y &2l""6l7m.M &2n""6n7o.A &26""6677.5 &2p""6p7q.) &2r""6r7s/\u0134#0\u0131*;).\u012b &2F""6F7G.\u011f &2J""6J7K.\u0113 &2L""6L7M.\u0107 &2X""6X7Y.\xfb &2P""6P7Q.\xef &2H""6H7I.\xe3 &2@""6@7A.\xd7 &2d""6d7e.\xcb &2R""6R7S.\xbf &2N""6N7O.\xb3 &2T""6T7U.\xa7 &2V""6V7W.\x9b &2f""6f7g.\x8f &2h""6h7i.\x83 &28""6879.w &2j""6j7k.k &;&.e &24""6475.Y &2l""6l7m.M &2n""6n7o.A &26""6677.5 &2p""6p7q.) &2r""6r7s&&&#/"!&,)'),_("%;//?#2P\"\"6P7Q/0$;//'$8#:t# )(#'#(\"'#&'#"),_("%;//?#24\"\"6475/0$;//'$8#:u# )(#'#(\"'#&'#"),_("%;//?#2>\"\"6>7?/0$;//'$8#:v# )(#'#(\"'#&'#"),_("%;//?#2T\"\"6T7U/0$;//'$8#:w# )(#'#(\"'#&'#"),_("%;//?#2V\"\"6V7W/0$;//'$8#:x# )(#'#(\"'#&'#"),_('%2h""6h7i/0#;//\'$8":y" )("\'#&\'#'),_('%;//6#2f""6f7g/\'$8":z" )("\'#&\'#'),_("%;//?#2D\"\"6D7E/0$;//'$8#:{# )(#'#(\"'#&'#"),_("%;//?#22\"\"6273/0$;//'$8#:|# )(#'#(\"'#&'#"),_("%;//?#28\"\"6879/0$;//'$8#:}# )(#'#(\"'#&'#"),_("%;//0#;&/'$8\":~\" )(\"'#&'#"),_("%;&/0#;//'$8\":~\" )(\"'#&'#"),_("%;=/T#$;G.) &;K.# &;F0/*;G.) &;K.# &;F&/,$;>/#$+#)(#'#(\"'#&'#"),_('4\x7f""5!7\x80.A &4\x81""5!7\x82.5 &4\x83""5!7\x84.) &;3.# &;.'),_("%%;//Q#;&/H$$;J.# &;K0)*;J.# &;K&/,$;&/#$+$)($'#(#'#(\"'#&'#/\"!&,)"),_("%;//]#;&/T$%$;J.# &;K0)*;J.# &;K&/\"!&,)/1$;&/($8$:\x85$!!)($'#(#'#(\"'#&'#"),_(';..G &2L""6L7M.; &4\x86""5!7\x87./ &4\x83""5!7\x84.# &;3'),_('%2j""6j7k/J#4\x88""5!7\x89.5 &4\x8a""5!7\x8b.) &4\x8c""5!7\x8d/#$+")("\'#&\'#'),_("%;N/M#28\"\"6879/>$;O.\" &\"/0$;S/'$8$:\x8e$ )($'#(#'#(\"'#&'#"),_("%;N/d#28\"\"6879/U$;O.\" &\"/G$;S/>$;_/5$;l.\" &\"/'$8&:\x8f& )(&'#(%'#($'#(#'#(\"'#&'#"),_('%3\x90""5$7\x91.) &3\x92""5#7\x93/\' 8!:\x94!! )'),_('%;P/]#%28""6879/,#;R/#$+")("\'#&\'#." &"/6$2:""6:7;/\'$8#:\x95# )(#\'#("\'#&\'#'),_("$;+.) &;-.# &;Q/2#0/*;+.) &;-.# &;Q&&&#"),_('2<""6<7=.q &2>""6>7?.e &2@""6@7A.Y &2B""6B7C.M &2D""6D7E.A &22""6273.5 &26""6677.) &24""6475'),_('%$;+._ &;-.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E0e*;+._ &;-.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E&/& 8!:\x96! )'),_('%;T/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),_("%;U.) &;\\.# &;X/& 8!:\x97! )"),_('%$%;V/2#2J""6J7K/#$+")("\'#&\'#0<*%;V/2#2J""6J7K/#$+")("\'#&\'#&/D#;W/;$2J""6J7K." &"/\'$8#:\x98# )(#\'#("\'#&\'#'),_('$4\x99""5!7\x9a/,#0)*4\x99""5!7\x9a&&&#'),_('%4$""5!7%/?#$4\x9b""5!7\x9c0)*4\x9b""5!7\x9c&/#$+")("\'#&\'#'),_('%2l""6l7m/?#;Y/6$2n""6n7o/\'$8#:\x9d# )(#\'#("\'#&\'#'),_('%%;Z/\xb3#28""6879/\xa4$;Z/\x9b$28""6879/\x8c$;Z/\x83$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+-)(-\'#(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u0790 &%2\x9e""6\x9e7\x9f/\xa4#;Z/\x9b$28""6879/\x8c$;Z/\x83$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+,)(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u06f9 &%2\x9e""6\x9e7\x9f/\x8c#;Z/\x83$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u067a &%2\x9e""6\x9e7\x9f/t#;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u0613 &%2\x9e""6\x9e7\x9f/\\#;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+&)(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u05c4 &%2\x9e""6\x9e7\x9f/D#;Z/;$28""6879/,$;[/#$+$)($\'#(#\'#("\'#&\'#.\u058d &%2\x9e""6\x9e7\x9f/,#;[/#$+")("\'#&\'#.\u056e &%2\x9e""6\x9e7\x9f/,#;Z/#$+")("\'#&\'#.\u054f &%;Z/\x9b#2\x9e""6\x9e7\x9f/\x8c$;Z/\x83$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$++)(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u04c7 &%;Z/\xaa#%28""6879/,#;Z/#$+")("\'#&\'#." &"/\x83$2\x9e""6\x9e7\x9f/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u0430 &%;Z/\xb9#%28""6879/,#;Z/#$+")("\'#&\'#." &"/\x92$%28""6879/,#;Z/#$+")("\'#&\'#." &"/k$2\x9e""6\x9e7\x9f/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+))()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u038a &%;Z/\xc8#%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xa1$%28""6879/,#;Z/#$+")("\'#&\'#." &"/z$%28""6879/,#;Z/#$+")("\'#&\'#." &"/S$2\x9e""6\x9e7\x9f/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u02d5 &%;Z/\xd7#%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xb0$%28""6879/,#;Z/#$+")("\'#&\'#." &"/\x89$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2\x9e""6\x9e7\x9f/,$;[/#$+\')(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u0211 &%;Z/\xfe#%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xd7$%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xb0$%28""6879/,#;Z/#$+")("\'#&\'#." &"/\x89$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2\x9e""6\x9e7\x9f/,$;Z/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u0126 &%;Z/\u011c#%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xf5$%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xce$%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xa7$%28""6879/,#;Z/#$+")("\'#&\'#." &"/\x80$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Y$%28""6879/,#;Z/#$+")("\'#&\'#." &"/2$2\x9e""6\x9e7\x9f/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#/& 8!:\xa0! )'),_('%;#/M#;#." &"/?$;#." &"/1$;#." &"/#$+$)($\'#(#\'#("\'#&\'#'),_("%;Z/;#28\"\"6879/,$;Z/#$+#)(#'#(\"'#&'#.# &;\\"),_("%;]/o#2J\"\"6J7K/`$;]/W$2J\"\"6J7K/H$;]/?$2J\"\"6J7K/0$;]/'$8':\xa1' )(''#(&'#(%'#($'#(#'#(\"'#&'#"),_('%2\xa2""6\xa27\xa3/2#4\xa4""5!7\xa5/#$+")("\'#&\'#.\x98 &%2\xa6""6\xa67\xa7/;#4\xa8""5!7\xa9/,$;!/#$+#)(#\'#("\'#&\'#.j &%2\xaa""6\xaa7\xab/5#;!/,$;!/#$+#)(#\'#("\'#&\'#.B &%4\xac""5!7\xad/,#;!/#$+")("\'#&\'#.# &;!'),_('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:\xae!! )'),_('$%22""6273/,#;`/#$+")("\'#&\'#0<*%22""6273/,#;`/#$+")("\'#&\'#&'),_(";a.A &;b.; &;c.5 &;d./ &;e.) &;f.# &;g"),_('%3\xaf""5*7\xb0/a#3\xb1""5#7\xb2.G &3\xb3""5#7\xb4.; &3\xb5""5$7\xb6./ &3\xb7""5#7\xb8.# &;6/($8":\xb9"! )("\'#&\'#'),_('%3\xba""5%7\xbb/I#3\xbc""5%7\xbd./ &3\xbe""5"7\xbf.# &;6/($8":\xc0"! )("\'#&\'#'),_('%3\xc1""5\'7\xc2/1#;\x90/($8":\xc3"! )("\'#&\'#'),_('%3\xc4""5$7\xc5/1#;\xf0/($8":\xc6"! )("\'#&\'#'),_('%3\xc7""5&7\xc8/1#;T/($8":\xc9"! )("\'#&\'#'),_('%3\xca""5"7\xcb/N#%2>""6>7?/,#;6/#$+")("\'#&\'#." &"/\'$8":\xcc" )("\'#&\'#'),_('%;h/P#%2>""6>7?/,#;i/#$+")("\'#&\'#." &"/)$8":\xcd""! )("\'#&\'#'),_('%$;j/�#*;j&&&#/"!&,)'),_('%$;j/�#*;j&&&#/"!&,)'),_(";k.) &;+.# &;-"),_('2l""6l7m.e &2n""6n7o.Y &24""6475.M &28""6879.A &2<""6<7=.5 &2@""6@7A.) &2B""6B7C'),_('%26""6677/n#;m/e$$%2<""6<7=/,#;m/#$+")("\'#&\'#0<*%2<""6<7=/,#;m/#$+")("\'#&\'#&/#$+#)(#\'#("\'#&\'#'),_('%;n/A#2>""6>7?/2$;o/)$8#:\xce#"" )(#\'#("\'#&\'#'),_("$;p.) &;+.# &;-/2#0/*;p.) &;+.# &;-&&&#"),_("$;p.) &;+.# &;-0/*;p.) &;+.# &;-&"),_('2l""6l7m.e &2n""6n7o.Y &24""6475.M &26""6677.A &28""6879.5 &2@""6@7A.) &2B""6B7C'),_(";\x91.# &;r"),_("%;\x90/G#;'/>$;s/5$;'/,$;\x84/#$+%)(%'#($'#(#'#(\"'#&'#"),_(";M.# &;t"),_("%;\x7f/E#28\"\"6879/6$;u.# &;x/'$8#:\xcf# )(#'#(\"'#&'#"),_('%;v.# &;w/J#%26""6677/,#;\x83/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),_('%2\xd0""6\xd07\xd1/:#;\x80/1$;w." &"/#$+#)(#\'#("\'#&\'#'),_('%24""6475/,#;{/#$+")("\'#&\'#'),_("%;z/3#$;y0#*;y&/#$+\")(\"'#&'#"),_(";*.) &;+.# &;-"),_(';+.\x8f &;-.\x89 &22""6273.} &26""6677.q &28""6879.e &2:""6:7;.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),_('%;|/e#$%24""6475/,#;|/#$+")("\'#&\'#0<*%24""6475/,#;|/#$+")("\'#&\'#&/#$+")("\'#&\'#'),_('%$;~0#*;~&/e#$%22""6273/,#;}/#$+")("\'#&\'#0<*%22""6273/,#;}/#$+")("\'#&\'#&/#$+")("\'#&\'#'),_("$;~0#*;~&"),_(';+.w &;-.q &28""6879.e &2:""6:7;.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),_('%%;"/\x87#$;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K0M*;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K&/#$+")("\'#&\'#/& 8!:\xd2! )'),_(";\x81.# &;\x82"),_('%%;O/2#2:""6:7;/#$+")("\'#&\'#." &"/,#;S/#$+")("\'#&\'#." &"'),_('$;+.\x83 &;-.} &2B""6B7C.q &2D""6D7E.e &22""6273.Y &28""6879.M &2:""6:7;.A &2<""6<7=.5 &2>""6>7?.) &2@""6@7A/\x8c#0\x89*;+.\x83 &;-.} &2B""6B7C.q &2D""6D7E.e &22""6273.Y &28""6879.M &2:""6:7;.A &2<""6<7=.5 &2>""6>7?.) &2@""6@7A&&&#'),_("$;y0#*;y&"),_('%3\x92""5#7\xd3/q#24""6475/b$$;!/�#*;!&&&#/L$2J""6J7K/=$$;!/�#*;!&&&#/\'$8%:\xd4% )(%\'#($\'#(#\'#("\'#&\'#'),_('2\xd5""6\xd57\xd6'),_('2\xd7""6\xd77\xd8'),_('2\xd9""6\xd97\xda'),_('2\xdb""6\xdb7\xdc'),_('2\xdd""6\xdd7\xde'),_('2\xdf""6\xdf7\xe0'),_('2\xe1""6\xe17\xe2'),_('2\xe3""6\xe37\xe4'),_('2\xe5""6\xe57\xe6'),_('2\xe7""6\xe77\xe8'),_('2\xe9""6\xe97\xea'),_("%;\x85.Y &;\x86.S &;\x88.M &;\x89.G &;\x8a.A &;\x8b.; &;\x8c.5 &;\x8f./ &;\x8d.) &;\x8e.# &;6/& 8!:\xeb! )"),_("%;\x84/G#;'/>$;\x92/5$;'/,$;\x94/#$+%)(%'#($'#(#'#(\"'#&'#"),_("%;\x93/' 8!:\xec!! )"),_("%;!/5#;!/,$;!/#$+#)(#'#(\"'#&'#"),_("%$;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(0G*;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(&/& 8!:\xed! )"),_("%;\xb6/Y#$%;A/,#;\xb6/#$+\")(\"'#&'#06*%;A/,#;\xb6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),_('%;9/N#%2:""6:7;/,#;9/#$+")("\'#&\'#." &"/\'$8":\xee" )("\'#&\'#'),_("%;:.c &%;\x98/Y#$%;A/,#;\x98/#$+\")(\"'#&'#06*%;A/,#;\x98/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/& 8!:\xef! )"),_("%;L.# &;\x99/]#$%;B/,#;\x9b/#$+\")(\"'#&'#06*%;B/,#;\x9b/#$+\")(\"'#&'#&/'$8\":\xf0\" )(\"'#&'#"),_("%;\x9a.\" &\"/>#;@/5$;M/,$;?/#$+$)($'#(#'#(\"'#&'#"),_("%%;6/Y#$%;./,#;6/#$+\")(\"'#&'#06*%;./,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#.# &;H/' 8!:\xf1!! )"),_(";\x9c.) &;\x9d.# &;\xa0"),_("%3\xf2\"\"5!7\xf3/:#;$;\xcf/5$;./,$;\x90/#$+%)(%'#($'#(#'#(\"'#&'#"),_("%$;!/�#*;!&&&#/' 8!:\u014b!! )"),_("%;\xd1/]#$%;A/,#;\xd1/#$+\")(\"'#&'#06*%;A/,#;\xd1/#$+\")(\"'#&'#&/'$8\":\u014c\" )(\"'#&'#"),_("%;\x99/]#$%;B/,#;\xa0/#$+\")(\"'#&'#06*%;B/,#;\xa0/#$+\")(\"'#&'#&/'$8\":\u014d\" )(\"'#&'#"),_('%;L.O &;\x99.I &%;@." &"/:#;t/1$;?." &"/#$+#)(#\'#("\'#&\'#/]#$%;B/,#;\xa0/#$+")("\'#&\'#06*%;B/,#;\xa0/#$+")("\'#&\'#&/\'$8":\u014e" )("\'#&\'#'),_("%;\xd4/]#$%;B/,#;\xd5/#$+\")(\"'#&'#06*%;B/,#;\xd5/#$+\")(\"'#&'#&/'$8\":\u014f\" )(\"'#&'#"),_("%;\x96/& 8!:\u0150! )"),_('%3\u0151""5(7\u0152/:#;$;6/5$;;/,$;\xec/#$+%)(%'#($'#(#'#(\"'#&'#"),_('%3\x92""5#7\xd3.# &;6/\' 8!:\u018b!! )'),_('%3\xb1""5#7\u018c.G &3\xb3""5#7\u018d.; &3\xb7""5#7\u018e./ &3\xb5""5$7\u018f.# &;6/\' 8!:\u0190!! )'),_('%;\xee/D#%;C/,#;\xef/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),_("%;U.) &;\\.# &;X/& 8!:\u0191! )"),_('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:\u0192!! )'),_('%%;!/?#;!." &"/1$;!." &"/#$+#)(#\'#("\'#&\'#/\' 8!:\u0193!! )'),_(";\xbe"),_('%;\x9e/^#$%;B/,#;\xf3/#$+")("\'#&\'#06*%;B/,#;\xf3/#$+")("\'#&\'#&/($8":\u0194"!!)("\'#&\'#'),_(";\xf4.# &;\xa0"),_('%2\u0195""6\u01957\u0196/L#;""6>7?'),_('%;\u0100/b#28""6879/S$;\xfb/J$%2\u01a3""6\u01a37\u01a4/,#;\xec/#$+")("\'#&\'#." &"/#$+$)($\'#(#\'#("\'#&\'#'),_('%3\u01a5""5%7\u01a6.) &3\u01a7""5$7\u01a8/\' 8!:\u01a1!! )'),_('%3\xb1""5#7\xb2.6 &3\xb3""5#7\xb4.* &$;+0#*;+&/\' 8!:\u01a9!! )'),_("%;\u0104/\x87#2F\"\"6F7G/x$;\u0103/o$2F\"\"6F7G/`$;\u0103/W$2F\"\"6F7G/H$;\u0103/?$2F\"\"6F7G/0$;\u0105/'$8):\u01aa) )()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#"),_("%;#/>#;#/5$;#/,$;#/#$+$)($'#(#'#(\"'#&'#"),_("%;\u0103/,#;\u0103/#$+\")(\"'#&'#"),_("%;\u0103/5#;\u0103/,$;\u0103/#$+#)(#'#(\"'#&'#"),_("%;q/T#$;m0#*;m&/D$%; /,#;\xf8/#$+\")(\"'#&'#.\" &\"/#$+#)(#'#(\"'#&'#"),_('%2\u01ab""6\u01ab7\u01ac.) &2\u01ad""6\u01ad7\u01ae/w#;0/n$;\u0108/e$$%;B/2#;\u0109.# &;\xa0/#$+")("\'#&\'#0<*%;B/2#;\u0109.# &;\xa0/#$+")("\'#&\'#&/#$+$)($\'#(#\'#("\'#&\'#'),_(";\x99.# &;L"),_("%2\u01af\"\"6\u01af7\u01b0/5#;g&&(g=p,f=[]),f.push(e))}function R(e,t,r){return new o(o.buildMessage(e,t),e,t,r)}function _(e){return e.split("").map((function(e){return e.charCodeAt(0)-32}))}if(t.data={},(r=function t(r){for(var n,s=d[r],o=0,a=[],c=s.length,l=[],g=[];;){for(;op?(c=o+3+s[o+1],o+=3):(c=o+3+s[o+1]+s[o+2],o+=3+s[o+1]);break;case 18:l.push(c),a.push(o+4+s[o+2]+s[o+3]),e.substr(p,u[s[o+1]].length)===u[s[o+1]]?(c=o+4+s[o+2],o+=4):(c=o+4+s[o+2]+s[o+3],o+=4+s[o+2]);break;case 19:l.push(c),a.push(o+4+s[o+2]+s[o+3]),e.substr(p,u[s[o+1]].length).toLowerCase()===u[s[o+1]]?(c=o+4+s[o+2],o+=4):(c=o+4+s[o+2]+s[o+3],o+=4+s[o+2]);break;case 20:l.push(c),a.push(o+4+s[o+2]+s[o+3]),u[s[o+1]].test(e.charAt(p))?(c=o+4+s[o+2],o+=4):(c=o+4+s[o+2]+s[o+3],o+=4+s[o+2]);break;case 21:g.push(e.substr(p,s[o+1])),p+=s[o+1],o+=2;break;case 22:g.push(u[s[o+1]]),p+=u[s[o+1]].length,o+=2;break;case 23:g.push(i),0===m&&C(u[s[o+1]]),o+=2;break;case 24:h=g[g.length-1-s[o+1]],o+=2;break;case 25:h=p,o++;break;case 26:n=s.slice(o+4,o+4+s[o+3]).map((function(e){return g[g.length-1-e]})),g.splice(g.length-s[o+2],s[o+2],u[s[o+1]].apply(null,n)),o+=4+s[o+3];break;case 27:g.push(t(s[o+1])),o+=2;break;case 28:m++,o++;break;case 29:m--,o++;break;default:throw new Error("Invalid opcode: "+s[o]+".")}if(!(l.length>0))break;c=l.pop(),o=a.pop()}return g[0]}(c))!==i&&p===e.length)return r;throw r!==i&&p-1)this.qop="auth";else{if(!(t.qop.indexOf("auth-int")>-1))return this.logger.warn("challenge without Digest qop different than 'auth' or 'auth-int', authentication aborted"),!1;this.qop="auth-int"}else this.qop=void 0;return this.method=e.method,this.uri=e.ruri,this.cnonce=n.createRandomToken(12),this.nc+=1,this.updateNcHex(),4294967296===this.nc&&(this.nc=1,this.ncHex="00000001"),this.calculateResponse(r),!0},e.prototype.toString=function(){var e=[];if(!this.response)throw new Error("response field does not exist, cannot generate Authorization header");return e.push("algorithm="+this.algorithm),e.push('username="'+this.username+'"'),e.push('realm="'+this.realm+'"'),e.push('nonce="'+this.nonce+'"'),e.push('uri="'+this.uri+'"'),e.push('response="'+this.response+'"'),this.opaque&&e.push('opaque="'+this.opaque+'"'),this.qop&&(e.push("qop="+this.qop),e.push('cnonce="'+this.cnonce+'"'),e.push("nc="+this.ncHex)),"Digest "+e.join(", ")},e.prototype.updateNcHex=function(){var e=Number(this.nc).toString(16);this.ncHex="00000000".substr(0,8-e.length)+e},e.prototype.calculateResponse=function(e){var t,r=i.default(this.username+":"+this.realm+":"+this.password);"auth"===this.qop?(t=i.default(this.method+":"+this.uri),this.response=i.default(r+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth:"+t)):"auth-int"===this.qop?(t=i.default(this.method+":"+this.uri+":"+i.default(e||"")),this.response=i.default(r+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth-int:"+t)):void 0===this.qop&&(t=i.default(this.method+":"+this.uri),this.response=i.default(r+":"+this.nonce+":"+t))},e}();t.DigestAuthentication=s},function(e,t,r){var i;e.exports=(i=r(61),function(e){var t=i,r=t.lib,n=r.WordArray,s=r.Hasher,o=t.algo,a=[];!function(){for(var t=0;t<64;t++)a[t]=4294967296*e.abs(e.sin(t+1))|0}();var c=o.MD5=s.extend({_doReset:function(){this._hash=new n.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(e,t){for(var r=0;r<16;r++){var i=t+r,n=e[i];e[i]=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8)}var s=this._hash.words,o=e[t+0],c=e[t+1],l=e[t+2],g=e[t+3],f=e[t+4],m=e[t+5],v=e[t+6],S=e[t+7],T=e[t+8],y=e[t+9],E=e[t+10],b=e[t+11],C=e[t+12],R=e[t+13],_=e[t+14],w=e[t+15],A=s[0],I=s[1],O=s[2],N=s[3];A=u(A,I,O,N,o,7,a[0]),N=u(N,A,I,O,c,12,a[1]),O=u(O,N,A,I,l,17,a[2]),I=u(I,O,N,A,g,22,a[3]),A=u(A,I,O,N,f,7,a[4]),N=u(N,A,I,O,m,12,a[5]),O=u(O,N,A,I,v,17,a[6]),I=u(I,O,N,A,S,22,a[7]),A=u(A,I,O,N,T,7,a[8]),N=u(N,A,I,O,y,12,a[9]),O=u(O,N,A,I,E,17,a[10]),I=u(I,O,N,A,b,22,a[11]),A=u(A,I,O,N,C,7,a[12]),N=u(N,A,I,O,R,12,a[13]),O=u(O,N,A,I,_,17,a[14]),A=d(A,I=u(I,O,N,A,w,22,a[15]),O,N,c,5,a[16]),N=d(N,A,I,O,v,9,a[17]),O=d(O,N,A,I,b,14,a[18]),I=d(I,O,N,A,o,20,a[19]),A=d(A,I,O,N,m,5,a[20]),N=d(N,A,I,O,E,9,a[21]),O=d(O,N,A,I,w,14,a[22]),I=d(I,O,N,A,f,20,a[23]),A=d(A,I,O,N,y,5,a[24]),N=d(N,A,I,O,_,9,a[25]),O=d(O,N,A,I,g,14,a[26]),I=d(I,O,N,A,T,20,a[27]),A=d(A,I,O,N,R,5,a[28]),N=d(N,A,I,O,l,9,a[29]),O=d(O,N,A,I,S,14,a[30]),A=p(A,I=d(I,O,N,A,C,20,a[31]),O,N,m,4,a[32]),N=p(N,A,I,O,T,11,a[33]),O=p(O,N,A,I,b,16,a[34]),I=p(I,O,N,A,_,23,a[35]),A=p(A,I,O,N,c,4,a[36]),N=p(N,A,I,O,f,11,a[37]),O=p(O,N,A,I,S,16,a[38]),I=p(I,O,N,A,E,23,a[39]),A=p(A,I,O,N,R,4,a[40]),N=p(N,A,I,O,o,11,a[41]),O=p(O,N,A,I,g,16,a[42]),I=p(I,O,N,A,v,23,a[43]),A=p(A,I,O,N,y,4,a[44]),N=p(N,A,I,O,C,11,a[45]),O=p(O,N,A,I,w,16,a[46]),A=h(A,I=p(I,O,N,A,l,23,a[47]),O,N,o,6,a[48]),N=h(N,A,I,O,S,10,a[49]),O=h(O,N,A,I,_,15,a[50]),I=h(I,O,N,A,m,21,a[51]),A=h(A,I,O,N,C,6,a[52]),N=h(N,A,I,O,g,10,a[53]),O=h(O,N,A,I,E,15,a[54]),I=h(I,O,N,A,c,21,a[55]),A=h(A,I,O,N,T,6,a[56]),N=h(N,A,I,O,w,10,a[57]),O=h(O,N,A,I,v,15,a[58]),I=h(I,O,N,A,R,21,a[59]),A=h(A,I,O,N,f,6,a[60]),N=h(N,A,I,O,b,10,a[61]),O=h(O,N,A,I,l,15,a[62]),I=h(I,O,N,A,y,21,a[63]),s[0]=s[0]+A|0,s[1]=s[1]+I|0,s[2]=s[2]+O|0,s[3]=s[3]+N|0},_doFinalize:function(){var t=this._data,r=t.words,i=8*this._nDataBytes,n=8*t.sigBytes;r[n>>>5]|=128<<24-n%32;var s=e.floor(i/4294967296),o=i;r[15+(n+64>>>9<<4)]=16711935&(s<<8|s>>>24)|4278255360&(s<<24|s>>>8),r[14+(n+64>>>9<<4)]=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8),t.sigBytes=4*(r.length+1),this._process();for(var a=this._hash,c=a.words,u=0;u<4;u++){var d=c[u];c[u]=16711935&(d<<8|d>>>24)|4278255360&(d<<24|d>>>8)}return a},clone:function(){var e=s.clone.call(this);return e._hash=this._hash.clone(),e}});function u(e,t,r,i,n,s,o){var a=e+(t&r|~t&i)+n+o;return(a<>>32-s)+t}function d(e,t,r,i,n,s,o){var a=e+(t&i|r&~i)+n+o;return(a<>>32-s)+t}function p(e,t,r,i,n,s,o){var a=e+(t^r^i)+n+o;return(a<>>32-s)+t}function h(e,t,r,i,n,s,o){var a=e+(r^(t|~i))+n+o;return(a<>>32-s)+t}t.MD5=s._createHelper(c),t.HmacMD5=s._createHmacHelper(c)}(Math),i.MD5)},function(e,t,r){var i;e.exports=(i=i||function(e,t){var r=Object.create||function(){function e(){}return function(t){var r;return e.prototype=t,r=new e,e.prototype=null,r}}(),i={},n=i.lib={},s=n.Base={extend:function(e){var t=r(this);return e&&t.mixIn(e),t.hasOwnProperty("init")&&this.init!==t.init||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},o=n.WordArray=s.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||c).stringify(this)},concat:function(e){var t=this.words,r=e.words,i=this.sigBytes,n=e.sigBytes;if(this.clamp(),i%4)for(var s=0;s>>2]>>>24-s%4*8&255;t[i+s>>>2]|=o<<24-(i+s)%4*8}else for(s=0;s>>2]=r[s>>>2];return this.sigBytes+=n,this},clamp:function(){var t=this.words,r=this.sigBytes;t[r>>>2]&=4294967295<<32-r%4*8,t.length=e.ceil(r/4)},clone:function(){var e=s.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var r,i=[],n=function(t){t=t;var r=987654321,i=4294967295;return function(){var n=((r=36969*(65535&r)+(r>>16)&i)<<16)+(t=18e3*(65535&t)+(t>>16)&i)&i;return n/=4294967296,(n+=.5)*(e.random()>.5?1:-1)}},s=0;s>>2]>>>24-n%4*8&255;i.push((s>>>4).toString(16)),i.push((15&s).toString(16))}return i.join("")},parse:function(e){for(var t=e.length,r=[],i=0;i>>3]|=parseInt(e.substr(i,2),16)<<24-i%8*4;return new o.init(r,t/2)}},u=a.Latin1={stringify:function(e){for(var t=e.words,r=e.sigBytes,i=[],n=0;n>>2]>>>24-n%4*8&255;i.push(String.fromCharCode(s))}return i.join("")},parse:function(e){for(var t=e.length,r=[],i=0;i>>2]|=(255&e.charCodeAt(i))<<24-i%4*8;return new o.init(r,t)}},d=a.Utf8={stringify:function(e){try{return decodeURIComponent(escape(u.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return u.parse(unescape(encodeURIComponent(e)))}},p=n.BufferedBlockAlgorithm=s.extend({reset:function(){this._data=new o.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=d.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var r=this._data,i=r.words,n=r.sigBytes,s=this.blockSize,a=n/(4*s),c=(a=t?e.ceil(a):e.max((0|a)-this._minBufferSize,0))*s,u=e.min(4*c,n);if(c){for(var d=0;d699)throw new TypeError("Invalid statusCode: "+t.statusCode);var n=t.reasonPhrase?t.reasonPhrase:i.getReasonPhrase(t.statusCode),s="SIP/2.0 "+t.statusCode+" "+n+r;t.statusCode>=100&&t.statusCode,t.statusCode;var o="From: "+e.getHeader("From")+r,a="Call-ID: "+e.callId+r,c="CSeq: "+e.cseq+" "+e.method+r,u=e.getHeaders("via").reduce((function(e,t){return e+"Via: "+t+r}),""),d="To: "+e.getHeader("to");if(t.statusCode>100&&!e.parseHeader("to").hasParam("tag")){var p=t.toTag;p||(p=i.newTag()),d+=";tag="+p}d+=r;var h="";t.supported&&(h="Supported: "+t.supported.join(", ")+r);var l="";t.userAgent&&(l="User-Agent: "+t.userAgent+r);var g="";return t.extraHeaders&&(g=t.extraHeaders.reduce((function(e,t){return e+t.trim()+r}),"")),s+=u,s+=o,s+=d,s+=c,s+=a,s+=h,s+=l,s+=g,t.body?(s+="Content-Type: "+t.body.contentType+r,s+="Content-Length: "+i.str_utf8_length(t.body.content)+r+r,s+=t.body.content):s+="Content-Length: 0\r\n\r\n",{message:s}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(2),s=r(15),o=r(6),a=r(1),c=r(36),u=r(37),d=r(38),p=r(39),h=r(40),l=r(26),g=r(41),f=r(42),m=r(43),v=r(44),S=r(45),T=r(46),y=function(e){function t(t,r,i,n){var o=e.call(this,r,i)||this;return o.initialTransaction=t,o._signalingState=s.SignalingState.Initial,o.ackWait=!1,o.delegate=n,t instanceof a.InviteServerTransaction&&(o.ackWait=!0),o.early||o.start2xxRetransmissionTimer(),o.signalingStateTransition(t.request),o.logger=r.loggerFactory.getLogger("sip.invite-dialog"),o.logger.log("INVITE dialog "+o.id+" constructed"),o}return i.__extends(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this),this._signalingState=s.SignalingState.Closed,this._offer=void 0,this._answer=void 0,this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.logger.log("INVITE dialog "+this.id+" destroyed")},Object.defineProperty(t.prototype,"sessionState",{get:function(){return this.early?s.SessionState.Early:this.ackWait?s.SessionState.AckWait:this._signalingState===s.SignalingState.Closed?s.SessionState.Terminated:s.SessionState.Confirmed},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"signalingState",{get:function(){return this._signalingState},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"offer",{get:function(){return this._offer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"answer",{get:function(){return this._answer},enumerable:!0,configurable:!0}),t.prototype.confirm=function(){this.early&&this.start2xxRetransmissionTimer(),e.prototype.confirm.call(this)},t.prototype.reConfirm=function(){this.reinviteUserAgentServer&&this.startReInvite2xxRetransmissionTimer()},t.prototype.ack=function(e){var t;if(void 0===e&&(e={}),this.logger.log("INVITE dialog "+this.id+" sending ACK request"),this.reinviteUserAgentClient){if(!(this.reinviteUserAgentClient.transaction instanceof a.InviteClientTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");t=this.reinviteUserAgentClient.transaction,this.reinviteUserAgentClient=void 0}else{if(!(this.initialTransaction instanceof a.InviteClientTransaction))throw new Error("Initial transaction not instance of InviteClientTransaction.");t=this.initialTransaction}e.cseq=t.request.cseq;var r=this.createOutgoingRequestMessage(n.C.ACK,e);return t.ackResponse(r),this.signalingStateTransition(r),{message:r}},t.prototype.bye=function(e,t){if(this.logger.log("INVITE dialog "+this.id+" sending BYE request"),this.initialTransaction instanceof a.InviteServerTransaction){if(this.early)throw new Error("UAS MUST NOT send a BYE on early dialogs.");if(this.ackWait&&this.initialTransaction.state!==a.TransactionState.Terminated)throw new Error("UAS MUST NOT send a BYE on a confirmed dialog until it has received an ACK for its 2xx response or until the server transaction times out.")}return new c.ByeUserAgentClient(this,e,t)},t.prototype.info=function(e,t){if(this.logger.log("INVITE dialog "+this.id+" sending INFO request"),this.early)throw new Error("Dialog not confirmed.");return new d.InfoUserAgentClient(this,e,t)},t.prototype.invite=function(e,t){if(this.logger.log("INVITE dialog "+this.id+" sending INVITE request"),this.early)throw new Error("Dialog not confirmed.");if(this.reinviteUserAgentClient)throw new Error("There is an ongoing re-INVITE client transaction.");if(this.reinviteUserAgentServer)throw new Error("There is an ongoing re-INVITE server transaction.");return new m.ReInviteUserAgentClient(this,e,t)},t.prototype.notify=function(e,t){if(this.logger.log("INVITE dialog "+this.id+" sending NOTIFY request"),this.early)throw new Error("Dialog not confirmed.");return new h.NotifyUserAgentClient(this,e,t)},t.prototype.prack=function(e,t){return this.logger.log("INVITE dialog "+this.id+" sending PRACK request"),new g.PrackUserAgentClient(this,e,t)},t.prototype.refer=function(e,t){if(this.logger.log("INVITE dialog "+this.id+" sending REFER request"),this.early)throw new Error("Dialog not confirmed.");return new S.ReferUserAgentClient(this,e,t)},t.prototype.receiveRequest=function(t){if(this.logger.log("INVITE dialog "+this.id+" received "+t.method+" request"),t.method===n.C.ACK){if(this.ackWait){if(this.initialTransaction instanceof a.InviteClientTransaction)return void this.logger.warn("INVITE dialog "+this.id+" received unexpected "+t.method+" request, dropping.");if(this.initialTransaction.request.cseq!==t.cseq)return void this.logger.warn("INVITE dialog "+this.id+" received unexpected "+t.method+" request, dropping.");this.ackWait=!1}else{if(!this.reinviteUserAgentServer)return void this.logger.warn("INVITE dialog "+this.id+" received unexpected "+t.method+" request, dropping.");if(this.reinviteUserAgentServer.transaction.request.cseq!==t.cseq)return void this.logger.warn("INVITE dialog "+this.id+" received unexpected "+t.method+" request, dropping.");this.reinviteUserAgentServer=void 0}return this.signalingStateTransition(t),void(this.delegate&&this.delegate.onAck&&this.delegate.onAck({message:t}))}if(this.sequenceGuard(t)){if(t.method===n.C.INVITE){if(this.reinviteUserAgentServer){var r=["Retry-After: "+(Math.floor(10*Math.random())+1)];return void this.core.replyStateless(t,{statusCode:500,extraHeaders:r})}if(this.reinviteUserAgentClient)return void this.core.replyStateless(t,{statusCode:491})}if(e.prototype.receiveRequest.call(this,t),t.method===n.C.INVITE){var i=t.parseHeader("contact");if(!i)throw new Error("Contact undefined.");if(!(i instanceof n.NameAddrHeader))throw new Error("Contact not instance of NameAddrHeader.");this.dialogState.remoteTarget=i.uri}switch(t.method){case n.C.BYE:var s=new u.ByeUserAgentServer(this,t);this.delegate&&this.delegate.onBye?this.delegate.onBye(s):s.accept(),this.dispose();break;case n.C.INFO:s=new p.InfoUserAgentServer(this,t);this.delegate&&this.delegate.onInfo?this.delegate.onInfo(s):s.reject({statusCode:469,extraHeaders:["Recv-Info :"]});break;case n.C.INVITE:s=new v.ReInviteUserAgentServer(this,t);this.signalingStateTransition(t),this.delegate&&this.delegate.onInvite?this.delegate.onInvite(s):s.reject({statusCode:488});break;case n.C.NOTIFY:s=new l.NotifyUserAgentServer(this,t);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(s):s.accept();break;case n.C.PRACK:s=new f.PrackUserAgentServer(this,t);this.delegate&&this.delegate.onPrack?this.delegate.onPrack(s):s.accept();break;case n.C.REFER:s=new T.ReferUserAgentServer(this,t);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(s):s.reject();break;default:this.logger.log("INVITE dialog "+this.id+" received unimplemented "+t.method+" request"),this.core.replyStateless(t,{statusCode:501})}}else this.logger.log("INVITE dialog "+this.id+" rejected out of order "+t.method+" request.")},t.prototype.reliableSequenceGuard=function(e){var t=e.statusCode;if(!t)throw new Error("Status code undefined");if(t>100&&t<200){var r=e.getHeader("require"),i=e.getHeader("rseq"),n=r&&r.includes("100rel")&&i?Number(i):void 0;if(n){if(this.rseq&&this.rseq+1!==n)return!1;this.rseq||(this.rseq=n)}}return!0},t.prototype.signalingStateRollback=function(){this._signalingState!==s.SignalingState.HaveLocalOffer&&this.signalingState!==s.SignalingState.HaveRemoteOffer||this._rollbackOffer&&this._rollbackAnswer&&(this._signalingState=s.SignalingState.Stable,this._offer=this._rollbackOffer,this._answer=this._rollbackAnswer)},t.prototype.signalingStateTransition=function(e){var t=n.getBody(e);if(t&&"session"===t.contentDisposition){if(this._signalingState===s.SignalingState.Stable&&(this._rollbackOffer=this._offer,this._rollbackAnswer=this._answer),e instanceof n.IncomingRequestMessage)switch(this._signalingState){case s.SignalingState.Initial:case s.SignalingState.Stable:this._signalingState=s.SignalingState.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case s.SignalingState.HaveLocalOffer:this._signalingState=s.SignalingState.Stable,this._answer=t;break;case s.SignalingState.HaveRemoteOffer:case s.SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof n.IncomingResponseMessage)switch(this._signalingState){case s.SignalingState.Initial:case s.SignalingState.Stable:this._signalingState=s.SignalingState.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case s.SignalingState.HaveLocalOffer:this._signalingState=s.SignalingState.Stable,this._answer=t;break;case s.SignalingState.HaveRemoteOffer:case s.SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof n.OutgoingRequestMessage)switch(this._signalingState){case s.SignalingState.Initial:case s.SignalingState.Stable:this._signalingState=s.SignalingState.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case s.SignalingState.HaveLocalOffer:break;case s.SignalingState.HaveRemoteOffer:this._signalingState=s.SignalingState.Stable,this._answer=t;break;case s.SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}if(n.isBody(e))switch(this._signalingState){case s.SignalingState.Initial:case s.SignalingState.Stable:this._signalingState=s.SignalingState.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case s.SignalingState.HaveLocalOffer:break;case s.SignalingState.HaveRemoteOffer:this._signalingState=s.SignalingState.Stable,this._answer=t;break;case s.SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}}},t.prototype.start2xxRetransmissionTimer=function(){var e=this;if(this.initialTransaction instanceof a.InviteServerTransaction){var t=this.initialTransaction,r=o.Timers.T1,i=function(){e.ackWait?(e.logger.log("No ACK for 2xx response received, attempting retransmission"),t.retransmitAcceptedResponse(),r=Math.min(2*r,o.Timers.T2),e.invite2xxTimer=setTimeout(i,r)):e.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(i,r);var n=function(){t.state===a.TransactionState.Terminated&&(t.removeListener("stateChanged",n),e.invite2xxTimer&&(clearTimeout(e.invite2xxTimer),e.invite2xxTimer=void 0),e.ackWait&&(e.delegate&&e.delegate.onAckTimeout?e.delegate.onAckTimeout():e.bye()))};t.addListener("stateChanged",n)}},t.prototype.startReInvite2xxRetransmissionTimer=function(){var e=this;if(this.reinviteUserAgentServer&&this.reinviteUserAgentServer.transaction instanceof a.InviteServerTransaction){var t=this.reinviteUserAgentServer.transaction,r=o.Timers.T1,i=function(){e.reinviteUserAgentServer?(e.logger.log("No ACK for 2xx response received, attempting retransmission"),t.retransmitAcceptedResponse(),r=Math.min(2*r,o.Timers.T2),e.invite2xxTimer=setTimeout(i,r)):e.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(i,r);var n=function(){t.state===a.TransactionState.Terminated&&(t.removeListener("stateChanged",n),e.invite2xxTimer&&(clearTimeout(e.invite2xxTimer),e.invite2xxTimer=void 0),e.reinviteUserAgentServer)};t.addListener("stateChanged",n)}},t}(r(18).Dialog);t.SessionDialog=y},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e){e.Initial="Initial",e.Early="Early",e.AckWait="AckWait",e.Confirmed="Confirmed",e.Terminated="Terminated"}(t.SessionState||(t.SessionState={})),function(e){e.Initial="Initial",e.HaveLocalOffer="HaveLocalOffer",e.HaveRemoteOffer="HaveRemoteOffer",e.Stable="Stable",e.Closed="Closed"}(t.SignalingState||(t.SignalingState={}))},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=function(e){function t(t){return e.call(this,t||"Transaction state error.")||this}return i.__extends(t,e),t}(r(24).Exception);t.TransactionStateError=n},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=function(e){function t(t){return e.call(this,t||"Unspecified transport error.")||this}return i.__extends(t,e),t}(r(24).Exception);t.TransportError=n},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(2),s=r(6),o=r(25),a=r(13),c=function(e){function t(t,r,i){return e.call(this,t,r,i,a.TransactionState.Proceeding,"sip.transaction.ist")||this}return i.__extends(t,e),t.prototype.dispose=function(){this.stopProgressExtensionTimer(),this.H&&(clearTimeout(this.H),this.H=void 0),this.I&&(clearTimeout(this.I),this.I=void 0),this.L&&(clearTimeout(this.L),this.L=void 0),e.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"kind",{get:function(){return"ist"},enumerable:!0,configurable:!0}),t.prototype.receiveRequest=function(e){var t=this;switch(this.state){case a.TransactionState.Proceeding:if(e.method===n.C.INVITE)return void(this.lastProvisionalResponse&&this.send(this.lastProvisionalResponse).catch((function(e){t.logTransportError(e,"Failed to send retransmission of provisional response.")})));break;case a.TransactionState.Accepted:if(e.method===n.C.INVITE)return;break;case a.TransactionState.Completed:if(e.method===n.C.INVITE){if(!this.lastFinalResponse)throw new Error("Last final response undefined.");return void this.send(this.lastFinalResponse).catch((function(e){t.logTransportError(e,"Failed to send retransmission of final response.")}))}if(e.method===n.C.ACK)return void this.stateTransition(a.TransactionState.Confirmed);break;case a.TransactionState.Confirmed:case a.TransactionState.Terminated:if(e.method===n.C.INVITE||e.method===n.C.ACK)return;break;default:throw new Error("Invalid state "+this.state)}var r="INVITE server transaction received unexpected "+e.method+" request while in state "+this.state+".";this.logger.warn(r)},t.prototype.receiveResponse=function(e,t){var r=this;if(e<100||e>699)throw new Error("Invalid status code "+e);switch(this.state){case a.TransactionState.Proceeding:if(e>=100&&e<=199)return this.lastProvisionalResponse=t,e>100&&this.startProgressExtensionTimer(),void this.send(t).catch((function(e){r.logTransportError(e,"Failed to send 1xx response.")}));if(e>=200&&e<=299)return this.lastFinalResponse=t,this.stateTransition(a.TransactionState.Accepted),void this.send(t).catch((function(e){r.logTransportError(e,"Failed to send 2xx response.")}));if(e>=300&&e<=699)return this.lastFinalResponse=t,this.stateTransition(a.TransactionState.Completed),void this.send(t).catch((function(e){r.logTransportError(e,"Failed to send non-2xx final response.")}));break;case a.TransactionState.Accepted:if(e>=200&&e<=299)return void this.send(t).catch((function(e){r.logTransportError(e,"Failed to send 2xx response.")}));break;case a.TransactionState.Completed:case a.TransactionState.Confirmed:case a.TransactionState.Terminated:break;default:throw new Error("Invalid state "+this.state)}var i="INVITE server transaction received unexpected "+e+" response from TU while in state "+this.state+".";throw this.logger.error(i),new Error(i)},t.prototype.retransmitAcceptedResponse=function(){var e=this;this.state===a.TransactionState.Accepted&&this.lastFinalResponse&&this.send(this.lastFinalResponse).catch((function(t){e.logTransportError(t,"Failed to send 2xx response.")}))},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e)},t.prototype.typeToString=function(){return"INVITE server transaction"},t.prototype.stateTransition=function(e){var t=this,r=function(){throw new Error("Invalid state transition from "+t.state+" to "+e)};switch(e){case a.TransactionState.Proceeding:r();break;case a.TransactionState.Accepted:case a.TransactionState.Completed:this.state!==a.TransactionState.Proceeding&&r();break;case a.TransactionState.Confirmed:this.state!==a.TransactionState.Completed&&r();break;case a.TransactionState.Terminated:this.state!==a.TransactionState.Accepted&&this.state!==a.TransactionState.Completed&&this.state!==a.TransactionState.Confirmed&&r();break;default:r()}this.stopProgressExtensionTimer(),e===a.TransactionState.Accepted&&(this.L=setTimeout((function(){return t.timer_L()}),s.Timers.TIMER_L)),e===a.TransactionState.Completed&&(this.H=setTimeout((function(){return t.timer_H()}),s.Timers.TIMER_H)),e===a.TransactionState.Confirmed&&(this.I=setTimeout((function(){return t.timer_I()}),s.Timers.TIMER_I)),e===a.TransactionState.Terminated&&this.dispose(),this.setState(e)},t.prototype.startProgressExtensionTimer=function(){var e=this;void 0===this.progressExtensionTimer&&(this.progressExtensionTimer=setInterval((function(){if(e.logger.debug("Progress extension timer expired for INVITE server transaction "+e.id+"."),!e.lastProvisionalResponse)throw new Error("Last provisional response undefined.");e.send(e.lastProvisionalResponse).catch((function(t){e.logTransportError(t,"Failed to send retransmission of provisional response.")}))}),s.Timers.PROVISIONAL_RESPONSE_INTERVAL))},t.prototype.stopProgressExtensionTimer=function(){void 0!==this.progressExtensionTimer&&(clearInterval(this.progressExtensionTimer),this.progressExtensionTimer=void 0)},t.prototype.timer_G=function(){},t.prototype.timer_H=function(){this.logger.debug("Timer H expired for INVITE server transaction "+this.id+"."),this.state===a.TransactionState.Completed&&(this.logger.warn("ACK to negative final response was never received, terminating transaction."),this.stateTransition(a.TransactionState.Terminated))},t.prototype.timer_I=function(){this.logger.debug("Timer I expired for INVITE server transaction "+this.id+"."),this.stateTransition(a.TransactionState.Terminated)},t.prototype.timer_L=function(){this.logger.debug("Timer L expired for INVITE server transaction "+this.id+"."),this.state===a.TransactionState.Accepted&&this.stateTransition(a.TransactionState.Terminated)},t}(o.ServerTransaction);t.InviteServerTransaction=c},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(6),s=r(22),o=r(13),a=function(e){function t(t,r,i){var s=e.call(this,t,r,i,o.TransactionState.Trying,"sip.transaction.nict")||this;return s.F=setTimeout((function(){return s.timer_F()}),n.Timers.TIMER_F),s.send(t.toString()).catch((function(e){s.logTransportError(e,"Failed to send initial outgoing request.")})),s}return i.__extends(t,e),t.prototype.dispose=function(){this.F&&(clearTimeout(this.F),this.F=void 0),this.K&&(clearTimeout(this.K),this.K=void 0),e.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"kind",{get:function(){return"nict"},enumerable:!0,configurable:!0}),t.prototype.receiveResponse=function(e){var t=e.statusCode;if(!t||t<100||t>699)throw new Error("Invalid status code "+t);switch(this.state){case o.TransactionState.Trying:if(t>=100&&t<=199)return this.stateTransition(o.TransactionState.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=699)return this.stateTransition(o.TransactionState.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case o.TransactionState.Proceeding:if(t>=100&&t<=199&&this.user.receiveResponse)return this.user.receiveResponse(e);if(t>=200&&t<=699)return this.stateTransition(o.TransactionState.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));case o.TransactionState.Completed:case o.TransactionState.Terminated:return;default:throw new Error("Invalid state "+this.state)}var r="Non-INVITE client transaction received unexpected "+t+" response while in state "+this.state+".";this.logger.warn(r)},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(o.TransactionState.Terminated,!0)},t.prototype.typeToString=function(){return"non-INVITE client transaction"},t.prototype.stateTransition=function(e,t){var r=this;void 0===t&&(t=!1);var i=function(){throw new Error("Invalid state transition from "+r.state+" to "+e)};switch(e){case o.TransactionState.Trying:i();break;case o.TransactionState.Proceeding:this.state!==o.TransactionState.Trying&&i();break;case o.TransactionState.Completed:this.state!==o.TransactionState.Trying&&this.state!==o.TransactionState.Proceeding&&i();break;case o.TransactionState.Terminated:this.state!==o.TransactionState.Trying&&this.state!==o.TransactionState.Proceeding&&this.state!==o.TransactionState.Completed&&(t||i());break;default:i()}e===o.TransactionState.Completed&&(this.F&&(clearTimeout(this.F),this.F=void 0),this.K=setTimeout((function(){return r.timer_K()}),n.Timers.TIMER_K)),e===o.TransactionState.Terminated&&this.dispose(),this.setState(e)},t.prototype.timer_F=function(){this.logger.debug("Timer F expired for non-INVITE client transaction "+this.id+"."),this.state!==o.TransactionState.Trying&&this.state!==o.TransactionState.Proceeding||(this.onRequestTimeout(),this.stateTransition(o.TransactionState.Terminated))},t.prototype.timer_K=function(){this.state===o.TransactionState.Completed&&this.stateTransition(o.TransactionState.Terminated)},t}(s.ClientTransaction);t.NonInviteClientTransaction=a},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(6),s=r(25),o=r(13),a=function(e){function t(t,r,i){return e.call(this,t,r,i,o.TransactionState.Trying,"sip.transaction.nist")||this}return i.__extends(t,e),t.prototype.dispose=function(){this.J&&(clearTimeout(this.J),this.J=void 0),e.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"kind",{get:function(){return"nist"},enumerable:!0,configurable:!0}),t.prototype.receiveRequest=function(e){var t=this;switch(this.state){case o.TransactionState.Trying:break;case o.TransactionState.Proceeding:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch((function(e){t.logTransportError(e,"Failed to send retransmission of provisional response.")}));break;case o.TransactionState.Completed:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch((function(e){t.logTransportError(e,"Failed to send retransmission of final response.")}));break;case o.TransactionState.Terminated:break;default:throw new Error("Invalid state "+this.state)}},t.prototype.receiveResponse=function(e,t){var r=this;if(e<100||e>699)throw new Error("Invalid status code "+e);if(e>100&&e<=199)throw new Error("Provisional response other than 100 not allowed.");switch(this.state){case o.TransactionState.Trying:if(this.lastResponse=t,e>=100&&e<200)return this.stateTransition(o.TransactionState.Proceeding),void this.send(t).catch((function(e){r.logTransportError(e,"Failed to send provisional response.")}));if(e>=200&&e<=699)return this.stateTransition(o.TransactionState.Completed),void this.send(t).catch((function(e){r.logTransportError(e,"Failed to send final response.")}));break;case o.TransactionState.Proceeding:if(this.lastResponse=t,e>=200&&e<=699)return this.stateTransition(o.TransactionState.Completed),void this.send(t).catch((function(e){r.logTransportError(e,"Failed to send final response.")}));break;case o.TransactionState.Completed:return;case o.TransactionState.Terminated:break;default:throw new Error("Invalid state "+this.state)}var i="Non-INVITE server transaction received unexpected "+e+" response from TU while in state "+this.state+".";throw this.logger.error(i),new Error(i)},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(o.TransactionState.Terminated,!0)},t.prototype.typeToString=function(){return"non-INVITE server transaction"},t.prototype.stateTransition=function(e,t){var r=this;void 0===t&&(t=!1);var i=function(){throw new Error("Invalid state transition from "+r.state+" to "+e)};switch(e){case o.TransactionState.Trying:i();break;case o.TransactionState.Proceeding:this.state!==o.TransactionState.Trying&&i();break;case o.TransactionState.Completed:this.state!==o.TransactionState.Trying&&this.state!==o.TransactionState.Proceeding&&i();break;case o.TransactionState.Terminated:this.state!==o.TransactionState.Proceeding&&this.state!==o.TransactionState.Completed&&(t||i());break;default:i()}e===o.TransactionState.Completed&&(this.J=setTimeout((function(){return r.timer_J()}),n.Timers.TIMER_J)),e===o.TransactionState.Terminated&&this.dispose(),this.setState(e)},t.prototype.timer_J=function(){this.logger.debug("Timer J expired for NON-INVITE server transaction "+this.id+"."),this.state===o.TransactionState.Completed&&this.stateTransition(o.TransactionState.Terminated)},t}(s.ServerTransaction);t.NonInviteServerTransaction=a},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e){e.Initial="Initial",e.NotifyWait="NotifyWait",e.Pending="Pending",e.Active="Active",e.Terminated="Terminated"}(t.SubscriptionState||(t.SubscriptionState={}))},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0);i.__exportStar(r(28),t),i.__exportStar(r(72),t),i.__exportStar(r(49),t)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(28),n=r(49),s=function(){function e(){this.builtinEnabled=!0,this._level=i.Levels.log,this.loggers={},this.logger=this.getLogger("sip:loggerfactory")}return Object.defineProperty(e.prototype,"level",{get:function(){return this._level},set:function(e){e>=0&&e<=3?this._level=e:e>3?this._level=3:i.Levels.hasOwnProperty(e)?this._level=e:this.logger.error("invalid 'level' parameter value: "+JSON.stringify(e))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"connector",{get:function(){return this._connector},set:function(e){e?"function"==typeof e?this._connector=e:this.logger.error("invalid 'connector' parameter value: "+JSON.stringify(e)):this._connector=void 0},enumerable:!0,configurable:!0}),e.prototype.getLogger=function(e,t){if(t&&3===this.level)return new n.Logger(this,e,t);if(this.loggers[e])return this.loggers[e];var r=new n.Logger(this,e);return this.loggers[e]=r,r},e.prototype.genericLog=function(e,t,r,n){this.level>=e&&this.builtinEnabled&&this.print(e,t,r,n),this.connector&&this.connector(i.Levels[e],t,r,n)},e.prototype.print=function(e,t,r,n){if("string"==typeof n){var s=[new Date,t];r&&s.push(r),n=s.concat(n).join(" | ")}switch(e){case i.Levels.error:console.error(n);break;case i.Levels.warn:console.warn(n);break;case i.Levels.log:console.log(n);break;case i.Levels.debug:console.debug(n)}},e}();t.LoggerFactory=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),r(0).__exportStar(r(74),t)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(2),s=r(1),o=r(50),a=r(14),c=["application/sdp","application/dtmf-relay"],u=function(){function e(e,t){void 0===t&&(t={}),this.userAgentClients=new Map,this.userAgentServers=new Map,this.configuration=e,this.delegate=t,this.dialogs=new Map,this.subscribers=new Map,this.logger=e.loggerFactory.getLogger("sip.user-agent-core")}return e.prototype.dispose=function(){this.reset()},e.prototype.reset=function(){this.dialogs.forEach((function(e){return e.dispose()})),this.dialogs.clear(),this.subscribers.forEach((function(e){return e.dispose()})),this.subscribers.clear(),this.userAgentClients.forEach((function(e){return e.dispose()})),this.userAgentClients.clear(),this.userAgentServers.forEach((function(e){return e.dispose()})),this.userAgentServers.clear()},Object.defineProperty(e.prototype,"loggerFactory",{get:function(){return this.configuration.loggerFactory},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"transport",{get:function(){var e=this.configuration.transportAccessor();if(!e)throw new Error("Transport undefined.");return e},enumerable:!0,configurable:!0}),e.prototype.invite=function(e,t){return new o.InviteUserAgentClient(this,e,t)},e.prototype.message=function(e,t){return new o.MessageUserAgentClient(this,e,t)},e.prototype.publish=function(e,t){return new o.PublishUserAgentClient(this,e,t)},e.prototype.register=function(e,t){return new o.RegisterUserAgentClient(this,e,t)},e.prototype.subscribe=function(e,t){return new o.SubscribeUserAgentClient(this,e,t)},e.prototype.request=function(e,t){return new o.UserAgentClient(s.NonInviteClientTransaction,this,e,t)},e.prototype.makeOutgoingRequestMessage=function(e,t,r,s,o,a,c){var u=this.configuration.sipjsId,d=this.configuration.displayName,p=this.configuration.viaForceRport,h=this.configuration.hackViaTcp,l=this.configuration.supportedOptionTags.slice();e===n.C.REGISTER&&l.push("path","gruu"),e===n.C.INVITE&&(this.configuration.contact.pubGruu||this.configuration.contact.tempGruu)&&l.push("gruu");var g={callIdPrefix:u,forceRport:p,fromDisplayName:d,hackViaTcp:h,optionTags:l,routeSet:this.configuration.routeSet,userAgentString:this.configuration.userAgentHeaderFieldValue,viaHost:this.configuration.viaHost},f=i.__assign({},g,o);return new n.OutgoingRequestMessage(e,t,r,s,f,a,c)},e.prototype.receiveIncomingRequestFromTransport=function(e){this.receiveRequestFromTransport(e)},e.prototype.receiveIncomingResponseFromTransport=function(e){this.receiveResponseFromTransport(e)},e.prototype.replyStateless=function(e,t){var r=this.configuration.userAgentHeaderFieldValue,s=this.configuration.supportedOptionTagsResponse;t=i.__assign({},t,{userAgent:r,supported:s});var o=n.constructOutgoingResponse(e,t);return this.transport.send(o.message),o},e.prototype.receiveRequestFromTransport=function(e){var t=e.viaBranch,r=this.userAgentServers.get(t);e.method===n.C.ACK&&r&&r.transaction.state===s.TransactionState.Accepted&&r instanceof o.InviteUserAgentServer?this.logger.warn("Discarding out of dialog ACK after 2xx response sent on transaction "+t+"."):e.method!==n.C.CANCEL?r?r.transaction.receiveRequest(e):this.receiveRequest(e):r?(this.replyStateless(e,{statusCode:200}),r.transaction instanceof s.InviteServerTransaction&&r.transaction.state===s.TransactionState.Proceeding&&r instanceof o.InviteUserAgentServer&&r.receiveCancel(e)):this.replyStateless(e,{statusCode:481})},e.prototype.receiveRequest=function(e){if(a.AllowedMethods.includes(e.method)){if(!e.ruri)throw new Error("Request-URI undefined.");if("sip"===e.ruri.scheme){var t=e.ruri,r=function(e){return!!e&&e.user===t.user};if(!r(this.configuration.aor)&&!(r(this.configuration.contact.uri)||r(this.configuration.contact.pubGruu)||r(this.configuration.contact.tempGruu)))return this.logger.warn("Request-URI does not point to us."),void(e.method!==n.C.ACK&&this.replyStateless(e,{statusCode:404}));if(e.method!==n.C.INVITE||e.hasHeader("Contact")){if(!e.toTag){var i=e.viaBranch;if(!this.userAgentServers.has(i))if(Array.from(this.userAgentServers.values()).some((function(t){return t.transaction.request.fromTag===e.fromTag&&t.transaction.request.callId===e.callId&&t.transaction.request.cseq===e.cseq})))return void this.replyStateless(e,{statusCode:482})}e.toTag?this.receiveInsideDialogRequest(e):this.receiveOutsideDialogRequest(e)}else this.replyStateless(e,{statusCode:400,reasonPhrase:"Missing Contact Header"})}else this.replyStateless(e,{statusCode:416})}else{var s="Allow: "+a.AllowedMethods.toString();this.replyStateless(e,{statusCode:405,extraHeaders:[s]})}},e.prototype.receiveInsideDialogRequest=function(e){if(e.method===n.C.NOTIFY){var t=e.parseHeader("Event");if(!t||!t.event)return void this.replyStateless(e,{statusCode:489});var r=e.callId+e.toTag+t.event,i=this.subscribers.get(r);if(i){var s=new o.NotifyUserAgentServer(this,e);return void i.onNotify(s)}}var u=e.callId+e.toTag+e.fromTag,d=this.dialogs.get(u);if(d){if(e.method===n.C.OPTIONS){var p="Allow: "+a.AllowedMethods.toString(),h="Accept: "+c.toString();return void this.replyStateless(e,{statusCode:200,extraHeaders:[p,h]})}d.receiveRequest(e)}else e.method!==n.C.ACK&&this.replyStateless(e,{statusCode:481})},e.prototype.receiveOutsideDialogRequest=function(e){switch(e.method){case n.C.ACK:break;case n.C.BYE:this.replyStateless(e,{statusCode:481});break;case n.C.CANCEL:throw new Error("Unexpected out of dialog request method "+e.method+".");case n.C.INFO:this.replyStateless(e,{statusCode:405});break;case n.C.INVITE:var t=new o.InviteUserAgentServer(this,e);this.delegate.onInvite?this.delegate.onInvite(t):t.reject();break;case n.C.MESSAGE:t=new o.MessageUserAgentServer(this,e);this.delegate.onMessage?this.delegate.onMessage(t):t.accept();break;case n.C.NOTIFY:t=new o.NotifyUserAgentServer(this,e);this.delegate.onNotify?this.delegate.onNotify(t):t.reject({statusCode:405});break;case n.C.OPTIONS:var r="Allow: "+a.AllowedMethods.toString(),i="Accept: "+c.toString();this.replyStateless(e,{statusCode:200,extraHeaders:[r,i]});break;case n.C.REFER:t=new o.ReferUserAgentServer(this,e);this.delegate.onRefer?this.delegate.onRefer(t):t.reject({statusCode:405});break;case n.C.REGISTER:t=new o.RegisterUserAgentServer(this,e);this.delegate.onRegister?this.delegate.onRegister(t):t.reject({statusCode:405});break;case n.C.SUBSCRIBE:t=new o.SubscribeUserAgentServer(this,e);this.delegate.onSubscribe?this.delegate.onSubscribe(t):t.reject({statusCode:480});break;default:throw new Error("Unexpected out of dialog request method "+e.method+".")}},e.prototype.receiveResponseFromTransport=function(e){if(e.getHeaders("via").length>1)this.logger.warn("More than one Via header field present in the response, dropping");else{var t=e.viaBranch+e.method,r=this.userAgentClients.get(t);r?r.transaction.receiveResponse(e):this.logger.warn("Discarding unmatched "+e.statusCode+" response to "+e.method+" "+t+".")}},e}();t.UserAgentCore=u},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){return e.call(this,n.NonInviteClientTransaction,t,r,i)||this}return i.__extends(t,e),t}(r(3).UserAgentClient);t.CancelUserAgentClient=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(17),s=r(15),o=r(1),a=function(e){function t(t,r,i){var n=e.call(this,o.InviteClientTransaction,t,r,i)||this;return n.confirmedDialogAcks=new Map,n.confirmedDialogs=new Map,n.earlyDialogs=new Map,n.delegate=i,n}return i.__extends(t,e),t.prototype.dispose=function(){this.earlyDialogs.forEach((function(e){return e.dispose()})),this.earlyDialogs.clear(),e.prototype.dispose.call(this)},t.prototype.receiveResponse=function(e){var t=this;if(this.authenticationGuard(e)){var r=e.statusCode?e.statusCode.toString():"";if(!r)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(r):return void(this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e}));case/^1[0-9]{2}$/.test(r):if(!e.toTag)return void this.logger.warn("Non-100 1xx INVITE response received without a to tag, dropping.");var i=n.Dialog.initialDialogStateForUserAgentClient(this.message,e),a=this.earlyDialogs.get(i.id);if(!a){if(!((d=this.transaction)instanceof o.InviteClientTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");a=new n.SessionDialog(d,this.core,i),this.earlyDialogs.set(a.id,a)}if(!a.reliableSequenceGuard(e))return void this.logger.warn("1xx INVITE reliable response received out of order, dropping.");a.signalingState!==s.SignalingState.Initial&&a.signalingState!==s.SignalingState.HaveLocalOffer||a.signalingStateTransition(e);var c=a;return void(this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:c,prack:function(e){return c.prack(void 0,e)}}));case/^2[0-9]{2}$/.test(r):i=n.Dialog.initialDialogStateForUserAgentClient(this.message,e);var u=this.confirmedDialogs.get(i.id);if(u){if(h=this.confirmedDialogAcks.get(i.id)){if(!((d=this.transaction)instanceof o.InviteClientTransaction))throw new Error("Client transaction not instance of InviteClientTransaction.");d.ackResponse(h.message)}return}if(u=this.earlyDialogs.get(i.id))u.confirm(),u.recomputeRouteSet(e),this.earlyDialogs.delete(u.id),this.confirmedDialogs.set(u.id,u);else{var d;if(!((d=this.transaction)instanceof o.InviteClientTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");u=new n.SessionDialog(d,this.core,i),this.confirmedDialogs.set(u.id,u)}u.signalingState!==s.SignalingState.Initial&&u.signalingState!==s.SignalingState.HaveLocalOffer||u.signalingStateTransition(e);var p=u;if(this.delegate&&this.delegate.onAccept)this.delegate.onAccept({message:e,session:p,ack:function(e){var r=p.ack(e);return t.confirmedDialogAcks.set(p.id,r),r}});else{var h=p.ack();this.confirmedDialogAcks.set(p.id,h)}return;case/^3[0-9]{2}$/.test(r):return this.earlyDialogs.forEach((function(e){return e.dispose()})),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e}));case/^[4-6][0-9]{2}$/.test(r):return this.earlyDialogs.forEach((function(e){return e.dispose()})),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e}));default:throw new Error("Invalid status code "+r)}throw new Error("Executing what should be an unreachable code path receiving "+r+" response.")}},t}(r(3).UserAgentClient);t.InviteUserAgentClient=a},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(17),s=r(16),o=r(15),a=r(1),c=r(14),u=function(e){function t(t,r,i){var n=e.call(this,a.InviteServerTransaction,t,r,i)||this;return n.core=t,n}return i.__extends(t,e),t.prototype.dispose=function(){this.earlyDialog&&this.earlyDialog.dispose(),e.prototype.dispose.call(this)},t.prototype.accept=function(t){if(void 0===t&&(t={statusCode:200}),!this.acceptable)throw new s.TransactionStateError(this.message.method+" not acceptable in state "+this.transaction.state+".");if(!this.confirmedDialog)if(this.earlyDialog)this.earlyDialog.confirm(),this.confirmedDialog=this.earlyDialog,this.earlyDialog=void 0;else{var r=this.transaction;if(!(r instanceof a.InviteServerTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");var u=n.Dialog.initialDialogStateForUserAgentServer(this.message,this.toTag);this.confirmedDialog=new n.SessionDialog(r,this.core,u)}var d=this.message.getHeaders("record-route").map((function(e){return"Record-Route: "+e})),p="Contact: "+this.core.configuration.contact.toString(),h="Allow: "+c.AllowedMethods.toString();if(!t.body)if(this.confirmedDialog.signalingState===o.SignalingState.Stable)t.body=this.confirmedDialog.answer;else if(this.confirmedDialog.signalingState===o.SignalingState.Initial||this.confirmedDialog.signalingState===o.SignalingState.HaveRemoteOffer)throw new Error("Response must have a body.");t.statusCode=t.statusCode||200,t.extraHeaders=t.extraHeaders||[],t.extraHeaders=t.extraHeaders.concat(d),t.extraHeaders.push(h),t.extraHeaders.push(p);var l=e.prototype.accept.call(this,t),g=this.confirmedDialog,f=i.__assign({},l,{session:g});return t.body&&this.confirmedDialog.signalingState!==o.SignalingState.Stable&&this.confirmedDialog.signalingStateTransition(t.body),f},t.prototype.progress=function(t){if(void 0===t&&(t={statusCode:180}),!this.progressable)throw new s.TransactionStateError(this.message.method+" not progressable in state "+this.transaction.state+".");if(!this.earlyDialog){var r=this.transaction;if(!(r instanceof a.InviteServerTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");var c=n.Dialog.initialDialogStateForUserAgentServer(this.message,this.toTag,!0);this.earlyDialog=new n.SessionDialog(r,this.core,c)}var u=this.message.getHeaders("record-route").map((function(e){return"Record-Route: "+e})),d="Contact: "+this.core.configuration.contact;t.extraHeaders=t.extraHeaders||[],t.extraHeaders=t.extraHeaders.concat(u),t.extraHeaders.push(d);var p=e.prototype.progress.call(this,t),h=this.earlyDialog,l=i.__assign({},p,{session:h});return t.body&&this.earlyDialog.signalingState!==o.SignalingState.Stable&&this.earlyDialog.signalingStateTransition(t.body),l},t.prototype.redirect=function(t,r){return void 0===r&&(r={statusCode:302}),e.prototype.redirect.call(this,t,r)},t.prototype.reject=function(t){return void 0===t&&(t={statusCode:486}),e.prototype.reject.call(this,t)},t}(r(4).UserAgentServer);t.InviteUserAgentServer=u},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){return e.call(this,n.NonInviteClientTransaction,t,r,i)||this}return i.__extends(t,e),t}(r(3).UserAgentClient);t.MessageUserAgentClient=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){var s=e.call(this,n.NonInviteServerTransaction,t,r,i)||this;return s.core=t,s}return i.__extends(t,e),t}(r(4).UserAgentServer);t.MessageUserAgentServer=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){return e.call(this,n.NonInviteClientTransaction,t,r,i)||this}return i.__extends(t,e),t}(r(3).UserAgentClient);t.PublishUserAgentClient=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){return e.call(this,n.NonInviteServerTransaction,t.userAgentCore,r,i)||this}return i.__extends(t,e),t}(r(4).UserAgentServer);t.ReSubscribeUserAgentServer=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){return e.call(this,n.NonInviteClientTransaction,t,r,i)||this}return i.__extends(t,e),t}(r(3).UserAgentClient);t.RegisterUserAgentClient=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){var s=e.call(this,n.NonInviteServerTransaction,t,r,i)||this;return s.core=t,s}return i.__extends(t,e),t}(r(4).UserAgentServer);t.RegisterUserAgentServer=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(47),s=r(27),o=r(6),a=r(1),c=function(e){function t(t,r,i){var n=this,o=r.getHeader("Event");if(!o)throw new Error("Event undefined");var c=r.getHeader("Expires");if(!c)throw new Error("Expires undefined");return(n=e.call(this,a.NonInviteClientTransaction,t,r,i)||this).delegate=i,n.subscriberId=r.callId+r.fromTag+o,n.subscriptionExpiresRequested=n.subscriptionExpires=Number(c),n.subscriptionEvent=o,n.subscriptionState=s.SubscriptionState.NotifyWait,n.waitNotifyStart(),n}return i.__extends(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this)},t.prototype.onNotify=function(e){var t=e.message.parseHeader("Event").event;if(!t||t!==this.subscriptionEvent)return this.logger.warn("Failed to parse event."),void e.reject({statusCode:489});var r=e.message.parseHeader("Subscription-State");if(!r||!r.state)return this.logger.warn("Failed to parse subscription state."),void e.reject({statusCode:489});var i=r.state;switch(i){case"pending":case"active":case"terminated":break;default:return this.logger.warn("Invalid subscription state "+i),void e.reject({statusCode:489})}if("terminated"!==i&&!e.message.parseHeader("contact"))return this.logger.warn("Failed to parse contact."),void e.reject({statusCode:489});if(this.dialog)throw new Error("Dialog already created. This implementation only supports install of single subscriptions.");switch(this.waitNotifyStop(),this.subscriptionExpires=r.expires?Math.min(this.subscriptionExpires,Math.max(r.expires,0)):this.subscriptionExpires,i){case"pending":this.subscriptionState=s.SubscriptionState.Pending;break;case"active":this.subscriptionState=s.SubscriptionState.Active;break;case"terminated":this.subscriptionState=s.SubscriptionState.Terminated;break;default:throw new Error("Unrecognized state "+i+".")}if(this.subscriptionState!==s.SubscriptionState.Terminated){var o=n.SubscriptionDialog.initialDialogStateForSubscription(this.message,e.message);this.dialog=new n.SubscriptionDialog(this.subscriptionEvent,this.subscriptionExpires,this.subscriptionState,this.core,o)}if(this.delegate&&this.delegate.onNotify){var a=e,c=this.dialog;this.delegate.onNotify({request:a,subscription:c})}else e.accept()},t.prototype.waitNotifyStart=function(){var e=this;this.N||(this.core.subscribers.set(this.subscriberId,this),this.N=setTimeout((function(){return e.timer_N()}),o.Timers.TIMER_N))},t.prototype.waitNotifyStop=function(){this.N&&(this.core.subscribers.delete(this.subscriberId),clearTimeout(this.N),this.N=void 0)},t.prototype.receiveResponse=function(t){if(this.authenticationGuard(t)){if(t.statusCode&&t.statusCode>=200&&t.statusCode<300){var r=t.getHeader("Expires");if(r){var i=Number(r);i>this.subscriptionExpiresRequested&&this.logger.warn("Expires header in a 200-class response to SUBSCRIBE with a higher value than the one in the request"),ithis.subscriptionExpires&&(this.dialog.subscriptionExpires=this.subscriptionExpires)}t.statusCode&&t.statusCode>=300&&t.statusCode<700&&this.waitNotifyStop(),e.prototype.receiveResponse.call(this,t)}},t.prototype.timer_N=function(){this.logger.warn("Timer N expired for SUBSCRIBE user agent client. Timed out waiting for NOTIFY."),this.waitNotifyStop(),this.delegate&&this.delegate.onNotifyTimeout&&this.delegate.onNotifyTimeout()},t}(r(3).UserAgentClient);t.SubscribeUserAgentClient=c},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(1),s=function(e){function t(t,r,i){var s=e.call(this,n.NonInviteServerTransaction,t,r,i)||this;return s.core=t,s}return i.__extends(t,e),t}(r(4).UserAgentServer);t.SubscribeUserAgentServer=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=function(e){function t(t,r){var i=e.call(this)||this;return i.logger=t,i}return i.__extends(t,e),t.prototype.connect=function(e){var t=this;return void 0===e&&(e={}),this.connectPromise(e).then((function(e){e.overrideEvent||t.emit("connected")}))},t.prototype.send=function(e,t){var r=this;return void 0===t&&(t={}),this.sendPromise(e).then((function(e){e.overrideEvent||r.emit("messageSent",e.msg)}))},t.prototype.disconnect=function(e){var t=this;return void 0===e&&(e={}),this.disconnectPromise(e).then((function(e){e.overrideEvent||t.emit("disconnected")}))},t.prototype.afterConnected=function(e){this.isConnected()?e():this.once("connected",e)},t.prototype.waitForConnected=function(){var e=this;return console.warn("DEPRECATION WARNING Transport.waitForConnected(): use afterConnected() instead"),new Promise((function(t){e.afterConnected(t)}))},t}(r(7).EventEmitter);t.Transport=n},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=function(e,t){for(var r,i=[],n=e.split(/\r\n/),s=0;sn)throw new TypeError("Invalid statusCode: "+r);var p,h={statusCode:r,reasonPhrase:s,extraHeaders:a,body:u},l=r.toString();switch(!0){case/^100$/.test(l):p=this.incomingRequest.trying(h).message;break;case/^1[0-9]{2}$/.test(l):p=this.incomingRequest.progress(h).message;break;case/^2[0-9]{2}$/.test(l):p=this.incomingRequest.accept(h).message;break;case/^3[0-9]{2}$/.test(l):p=this.incomingRequest.redirect([],h).message;break;case/^[4-6][0-9]{2}$/.test(l):p=this.incomingRequest.reject(h).message;break;default:throw new Error("Invalid status code "+r)}return d.forEach((function(e){t.emit(e,p,s)})),this},t.prototype.onRequestTimeout=function(){this.emit("failed",void 0,s.C.causes.REQUEST_TIMEOUT)},t.prototype.onTransportError=function(){this.emit("failed",void 0,s.C.causes.CONNECTION_ERROR)},t}(n.EventEmitter);t.ServerContext=u},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(7),s=r(52),o=r(8),a=r(12),c=r(9),u=i.__importStar(r(87)),d=r(97),p=function(e){function t(t,r,i){var n=e.call(this)||this;return n.type=o.TypeStrings.SessionDescriptionHandler,n.options=i||{},n.logger=t,n.observer=r,n.dtmfSender=void 0,n.shouldAcquireMedia=!0,n.CONTENT_TYPE="application/sdp",n.C={DIRECTION:{NULL:null,SENDRECV:"sendrecv",SENDONLY:"sendonly",RECVONLY:"recvonly",INACTIVE:"inactive"}},n.logger.log("SessionDescriptionHandlerOptions: "+JSON.stringify(n.options)),n.direction=n.C.DIRECTION.NULL,n.modifiers=n.options.modifiers||[],Array.isArray(n.modifiers)||(n.modifiers=[n.modifiers]),n.iceGatheringTimeout=!1,n.initPeerConnection(n.options.peerConnectionOptions),n.constraints=n.checkAndDefaultConstraints(n.options.constraints),n}return i.__extends(t,e),t.defaultFactory=function(e,r){return new t(e instanceof s.Session?e.userAgent.getLogger("sip.sessionDescriptionHandler",e.id):e.ua.getLogger("sip.invitecontext.sessionDescriptionHandler",e.id),new d.SessionDescriptionHandlerObserver(e,r),r)},t.prototype.close=function(){this.logger.log("closing PeerConnection"),this.peerConnection&&"closed"!==this.peerConnection.signalingState&&(this.peerConnection.getSenders?this.peerConnection.getSenders().forEach((function(e){e.track&&e.track.stop()})):(this.logger.warn("Using getLocalStreams which is deprecated"),this.peerConnection.getLocalStreams().forEach((function(e){e.getTracks().forEach((function(e){e.stop()}))}))),this.peerConnection.getReceivers?this.peerConnection.getReceivers().forEach((function(e){e.track&&e.track.stop()})):(this.logger.warn("Using getRemoteStreams which is deprecated"),this.peerConnection.getRemoteStreams().forEach((function(e){e.getTracks().forEach((function(e){e.stop()}))}))),this.resetIceGatheringComplete(),this.peerConnection.close())},t.prototype.getDescription=function(e,t){var r=this;void 0===e&&(e={}),void 0===t&&(t=[]),e.peerConnectionOptions&&this.initPeerConnection(e.peerConnectionOptions);var i=Object.assign({},this.constraints,e.constraints);return i=this.checkAndDefaultConstraints(i),JSON.stringify(i)!==JSON.stringify(this.constraints)&&(this.constraints=i,this.shouldAcquireMedia=!0),Array.isArray(t)||(t=[t]),t=t.concat(this.modifiers),Promise.resolve().then((function(){if(r.shouldAcquireMedia)return r.acquire(r.constraints).then((function(){r.shouldAcquireMedia=!1}))})).then((function(){return r.createOfferOrAnswer(e.RTCOfferOptions,t)})).then((function(e){if(void 0===e.sdp)throw new a.Exceptions.SessionDescriptionHandlerError("getDescription",void 0,"SDP undefined");return r.emit("getDescription",e),{body:e.sdp,contentType:r.CONTENT_TYPE}}))},t.prototype.hasDescription=function(e){return e===this.CONTENT_TYPE},t.prototype.holdModifier=function(e){return e.sdp?(/a=(sendrecv|sendonly|recvonly|inactive)/.test(e.sdp)?(e.sdp=e.sdp.replace(/a=sendrecv\r\n/g,"a=sendonly\r\n"),e.sdp=e.sdp.replace(/a=recvonly\r\n/g,"a=inactive\r\n")):e.sdp=e.sdp.replace(/(m=[^\r]*\r\n)/g,"$1a=sendonly\r\n"),Promise.resolve(e)):Promise.resolve(e)},t.prototype.setDescription=function(e,t,r){var i=this;void 0===t&&(t={}),void 0===r&&(r=[]),t.peerConnectionOptions&&this.initPeerConnection(t.peerConnectionOptions),Array.isArray(r)||(r=[r]),r=r.concat(this.modifiers);var n={type:this.hasOffer("local")?"answer":"offer",sdp:e};return Promise.resolve().then((function(){if(i.shouldAcquireMedia&&i.options.alwaysAcquireMediaFirst)return i.acquire(i.constraints).then((function(){i.shouldAcquireMedia=!1}))})).then((function(){return c.Utils.reducePromises(r,n)})).catch((function(e){if(e.type===o.TypeStrings.SessionDescriptionHandlerError)throw e;var t=new a.Exceptions.SessionDescriptionHandlerError("setDescription",e,"The modifiers did not resolve successfully");throw i.logger.error(t.message),i.emit("peerConnection-setRemoteDescriptionFailed",t),t})).then((function(e){return i.emit("setDescription",e),i.peerConnection.setRemoteDescription(e)})).catch((function(n){if(n.type===o.TypeStrings.SessionDescriptionHandlerError)throw n;if(/^m=video.+$/gm.test(e)&&!t.disableAudioFallback)return t.disableAudioFallback=!0,i.setDescription(e,t,[u.stripVideo].concat(r));var s=new a.Exceptions.SessionDescriptionHandlerError("setDescription",n);throw s.error&&i.logger.error(s.error),i.emit("peerConnection-setRemoteDescriptionFailed",s),s})).then((function(){i.peerConnection.getReceivers?i.emit("setRemoteDescription",i.peerConnection.getReceivers()):i.emit("setRemoteDescription",i.peerConnection.getRemoteStreams()),i.emit("confirmed",i)}))},t.prototype.sendDtmf=function(e,t){if(void 0===t&&(t={}),!this.dtmfSender&&this.hasBrowserGetSenderSupport()){var r=this.peerConnection.getSenders();r.length>0&&(this.dtmfSender=r[0].dtmf)}if(!this.dtmfSender&&this.hasBrowserTrackSupport()){var i=this.peerConnection.getLocalStreams();if(i.length>0){var n=i[0].getAudioTracks();n.length>0&&(this.dtmfSender=this.peerConnection.createDTMFSender(n[0]))}}if(!this.dtmfSender)return!1;try{this.dtmfSender.insertDTMF(e,t.duration,t.interToneGap)}catch(e){if("InvalidStateError"===e.type||"InvalidCharacterError"===e.type)return this.logger.error(e),!1;throw e}return this.logger.log("DTMF sent via RTP: "+e.toString()),!0},t.prototype.getDirection=function(){return this.direction},t.prototype.on=function(t,r){return e.prototype.on.call(this,t,r)},t.prototype.getMediaStream=function(e){return navigator.mediaDevices.getUserMedia(e)},t.prototype.createOfferOrAnswer=function(e,t){var r=this;void 0===e&&(e={}),void 0===t&&(t=[]);var i=this.hasOffer("remote")?"createAnswer":"createOffer",n=this.peerConnection;return this.logger.log(i),(this.hasOffer("remote")?n.createAnswer:n.createOffer).apply(n,e).catch((function(e){if(e.type===o.TypeStrings.SessionDescriptionHandlerError)throw e;var t=new a.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer",e,"peerConnection-"+i+"Failed");throw r.emit("peerConnection-"+i+"Failed",t),t})).then((function(e){return c.Utils.reducePromises(t,r.createRTCSessionDescriptionInit(e))})).then((function(e){return r.resetIceGatheringComplete(),r.logger.log("Setting local sdp."),r.logger.log("sdp is "+e.sdp||!1),n.setLocalDescription(e)})).catch((function(e){if(e.type===o.TypeStrings.SessionDescriptionHandlerError)throw e;var t=new a.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer",e,"peerConnection-SetLocalDescriptionFailed");throw r.emit("peerConnection-SetLocalDescriptionFailed",t),t})).then((function(){return r.waitForIceGatheringComplete()})).then((function(){if(!r.peerConnection.localDescription)throw new a.Exceptions.SessionDescriptionHandlerError("Missing local description");var e=r.createRTCSessionDescriptionInit(r.peerConnection.localDescription);return c.Utils.reducePromises(t,e)})).then((function(e){return r.setDirection(e.sdp||""),e})).catch((function(e){if(e.type===o.TypeStrings.SessionDescriptionHandlerError)throw e;var t=new a.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer",e);throw r.logger.error(t.toString()),t}))},t.prototype.createRTCSessionDescriptionInit=function(e){return{type:e.type,sdp:e.sdp}},t.prototype.addDefaultIceCheckingTimeout=function(e){return void 0===e.iceCheckingTimeout&&(e.iceCheckingTimeout=5e3),e},t.prototype.addDefaultIceServers=function(e){return e.iceServers||(e.iceServers=[{urls:"stun:stun.l.google.com:19302"}]),e},t.prototype.checkAndDefaultConstraints=function(e){var t={audio:!0,video:!this.options.alwaysAcquireMediaFirst};return e=e||t,0===Object.keys(e).length&&e.constructor===Object?t:e},t.prototype.hasBrowserTrackSupport=function(){return Boolean(this.peerConnection.addTrack)},t.prototype.hasBrowserGetSenderSupport=function(){return Boolean(this.peerConnection.getSenders)},t.prototype.initPeerConnection=function(e){var t=this;void 0===e&&(e={}),(e=this.addDefaultIceCheckingTimeout(e)).rtcConfiguration=e.rtcConfiguration||{},e.rtcConfiguration=this.addDefaultIceServers(e.rtcConfiguration),this.logger.log("initPeerConnection"),this.peerConnection&&(this.logger.log("Already have a peer connection for this session. Tearing down."),this.resetIceGatheringComplete(),this.peerConnection.close()),this.peerConnection=new RTCPeerConnection(e.rtcConfiguration),this.logger.log("New peer connection created"),"ontrack"in this.peerConnection?this.peerConnection.addEventListener("track",(function(e){t.logger.log("track added"),t.observer.trackAdded(),t.emit("addTrack",e)})):(this.logger.warn("Using onaddstream which is deprecated"),this.peerConnection.onaddstream=function(e){t.logger.log("stream added"),t.emit("addStream",e)}),this.peerConnection.onicecandidate=function(e){t.emit("iceCandidate",e),e.candidate?t.logger.log("ICE candidate received: "+(null===e.candidate.candidate?null:e.candidate.candidate.trim())):null===e.candidate&&(t.logger.log("ICE candidate gathering complete"),t.triggerIceGatheringComplete())},this.peerConnection.onicegatheringstatechange=function(){switch(t.logger.log("RTCIceGatheringState changed: "+t.peerConnection.iceGatheringState),t.peerConnection.iceGatheringState){case"gathering":t.emit("iceGathering",t),!t.iceGatheringTimer&&e.iceCheckingTimeout&&(t.iceGatheringTimeout=!1,t.iceGatheringTimer=setTimeout((function(){t.logger.log("RTCIceChecking Timeout Triggered after "+e.iceCheckingTimeout+" milliseconds"),t.iceGatheringTimeout=!0,t.triggerIceGatheringComplete()}),e.iceCheckingTimeout));break;case"complete":t.triggerIceGatheringComplete()}},this.peerConnection.oniceconnectionstatechange=function(){var e;switch(t.peerConnection.iceConnectionState){case"new":e="iceConnection";break;case"checking":e="iceConnectionChecking";break;case"connected":e="iceConnectionConnected";break;case"completed":e="iceConnectionCompleted";break;case"failed":e="iceConnectionFailed";break;case"disconnected":e="iceConnectionDisconnected";break;case"closed":e="iceConnectionClosed";break;default:return void t.logger.warn("Unknown iceConnection state: "+t.peerConnection.iceConnectionState)}t.logger.log("ICE Connection State changed to "+e),t.emit(e,t)}},t.prototype.acquire=function(e){var t=this;return e=this.checkAndDefaultConstraints(e),new Promise((function(r,i){t.logger.log("acquiring local media"),t.emit("userMediaRequest",e),e.audio||e.video?t.getMediaStream(e).then((function(e){t.observer.trackAdded(),t.emit("userMedia",e),r(e)})).catch((function(e){t.emit("userMediaFailed",e),i(e)})):r([])})).catch((function(e){if(e.type===o.TypeStrings.SessionDescriptionHandlerError)throw e;var r=new a.Exceptions.SessionDescriptionHandlerError("acquire",e,"unable to acquire streams");throw t.logger.error(r.message),r.error&&t.logger.error(r.error),r})).then((function(e){return t.logger.log("acquired local media streams"),t.peerConnection.removeTrack&&t.peerConnection.getSenders().forEach((function(e){t.peerConnection.removeTrack(e)})),e})).catch((function(e){if(e.type===o.TypeStrings.SessionDescriptionHandlerError)throw e;var r=new a.Exceptions.SessionDescriptionHandlerError("acquire",e,"error removing streams");throw t.logger.error(r.message),r.error&&t.logger.error(r.error),r})).then((function(e){return[].concat(e).forEach((function(e){t.peerConnection.addTrack?e.getTracks().forEach((function(r){t.peerConnection.addTrack(r,e)})):t.peerConnection.addStream(e)})),Promise.resolve()})).catch((function(e){if(e.type===o.TypeStrings.SessionDescriptionHandlerError)throw e;var r=new a.Exceptions.SessionDescriptionHandlerError("acquire",e,"error adding stream");throw t.logger.error(r.message),r.error&&t.logger.error(r.error),r}))},t.prototype.hasOffer=function(e){var t="have-"+e+"-offer";return this.peerConnection.signalingState===t},t.prototype.isIceGatheringComplete=function(){return"complete"===this.peerConnection.iceGatheringState||this.iceGatheringTimeout},t.prototype.resetIceGatheringComplete=function(){this.iceGatheringTimeout=!1,this.logger.log("resetIceGatheringComplete"),this.iceGatheringTimer&&(clearTimeout(this.iceGatheringTimer),this.iceGatheringTimer=void 0),this.iceGatheringDeferred&&(this.iceGatheringDeferred.reject(),this.iceGatheringDeferred=void 0)},t.prototype.setDirection=function(e){var t=e.match(/a=(sendrecv|sendonly|recvonly|inactive)/);if(null===t)return this.direction=this.C.DIRECTION.NULL,void this.observer.directionChanged();var r=t[1];switch(r){case this.C.DIRECTION.SENDRECV:case this.C.DIRECTION.SENDONLY:case this.C.DIRECTION.RECVONLY:case this.C.DIRECTION.INACTIVE:this.direction=r;break;default:this.direction=this.C.DIRECTION.NULL}this.observer.directionChanged()},t.prototype.triggerIceGatheringComplete=function(){this.isIceGatheringComplete()&&(this.emit("iceGatheringComplete",this),this.iceGatheringTimer&&(clearTimeout(this.iceGatheringTimer),this.iceGatheringTimer=void 0),this.iceGatheringDeferred&&(this.iceGatheringDeferred.resolve(),this.iceGatheringDeferred=void 0))},t.prototype.waitForIceGatheringComplete=function(){return this.logger.log("waitForIceGatheringComplete"),this.isIceGatheringComplete()?(this.logger.log("ICE is already complete. Return resolved."),Promise.resolve()):(this.iceGatheringDeferred||(this.iceGatheringDeferred=c.Utils.defer()),this.logger.log("ICE is not complete. Returning promise"),this.iceGatheringDeferred?this.iceGatheringDeferred.promise:Promise.resolve())},t}(n.EventEmitter);t.SessionDescriptionHandler=p},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e){this.incomingInfoRequest=e}return Object.defineProperty(e.prototype,"request",{get:function(){return this.incomingInfoRequest.message},enumerable:!0,configurable:!0}),e.prototype.accept=function(e){return this.incomingInfoRequest.accept(e),Promise.resolve()},e.prototype.reject=function(e){return this.incomingInfoRequest.reject(e),Promise.resolve()},e}();t.Info=i},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(5),n=function(){function e(e,t){this.incomingReferRequest=e,this.session=t}return Object.defineProperty(e.prototype,"referTo",{get:function(){var e=this.incomingReferRequest.message.parseHeader("refer-to");if(!(e instanceof i.NameAddrHeader))throw new Error("Failed to parse Refer-To header.");return e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"referredBy",{get:function(){return this.incomingReferRequest.message.getHeader("referred-by")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"replaces",{get:function(){return this.referTo.uri.getHeader("replaces")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"request",{get:function(){return this.incomingReferRequest.message},enumerable:!0,configurable:!0}),e.prototype.accept=function(e){return void 0===e&&(e={statusCode:202}),this.incomingReferRequest.accept(e),Promise.resolve()},e.prototype.reject=function(e){return this.incomingReferRequest.reject(e),Promise.resolve()},e.prototype.makeInviter=function(e){if(this.inviter)return this.inviter;var t=this.referTo.uri.clone();t.clearHeaders();var r=((e=e||{}).extraHeaders||[]).slice(),i=this.replaces;i&&r.push("Replaces: "+decodeURIComponent(i));var n=this.referredBy;return n&&r.push("Referred-By: "+n),e.extraHeaders=r,this.inviter=this.session.userAgent.makeInviter(t,e),this.inviter.referred=this.session,this.session.referral=this.inviter,this.inviter},e}();t.Referral=n},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i,n=r(0),s=r(5),o=r(8),a=r(12),c=r(9);!function(e){e[e.STATUS_CONNECTING=0]="STATUS_CONNECTING",e[e.STATUS_OPEN=1]="STATUS_OPEN",e[e.STATUS_CLOSING=2]="STATUS_CLOSING",e[e.STATUS_CLOSED=3]="STATUS_CLOSED"}(i=t.TransportStatus||(t.TransportStatus={}));var u=function(e){function t(t,r){void 0===r&&(r={});var n=e.call(this,t,r)||this;return n.type=o.TypeStrings.Transport,n.reconnectionAttempts=0,n.status=i.STATUS_CONNECTING,n.configuration=n.loadConfig(r),n.server=n.configuration.wsServers[0],n}return n.__extends(t,e),t.prototype.isConnected=function(){return this.status===i.STATUS_OPEN},t.prototype.sendPromise=function(e,t){if(void 0===t&&(t={}),!this.statusAssert(i.STATUS_OPEN,t.force))return this.onError("unable to send message - WebSocket not open"),Promise.reject();var r=e.toString();return this.ws?(!0===this.configuration.traceSip&&this.logger.log("sending WebSocket message:\n\n"+r+"\n"),this.ws.send(r),Promise.resolve({msg:r})):(this.onError("unable to send message - WebSocket does not exist"),Promise.reject())},t.prototype.disconnectPromise=function(e){var t=this;return void 0===e&&(e={}),this.disconnectionPromise?this.disconnectionPromise:(e.code=e.code||1e3,this.statusTransition(i.STATUS_CLOSING,e.force)?(this.emit("disconnecting"),this.disconnectionPromise=new Promise((function(r,i){t.disconnectDeferredResolve=r,t.reconnectTimer&&(clearTimeout(t.reconnectTimer),t.reconnectTimer=void 0),t.ws?(t.stopSendingKeepAlives(),t.logger.log("closing WebSocket "+t.server.wsUri),t.ws.close(e.code,e.reason)):i("Attempted to disconnect but the websocket doesn't exist")})),this.disconnectionPromise):this.status===i.STATUS_CLOSED?Promise.resolve({overrideEvent:!0}):this.connectionPromise?this.connectionPromise.then((function(){return Promise.reject("The websocket did not disconnect")})).catch((function(){return Promise.resolve({overrideEvent:!0})})):Promise.reject("The websocket did not disconnect"))},t.prototype.connectPromise=function(e){var t=this;return void 0===e&&(e={}),this.status!==i.STATUS_CLOSING||e.force?this.connectionPromise?this.connectionPromise:(this.server=this.server||this.getNextWsServer(e.force),this.connectionPromise=new Promise((function(r,n){if((t.status===i.STATUS_OPEN||t.status===i.STATUS_CLOSING)&&!e.force)return t.logger.warn("WebSocket "+t.server.wsUri+" is already connected"),void n("Failed status check - attempted to open a connection but already open/closing");t.connectDeferredResolve=r,t.connectDeferredReject=n,t.status=i.STATUS_CONNECTING,t.emit("connecting"),t.logger.log("connecting to WebSocket "+t.server.wsUri),t.disposeWs();try{t.ws=new WebSocket(t.server.wsUri,"sip")}catch(e){return t.ws=null,t.statusTransition(i.STATUS_CLOSED,!0),t.onError("error connecting to WebSocket "+t.server.wsUri+":"+e),n("Failed to create a websocket"),t.connectDeferredResolve=void 0,void(t.connectDeferredReject=void 0)}if(!t.ws)return n("Unexpected instance websocket not set"),t.connectDeferredResolve=void 0,void(t.connectDeferredReject=void 0);t.connectionTimeout=setTimeout((function(){t.statusTransition(i.STATUS_CLOSED),t.logger.warn("took too long to connect - exceeded time set in configuration.connectionTimeout: "+t.configuration.connectionTimeout+"s"),t.emit("disconnected",{code:1e3}),t.connectionPromise=void 0,n("Connection timeout"),t.connectDeferredResolve=void 0,t.connectDeferredReject=void 0;var e=t.ws;t.disposeWs(),e.close(1e3)}),1e3*t.configuration.connectionTimeout),t.boundOnOpen=t.onOpen.bind(t),t.boundOnMessage=t.onMessage.bind(t),t.boundOnClose=t.onClose.bind(t),t.boundOnError=t.onWebsocketError.bind(t),t.ws.addEventListener("open",t.boundOnOpen),t.ws.addEventListener("message",t.boundOnMessage),t.ws.addEventListener("close",t.boundOnClose),t.ws.addEventListener("error",t.boundOnError)})),this.connectionPromise):Promise.reject("WebSocket "+this.server.wsUri+" is closing")},t.prototype.onMessage=function(e){var t,r=e.data;if(/^(\r\n)+$/.test(r))return this.clearKeepAliveTimeout(),void(!0===this.configuration.traceSip&&this.logger.log("received WebSocket message with CRLF Keep Alive response"));if(r){if("string"!=typeof r){try{t=String.fromCharCode.apply(null,new Uint8Array(r))}catch(e){return void this.logger.warn("received WebSocket binary message failed to be converted into string, message discarded")}!0===this.configuration.traceSip&&this.logger.log("received WebSocket binary message:\n\n"+r+"\n")}else!0===this.configuration.traceSip&&this.logger.log("received WebSocket text message:\n\n"+r+"\n"),t=r;this.emit("message",t)}else this.logger.warn("received empty message, message discarded")},t.prototype.onOpen=function(){if(this.status===i.STATUS_CLOSED){var e=this.ws;return this.disposeWs(),void e.close(1e3)}this.statusTransition(i.STATUS_OPEN,!0),this.emit("connected"),this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=void 0),this.logger.log("WebSocket "+this.server.wsUri+" connected"),void 0!==this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.reconnectionAttempts=0,this.disconnectionPromise=void 0,this.disconnectDeferredResolve=void 0,this.startSendingKeepAlives(),this.connectDeferredResolve?(this.connectDeferredResolve({overrideEvent:!0}),this.connectDeferredResolve=void 0,this.connectDeferredReject=void 0):this.logger.warn("Unexpected websocket.onOpen with no connectDeferredResolve")},t.prototype.onClose=function(e){if(this.logger.log("WebSocket disconnected (code: "+e.code+(e.reason?"| reason: "+e.reason:"")+")"),this.status!==i.STATUS_CLOSING&&(this.logger.warn("WebSocket closed without SIP.js requesting it"),this.emit("transportError")),this.stopSendingKeepAlives(),this.connectionTimeout&&clearTimeout(this.connectionTimeout),this.connectDeferredReject&&this.connectDeferredReject("Websocket Closed"),this.connectionTimeout=void 0,this.connectionPromise=void 0,this.connectDeferredResolve=void 0,this.connectDeferredReject=void 0,this.disconnectDeferredResolve)return this.disconnectDeferredResolve({overrideEvent:!0}),this.statusTransition(i.STATUS_CLOSED),void(this.disconnectDeferredResolve=void 0);this.statusTransition(i.STATUS_CLOSED,!0),this.emit("disconnected",{code:e.code,reason:e.reason}),this.disposeWs(),this.reconnect()},t.prototype.disposeWs=function(){this.ws&&(this.ws.removeEventListener("open",this.boundOnOpen),this.ws.removeEventListener("message",this.boundOnMessage),this.ws.removeEventListener("close",this.boundOnClose),this.ws.removeEventListener("error",this.boundOnError),this.ws=void 0)},t.prototype.onError=function(e){this.logger.warn("Transport error: "+e),this.emit("transportError")},t.prototype.onWebsocketError=function(){this.onError("The Websocket had an error")},t.prototype.reconnect=function(){var e=this;if(this.reconnectionAttempts>0&&this.logger.log("Reconnection attempt "+this.reconnectionAttempts+" failed"),this.noAvailableServers())return this.logger.warn("attempted to get next ws server but there are no available ws servers left"),this.logger.warn("no available ws servers left - going to closed state"),this.statusTransition(i.STATUS_CLOSED,!0),this.emit("closed"),void this.resetServerErrorStatus();this.isConnected()&&(this.logger.warn("attempted to reconnect while connected - forcing disconnect"),this.disconnect({force:!0})),this.reconnectionAttempts+=1,this.reconnectionAttempts>this.configuration.maxReconnectionAttempts?(this.logger.warn("maximum reconnection attempts for WebSocket "+this.server.wsUri),this.logger.log("transport "+this.server.wsUri+" failed | connection state set to 'error'"),this.server.isError=!0,this.emit("transportError"),this.noAvailableServers()||(this.server=this.getNextWsServer()),this.reconnectionAttempts=0,this.reconnect()):(this.logger.log("trying to reconnect to WebSocket "+this.server.wsUri+" (reconnection attempt "+this.reconnectionAttempts+")"),this.reconnectTimer=setTimeout((function(){e.connect(),e.reconnectTimer=void 0}),1===this.reconnectionAttempts?0:1e3*this.configuration.reconnectionTimeout))},t.prototype.resetServerErrorStatus=function(){for(var e=0,t=this.configuration.wsServers;et[0].weight?t=[n]:n.weight===t[0].weight&&t.push(n))}return t[Math.floor(Math.random()*t.length)]},t.prototype.noAvailableServers=function(){for(var e=0,t=this.configuration.wsServers;e",weight:0,wsUri:"wss://edge.sip.onsip.com",isError:!1}],connectionTimeout:5,maxReconnectionAttempts:3,reconnectionTimeout:4,keepAliveInterval:0,keepAliveDebounce:10,traceSip:!1},r=this.getConfigurationCheck();for(var i in r.mandatory){if(!e.hasOwnProperty(i))throw new a.Exceptions.ConfigurationError(i);var n=e[i];if(void 0===(s=r.mandatory[i](n)))throw new a.Exceptions.ConfigurationError(i,n);t[i]=s}for(var i in r.optional)if(e.hasOwnProperty(i)){var s;if((n=e[i])instanceof Array&&0===n.length||null===n||""===n||void 0===n||"number"==typeof n&&isNaN(n))continue;if(void 0===(s=r.optional[i](n)))throw new a.Exceptions.ConfigurationError(i,n);t[i]=s}var o={};for(var i in t)t.hasOwnProperty(i)&&(o[i]={value:t[i]});var c=Object.defineProperties({},o);for(var i in this.logger.log("configuration parameters after validation:"),t)t.hasOwnProperty(i)&&this.logger.log("\xb7 "+i+": "+JSON.stringify(t[i]));return c},t.prototype.getConfigurationCheck=function(){return{mandatory:{},optional:{wsServers:function(e){if("string"==typeof e)e=[{wsUri:e}];else{if(!(e instanceof Array))return;for(var t=0;t",n.weight||(n.weight=0),n.isError=!1,n.scheme=o.scheme.toUpperCase()}return e},keepAliveInterval:function(e){if(c.Utils.isDecimal(e)){var t=Number(e);if(t>0)return t}},keepAliveDebounce:function(e){if(c.Utils.isDecimal(e)){var t=Number(e);if(t>0)return t}},traceSip:function(e){if("boolean"==typeof e)return e},connectionTimeout:function(e){if(c.Utils.isDecimal(e)){var t=Number(e);if(t>0)return t}},maxReconnectionAttempts:function(e){if(c.Utils.isDecimal(e)){var t=Number(e);if(t>=0)return t}},reconnectionTimeout:function(e){if(c.Utils.isDecimal(e)){var t=Number(e);if(t>0)return t}}}}},t.C=i,t}(s.Transport);t.Transport=u},,function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(51),s=r(11),o=r(5),a=r(8),c=r(12),u=r(90),d=function(e){function t(t,r,i,n){void 0===n&&(n={});var o=this;if(void 0===t||void 0===r||void 0===i)throw new TypeError("Not enough arguments");return(o=e.call(this,t,s.C.REFER,r.remoteIdentity.uri.toString(),n)||this).type=a.TypeStrings.ReferClientContext,o.options=n,o.extraHeaders=(o.options.extraHeaders||[]).slice(),o.applicant=r,o.target=o.initReferTo(i),o.ua&&o.extraHeaders.push("Referred-By: <"+o.ua.configuration.uri+">"),o.extraHeaders.push("Contact: "+r.contact),o.extraHeaders.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),o.extraHeaders.push("Refer-To: "+o.target),o.errorListener=o.onTransportError.bind(o),t.transport&&t.transport.on("transportError",o.errorListener),o}return i.__extends(t,e),t.prototype.refer=function(e){var t=this;void 0===e&&(e={});var r=(this.extraHeaders||[]).slice();return e.extraHeaders&&r.concat(e.extraHeaders),this.applicant.sendRequest(s.C.REFER,{extraHeaders:this.extraHeaders,receiveResponse:function(r){var i=r&&r.statusCode?r.statusCode.toString():"";/^1[0-9]{2}$/.test(i)?t.emit("referRequestProgress",t):/^2[0-9]{2}$/.test(i)?t.emit("referRequestAccepted",t):/^[4-6][0-9]{2}$/.test(i)&&t.emit("referRequestRejected",t),e.receiveResponse&&e.receiveResponse(r)}}),this},t.prototype.receiveNotify=function(e){var t=e.message.hasHeader("Content-Type")?e.message.getHeader("Content-Type"):void 0;if(t&&-1!==t.search(/^message\/sipfrag/)){var r=o.Grammar.parse(e.message.body,"sipfrag");if(-1===r)return void e.reject({statusCode:489,reasonPhrase:"Bad Event"});switch(!0){case/^1[0-9]{2}$/.test(r.status_code):this.emit("referProgress",this);break;case/^2[0-9]{2}$/.test(r.status_code):this.emit("referAccepted",this),!this.options.activeAfterTransfer&&this.applicant.terminate&&this.applicant.terminate();break;default:this.emit("referRejected",this)}return e.accept(),void this.emit("notify",e.message)}e.reject({statusCode:489,reasonPhrase:"Bad Event"})},t.prototype.initReferTo=function(e){var t;if("string"==typeof e){var r=o.Grammar.parse(e,"Refer_To");t=r&&r.uri?r.uri:e;var i=this.ua.normalizeTarget(e);if(!i)throw new TypeError("Invalid target: "+e);t=i}else{if(!e.session)throw new Error("Session undefined.");var n=e.remoteIdentity.friendlyName,s=e.session.remoteTarget.toString(),a=e.session.callId,c=e.session.remoteTag,u=e.session.localTag;t='"'+n+'" <'+s+"?Replaces="+encodeURIComponent(a+";to-tag="+c+";from-tag="+u)+">"}return t},t}(n.ClientContext);t.ReferClientContext=d;var p=function(e){function t(t,r,i){var n=e.call(this,t,r)||this;return n.session=i,n.type=a.TypeStrings.ReferServerContext,n.ua=t,n.status=a.SessionStatus.STATUS_INVITE_RECEIVED,n.fromTag=n.request.fromTag,n.id=n.request.callId+n.fromTag,n.contact=n.ua.contact.toString(),n.logger=t.getLogger("sip.referservercontext",n.id),n.cseq=Math.floor(1e4*Math.random()),n.callId=n.request.callId,n.fromUri=n.request.to.uri,n.fromTag=n.request.to.parameters.tag,n.remoteTarget=n.request.headers.Contact[0].parsed.uri,n.toUri=n.request.from.uri,n.toTag=n.request.fromTag,n.routeSet=n.request.getHeaders("record-route"),n.request.hasHeader("refer-to")?(n.referTo=n.request.parseHeader("refer-to"),n.referredSession=n.ua.findSession(n.request),n.request.hasHeader("referred-by")&&(n.referredBy=n.request.getHeader("referred-by")),n.referTo.uri.hasHeader("replaces")&&(n.replaces=n.referTo.uri.getHeader("replaces")),n.errorListener=n.onTransportError.bind(n),t.transport&&t.transport.on("transportError",n.errorListener),n.status=a.SessionStatus.STATUS_WAITING_FOR_ANSWER,n):(n.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting refer."),n.reject(),n)}return i.__extends(t,e),t.prototype.progress=function(){if(this.status!==a.SessionStatus.STATUS_WAITING_FOR_ANSWER)throw new c.Exceptions.InvalidStateError(this.status);this.incomingRequest.trying()},t.prototype.reject=function(t){if(void 0===t&&(t={}),this.status===a.SessionStatus.STATUS_TERMINATED)throw new c.Exceptions.InvalidStateError(this.status);this.logger.log("Rejecting refer"),this.status=a.SessionStatus.STATUS_TERMINATED,e.prototype.reject.call(this,t),this.emit("referRequestRejected",this)},t.prototype.accept=function(e,t){var r=this;if(void 0===e&&(e={}),this.status!==a.SessionStatus.STATUS_WAITING_FOR_ANSWER)throw new c.Exceptions.InvalidStateError(this.status);if(this.status=a.SessionStatus.STATUS_ANSWERED,this.incomingRequest.accept({statusCode:202,reasonPhrase:"Accepted"}),this.emit("referRequestAccepted",this),e.followRefer){this.logger.log("Accepted refer, attempting to automatically follow it");var i=this.referTo.uri;if(!i.scheme||!i.scheme.match("^sips?$"))return this.logger.error("SIP.js can only automatically follow SIP refer target"),void this.reject();var n=e.inviteOptions||{},s=(n.extraHeaders||[]).slice();if(this.replaces&&s.push("Replaces: "+decodeURIComponent(this.replaces)),this.referredBy&&s.push("Referred-By: "+this.referredBy),n.extraHeaders=s,i.clearHeaders(),this.targetSession=this.ua.invite(i.toString(),n,t),this.emit("referInviteSent",this),this.targetSession){this.targetSession.once("progress",(function(e){var t=e.statusCode||100,i=e.reasonPhrase;r.sendNotify(("SIP/2.0 "+t+" "+i).trim()),r.emit("referProgress",r),r.referredSession&&r.referredSession.emit("referProgress",r)})),this.targetSession.once("accepted",(function(){r.logger.log("Successfully followed the refer"),r.sendNotify("SIP/2.0 200 OK"),r.emit("referAccepted",r),r.referredSession&&r.referredSession.emit("referAccepted",r)}));var o=function(e){if(r.status!==a.SessionStatus.STATUS_TERMINATED){if(r.logger.log("Refer was not successful. Resuming session"),e&&429===e.statusCode)return r.logger.log("Alerting referrer that identity is required."),void r.sendNotify("SIP/2.0 429 Provide Referrer Identity");r.sendNotify("SIP/2.0 603 Declined"),r.status=a.SessionStatus.STATUS_TERMINATED,r.emit("referRejected",r),r.referredSession&&r.referredSession.emit("referRejected")}};this.targetSession.once("rejected",o),this.targetSession.once("failed",o)}}else this.logger.log("Accepted refer, but did not automatically follow it"),this.sendNotify("SIP/2.0 200 OK"),this.emit("referAccepted",this),this.referredSession&&this.referredSession.emit("referAccepted",this)},t.prototype.sendNotify=function(e){if(this.status!==a.SessionStatus.STATUS_ANSWERED)throw new c.Exceptions.InvalidStateError(this.status);if(-1===o.Grammar.parse(e,"sipfrag"))throw new Error("sipfrag body is required to send notify for refer");var t={contentDisposition:"render",contentType:"message/sipfrag",content:e};if(this.session)this.session.notify(void 0,{extraHeaders:["Event: refer","Subscription-State: terminated"],body:t});else{var r=this.ua.userAgentCore.makeOutgoingRequestMessage(s.C.NOTIFY,this.remoteTarget,this.fromUri,this.toUri,{cseq:this.cseq+=1,callId:this.callId,fromTag:this.fromTag,toTag:this.toTag,routeSet:this.routeSet},["Event: refer","Subscription-State: terminated","Content-Type: message/sipfrag"],t),i=this.ua.transport;if(!i)throw new Error("Transport undefined.");var n={loggerFactory:this.ua.getLoggerFactory()};new o.NonInviteClientTransaction(r,i,n)}},t.prototype.on=function(t,r){return e.prototype.on.call(this,t,r)},t}(u.ServerContext);t.ReferServerContext=p},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(8),n=function(){function e(e,t){this.type=i.TypeStrings.SessionDescriptionHandlerObserver,this.session=e,this.options=t}return e.prototype.trackAdded=function(){this.session.emit("trackAdded")},e.prototype.directionChanged=function(){this.session.emit("directionChanged")},e}();t.SessionDescriptionHandlerObserver=n},,,function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(51),s=r(11),o=r(5),a=r(8),c=r(12),u=r(9),d=function(e){function t(t,r,i,n){void 0===n&&(n={});var o=this;if(n.extraHeaders=(n.extraHeaders||[]).slice(),n.contentType=n.contentType||"text/plain","number"!=typeof n.expires||n.expires%1!=0?n.expires=3600:n.expires=Number(n.expires),"boolean"!=typeof n.unpublishOnClose&&(n.unpublishOnClose=!0),null==r||""===r)throw new c.Exceptions.MethodParameterError("Publish","Target",r);if(void 0===(r=t.normalizeTarget(r)))throw new c.Exceptions.MethodParameterError("Publish","Target",r);if((o=e.call(this,t,s.C.PUBLISH,r,n)||this).type=a.TypeStrings.PublishContext,o.options=n,o.target=r,null==i||""===i)throw new c.Exceptions.MethodParameterError("Publish","Event",i);return o.event=i,o.logger=t.getLogger("sip.publish"),o.pubRequestExpires=o.options.expires,o}return i.__extends(t,e),t.prototype.publish=function(e){this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.options.body=e,this.pubRequestBody=this.options.body,0===this.pubRequestExpires&&(this.pubRequestExpires=this.options.expires,this.pubRequestEtag=void 0),this.ua.publishers[this.target.toString()+":"+this.event]||(this.ua.publishers[this.target.toString()+":"+this.event]=this),this.sendPublishRequest()},t.prototype.unpublish=function(){this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,this.pubRequestExpires=0,void 0!==this.pubRequestEtag&&this.sendPublishRequest()},t.prototype.close=function(){this.options.unpublishOnClose?this.unpublish():(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,this.pubRequestExpires=0,this.pubRequestEtag=void 0),this.ua.publishers[this.target.toString()+":"+this.event]&&delete this.ua.publishers[this.target.toString()+":"+this.event]},t.prototype.onRequestTimeout=function(){e.prototype.onRequestTimeout.call(this),this.emit("unpublished",void 0,s.C.causes.REQUEST_TIMEOUT)},t.prototype.onTransportError=function(){e.prototype.onTransportError.call(this),this.emit("unpublished",void 0,s.C.causes.CONNECTION_ERROR)},t.prototype.receiveResponse=function(e){var t=this,r=e.statusCode||0,i=u.Utils.getReasonPhrase(r);switch(!0){case/^1[0-9]{2}$/.test(r.toString()):this.emit("progress",e,i);break;case/^2[0-9]{2}$/.test(r.toString()):if(e.hasHeader("SIP-ETag")?this.pubRequestEtag=e.getHeader("SIP-ETag"):this.logger.warn("SIP-ETag header missing in a 200-class response to PUBLISH"),e.hasHeader("Expires")){var n=Number(e.getHeader("Expires"));"number"==typeof n&&n>=0&&n<=this.pubRequestExpires?this.pubRequestExpires=n:this.logger.warn("Bad Expires header in a 200-class response to PUBLISH")}else this.logger.warn("Expires header missing in a 200-class response to PUBLISH");0!==this.pubRequestExpires?(this.publishRefreshTimer=setTimeout((function(){return t.refreshRequest()}),900*this.pubRequestExpires),this.emit("published",e,i)):this.emit("unpublished",e,i);break;case/^412$/.test(r.toString()):void 0!==this.pubRequestEtag&&0!==this.pubRequestExpires?(this.logger.warn("412 response to PUBLISH, recovering"),this.pubRequestEtag=void 0,this.emit("progress",e,i),this.publish(this.options.body)):(this.logger.warn("412 response to PUBLISH, recovery failed"),this.pubRequestExpires=0,this.emit("failed",e,i),this.emit("unpublished",e,i));break;case/^423$/.test(r.toString()):if(0!==this.pubRequestExpires&&e.hasHeader("Min-Expires")){var s=Number(e.getHeader("Min-Expires"));"number"==typeof s||s>this.pubRequestExpires?(this.logger.warn("423 code in response to PUBLISH, adjusting the Expires value and trying to recover"),this.pubRequestExpires=s,this.emit("progress",e,i),this.publish(this.options.body)):(this.logger.warn("Bad 423 response Min-Expires header received for PUBLISH"),this.pubRequestExpires=0,this.emit("failed",e,i),this.emit("unpublished",e,i))}else this.logger.warn("423 response to PUBLISH, recovery failed"),this.pubRequestExpires=0,this.emit("failed",e,i),this.emit("unpublished",e,i);break;default:this.pubRequestExpires=0,this.emit("failed",e,i),this.emit("unpublished",e,i)}0===this.pubRequestExpires&&(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,this.pubRequestEtag=void 0)},t.prototype.send=function(){var e=this;return this.ua.userAgentCore.publish(this.request,{onAccept:function(t){return e.receiveResponse(t.message)},onProgress:function(t){return e.receiveResponse(t.message)},onRedirect:function(t){return e.receiveResponse(t.message)},onReject:function(t){return e.receiveResponse(t.message)},onTrying:function(t){return e.receiveResponse(t.message)}}),this},t.prototype.refreshRequest=function(){if(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,void 0===this.pubRequestEtag)throw new c.Exceptions.MethodParameterError("Publish","Body",void 0);if(0===this.pubRequestExpires)throw new c.Exceptions.MethodParameterError("Publish","Expire",this.pubRequestExpires);this.sendPublishRequest()},t.prototype.sendPublishRequest=function(){var e=Object.create(this.options||Object.prototype);e.extraHeaders=(this.options.extraHeaders||[]).slice(),e.extraHeaders.push("Event: "+this.event),e.extraHeaders.push("Expires: "+this.pubRequestExpires),void 0!==this.pubRequestEtag&&e.extraHeaders.push("SIP-If-Match: "+this.pubRequestEtag);var t=this.target instanceof o.URI?this.target:this.ua.normalizeTarget(this.target);if(!t)throw new Error("ruri undefined.");var r,i,n=this.options.params||{};void 0!==this.pubRequestBody&&(r={body:this.pubRequestBody,contentType:this.options.contentType}),r&&(i=u.Utils.fromBodyObj(r)),this.request=this.ua.userAgentCore.makeOutgoingRequestMessage(s.C.PUBLISH,t,n.fromUri?n.fromUri:this.ua.userAgentCore.configuration.aor,n.toUri?n.toUri:this.target,n,e.extraHeaders,i),this.send()},t}(n.ClientContext);t.PublishContext=d},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(51),s=r(11),o=r(5),a=r(8),c=r(12),u=r(9);function d(e){var t={expires:600,extraContactHeaderParams:[],instanceId:void 0,params:{},regId:void 0,registrar:void 0},r={mandatory:{},optional:{expires:function(e){if(u.Utils.isDecimal(e)){var t=Number(e);if(t>=0)return t}},extraContactHeaderParams:function(e){if(e instanceof Array)return e.filter((function(e){return"string"==typeof e}))},instanceId:function(e){if("string"==typeof e)return/^uuid:/i.test(e)&&(e=e.substr(5)),-1===o.Grammar.parse(e,"uuid")?void 0:e},params:function(e){if("object"==typeof e)return e},regId:function(e){if(u.Utils.isDecimal(e)){var t=Number(e);if(t>=0)return t}},registrar:function(e){if("string"==typeof e){/^sip:/i.test(e)||(e=s.C.SIP+":"+e);var t=o.Grammar.URIParse(e);return t?t.user?void 0:t:void 0}}}};for(var i in r.mandatory){if(!e.hasOwnProperty(i))throw new c.Exceptions.ConfigurationError(i);var n=e[i];if(void 0===(a=r.mandatory[i](n)))throw new c.Exceptions.ConfigurationError(i,n);t[i]=a}for(var i in r.optional)if(e.hasOwnProperty(i)){var a;if((n=e[i])instanceof Array&&0===n.length)continue;if(null===n||""===n||void 0===n||"number"==typeof n&&isNaN(n))continue;if(void 0===(a=r.optional[i](n)))throw new c.Exceptions.ConfigurationError(i,n);t[i]=a}return t}var p=function(e){function t(t,r){void 0===r&&(r={});var i=this,n=d(r);if(n.regId&&!n.instanceId?n.instanceId=u.Utils.newUUID():!n.regId&&n.instanceId&&(n.regId=1),n.params.toUri=n.params.toUri||t.configuration.uri,n.params.toDisplayName=n.params.toDisplayName||t.configuration.displayName,n.params.callId=n.params.callId||u.Utils.createRandomToken(22),n.params.cseq=n.params.cseq||Math.floor(1e4*Math.random()),!n.registrar){var o={};"object"==typeof t.configuration.uri?(o=t.configuration.uri.clone()).user=void 0:o=t.configuration.uri,n.registrar=o}for(var c in(i=e.call(this,t,s.C.REGISTER,n.registrar,n)||this).type=a.TypeStrings.RegisterContext,i.options=n,i.logger=t.getLogger("sip.registercontext"),i.logger.log("configuration parameters for RegisterContext after validation:"),n)n.hasOwnProperty(c)&&i.logger.log("\xb7 "+c+": "+JSON.stringify(n[c]));return i.expires=n.expires,i.contact=t.contact.toString(),i.registered=!1,t.transport.on("disconnected",(function(){return i.onTransportDisconnected()})),i}return i.__extends(t,e),t.prototype.register=function(e){var t=this;void 0===e&&(e={}),this.options=i.__assign({},this.options,e);var r=(this.options.extraHeaders||[]).slice();r.push("Contact: "+this.generateContactHeader(this.expires)),r.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),this.closeHeaders=this.options.closeWithHeaders?(this.options.extraHeaders||[]).slice():[],this.receiveResponse=function(e){if(e.cseq===t.request.cseq){void 0!==t.registrationTimer&&(clearTimeout(t.registrationTimer),t.registrationTimer=void 0);var r=(e.statusCode||0).toString();switch(!0){case/^1[0-9]{2}$/.test(r):t.emit("progress",e);break;case/^2[0-9]{2}$/.test(r):t.emit("accepted",e);var i=void 0;e.hasHeader("expires")&&(i=Number(e.getHeader("expires"))),void 0!==t.registrationExpiredTimer&&(clearTimeout(t.registrationExpiredTimer),t.registrationExpiredTimer=void 0);var n=e.getHeaders("contact").length;if(!n){t.logger.warn("no Contact header in response to REGISTER, response ignored");break}for(var a=void 0;n--;){if((a=e.parseHeader("contact",n)).uri.user===t.ua.contact.uri.user){i=a.getParam("expires");break}a=void 0}if(!a){t.logger.warn("no Contact header pointing to us, response ignored");break}void 0===i&&(i=t.expires),t.registrationTimer=setTimeout((function(){t.registrationTimer=void 0,t.register(t.options)}),1e3*i-3e3),t.registrationExpiredTimer=setTimeout((function(){t.logger.warn("registration expired"),t.registered&&t.unregistered(void 0,s.C.causes.EXPIRES)}),1e3*i),a.hasParam("temp-gruu")&&(t.ua.contact.tempGruu=o.Grammar.URIParse(a.getParam("temp-gruu").replace(/"/g,""))),a.hasParam("pub-gruu")&&(t.ua.contact.pubGruu=o.Grammar.URIParse(a.getParam("pub-gruu").replace(/"/g,""))),t.registered=!0,t.emit("registered",e||void 0);break;case/^423$/.test(r):e.hasHeader("min-expires")?(t.expires=Number(e.getHeader("min-expires")),t.register(t.options)):(t.logger.warn("423 response received for REGISTER without Min-Expires"),t.registrationFailure(e,s.C.causes.SIP_FAILURE_CODE));break;default:t.registrationFailure(e,u.Utils.sipErrorCause(e.statusCode||0))}}},this.onRequestTimeout=function(){t.registrationFailure(void 0,s.C.causes.REQUEST_TIMEOUT)},this.onTransportError=function(){t.registrationFailure(void 0,s.C.causes.CONNECTION_ERROR)},this.request.cseq++,this.request.setHeader("cseq",this.request.cseq+" REGISTER"),this.request.extraHeaders=r,this.send()},t.prototype.close=function(){var e={all:!1,extraHeaders:this.closeHeaders};this.registeredBefore=this.registered,this.registered&&this.unregister(e)},t.prototype.unregister=function(e){var t=this;void 0===e&&(e={}),this.registered||e.all||this.logger.warn("Already unregistered, but sending an unregister anyways.");var r=(e.extraHeaders||[]).slice();this.registered=!1,void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),e.all?(r.push("Contact: *"),r.push("Expires: 0")):r.push("Contact: "+this.generateContactHeader(0)),this.receiveResponse=function(e){var r=e&&e.statusCode?e.statusCode.toString():"";switch(!0){case/^1[0-9]{2}$/.test(r):t.emit("progress",e);break;case/^2[0-9]{2}$/.test(r):t.emit("accepted",e),void 0!==t.registrationExpiredTimer&&(clearTimeout(t.registrationExpiredTimer),t.registrationExpiredTimer=void 0),t.unregistered(e);break;default:t.unregistered(e,u.Utils.sipErrorCause(e.statusCode||0))}},this.onRequestTimeout=function(){},this.request.cseq++,this.request.setHeader("cseq",this.request.cseq+" REGISTER"),this.request.extraHeaders=r,this.send()},t.prototype.unregistered=function(e,t){this.registered=!1,this.emit("unregistered",e||void 0,t||void 0)},t.prototype.send=function(){var e=this;return this.ua.userAgentCore.register(this.request,{onAccept:function(t){return e.receiveResponse(t.message)},onProgress:function(t){return e.receiveResponse(t.message)},onRedirect:function(t){return e.receiveResponse(t.message)},onReject:function(t){return e.receiveResponse(t.message)},onTrying:function(t){return e.receiveResponse(t.message)}}),this},t.prototype.registrationFailure=function(e,t){this.emit("failed",e||void 0,t||void 0)},t.prototype.onTransportDisconnected=function(){this.registeredBefore=this.registered,void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),void 0!==this.registrationExpiredTimer&&(clearTimeout(this.registrationExpiredTimer),this.registrationExpiredTimer=void 0),this.registered&&this.unregistered(void 0,s.C.causes.CONNECTION_ERROR)},t.prototype.generateContactHeader=function(e){void 0===e&&(e=0);var t=this.contact;return this.options.regId&&this.options.instanceId&&(t+=";reg-id="+this.options.regId,t+=';+sip.instance=""'),this.options.extraContactHeaderParams&&this.options.extraContactHeaderParams.forEach((function(e){t+=";"+e})),t+=";expires="+e},t}(n.ClientContext);t.RegisterContext=p},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(7),s=r(51),o=r(11),a=r(5),c=r(8),u=r(12),d=r(96),p=r(90),h=r(110),l=r(9),g=function(e){function t(r){var i=e.call(this)||this;if(i.data={},i.type=c.TypeStrings.Session,!r)throw new u.Exceptions.SessionDescriptionHandlerError("A session description handler is required for the session to function");return i.status=t.C.STATUS_NULL,i.pendingReinvite=!1,i.sessionDescriptionHandlerFactory=r,i.hasOffer=!1,i.hasAnswer=!1,i.timers={ackTimer:void 0,expiresTimer:void 0,invite2xxTimer:void 0,userNoAnswerTimer:void 0,rel1xxTimer:void 0,prackTimer:void 0},i.startTime=void 0,i.endTime=void 0,i.tones=void 0,i.localHold=!1,i.earlySdp=void 0,i.rel100=o.C.supported.UNSUPPORTED,i}return i.__extends(t,e),t.prototype.dtmf=function(e,t){var r=this;if(void 0===t&&(t={}),this.status!==c.SessionStatus.STATUS_CONFIRMED&&this.status!==c.SessionStatus.STATUS_WAITING_FOR_ACK)throw new u.Exceptions.InvalidStateError(this.status);if(!e||!e.toString().match(/^[0-9A-D#*,]+$/i))throw new TypeError("Invalid tones: "+e);var i=function(){if(r.status!==c.SessionStatus.STATUS_TERMINATED&&r.tones&&0!==r.tones.length){var e,n=r.tones.shift();","===n.tone?e=2e3:(n.on("failed",(function(){r.tones=void 0})),n.send(t),e=n.duration+n.interToneGap),setTimeout(i,e)}else r.tones=void 0};e=e.toString();var n=this.ua.configuration.dtmfType;this.sessionDescriptionHandler&&n===o.C.dtmfType.RTP&&(this.sessionDescriptionHandler.sendDtmf(e,t)||(this.logger.warn("Attempt to use dtmfType 'RTP' has failed, falling back to INFO packet method"),n=o.C.dtmfType.INFO));if(n===o.C.dtmfType.INFO){for(var s=[],a=e.split("");a.length>0;)s.push(new h.DTMF(this,a.shift(),t));if(this.tones)return this.tones=this.tones.concat(s),this;this.tones=s,i()}return this},t.prototype.bye=function(e){if(void 0===e&&(e={}),this.status===c.SessionStatus.STATUS_TERMINATED)return this.logger.error("Error: Attempted to send BYE in a terminated session."),this;this.logger.log("terminating Session");var t=e.statusCode;if(t&&(t<200||t>=700))throw new TypeError("Invalid statusCode: "+t);return e.receiveResponse=function(){},this.sendRequest(o.C.BYE,e).terminated()},t.prototype.refer=function(e,t){if(void 0===t&&(t={}),this.status!==c.SessionStatus.STATUS_CONFIRMED)throw new u.Exceptions.InvalidStateError(this.status);return this.referContext=new d.ReferClientContext(this.ua,this,e,t),this.emit("referRequested",this.referContext),this.referContext.refer(t),this.referContext},t.prototype.sendRequest=function(e,t){if(void 0===t&&(t={}),!this.session)throw new Error("Session undefined.");var r;t.body&&(t.body=l.Utils.fromBodyObj(t.body));var i,n=t.receiveResponse;n&&(r={onAccept:function(e){return n(e.message)},onProgress:function(e){return n(e.message)},onRedirect:function(e){return n(e.message)},onReject:function(e){return n(e.message)},onTrying:function(e){return n(e.message)}});var s=t;switch(e){case o.C.BYE:i=this.session.bye(r,s);break;case o.C.INVITE:i=this.session.invite(r,s);break;case o.C.REFER:i=this.session.refer(r,s);break;default:throw new Error("Unexpected "+e+". Method not implemented by user agent core.")}return this.emit(e.toLowerCase(),i.message),this},t.prototype.close=function(){if(this.status===c.SessionStatus.STATUS_TERMINATED)return this;for(var e in this.logger.log("closing INVITE session "+this.id),this.sessionDescriptionHandler&&this.sessionDescriptionHandler.close(),this.timers)this.timers[e]&&clearTimeout(this.timers[e]);return this.status=c.SessionStatus.STATUS_TERMINATED,this.ua.transport&&this.ua.transport.removeListener("transportError",this.errorListener),delete this.ua.sessions[this.id],this},t.prototype.hold=function(e,t){if(void 0===e&&(e={}),void 0===t&&(t=[]),this.status!==c.SessionStatus.STATUS_WAITING_FOR_ACK&&this.status!==c.SessionStatus.STATUS_CONFIRMED)throw new u.Exceptions.InvalidStateError(this.status);this.localHold?this.logger.log("Session is already on hold, cannot put it on hold again"):(e.modifiers=t,this.sessionDescriptionHandler&&e.modifiers.push(this.sessionDescriptionHandler.holdModifier),this.localHold=!0,this.sendReinvite(e))},t.prototype.unhold=function(e,t){if(void 0===e&&(e={}),void 0===t&&(t=[]),this.status!==c.SessionStatus.STATUS_WAITING_FOR_ACK&&this.status!==c.SessionStatus.STATUS_CONFIRMED)throw new u.Exceptions.InvalidStateError(this.status);this.localHold?(e.modifiers=t,this.localHold=!1,this.sendReinvite(e)):this.logger.log("Session is not on hold, cannot unhold it")},t.prototype.reinvite=function(e,t){return void 0===e&&(e={}),void 0===t&&(t=[]),e.modifiers=t,this.sendReinvite(e)},t.prototype.terminate=function(e){return this},t.prototype.onTransportError=function(){this.status!==c.SessionStatus.STATUS_CONFIRMED&&this.status!==c.SessionStatus.STATUS_TERMINATED&&this.failed(void 0,o.C.causes.CONNECTION_ERROR)},t.prototype.onRequestTimeout=function(){this.status===c.SessionStatus.STATUS_CONFIRMED?this.terminated(void 0,o.C.causes.REQUEST_TIMEOUT):this.status!==c.SessionStatus.STATUS_TERMINATED&&(this.failed(void 0,o.C.causes.REQUEST_TIMEOUT),this.terminated(void 0,o.C.causes.REQUEST_TIMEOUT))},t.prototype.onDialogError=function(e){this.status===c.SessionStatus.STATUS_CONFIRMED?this.terminated(e,o.C.causes.DIALOG_ERROR):this.status!==c.SessionStatus.STATUS_TERMINATED&&(this.failed(e,o.C.causes.DIALOG_ERROR),this.terminated(e,o.C.causes.DIALOG_ERROR))},t.prototype.on=function(t,r){return e.prototype.on.call(this,t,r)},t.prototype.onAck=function(e){var t=this,r=function(){clearTimeout(t.timers.ackTimer),clearTimeout(t.timers.invite2xxTimer),t.status=c.SessionStatus.STATUS_CONFIRMED;var r=e.message.getHeader("Content-Disposition");r&&"render"===r.type&&(t.renderbody=e.message.body,t.rendertype=e.message.getHeader("Content-Type")),t.emit("confirmed",e.message)};this.status===c.SessionStatus.STATUS_WAITING_FOR_ACK&&(this.sessionDescriptionHandler&&this.sessionDescriptionHandler.hasDescription(e.message.getHeader("Content-Type")||"")?(this.hasAnswer=!0,this.sessionDescriptionHandler.setDescription(e.message.body,this.sessionDescriptionHandlerOptions,this.modifiers).catch((function(r){throw t.logger.warn(r),t.terminate({statusCode:"488",reasonPhrase:"Bad Media Description"}),t.failed(e.message,o.C.causes.BAD_MEDIA_DESCRIPTION),t.terminated(e.message,o.C.causes.BAD_MEDIA_DESCRIPTION),r})).then((function(){return r()}))):r())},t.prototype.receiveRequest=function(e){switch(e.message.method){case o.C.BYE:e.accept(),this.status===c.SessionStatus.STATUS_CONFIRMED&&(this.emit("bye",e.message),this.terminated(e.message,o.C.BYE));break;case o.C.INVITE:this.status===c.SessionStatus.STATUS_CONFIRMED&&(this.logger.log("re-INVITE received"),this.receiveReinvite(e));break;case o.C.INFO:if(this.status===c.SessionStatus.STATUS_CONFIRMED||this.status===c.SessionStatus.STATUS_WAITING_FOR_ACK){if(this.onInfo)return this.onInfo(e.message);var t=e.message.getHeader("content-type");if(t)if(t.match(/^application\/dtmf-relay/i)){if(e.message.body){var r=e.message.body.split("\r\n",2);if(2===r.length){var i=void 0,n=void 0,s=/^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/;s.test(r[0])&&(i=r[0].replace(s,"$2"));var a=/^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/;a.test(r[1])&&(n=parseInt(r[1].replace(a,"$2"),10)),i&&n&&new h.DTMF(this,i,{duration:n}).init_incoming(e)}}}else e.reject({statusCode:415,extraHeaders:["Accept: application/dtmf-relay"]})}break;case o.C.REFER:if(this.status===c.SessionStatus.STATUS_CONFIRMED)if(this.logger.log("REFER received"),this.referContext=new d.ReferServerContext(this.ua,e,this.session),this.listeners("referRequested").length)this.emit("referRequested",this.referContext);else{this.logger.log("No referRequested listeners, automatically accepting and following the refer");var u={followRefer:!0};this.passedOptions&&(u.inviteOptions=this.passedOptions),this.referContext.accept(u,this.modifiers)}break;case o.C.NOTIFY:if(this.referContext&&this.referContext.type===c.TypeStrings.ReferClientContext&&e.message.hasHeader("event")&&/^refer(;.*)?$/.test(e.message.getHeader("event")))return void this.referContext.receiveNotify(e);e.accept(),this.emit("notify",e.message)}},t.prototype.receiveReinvite=function(e){var t,r=this;if(this.emit("reinvite",this,e.message),e.message.hasHeader("P-Asserted-Identity")&&(this.assertedIdentity=a.Grammar.nameAddrHeaderParse(e.message.getHeader("P-Asserted-Identity"))),this.sessionDescriptionHandler){if("0"!==e.message.getHeader("Content-Length")||e.message.getHeader("Content-Type")){if(!this.sessionDescriptionHandler.hasDescription(e.message.getHeader("Content-Type")||""))return e.reject({statusCode:415}),void this.emit("reinviteFailed",this);t=this.sessionDescriptionHandler.setDescription(e.message.body,this.sessionDescriptionHandlerOptions,this.modifiers).then(this.sessionDescriptionHandler.getDescription.bind(this.sessionDescriptionHandler,this.sessionDescriptionHandlerOptions,this.modifiers))}else t=this.sessionDescriptionHandler.getDescription(this.sessionDescriptionHandlerOptions,this.modifiers);t.catch((function(t){var i;throw t.type===c.TypeStrings.SessionDescriptionHandlerError?i=500:t.type===c.TypeStrings.RenegotiationError?(r.emit("renegotiationError",t),r.logger.warn(t.toString()),i=488):(r.logger.error(t),i=488),e.reject({statusCode:i}),r.emit("reinviteFailed",r),t})).then((function(t){var i=["Contact: "+r.contact];e.accept({statusCode:200,extraHeaders:i,body:l.Utils.fromBodyObj(t)}),r.status=c.SessionStatus.STATUS_WAITING_FOR_ACK,r.emit("reinviteAccepted",r)}))}else this.logger.warn("No SessionDescriptionHandler to reinvite")},t.prototype.sendReinvite=function(e){var t=this;if(void 0===e&&(e={}),this.pendingReinvite)this.logger.warn("Reinvite in progress. Please wait until complete, then try again.");else if(this.sessionDescriptionHandler){this.pendingReinvite=!0,e.modifiers=e.modifiers||[];var r=(e.extraHeaders||[]).slice();r.push("Contact: "+this.contact),r.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),this.sessionDescriptionHandler.getDescription(e.sessionDescriptionHandlerOptions,e.modifiers).then((function(e){if(!t.session)throw new Error("Session undefined.");var i={onAccept:function(e){if(t.status!==c.SessionStatus.STATUS_TERMINATED)if(t.pendingReinvite){if(t.status=c.SessionStatus.STATUS_CONFIRMED,t.emit("ack",e.ack()),t.pendingReinvite=!1,clearTimeout(t.timers.invite2xxTimer),!t.sessionDescriptionHandler||!t.sessionDescriptionHandler.hasDescription(e.message.getHeader("Content-Type")||""))return t.logger.error("2XX response received to re-invite but did not have a description"),t.emit("reinviteFailed",t),void t.emit("renegotiationError",new u.Exceptions.RenegotiationError("2XX response received to re-invite but did not have a description"));t.sessionDescriptionHandler.setDescription(e.message.body,t.sessionDescriptionHandlerOptions,t.modifiers).catch((function(e){throw t.logger.error("Could not set the description in 2XX response"),t.logger.error(e),t.emit("reinviteFailed",t),t.emit("renegotiationError",e),t.sendRequest(o.C.BYE,{extraHeaders:["Reason: "+l.Utils.getReasonHeaderValue(488,"Not Acceptable Here")]}),t.terminated(void 0,o.C.causes.INCOMPATIBLE_SDP),e})).then((function(){t.emit("reinviteAccepted",t)}))}else t.logger.error("Received reinvite response, but have no pending reinvite");else t.logger.error("Received reinvite response, but in STATUS_TERMINATED")},onProgress:function(e){},onRedirect:function(e){t.pendingReinvite=!1,t.logger.log("Received a non 1XX or 2XX response to a re-invite"),t.emit("reinviteFailed",t),t.emit("renegotiationError",new u.Exceptions.RenegotiationError("Invalid response to a re-invite"))},onReject:function(e){t.pendingReinvite=!1,t.logger.log("Received a non 1XX or 2XX response to a re-invite"),t.emit("reinviteFailed",t),t.emit("renegotiationError",new u.Exceptions.RenegotiationError("Invalid response to a re-invite"))},onTrying:function(e){}},n={extraHeaders:r,body:l.Utils.fromBodyObj(e)};t.session.invite(i,n)})).catch((function(e){if(e.type===c.TypeStrings.RenegotiationError)throw t.pendingReinvite=!1,t.emit("renegotiationError",e),t.logger.warn("Renegotiation Error"),t.logger.warn(e.toString()),e;throw t.logger.error("sessionDescriptionHandler error"),t.logger.error(e),e}))}else this.logger.warn("No SessionDescriptionHandler, can't reinvite..")},t.prototype.failed=function(e,t){return this.status===c.SessionStatus.STATUS_TERMINATED?this:(this.emit("failed",e,t),this)},t.prototype.rejected=function(e,t){return this.emit("rejected",e,t),this},t.prototype.canceled=function(){return this.sessionDescriptionHandler&&this.sessionDescriptionHandler.close(),this.emit("cancel"),this},t.prototype.accepted=function(e,t){return e instanceof String||(t=l.Utils.getReasonPhrase(e&&e.statusCode||0,t)),this.startTime=new Date,this.replacee&&(this.replacee.emit("replaced",this),this.replacee.terminate()),this.emit("accepted",e,t),this},t.prototype.terminated=function(e,t){return this.status===c.SessionStatus.STATUS_TERMINATED?this:(this.endTime=new Date,this.close(),this.emit("terminated",e,t),this)},t.prototype.connecting=function(e){return this.emit("connecting",{request:e}),this},t.C=c.SessionStatus,t}(n.EventEmitter);t.Session=g;var f=function(e){function t(t,r){var i=this;if(!t.configuration.sessionDescriptionHandlerFactory)throw t.logger.warn("Can't build ISC without SDH Factory"),new Error("ISC Constructor Failed");(i=e.call(this,t.configuration.sessionDescriptionHandlerFactory)||this)._canceled=!1,i.rseq=Math.floor(1e4*Math.random()),i.incomingRequest=r;var n=r.message;p.ServerContext.initializer(i,t,r),i.type=c.TypeStrings.InviteServerContext;var s=n.parseHeader("Content-Disposition");s&&"render"===s.type&&(i.renderbody=n.body,i.rendertype=n.getHeader("Content-Type")),i.status=c.SessionStatus.STATUS_INVITE_RECEIVED,i.fromTag=n.fromTag,i.id=n.callId+i.fromTag,i.request=n,i.contact=i.ua.contact.toString(),i.logger=t.getLogger("sip.inviteservercontext",i.id),i.ua.sessions[i.id]=i;var a=function(e,t){n.hasHeader(e)&&n.getHeader(e).toLowerCase().indexOf("100rel")>=0&&(i.rel100=t)};if(a("require",o.C.supported.REQUIRED),a("supported",o.C.supported.SUPPORTED),i.request.toTag=r.toTag,i.status=c.SessionStatus.STATUS_WAITING_FOR_ANSWER,i.timers.userNoAnswerTimer=setTimeout((function(){r.reject({statusCode:408}),i.failed(n,o.C.causes.NO_ANSWER),i.terminated(n,o.C.causes.NO_ANSWER)}),i.ua.configuration.noAnswerTimeout||60),n.hasHeader("expires")){var u=1e3*Number(n.getHeader("expires")||0);i.timers.expiresTimer=setTimeout((function(){i.status===c.SessionStatus.STATUS_WAITING_FOR_ANSWER&&(r.reject({statusCode:487}),i.failed(n,o.C.causes.EXPIRES),i.terminated(n,o.C.causes.EXPIRES))}),u)}return i.errorListener=i.onTransportError.bind(i),t.transport&&t.transport.on("transportError",i.errorListener),i}return i.__extends(t,e),Object.defineProperty(t.prototype,"autoSendAnInitialProvisionalResponse",{get:function(){return this.rel100!==o.C.supported.REQUIRED},enumerable:!0,configurable:!0}),t.prototype.reply=function(e){return void 0===e&&(e={}),this},t.prototype.reject=function(e){var t=this;if(void 0===e&&(e={}),this.status===c.SessionStatus.STATUS_TERMINATED)throw new u.Exceptions.InvalidStateError(this.status);this.logger.log("rejecting RTCSession");var r=e.statusCode||480,i=l.Utils.getReasonPhrase(r,e.reasonPhrase),n=e.extraHeaders||[];if(r<300||r>699)throw new TypeError("Invalid statusCode: "+r);var s=e.body?a.fromBodyLegacy(e.body):void 0,o=r<400?this.incomingRequest.redirect([],{statusCode:r,reasonPhrase:i,extraHeaders:n,body:s}):this.incomingRequest.reject({statusCode:r,reasonPhrase:i,extraHeaders:n,body:s});return["rejected","failed"].forEach((function(e){t.emit(e,o.message,i)})),this.terminated()},t.prototype.accept=function(e){var t=this;return void 0===e&&(e={}),this._accept(e).then((function(e){var r=e.message,i=e.session;i.delegate={onAck:function(e){return t.onAck(e)},onAckTimeout:function(){return t.onAckTimeout()},onBye:function(e){return t.receiveRequest(e)},onInfo:function(e){return t.receiveRequest(e)},onInvite:function(e){return t.receiveRequest(e)},onNotify:function(e){return t.receiveRequest(e)},onPrack:function(e){return t.receiveRequest(e)},onRefer:function(e){return t.receiveRequest(e)}},t.session=i,t.status=c.SessionStatus.STATUS_WAITING_FOR_ACK,t.accepted(r,l.Utils.getReasonPhrase(200))})).catch((function(e){if(t.onContextError(e),!t._canceled)throw e})),this},t.prototype.progress=function(e){var t=this;void 0===e&&(e={});var r=e.statusCode||180;if(r<100||r>199)throw new TypeError("Invalid statusCode: "+r);if(this.status===c.SessionStatus.STATUS_TERMINATED)return this.logger.warn("Unexpected call for progress while terminated, ignoring"),this;if(this.status===c.SessionStatus.STATUS_ANSWERED)return this.logger.warn("Unexpected call for progress while answered, ignoring"),this;if(this.status===c.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK)return this.logger.warn("Unexpected call for progress while answered (waiting for prack), ignoring"),this;if(this.status===c.SessionStatus.STATUS_WAITING_FOR_PRACK)return this.logger.warn("Unexpected call for progress while waiting for prack, ignoring"),this;if(100===e.statusCode){try{this.incomingRequest.trying()}catch(e){if(this.onContextError(e),!this._canceled)throw e}return this}return this.rel100===o.C.supported.REQUIRED||this.rel100===o.C.supported.SUPPORTED&&e.rel100||this.rel100===o.C.supported.SUPPORTED&&this.ua.configuration.rel100===o.C.supported.REQUIRED?(this._reliableProgressWaitForPrack(e).catch((function(e){if(t.onContextError(e),!t._canceled)throw e})),this):(this._progress(e).catch((function(e){if(t.onContextError(e),!t._canceled)throw e})),this)},t.prototype.terminate=function(e){var t=this;if(void 0===e&&(e={}),!this.session)return this.reject(e),this;switch(this.session.sessionState){case a.SessionState.Initial:case a.SessionState.Early:return this.reject(e),this;case a.SessionState.AckWait:return this.session.delegate={onAck:function(){t.sendRequest(o.C.BYE,e)},onAckTimeout:function(){t.sendRequest(o.C.BYE,e)}},this.emit("bye",this.request),this.terminated(),this;case a.SessionState.Confirmed:return this.bye(e),this;case a.SessionState.Terminated:default:return this}},t.prototype.onCancel=function(e){this.status!==c.SessionStatus.STATUS_WAITING_FOR_ANSWER&&this.status!==c.SessionStatus.STATUS_WAITING_FOR_PRACK&&this.status!==c.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK&&this.status!==c.SessionStatus.STATUS_EARLY_MEDIA&&this.status!==c.SessionStatus.STATUS_ANSWERED||(this.status=c.SessionStatus.STATUS_CANCELED,this.incomingRequest.reject({statusCode:487}),this.canceled(),this.rejected(e,o.C.causes.CANCELED),this.failed(e,o.C.causes.CANCELED),this.terminated(e,o.C.causes.CANCELED))},t.prototype.receiveRequest=function(t){var r=this;switch(t.message.method){case o.C.PRACK:this.status===c.SessionStatus.STATUS_WAITING_FOR_PRACK||this.status===c.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK?this.hasAnswer?(clearTimeout(this.timers.rel1xxTimer),clearTimeout(this.timers.prackTimer),t.accept(),this.status===c.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK&&(this.status=c.SessionStatus.STATUS_EARLY_MEDIA,this.accept()),this.status=c.SessionStatus.STATUS_EARLY_MEDIA):(this.sessionDescriptionHandler=this.setupSessionDescriptionHandler(),this.emit("SessionDescriptionHandler-created",this.sessionDescriptionHandler),this.sessionDescriptionHandler.hasDescription(t.message.getHeader("Content-Type")||"")?(this.hasAnswer=!0,this.sessionDescriptionHandler.setDescription(t.message.body,this.sessionDescriptionHandlerOptions,this.modifiers).then((function(){clearTimeout(r.timers.rel1xxTimer),clearTimeout(r.timers.prackTimer),t.accept(),r.status===c.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK&&(r.status=c.SessionStatus.STATUS_EARLY_MEDIA,r.accept()),r.status=c.SessionStatus.STATUS_EARLY_MEDIA}),(function(e){r.logger.warn(e),r.terminate({statusCode:"488",reasonPhrase:"Bad Media Description"}),r.failed(t.message,o.C.causes.BAD_MEDIA_DESCRIPTION),r.terminated(t.message,o.C.causes.BAD_MEDIA_DESCRIPTION)}))):(this.terminate({statusCode:"488",reasonPhrase:"Bad Media Description"}),this.failed(t.message,o.C.causes.BAD_MEDIA_DESCRIPTION),this.terminated(t.message,o.C.causes.BAD_MEDIA_DESCRIPTION))):this.status===c.SessionStatus.STATUS_EARLY_MEDIA&&t.accept();break;default:e.prototype.receiveRequest.call(this,t)}},t.prototype.setupSessionDescriptionHandler=function(){return this.sessionDescriptionHandler?this.sessionDescriptionHandler:this.sessionDescriptionHandlerFactory(this,this.ua.configuration.sessionDescriptionHandlerFactoryOptions)},t.prototype.generateResponseOfferAnswer=function(e){if(!this.session){var t=a.getBody(this.incomingRequest.message);return t&&"session"===t.contentDisposition?this.setOfferAndGetAnswer(t,e):this.getOffer(e)}switch(this.session.signalingState){case a.SignalingState.Initial:return this.getOffer(e);case a.SignalingState.Stable:case a.SignalingState.HaveLocalOffer:return Promise.resolve(void 0);case a.SignalingState.HaveRemoteOffer:if(!this.session.offer)throw new Error("Session offer undefined");return this.setOfferAndGetAnswer(this.session.offer,e);case a.SignalingState.Closed:default:throw new Error("Invalid signaling state "+this.session.signalingState+".")}},t.prototype.handlePrackOfferAnswer=function(e,t){if(!this.session)throw new Error("Session undefined.");var r=a.getBody(e.message);if(!r||"session"!==r.contentDisposition)return Promise.resolve(void 0);switch(this.session.signalingState){case a.SignalingState.Initial:throw new Error("Invalid signaling state "+this.session.signalingState+".");case a.SignalingState.Stable:return this.setAnswer(r,t).then((function(){}));case a.SignalingState.HaveLocalOffer:throw new Error("Invalid signaling state "+this.session.signalingState+".");case a.SignalingState.HaveRemoteOffer:return this.setOfferAndGetAnswer(r,t);case a.SignalingState.Closed:default:throw new Error("Invalid signaling state "+this.session.signalingState+".")}},t.prototype.canceled=function(){return this._canceled=!0,e.prototype.canceled.call(this)},t.prototype.terminated=function(t,r){return this.prackNeverArrived(),e.prototype.terminated.call(this,t,r)},t.prototype._accept=function(e){var t=this;return void 0===e&&(e={}),this.onInfo=e.onInfo,this.status===c.SessionStatus.STATUS_WAITING_FOR_PRACK?(this.status=c.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK,this.waitForArrivalOfPrack().then((function(){t.status=c.SessionStatus.STATUS_ANSWERED,clearTimeout(t.timers.userNoAnswerTimer)})).then((function(){return t.generateResponseOfferAnswer(e)})).then((function(e){return t.incomingRequest.accept({statusCode:200,body:e})}))):this.status!==c.SessionStatus.STATUS_WAITING_FOR_ANSWER?Promise.reject(new u.Exceptions.InvalidStateError(this.status)):(this.status=c.SessionStatus.STATUS_ANSWERED,this.status=c.SessionStatus.STATUS_ANSWERED,clearTimeout(this.timers.userNoAnswerTimer),this.generateResponseOfferAnswer(e).then((function(e){return t.incomingRequest.accept({statusCode:200,body:e})})))},t.prototype._progress=function(e){void 0===e&&(e={});var t=e.statusCode||180,r=e.reasonPhrase,i=(e.extraHeaders||[]).slice(),n=e.body?a.fromBodyLegacy(e.body):void 0;if(183===t&&!n)return this._progressWithSDP(e);try{var s=this.incomingRequest.progress({statusCode:t,reasonPhrase:r,extraHeaders:i,body:n});return this.emit("progress",s.message,r),this.session=s.session,Promise.resolve(s)}catch(e){return Promise.reject(e)}},t.prototype._progressWithSDP=function(e){var t=this;void 0===e&&(e={});var r=e.statusCode||183,i=e.reasonPhrase,n=(e.extraHeaders||[]).slice();return this.generateResponseOfferAnswer(e).then((function(e){return t.incomingRequest.progress({statusCode:r,reasonPhrase:i,extraHeaders:n,body:e})})).then((function(e){return t.emit("progress",e.message,i),t.session=e.session,e}))},t.prototype._reliableProgress=function(e){var t=this;void 0===e&&(e={});var r=e.statusCode||183,i=e.reasonPhrase,n=(e.extraHeaders||[]).slice();return n.push("Require: 100rel"),n.push("RSeq: "+Math.floor(1e4*Math.random())),this.generateResponseOfferAnswer(e).then((function(e){return t.incomingRequest.progress({statusCode:r,reasonPhrase:i,extraHeaders:n,body:e})})).then((function(e){return t.emit("progress",e.message,i),t.session=e.session,e}))},t.prototype._reliableProgressWaitForPrack=function(e){var t=this;void 0===e&&(e={});var r,i=e.statusCode||183,n=e.reasonPhrase,s=(e.extraHeaders||[]).slice();return s.push("Require: 100rel"),s.push("RSeq: "+this.rseq++),this.status=c.SessionStatus.STATUS_WAITING_FOR_PRACK,new Promise((function(d,p){var h=!0;return t.generateResponseOfferAnswer(e).then((function(e){return r=e,t.incomingRequest.progress({statusCode:i,reasonPhrase:n,extraHeaders:s,body:r})})).then((function(l){var g,f;t.emit("progress",l.message,n),t.session=l.session,l.session.delegate={onPrack:function(r){g=r,clearTimeout(m),clearTimeout(T),h&&(h=!1,t.handlePrackOfferAnswer(g,e).then((function(e){try{f=g.accept({statusCode:200,body:e}),t.status===c.SessionStatus.STATUS_WAITING_FOR_PRACK&&(t.status=c.SessionStatus.STATUS_WAITING_FOR_ANSWER),t.prackArrived(),d({prackRequest:g,prackResponse:f,progressResponse:l})}catch(e){p(e)}})))}};var m=setTimeout((function(){if(h){h=!1,t.logger.warn("No PRACK received, rejecting INVITE."),clearTimeout(T);try{t.incomingRequest.reject({statusCode:504}),t.terminated(void 0,o.C.causes.NO_PRACK),p(new u.Exceptions.TerminatedSessionError)}catch(e){p(e)}}}),64*a.Timers.T1),v=function(){try{t.incomingRequest.progress({statusCode:i,reasonPhrase:n,extraHeaders:s,body:r})}catch(e){return h=!1,void p(e)}T=setTimeout(v,S*=2)},S=a.Timers.T1,T=setTimeout(v,S)}))}))},t.prototype.onAckTimeout=function(){if(this.status===c.SessionStatus.STATUS_WAITING_FOR_ACK){if(this.logger.log("no ACK received for an extended period of time, terminating the call"),!this.session)throw new Error("Session undefined.");this.session.bye(),this.terminated(void 0,o.C.causes.NO_ACK)}},t.prototype.onContextError=function(e){var t=480;e instanceof a.Exception?e instanceof u.Exceptions.SessionDescriptionHandlerError?(this.logger.error(e.message),e.error&&this.logger.error(e.error)):e instanceof u.Exceptions.TerminatedSessionError?this.logger.warn("Incoming session terminated while waiting for PRACK."):e instanceof u.Exceptions.UnsupportedSessionDescriptionContentTypeError?t=415:e instanceof a.Exception&&this.logger.error(e.message):e instanceof Error?this.logger.error(e.message):(this.logger.error("An error occurred in the session description handler."),this.logger.error(e));try{this.incomingRequest.reject({statusCode:t}),this.failed(this.incomingRequest.message,e.message),this.terminated(this.incomingRequest.message,e.message)}catch(e){return}},t.prototype.prackArrived=function(){this.waitingForPrackResolve&&this.waitingForPrackResolve(),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0},t.prototype.prackNeverArrived=function(){this.waitingForPrackReject&&this.waitingForPrackReject(new u.Exceptions.TerminatedSessionError),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0},t.prototype.waitForArrivalOfPrack=function(){var e=this;if(this.waitingForPrackPromise)throw new Error("Already waiting for PRACK");return this.waitingForPrackPromise=new Promise((function(t,r){e.waitingForPrackResolve=t,e.waitingForPrackReject=r})),this.waitingForPrackPromise},t.prototype.getOffer=function(e){return this.hasOffer=!0,this.getSessionDescriptionHandler().getDescription(e.sessionDescriptionHandlerOptions,e.modifiers).then((function(e){return l.Utils.fromBodyObj(e)}))},t.prototype.setAnswer=function(e,t){this.hasAnswer=!0;var r=this.getSessionDescriptionHandler();return r.hasDescription(e.contentType)?r.setDescription(e.content,t.sessionDescriptionHandlerOptions,t.modifiers):Promise.reject(new u.Exceptions.UnsupportedSessionDescriptionContentTypeError)},t.prototype.setOfferAndGetAnswer=function(e,t){this.hasOffer=!0,this.hasAnswer=!0;var r=this.getSessionDescriptionHandler();return r.hasDescription(e.contentType)?r.setDescription(e.content,t.sessionDescriptionHandlerOptions,t.modifiers).then((function(){return r.getDescription(t.sessionDescriptionHandlerOptions,t.modifiers)})).then((function(e){return l.Utils.fromBodyObj(e)})):Promise.reject(new u.Exceptions.UnsupportedSessionDescriptionContentTypeError)},t.prototype.getSessionDescriptionHandler=function(){var e=this.sessionDescriptionHandler=this.setupSessionDescriptionHandler();return this.emit("SessionDescriptionHandler-created",this.sessionDescriptionHandler),e},t}(g);t.InviteServerContext=f;var m=function(e){function t(t,r,i,n){void 0===i&&(i={}),void 0===n&&(n=[]);var a=this;if(!t.configuration.sessionDescriptionHandlerFactory)throw t.logger.warn("Can't build ISC without SDH Factory"),new Error("ICC Constructor Failed");i.params=i.params||{};var d=i.anonymous||!1,p=l.Utils.newTag();i.params.fromTag=p;var h=t.contact.toString({anonymous:d,outbound:d?!t.contact.tempGruu:!t.contact.pubGruu}),g=(i.extraHeaders||[]).slice();if(d&&t.configuration.uri&&(i.params.fromDisplayName="Anonymous",i.params.fromUri="sip:anonymous@anonymous.invalid",g.push("P-Preferred-Identity: "+t.configuration.uri.toString()),g.push("Privacy: id")),g.push("Contact: "+h),g.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),t.configuration.rel100===o.C.supported.REQUIRED&&g.push("Require: 100rel"),t.configuration.replaces===o.C.supported.REQUIRED&&g.push("Require: replaces"),i.extraHeaders=g,a=e.call(this,t.configuration.sessionDescriptionHandlerFactory)||this,s.ClientContext.initializer(a,t,o.C.INVITE,r,i),a.earlyMediaSessionDescriptionHandlers=new Map,a.type=c.TypeStrings.InviteClientContext,a.passedOptions=i,a.sessionDescriptionHandlerOptions=i.sessionDescriptionHandlerOptions||{},a.modifiers=n,a.inviteWithoutSdp=i.inviteWithoutSdp||!1,a.anonymous=i.anonymous||!1,a.renderbody=i.renderbody||void 0,a.rendertype=i.rendertype||"text/plain",a.fromTag=p,a.contact=h,a.status!==c.SessionStatus.STATUS_NULL)throw new u.Exceptions.InvalidStateError(a.status);return a.isCanceled=!1,a.received100=!1,a.method=o.C.INVITE,a.logger=t.getLogger("sip.inviteclientcontext"),t.applicants[a.toString()]=a,a.id=a.request.callId+a.fromTag,a.onInfo=i.onInfo,a.errorListener=a.onTransportError.bind(a),t.transport&&t.transport.on("transportError",a.errorListener),a}return i.__extends(t,e),t.prototype.receiveResponse=function(e){throw new Error("Unimplemented.")},t.prototype.send=function(){return this.sendInvite(),this},t.prototype.invite=function(){var e=this;return this.ua.sessions[this.id]=this,Promise.resolve().then((function(){e.isCanceled||e.status===c.SessionStatus.STATUS_TERMINATED||(e.inviteWithoutSdp?(e.renderbody&&e.rendertype&&(e.request.body={body:e.renderbody,contentType:e.rendertype}),e.status=c.SessionStatus.STATUS_INVITE_SENT,e.send()):(e.sessionDescriptionHandler=e.sessionDescriptionHandlerFactory(e,e.ua.configuration.sessionDescriptionHandlerFactoryOptions||{}),e.emit("SessionDescriptionHandler-created",e.sessionDescriptionHandler),e.sessionDescriptionHandler.getDescription(e.sessionDescriptionHandlerOptions,e.modifiers).then((function(t){e.isCanceled||e.status===c.SessionStatus.STATUS_TERMINATED||(e.hasOffer=!0,e.request.body=t,e.status=c.SessionStatus.STATUS_INVITE_SENT,e.send())}),(function(t){t.type===c.TypeStrings.SessionDescriptionHandlerError&&(e.logger.log(t.message),t.error&&e.logger.log(t.error)),e.status!==c.SessionStatus.STATUS_TERMINATED&&(e.failed(void 0,o.C.causes.WEBRTC_ERROR),e.terminated(void 0,o.C.causes.WEBRTC_ERROR))}))))})),this},t.prototype.cancel=function(e){if(void 0===e&&(e={}),this.status===c.SessionStatus.STATUS_TERMINATED||this.status===c.SessionStatus.STATUS_CONFIRMED)throw new u.Exceptions.InvalidStateError(this.status);if(this.isCanceled)throw new u.Exceptions.InvalidStateError(c.SessionStatus.STATUS_CANCELED);this.isCanceled=!0,this.logger.log("Canceling session");var t=l.Utils.getCancelReason(e.statusCode,e.reasonPhrase);return e.extraHeaders=(e.extraHeaders||[]).slice(),this.outgoingInviteRequest&&(this.logger.warn("Canceling session before it was created"),this.outgoingInviteRequest.cancel(t,e)),this.canceled()},t.prototype.terminate=function(e){return this.status===c.SessionStatus.STATUS_TERMINATED?this:(this.status===c.SessionStatus.STATUS_WAITING_FOR_ACK||this.status===c.SessionStatus.STATUS_CONFIRMED?this.bye(e):this.cancel(e),this)},t.prototype.sendInvite=function(){var e=this;this.outgoingInviteRequest=this.ua.userAgentCore.invite(this.request,{onAccept:function(t){return e.onAccept(t)},onProgress:function(t){return e.onProgress(t)},onRedirect:function(t){return e.onRedirect(t)},onReject:function(t){return e.onReject(t)},onTrying:function(t){return e.onTrying(t)}})},t.prototype.ackAndBye=function(e,t,r,i){if(!this.ua.userAgentCore)throw new Error("Method requires user agent core.");var n=[];r&&n.push("Reason: "+l.Utils.getReasonHeaderValue(r,i));var s=e.ack();this.emit("ack",s.message);var o=t.bye(void 0,{extraHeaders:n});this.emit("bye",o.message)},t.prototype.disposeEarlyMedia=function(){if(!this.earlyMediaSessionDescriptionHandlers)throw new Error("Early media session description handlers undefined.");this.earlyMediaSessionDescriptionHandlers.forEach((function(e){e.close()}))},t.prototype.onAccept=function(e){var t=this;if(!this.earlyMediaSessionDescriptionHandlers)throw new Error("Early media session description handlers undefined.");var r=e.message,i=e.session;if(this.session)this.ackAndBye(e,i);else{if(this.isCanceled)return this.ackAndBye(e,i),void this.emit("bye",this.request);switch(r.hasHeader("P-Asserted-Identity")&&(this.assertedIdentity=a.Grammar.nameAddrHeaderParse(r.getHeader("P-Asserted-Identity"))),this.session=i,this.session.delegate={onAck:function(e){return t.onAck(e)},onBye:function(e){return t.receiveRequest(e)},onInfo:function(e){return t.receiveRequest(e)},onInvite:function(e){return t.receiveRequest(e)},onNotify:function(e){return t.receiveRequest(e)},onPrack:function(e){return t.receiveRequest(e)},onRefer:function(e){return t.receiveRequest(e)}},i.signalingState){case a.SignalingState.Initial:case a.SignalingState.HaveLocalOffer:this.ackAndBye(e,i,400,"Missing session description"),this.failed(r,o.C.causes.BAD_MEDIA_DESCRIPTION);break;case a.SignalingState.HaveRemoteOffer:var n=this.sessionDescriptionHandlerFactory(this,this.ua.configuration.sessionDescriptionHandlerFactoryOptions||{});if(this.sessionDescriptionHandler=n,this.emit("SessionDescriptionHandler-created",this.sessionDescriptionHandler),!n.hasDescription(r.getHeader("Content-Type")||"")){this.ackAndBye(e,i,400,"Missing session description"),this.failed(r,o.C.causes.BAD_MEDIA_DESCRIPTION);break}this.hasOffer=!0,n.setDescription(r.body,this.sessionDescriptionHandlerOptions,this.modifiers).then((function(){return n.getDescription(t.sessionDescriptionHandlerOptions,t.modifiers)})).then((function(i){if(!t.isCanceled&&t.status!==c.SessionStatus.STATUS_TERMINATED){t.status=c.SessionStatus.STATUS_CONFIRMED,t.hasAnswer=!0;var n={contentDisposition:"session",contentType:i.contentType,content:i.body},s=e.ack({body:n});t.emit("ack",s.message),t.accepted(r)}})).catch((function(n){if(n.type!==c.TypeStrings.SessionDescriptionHandlerError)throw n;t.logger.warn("invalid description"),t.logger.warn(n.toString()),t.ackAndBye(e,i,488,"Invalid session description"),t.failed(r,o.C.causes.BAD_MEDIA_DESCRIPTION)}));break;case a.SignalingState.Stable:var s;if(this.renderbody&&this.rendertype&&(s={body:{contentDisposition:"render",contentType:this.rendertype,content:this.renderbody}}),this.hasOffer&&!this.hasAnswer){if(!this.sessionDescriptionHandler)throw new Error("Session description handler undefined.");var u=i.answer;if(!u)throw new Error("Answer is undefined.");this.sessionDescriptionHandler.setDescription(u.content,this.sessionDescriptionHandlerOptions,this.modifiers).then((function(){t.hasAnswer=!0,t.status=c.SessionStatus.STATUS_CONFIRMED;var i=e.ack(s);t.emit("ack",i.message),t.accepted(r)})).catch((function(n){t.logger.error(n),t.ackAndBye(e,i,488,"Not Acceptable Here"),t.failed(r,o.C.causes.BAD_MEDIA_DESCRIPTION)}))}else{if(this.sessionDescriptionHandler=this.earlyMediaSessionDescriptionHandlers.get(i.id),!this.sessionDescriptionHandler)throw new Error("Session description handler undefined.");this.earlyMediaSessionDescriptionHandlers.delete(i.id),this.hasOffer=!0,this.hasAnswer=!0,this.status=c.SessionStatus.STATUS_CONFIRMED;var d=e.ack();this.emit("ack",d.message),this.accepted(r)}break;case a.SignalingState.Closed:break;default:throw new Error("Unknown session signaling state.")}this.disposeEarlyMedia()}},t.prototype.onProgress=function(e){var t=this;if(!this.isCanceled){if(!this.outgoingInviteRequest)throw new Error("Outgoing INVITE request undefined.");if(!this.earlyMediaSessionDescriptionHandlers)throw new Error("Early media session description handlers undefined.");var r=e.message,i=e.session;if(this.status=c.SessionStatus.STATUS_1XX_RECEIVED,r.hasHeader("P-Asserted-Identity")&&(this.assertedIdentity=a.Grammar.nameAddrHeaderParse(r.getHeader("P-Asserted-Identity"))),!i)throw new Error("Session undefined.");var n=r.getHeader("require"),s=r.getHeader("rseq"),u=!!(n&&n.includes("100rel")&&s?Number(s):void 0),d=[];if(u&&d.push("RAck: "+r.getHeader("rseq")+" "+r.getHeader("cseq")),i.signalingState===a.SignalingState.Initial)return u&&(this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."),e.prack({extraHeaders:d})),void this.emit("progress",r);if(i.signalingState===a.SignalingState.HaveLocalOffer)return u&&e.prack({extraHeaders:d}),void this.emit("progress",r);if(i.signalingState===a.SignalingState.HaveRemoteOffer){if(!u)return void this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response.");var p=this.sessionDescriptionHandlerFactory(this,this.ua.configuration.sessionDescriptionHandlerFactoryOptions||{});return this.emit("SessionDescriptionHandler-created",p),this.earlyMediaSessionDescriptionHandlers.set(i.id,p),void p.setDescription(r.body,this.sessionDescriptionHandlerOptions,this.modifiers).then((function(){return p.getDescription(t.sessionDescriptionHandlerOptions,t.modifiers)})).then((function(i){var n={contentDisposition:"session",contentType:i.contentType,content:i.body};e.prack({extraHeaders:d,body:n}),t.status=c.SessionStatus.STATUS_EARLY_MEDIA,t.emit("progress",r)})).catch((function(e){t.status!==c.SessionStatus.STATUS_TERMINATED&&(t.failed(void 0,o.C.causes.WEBRTC_ERROR),t.terminated(void 0,o.C.causes.WEBRTC_ERROR))}))}return i.signalingState===a.SignalingState.Stable?(u&&e.prack({extraHeaders:d}),void this.emit("progress",r)):void 0}},t.prototype.onRedirect=function(e){this.disposeEarlyMedia();var t=e.message,r=t.statusCode,i=l.Utils.sipErrorCause(r||0);this.rejected(t,i),this.failed(t,i),this.terminated(t,i)},t.prototype.onReject=function(e){this.disposeEarlyMedia();var t=e.message,r=t.statusCode,i=l.Utils.sipErrorCause(r||0);this.rejected(t,i),this.failed(t,i),this.terminated(t,i)},t.prototype.onTrying=function(e){this.received100=!0,this.emit("progress",e.message)},t}(g);t.InviteClientContext=m},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(7),s=r(11),o=r(5),a=r(14),c=r(8),u=r(9),d=function(e){function t(t,r,i,n){void 0===n&&(n={});var o=e.call(this)||this;o.data={},o.method=s.C.SUBSCRIBE,o.body=void 0,o.type=c.TypeStrings.Subscription,o.ua=t,o.logger=t.getLogger("sip.subscription"),n.body&&(o.body={body:n.body,contentType:n.contentType?n.contentType:"application/sdp"});var a=t.normalizeTarget(r);if(!a)throw new TypeError("Invalid target: "+r);if(o.uri=a,o.event=i,void 0===n.expires?o.expires=3600:"number"!=typeof n.expires?(t.logger.warn('Option "expires" must be a number. Using default of 3600.'),o.expires=3600):o.expires=n.expires,o.extraHeaders=(n.extraHeaders||[]).slice(),o.context=o.initContext(),o.disposed=!1,o.request=o.context.message,!o.request.from)throw new Error("From undefined.");if(!o.request.to)throw new Error("From undefined.");return o.localIdentity=o.request.from,o.remoteIdentity=o.request.to,o.id=o.request.callId+o.request.from.parameters.tag+o.event,o.ua.subscriptions[o.id]=o,o}return i.__extends(t,e),t.prototype.dispose=function(){this.disposed||(this.retryAfterTimer&&(clearTimeout(this.retryAfterTimer),this.retryAfterTimer=void 0),this.context.dispose(),this.disposed=!0,delete this.ua.subscriptions[this.id])},t.prototype.on=function(t,r){return e.prototype.on.call(this,t,r)},t.prototype.emit=function(t){for(var r=[],i=1;i0?(e.accept(),i.emit("notify",{request:e.message})):e.reject({statusCode:481})},onRefer:function(e){i.logger.log("Received an out of dialog refer"),i.configuration.allowOutOfDialogRefers||e.reject({statusCode:405}),i.logger.log("Allow out of dialog refers is enabled on the UA");var t=new h.ReferServerContext(i,e);i.listeners("outOfDialogReferRequested").length?i.emit("outOfDialogReferRequested",t):(i.logger.log("No outOfDialogReferRequest listeners, automatically accepting and following the out of dialog refer"),t.accept({followRefer:!0}))},onSubscribe:function(e){i.emit("subscribe",e)}};return i.userAgentCore=new a.UserAgentCore(u,d),i.registerContext=new l.RegisterContext(i,r.registerOptions),i.registerContext.on("failed",i.emit.bind(i,"registrationFailed")),i.registerContext.on("registered",i.emit.bind(i,"registered")),i.registerContext.on("unregistered",i.emit.bind(i,"unregistered")),i.configuration.autostart&&i.start(),i}return i.__extends(t,e),t.prototype.register=function(e){return void 0===e&&(e={}),e.register&&(this.configuration.register=!0),this.registerContext.register(e),this},t.prototype.unregister=function(e){var t=this;return this.configuration.register=!1,this.transport.afterConnected((function(){t.registerContext.unregister(e)})),this},t.prototype.isRegistered=function(){return this.registerContext.registered},t.prototype.invite=function(e,t,r){var i=this,n=new f.InviteClientContext(this,e,t,r);return this.transport.afterConnected((function(){n.invite(),i.emit("inviteSent",n)})),n},t.prototype.subscribe=function(e,t,r){var i=new m.Subscription(this,e,t,r);return this.transport.afterConnected((function(){return i.subscribe()})),i},t.prototype.publish=function(e,t,r,i){var n=new p.PublishContext(this,e,t,i);return this.transport.afterConnected((function(){n.publish(r)})),n},t.prototype.message=function(e,t,r){if(void 0===r&&(r={}),void 0===t)throw new TypeError("Not enough arguments");return r.contentType=r.contentType||"text/plain",r.body=t,this.request(o.C.MESSAGE,e,r)},t.prototype.request=function(e,t,r){var i=new s.ClientContext(this,e,t,r);return this.transport.afterConnected((function(){return i.send()})),i},t.prototype.stop=function(){if(this.logger.log("user requested closure..."),this.status===c.UAStatus.STATUS_USER_CLOSED)return this.logger.warn("UA already closed"),this;for(var e in this.logger.log("closing registerContext"),this.registerContext.close(),this.sessions)this.sessions[e]&&(this.logger.log("closing session "+e),this.sessions[e].terminate());for(var t in this.subscriptions)this.subscriptions[t]&&(this.logger.log("unsubscribe "+t),this.subscriptions[t].unsubscribe());for(var r in this.publishers)this.publishers[r]&&(this.logger.log("unpublish "+r),this.publishers[r].close());for(var i in this.applicants)this.applicants[i]&&this.applicants[i].close();if(this.status=c.UAStatus.STATUS_USER_CLOSED,this.transport.disconnect(),this.userAgentCore.reset(),this.configuration.autostop){var n=!("undefined"==typeof chrome||!chrome.app||!chrome.app.runtime);"undefined"==typeof window||"function"!=typeof window.removeEventListener||n||window.removeEventListener("unload",this.unloadListener)}return this},t.prototype.start=function(){if(this.logger.log("user requested startup..."),this.status===c.UAStatus.STATUS_INIT?(this.status=c.UAStatus.STATUS_STARTING,this.setTransportListeners(),this.emit("transportCreated",this.transport),this.transport.connect()):this.status===c.UAStatus.STATUS_USER_CLOSED?(this.logger.log("resuming"),this.status=c.UAStatus.STATUS_READY,this.transport.connect()):this.status===c.UAStatus.STATUS_STARTING?this.logger.log("UA is in STARTING status, not opening new connection"):this.status===c.UAStatus.STATUS_READY?this.logger.log("UA is in READY status, not resuming"):this.logger.error("Connection is down. Auto-Recovery system is trying to connect"),this.configuration.autostop){var e=!("undefined"==typeof chrome||!chrome.app||!chrome.app.runtime);"undefined"==typeof window||"function"!=typeof window.addEventListener||e||window.addEventListener("unload",this.unloadListener)}return this},t.prototype.normalizeTarget=function(e){return v.Utils.normalizeTarget(e,this.configuration.hostportParams)},t.prototype.getLogger=function(e,t){return this.log.getLogger(e,t)},t.prototype.getLoggerFactory=function(){return this.log},t.prototype.getSupportedResponseOptions=function(){var e=[];(this.contact.pubGruu||this.contact.tempGruu)&&e.push("gruu"),this.configuration.rel100===o.C.supported.SUPPORTED&&e.push("100rel"),this.configuration.replaces===o.C.supported.SUPPORTED&&e.push("replaces"),e.push("outbound"),e=e.concat(this.configuration.extraSupported||[]);var t=this.configuration.hackAllowUnregisteredOptionTags||!1,r={};return e=e.filter((function(e){var i=o.C.OPTION_TAGS[e],n=!r[e];return r[e]=!0,(i||t)&&n}))},t.prototype.findSession=function(e){return this.sessions[e.callId+e.fromTag]||this.sessions[e.callId+e.toTag]||void 0},t.prototype.on=function(t,r){return e.prototype.on.call(this,t,r)},t.prototype.onTransportError=function(){this.status!==c.UAStatus.STATUS_USER_CLOSED&&(this.error&&this.error===t.C.NETWORK_ERROR||(this.status=c.UAStatus.STATUS_NOT_READY,this.error=t.C.NETWORK_ERROR))},t.prototype.setTransportListeners=function(){var e=this;this.transport.on("connected",(function(){return e.onTransportConnected()})),this.transport.on("message",(function(t){return e.onTransportReceiveMsg(t)})),this.transport.on("transportError",(function(){return e.onTransportError()}))},t.prototype.onTransportConnected=function(){var e=this;this.configuration.register&&Promise.resolve().then((function(){return e.registerContext.register()}))},t.prototype.onTransportReceiveMsg=function(e){var t=this,r=d.Parser.parseMessage(e,this.getLogger("sip.parser"));if(r)if(this.status===c.UAStatus.STATUS_USER_CLOSED&&r instanceof a.IncomingRequestMessage)this.logger.warn("UA received message when status = USER_CLOSED - aborting");else{var i=function(){for(var e=0,i=["from","to","call_id","cseq","via"];e1)return void this.logger.warn("More than one Via header field present in the response. Dropping.");if(r.via.host!==this.configuration.viaHost||void 0!==r.via.port)return void this.logger.warn("Via sent-by in the response does not match UA Via host value. Dropping.");var s;n=v.Utils.str_utf8_length(r.body);if((s=r.getHeader("content-length"))&&n"}};var h={};for(var n in r)r.hasOwnProperty(n)&&(h[n]=r[n]);for(var n in Object.assign(this.configuration,h),this.logger.log("configuration parameters after validation:"),r)if(r.hasOwnProperty(n))switch(n){case"uri":case"sessionDescriptionHandlerFactory":this.logger.log("\xb7 "+n+": "+r[n]);break;case"password":this.logger.log("\xb7 "+n+": NOT SHOWN");break;case"transportConstructor":this.logger.log("\xb7 "+n+": "+r[n].name);break;default:this.logger.log("\xb7 "+n+": "+JSON.stringify(r[n]))}},t.prototype.getConfigurationCheck=function(){return{mandatory:{},optional:{uri:function(e){/^sip:/i.test(e)||(e=o.C.SIP+":"+e);var t=a.Grammar.URIParse(e);return t&&t.user?t:void 0},transportConstructor:function(e){if(e instanceof Function)return e},transportOptions:function(e){if("object"==typeof e)return e},authorizationUser:function(e){return-1===a.Grammar.parse('"'+e+'"',"quoted_string")?void 0:e},displayName:function(e){return-1===a.Grammar.parse('"'+e+'"',"displayName")?void 0:e},dtmfType:function(e){switch(e){case o.C.dtmfType.RTP:return o.C.dtmfType.RTP;case o.C.dtmfType.INFO:default:return o.C.dtmfType.INFO}},hackViaTcp:function(e){if("boolean"==typeof e)return e},hackIpInContact:function(e){return"boolean"==typeof e?e:"string"==typeof e&&-1!==a.Grammar.parse(e,"host")?e:void 0},hackWssInTransport:function(e){if("boolean"==typeof e)return e},hackAllowUnregisteredOptionTags:function(e){if("boolean"==typeof e)return e},contactTransport:function(e){if("string"==typeof e)return e},extraSupported:function(e){if(e instanceof Array){for(var t=0,r=e;t0)return t}},password:function(e){return String(e)},rel100:function(e){return e===o.C.supported.REQUIRED?o.C.supported.REQUIRED:e===o.C.supported.SUPPORTED?o.C.supported.SUPPORTED:o.C.supported.UNSUPPORTED},replaces:function(e){return e===o.C.supported.REQUIRED?o.C.supported.REQUIRED:e===o.C.supported.SUPPORTED?o.C.supported.SUPPORTED:o.C.supported.UNSUPPORTED},register:function(e){if("boolean"==typeof e)return e},registerOptions:function(e){if("object"==typeof e)return e},usePreloadedRoute:function(e){if("boolean"==typeof e)return e},userAgentString:function(e){if("string"==typeof e)return e},autostart:function(e){if("boolean"==typeof e)return e},autostop:function(e){if("boolean"==typeof e)return e},sessionDescriptionHandlerFactory:function(e){if(e instanceof Function)return e},sessionDescriptionHandlerFactoryOptions:function(e){if("object"==typeof e)return e},authenticationFactory:this.checkAuthenticationFactory,allowLegacyNotifications:function(e){if("boolean"==typeof e)return e},custom:function(e){if("object"==typeof e)return e},contactName:function(e){if("string"==typeof e)return e},experimentalFeatures:function(e){if("boolean"==typeof e)return e}}}},t.C={STATUS_INIT:0,STATUS_STARTING:1,STATUS_READY:2,STATUS_USER_CLOSED:3,STATUS_NOT_READY:4,CONFIGURATION_ERROR:1,NETWORK_ERROR:2,ALLOWED_METHODS:["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"],ACCEPTED_BODY_TYPES:["application/sdp","application/dtmf-relay"],MAX_FORWARDS:70,TAG_LENGTH:10},t}(n.EventEmitter);function E(e){if(!(e.configuration.uri instanceof a.URI))throw new Error("Configuration URI not instance of URI.");var t=e.configuration.uri,r=e.contact,i=e.configuration.displayName?e.configuration.displayName:"",n=!!e.configuration.hackViaTcp,s=e.configuration.usePreloadedRoute&&e.transport.server&&e.transport.server.sipUri?[e.transport.server.sipUri]:[],c=e.configuration.sipjsId||v.Utils.createRandomToken(5),u=[];u.push("outbound"),e.configuration.rel100===o.C.supported.SUPPORTED&&u.push("100rel"),e.configuration.replaces===o.C.supported.SUPPORTED&&u.push("replaces"),e.configuration.extraSupported&&u.push.apply(u,e.configuration.extraSupported),e.configuration.hackAllowUnregisteredOptionTags||(u=u.filter((function(e){return o.C.OPTION_TAGS[e]}))),u=Array.from(new Set(u));var d=e.getSupportedResponseOptions(),p=e.configuration.userAgentString||"sipjs";if(!e.configuration.viaHost)throw new Error("Configuration via host undefined");var h=!!e.configuration.forceRport,l=e.configuration.viaHost;return{aor:t,contact:r,displayName:i,hackViaTcp:n,loggerFactory:e.getLoggerFactory(),routeSet:s,sipjsId:c,supportedOptionTags:u,supportedOptionTagsResponse:d,userAgentHeaderFieldValue:p,viaForceRport:h,viaHost:l,authenticationFactory:function(){if(e.configuration.authenticationFactory)return e.configuration.authenticationFactory(e)},transportAccessor:function(){return e.transport}}}t.UA=y,function(e){!function(e){e.RTP="rtp",e.INFO="info"}(e.DtmfType||(e.DtmfType={}))}(y=t.UA||(t.UA={})),t.UA=y,t.makeUserAgentCoreConfigurationFromUA=E},,,,,function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(5);t.DigestAuthentication=n.DigestAuthentication,t.Grammar=n.Grammar,t.IncomingRequest=n.IncomingRequestMessage,t.IncomingResponse=n.IncomingResponseMessage,t.LoggerFactory=n.LoggerFactory,t.NameAddrHeader=n.NameAddrHeader,t.OutgoingRequest=n.OutgoingRequestMessage,t.Timers=n.Timers,t.Transport=n.Transport,t.URI=n.URI;var s=r(51);t.ClientContext=s.ClientContext;var o=r(11);t.C=o.C;var a=r(8);t.DialogStatus=a.DialogStatus,t.SessionStatus=a.SessionStatus,t.TypeStrings=a.TypeStrings,t.UAStatus=a.UAStatus;var c=r(12);t.Exceptions=c.Exceptions;var u=r(89);t.Parser=u.Parser;var d=r(100);t.PublishContext=d.PublishContext;var p=r(96);t.ReferClientContext=p.ReferClientContext,t.ReferServerContext=p.ReferServerContext;var h=r(101);t.RegisterContext=h.RegisterContext;var l=r(90);t.ServerContext=l.ServerContext;var g=r(102);t.InviteClientContext=g.InviteClientContext,t.InviteServerContext=g.InviteServerContext,t.Session=g.Session;var f=r(103);t.Subscription=f.Subscription;var m=r(1),v={InviteClientTransaction:m.InviteClientTransaction,InviteServerTransaction:m.InviteServerTransaction,NonInviteClientTransaction:m.NonInviteClientTransaction,NonInviteServerTransaction:m.NonInviteServerTransaction};t.Transactions=v;var S=r(104);t.makeUserAgentCoreConfigurationFromUA=S.makeUserAgentCoreConfigurationFromUA,t.UA=S.UA;var T=r(9);t.Utils=T.Utils;var y=i.__importStar(r(111));t.Web=y;var E=o.C.version;t.version=E;t.name="sip.js";var b=i.__importStar(r(5));t.Core=b},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=r(0),n=r(7),s=r(11),o=r(8),a=r(12),c=r(9),u=function(e){function t(t,r,i){void 0===i&&(i={});var n=e.call(this)||this;if(n.C={MIN_DURATION:70,MAX_DURATION:6e3,DEFAULT_DURATION:100,MIN_INTER_TONE_GAP:50,DEFAULT_INTER_TONE_GAP:500},n.type=o.TypeStrings.DTMF,void 0===r)throw new TypeError("Not enough arguments");if(n.logger=t.ua.getLogger("sip.invitecontext.dtmf",t.id),n.owner=t,"string"==typeof r)r=r.toUpperCase();else{if("number"!=typeof r)throw new TypeError("Invalid tone: "+r);r=r.toString()}if(!r.match(/^[0-9A-D#*]$/))throw new TypeError("Invalid tone: "+r);n.tone=r;var s=i.duration,a=i.interToneGap;if(s&&!c.Utils.isDecimal(s))throw new TypeError("Invalid tone duration: "+s);if(s?sn.C.MAX_DURATION?(n.logger.warn("'duration' value is greater than the maximum allowed, setting it to "+n.C.MAX_DURATION+" milliseconds"),s=n.C.MAX_DURATION):s=Math.abs(s):s=n.C.DEFAULT_DURATION,n.duration=s,a&&!c.Utils.isDecimal(a))throw new TypeError("Invalid interToneGap: "+a);return a?a-1&&n.indexOf("chrome")<0?s=!0:n.indexOf("firefox")>-1&&n.indexOf("chrome")<0&&(c=!0);var u={};return s&&(u.modifiers=[a.stripG722]),c&&(u.alwaysAcquireMediaFirst=!0),r.options.ua.uri?r.anonymous=!1:r.anonymous=!0,r.ua=new o.UA({uri:r.options.ua.uri,authorizationUser:r.options.ua.authorizationUser,password:r.options.ua.password,displayName:r.options.ua.displayName,userAgentString:r.options.ua.userAgentString,register:!0,sessionDescriptionHandlerFactoryOptions:u,transportOptions:{traceSip:r.options.ua.traceSip,wsServers:r.options.ua.wsServers}}),r.state=i.STATUS_NULL,r.logger=r.ua.getLogger("sip.simple"),r.ua.on("registered",(function(){r.emit("registered",r.ua)})),r.ua.on("unregistered",(function(){r.emit("unregistered",r.ua)})),r.ua.on("registrationFailed",(function(){r.emit("unregistered",r.ua)})),r.ua.on("invite",(function(e){if(r.state!==i.STATUS_NULL&&r.state!==i.STATUS_COMPLETED)return r.logger.warn("Rejecting incoming call. Simple only supports 1 call at a time"),void e.reject();r.session=e,r.setupSession(),r.emit("ringing",r.session)})),r.ua.on("message",(function(e){r.emit("message",e)})),r}return n.__extends(t,e),t.prototype.call=function(e){if(this.ua&&this.checkRegistration()){if(this.state===i.STATUS_NULL||this.state===i.STATUS_COMPLETED)return this.options.media.remote.audio&&(this.options.media.remote.audio.autoplay=!0),this.options.media.remote.video&&(this.options.media.remote.video.autoplay=!0),this.options.media.local&&this.options.media.local.video&&(this.options.media.local.video.autoplay=!0,this.options.media.local.video.volume=0),this.session=this.ua.invite(e,{sessionDescriptionHandlerOptions:{constraints:{audio:this.audio,video:this.video}}}),this.setupSession(),this.session;this.logger.warn("Cannot make more than a single call with Simple")}else this.logger.warn("A registered UA is required for calling")},t.prototype.answer=function(){if(this.state===i.STATUS_NEW||this.state===i.STATUS_CONNECTING)return this.options.media.remote.audio&&(this.options.media.remote.audio.autoplay=!0),this.options.media.remote.video&&(this.options.media.remote.video.autoplay=!0),this.session.accept({sessionDescriptionHandlerOptions:{constraints:{audio:this.audio,video:this.video}}});this.logger.warn("No call to answer")},t.prototype.reject=function(){if(this.state===i.STATUS_NEW||this.state===i.STATUS_CONNECTING)return this.session.reject();this.logger.warn("Call is already answered")},t.prototype.hangup=function(){if(this.state===i.STATUS_CONNECTED||this.state===i.STATUS_CONNECTING||this.state===i.STATUS_NEW)return this.state!==i.STATUS_CONNECTED?this.session.cancel():this.session?this.session.bye():void 0;this.logger.warn("No active call to hang up on")},t.prototype.hold=function(){if(this.state===i.STATUS_CONNECTED&&this.session&&!this.session.localHold)return this.mute(),this.logger.log("Placing session on hold"),this.session.hold();this.logger.warn("Cannot put call on hold")},t.prototype.unhold=function(){if(this.state===i.STATUS_CONNECTED&&this.session&&this.session.localHold)return this.unmute(),this.logger.log("Placing call off hold"),this.session.unhold();this.logger.warn("Cannot unhold a call that is not on hold")},t.prototype.mute=function(){this.state===i.STATUS_CONNECTED?(this.logger.log("Muting Audio"),this.toggleMute(!0),this.emit("mute",this)):this.logger.warn("An acitve call is required to mute audio")},t.prototype.unmute=function(){this.state===i.STATUS_CONNECTED?(this.logger.log("Unmuting Audio"),this.toggleMute(!1),this.emit("unmute",this)):this.logger.warn("An active call is required to unmute audio")},t.prototype.sendDTMF=function(e){this.state===i.STATUS_CONNECTED&&this.session?(this.logger.log("Sending DTMF tone: "+e),this.session.dtmf(e)):this.logger.warn("An active call is required to send a DTMF tone")},t.prototype.message=function(e,t){this.ua&&this.checkRegistration()?e&&t?this.ua.message(e,t):this.logger.warn("A destination and message are required to send a message"):this.logger.warn("A registered UA is required to send a message")},t.prototype.checkRegistration=function(){return this.anonymous||this.ua&&this.ua.isRegistered()},t.prototype.setupRemoteMedia=function(){var e=this;if(this.session){var t,r=this.session.sessionDescriptionHandler.peerConnection;r.getReceivers?(t=new MediaStream,r.getReceivers().forEach((function(e){var r=e.track;r&&t.addTrack(r)}))):t=r.getRemoteStreams()[0],this.video?(this.options.media.remote.video.srcObject=t,this.options.media.remote.video.play().catch((function(){e.logger.log("play was rejected")}))):this.audio&&(this.options.media.remote.audio.srcObject=t,this.options.media.remote.audio.play().catch((function(){e.logger.log("play was rejected")})))}else this.logger.warn("No session to set remote media on")},t.prototype.setupLocalMedia=function(){if(this.session){if(this.video&&this.options.media.local&&this.options.media.local.video){var e,t=this.session.sessionDescriptionHandler.peerConnection;t.getSenders?(e=new MediaStream,t.getSenders().forEach((function(t){var r=t.track;r&&"video"===r.kind&&e.addTrack(r)}))):e=t.getLocalStreams()[0],this.options.media.local.video.srcObject=e,this.options.media.local.video.volume=0,this.options.media.local.video.play()}}else this.logger.warn("No session to set local media on")},t.prototype.cleanupMedia=function(){this.video&&(this.options.media.remote.video.srcObject=null,this.options.media.remote.video.pause(),this.options.media.local&&this.options.media.local.video&&(this.options.media.local.video.srcObject=null,this.options.media.local.video.pause())),this.audio&&(this.options.media.remote.audio.srcObject=null,this.options.media.remote.audio.pause())},t.prototype.setupSession=function(){var e=this;this.session?(this.state=i.STATUS_NEW,this.emit("new",this.session),this.session.on("progress",(function(){return e.onProgress()})),this.session.on("accepted",(function(){return e.onAccepted()})),this.session.on("rejected",(function(){return e.onEnded()})),this.session.on("failed",(function(){return e.onFailed()})),this.session.on("terminated",(function(){return e.onEnded()}))):this.logger.warn("No session to set up")},t.prototype.destroyMedia=function(){this.session&&this.session.sessionDescriptionHandler&&this.session.sessionDescriptionHandler.close()},t.prototype.toggleMute=function(e){if(this.session){var t=this.session.sessionDescriptionHandler.peerConnection;t.getSenders?t.getSenders().forEach((function(t){t.track&&(t.track.enabled=!e)})):t.getLocalStreams().forEach((function(t){t.getAudioTracks().forEach((function(t){t.enabled=!e})),t.getVideoTracks().forEach((function(t){t.enabled=!e}))}))}else this.logger.warn("No session to toggle mute")},t.prototype.onAccepted=function(){var e=this;this.session?(this.state=i.STATUS_CONNECTED,this.emit("connected",this.session),this.setupLocalMedia(),this.setupRemoteMedia(),this.session.sessionDescriptionHandler&&(this.session.sessionDescriptionHandler.on("addTrack",(function(){e.logger.log("A track has been added, triggering new remoteMedia setup"),e.setupRemoteMedia()})),this.session.sessionDescriptionHandler.on("addStream",(function(){e.logger.log("A stream has been added, trigger new remoteMedia setup"),e.setupRemoteMedia()}))),this.session.on("dtmf",(function(t,r){e.emit("dtmf",r.tone)})),this.session.on("bye",(function(){return e.onEnded()}))):this.logger.warn("No session for accepting")},t.prototype.onProgress=function(){this.state=i.STATUS_CONNECTING,this.emit("connecting",this.session)},t.prototype.onFailed=function(){this.onEnded()},t.prototype.onEnded=function(){this.state=i.STATUS_COMPLETED,this.emit("ended",this.session),this.cleanupMedia()},t.C=i,t}(s.EventEmitter);t.Simple=c}])})); \ No newline at end of file diff --git a/lib/ClientContext.d.ts b/lib/ClientContext.d.ts deleted file mode 100644 index 1ca7894be..000000000 --- a/lib/ClientContext.d.ts +++ /dev/null @@ -1,36 +0,0 @@ -/// -import { EventEmitter } from "events"; -import { IncomingResponseMessage, Logger, NameAddrHeader, OutgoingRequestMessage, URI } from "./core"; -import { TypeStrings } from "./Enums"; -import { BodyObj } from "./session-description-handler"; -import { UA } from "./UA"; -export declare namespace ClientContext { - interface Options { - body?: string; - contentType?: string; - extraHeaders?: Array; - params?: { - fromUri?: string | URI; - toUri?: string | URI; - toDisplayName?: string; - }; - } -} -export declare class ClientContext extends EventEmitter { - static initializer(objToConstruct: ClientContext, ua: UA, method: string, originalTarget: string | URI, options?: ClientContext.Options): void; - type: TypeStrings; - data: any; - ua: UA; - logger: Logger; - request: OutgoingRequestMessage; - method: string; - body: BodyObj | undefined; - localIdentity: NameAddrHeader; - remoteIdentity: NameAddrHeader; - constructor(ua: UA, method: string, target: string | URI, options?: ClientContext.Options); - send(): this; - receiveResponse(response: IncomingResponseMessage): void; - onRequestTimeout(): void; - onTransportError(): void; -} -//# sourceMappingURL=ClientContext.d.ts.map \ No newline at end of file diff --git a/lib/ClientContext.d.ts.map b/lib/ClientContext.d.ts.map deleted file mode 100644 index 61082e43b..000000000 --- a/lib/ClientContext.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"ClientContext.d.ts","sourceRoot":"","sources":["../src/ClientContext.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAGtC,OAAO,EAAiB,uBAAuB,EAAE,MAAM,EAAE,cAAc,EAAE,sBAAsB,EAAE,GAAG,EAAE,MAAM,QAAQ,CAAC;AACrH,OAAO,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AACtC,OAAO,EAAE,OAAO,EAAE,MAAM,+BAA+B,CAAC;AACxD,OAAO,EAAE,EAAE,EAAE,MAAM,MAAM,CAAC;AAG1B,yBAAiB,aAAa,CAAC;IAC7B,UAAiB,OAAO;QACtB,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,WAAW,CAAC,EAAE,MAAM,CAAC;QACrB,YAAY,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;QAC7B,MAAM,CAAC,EAAE;YACP,OAAO,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC;YACvB,KAAK,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC;YACrB,aAAa,CAAC,EAAE,MAAM,CAAC;SACxB,CAAC;KACH;CACF;AAED,qBAAa,aAAc,SAAQ,YAAY;WAC/B,WAAW,CACvB,cAAc,EAAE,aAAa,EAC7B,EAAE,EAAE,EAAE,EACN,MAAM,EAAE,MAAM,EACd,cAAc,EAAE,MAAM,GAAG,GAAG,EAC5B,OAAO,CAAC,EAAE,aAAa,CAAC,OAAO,GAC9B,IAAI;IAgFA,IAAI,EAAG,WAAW,CAAC;IACnB,IAAI,EAAE,GAAG,CAAM;IAIf,EAAE,EAAG,EAAE,CAAC;IACR,MAAM,EAAG,MAAM,CAAC;IAChB,OAAO,EAAG,sBAAsB,CAAC;IACjC,MAAM,EAAG,MAAM,CAAC;IAChB,IAAI,EAAG,OAAO,GAAG,SAAS,CAAC;IAC3B,aAAa,EAAG,cAAc,CAAC;IAC/B,cAAc,EAAG,cAAc,CAAC;gBAE3B,EAAE,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,GAAG,EAAE,OAAO,CAAC,EAAE,aAAa,CAAC,OAAO;IAMlF,IAAI,IAAI,IAAI;IAWZ,eAAe,CAAC,QAAQ,EAAE,uBAAuB,GAAG,IAAI;IA0BxD,gBAAgB,IAAI,IAAI;IAIxB,gBAAgB,IAAI,IAAI;CAGhC"} \ No newline at end of file diff --git a/lib/ClientContext.js b/lib/ClientContext.js deleted file mode 100644 index 862047dea..000000000 --- a/lib/ClientContext.js +++ /dev/null @@ -1,123 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var events_1 = require("events"); -var Constants_1 = require("./Constants"); -var core_1 = require("./core"); -var Enums_1 = require("./Enums"); -var Utils_1 = require("./Utils"); -var ClientContext = /** @class */ (function (_super) { - tslib_1.__extends(ClientContext, _super); - function ClientContext(ua, method, target, options) { - var _this = _super.call(this) || this; - _this.data = {}; - ClientContext.initializer(_this, ua, method, target, options); - return _this; - } - ClientContext.initializer = function (objToConstruct, ua, method, originalTarget, options) { - objToConstruct.type = Enums_1.TypeStrings.ClientContext; - // Validate arguments - if (originalTarget === undefined) { - throw new TypeError("Not enough arguments"); - } - objToConstruct.ua = ua; - objToConstruct.logger = ua.getLogger("sip.clientcontext"); - objToConstruct.method = method; - var target = ua.normalizeTarget(originalTarget); - if (!target) { - throw new TypeError("Invalid target: " + originalTarget); - } - var fromURI = ua.userAgentCore.configuration.aor; - if (options && options.params && options.params.fromUri) { - fromURI = - (typeof options.params.fromUri === "string") ? - core_1.Grammar.URIParse(options.params.fromUri) : - options.params.fromUri; - if (!fromURI) { - throw new TypeError("Invalid from URI: " + options.params.fromUri); - } - } - var toURI = target; - if (options && options.params && options.params.toUri) { - toURI = - (typeof options.params.toUri === "string") ? - core_1.Grammar.URIParse(options.params.toUri) : - options.params.toUri; - if (!toURI) { - throw new TypeError("Invalid to URI: " + options.params.toUri); - } - } - /* Options - * - extraHeaders - * - params - * - contentType - * - body - */ - options = Object.create(options || Object.prototype); - options = options || {}; - var extraHeaders = (options.extraHeaders || []).slice(); - var params = options.params || {}; - var bodyObj; - if (options.body) { - bodyObj = { - body: options.body, - contentType: options.contentType ? options.contentType : "application/sdp" - }; - objToConstruct.body = bodyObj; - } - var body; - if (bodyObj) { - body = Utils_1.Utils.fromBodyObj(bodyObj); - } - // Build the request - objToConstruct.request = ua.userAgentCore.makeOutgoingRequestMessage(method, target, fromURI, toURI, params, extraHeaders, body); - /* Set other properties from the request */ - if (objToConstruct.request.from) { - objToConstruct.localIdentity = objToConstruct.request.from; - } - if (objToConstruct.request.to) { - objToConstruct.remoteIdentity = objToConstruct.request.to; - } - }; - ClientContext.prototype.send = function () { - var _this = this; - this.ua.userAgentCore.request(this.request, { - onAccept: function (response) { return _this.receiveResponse(response.message); }, - onProgress: function (response) { return _this.receiveResponse(response.message); }, - onRedirect: function (response) { return _this.receiveResponse(response.message); }, - onReject: function (response) { return _this.receiveResponse(response.message); }, - onTrying: function (response) { return _this.receiveResponse(response.message); } - }); - return this; - }; - ClientContext.prototype.receiveResponse = function (response) { - var statusCode = response.statusCode || 0; - var cause = Utils_1.Utils.getReasonPhrase(statusCode); - switch (true) { - case /^1[0-9]{2}$/.test(statusCode.toString()): - this.emit("progress", response, cause); - break; - case /^2[0-9]{2}$/.test(statusCode.toString()): - if (this.ua.applicants[this.toString()]) { - delete this.ua.applicants[this.toString()]; - } - this.emit("accepted", response, cause); - break; - default: - if (this.ua.applicants[this.toString()]) { - delete this.ua.applicants[this.toString()]; - } - this.emit("rejected", response, cause); - this.emit("failed", response, cause); - break; - } - }; - ClientContext.prototype.onRequestTimeout = function () { - this.emit("failed", undefined, Constants_1.C.causes.REQUEST_TIMEOUT); - }; - ClientContext.prototype.onTransportError = function () { - this.emit("failed", undefined, Constants_1.C.causes.CONNECTION_ERROR); - }; - return ClientContext; -}(events_1.EventEmitter)); -exports.ClientContext = ClientContext; diff --git a/lib/Constants.d.ts b/lib/Constants.d.ts deleted file mode 100644 index 4f3ac16f7..000000000 --- a/lib/Constants.d.ts +++ /dev/null @@ -1,64 +0,0 @@ -export declare namespace C { - const version = "0.15.5"; - const USER_AGENT: string; - const SIP = "sip"; - const SIPS = "sips"; - enum causes { - CONNECTION_ERROR = "Connection Error", - INTERNAL_ERROR = "Internal Error", - REQUEST_TIMEOUT = "Request Timeout", - SIP_FAILURE_CODE = "SIP Failure Code", - ADDRESS_INCOMPLETE = "Address Incomplete", - AUTHENTICATION_ERROR = "Authentication Error", - BUSY = "Busy", - DIALOG_ERROR = "Dialog Error", - INCOMPATIBLE_SDP = "Incompatible SDP", - NOT_FOUND = "Not Found", - REDIRECTED = "Redirected", - REJECTED = "Rejected", - UNAVAILABLE = "Unavailable", - BAD_MEDIA_DESCRIPTION = "Bad Media Description", - CANCELED = "Canceled", - EXPIRES = "Expires", - NO_ACK = "No ACK", - NO_ANSWER = "No Answer", - NO_PRACK = "No PRACK", - RTP_TIMEOUT = "RTP Timeout", - USER_DENIED_MEDIA_ACCESS = "User Denied Media Access", - WEBRTC_ERROR = "WebRTC Error", - WEBRTC_NOT_SUPPORTED = "WebRTC Not Supported" - } - enum supported { - REQUIRED = "required", - SUPPORTED = "supported", - UNSUPPORTED = "none" - } - const SIP_ERROR_CAUSES: { - [name: string]: Array; - }; - const ACK = "ACK"; - const BYE = "BYE"; - const CANCEL = "CANCEL"; - const INFO = "INFO"; - const INVITE = "INVITE"; - const MESSAGE = "MESSAGE"; - const NOTIFY = "NOTIFY"; - const OPTIONS = "OPTIONS"; - const REGISTER = "REGISTER"; - const UPDATE = "UPDATE"; - const SUBSCRIBE = "SUBSCRIBE"; - const PUBLISH = "PUBLISH"; - const REFER = "REFER"; - const PRACK = "PRACK"; - const REASON_PHRASE: { - [code: number]: string; - }; - const OPTION_TAGS: { - [option: string]: boolean; - }; - enum dtmfType { - INFO = "info", - RTP = "rtp" - } -} -//# sourceMappingURL=Constants.d.ts.map \ No newline at end of file diff --git a/lib/Constants.d.ts.map b/lib/Constants.d.ts.map deleted file mode 100644 index f19a04076..000000000 --- a/lib/Constants.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"Constants.d.ts","sourceRoot":"","sources":["../src/Constants.ts"],"names":[],"mappings":"AAEA,yBAAiB,CAAC,CAAC;IACV,MAAM,OAAO,WAAkB,CAAC;IAChC,MAAM,UAAU,QAA+B,CAAC;IAGhD,MAAM,GAAG,QAAQ,CAAC;IAClB,MAAM,IAAI,SAAS,CAAC;IAG3B,KAAY,MAAM;QAEhB,gBAAgB,qBAA6B;QAC7C,cAAc,mBAA6B;QAC3C,eAAe,oBAA6B;QAC5C,gBAAgB,qBAA6B;QAG7C,kBAAkB,uBAA6B;QAC/C,oBAAoB,yBAA6B;QACjD,IAAI,SAA6B;QACjC,YAAY,iBAA6B;QACzC,gBAAgB,qBAA6B;QAC7C,SAAS,cAA6B;QACtC,UAAU,eAA6B;QACvC,QAAQ,aAA6B;QACrC,WAAW,gBAA6B;QAIxC,qBAAqB,0BAA6B;QAClD,QAAQ,aAA6B;QACrC,OAAO,YAA6B;QACpC,MAAM,WAA6B;QACnC,SAAS,cAA6B;QACtC,QAAQ,aAA6B;QACrC,WAAW,gBAA6B;QACxC,wBAAwB,6BAA6B;QACrD,YAAY,iBAA6B;QACzC,oBAAoB,yBAA6B;KAClD;IAED,KAAY,SAAS;QACnB,QAAQ,aAAsB;QAC9B,SAAS,cAAsB;QAC/B,WAAW,SAAe;KAC3B;IAEM,MAAM,gBAAgB,EAAE;QAAC,CAAC,IAAI,EAAE,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,CAAA;KAS5D,CAAC;IAGK,MAAM,GAAG,QAAQ,CAAC;IAClB,MAAM,GAAG,QAAQ,CAAC;IAClB,MAAM,MAAM,WAAW,CAAC;IACxB,MAAM,IAAI,SAAS,CAAC;IACpB,MAAM,MAAM,WAAW,CAAC;IACxB,MAAM,OAAO,YAAY,CAAC;IAC1B,MAAM,MAAM,WAAW,CAAC;IACxB,MAAM,OAAO,YAAY,CAAC;IAC1B,MAAM,QAAQ,aAAa,CAAC;IAC5B,MAAM,MAAM,WAAW,CAAC;IACxB,MAAM,SAAS,cAAc,CAAC;IAC9B,MAAM,OAAO,YAAY,CAAC;IAC1B,MAAM,KAAK,UAAU,CAAC;IACtB,MAAM,KAAK,UAAU,CAAC;IAMtB,MAAM,aAAa,EAAE;QAAC,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAA;KAwElD,CAAC;IAKK,MAAM,WAAW,EAAE;QAAC,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAA;KAkCnD,CAAC;IAEF,KAAY,QAAQ;QAClB,IAAI,SAAS;QACb,GAAG,QAAQ;KACZ;CACF"} \ No newline at end of file diff --git a/lib/Constants.js b/lib/Constants.js deleted file mode 100644 index cb0cb3cd4..000000000 --- a/lib/Constants.js +++ /dev/null @@ -1,192 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var version_1 = require("./version"); -var C; -(function (C) { - C.version = version_1.LIBRARY_VERSION; - C.USER_AGENT = "SIP.js/" + version_1.LIBRARY_VERSION; - // SIP scheme - C.SIP = "sip"; - C.SIPS = "sips"; - // End and Failure causes - var causes; - (function (causes) { - // Generic error causes - causes["CONNECTION_ERROR"] = "Connection Error"; - causes["INTERNAL_ERROR"] = "Internal Error"; - causes["REQUEST_TIMEOUT"] = "Request Timeout"; - causes["SIP_FAILURE_CODE"] = "SIP Failure Code"; - // SIP error causes - causes["ADDRESS_INCOMPLETE"] = "Address Incomplete"; - causes["AUTHENTICATION_ERROR"] = "Authentication Error"; - causes["BUSY"] = "Busy"; - causes["DIALOG_ERROR"] = "Dialog Error"; - causes["INCOMPATIBLE_SDP"] = "Incompatible SDP"; - causes["NOT_FOUND"] = "Not Found"; - causes["REDIRECTED"] = "Redirected"; - causes["REJECTED"] = "Rejected"; - causes["UNAVAILABLE"] = "Unavailable"; - // Session error causes - causes["BAD_MEDIA_DESCRIPTION"] = "Bad Media Description"; - causes["CANCELED"] = "Canceled"; - causes["EXPIRES"] = "Expires"; - causes["NO_ACK"] = "No ACK"; - causes["NO_ANSWER"] = "No Answer"; - causes["NO_PRACK"] = "No PRACK"; - causes["RTP_TIMEOUT"] = "RTP Timeout"; - causes["USER_DENIED_MEDIA_ACCESS"] = "User Denied Media Access"; - causes["WEBRTC_ERROR"] = "WebRTC Error"; - causes["WEBRTC_NOT_SUPPORTED"] = "WebRTC Not Supported"; - })(causes = C.causes || (C.causes = {})); - var supported; - (function (supported) { - supported["REQUIRED"] = "required"; - supported["SUPPORTED"] = "supported"; - supported["UNSUPPORTED"] = "none"; - })(supported = C.supported || (C.supported = {})); - C.SIP_ERROR_CAUSES = { - ADDRESS_INCOMPLETE: [484], - AUTHENTICATION_ERROR: [401, 407], - BUSY: [486, 600], - INCOMPATIBLE_SDP: [488, 606], - NOT_FOUND: [404, 604], - REDIRECTED: [300, 301, 302, 305, 380], - REJECTED: [403, 603], - UNAVAILABLE: [480, 410, 408, 430] - }; - // SIP Methods - C.ACK = "ACK"; - C.BYE = "BYE"; - C.CANCEL = "CANCEL"; - C.INFO = "INFO"; - C.INVITE = "INVITE"; - C.MESSAGE = "MESSAGE"; - C.NOTIFY = "NOTIFY"; - C.OPTIONS = "OPTIONS"; - C.REGISTER = "REGISTER"; - C.UPDATE = "UPDATE"; - C.SUBSCRIBE = "SUBSCRIBE"; - C.PUBLISH = "PUBLISH"; - C.REFER = "REFER"; - C.PRACK = "PRACK"; - /* SIP Response Reasons - * DOC: http://www.iana.org/assignments/sip-parameters - * Copied from https://github.com/versatica/OverSIP/blob/master/lib/oversip/sip/constants.rb#L7 - */ - C.REASON_PHRASE = { - 100: "Trying", - 180: "Ringing", - 181: "Call Is Being Forwarded", - 182: "Queued", - 183: "Session Progress", - 199: "Early Dialog Terminated", - 200: "OK", - 202: "Accepted", - 204: "No Notification", - 300: "Multiple Choices", - 301: "Moved Permanently", - 302: "Moved Temporarily", - 305: "Use Proxy", - 380: "Alternative Service", - 400: "Bad Request", - 401: "Unauthorized", - 402: "Payment Required", - 403: "Forbidden", - 404: "Not Found", - 405: "Method Not Allowed", - 406: "Not Acceptable", - 407: "Proxy Authentication Required", - 408: "Request Timeout", - 410: "Gone", - 412: "Conditional Request Failed", - 413: "Request Entity Too Large", - 414: "Request-URI Too Long", - 415: "Unsupported Media Type", - 416: "Unsupported URI Scheme", - 417: "Unknown Resource-Priority", - 420: "Bad Extension", - 421: "Extension Required", - 422: "Session Interval Too Small", - 423: "Interval Too Brief", - 428: "Use Identity Header", - 429: "Provide Referrer Identity", - 430: "Flow Failed", - 433: "Anonymity Disallowed", - 436: "Bad Identity-Info", - 437: "Unsupported Certificate", - 438: "Invalid Identity Header", - 439: "First Hop Lacks Outbound Support", - 440: "Max-Breadth Exceeded", - 469: "Bad Info Package", - 470: "Consent Needed", - 478: "Unresolvable Destination", - 480: "Temporarily Unavailable", - 481: "Call/Transaction Does Not Exist", - 482: "Loop Detected", - 483: "Too Many Hops", - 484: "Address Incomplete", - 485: "Ambiguous", - 486: "Busy Here", - 487: "Request Terminated", - 488: "Not Acceptable Here", - 489: "Bad Event", - 491: "Request Pending", - 493: "Undecipherable", - 494: "Security Agreement Required", - 500: "Internal Server Error", - 501: "Not Implemented", - 502: "Bad Gateway", - 503: "Service Unavailable", - 504: "Server Time-out", - 505: "Version Not Supported", - 513: "Message Too Large", - 580: "Precondition Failure", - 600: "Busy Everywhere", - 603: "Decline", - 604: "Does Not Exist Anywhere", - 606: "Not Acceptable" - }; - /* SIP Option Tags - * DOC: http://www.iana.org/assignments/sip-parameters/sip-parameters.xhtml#sip-parameters-4 - */ - C.OPTION_TAGS = { - "100rel": true, - "199": true, - "answermode": true, - "early-session": true, - "eventlist": true, - "explicitsub": true, - "from-change": true, - "geolocation-http": true, - "geolocation-sip": true, - "gin": true, - "gruu": true, - "histinfo": true, - "ice": true, - "join": true, - "multiple-refer": true, - "norefersub": true, - "nosub": true, - "outbound": true, - "path": true, - "policy": true, - "precondition": true, - "pref": true, - "privacy": true, - "recipient-list-invite": true, - "recipient-list-message": true, - "recipient-list-subscribe": true, - "replaces": true, - "resource-priority": true, - "sdp-anat": true, - "sec-agree": true, - "tdialog": true, - "timer": true, - "uui": true // RFC 7433 - }; - var dtmfType; - (function (dtmfType) { - dtmfType["INFO"] = "info"; - dtmfType["RTP"] = "rtp"; - })(dtmfType = C.dtmfType || (C.dtmfType = {})); -})(C = exports.C || (exports.C = {})); diff --git a/lib/Enums.d.ts b/lib/Enums.d.ts deleted file mode 100644 index 61ef0a61a..000000000 --- a/lib/Enums.d.ts +++ /dev/null @@ -1,62 +0,0 @@ -export declare enum DialogStatus { - STATUS_EARLY = 1, - STATUS_CONFIRMED = 2 -} -export declare enum SessionStatus { - STATUS_NULL = 0, - STATUS_INVITE_SENT = 1, - STATUS_1XX_RECEIVED = 2, - STATUS_INVITE_RECEIVED = 3, - STATUS_WAITING_FOR_ANSWER = 4, - STATUS_ANSWERED = 5, - STATUS_WAITING_FOR_PRACK = 6, - STATUS_WAITING_FOR_ACK = 7, - STATUS_CANCELED = 8, - STATUS_TERMINATED = 9, - STATUS_ANSWERED_WAITING_FOR_PRACK = 10, - STATUS_EARLY_MEDIA = 11, - STATUS_CONFIRMED = 12 -} -export declare enum TypeStrings { - ClientContext = 0, - ConfigurationError = 1, - Dialog = 2, - DigestAuthentication = 3, - DTMF = 4, - IncomingMessage = 5, - IncomingRequest = 6, - IncomingResponse = 7, - InvalidStateError = 8, - InviteClientContext = 9, - InviteServerContext = 10, - Logger = 11, - LoggerFactory = 12, - MethodParameterError = 13, - NameAddrHeader = 14, - NotSupportedError = 15, - OutgoingRequest = 16, - Parameters = 17, - PublishContext = 18, - ReferClientContext = 19, - ReferServerContext = 20, - RegisterContext = 21, - RenegotiationError = 22, - RequestSender = 23, - ServerContext = 24, - Session = 25, - SessionDescriptionHandler = 26, - SessionDescriptionHandlerError = 27, - SessionDescriptionHandlerObserver = 28, - Subscription = 29, - Transport = 30, - UA = 31, - URI = 32 -} -export declare enum UAStatus { - STATUS_INIT = 0, - STATUS_STARTING = 1, - STATUS_READY = 2, - STATUS_USER_CLOSED = 3, - STATUS_NOT_READY = 4 -} -//# sourceMappingURL=Enums.d.ts.map \ No newline at end of file diff --git a/lib/Enums.d.ts.map b/lib/Enums.d.ts.map deleted file mode 100644 index 265e93d79..000000000 --- a/lib/Enums.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"Enums.d.ts","sourceRoot":"","sources":["../src/Enums.ts"],"names":[],"mappings":"AAGA,oBAAY,YAAY;IACtB,YAAY,IAAI;IAChB,gBAAgB,IAAI;CACrB;AAED,oBAAY,aAAa;IAEvB,WAAW,IAAA;IACX,kBAAkB,IAAA;IAClB,mBAAmB,IAAA;IACnB,sBAAsB,IAAA;IACtB,yBAAyB,IAAA;IACzB,eAAe,IAAA;IACf,wBAAwB,IAAA;IACxB,sBAAsB,IAAA;IACtB,eAAe,IAAA;IACf,iBAAiB,IAAA;IACjB,iCAAiC,KAAA;IACjC,kBAAkB,KAAA;IAClB,gBAAgB,KAAA;CACjB;AAED,oBAAY,WAAW;IACrB,aAAa,IAAA;IACb,kBAAkB,IAAA;IAClB,MAAM,IAAA;IACN,oBAAoB,IAAA;IACpB,IAAI,IAAA;IACJ,eAAe,IAAA;IACf,eAAe,IAAA;IACf,gBAAgB,IAAA;IAChB,iBAAiB,IAAA;IACjB,mBAAmB,IAAA;IACnB,mBAAmB,KAAA;IACnB,MAAM,KAAA;IACN,aAAa,KAAA;IACb,oBAAoB,KAAA;IACpB,cAAc,KAAA;IACd,iBAAiB,KAAA;IACjB,eAAe,KAAA;IACf,UAAU,KAAA;IACV,cAAc,KAAA;IACd,kBAAkB,KAAA;IAClB,kBAAkB,KAAA;IAClB,eAAe,KAAA;IACf,kBAAkB,KAAA;IAClB,aAAa,KAAA;IACb,aAAa,KAAA;IACb,OAAO,KAAA;IACP,yBAAyB,KAAA;IACzB,8BAA8B,KAAA;IAC9B,iCAAiC,KAAA;IACjC,YAAY,KAAA;IACZ,SAAS,KAAA;IACT,EAAE,KAAA;IACF,GAAG,KAAA;CACJ;AAGD,oBAAY,QAAQ;IAClB,WAAW,IAAA;IACX,eAAe,IAAA;IACf,YAAY,IAAA;IACZ,kBAAkB,IAAA;IAClB,gBAAgB,IAAA;CACjB"} \ No newline at end of file diff --git a/lib/Enums.js b/lib/Enums.js deleted file mode 100644 index 920136fd0..000000000 --- a/lib/Enums.js +++ /dev/null @@ -1,71 +0,0 @@ -"use strict"; -// enums can't really be declared, so they are set here. -// pulled out of individual files to avoid circular dependencies -Object.defineProperty(exports, "__esModule", { value: true }); -var DialogStatus; -(function (DialogStatus) { - DialogStatus[DialogStatus["STATUS_EARLY"] = 1] = "STATUS_EARLY"; - DialogStatus[DialogStatus["STATUS_CONFIRMED"] = 2] = "STATUS_CONFIRMED"; -})(DialogStatus = exports.DialogStatus || (exports.DialogStatus = {})); -var SessionStatus; -(function (SessionStatus) { - // Session states - SessionStatus[SessionStatus["STATUS_NULL"] = 0] = "STATUS_NULL"; - SessionStatus[SessionStatus["STATUS_INVITE_SENT"] = 1] = "STATUS_INVITE_SENT"; - SessionStatus[SessionStatus["STATUS_1XX_RECEIVED"] = 2] = "STATUS_1XX_RECEIVED"; - SessionStatus[SessionStatus["STATUS_INVITE_RECEIVED"] = 3] = "STATUS_INVITE_RECEIVED"; - SessionStatus[SessionStatus["STATUS_WAITING_FOR_ANSWER"] = 4] = "STATUS_WAITING_FOR_ANSWER"; - SessionStatus[SessionStatus["STATUS_ANSWERED"] = 5] = "STATUS_ANSWERED"; - SessionStatus[SessionStatus["STATUS_WAITING_FOR_PRACK"] = 6] = "STATUS_WAITING_FOR_PRACK"; - SessionStatus[SessionStatus["STATUS_WAITING_FOR_ACK"] = 7] = "STATUS_WAITING_FOR_ACK"; - SessionStatus[SessionStatus["STATUS_CANCELED"] = 8] = "STATUS_CANCELED"; - SessionStatus[SessionStatus["STATUS_TERMINATED"] = 9] = "STATUS_TERMINATED"; - SessionStatus[SessionStatus["STATUS_ANSWERED_WAITING_FOR_PRACK"] = 10] = "STATUS_ANSWERED_WAITING_FOR_PRACK"; - SessionStatus[SessionStatus["STATUS_EARLY_MEDIA"] = 11] = "STATUS_EARLY_MEDIA"; - SessionStatus[SessionStatus["STATUS_CONFIRMED"] = 12] = "STATUS_CONFIRMED"; -})(SessionStatus = exports.SessionStatus || (exports.SessionStatus = {})); -var TypeStrings; -(function (TypeStrings) { - TypeStrings[TypeStrings["ClientContext"] = 0] = "ClientContext"; - TypeStrings[TypeStrings["ConfigurationError"] = 1] = "ConfigurationError"; - TypeStrings[TypeStrings["Dialog"] = 2] = "Dialog"; - TypeStrings[TypeStrings["DigestAuthentication"] = 3] = "DigestAuthentication"; - TypeStrings[TypeStrings["DTMF"] = 4] = "DTMF"; - TypeStrings[TypeStrings["IncomingMessage"] = 5] = "IncomingMessage"; - TypeStrings[TypeStrings["IncomingRequest"] = 6] = "IncomingRequest"; - TypeStrings[TypeStrings["IncomingResponse"] = 7] = "IncomingResponse"; - TypeStrings[TypeStrings["InvalidStateError"] = 8] = "InvalidStateError"; - TypeStrings[TypeStrings["InviteClientContext"] = 9] = "InviteClientContext"; - TypeStrings[TypeStrings["InviteServerContext"] = 10] = "InviteServerContext"; - TypeStrings[TypeStrings["Logger"] = 11] = "Logger"; - TypeStrings[TypeStrings["LoggerFactory"] = 12] = "LoggerFactory"; - TypeStrings[TypeStrings["MethodParameterError"] = 13] = "MethodParameterError"; - TypeStrings[TypeStrings["NameAddrHeader"] = 14] = "NameAddrHeader"; - TypeStrings[TypeStrings["NotSupportedError"] = 15] = "NotSupportedError"; - TypeStrings[TypeStrings["OutgoingRequest"] = 16] = "OutgoingRequest"; - TypeStrings[TypeStrings["Parameters"] = 17] = "Parameters"; - TypeStrings[TypeStrings["PublishContext"] = 18] = "PublishContext"; - TypeStrings[TypeStrings["ReferClientContext"] = 19] = "ReferClientContext"; - TypeStrings[TypeStrings["ReferServerContext"] = 20] = "ReferServerContext"; - TypeStrings[TypeStrings["RegisterContext"] = 21] = "RegisterContext"; - TypeStrings[TypeStrings["RenegotiationError"] = 22] = "RenegotiationError"; - TypeStrings[TypeStrings["RequestSender"] = 23] = "RequestSender"; - TypeStrings[TypeStrings["ServerContext"] = 24] = "ServerContext"; - TypeStrings[TypeStrings["Session"] = 25] = "Session"; - TypeStrings[TypeStrings["SessionDescriptionHandler"] = 26] = "SessionDescriptionHandler"; - TypeStrings[TypeStrings["SessionDescriptionHandlerError"] = 27] = "SessionDescriptionHandlerError"; - TypeStrings[TypeStrings["SessionDescriptionHandlerObserver"] = 28] = "SessionDescriptionHandlerObserver"; - TypeStrings[TypeStrings["Subscription"] = 29] = "Subscription"; - TypeStrings[TypeStrings["Transport"] = 30] = "Transport"; - TypeStrings[TypeStrings["UA"] = 31] = "UA"; - TypeStrings[TypeStrings["URI"] = 32] = "URI"; -})(TypeStrings = exports.TypeStrings || (exports.TypeStrings = {})); -// UA status codes -var UAStatus; -(function (UAStatus) { - UAStatus[UAStatus["STATUS_INIT"] = 0] = "STATUS_INIT"; - UAStatus[UAStatus["STATUS_STARTING"] = 1] = "STATUS_STARTING"; - UAStatus[UAStatus["STATUS_READY"] = 2] = "STATUS_READY"; - UAStatus[UAStatus["STATUS_USER_CLOSED"] = 3] = "STATUS_USER_CLOSED"; - UAStatus[UAStatus["STATUS_NOT_READY"] = 4] = "STATUS_NOT_READY"; -})(UAStatus = exports.UAStatus || (exports.UAStatus = {})); diff --git a/lib/Exceptions.d.ts b/lib/Exceptions.d.ts deleted file mode 100644 index 49afc4527..000000000 --- a/lib/Exceptions.d.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { Exception } from "./core"; -import { SessionStatus, TypeStrings } from "./Enums"; -export declare namespace Exceptions { - /** - * Indicates the session description handler has closed. - * Occurs when getDescription() or setDescription() are called after close() has been called. - * Occurs when close() is called while getDescription() or setDescription() are in progress. - */ - class ClosedSessionDescriptionHandlerError extends Exception { - constructor(); - } - /** - * Indicates the session terminated before the action completed. - */ - class TerminatedSessionError extends Exception { - constructor(); - } - /** - * Unsupported session description content type. - */ - class UnsupportedSessionDescriptionContentTypeError extends Exception { - constructor(message?: string); - } -} -/** - * DEPRECATED: The original implementation of exceptions in this library attempted to - * deal with the lack of type checking in JavaScript by adding a "type" attribute - * to objects and using that to discriminate. On top of that it layered allcoated - * "code" numbers and constant "name" strings. All of that is unnecessary when using - * TypeScript, inheriting from Error and properly setting up the prototype chain... - */ -declare abstract class LegacyException extends Exception { - type: TypeStrings; - name: string; - message: string; - code: number; - constructor(code: number, name: string, message: string); -} -export declare namespace Exceptions { - class ConfigurationError extends LegacyException { - parameter: string; - value: any; - constructor(parameter: string, value?: any); - } - class InvalidStateError extends LegacyException { - status: SessionStatus; - constructor(status: SessionStatus); - } - class NotSupportedError extends LegacyException { - constructor(message: string); - } - class RenegotiationError extends LegacyException { - constructor(message: string); - } - class MethodParameterError extends LegacyException { - method: string; - parameter: string; - value: any; - constructor(method: string, parameter: string, value: any); - } - class SessionDescriptionHandlerError extends LegacyException { - error: string | undefined; - method: string; - constructor(method: string, error?: string, message?: string); - } -} -export {}; -//# sourceMappingURL=Exceptions.d.ts.map \ No newline at end of file diff --git a/lib/Exceptions.d.ts.map b/lib/Exceptions.d.ts.map deleted file mode 100644 index 414eb5a53..000000000 --- a/lib/Exceptions.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"Exceptions.d.ts","sourceRoot":"","sources":["../src/Exceptions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,QAAQ,CAAC;AACnC,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAIrD,yBAAiB,UAAU,CAAC;IAE1B;;;;OAIG;IACH,MAAa,oCAAqC,SAAQ,SAAS;;KAIlE;IAED;;OAEG;IACH,MAAa,sBAAuB,SAAQ,SAAS;;KAIpD;IAED;;OAEG;IACH,MAAa,6CAA8C,SAAQ,SAAS;oBAC9D,OAAO,CAAC,EAAE,MAAM;KAG7B;CACF;AAED;;;;;;GAMG;AACH,uBAAe,eAAgB,SAAQ,SAAS;IACvC,IAAI,EAAG,WAAW,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,MAAM,CAAC;gBAER,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM;CAMxD;AAED,yBAAiB,UAAU,CAAC;IAC1B,MAAa,kBAAmB,SAAQ,eAAe;QAC9C,SAAS,EAAE,MAAM,CAAC;QAClB,KAAK,EAAE,GAAG,CAAC;oBAEN,SAAS,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,GAAG;KAO3C;IAED,MAAa,iBAAkB,SAAQ,eAAe;QAC7C,MAAM,EAAE,aAAa,CAAC;oBAEjB,MAAM,EAAE,aAAa;KAKlC;IAED,MAAa,iBAAkB,SAAQ,eAAe;oBACxC,OAAO,EAAE,MAAM;KAI5B;IAID,MAAa,kBAAmB,SAAQ,eAAe;oBACzC,OAAO,EAAE,MAAM;KAI5B;IAED,MAAa,oBAAqB,SAAQ,eAAe;QAChD,MAAM,EAAE,MAAM,CAAC;QACf,SAAS,EAAE,MAAM,CAAC;QAClB,KAAK,EAAE,GAAG,CAAC;oBAEN,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG;KAS1D;IAID,MAAa,8BAA+B,SAAQ,eAAe;QAC1D,KAAK,EAAE,MAAM,GAAG,SAAS,CAAC;QAC1B,MAAM,EAAE,MAAM,CAAC;oBAEV,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM;KAM7D;CACF"} \ No newline at end of file diff --git a/lib/Exceptions.js b/lib/Exceptions.js deleted file mode 100644 index 7ba7fbcc8..000000000 --- a/lib/Exceptions.js +++ /dev/null @@ -1,137 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var core_1 = require("./core"); -var Enums_1 = require("./Enums"); -// tslint:disable:max-classes-per-file -var Exceptions; -(function (Exceptions) { - /** - * Indicates the session description handler has closed. - * Occurs when getDescription() or setDescription() are called after close() has been called. - * Occurs when close() is called while getDescription() or setDescription() are in progress. - */ - var ClosedSessionDescriptionHandlerError = /** @class */ (function (_super) { - tslib_1.__extends(ClosedSessionDescriptionHandlerError, _super); - function ClosedSessionDescriptionHandlerError() { - return _super.call(this, "The session description handler has closed.") || this; - } - return ClosedSessionDescriptionHandlerError; - }(core_1.Exception)); - Exceptions.ClosedSessionDescriptionHandlerError = ClosedSessionDescriptionHandlerError; - /** - * Indicates the session terminated before the action completed. - */ - var TerminatedSessionError = /** @class */ (function (_super) { - tslib_1.__extends(TerminatedSessionError, _super); - function TerminatedSessionError() { - return _super.call(this, "The session has terminated.") || this; - } - return TerminatedSessionError; - }(core_1.Exception)); - Exceptions.TerminatedSessionError = TerminatedSessionError; - /** - * Unsupported session description content type. - */ - var UnsupportedSessionDescriptionContentTypeError = /** @class */ (function (_super) { - tslib_1.__extends(UnsupportedSessionDescriptionContentTypeError, _super); - function UnsupportedSessionDescriptionContentTypeError(message) { - return _super.call(this, message ? message : "Unsupported session description content type.") || this; - } - return UnsupportedSessionDescriptionContentTypeError; - }(core_1.Exception)); - Exceptions.UnsupportedSessionDescriptionContentTypeError = UnsupportedSessionDescriptionContentTypeError; -})(Exceptions = exports.Exceptions || (exports.Exceptions = {})); -/** - * DEPRECATED: The original implementation of exceptions in this library attempted to - * deal with the lack of type checking in JavaScript by adding a "type" attribute - * to objects and using that to discriminate. On top of that it layered allcoated - * "code" numbers and constant "name" strings. All of that is unnecessary when using - * TypeScript, inheriting from Error and properly setting up the prototype chain... - */ -var LegacyException = /** @class */ (function (_super) { - tslib_1.__extends(LegacyException, _super); - function LegacyException(code, name, message) { - var _this = _super.call(this, message) || this; - _this.code = code; - _this.name = name; - _this.message = message; - return _this; - } - return LegacyException; -}(core_1.Exception)); -(function (Exceptions) { - var ConfigurationError = /** @class */ (function (_super) { - tslib_1.__extends(ConfigurationError, _super); - function ConfigurationError(parameter, value) { - var _this = _super.call(this, 1, "CONFIGURATION_ERROR", (!value) ? "Missing parameter: " + parameter : - "Invalid value " + JSON.stringify(value) + " for parameter '" + parameter + "'") || this; - _this.type = Enums_1.TypeStrings.ConfigurationError; - _this.parameter = parameter; - _this.value = value; - return _this; - } - return ConfigurationError; - }(LegacyException)); - Exceptions.ConfigurationError = ConfigurationError; - var InvalidStateError = /** @class */ (function (_super) { - tslib_1.__extends(InvalidStateError, _super); - function InvalidStateError(status) { - var _this = _super.call(this, 2, "INVALID_STATE_ERROR", "Invalid status: " + status) || this; - _this.type = Enums_1.TypeStrings.InvalidStateError; - _this.status = status; - return _this; - } - return InvalidStateError; - }(LegacyException)); - Exceptions.InvalidStateError = InvalidStateError; - var NotSupportedError = /** @class */ (function (_super) { - tslib_1.__extends(NotSupportedError, _super); - function NotSupportedError(message) { - var _this = _super.call(this, 3, "NOT_SUPPORTED_ERROR", message) || this; - _this.type = Enums_1.TypeStrings.NotSupportedError; - return _this; - } - return NotSupportedError; - }(LegacyException)); - Exceptions.NotSupportedError = NotSupportedError; - // 4 was GetDescriptionError, which was deprecated and now removed - var RenegotiationError = /** @class */ (function (_super) { - tslib_1.__extends(RenegotiationError, _super); - function RenegotiationError(message) { - var _this = _super.call(this, 5, "RENEGOTIATION_ERROR", message) || this; - _this.type = Enums_1.TypeStrings.RenegotiationError; - return _this; - } - return RenegotiationError; - }(LegacyException)); - Exceptions.RenegotiationError = RenegotiationError; - var MethodParameterError = /** @class */ (function (_super) { - tslib_1.__extends(MethodParameterError, _super); - function MethodParameterError(method, parameter, value) { - var _this = _super.call(this, 6, "METHOD_PARAMETER_ERROR", (!value) ? - "Missing parameter: " + parameter : - "Invalid value " + JSON.stringify(value) + " for parameter '" + parameter + "'") || this; - _this.type = Enums_1.TypeStrings.MethodParameterError; - _this.method = method; - _this.parameter = parameter; - _this.value = value; - return _this; - } - return MethodParameterError; - }(LegacyException)); - Exceptions.MethodParameterError = MethodParameterError; - // 7 was TransportError, which was replaced - var SessionDescriptionHandlerError = /** @class */ (function (_super) { - tslib_1.__extends(SessionDescriptionHandlerError, _super); - function SessionDescriptionHandlerError(method, error, message) { - var _this = _super.call(this, 8, "SESSION_DESCRIPTION_HANDLER_ERROR", message || "Error with Session Description Handler") || this; - _this.type = Enums_1.TypeStrings.SessionDescriptionHandlerError; - _this.method = method; - _this.error = error; - return _this; - } - return SessionDescriptionHandlerError; - }(LegacyException)); - Exceptions.SessionDescriptionHandlerError = SessionDescriptionHandlerError; -})(Exceptions = exports.Exceptions || (exports.Exceptions = {})); diff --git a/lib/Parser.d.ts b/lib/Parser.d.ts deleted file mode 100644 index 99621bdda..000000000 --- a/lib/Parser.d.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { IncomingRequestMessage, IncomingResponseMessage, Logger } from "./core"; -/** - * Extract and parse every header of a SIP message. - * @namespace - */ -export declare namespace Parser { - function getHeader(data: any, headerStart: number): number; - function parseHeader(message: IncomingRequestMessage | IncomingResponseMessage, data: any, headerStart: number, headerEnd: number): boolean | { - error: string; - }; - /** Parse SIP Message - * @function - * @param {String} message SIP message. - * @param {Object} logger object. - * @returns {SIP.IncomingRequest|SIP.IncomingResponse|undefined} - */ - function parseMessage(data: string, logger: Logger): IncomingRequestMessage | IncomingResponseMessage | undefined; -} -//# sourceMappingURL=Parser.d.ts.map \ No newline at end of file diff --git a/lib/Parser.d.ts.map b/lib/Parser.d.ts.map deleted file mode 100644 index cd75aeaee..000000000 --- a/lib/Parser.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"Parser.d.ts","sourceRoot":"","sources":["../src/Parser.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,sBAAsB,EACtB,uBAAuB,EACvB,MAAM,EACP,MAAM,QAAQ,CAAC;AAEhB;;;GAGG;AACH,yBAAiB,MAAM,CAAC;IAEtB,SAAgB,SAAS,CAAC,IAAI,EAAE,GAAG,EAAE,WAAW,EAAE,MAAM,GAAG,MAAM,CAgChE;IAED,SAAgB,WAAW,CACzB,OAAO,EAAE,sBAAsB,GAAG,uBAAuB,EACzD,IAAI,EAAE,GAAG,EACT,WAAW,EAAE,MAAM,EACnB,SAAS,EAAE,MAAM,GAChB,OAAO,GAAG;QAAC,KAAK,EAAE,MAAM,CAAA;KAAC,CAsI3B;IAED;;;;;OAKG;IACH,SAAgB,YAAY,CAC1B,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,GACb,sBAAsB,GAAG,uBAAuB,GAAG,SAAS,CAoE9D;CACF"} \ No newline at end of file diff --git a/lib/Parser.js b/lib/Parser.js deleted file mode 100644 index 1b3c2eb94..000000000 --- a/lib/Parser.js +++ /dev/null @@ -1,241 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var core_1 = require("./core"); -/** - * Extract and parse every header of a SIP message. - * @namespace - */ -var Parser; -(function (Parser) { - function getHeader(data, headerStart) { - // 'start' position of the header. - var start = headerStart; - // 'end' position of the header. - var end = 0; - // 'partial end' position of the header. - var partialEnd = 0; - // End of message. - if (data.substring(start, start + 2).match(/(^\r\n)/)) { - return -2; - } - while (end === 0) { - // Partial End of Header. - partialEnd = data.indexOf("\r\n", start); - // 'indexOf' returns -1 if the value to be found never occurs. - if (partialEnd === -1) { - return partialEnd; - } - if (!data.substring(partialEnd + 2, partialEnd + 4).match(/(^\r\n)/) && - data.charAt(partialEnd + 2).match(/(^\s+)/)) { - // Not the end of the message. Continue from the next position. - start = partialEnd + 2; - } - else { - end = partialEnd; - } - } - return end; - } - Parser.getHeader = getHeader; - function parseHeader(message, data, headerStart, headerEnd) { - var hcolonIndex = data.indexOf(":", headerStart); - var headerName = data.substring(headerStart, hcolonIndex).trim(); - var headerValue = data.substring(hcolonIndex + 1, headerEnd).trim(); - var parsed; - // If header-field is well-known, parse it. - switch (headerName.toLowerCase()) { - case "via": - case "v": - message.addHeader("via", headerValue); - if (message.getHeaders("via").length === 1) { - parsed = message.parseHeader("Via"); - if (parsed) { - message.via = parsed; - message.viaBranch = parsed.branch; - } - } - else { - parsed = 0; - } - break; - case "from": - case "f": - message.setHeader("from", headerValue); - parsed = message.parseHeader("from"); - if (parsed) { - message.from = parsed; - message.fromTag = parsed.getParam("tag"); - } - break; - case "to": - case "t": - message.setHeader("to", headerValue); - parsed = message.parseHeader("to"); - if (parsed) { - message.to = parsed; - message.toTag = parsed.getParam("tag"); - } - break; - case "record-route": - parsed = core_1.Grammar.parse(headerValue, "Record_Route"); - if (parsed === -1) { - parsed = undefined; - break; - } - for (var header in parsed) { - if (parsed[header]) { - message.addHeader("record-route", headerValue.substring(parsed[header].position, parsed[header].offset)); - message.headers["Record-Route"][message.getHeaders("record-route").length - 1].parsed = - parsed[header].parsed; - } - } - break; - case "call-id": - case "i": - message.setHeader("call-id", headerValue); - parsed = message.parseHeader("call-id"); - if (parsed) { - message.callId = headerValue; - } - break; - case "contact": - case "m": - parsed = core_1.Grammar.parse(headerValue, "Contact"); - if (parsed === -1) { - parsed = undefined; - break; - } - if (!(parsed instanceof Array)) { - parsed = undefined; - break; - } - parsed.forEach(function (header) { - message.addHeader("contact", headerValue.substring(header.position, header.offset)); - message.headers.Contact[message.getHeaders("contact").length - 1].parsed = header.parsed; - }); - break; - case "content-length": - case "l": - message.setHeader("content-length", headerValue); - parsed = message.parseHeader("content-length"); - break; - case "content-type": - case "c": - message.setHeader("content-type", headerValue); - parsed = message.parseHeader("content-type"); - break; - case "cseq": - message.setHeader("cseq", headerValue); - parsed = message.parseHeader("cseq"); - if (parsed) { - message.cseq = parsed.value; - } - if (message instanceof core_1.IncomingResponseMessage) { - message.method = parsed.method; - } - break; - case "max-forwards": - message.setHeader("max-forwards", headerValue); - parsed = message.parseHeader("max-forwards"); - break; - case "www-authenticate": - message.setHeader("www-authenticate", headerValue); - parsed = message.parseHeader("www-authenticate"); - break; - case "proxy-authenticate": - message.setHeader("proxy-authenticate", headerValue); - parsed = message.parseHeader("proxy-authenticate"); - break; - case "refer-to": - case "r": - message.setHeader("refer-to", headerValue); - parsed = message.parseHeader("refer-to"); - if (parsed) { - message.referTo = parsed; - } - break; - default: - // Do not parse this header. - message.addHeader(headerName.toLowerCase(), headerValue); - parsed = 0; - } - if (parsed === undefined) { - return { - error: "error parsing header '" + headerName + "'" - }; - } - else { - return true; - } - } - Parser.parseHeader = parseHeader; - /** Parse SIP Message - * @function - * @param {String} message SIP message. - * @param {Object} logger object. - * @returns {SIP.IncomingRequest|SIP.IncomingResponse|undefined} - */ - function parseMessage(data, logger) { - var headerStart = 0; - var headerEnd = data.indexOf("\r\n"); - if (headerEnd === -1) { - logger.warn("no CRLF found, not a SIP message, discarded"); - return; - } - // Parse first line. Check if it is a Request or a Reply. - var firstLine = data.substring(0, headerEnd); - var parsed = core_1.Grammar.parse(firstLine, "Request_Response"); - var message; - if (parsed === -1) { - logger.warn('error parsing first line of SIP message: "' + firstLine + '"'); - return; - } - else if (!parsed.status_code) { - message = new core_1.IncomingRequestMessage(); - message.method = parsed.method; - message.ruri = parsed.uri; - } - else { - message = new core_1.IncomingResponseMessage(); - message.statusCode = parsed.status_code; - message.reasonPhrase = parsed.reason_phrase; - } - message.data = data; - headerStart = headerEnd + 2; - /* Loop over every line in data. Detect the end of each header and parse - * it or simply add to the headers collection. - */ - var bodyStart; - while (true) { - headerEnd = getHeader(data, headerStart); - // The SIP message has normally finished. - if (headerEnd === -2) { - bodyStart = headerStart + 2; - break; - } - else if (headerEnd === -1) { - // data.indexOf returned -1 due to a malformed message. - logger.error("malformed message"); - return; - } - var parsedHeader = parseHeader(message, data, headerStart, headerEnd); - if (parsedHeader !== true) { - logger.error(parsed.error); - return; - } - headerStart = headerEnd + 2; - } - /* RFC3261 18.3. - * If there are additional bytes in the transport packet - * beyond the end of the body, they MUST be discarded. - */ - if (message.hasHeader("content-length")) { - message.body = data.substr(bodyStart, Number(message.getHeader("content-length"))); - } - else { - message.body = data.substring(bodyStart); - } - return message; - } - Parser.parseMessage = parseMessage; -})(Parser = exports.Parser || (exports.Parser = {})); diff --git a/lib/PublishContext.d.ts b/lib/PublishContext.d.ts deleted file mode 100644 index 4d039a2c3..000000000 --- a/lib/PublishContext.d.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { ClientContext } from "./ClientContext"; -import { IncomingResponseMessage, URI } from "./core"; -import { TypeStrings } from "./Enums"; -import { UA } from "./UA"; -/** - * SIP Publish (SIP Extension for Event State Publication RFC3903) - * @class Class creating a SIP PublishContext. - */ -export declare class PublishContext extends ClientContext { - type: TypeStrings; - private options; - private event; - private target; - private pubRequestBody; - private pubRequestExpires; - private pubRequestEtag; - private publishRefreshTimer; - constructor(ua: UA, target: string | URI, event: string, options?: any); - /** - * Publish - * @param {string} Event body to publish, optional - */ - publish(body: string): void; - /** - * Unpublish - */ - unpublish(): void; - /** - * Close - */ - close(): void; - onRequestTimeout(): void; - onTransportError(): void; - receiveResponse(response: IncomingResponseMessage): void; - send(): this; - private refreshRequest; - private sendPublishRequest; -} -//# sourceMappingURL=PublishContext.d.ts.map \ No newline at end of file diff --git a/lib/PublishContext.d.ts.map b/lib/PublishContext.d.ts.map deleted file mode 100644 index 5392e3499..000000000 --- a/lib/PublishContext.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"PublishContext.d.ts","sourceRoot":"","sources":["../src/PublishContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAEhD,OAAO,EAAQ,uBAAuB,EAAE,GAAG,EAAE,MAAM,QAAQ,CAAC;AAE5D,OAAO,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAGtC,OAAO,EAAE,EAAE,EAAE,MAAM,MAAM,CAAC;AAG1B;;;GAGG;AACH,qBAAa,cAAe,SAAQ,aAAa;IACxC,IAAI,EAAE,WAAW,CAAC;IAEzB,OAAO,CAAC,OAAO,CAAM;IACrB,OAAO,CAAC,KAAK,CAAS;IACtB,OAAO,CAAC,MAAM,CAAe;IAC7B,OAAO,CAAC,cAAc,CAAM;IAC5B,OAAO,CAAC,iBAAiB,CAAS;IAClC,OAAO,CAAC,cAAc,CAAqB;IAC3C,OAAO,CAAC,mBAAmB,CAAkB;gBAEjC,EAAE,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,GAAG,GAAG,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,GAAE,GAAQ;IAwC1E;;;OAGG;IACI,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI;IAwBlC;;OAEG;IACI,SAAS,IAAI,IAAI;IAexB;;OAEG;IACI,KAAK,IAAI,IAAI;IAoBb,gBAAgB,IAAI,IAAI;IAKxB,gBAAgB,IAAI,IAAI;IAKxB,eAAe,CAAC,QAAQ,EAAE,uBAAuB,GAAG,IAAI;IAqGxD,IAAI,IAAI,IAAI;IAWnB,OAAO,CAAC,cAAc;IAuBtB,OAAO,CAAC,kBAAkB;CAwC3B"} \ No newline at end of file diff --git a/lib/PublishContext.js b/lib/PublishContext.js deleted file mode 100644 index 585e50ad2..000000000 --- a/lib/PublishContext.js +++ /dev/null @@ -1,272 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var ClientContext_1 = require("./ClientContext"); -var Constants_1 = require("./Constants"); -var core_1 = require("./core"); -var Enums_1 = require("./Enums"); -var Exceptions_1 = require("./Exceptions"); -var Utils_1 = require("./Utils"); -/** - * SIP Publish (SIP Extension for Event State Publication RFC3903) - * @class Class creating a SIP PublishContext. - */ -var PublishContext = /** @class */ (function (_super) { - tslib_1.__extends(PublishContext, _super); - function PublishContext(ua, target, event, options) { - if (options === void 0) { options = {}; } - var _this = this; - options.extraHeaders = (options.extraHeaders || []).slice(); - options.contentType = (options.contentType || "text/plain"); - if (typeof options.expires !== "number" || (options.expires % 1) !== 0) { - options.expires = 3600; - } - else { - options.expires = Number(options.expires); - } - if (typeof (options.unpublishOnClose) !== "boolean") { - options.unpublishOnClose = true; - } - if (target === undefined || target === null || target === "") { - throw new Exceptions_1.Exceptions.MethodParameterError("Publish", "Target", target); - } - else { - target = ua.normalizeTarget(target); - if (target === undefined) { - throw new Exceptions_1.Exceptions.MethodParameterError("Publish", "Target", target); - } - } - _this = _super.call(this, ua, Constants_1.C.PUBLISH, target, options) || this; - _this.type = Enums_1.TypeStrings.PublishContext; - _this.options = options; - _this.target = target; - if (event === undefined || event === null || event === "") { - throw new Exceptions_1.Exceptions.MethodParameterError("Publish", "Event", event); - } - else { - _this.event = event; - } - _this.logger = ua.getLogger("sip.publish"); - _this.pubRequestExpires = _this.options.expires; - return _this; - } - /** - * Publish - * @param {string} Event body to publish, optional - */ - PublishContext.prototype.publish = function (body) { - // Clean up before the run - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - // is Inital or Modify request - this.options.body = body; - this.pubRequestBody = this.options.body; - if (this.pubRequestExpires === 0) { - // This is Initial request after unpublish - this.pubRequestExpires = this.options.expires; - this.pubRequestEtag = undefined; - } - if (!(this.ua.publishers[this.target.toString() + ":" + this.event])) { - this.ua.publishers[this.target.toString() + ":" + this.event] = this; - } - this.sendPublishRequest(); - }; - /** - * Unpublish - */ - PublishContext.prototype.unpublish = function () { - // Clean up before the run - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - this.pubRequestBody = undefined; - this.pubRequestExpires = 0; - if (this.pubRequestEtag !== undefined) { - this.sendPublishRequest(); - } - }; - /** - * Close - */ - PublishContext.prototype.close = function () { - // Send unpublish, if requested - if (this.options.unpublishOnClose) { - this.unpublish(); - } - else { - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - this.pubRequestBody = undefined; - this.pubRequestExpires = 0; - this.pubRequestEtag = undefined; - } - if (this.ua.publishers[this.target.toString() + ":" + this.event]) { - delete this.ua.publishers[this.target.toString() + ":" + this.event]; - } - }; - PublishContext.prototype.onRequestTimeout = function () { - _super.prototype.onRequestTimeout.call(this); - this.emit("unpublished", undefined, Constants_1.C.causes.REQUEST_TIMEOUT); - }; - PublishContext.prototype.onTransportError = function () { - _super.prototype.onTransportError.call(this); - this.emit("unpublished", undefined, Constants_1.C.causes.CONNECTION_ERROR); - }; - PublishContext.prototype.receiveResponse = function (response) { - var _this = this; - var statusCode = response.statusCode || 0; - var cause = Utils_1.Utils.getReasonPhrase(statusCode); - switch (true) { - case /^1[0-9]{2}$/.test(statusCode.toString()): - this.emit("progress", response, cause); - break; - case /^2[0-9]{2}$/.test(statusCode.toString()): - // Set SIP-Etag - if (response.hasHeader("SIP-ETag")) { - this.pubRequestEtag = response.getHeader("SIP-ETag"); - } - else { - this.logger.warn("SIP-ETag header missing in a 200-class response to PUBLISH"); - } - // Update Expire - if (response.hasHeader("Expires")) { - var expires = Number(response.getHeader("Expires")); - if (typeof expires === "number" && expires >= 0 && expires <= this.pubRequestExpires) { - this.pubRequestExpires = expires; - } - else { - this.logger.warn("Bad Expires header in a 200-class response to PUBLISH"); - } - } - else { - this.logger.warn("Expires header missing in a 200-class response to PUBLISH"); - } - if (this.pubRequestExpires !== 0) { - // Schedule refresh - this.publishRefreshTimer = setTimeout(function () { return _this.refreshRequest(); }, this.pubRequestExpires * 900); - this.emit("published", response, cause); - } - else { - this.emit("unpublished", response, cause); - } - break; - case /^412$/.test(statusCode.toString()): - // 412 code means no matching ETag - possibly the PUBLISH expired - // Resubmit as new request, if the current request is not a "remove" - if (this.pubRequestEtag !== undefined && this.pubRequestExpires !== 0) { - this.logger.warn("412 response to PUBLISH, recovering"); - this.pubRequestEtag = undefined; - this.emit("progress", response, cause); - this.publish(this.options.body); - } - else { - this.logger.warn("412 response to PUBLISH, recovery failed"); - this.pubRequestExpires = 0; - this.emit("failed", response, cause); - this.emit("unpublished", response, cause); - } - break; - case /^423$/.test(statusCode.toString()): - // 423 code means we need to adjust the Expires interval up - if (this.pubRequestExpires !== 0 && response.hasHeader("Min-Expires")) { - var minExpires = Number(response.getHeader("Min-Expires")); - if (typeof minExpires === "number" || minExpires > this.pubRequestExpires) { - this.logger.warn("423 code in response to PUBLISH, adjusting the Expires value and trying to recover"); - this.pubRequestExpires = minExpires; - this.emit("progress", response, cause); - this.publish(this.options.body); - } - else { - this.logger.warn("Bad 423 response Min-Expires header received for PUBLISH"); - this.pubRequestExpires = 0; - this.emit("failed", response, cause); - this.emit("unpublished", response, cause); - } - } - else { - this.logger.warn("423 response to PUBLISH, recovery failed"); - this.pubRequestExpires = 0; - this.emit("failed", response, cause); - this.emit("unpublished", response, cause); - } - break; - default: - this.pubRequestExpires = 0; - this.emit("failed", response, cause); - this.emit("unpublished", response, cause); - break; - } - // Do the cleanup - if (this.pubRequestExpires === 0) { - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - this.pubRequestBody = undefined; - this.pubRequestEtag = undefined; - } - }; - PublishContext.prototype.send = function () { - var _this = this; - this.ua.userAgentCore.publish(this.request, { - onAccept: function (response) { return _this.receiveResponse(response.message); }, - onProgress: function (response) { return _this.receiveResponse(response.message); }, - onRedirect: function (response) { return _this.receiveResponse(response.message); }, - onReject: function (response) { return _this.receiveResponse(response.message); }, - onTrying: function (response) { return _this.receiveResponse(response.message); } - }); - return this; - }; - PublishContext.prototype.refreshRequest = function () { - // Clean up before the run - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - // This is Refresh request - this.pubRequestBody = undefined; - if (this.pubRequestEtag === undefined) { - // Request not valid - throw new Exceptions_1.Exceptions.MethodParameterError("Publish", "Body", undefined); - } - if (this.pubRequestExpires === 0) { - // Request not valid - throw new Exceptions_1.Exceptions.MethodParameterError("Publish", "Expire", this.pubRequestExpires); - } - this.sendPublishRequest(); - }; - PublishContext.prototype.sendPublishRequest = function () { - var reqOptions = Object.create(this.options || Object.prototype); - reqOptions.extraHeaders = (this.options.extraHeaders || []).slice(); - reqOptions.extraHeaders.push("Event: " + this.event); - reqOptions.extraHeaders.push("Expires: " + this.pubRequestExpires); - if (this.pubRequestEtag !== undefined) { - reqOptions.extraHeaders.push("SIP-If-Match: " + this.pubRequestEtag); - } - var ruri = this.target instanceof core_1.URI ? this.target : this.ua.normalizeTarget(this.target); - if (!ruri) { - throw new Error("ruri undefined."); - } - var params = this.options.params || {}; - var bodyObj; - if (this.pubRequestBody !== undefined) { - bodyObj = { - body: this.pubRequestBody, - contentType: this.options.contentType - }; - } - var body; - if (bodyObj) { - body = Utils_1.Utils.fromBodyObj(bodyObj); - } - this.request = this.ua.userAgentCore.makeOutgoingRequestMessage(Constants_1.C.PUBLISH, ruri, params.fromUri ? params.fromUri : this.ua.userAgentCore.configuration.aor, params.toUri ? params.toUri : this.target, params, reqOptions.extraHeaders, body); - this.send(); - }; - return PublishContext; -}(ClientContext_1.ClientContext)); -exports.PublishContext = PublishContext; diff --git a/lib/React/SessionDescriptionHandler.d.ts b/lib/React/SessionDescriptionHandler.d.ts deleted file mode 100644 index 1b430761f..000000000 --- a/lib/React/SessionDescriptionHandler.d.ts +++ /dev/null @@ -1,94 +0,0 @@ -/// -import { EventEmitter } from "events"; -import { Logger } from "../core"; -import { TypeStrings } from "../Enums"; -import { InviteClientContext, InviteServerContext } from "../Session"; -import { BodyObj, SessionDescriptionHandler as SessionDescriptionHandlerDefinition, SessionDescriptionHandlerModifiers } from "../session-description-handler"; -import { SessionDescriptionHandlerObserver } from "./SessionDescriptionHandlerObserver"; -export declare class SessionDescriptionHandler extends EventEmitter implements SessionDescriptionHandlerDefinition { - /** - * @param {SIP.Session} session - * @param {Object} [options] - */ - static defaultFactory(session: InviteClientContext | InviteServerContext, options: any): SessionDescriptionHandler; - type: TypeStrings; - private options; - private logger; - private observer; - private dtmfSender; - private shouldAcquireMedia; - private CONTENT_TYPE; - private direction; - private C; - private modifiers; - private WebRTC; - private iceGatheringDeferred; - private iceGatheringTimeout; - private iceGatheringTimer; - private constraints; - private peerConnection; - constructor(logger: Logger, observer: SessionDescriptionHandlerObserver, options: any); - /** - * Destructor - */ - close(): void; - /** - * Gets the local description from the underlying media implementation - * @param {Object} [options] Options object to be used by getDescription - * @param {MediaStreamConstraints} [options.constraints] MediaStreamConstraints - * https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints - * @param {Object} [options.peerConnectionOptions] If this is set it will recreate the peer - * connection with the new options - * @param {Array} [modifiers] Array with one time use description modifiers - * @returns {Promise} Promise that resolves with the local description to be used for the session - */ - getDescription(options?: any, modifiers?: SessionDescriptionHandlerModifiers): Promise; - /** - * Check if the Session Description Handler can handle the Content-Type described by a SIP Message - * @param {String} contentType The content type that is in the SIP Message - * @returns {boolean} - */ - hasDescription(contentType: string): boolean; - /** - * The modifier that should be used when the session would like to place the call on hold - * @param {String} [sdp] The description that will be modified - * @returns {Promise} Promise that resolves with modified SDP - */ - holdModifier(description: RTCSessionDescriptionInit): Promise; - /** - * Set the remote description to the underlying media implementation - * @param {String} sessionDescription The description provided by a SIP message to be set on the media implementation - * @param {Object} [options] Options object to be used by getDescription - * @param {MediaStreamConstraints} [options.constraints] MediaStreamConstraints - * https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints - * @param {Object} [options.peerConnectionOptions] If this is set it will recreate the peer - * connection with the new options - * @param {Array} [modifiers] Array with one time use description modifiers - * @returns {Promise} Promise that resolves once the description is set - */ - setDescription(sessionDescription: string, options?: any, modifiers?: SessionDescriptionHandlerModifiers): Promise; - /** - * Send DTMF via RTP (RFC 4733) - * @param {String} tones A string containing DTMF digits - * @param {Object} [options] Options object to be used by sendDtmf - * @returns {boolean} true if DTMF send is successful, false otherwise - */ - sendDtmf(tones: string, options: any): boolean; - getDirection(): string; - private createOfferOrAnswer; - private createRTCSessionDescriptionInit; - private addDefaultIceCheckingTimeout; - private addDefaultIceServers; - private checkAndDefaultConstraints; - private hasBrowserTrackSupport; - private hasBrowserGetSenderSupport; - private initPeerConnection; - private acquire; - private hasOffer; - private isIceGatheringComplete; - private resetIceGatheringComplete; - private setDirection; - private triggerIceGatheringComplete; - private waitForIceGatheringComplete; -} -//# sourceMappingURL=SessionDescriptionHandler.d.ts.map \ No newline at end of file diff --git a/lib/React/SessionDescriptionHandler.d.ts.map b/lib/React/SessionDescriptionHandler.d.ts.map deleted file mode 100644 index 1da0e6c87..000000000 --- a/lib/React/SessionDescriptionHandler.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"SessionDescriptionHandler.d.ts","sourceRoot":"","sources":["../../src/React/SessionDescriptionHandler.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAOtC,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAEvC,OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AACtE,OAAO,EACL,OAAO,EACP,yBAAyB,IAAI,mCAAmC,EAChE,kCAAkC,EACnC,MAAM,gCAAgC,CAAC;AAKxC,OAAO,EAAE,iCAAiC,EAAE,MAAM,qCAAqC,CAAC;AAQxF,qBAAa,yBAA0B,SAAQ,YAAa,YAAW,mCAAmC;IACxG;;;OAGG;WACW,cAAc,CAC1B,OAAO,EAAE,mBAAmB,GAAG,mBAAmB,EAClD,OAAO,EAAE,GAAG,GACX,yBAAyB;IASrB,IAAI,EAAE,WAAW,CAAC;IACzB,OAAO,CAAC,OAAO,CAAM;IACrB,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,QAAQ,CAAoC;IACpD,OAAO,CAAC,UAAU,CAAM;IACxB,OAAO,CAAC,kBAAkB,CAAU;IACpC,OAAO,CAAC,YAAY,CAAS;IAC7B,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,CAAC,CAAM;IACf,OAAO,CAAC,SAAS,CAAqC;IACtD,OAAO,CAAC,MAAM,CAAM;IACpB,OAAO,CAAC,oBAAoB,CAAkC;IAC9D,OAAO,CAAC,mBAAmB,CAAU;IACrC,OAAO,CAAC,iBAAiB,CAAkB;IAC3C,OAAO,CAAC,WAAW,CAAM;IACzB,OAAO,CAAC,cAAc,CAAM;gBAEhB,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,iCAAiC,EAAE,OAAO,EAAE,GAAG;IAgDrF;;OAEG;IACI,KAAK,IAAI,IAAI;IAqCpB;;;;;;;;;OASG;IACI,cAAc,CAAC,OAAO,GAAE,GAAQ,EAAE,SAAS,GAAE,kCAAsC,GAAG,OAAO,CAAC,OAAO,CAAC;IAmD7G;;;;OAIG;IACI,cAAc,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO;IAInD;;;;OAIG;IACI,YAAY,CAAC,WAAW,EAAE,yBAAyB,GAAG,OAAO,CAAC,yBAAyB,CAAC;IAc/F;;;;;;;;;;OAUG;IACI,cAAc,CACnB,kBAAkB,EAAE,MAAM,EAC1B,OAAO,GAAE,GAAQ,EACjB,SAAS,GAAE,kCAAuC,GACjD,OAAO,CAAC,IAAI,CAAC;IAiEhB;;;;;OAKG;IACI,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,GAAG,OAAO;IAiC9C,YAAY,IAAI,MAAM;IAK7B,OAAO,CAAC,mBAAmB;IA0D3B,OAAO,CAAC,+BAA+B;IAOvC,OAAO,CAAC,4BAA4B;IAOpC,OAAO,CAAC,oBAAoB;IAO5B,OAAO,CAAC,0BAA0B;IAWlC,OAAO,CAAC,sBAAsB;IAI9B,OAAO,CAAC,0BAA0B;IAIlC,OAAO,CAAC,kBAAkB;IAiG1B,OAAO,CAAC,OAAO;IA0Ff,OAAO,CAAC,QAAQ;IAMhB,OAAO,CAAC,sBAAsB;IAI9B,OAAO,CAAC,yBAAyB;IAgBjC,OAAO,CAAC,YAAY;IAsBpB,OAAO,CAAC,2BAA2B;IAgBnC,OAAO,CAAC,2BAA2B;CAWpC"} \ No newline at end of file diff --git a/lib/React/SessionDescriptionHandler.js b/lib/React/SessionDescriptionHandler.js deleted file mode 100644 index 061beeb44..000000000 --- a/lib/React/SessionDescriptionHandler.js +++ /dev/null @@ -1,639 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var events_1 = require("events"); -var react_native_webrtc_1 = require("react-native-webrtc"); -var Enums_1 = require("../Enums"); -var Exceptions_1 = require("../Exceptions"); -var Utils_1 = require("../Utils"); -var session_1 = require("../api/session"); -var Modifiers = tslib_1.__importStar(require("../Web/Modifiers")); -var SessionDescriptionHandlerObserver_1 = require("./SessionDescriptionHandlerObserver"); -/* SessionDescriptionHandler - * @class PeerConnection helper Class. - * @param {SIP.Session} session - * @param {Object} [options] - */ -var SessionDescriptionHandler = /** @class */ (function (_super) { - tslib_1.__extends(SessionDescriptionHandler, _super); - function SessionDescriptionHandler(logger, observer, options) { - var _this = _super.call(this) || this; - _this.type = Enums_1.TypeStrings.SessionDescriptionHandler; - // TODO: Validate the options - _this.options = options || {}; - _this.logger = logger; - _this.observer = observer; - _this.dtmfSender = undefined; - _this.shouldAcquireMedia = true; - _this.CONTENT_TYPE = "application/sdp"; - _this.C = { - DIRECTION: { - NULL: null, - SENDRECV: "sendrecv", - SENDONLY: "sendonly", - RECVONLY: "recvonly", - INACTIVE: "inactive" - } - }; - _this.logger.log("SessionDescriptionHandlerOptions: " + JSON.stringify(_this.options)); - _this.direction = _this.C.DIRECTION.NULL; - _this.modifiers = _this.options.modifiers || []; - if (!Array.isArray(_this.modifiers)) { - _this.modifiers = [_this.modifiers]; - } - _this.WebRTC = { - MediaStream: react_native_webrtc_1.MediaStream, - getUserMedia: react_native_webrtc_1.mediaDevices.getUserMedia, - RTCPeerConnection: react_native_webrtc_1.RTCPeerConnection - }; - _this.iceGatheringTimeout = false; - _this.initPeerConnection(_this.options.peerConnectionOptions); - _this.constraints = _this.checkAndDefaultConstraints(_this.options.constraints); - return _this; - } - /** - * @param {SIP.Session} session - * @param {Object} [options] - */ - SessionDescriptionHandler.defaultFactory = function (session, options) { - var logger = (session instanceof session_1.Session) ? - session.userAgent.getLogger("sip.sessionDescriptionHandler", session.id) : - session.ua.getLogger("sip.invitecontext.sessionDescriptionHandler", session.id); - var observer = new SessionDescriptionHandlerObserver_1.SessionDescriptionHandlerObserver(session, options); - return new SessionDescriptionHandler(logger, observer, options); - }; - // Functions the sesssion can use - /** - * Destructor - */ - SessionDescriptionHandler.prototype.close = function () { - this.logger.log("closing PeerConnection"); - // have to check signalingState since this.close() gets called multiple times - if (this.peerConnection && this.peerConnection.signalingState !== "closed") { - if (this.peerConnection.getSenders) { - this.peerConnection.getSenders().forEach(function (sender) { - if (sender.track) { - sender.track.stop(); - } - }); - } - else { - this.logger.warn("Using getLocalStreams which is deprecated"); - this.peerConnection.getLocalStreams().forEach(function (stream) { - stream.getTracks().forEach(function (track) { - track.stop(); - }); - }); - } - if (this.peerConnection.getReceivers) { - this.peerConnection.getReceivers().forEach(function (receiver) { - if (receiver.track) { - receiver.track.stop(); - } - }); - } - else { - this.logger.warn("Using getRemoteStreams which is deprecated"); - this.peerConnection.getRemoteStreams().forEach(function (stream) { - stream.getTracks().forEach(function (track) { - track.stop(); - }); - }); - } - this.resetIceGatheringComplete(); - this.peerConnection.close(); - } - }; - /** - * Gets the local description from the underlying media implementation - * @param {Object} [options] Options object to be used by getDescription - * @param {MediaStreamConstraints} [options.constraints] MediaStreamConstraints - * https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints - * @param {Object} [options.peerConnectionOptions] If this is set it will recreate the peer - * connection with the new options - * @param {Array} [modifiers] Array with one time use description modifiers - * @returns {Promise} Promise that resolves with the local description to be used for the session - */ - SessionDescriptionHandler.prototype.getDescription = function (options, modifiers) { - var _this = this; - if (options === void 0) { options = {}; } - if (modifiers === void 0) { modifiers = []; } - if (options.peerConnectionOptions) { - this.initPeerConnection(options.peerConnectionOptions); - } - // Merge passed constraints with saved constraints and save - var newConstraints = Object.assign({}, this.constraints, options.constraints); - newConstraints = this.checkAndDefaultConstraints(newConstraints); - if (JSON.stringify(newConstraints) !== JSON.stringify(this.constraints)) { - this.constraints = newConstraints; - this.shouldAcquireMedia = true; - } - if (!Array.isArray(modifiers)) { - modifiers = [modifiers]; - } - modifiers = modifiers.concat(this.modifiers); - return Promise.resolve().then(function () { - if (_this.shouldAcquireMedia) { - return _this.acquire(_this.constraints).then(function () { - _this.shouldAcquireMedia = false; - }); - } - }).then(function () { return _this.createOfferOrAnswer(options.RTCOfferOptions, modifiers); }) - .then(function (description) { - // Recreate offer containing the ICE Candidates - if (description.type === "offer") { - return _this.peerConnection.createOffer() - .then(function (sdp) { return _this.createRTCSessionDescriptionInit(sdp); }); - } - return description; - }).catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("createOffer failed", e); - _this.logger.error(error.toString()); - throw error; - }).then(function (description) { - if (description.sdp === undefined) { - throw new Exceptions_1.Exceptions.SessionDescriptionHandlerError("getDescription", undefined, "SDP undefined"); - } - _this.emit("getDescription", description); - return { - body: description.sdp, - contentType: _this.CONTENT_TYPE - }; - }); - }; - /** - * Check if the Session Description Handler can handle the Content-Type described by a SIP Message - * @param {String} contentType The content type that is in the SIP Message - * @returns {boolean} - */ - SessionDescriptionHandler.prototype.hasDescription = function (contentType) { - return contentType === this.CONTENT_TYPE; - }; - /** - * The modifier that should be used when the session would like to place the call on hold - * @param {String} [sdp] The description that will be modified - * @returns {Promise} Promise that resolves with modified SDP - */ - SessionDescriptionHandler.prototype.holdModifier = function (description) { - if (!description.sdp) { - return Promise.resolve(description); - } - if (!(/a=(sendrecv|sendonly|recvonly|inactive)/).test(description.sdp)) { - description.sdp = description.sdp.replace(/(m=[^\r]*\r\n)/g, "$1a=sendonly\r\n"); - } - else { - description.sdp = description.sdp.replace(/a=sendrecv\r\n/g, "a=sendonly\r\n"); - description.sdp = description.sdp.replace(/a=recvonly\r\n/g, "a=inactive\r\n"); - } - return Promise.resolve(description); - }; - /** - * Set the remote description to the underlying media implementation - * @param {String} sessionDescription The description provided by a SIP message to be set on the media implementation - * @param {Object} [options] Options object to be used by getDescription - * @param {MediaStreamConstraints} [options.constraints] MediaStreamConstraints - * https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints - * @param {Object} [options.peerConnectionOptions] If this is set it will recreate the peer - * connection with the new options - * @param {Array} [modifiers] Array with one time use description modifiers - * @returns {Promise} Promise that resolves once the description is set - */ - SessionDescriptionHandler.prototype.setDescription = function (sessionDescription, options, modifiers) { - var _this = this; - if (options === void 0) { options = {}; } - if (modifiers === void 0) { modifiers = []; } - options = options || {}; - if (options.peerConnectionOptions) { - this.initPeerConnection(options.peerConnectionOptions); - } - if (!Array.isArray(modifiers)) { - modifiers = [modifiers]; - } - modifiers = modifiers.concat(this.modifiers); - var description = { - type: this.hasOffer("local") ? "answer" : "offer", - sdp: sessionDescription - }; - return Promise.resolve().then(function () { - // Media should be acquired in getDescription unless we need to do it sooner for some reason (FF61+) - if (_this.shouldAcquireMedia && _this.options.alwaysAcquireMediaFirst) { - return _this.acquire(_this.constraints).then(function () { - _this.shouldAcquireMedia = false; - }); - } - }).then(function () { return Utils_1.Utils.reducePromises(modifiers, description); }) - .catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("setDescription", e, "The modifiers did not resolve successfully"); - _this.logger.error(error.message); - _this.emit("peerConnection-setRemoteDescriptionFailed", error); - throw error; - }).then(function (modifiedDescription) { - _this.emit("setDescription", modifiedDescription); - return _this.peerConnection.setRemoteDescription(modifiedDescription); - }).catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - // Check the original SDP for video, and ensure that we have want to do audio fallback - if ((/^m=video.+$/gm).test(sessionDescription) && !options.disableAudioFallback) { - // Do not try to audio fallback again - options.disableAudioFallback = true; - // Remove video first, then do the other modifiers - return _this.setDescription(sessionDescription, options, [Modifiers.stripVideo].concat(modifiers)); - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("setDescription", e); - if (error.error) { - _this.logger.error(error.error); - } - _this.emit("peerConnection-setRemoteDescriptionFailed", error); - throw error; - }).then(function () { - if (_this.peerConnection.getReceivers) { - _this.emit("setRemoteDescription", _this.peerConnection.getReceivers()); - } - else { - _this.emit("setRemoteDescription", _this.peerConnection.getRemoteStreams()); - } - _this.emit("confirmed", _this); - }); - }; - /** - * Send DTMF via RTP (RFC 4733) - * @param {String} tones A string containing DTMF digits - * @param {Object} [options] Options object to be used by sendDtmf - * @returns {boolean} true if DTMF send is successful, false otherwise - */ - SessionDescriptionHandler.prototype.sendDtmf = function (tones, options) { - if (!this.dtmfSender && this.hasBrowserGetSenderSupport()) { - var senders = this.peerConnection.getSenders(); - if (senders.length > 0) { - this.dtmfSender = senders[0].dtmf; - } - } - if (!this.dtmfSender && this.hasBrowserTrackSupport()) { - var streams = this.peerConnection.getLocalStreams(); - if (streams.length > 0) { - var audioTracks = streams[0].getAudioTracks(); - if (audioTracks.length > 0) { - this.dtmfSender = this.peerConnection.createDTMFSender(audioTracks[0]); - } - } - } - if (!this.dtmfSender) { - return false; - } - try { - this.dtmfSender.insertDTMF(tones, options.duration, options.interToneGap); - } - catch (e) { - if (e.type === "InvalidStateError" || e.type === "InvalidCharacterError") { - this.logger.error(e); - return false; - } - else { - throw e; - } - } - this.logger.log("DTMF sent via RTP: " + tones.toString()); - return true; - }; - SessionDescriptionHandler.prototype.getDirection = function () { - return this.direction; - }; - // Internal functions - SessionDescriptionHandler.prototype.createOfferOrAnswer = function (RTCOfferOptions, modifiers) { - var _this = this; - if (RTCOfferOptions === void 0) { RTCOfferOptions = {}; } - RTCOfferOptions = RTCOfferOptions || {}; - var methodName = this.hasOffer("remote") ? "createAnswer" : "createOffer"; - var pc = this.peerConnection; - this.logger.log(methodName); - return pc[methodName](RTCOfferOptions).catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer", e, "peerConnection-" + methodName + "Failed"); - _this.emit("peerConnection-" + methodName + "Failed", error); - throw error; - }).then(function (sdp) { return Utils_1.Utils.reducePromises(modifiers, _this.createRTCSessionDescriptionInit(sdp)); }) - .then(function (sdp) { - _this.resetIceGatheringComplete(); - _this.logger.log("Setting local sdp."); - _this.logger.log("sdp is " + sdp.sdp || "undefined"); - return pc.setLocalDescription(sdp); - }) - .catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer", e, "peerConnection-SetLocalDescriptionFailed"); - _this.emit("peerConnection-SetLocalDescriptionFailed", error); - throw error; - }).then(function () { return _this.waitForIceGatheringComplete(); }) - .then(function () { - var localDescription = _this.createRTCSessionDescriptionInit(_this.peerConnection.localDescription); - return Utils_1.Utils.reducePromises(modifiers, localDescription); - }).then(function (localDescription) { - _this.setDirection(localDescription.sdp || ""); - return localDescription; - }).catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer", e); - _this.logger.error(error.toString()); - throw error; - }); - }; - // Creates an RTCSessionDescriptionInit from an RTCSessionDescription - SessionDescriptionHandler.prototype.createRTCSessionDescriptionInit = function (RTCSessionDescription) { - return { - type: RTCSessionDescription.type, - sdp: RTCSessionDescription.sdp - }; - }; - SessionDescriptionHandler.prototype.addDefaultIceCheckingTimeout = function (peerConnectionOptions) { - if (peerConnectionOptions.iceCheckingTimeout === undefined) { - peerConnectionOptions.iceCheckingTimeout = 5000; - } - return peerConnectionOptions; - }; - SessionDescriptionHandler.prototype.addDefaultIceServers = function (rtcConfiguration) { - if (!rtcConfiguration.iceServers) { - rtcConfiguration.iceServers = [{ urls: "stun:stun.l.google.com:19302" }]; - } - return rtcConfiguration; - }; - SessionDescriptionHandler.prototype.checkAndDefaultConstraints = function (constraints) { - var defaultConstraints = { audio: true, video: !this.options.alwaysAcquireMediaFirst }; - constraints = constraints || defaultConstraints; - // Empty object check - if (Object.keys(constraints).length === 0 && constraints.constructor === Object) { - return defaultConstraints; - } - return constraints; - }; - SessionDescriptionHandler.prototype.hasBrowserTrackSupport = function () { - return Boolean(this.peerConnection.addTrack); - }; - SessionDescriptionHandler.prototype.hasBrowserGetSenderSupport = function () { - return Boolean(this.peerConnection.getSenders); - }; - SessionDescriptionHandler.prototype.initPeerConnection = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - options = this.addDefaultIceCheckingTimeout(options); - options.rtcConfiguration = options.rtcConfiguration || {}; - options.rtcConfiguration = this.addDefaultIceServers(options.rtcConfiguration); - this.logger.log("initPeerConnection"); - if (this.peerConnection) { - this.logger.log("Already have a peer connection for this session. Tearing down."); - this.resetIceGatheringComplete(); - this.peerConnection.close(); - } - this.peerConnection = new this.WebRTC.RTCPeerConnection(options.rtcConfiguration); - this.logger.log("New peer connection created"); - if ("ontrack" in this.peerConnection) { - this.peerConnection.addEventListener("track", function (e) { - _this.logger.log("track added"); - _this.observer.trackAdded(); - _this.emit("addTrack", e); - }); - } - else { - this.logger.warn("Using onaddstream which is deprecated"); - this.peerConnection.onaddstream = function (e) { - _this.logger.log("stream added"); - _this.emit("addStream", e); - }; - } - this.peerConnection.onicecandidate = function (e) { - _this.emit("iceCandidate", e); - if (e.candidate) { - _this.logger.log("ICE candidate received: " + - (e.candidate.candidate === null ? null : e.candidate.candidate.trim())); - } - else if (e.candidate === null) { - // indicates the end of candidate gathering - _this.logger.log("ICE candidate gathering complete"); - _this.triggerIceGatheringComplete(); - } - }; - this.peerConnection.onicegatheringstatechange = function () { - _this.logger.log("RTCIceGatheringState changed: " + _this.peerConnection.iceGatheringState); - switch (_this.peerConnection.iceGatheringState) { - case "gathering": - _this.emit("iceGathering", _this); - if (!_this.iceGatheringTimer && options.iceCheckingTimeout) { - _this.iceGatheringTimeout = false; - _this.iceGatheringTimer = setTimeout(function () { - _this.logger.log("RTCIceChecking Timeout Triggered after " + options.iceCheckingTimeout + " milliseconds"); - _this.iceGatheringTimeout = true; - _this.triggerIceGatheringComplete(); - }, options.iceCheckingTimeout); - } - break; - case "complete": - _this.triggerIceGatheringComplete(); - break; - } - }; - this.peerConnection.oniceconnectionstatechange = function () { - var stateEvent; - switch (_this.peerConnection.iceConnectionState) { - case "new": - stateEvent = "iceConnection"; - break; - case "checking": - stateEvent = "iceConnectionChecking"; - break; - case "connected": - stateEvent = "iceConnectionConnected"; - break; - case "completed": - stateEvent = "iceConnectionCompleted"; - break; - case "failed": - stateEvent = "iceConnectionFailed"; - break; - case "disconnected": - stateEvent = "iceConnectionDisconnected"; - break; - case "closed": - stateEvent = "iceConnectionClosed"; - break; - default: - _this.logger.warn("Unknown iceConnection state: " + _this.peerConnection.iceConnectionState); - return; - } - _this.logger.log("ICE Connection State changed to " + stateEvent); - _this.emit(stateEvent, _this); - }; - }; - SessionDescriptionHandler.prototype.acquire = function (constraints) { - var _this = this; - // Default audio & video to true - constraints = this.checkAndDefaultConstraints(constraints); - return new Promise(function (resolve, reject) { - /* - * Make the call asynchronous, so that ICCs have a chance - * to define callbacks to `userMediaRequest` - */ - _this.logger.log("acquiring local media"); - _this.emit("userMediaRequest", constraints); - if (constraints.audio || constraints.video) { - _this.WebRTC.getUserMedia(constraints).then(function (streams) { - _this.observer.trackAdded(); - _this.emit("userMedia", streams); - resolve(streams); - }).catch(function (e) { - _this.emit("userMediaFailed", e); - reject(e); - }); - } - else { - // Local streams were explicitly excluded. - resolve([]); - } - }).catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("acquire", e, "unable to acquire streams"); - _this.logger.error(error.message); - if (error.error) { - _this.logger.error(error.error); - } - throw error; - }).then(function (streams) { - _this.logger.log("acquired local media streams"); - try { - // Remove old tracks - if (_this.peerConnection.removeTrack) { - _this.peerConnection.getSenders().forEach(function (sender) { - _this.peerConnection.removeTrack(sender); - }); - } - return streams; - } - catch (e) { - return Promise.reject(e); - } - }) - .catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("acquire", e, "error removing streams"); - _this.logger.error(error.message); - if (error.error) { - _this.logger.error(error.error); - } - throw error; - }).then(function (streams) { - try { - streams = [].concat(streams); - streams.forEach(function (stream) { - if (_this.peerConnection.addTrack) { - stream.getTracks().forEach(function (track) { - _this.peerConnection.addTrack(track, stream); - }); - } - else { - // Chrome 59 does not support addTrack - _this.peerConnection.addStream(stream); - } - }); - } - catch (e) { - return Promise.reject(e); - } - return Promise.resolve(); - }) - .catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("acquire", e, "error adding stream"); - _this.logger.error(error.message); - if (error.error) { - _this.logger.error(error.error); - } - throw error; - }); - }; - SessionDescriptionHandler.prototype.hasOffer = function (where) { - var offerState = "have-" + where + "-offer"; - return this.peerConnection.signalingState === offerState; - }; - // ICE gathering state handling - SessionDescriptionHandler.prototype.isIceGatheringComplete = function () { - return this.peerConnection.iceGatheringState === "complete" || this.iceGatheringTimeout; - }; - SessionDescriptionHandler.prototype.resetIceGatheringComplete = function () { - this.iceGatheringTimeout = false; - this.logger.log("resetIceGatheringComplete"); - if (this.iceGatheringTimer) { - clearTimeout(this.iceGatheringTimer); - this.iceGatheringTimer = undefined; - } - if (this.iceGatheringDeferred) { - this.iceGatheringDeferred.reject(); - this.iceGatheringDeferred = undefined; - } - }; - SessionDescriptionHandler.prototype.setDirection = function (sdp) { - var match = sdp.match(/a=(sendrecv|sendonly|recvonly|inactive)/); - if (match === null) { - this.direction = this.C.DIRECTION.NULL; - this.observer.directionChanged(); - return; - } - var direction = match[1]; - switch (direction) { - case this.C.DIRECTION.SENDRECV: - case this.C.DIRECTION.SENDONLY: - case this.C.DIRECTION.RECVONLY: - case this.C.DIRECTION.INACTIVE: - this.direction = direction; - break; - default: - this.direction = this.C.DIRECTION.NULL; - break; - } - this.observer.directionChanged(); - }; - SessionDescriptionHandler.prototype.triggerIceGatheringComplete = function () { - if (this.isIceGatheringComplete()) { - this.emit("iceGatheringComplete", this); - if (this.iceGatheringTimer) { - clearTimeout(this.iceGatheringTimer); - this.iceGatheringTimer = undefined; - } - if (this.iceGatheringDeferred) { - this.iceGatheringDeferred.resolve(); - this.iceGatheringDeferred = undefined; - } - } - }; - SessionDescriptionHandler.prototype.waitForIceGatheringComplete = function () { - this.logger.log("waitForIceGatheringComplete"); - if (this.isIceGatheringComplete()) { - this.logger.log("ICE is already complete. Return resolved."); - return Promise.resolve(); - } - else if (!this.iceGatheringDeferred) { - this.iceGatheringDeferred = Utils_1.Utils.defer(); - } - this.logger.log("ICE is not complete. Returning promise"); - return this.iceGatheringDeferred ? this.iceGatheringDeferred.promise : Promise.resolve(); - }; - return SessionDescriptionHandler; -}(events_1.EventEmitter)); -exports.SessionDescriptionHandler = SessionDescriptionHandler; diff --git a/lib/React/SessionDescriptionHandlerObserver.d.ts b/lib/React/SessionDescriptionHandlerObserver.d.ts deleted file mode 100644 index 3a9ca0ebb..000000000 --- a/lib/React/SessionDescriptionHandlerObserver.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { TypeStrings } from "../Enums"; -import { InviteClientContext, InviteServerContext } from "../Session"; -export declare class SessionDescriptionHandlerObserver { - type: TypeStrings; - private session; - private options; - constructor(session: InviteClientContext | InviteServerContext, options: any); - trackAdded(): void; - directionChanged(): void; -} -//# sourceMappingURL=SessionDescriptionHandlerObserver.d.ts.map \ No newline at end of file diff --git a/lib/React/SessionDescriptionHandlerObserver.d.ts.map b/lib/React/SessionDescriptionHandlerObserver.d.ts.map deleted file mode 100644 index 320777c9b..000000000 --- a/lib/React/SessionDescriptionHandlerObserver.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"SessionDescriptionHandlerObserver.d.ts","sourceRoot":"","sources":["../../src/React/SessionDescriptionHandlerObserver.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AACvC,OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAQtE,qBAAa,iCAAiC;IACrC,IAAI,EAAE,WAAW,CAAC;IACzB,OAAO,CAAC,OAAO,CAA4C;IAC3D,OAAO,CAAC,OAAO,CAAM;gBAET,OAAO,EAAE,mBAAmB,GAAG,mBAAmB,EAAE,OAAO,EAAE,GAAG;IAMrE,UAAU,IAAI,IAAI;IAIlB,gBAAgB,IAAI,IAAI;CAGhC"} \ No newline at end of file diff --git a/lib/React/SessionDescriptionHandlerObserver.js b/lib/React/SessionDescriptionHandlerObserver.js deleted file mode 100644 index d410c8968..000000000 --- a/lib/React/SessionDescriptionHandlerObserver.js +++ /dev/null @@ -1,23 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var Enums_1 = require("../Enums"); -/* SessionDescriptionHandlerObserver - * @class SessionDescriptionHandler Observer Class. - * @param {SIP.Session} session - * @param {Object} [options] - */ -var SessionDescriptionHandlerObserver = /** @class */ (function () { - function SessionDescriptionHandlerObserver(session, options) { - this.type = Enums_1.TypeStrings.SessionDescriptionHandlerObserver; - this.session = session; - this.options = options; - } - SessionDescriptionHandlerObserver.prototype.trackAdded = function () { - this.session.emit("trackAdded"); - }; - SessionDescriptionHandlerObserver.prototype.directionChanged = function () { - this.session.emit("directionChanged"); - }; - return SessionDescriptionHandlerObserver; -}()); -exports.SessionDescriptionHandlerObserver = SessionDescriptionHandlerObserver; diff --git a/lib/React/index.d.ts b/lib/React/index.d.ts deleted file mode 100644 index 0e03ee72b..000000000 --- a/lib/React/index.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { SessionDescriptionHandler } from "./SessionDescriptionHandler"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/React/index.d.ts.map b/lib/React/index.d.ts.map deleted file mode 100644 index f1f2a6d99..000000000 --- a/lib/React/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/React/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,yBAAyB,EAAE,MAAM,6BAA6B,CAAC"} \ No newline at end of file diff --git a/lib/React/index.js b/lib/React/index.js deleted file mode 100644 index 3196ab1f6..000000000 --- a/lib/React/index.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var SessionDescriptionHandler_1 = require("./SessionDescriptionHandler"); -exports.SessionDescriptionHandler = SessionDescriptionHandler_1.SessionDescriptionHandler; diff --git a/lib/ReferContext.d.ts b/lib/ReferContext.d.ts deleted file mode 100644 index 57524bea5..000000000 --- a/lib/ReferContext.d.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { ClientContext } from "./ClientContext"; -import { IncomingRequest, NameAddrHeader, Session, URI } from "./core"; -import { SessionStatus, TypeStrings } from "./Enums"; -import { ServerContext } from "./ServerContext"; -import { InviteClientContext, InviteServerContext } from "./Session"; -import { SessionDescriptionHandlerModifiers } from "./session-description-handler"; -import { UA } from "./UA"; -export declare namespace ReferServerContext { - interface AcceptOptions { - /** If true, accept REFER request and automatically attempt to follow it. */ - followRefer?: boolean; - /** If followRefer is true, options to following INVITE request. */ - inviteOptions?: InviteClientContext.Options; - } - interface RejectOptions { - } -} -export declare class ReferClientContext extends ClientContext { - type: TypeStrings; - protected extraHeaders: Array; - protected options: any; - protected applicant: InviteClientContext | InviteServerContext; - protected target: URI | string; - private errorListener; - constructor(ua: UA, applicant: InviteClientContext | InviteServerContext, target: InviteClientContext | InviteServerContext | string, options?: any); - refer(options?: any): ReferClientContext; - receiveNotify(request: IncomingRequest): void; - protected initReferTo(target: InviteClientContext | InviteServerContext | string): string | URI; -} -export declare class ReferServerContext extends ServerContext { - private session?; - type: TypeStrings; - referTo: NameAddrHeader; - targetSession: InviteClientContext | InviteServerContext | undefined; - protected status: SessionStatus; - protected fromTag: string; - protected fromUri: URI; - protected toUri: URI; - protected toTag: string; - protected routeSet: Array; - protected remoteTarget: URI; - protected id: string; - protected callId: string; - protected cseq: number; - protected contact: string; - protected referredBy: string | undefined; - protected referredSession: InviteClientContext | InviteServerContext | undefined; - protected replaces: string | undefined; - protected errorListener: (() => void); - constructor(ua: UA, incomingRequest: IncomingRequest, session?: Session | undefined); - progress(): void; - reject(options?: ReferServerContext.RejectOptions): void; - accept(options?: ReferServerContext.AcceptOptions, modifiers?: SessionDescriptionHandlerModifiers): void; - sendNotify(bodyStr: string): void; - on(name: "referAccepted" | "referInviteSent" | "referProgress" | "referRejected" | "referRequestAccepted" | "referRequestRejected", callback: (referServerContext: ReferServerContext) => void): this; -} -//# sourceMappingURL=ReferContext.d.ts.map \ No newline at end of file diff --git a/lib/ReferContext.d.ts.map b/lib/ReferContext.d.ts.map deleted file mode 100644 index 073206ff5..000000000 --- a/lib/ReferContext.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"ReferContext.d.ts","sourceRoot":"","sources":["../src/ReferContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAEhD,OAAO,EAEL,eAAe,EAEf,cAAc,EAEd,OAAO,EACP,GAAG,EACJ,MAAM,QAAQ,CAAC;AAChB,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAErD,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EACL,mBAAmB,EACnB,mBAAmB,EACpB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,kCAAkC,EAAE,MAAM,+BAA+B,CAAC;AACnF,OAAO,EAAE,EAAE,EAAE,MAAM,MAAM,CAAC;AAE1B,yBAAiB,kBAAkB,CAAC;IAElC,UAAiB,aAAa;QAC5B,4EAA4E;QAC5E,WAAW,CAAC,EAAE,OAAO,CAAC;QACtB,mEAAmE;QACnE,aAAa,CAAC,EAAE,mBAAmB,CAAC,OAAO,CAAC;KAC7C;IAGD,UAAiB,aAAa;KAC7B;CACF;AAGD,qBAAa,kBAAmB,SAAQ,aAAa;IAC5C,IAAI,EAAE,WAAW,CAAC;IACzB,SAAS,CAAC,YAAY,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IACtC,SAAS,CAAC,OAAO,EAAE,GAAG,CAAC;IACvB,SAAS,CAAC,SAAS,EAAE,mBAAmB,GAAG,mBAAmB,CAAC;IAC/D,SAAS,CAAC,MAAM,EAAE,GAAG,GAAG,MAAM,CAAC;IAC/B,OAAO,CAAC,aAAa,CAA2B;gBAG9C,EAAE,EAAE,EAAE,EACN,SAAS,EAAE,mBAAmB,GAAG,mBAAmB,EACpD,MAAM,EAAE,mBAAmB,GAAG,mBAAmB,GAAG,MAAM,EAC1D,OAAO,GAAE,GAAQ;IAwCZ,KAAK,CAAC,OAAO,GAAE,GAAQ,GAAG,kBAAkB;IA0B5C,aAAa,CAAC,OAAO,EAAE,eAAe,GAAG,IAAI;IAqCpD,SAAS,CAAC,WAAW,CAAC,MAAM,EAAE,mBAAmB,GAAG,mBAAmB,GAAG,MAAM,GAAG,MAAM,GAAG,GAAG;CA8BhG;AAGD,qBAAa,kBAAmB,SAAQ,aAAa;IAqBG,OAAO,CAAC,OAAO,CAAC;IApB/D,IAAI,EAAE,WAAW,CAAC;IAClB,OAAO,EAAG,cAAc,CAAC;IACzB,aAAa,EAAE,mBAAmB,GAAG,mBAAmB,GAAG,SAAS,CAAC;IAE5E,SAAS,CAAC,MAAM,EAAE,aAAa,CAAC;IAChC,SAAS,CAAC,OAAO,EAAE,MAAM,CAAC;IAC1B,SAAS,CAAC,OAAO,EAAE,GAAG,CAAC;IACvB,SAAS,CAAC,KAAK,EAAE,GAAG,CAAC;IACrB,SAAS,CAAC,KAAK,EAAE,MAAM,CAAC;IACxB,SAAS,CAAC,QAAQ,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAClC,SAAS,CAAC,YAAY,EAAE,GAAG,CAAC;IAC5B,SAAS,CAAC,EAAE,EAAE,MAAM,CAAC;IACrB,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC;IACzB,SAAS,CAAC,IAAI,EAAE,MAAM,CAAC;IACvB,SAAS,CAAC,OAAO,EAAE,MAAM,CAAC;IAC1B,SAAS,CAAC,UAAU,EAAE,MAAM,GAAG,SAAS,CAAC;IACzC,SAAS,CAAC,eAAe,EAAG,mBAAmB,GAAG,mBAAmB,GAAG,SAAS,CAAC;IAClF,SAAS,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IACvC,SAAS,CAAC,aAAa,EAAG,CAAC,MAAM,IAAI,CAAC,CAAC;gBAE3B,EAAE,EAAE,EAAE,EAAE,eAAe,EAAE,eAAe,EAAU,OAAO,CAAC,qBAAS;IAmDxE,QAAQ,IAAI,IAAI;IAOhB,MAAM,CAAC,OAAO,GAAE,kBAAkB,CAAC,aAAkB,GAAG,IAAI;IAU5D,MAAM,CACX,OAAO,GAAE,kBAAkB,CAAC,aAAkB,EAC9C,SAAS,CAAC,EAAE,kCAAkC,GAC7C,IAAI;IA8FA,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAmEjC,EAAE,CACP,IAAI,EACF,eAAe,GACf,iBAAiB,GACjB,eAAe,GACf,eAAe,GACf,sBAAsB,GACtB,sBAAsB,EACxB,QAAQ,EAAE,CAAC,kBAAkB,EAAE,kBAAkB,KAAK,IAAI,GACzD,IAAI;CAER"} \ No newline at end of file diff --git a/lib/ReferContext.js b/lib/ReferContext.js deleted file mode 100644 index 2775dedb7..000000000 --- a/lib/ReferContext.js +++ /dev/null @@ -1,344 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var ClientContext_1 = require("./ClientContext"); -var Constants_1 = require("./Constants"); -var core_1 = require("./core"); -var Enums_1 = require("./Enums"); -var Exceptions_1 = require("./Exceptions"); -var ServerContext_1 = require("./ServerContext"); -// tslint:disable-next-line:max-classes-per-file -var ReferClientContext = /** @class */ (function (_super) { - tslib_1.__extends(ReferClientContext, _super); - function ReferClientContext(ua, applicant, target, options) { - if (options === void 0) { options = {}; } - var _this = this; - if (ua === undefined || applicant === undefined || target === undefined) { - throw new TypeError("Not enough arguments"); - } - _this = _super.call(this, ua, Constants_1.C.REFER, applicant.remoteIdentity.uri.toString(), options) || this; - _this.type = Enums_1.TypeStrings.ReferClientContext; - _this.options = options; - _this.extraHeaders = (_this.options.extraHeaders || []).slice(); - _this.applicant = applicant; - _this.target = _this.initReferTo(target); - if (_this.ua) { - _this.extraHeaders.push("Referred-By: <" + _this.ua.configuration.uri + ">"); - } - // TODO: Check that this is correct isc/icc - _this.extraHeaders.push("Contact: " + applicant.contact); - // this is UA.C.ALLOWED_METHODS, removed to get around circular dependency - _this.extraHeaders.push("Allow: " + [ - "ACK", - "CANCEL", - "INVITE", - "MESSAGE", - "BYE", - "OPTIONS", - "INFO", - "NOTIFY", - "REFER" - ].toString()); - _this.extraHeaders.push("Refer-To: " + _this.target); - _this.errorListener = _this.onTransportError.bind(_this); - if (ua.transport) { - ua.transport.on("transportError", _this.errorListener); - } - return _this; - } - ReferClientContext.prototype.refer = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - var extraHeaders = (this.extraHeaders || []).slice(); - if (options.extraHeaders) { - extraHeaders.concat(options.extraHeaders); - } - this.applicant.sendRequest(Constants_1.C.REFER, { - extraHeaders: this.extraHeaders, - receiveResponse: function (response) { - var statusCode = response && response.statusCode ? response.statusCode.toString() : ""; - if (/^1[0-9]{2}$/.test(statusCode)) { - _this.emit("referRequestProgress", _this); - } - else if (/^2[0-9]{2}$/.test(statusCode)) { - _this.emit("referRequestAccepted", _this); - } - else if (/^[4-6][0-9]{2}$/.test(statusCode)) { - _this.emit("referRequestRejected", _this); - } - if (options.receiveResponse) { - options.receiveResponse(response); - } - } - }); - return this; - }; - ReferClientContext.prototype.receiveNotify = function (request) { - // If we can correctly handle this, then we need to send a 200 OK! - var contentType = request.message.hasHeader("Content-Type") ? - request.message.getHeader("Content-Type") : undefined; - if (contentType && contentType.search(/^message\/sipfrag/) !== -1) { - var messageBody = core_1.Grammar.parse(request.message.body, "sipfrag"); - if (messageBody === -1) { - request.reject({ - statusCode: 489, - reasonPhrase: "Bad Event" - }); - return; - } - switch (true) { - case (/^1[0-9]{2}$/.test(messageBody.status_code)): - this.emit("referProgress", this); - break; - case (/^2[0-9]{2}$/.test(messageBody.status_code)): - this.emit("referAccepted", this); - if (!this.options.activeAfterTransfer && this.applicant.terminate) { - this.applicant.terminate(); - } - break; - default: - this.emit("referRejected", this); - break; - } - request.accept(); - this.emit("notify", request.message); - return; - } - request.reject({ - statusCode: 489, - reasonPhrase: "Bad Event" - }); - }; - ReferClientContext.prototype.initReferTo = function (target) { - var stringOrURI; - if (typeof target === "string") { - // REFER without Replaces (Blind Transfer) - var targetString = core_1.Grammar.parse(target, "Refer_To"); - stringOrURI = targetString && targetString.uri ? targetString.uri : target; - // Check target validity - var targetUri = this.ua.normalizeTarget(target); - if (!targetUri) { - throw new TypeError("Invalid target: " + target); - } - stringOrURI = targetUri; - } - else { - // REFER with Replaces (Attended Transfer) - if (!target.session) { - throw new Error("Session undefined."); - } - var displayName = target.remoteIdentity.friendlyName; - var remoteTarget = target.session.remoteTarget.toString(); - var callId = target.session.callId; - var remoteTag = target.session.remoteTag; - var localTag = target.session.localTag; - var replaces = encodeURIComponent(callId + ";to-tag=" + remoteTag + ";from-tag=" + localTag); - stringOrURI = "\"" + displayName + "\" <" + remoteTarget + "?Replaces=" + replaces + ">"; - } - return stringOrURI; - }; - return ReferClientContext; -}(ClientContext_1.ClientContext)); -exports.ReferClientContext = ReferClientContext; -// tslint:disable-next-line:max-classes-per-file -var ReferServerContext = /** @class */ (function (_super) { - tslib_1.__extends(ReferServerContext, _super); - function ReferServerContext(ua, incomingRequest, session) { - var _this = _super.call(this, ua, incomingRequest) || this; - _this.session = session; - _this.type = Enums_1.TypeStrings.ReferServerContext; - _this.ua = ua; - _this.status = Enums_1.SessionStatus.STATUS_INVITE_RECEIVED; - _this.fromTag = _this.request.fromTag; - _this.id = _this.request.callId + _this.fromTag; - _this.contact = _this.ua.contact.toString(); - _this.logger = ua.getLogger("sip.referservercontext", _this.id); - // Needed to send the NOTIFY's - _this.cseq = Math.floor(Math.random() * 10000); - _this.callId = _this.request.callId; - _this.fromUri = _this.request.to.uri; - _this.fromTag = _this.request.to.parameters.tag; - _this.remoteTarget = _this.request.headers.Contact[0].parsed.uri; - _this.toUri = _this.request.from.uri; - _this.toTag = _this.request.fromTag; - _this.routeSet = _this.request.getHeaders("record-route"); - // RFC 3515 2.4.1 - if (!_this.request.hasHeader("refer-to")) { - _this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting refer."); - _this.reject(); - return _this; - } - _this.referTo = _this.request.parseHeader("refer-to"); - // TODO: Must set expiration timer and send 202 if there is no response by then - _this.referredSession = _this.ua.findSession(_this.request); - if (_this.request.hasHeader("referred-by")) { - _this.referredBy = _this.request.getHeader("referred-by"); - } - if (_this.referTo.uri.hasHeader("replaces")) { - _this.replaces = _this.referTo.uri.getHeader("replaces"); - } - _this.errorListener = _this.onTransportError.bind(_this); - if (ua.transport) { - ua.transport.on("transportError", _this.errorListener); - } - _this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER; - return _this; - } - ReferServerContext.prototype.progress = function () { - if (this.status !== Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER) { - throw new Exceptions_1.Exceptions.InvalidStateError(this.status); - } - this.incomingRequest.trying(); - }; - ReferServerContext.prototype.reject = function (options) { - if (options === void 0) { options = {}; } - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - throw new Exceptions_1.Exceptions.InvalidStateError(this.status); - } - this.logger.log("Rejecting refer"); - this.status = Enums_1.SessionStatus.STATUS_TERMINATED; - _super.prototype.reject.call(this, options); - this.emit("referRequestRejected", this); - }; - ReferServerContext.prototype.accept = function (options, modifiers) { - var _this = this; - if (options === void 0) { options = {}; } - if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER) { - this.status = Enums_1.SessionStatus.STATUS_ANSWERED; - } - else { - throw new Exceptions_1.Exceptions.InvalidStateError(this.status); - } - this.incomingRequest.accept({ - statusCode: 202, - reasonPhrase: "Accepted" - }); - this.emit("referRequestAccepted", this); - if (options.followRefer) { - this.logger.log("Accepted refer, attempting to automatically follow it"); - var target = this.referTo.uri; - if (!target.scheme || !target.scheme.match("^sips?$")) { - this.logger.error("SIP.js can only automatically follow SIP refer target"); - this.reject(); - return; - } - var inviteOptions = options.inviteOptions || {}; - var extraHeaders = (inviteOptions.extraHeaders || []).slice(); - if (this.replaces) { - // decodeURIComponent is a holdover from 2c086eb4. Not sure that it is actually necessary - extraHeaders.push("Replaces: " + decodeURIComponent(this.replaces)); - } - if (this.referredBy) { - extraHeaders.push("Referred-By: " + this.referredBy); - } - inviteOptions.extraHeaders = extraHeaders; - target.clearHeaders(); - this.targetSession = this.ua.invite(target.toString(), inviteOptions, modifiers); - this.emit("referInviteSent", this); - if (this.targetSession) { - this.targetSession.once("progress", function (response) { - var statusCode = response.statusCode || 100; - var reasonPhrase = response.reasonPhrase; - _this.sendNotify(("SIP/2.0 " + statusCode + " " + reasonPhrase).trim()); - _this.emit("referProgress", _this); - if (_this.referredSession) { - _this.referredSession.emit("referProgress", _this); - } - }); - this.targetSession.once("accepted", function () { - _this.logger.log("Successfully followed the refer"); - _this.sendNotify("SIP/2.0 200 OK"); - _this.emit("referAccepted", _this); - if (_this.referredSession) { - _this.referredSession.emit("referAccepted", _this); - } - }); - var referFailed = function (response) { - if (_this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return; // No throw here because it is possible this gets called multiple times - } - _this.logger.log("Refer was not successful. Resuming session"); - if (response && response.statusCode === 429) { - _this.logger.log("Alerting referrer that identity is required."); - _this.sendNotify("SIP/2.0 429 Provide Referrer Identity"); - return; - } - _this.sendNotify("SIP/2.0 603 Declined"); - // Must change the status after sending the final Notify or it will not send due to check - _this.status = Enums_1.SessionStatus.STATUS_TERMINATED; - _this.emit("referRejected", _this); - if (_this.referredSession) { - _this.referredSession.emit("referRejected"); - } - }; - this.targetSession.once("rejected", referFailed); - this.targetSession.once("failed", referFailed); - } - } - else { - this.logger.log("Accepted refer, but did not automatically follow it"); - this.sendNotify("SIP/2.0 200 OK"); - this.emit("referAccepted", this); - if (this.referredSession) { - this.referredSession.emit("referAccepted", this); - } - } - }; - ReferServerContext.prototype.sendNotify = function (bodyStr) { - // FIXME: Ported this. Clean it up. Session knows its state. - if (this.status !== Enums_1.SessionStatus.STATUS_ANSWERED) { - throw new Exceptions_1.Exceptions.InvalidStateError(this.status); - } - if (core_1.Grammar.parse(bodyStr, "sipfrag") === -1) { - throw new Error("sipfrag body is required to send notify for refer"); - } - var body = { - contentDisposition: "render", - contentType: "message/sipfrag", - content: bodyStr - }; - // NOTIFY requests sent in same dialog as in dialog REFER. - if (this.session) { - this.session.notify(undefined, { - extraHeaders: [ - "Event: refer", - "Subscription-State: terminated", - ], - body: body - }); - return; - } - // The implicit subscription created by a REFER is the same as a - // subscription created with a SUBSCRIBE request. The agent issuing the - // REFER can terminate this subscription prematurely by unsubscribing - // using the mechanisms described in [2]. Terminating a subscription, - // either by explicitly unsubscribing or rejecting NOTIFY, is not an - // indication that the referenced request should be withdrawn or - // abandoned. - // https://tools.ietf.org/html/rfc3515#section-2.4.4 - // NOTIFY requests sent in new dialog for out of dialog REFER. - // FIXME: TODO: This should be done in a subscribe dialog to satisfy the above. - var request = this.ua.userAgentCore.makeOutgoingRequestMessage(Constants_1.C.NOTIFY, this.remoteTarget, this.fromUri, this.toUri, { - cseq: this.cseq += 1, - callId: this.callId, - fromTag: this.fromTag, - toTag: this.toTag, - routeSet: this.routeSet - }, [ - "Event: refer", - "Subscription-State: terminated", - "Content-Type: message/sipfrag" - ], body); - var transport = this.ua.transport; - if (!transport) { - throw new Error("Transport undefined."); - } - var user = { - loggerFactory: this.ua.getLoggerFactory() - }; - var nic = new core_1.NonInviteClientTransaction(request, transport, user); - }; - ReferServerContext.prototype.on = function (name, callback) { return _super.prototype.on.call(this, name, callback); }; - return ReferServerContext; -}(ServerContext_1.ServerContext)); -exports.ReferServerContext = ReferServerContext; diff --git a/lib/RegisterContext.d.ts b/lib/RegisterContext.d.ts deleted file mode 100644 index ef2c93e62..000000000 --- a/lib/RegisterContext.d.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { ClientContext } from "./ClientContext"; -import { IncomingResponseMessage } from "./core"; -import { TypeStrings } from "./Enums"; -import { UA } from "./UA"; -export declare namespace RegisterContext { - interface RegistrationConfiguration { - expires?: string; - extraContactHeaderParams?: Array; - instanceId?: string; - params?: any; - regId?: number; - registrar?: string; - } -} -export declare class RegisterContext extends ClientContext { - type: TypeStrings; - registered: boolean; - private options; - private expires; - private contact; - private registrationTimer; - private registrationExpiredTimer; - private registeredBefore; - private closeHeaders; - constructor(ua: UA, options?: any); - register(options?: any): void; - close(): void; - unregister(options?: any): void; - unregistered(response?: IncomingResponseMessage, cause?: string): void; - send(): this; - private registrationFailure; - private onTransportDisconnected; - /** - * Helper Function to generate Contact Header - * @private - * returns {String} - */ - private generateContactHeader; -} -//# sourceMappingURL=RegisterContext.d.ts.map \ No newline at end of file diff --git a/lib/RegisterContext.d.ts.map b/lib/RegisterContext.d.ts.map deleted file mode 100644 index 40b64a670..000000000 --- a/lib/RegisterContext.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"RegisterContext.d.ts","sourceRoot":"","sources":["../src/RegisterContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAEhD,OAAO,EAAW,uBAAuB,EAAO,MAAM,QAAQ,CAAC;AAE/D,OAAO,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAEtC,OAAO,EAAE,EAAE,EAAE,MAAM,MAAM,CAAC;AAG1B,yBAAiB,eAAe,CAAC;IAC/B,UAAiB,yBAAyB;QACxC,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,wBAAwB,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;QACzC,UAAU,CAAC,EAAE,MAAM,CAAC;QACpB,MAAM,CAAC,EAAE,GAAG,CAAC;QACb,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,SAAS,CAAC,EAAE,MAAM,CAAC;KACpB;CACF;AAmID,qBAAa,eAAgB,SAAQ,aAAa;IACzC,IAAI,EAAE,WAAW,CAAC;IAClB,UAAU,EAAE,OAAO,CAAC;IAE3B,OAAO,CAAC,OAAO,CAAM;IACrB,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,OAAO,CAAS;IAExB,OAAO,CAAC,iBAAiB,CAAkB;IAC3C,OAAO,CAAC,wBAAwB,CAAkB;IAClD,OAAO,CAAC,gBAAgB,CAAsB;IAE9C,OAAO,CAAC,YAAY,CAA4B;gBAEpC,EAAE,EAAE,EAAE,EAAE,OAAO,GAAE,GAAQ;IAmD9B,QAAQ,CAAC,OAAO,GAAE,GAAQ,GAAG,IAAI;IAyIjC,KAAK,IAAI,IAAI;IAYb,UAAU,CAAC,OAAO,GAAE,GAAQ,GAAG,IAAI;IAqDnC,YAAY,CAAC,QAAQ,CAAC,EAAE,uBAAuB,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI;IAKtE,IAAI,IAAI,IAAI;IAWnB,OAAO,CAAC,mBAAmB;IAI3B,OAAO,CAAC,uBAAuB;IAiB/B;;;;OAIG;IACH,OAAO,CAAC,qBAAqB;CAiB9B"} \ No newline at end of file diff --git a/lib/RegisterContext.js b/lib/RegisterContext.js deleted file mode 100644 index 3cc3683b0..000000000 --- a/lib/RegisterContext.js +++ /dev/null @@ -1,411 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var ClientContext_1 = require("./ClientContext"); -var Constants_1 = require("./Constants"); -var core_1 = require("./core"); -var Enums_1 = require("./Enums"); -var Exceptions_1 = require("./Exceptions"); -var Utils_1 = require("./Utils"); -/** - * Configuration load. - * @private - * returns {any} - */ -function loadConfig(configuration) { - var settings = { - expires: 600, - extraContactHeaderParams: [], - instanceId: undefined, - params: {}, - regId: undefined, - registrar: undefined, - }; - var configCheck = getConfigurationCheck(); - // Check Mandatory parameters - for (var parameter in configCheck.mandatory) { - if (!configuration.hasOwnProperty(parameter)) { - throw new Exceptions_1.Exceptions.ConfigurationError(parameter); - } - else { - var value = configuration[parameter]; - var checkedValue = configCheck.mandatory[parameter](value); - if (checkedValue !== undefined) { - settings[parameter] = checkedValue; - } - else { - throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); - } - } - } - // Check Optional parameters - for (var parameter in configCheck.optional) { - if (configuration.hasOwnProperty(parameter)) { - var value = configuration[parameter]; - // If the parameter value is an empty array, but shouldn't be, apply its default value. - if (value instanceof Array && value.length === 0) { - continue; - } - // If the parameter value is null, empty string, or undefined then apply its default value. - // If it's a number with NaN value then also apply its default value. - // NOTE: JS does not allow "value === NaN", the following does the work: - if (value === null || value === "" || value === undefined || - (typeof (value) === "number" && isNaN(value))) { - continue; - } - var checkedValue = configCheck.optional[parameter](value); - if (checkedValue !== undefined) { - settings[parameter] = checkedValue; - } - else { - throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); - } - } - } - return settings; -} -function getConfigurationCheck() { - return { - mandatory: {}, - optional: { - expires: function (expires) { - if (Utils_1.Utils.isDecimal(expires)) { - var value = Number(expires); - if (value >= 0) { - return value; - } - } - }, - extraContactHeaderParams: function (extraContactHeaderParams) { - if (extraContactHeaderParams instanceof Array) { - return extraContactHeaderParams.filter(function (contactHeaderParam) { return (typeof contactHeaderParam === "string"); }); - } - }, - instanceId: function (instanceId) { - if (typeof instanceId !== "string") { - return; - } - if ((/^uuid:/i.test(instanceId))) { - instanceId = instanceId.substr(5); - } - if (core_1.Grammar.parse(instanceId, "uuid") === -1) { - return; - } - else { - return instanceId; - } - }, - params: function (params) { - if (typeof params === "object") { - return params; - } - }, - regId: function (regId) { - if (Utils_1.Utils.isDecimal(regId)) { - var value = Number(regId); - if (value >= 0) { - return value; - } - } - }, - registrar: function (registrar) { - if (typeof registrar !== "string") { - return; - } - if (!/^sip:/i.test(registrar)) { - registrar = Constants_1.C.SIP + ":" + registrar; - } - var parsed = core_1.Grammar.URIParse(registrar); - if (!parsed) { - return; - } - else if (parsed.user) { - return; - } - else { - return parsed; - } - } - } - }; -} -var RegisterContext = /** @class */ (function (_super) { - tslib_1.__extends(RegisterContext, _super); - function RegisterContext(ua, options) { - if (options === void 0) { options = {}; } - var _this = this; - var settings = loadConfig(options); - if (settings.regId && !settings.instanceId) { - settings.instanceId = Utils_1.Utils.newUUID(); - } - else if (!settings.regId && settings.instanceId) { - settings.regId = 1; - } - settings.params.toUri = settings.params.toUri || ua.configuration.uri; - settings.params.toDisplayName = settings.params.toDisplayName || ua.configuration.displayName; - settings.params.callId = settings.params.callId || Utils_1.Utils.createRandomToken(22); - settings.params.cseq = settings.params.cseq || Math.floor(Math.random() * 10000); - /* If no 'registrarServer' is set use the 'uri' value without user portion. */ - if (!settings.registrar) { - var registrarServer = {}; - if (typeof ua.configuration.uri === "object") { - registrarServer = ua.configuration.uri.clone(); - registrarServer.user = undefined; - } - else { - registrarServer = ua.configuration.uri; - } - settings.registrar = registrarServer; - } - _this = _super.call(this, ua, Constants_1.C.REGISTER, settings.registrar, settings) || this; - _this.type = Enums_1.TypeStrings.RegisterContext; - _this.options = settings; - _this.logger = ua.getLogger("sip.registercontext"); - _this.logger.log("configuration parameters for RegisterContext after validation:"); - for (var parameter in settings) { - if (settings.hasOwnProperty(parameter)) { - _this.logger.log("· " + parameter + ": " + JSON.stringify(settings[parameter])); - } - } - // Registration expires - _this.expires = settings.expires; - // Contact header - _this.contact = ua.contact.toString(); - // Set status - _this.registered = false; - ua.transport.on("disconnected", function () { return _this.onTransportDisconnected(); }); - return _this; - } - RegisterContext.prototype.register = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - // Handle Options - this.options = tslib_1.__assign({}, this.options, options); - var extraHeaders = (this.options.extraHeaders || []).slice(); - extraHeaders.push("Contact: " + this.generateContactHeader(this.expires)); - // this is UA.C.ALLOWED_METHODS, removed to get around circular dependency - extraHeaders.push("Allow: " + [ - "ACK", - "CANCEL", - "INVITE", - "MESSAGE", - "BYE", - "OPTIONS", - "INFO", - "NOTIFY", - "REFER" - ].toString()); - // Save original extraHeaders to be used in .close - this.closeHeaders = this.options.closeWithHeaders ? - (this.options.extraHeaders || []).slice() : []; - this.receiveResponse = function (response) { - // Discard responses to older REGISTER/un-REGISTER requests. - if (response.cseq !== _this.request.cseq) { - return; - } - // Clear registration timer - if (_this.registrationTimer !== undefined) { - clearTimeout(_this.registrationTimer); - _this.registrationTimer = undefined; - } - var statusCode = (response.statusCode || 0).toString(); - switch (true) { - case /^1[0-9]{2}$/.test(statusCode): - _this.emit("progress", response); - break; - case /^2[0-9]{2}$/.test(statusCode): - _this.emit("accepted", response); - var expires = void 0; - if (response.hasHeader("expires")) { - expires = Number(response.getHeader("expires")); - } - if (_this.registrationExpiredTimer !== undefined) { - clearTimeout(_this.registrationExpiredTimer); - _this.registrationExpiredTimer = undefined; - } - // Search the Contact pointing to us and update the expires value accordingly. - var contacts = response.getHeaders("contact").length; - if (!contacts) { - _this.logger.warn("no Contact header in response to REGISTER, response ignored"); - break; - } - var contact = void 0; - while (contacts--) { - contact = response.parseHeader("contact", contacts); - if (contact.uri.user === _this.ua.contact.uri.user) { - expires = contact.getParam("expires"); - break; - } - else { - contact = undefined; - } - } - if (!contact) { - _this.logger.warn("no Contact header pointing to us, response ignored"); - break; - } - if (expires === undefined) { - expires = _this.expires; - } - // Re-Register before the expiration interval has elapsed. - // For that, decrease the expires value. ie: 3 seconds - _this.registrationTimer = setTimeout(function () { - _this.registrationTimer = undefined; - _this.register(_this.options); - }, (expires * 1000) - 3000); - _this.registrationExpiredTimer = setTimeout(function () { - _this.logger.warn("registration expired"); - if (_this.registered) { - _this.unregistered(undefined, Constants_1.C.causes.EXPIRES); - } - }, expires * 1000); - // Save gruu values - if (contact.hasParam("temp-gruu")) { - _this.ua.contact.tempGruu = core_1.Grammar.URIParse(contact.getParam("temp-gruu").replace(/"/g, "")); - } - if (contact.hasParam("pub-gruu")) { - _this.ua.contact.pubGruu = core_1.Grammar.URIParse(contact.getParam("pub-gruu").replace(/"/g, "")); - } - _this.registered = true; - _this.emit("registered", response || undefined); - break; - // Interval too brief RFC3261 10.2.8 - case /^423$/.test(statusCode): - if (response.hasHeader("min-expires")) { - // Increase our registration interval to the suggested minimum - _this.expires = Number(response.getHeader("min-expires")); - // Attempt the registration again immediately - _this.register(_this.options); - } - else { // This response MUST contain a Min-Expires header field - _this.logger.warn("423 response received for REGISTER without Min-Expires"); - _this.registrationFailure(response, Constants_1.C.causes.SIP_FAILURE_CODE); - } - break; - default: - _this.registrationFailure(response, Utils_1.Utils.sipErrorCause(response.statusCode || 0)); - } - }; - this.onRequestTimeout = function () { - _this.registrationFailure(undefined, Constants_1.C.causes.REQUEST_TIMEOUT); - }; - this.onTransportError = function () { - _this.registrationFailure(undefined, Constants_1.C.causes.CONNECTION_ERROR); - }; - this.request.cseq++; - this.request.setHeader("cseq", this.request.cseq + " REGISTER"); - this.request.extraHeaders = extraHeaders; - this.send(); - }; - RegisterContext.prototype.close = function () { - var options = { - all: false, - extraHeaders: this.closeHeaders - }; - this.registeredBefore = this.registered; - if (this.registered) { - this.unregister(options); - } - }; - RegisterContext.prototype.unregister = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - if (!this.registered && !options.all) { - this.logger.warn("Already unregistered, but sending an unregister anyways."); - } - var extraHeaders = (options.extraHeaders || []).slice(); - this.registered = false; - // Clear the registration timer. - if (this.registrationTimer !== undefined) { - clearTimeout(this.registrationTimer); - this.registrationTimer = undefined; - } - if (options.all) { - extraHeaders.push("Contact: *"); - extraHeaders.push("Expires: 0"); - } - else { - extraHeaders.push("Contact: " + this.generateContactHeader(0)); - } - this.receiveResponse = function (response) { - var statusCode = (response && response.statusCode) ? response.statusCode.toString() : ""; - switch (true) { - case /^1[0-9]{2}$/.test(statusCode): - _this.emit("progress", response); - break; - case /^2[0-9]{2}$/.test(statusCode): - _this.emit("accepted", response); - if (_this.registrationExpiredTimer !== undefined) { - clearTimeout(_this.registrationExpiredTimer); - _this.registrationExpiredTimer = undefined; - } - _this.unregistered(response); - break; - default: - _this.unregistered(response, Utils_1.Utils.sipErrorCause(response.statusCode || 0)); - } - }; - this.onRequestTimeout = function () { - // Not actually unregistered... - // this.unregistered(undefined, SIP.C.causes.REQUEST_TIMEOUT); - }; - this.request.cseq++; - this.request.setHeader("cseq", this.request.cseq + " REGISTER"); - this.request.extraHeaders = extraHeaders; - this.send(); - }; - RegisterContext.prototype.unregistered = function (response, cause) { - this.registered = false; - this.emit("unregistered", response || undefined, cause || undefined); - }; - RegisterContext.prototype.send = function () { - var _this = this; - this.ua.userAgentCore.register(this.request, { - onAccept: function (response) { return _this.receiveResponse(response.message); }, - onProgress: function (response) { return _this.receiveResponse(response.message); }, - onRedirect: function (response) { return _this.receiveResponse(response.message); }, - onReject: function (response) { return _this.receiveResponse(response.message); }, - onTrying: function (response) { return _this.receiveResponse(response.message); } - }); - return this; - }; - RegisterContext.prototype.registrationFailure = function (response, cause) { - this.emit("failed", response || undefined, cause || undefined); - }; - RegisterContext.prototype.onTransportDisconnected = function () { - this.registeredBefore = this.registered; - if (this.registrationTimer !== undefined) { - clearTimeout(this.registrationTimer); - this.registrationTimer = undefined; - } - if (this.registrationExpiredTimer !== undefined) { - clearTimeout(this.registrationExpiredTimer); - this.registrationExpiredTimer = undefined; - } - if (this.registered) { - this.unregistered(undefined, Constants_1.C.causes.CONNECTION_ERROR); - } - }; - /** - * Helper Function to generate Contact Header - * @private - * returns {String} - */ - RegisterContext.prototype.generateContactHeader = function (expires) { - if (expires === void 0) { expires = 0; } - var contact = this.contact; - if (this.options.regId && this.options.instanceId) { - contact += ";reg-id=" + this.options.regId; - contact += ';+sip.instance=""'; - } - if (this.options.extraContactHeaderParams) { - this.options.extraContactHeaderParams.forEach(function (header) { - contact += ";" + header; - }); - } - contact += ";expires=" + expires; - return contact; - }; - return RegisterContext; -}(ClientContext_1.ClientContext)); -exports.RegisterContext = RegisterContext; diff --git a/lib/ServerContext.d.ts b/lib/ServerContext.d.ts deleted file mode 100644 index fb28e9dd3..000000000 --- a/lib/ServerContext.d.ts +++ /dev/null @@ -1,29 +0,0 @@ -/// -import { EventEmitter } from "events"; -import { IncomingRequest, IncomingRequestMessage, InviteServerTransaction, Logger, NameAddrHeader, NonInviteServerTransaction } from "./core"; -import { TypeStrings } from "./Enums"; -import { UA } from "./UA"; -export declare class ServerContext extends EventEmitter { - incomingRequest: IncomingRequest; - static initializer(objectToConstruct: ServerContext, ua: UA, incomingRequest: IncomingRequest): void; - type: TypeStrings; - ua: UA; - logger: Logger; - localIdentity: NameAddrHeader; - remoteIdentity: NameAddrHeader; - method: string; - request: IncomingRequestMessage; - data: any; - transaction: InviteServerTransaction | NonInviteServerTransaction; - body: any; - contentType: string | undefined; - assertedIdentity: NameAddrHeader | undefined; - constructor(ua: UA, incomingRequest: IncomingRequest); - progress(options?: any): any; - accept(options?: any): any; - reject(options?: any): any; - reply(options?: any): any; - onRequestTimeout(): void; - onTransportError(): void; -} -//# sourceMappingURL=ServerContext.d.ts.map \ No newline at end of file diff --git a/lib/ServerContext.d.ts.map b/lib/ServerContext.d.ts.map deleted file mode 100644 index 4ae962d26..000000000 --- a/lib/ServerContext.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"ServerContext.d.ts","sourceRoot":"","sources":["../src/ServerContext.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAGtC,OAAO,EAGL,eAAe,EACf,sBAAsB,EACtB,uBAAuB,EACvB,MAAM,EACN,cAAc,EACd,0BAA0B,EAE3B,MAAM,QAAQ,CAAC;AAChB,OAAO,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AACtC,OAAO,EAAE,EAAE,EAAE,MAAM,MAAM,CAAC;AAG1B,qBAAa,aAAc,SAAQ,YAAY;IA2ClB,eAAe,EAAE,eAAe;WAzC7C,WAAW,CAAC,iBAAiB,EAAE,aAAa,EAAE,EAAE,EAAE,EAAE,EAAE,eAAe,EAAE,eAAe,GAAG,IAAI;IAyBpG,IAAI,EAAG,WAAW,CAAC;IACnB,EAAE,EAAG,EAAE,CAAC;IACR,MAAM,EAAG,MAAM,CAAC;IAChB,aAAa,EAAG,cAAc,CAAC;IAC/B,cAAc,EAAG,cAAc,CAAC;IAChC,MAAM,EAAG,MAAM,CAAC;IAChB,OAAO,EAAG,sBAAsB,CAAC;IACjC,IAAI,EAAE,GAAG,CAAM;IAIf,WAAW,EAAG,uBAAuB,GAAG,0BAA0B,CAAC;IACnE,IAAI,EAAE,GAAG,CAAC;IACV,WAAW,EAAE,MAAM,GAAG,SAAS,CAAC;IAChC,gBAAgB,EAAE,cAAc,GAAG,SAAS,CAAC;gBAExC,EAAE,EAAE,EAAE,EAAS,eAAe,EAAE,eAAe;IAMpD,QAAQ,CAAC,OAAO,GAAE,GAAQ,GAAG,GAAG;IAShC,MAAM,CAAC,OAAO,GAAE,GAAQ,GAAG,GAAG;IAS9B,MAAM,CAAC,OAAO,GAAE,GAAQ,GAAG,GAAG;IAS9B,KAAK,CAAC,OAAO,GAAE,GAAQ,GAAG,GAAG;IAiD7B,gBAAgB,IAAI,IAAI;IAIxB,gBAAgB,IAAI,IAAI;CAGhC"} \ No newline at end of file diff --git a/lib/ServerContext.js b/lib/ServerContext.js deleted file mode 100644 index 37e40c588..000000000 --- a/lib/ServerContext.js +++ /dev/null @@ -1,119 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var events_1 = require("events"); -var Constants_1 = require("./Constants"); -var core_1 = require("./core"); -var Enums_1 = require("./Enums"); -var Utils_1 = require("./Utils"); -var ServerContext = /** @class */ (function (_super) { - tslib_1.__extends(ServerContext, _super); - function ServerContext(ua, incomingRequest) { - var _this = _super.call(this) || this; - _this.incomingRequest = incomingRequest; - _this.data = {}; - ServerContext.initializer(_this, ua, incomingRequest); - return _this; - } - // hack to get around our multiple inheritance issues - ServerContext.initializer = function (objectToConstruct, ua, incomingRequest) { - var request = incomingRequest.message; - objectToConstruct.type = Enums_1.TypeStrings.ServerContext; - objectToConstruct.ua = ua; - objectToConstruct.logger = ua.getLogger("sip.servercontext"); - objectToConstruct.request = request; - if (request.body) { - objectToConstruct.body = request.body; - } - if (request.hasHeader("Content-Type")) { - objectToConstruct.contentType = request.getHeader("Content-Type"); - } - objectToConstruct.method = request.method; - objectToConstruct.localIdentity = request.to; - objectToConstruct.remoteIdentity = request.from; - var hasAssertedIdentity = request.hasHeader("P-Asserted-Identity"); - if (hasAssertedIdentity) { - var assertedIdentity = request.getHeader("P-Asserted-Identity"); - if (assertedIdentity) { - objectToConstruct.assertedIdentity = core_1.Grammar.nameAddrHeaderParse(assertedIdentity); - } - } - }; - ServerContext.prototype.progress = function (options) { - if (options === void 0) { options = {}; } - options.statusCode = options.statusCode || 180; - options.minCode = 100; - options.maxCode = 199; - options.events = ["progress"]; - return this.reply(options); - }; - ServerContext.prototype.accept = function (options) { - if (options === void 0) { options = {}; } - options.statusCode = options.statusCode || 200; - options.minCode = 200; - options.maxCode = 299; - options.events = ["accepted"]; - return this.reply(options); - }; - ServerContext.prototype.reject = function (options) { - if (options === void 0) { options = {}; } - options.statusCode = options.statusCode || 480; - options.minCode = 300; - options.maxCode = 699; - options.events = ["rejected", "failed"]; - return this.reply(options); - }; - ServerContext.prototype.reply = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - var statusCode = options.statusCode || 100; - var minCode = options.minCode || 100; - var maxCode = options.maxCode || 699; - var reasonPhrase = Utils_1.Utils.getReasonPhrase(statusCode, options.reasonPhrase); - var extraHeaders = options.extraHeaders || []; - var body = options.body ? core_1.fromBodyLegacy(options.body) : undefined; - var events = options.events || []; - if (statusCode < minCode || statusCode > maxCode) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - var responseOptions = { - statusCode: statusCode, - reasonPhrase: reasonPhrase, - extraHeaders: extraHeaders, - body: body - }; - var response; - var statusCodeString = statusCode.toString(); - switch (true) { - case /^100$/.test(statusCodeString): - response = this.incomingRequest.trying(responseOptions).message; - break; - case /^1[0-9]{2}$/.test(statusCodeString): - response = this.incomingRequest.progress(responseOptions).message; - break; - case /^2[0-9]{2}$/.test(statusCodeString): - response = this.incomingRequest.accept(responseOptions).message; - break; - case /^3[0-9]{2}$/.test(statusCodeString): - response = this.incomingRequest.redirect([], responseOptions).message; - break; - case /^[4-6][0-9]{2}$/.test(statusCodeString): - response = this.incomingRequest.reject(responseOptions).message; - break; - default: - throw new Error("Invalid status code " + statusCode); - } - events.forEach(function (event) { - _this.emit(event, response, reasonPhrase); - }); - return this; - }; - ServerContext.prototype.onRequestTimeout = function () { - this.emit("failed", undefined, Constants_1.C.causes.REQUEST_TIMEOUT); - }; - ServerContext.prototype.onTransportError = function () { - this.emit("failed", undefined, Constants_1.C.causes.CONNECTION_ERROR); - }; - return ServerContext; -}(events_1.EventEmitter)); -exports.ServerContext = ServerContext; diff --git a/lib/Session.d.ts b/lib/Session.d.ts deleted file mode 100644 index a879c777f..000000000 --- a/lib/Session.d.ts +++ /dev/null @@ -1,376 +0,0 @@ -/// -import { EventEmitter } from "events"; -import { ClientContext } from "./ClientContext"; -import { C } from "./Constants"; -import { Body, IncomingAckRequest, IncomingInviteRequest, IncomingPrackRequest, IncomingRequest, IncomingRequestMessage, IncomingResponseMessage, InviteServerTransaction, Logger, NameAddrHeader, NonInviteServerTransaction, OutgoingRequestMessage, Session as SessionCore, URI } from "./core"; -import { SessionStatus, TypeStrings } from "./Enums"; -import { ReferClientContext, ReferServerContext } from "./ReferContext"; -import { ServerContext } from "./ServerContext"; -import { SessionDescriptionHandler, SessionDescriptionHandlerModifier, SessionDescriptionHandlerModifiers, SessionDescriptionHandlerOptions } from "./session-description-handler"; -import { SessionDescriptionHandlerFactory } from "./session-description-handler-factory"; -import { DTMF } from "./Session/DTMF"; -import { UA } from "./UA"; -export declare namespace Session { - interface DtmfOptions { - extraHeaders?: string[]; - duration?: number; - interToneGap?: number; - } -} -export declare abstract class Session extends EventEmitter { - static readonly C: typeof SessionStatus; - type: TypeStrings; - ua: UA; - logger: Logger; - method: string; - body: any; - status: SessionStatus; - contentType: string; - localIdentity: NameAddrHeader; - remoteIdentity: NameAddrHeader; - data: any; - assertedIdentity: NameAddrHeader | undefined; - id: string; - contact: string | undefined; - replacee: InviteClientContext | InviteServerContext | undefined; - localHold: boolean; - sessionDescriptionHandler: SessionDescriptionHandler | undefined; - startTime: Date | undefined; - endTime: Date | undefined; - session: SessionCore | undefined; - protected sessionDescriptionHandlerFactory: SessionDescriptionHandlerFactory; - protected sessionDescriptionHandlerOptions: any; - protected rel100: string; - protected earlySdp: string | undefined; - protected hasOffer: boolean; - protected hasAnswer: boolean; - protected timers: { - [name: string]: any; - }; - protected fromTag: string | undefined; - protected errorListener: ((...args: Array) => void); - protected renderbody: string | undefined; - protected rendertype: string | undefined; - protected modifiers: Array | undefined; - protected passedOptions: any; - protected onInfo: ((request: IncomingRequestMessage) => void) | undefined; - private tones; - private pendingReinvite; - private referContext; - protected constructor(sessionDescriptionHandlerFactory: SessionDescriptionHandlerFactory); - dtmf(tones: string | number, options?: Session.DtmfOptions): this; - bye(options?: any): this; - refer(target: string | InviteClientContext | InviteServerContext, options?: any): ReferClientContext; - /** - * Sends in dialog request. - * @param method Request method. - * @param options Options bucket. - */ - sendRequest(method: string, options?: any): this; - close(): this; - hold(options?: SessionDescriptionHandlerOptions, modifiers?: SessionDescriptionHandlerModifiers): void; - unhold(options?: SessionDescriptionHandlerOptions, modifiers?: SessionDescriptionHandlerModifiers): void; - reinvite(options?: any, modifiers?: SessionDescriptionHandlerModifiers): void; - terminate(options?: any): this; - onTransportError(): void; - onRequestTimeout(): void; - onDialogError(response: IncomingResponseMessage): void; - on(event: "dtmf", listener: (request: IncomingRequestMessage | OutgoingRequestMessage, dtmf: DTMF) => void): this; - on(event: "progress", listener: (response: IncomingResponseMessage | string, reasonPhrase?: any) => void): this; - on(event: "referRequested", listener: (context: ReferServerContext) => void): this; - on(event: "referInviteSent" | "referProgress" | "referAccepted" | "referRejected" | "referRequestProgress" | "referRequestAccepted" | "referRequestRejected" | "reinvite" | "reinviteAccepted" | "reinviteFailed" | "replaced", listener: (session: Session) => void): this; - on(event: "SessionDescriptionHandler-created", listener: (sessionDescriptionHandler: SessionDescriptionHandler) => void): this; - on(event: "accepted", listener: (response: any, cause: C.causes) => void): this; - on(event: "ack" | "bye" | "confirmed" | "connecting" | "notify", listener: (request: any) => void): this; - on(event: "dialog", listener: (dialog: any) => void): this; - on(event: "renegotiationError", listener: (error: any) => void): this; - on(event: "failed" | "rejected", listener: (response?: any, cause?: C.causes) => void): this; - on(event: "terminated", listener: (message?: any, cause?: C.causes) => void): this; - on(event: "cancel" | "trackAdded" | "directionChanged", listener: () => void): this; - protected onAck(incomingRequest: IncomingAckRequest): void; - protected receiveRequest(incomingRequest: IncomingRequest): void; - protected receiveReinvite(incomingRequest: IncomingRequest): void; - protected sendReinvite(options?: any): void; - protected failed(response: IncomingResponseMessage | IncomingRequestMessage | undefined, cause: string): this; - protected rejected(response: IncomingResponseMessage | IncomingRequestMessage, cause: string): this; - protected canceled(): this; - protected accepted(response?: IncomingResponseMessage | string, cause?: string): this; - protected terminated(message?: IncomingResponseMessage | IncomingRequestMessage, cause?: string): this; - protected connecting(request: IncomingRequestMessage): this; -} -export declare namespace InviteServerContext { - interface Options { - /** Array of extra headers added to the INVITE. */ - extraHeaders?: Array; - /** Options to pass to SessionDescriptionHandler's getDescription() and setDescription(). */ - sessionDescriptionHandlerOptions?: SessionDescriptionHandlerOptions; - modifiers?: SessionDescriptionHandlerModifiers; - onInfo?: ((request: IncomingRequestMessage) => void); - statusCode?: number; - reasonPhrase?: string; - body?: any; - rel100?: boolean; - } -} -export declare class InviteServerContext extends Session implements ServerContext { - type: TypeStrings; - transaction: InviteServerTransaction | NonInviteServerTransaction; - request: IncomingRequestMessage; - incomingRequest: IncomingInviteRequest; - /** - * FIXME: TODO: - * Used to squelch throwing of errors due to async race condition. - * We have an internal race between calling `accept()` and handling - * an incoming CANCEL request. As there is no good way currently to - * delegate the handling of this async errors to the caller of - * `accept()`, we are squelching the throwing ALL errors when - * they occur after receiving a CANCEL to catch the ONE we know - * is a "normal" exceptional condition. While this is a completely - * reasonable appraoch, the decision should be left up to the library user. - */ - private _canceled; - private rseq; - private waitingForPrackPromise; - private waitingForPrackResolve; - private waitingForPrackReject; - constructor(ua: UA, incomingInviteRequest: IncomingInviteRequest); - /** - * If true, a first provisional response after the 100 Trying - * will be sent automatically. This is false it the UAC required - * reliable provisional responses (100rel in Require header), - * otherwise it is true. The provisional is sent by calling - * `progress()` without any options. - * - * FIXME: TODO: It seems reasonable that the ISC user should - * be able to optionally disable this behavior. As the provisional - * is sent prior to the "invite" event being emitted, it's a known - * issue that the ISC user cannot register listeners or do any other - * setup prior to the call to `progress()`. As an example why this is - * an issue, setting `ua.configuration.rel100` to REQUIRED will result - * in an attempt by `progress()` to send a 183 with SDP produced by - * calling `getDescription()` on a session description handler, but - * the ISC user cannot perform any potentially required session description - * handler initialization (thus preventing the utilization of setting - * `ua.configuration.rel100` to REQUIRED). That begs the question of - * why this behavior is disabled when the UAC requires 100rel but not - * when the UAS requires 100rel? But ignoring that, it's just one example - * of a class of cases where the ISC user needs to do something prior - * to the first call to `progress()` and is unable to do so. - */ - readonly autoSendAnInitialProvisionalResponse: boolean; - reply(options?: any): this; - reject(options?: InviteServerContext.Options): this; - /** - * Accept the incoming INVITE request to start a Session. - * Replies to the INVITE request with a 200 Ok response. - * @param options Options bucket. - */ - accept(options?: InviteServerContext.Options): this; - /** - * Report progress to the the caller. - * Replies to the INVITE request with a 1xx provisional response. - * @param options Options bucket. - */ - progress(options?: InviteServerContext.Options): this; - /** - * Reject an unaccepted incoming INVITE request or send BYE if established session. - * @param options Options bucket. FIXME: This options bucket needs to be typed. - */ - terminate(options?: any): this; - onCancel(message: IncomingRequestMessage): void; - protected receiveRequest(incomingRequest: IncomingRequest): void; - protected setupSessionDescriptionHandler(): SessionDescriptionHandler; - protected generateResponseOfferAnswer(options: { - sessionDescriptionHandlerOptions?: SessionDescriptionHandlerOptions; - modifiers?: SessionDescriptionHandlerModifiers; - }): Promise; - protected handlePrackOfferAnswer(request: IncomingPrackRequest, options: { - sessionDescriptionHandlerOptions?: SessionDescriptionHandlerOptions; - modifiers?: SessionDescriptionHandlerModifiers; - }): Promise; - /** - * Called when session canceled. - */ - protected canceled(): this; - /** - * Called when session terminated. - * Using it here just for the PRACK timeout. - */ - protected terminated(message?: IncomingResponseMessage | IncomingRequestMessage, cause?: string): this; - /** - * A version of `accept` which resolves a session when the 200 Ok response is sent. - * @param options Options bucket. - * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. - * @throws {TransactionStateError} The transaction state does not allow for `accept()` to be called. - * Note that the transaction state can change while this call is in progress. - */ - private _accept; - /** - * A version of `progress` which resolves when the provisional response is sent. - * @param options Options bucket. - * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. - * @throws {TransactionStateError} The transaction state does not allow for `progress()` to be called. - * Note that the transaction state can change while this call is in progress. - */ - private _progress; - /** - * A version of `progress` which resolves when the provisional response with sdp is sent. - * @param options Options bucket. - * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. - * @throws {TransactionStateError} The transaction state does not allow for `progress()` to be called. - * Note that the transaction state can change while this call is in progress. - */ - private _progressWithSDP; - /** - * A version of `progress` which resolves when the reliable provisional response is sent. - * @param options Options bucket. - * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. - * @throws {TransactionStateError} The transaction state does not allow for `progress()` to be called. - * Note that the transaction state can change while this call is in progress. - */ - private _reliableProgress; - /** - * A version of `progress` which resolves when the reliable provisional response is acknowledged. - * @param options Options bucket. - * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. - * @throws {TransactionStateError} The transaction state does not allow for `progress()` to be called. - * Note that the transaction state can change while this call is in progress. - */ - private _reliableProgressWaitForPrack; - /** - * Callback for when ACK for a 2xx response is never received. - * @param session Session the ACK never arrived for - */ - private onAckTimeout; - /** - * FIXME: TODO: The current library interface presents async methods without a - * proper async error handling mechanism. Arguably a promise based interface - * would be an improvement over the pattern of returning `this`. The approach has - * been generally along the lines of log a error and terminate. - */ - private onContextError; - private prackArrived; - private prackNeverArrived; - /** - * @throws {Exceptions.TerminatedSessionError} The session terminated before being accepted (i.e. cancel arrived). - */ - private waitForArrivalOfPrack; - private getOffer; - private setAnswer; - private setOfferAndGetAnswer; - private getSessionDescriptionHandler; -} -export declare namespace InviteClientContext { - interface Options { - /** Anonymous call if true. */ - anonymous?: boolean; - /** Deprecated. */ - body?: string; - /** Deprecated. */ - contentType?: string; - /** Array of extra headers added to the INVITE. */ - extraHeaders?: Array; - /** If true, send INVITE without SDP. */ - inviteWithoutSdp?: boolean; - /** Deprecated. */ - onInfo?: any; - /** Deprecated. */ - params?: { - fromDisplayName?: string; - fromTag?: string; - fromUri?: string | URI; - toDisplayName?: string; - toUri?: string | URI; - }; - /** Deprecated. */ - renderbody?: string; - /** Deprecated. */ - rendertype?: string; - /** Options to pass to SessionDescriptionHandler's getDescription() and setDescription(). */ - sessionDescriptionHandlerOptions?: SessionDescriptionHandlerOptions; - } -} -export declare class InviteClientContext extends Session implements ClientContext { - type: TypeStrings; - request: OutgoingRequestMessage; - protected anonymous: boolean; - protected inviteWithoutSdp: boolean; - protected isCanceled: boolean; - protected received100: boolean; - private earlyMediaSessionDescriptionHandlers; - private outgoingInviteRequest; - constructor(ua: UA, target: string | URI, options?: InviteClientContext.Options, modifiers?: SessionDescriptionHandlerModifiers); - receiveResponse(response: IncomingResponseMessage): void; - send(): this; - invite(): this; - cancel(options?: any): this; - terminate(options?: any): this; - /** - * 13.2.1 Creating the Initial INVITE - * - * Since the initial INVITE represents a request outside of a dialog, - * its construction follows the procedures of Section 8.1.1. Additional - * processing is required for the specific case of INVITE. - * - * An Allow header field (Section 20.5) SHOULD be present in the INVITE. - * It indicates what methods can be invoked within a dialog, on the UA - * sending the INVITE, for the duration of the dialog. For example, a - * UA capable of receiving INFO requests within a dialog [34] SHOULD - * include an Allow header field listing the INFO method. - * - * A Supported header field (Section 20.37) SHOULD be present in the - * INVITE. It enumerates all the extensions understood by the UAC. - * - * An Accept (Section 20.1) header field MAY be present in the INVITE. - * It indicates which Content-Types are acceptable to the UA, in both - * the response received by it, and in any subsequent requests sent to - * it within dialogs established by the INVITE. The Accept header field - * is especially useful for indicating support of various session - * description formats. - * - * The UAC MAY add an Expires header field (Section 20.19) to limit the - * validity of the invitation. If the time indicated in the Expires - * header field is reached and no final answer for the INVITE has been - * received, the UAC core SHOULD generate a CANCEL request for the - * INVITE, as per Section 9. - * - * A UAC MAY also find it useful to add, among others, Subject (Section - * 20.36), Organization (Section 20.25) and User-Agent (Section 20.41) - * header fields. They all contain information related to the INVITE. - * - * The UAC MAY choose to add a message body to the INVITE. Section - * 8.1.1.10 deals with how to construct the header fields -- Content- - * Type among others -- needed to describe the message body. - * - * https://tools.ietf.org/html/rfc3261#section-13.2.1 - */ - private sendInvite; - private ackAndBye; - private disposeEarlyMedia; - /** - * Handle final response to initial INVITE. - * @param inviteResponse 2xx response. - */ - private onAccept; - /** - * Handle provisional response to initial INVITE. - * @param inviteResponse 1xx response. - */ - private onProgress; - /** - * Handle final response to initial INVITE. - * @param inviteResponse 3xx response. - */ - private onRedirect; - /** - * Handle final response to initial INVITE. - * @param inviteResponse 4xx, 5xx, or 6xx response. - */ - private onReject; - /** - * Handle final response to initial INVITE. - * @param inviteResponse 100 response. - */ - private onTrying; -} -//# sourceMappingURL=Session.d.ts.map \ No newline at end of file diff --git a/lib/Session.d.ts.map b/lib/Session.d.ts.map deleted file mode 100644 index a5a34c030..000000000 --- a/lib/Session.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"Session.d.ts","sourceRoot":"","sources":["../src/Session.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAEtC,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,CAAC,EAAE,MAAM,aAAa,CAAC;AAChC,OAAO,EAEL,IAAI,EAKJ,kBAAkB,EAClB,qBAAqB,EACrB,oBAAoB,EACpB,eAAe,EACf,sBAAsB,EAEtB,uBAAuB,EACvB,uBAAuB,EACvB,MAAM,EACN,cAAc,EACd,0BAA0B,EAK1B,sBAAsB,EAKtB,OAAO,IAAI,WAAW,EAItB,GAAG,EACJ,MAAM,QAAQ,CAAC;AAChB,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAErD,OAAO,EACL,kBAAkB,EAClB,kBAAkB,EACnB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAEL,yBAAyB,EACzB,iCAAiC,EACjC,kCAAkC,EAClC,gCAAgC,EACjC,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,gCAAgC,EAAE,MAAM,uCAAuC,CAAC;AACzF,OAAO,EAAE,IAAI,EAAE,MAAM,gBAAgB,CAAC;AACtC,OAAO,EAAE,EAAE,EAAE,MAAM,MAAM,CAAC;AAG1B,yBAAiB,OAAO,CAAC;IACvB,UAAiB,WAAW;QAC1B,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;QACxB,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,YAAY,CAAC,EAAE,MAAM,CAAC;KACvB;CACF;AAOD,8BAAsB,OAAQ,SAAQ,YAAY;IAChD,gBAAuB,CAAC,uBAAiB;IAGlC,IAAI,EAAE,WAAW,CAAC;IAClB,EAAE,EAAG,EAAE,CAAC;IACR,MAAM,EAAG,MAAM,CAAC;IAChB,MAAM,EAAG,MAAM,CAAC;IAChB,IAAI,EAAE,GAAG,CAAC;IACV,MAAM,EAAE,aAAa,CAAC;IACtB,WAAW,EAAG,MAAM,CAAC;IACrB,aAAa,EAAG,cAAc,CAAC;IAC/B,cAAc,EAAG,cAAc,CAAC;IAChC,IAAI,EAAE,GAAG,CAAM;IACf,gBAAgB,EAAE,cAAc,GAAG,SAAS,CAAC;IAC7C,EAAE,EAAG,MAAM,CAAC;IAEZ,OAAO,EAAE,MAAM,GAAG,SAAS,CAAC;IAC5B,QAAQ,EAAE,mBAAmB,GAAG,mBAAmB,GAAG,SAAS,CAAC;IAChE,SAAS,EAAE,OAAO,CAAC;IACnB,yBAAyB,EAAE,yBAAyB,GAAG,SAAS,CAAC;IACjE,SAAS,EAAE,IAAI,GAAG,SAAS,CAAC;IAC5B,OAAO,EAAE,IAAI,GAAG,SAAS,CAAC;IAE1B,OAAO,EAAE,WAAW,GAAG,SAAS,CAAC;IAExC,SAAS,CAAC,gCAAgC,EAAE,gCAAgC,CAAC;IAC7E,SAAS,CAAC,gCAAgC,EAAE,GAAG,CAAC;IAChD,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC;IAEzB,SAAS,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IACvC,SAAS,CAAC,QAAQ,EAAE,OAAO,CAAC;IAC5B,SAAS,CAAC,SAAS,EAAE,OAAO,CAAC;IAE7B,SAAS,CAAC,MAAM,EAAE;QAAC,CAAC,IAAI,EAAE,MAAM,GAAG,GAAG,CAAA;KAAC,CAAC;IACxC,SAAS,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,CAAC;IAEtC,SAAS,CAAC,aAAa,EAAG,CAAC,CAAC,GAAG,IAAI,EAAE,KAAK,CAAC,GAAG,CAAC,KAAK,IAAI,CAAC,CAAC;IAE1D,SAAS,CAAC,UAAU,EAAE,MAAM,GAAG,SAAS,CAAC;IACzC,SAAS,CAAC,UAAU,EAAE,MAAM,GAAG,SAAS,CAAC;IACzC,SAAS,CAAC,SAAS,EAAE,KAAK,CAAC,iCAAiC,CAAC,GAAG,SAAS,CAAC;IAC1E,SAAS,CAAC,aAAa,EAAE,GAAG,CAAC;IAC7B,SAAS,CAAC,MAAM,EAAE,CAAC,CAAC,OAAO,EAAE,sBAAsB,KAAK,IAAI,CAAC,GAAG,SAAS,CAAC;IAE1E,OAAO,CAAC,KAAK,CAAM;IAEnB,OAAO,CAAC,eAAe,CAAU;IACjC,OAAO,CAAC,YAAY,CAAsD;IAE1E,SAAS,aAAa,gCAAgC,EAAE,gCAAgC;IAsCjF,IAAI,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,OAAO,GAAE,OAAO,CAAC,WAAgB,GAAG,IAAI;IA0DrE,GAAG,CAAC,OAAO,GAAE,GAAQ,GAAG,IAAI;IAkB5B,KAAK,CAAC,MAAM,EAAE,MAAM,GAAG,mBAAmB,GAAG,mBAAmB,EAAE,OAAO,GAAE,GAAQ,GAAG,kBAAkB;IAoB/G;;;;OAIG;IACI,WAAW,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,GAAQ,GAAG,IAAI;IA8CpD,KAAK,IAAI,IAAI;IA+Bb,IAAI,CACT,OAAO,GAAE,gCAAqC,EAC9C,SAAS,GAAE,kCAAuC,GACjD,IAAI;IAoBA,MAAM,CACX,OAAO,GAAE,gCAAqC,EAC9C,SAAS,GAAE,kCAAuC,GACjD,IAAI;IAkBA,QAAQ,CAAC,OAAO,GAAE,GAAQ,EAAE,SAAS,GAAE,kCAAuC,GAAG,IAAI;IAMrF,SAAS,CAAC,OAAO,CAAC,EAAE,GAAG,GAAG,IAAI;IAK9B,gBAAgB,IAAI,IAAI;IAMxB,gBAAgB,IAAI,IAAI;IASxB,aAAa,CAAC,QAAQ,EAAE,uBAAuB,GAAG,IAAI;IAStD,EAAE,CACP,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,OAAO,EAAE,sBAAsB,GAAG,sBAAsB,EAAE,IAAI,EAAE,IAAI,KAAK,IAAI,GACtG,IAAI;IACA,EAAE,CACP,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,CAAC,QAAQ,EAAE,uBAAuB,GAAG,MAAM,EAAE,YAAY,CAAC,EAAE,GAAG,KAAK,IAAI,GACpG,IAAI;IACA,EAAE,CAAC,KAAK,EAAE,gBAAgB,EAAE,QAAQ,EAAE,CAAC,OAAO,EAAE,kBAAkB,KAAK,IAAI,GAAG,IAAI;IAClF,EAAE,CACP,KAAK,EACH,iBAAiB,GACjB,eAAe,GACf,eAAe,GACf,eAAe,GACf,sBAAsB,GACtB,sBAAsB,GACtB,sBAAsB,GACtB,UAAU,GACV,kBAAkB,GAClB,gBAAgB,GAChB,UAAU,EACZ,QAAQ,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,IAAI,GACnC,IAAI;IACA,EAAE,CACP,KAAK,EAAE,mCAAmC,EAC1C,QAAQ,EAAE,CAAC,yBAAyB,EAAE,yBAAyB,KAAK,IAAI,GACvE,IAAI;IACA,EAAE,CAAC,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,CAAC,QAAQ,EAAE,GAAG,EAAE,KAAK,EAAE,CAAC,CAAC,MAAM,KAAK,IAAI,GAAG,IAAI;IAC/E,EAAE,CACP,KAAK,EACH,KAAK,GACL,KAAK,GACL,WAAW,GACX,YAAY,GACZ,QAAQ,EACV,QAAQ,EAAE,CAAC,OAAO,EAAE,GAAG,KAAK,IAAI,GAC/B,IAAI;IACA,EAAE,CAAC,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE,CAAC,MAAM,EAAE,GAAG,KAAK,IAAI,GAAG,IAAI;IAC1D,EAAE,CAAC,KAAK,EAAE,oBAAoB,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE,GAAG,KAAK,IAAI,GAAG,IAAI;IACrE,EAAE,CAAC,KAAK,EAAE,QAAQ,GAAG,UAAU,EAAE,QAAQ,EAAE,CAAC,QAAQ,CAAC,EAAE,GAAG,EAAE,KAAK,CAAC,EAAE,CAAC,CAAC,MAAM,KAAK,IAAI,GAAG,IAAI;IAC5F,EAAE,CAAC,KAAK,EAAE,YAAY,EAAE,QAAQ,EAAE,CAAC,OAAO,CAAC,EAAE,GAAG,EAAE,KAAK,CAAC,EAAE,CAAC,CAAC,MAAM,KAAK,IAAI,GAAG,IAAI;IAClF,EAAE,CAAC,KAAK,EAAE,QAAQ,GAAG,YAAY,GAAG,kBAAkB,EAAE,QAAQ,EAAE,MAAM,IAAI,GAAG,IAAI;IAK1F,SAAS,CAAC,KAAK,CAAC,eAAe,EAAE,kBAAkB,GAAG,IAAI;IAuC1D,SAAS,CAAC,cAAc,CAAC,eAAe,EAAE,eAAe,GAAG,IAAI;IAsFhE,SAAS,CAAC,eAAe,CAAC,eAAe,EAAE,eAAe,GAAG,IAAI;IAoEjE,SAAS,CAAC,YAAY,CAAC,OAAO,GAAE,GAAQ,GAAG,IAAI;IAuI/C,SAAS,CAAC,MAAM,CAAC,QAAQ,EAAE,uBAAuB,GAAG,sBAAsB,GAAG,SAAS,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI;IAQ7G,SAAS,CAAC,QAAQ,CAAC,QAAQ,EAAE,uBAAuB,GAAG,sBAAsB,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI;IAKnG,SAAS,CAAC,QAAQ,IAAI,IAAI;IAQ1B,SAAS,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,uBAAuB,GAAG,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI;IAerF,SAAS,CAAC,UAAU,CAAC,OAAO,CAAC,EAAE,uBAAuB,GAAG,sBAAsB,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI;IAYtG,SAAS,CAAC,UAAU,CAAC,OAAO,EAAE,sBAAsB,GAAG,IAAI;CAI5D;AAED,yBAAiB,mBAAmB,CAAC;IACnC,UAAiB,OAAO;QACpB,kDAAkD;QAClD,YAAY,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;QAC7B,4FAA4F;QAC5F,gCAAgC,CAAC,EAAE,gCAAgC,CAAC;QACpE,SAAS,CAAC,EAAE,kCAAkC,CAAC;QAC/C,MAAM,CAAC,EAAE,CAAC,CAAC,OAAO,EAAE,sBAAsB,KAAK,IAAI,CAAC,CAAC;QACrD,UAAU,CAAC,EAAE,MAAM,CAAC;QACpB,YAAY,CAAC,EAAE,MAAM,CAAC;QACtB,IAAI,CAAC,EAAE,GAAG,CAAC;QACX,MAAM,CAAC,EAAE,OAAO,CAAC;KACpB;CACF;AAMD,qBAAa,mBAAoB,SAAQ,OAAQ,YAAW,aAAa;IAChE,IAAI,EAAE,WAAW,CAAC;IAClB,WAAW,EAAG,uBAAuB,GAAG,0BAA0B,CAAC;IACnE,OAAO,EAAG,sBAAsB,CAAC;IACjC,eAAe,EAAG,qBAAqB,CAAC;IAE/C;;;;;;;;;;OAUG;IACH,OAAO,CAAC,SAAS,CAAU;IAE3B,OAAO,CAAC,IAAI,CAAS;IAErB,OAAO,CAAC,sBAAsB,CAA4B;IAC1D,OAAO,CAAC,sBAAsB,CAA8B;IAC5D,OAAO,CAAC,qBAAqB,CAA6B;gBAE9C,EAAE,EAAE,EAAE,EAAE,qBAAqB,EAAE,qBAAqB;IA+EhE;;;;;;;;;;;;;;;;;;;;;;OAsBG;aACC,oCAAoC,EAAI,OAAO;IAK5C,KAAK,CAAC,OAAO,GAAE,GAAQ,GAAG,IAAI;IAM9B,MAAM,CAAC,OAAO,GAAE,mBAAmB,CAAC,OAAY,GAAG,IAAI;IA+B9D;;;;OAIG;IACI,MAAM,CAAC,OAAO,GAAE,mBAAmB,CAAC,OAAY,GAAG,IAAI;IA4B9D;;;;OAIG;IACI,QAAQ,CAAC,OAAO,GAAE,mBAAmB,CAAC,OAAY,GAAG,IAAI;IAiFhE;;;OAGG;IACI,SAAS,CAAC,OAAO,GAAE,GAAQ,GAAG,IAAI;IA8ClC,QAAQ,CAAC,OAAO,EAAE,sBAAsB,GAAG,IAAI;IAetD,SAAS,CAAC,cAAc,CAAC,eAAe,EAAE,eAAe,GAAG,IAAI;IAgEhE,SAAS,CAAC,8BAA8B,IAAI,yBAAyB;IAOrE,SAAS,CAAC,2BAA2B,CACnC,OAAO,EAAE;QACP,gCAAgC,CAAC,EAAE,gCAAgC,CAAC;QACpE,SAAS,CAAC,EAAE,kCAAkC,CAAA;KAC/C,GACA,OAAO,CAAC,IAAI,GAAG,SAAS,CAAC;IAoC5B,SAAS,CAAC,sBAAsB,CAC9B,OAAO,EAAE,oBAAoB,EAC7B,OAAO,EAAE;QACP,gCAAgC,CAAC,EAAE,gCAAgC,CAAC;QACpE,SAAS,CAAC,EAAE,kCAAkC,CAAA;KAC/C,GACA,OAAO,CAAC,IAAI,GAAG,SAAS,CAAC;IAuC5B;;OAEG;IACH,SAAS,CAAC,QAAQ,IAAI,IAAI;IAK1B;;;OAGG;IACH,SAAS,CAAC,UAAU,CAAC,OAAO,CAAC,EAAE,uBAAuB,GAAG,sBAAsB,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI;IAKtG;;;;;;OAMG;IACH,OAAO,CAAC,OAAO;IA6Cf;;;;;;OAMG;IACH,OAAO,CAAC,SAAS;IA6BjB;;;;;;OAMG;IACH,OAAO,CAAC,gBAAgB;IAexB;;;;;;OAMG;IACH,OAAO,CAAC,iBAAiB;IAiBzB;;;;;;OAMG;IACH,OAAO,CAAC,6BAA6B;IAyFrC;;;OAGG;IACH,OAAO,CAAC,YAAY;IAWpB;;;;;OAKG;IACH,OAAO,CAAC,cAAc;IAiCtB,OAAO,CAAC,YAAY;IASpB,OAAO,CAAC,iBAAiB;IASzB;;OAEG;IACH,OAAO,CAAC,qBAAqB;IAW7B,OAAO,CAAC,QAAQ;IAWhB,OAAO,CAAC,SAAS;IAajB,OAAO,CAAC,oBAAoB;IAgB5B,OAAO,CAAC,4BAA4B;CAQrC;AAED,yBAAiB,mBAAmB,CAAC;IACnC,UAAiB,OAAO;QACtB,8BAA8B;QAC9B,SAAS,CAAC,EAAE,OAAO,CAAC;QACpB,kBAAkB;QAClB,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,kBAAkB;QAClB,WAAW,CAAC,EAAE,MAAM,CAAC;QACrB,kDAAkD;QAClD,YAAY,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;QAC7B,wCAAwC;QACxC,gBAAgB,CAAC,EAAE,OAAO,CAAC;QAC3B,kBAAkB;QAClB,MAAM,CAAC,EAAE,GAAG,CAAC;QACb,kBAAkB;QAClB,MAAM,CAAC,EAAE;YACP,eAAe,CAAC,EAAE,MAAM,CAAC;YACzB,OAAO,CAAC,EAAE,MAAM,CAAC;YACjB,OAAO,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC;YACvB,aAAa,CAAC,EAAE,MAAM,CAAC;YACvB,KAAK,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC;SACtB,CAAC;QACF,kBAAkB;QAClB,UAAU,CAAC,EAAE,MAAM,CAAC;QACpB,kBAAkB;QAClB,UAAU,CAAC,EAAE,MAAM,CAAC;QACpB,4FAA4F;QAC5F,gCAAgC,CAAC,EAAE,gCAAgC,CAAC;KACrE;CACF;AAGD,qBAAa,mBAAoB,SAAQ,OAAQ,YAAW,aAAa;IAChE,IAAI,EAAE,WAAW,CAAC;IAClB,OAAO,EAAG,sBAAsB,CAAC;IAExC,SAAS,CAAC,SAAS,EAAE,OAAO,CAAC;IAC7B,SAAS,CAAC,gBAAgB,EAAE,OAAO,CAAC;IACpC,SAAS,CAAC,UAAU,EAAE,OAAO,CAAC;IAC9B,SAAS,CAAC,WAAW,EAAE,OAAO,CAAC;IAE/B,OAAO,CAAC,oCAAoC,CAAyC;IACrF,OAAO,CAAC,qBAAqB,CAAoC;gBAG/D,EAAE,EAAE,EAAE,EACN,MAAM,EAAE,MAAM,GAAG,GAAG,EACpB,OAAO,GAAE,mBAAmB,CAAC,OAAY,EACzC,SAAS,GAAE,kCAAuC;IAuG7C,eAAe,CAAC,QAAQ,EAAE,uBAAuB,GAAG,IAAI;IAKxD,IAAI,IAAI,IAAI;IAKZ,MAAM,IAAI,IAAI;IAyDd,MAAM,CAAC,OAAO,GAAE,GAAQ,GAAG,IAAI;IAwB/B,SAAS,CAAC,OAAO,CAAC,EAAE,GAAG,GAAG,IAAI;IAcrC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAsCG;IACH,OAAO,CAAC,UAAU;IA+OlB,OAAO,CAAC,SAAS;IAoBjB,OAAO,CAAC,iBAAiB;IASzB;;;OAGG;IACH,OAAO,CAAC,QAAQ;IA2JhB;;;OAGG;IACH,OAAO,CAAC,UAAU;IA6JlB;;;OAGG;IACH,OAAO,CAAC,UAAU;IAUlB;;;OAGG;IACH,OAAO,CAAC,QAAQ;IAUhB;;;OAGG;IACH,OAAO,CAAC,QAAQ;CAIjB"} \ No newline at end of file diff --git a/lib/Session.js b/lib/Session.js deleted file mode 100644 index fbb8cb460..000000000 --- a/lib/Session.js +++ /dev/null @@ -1,2207 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var events_1 = require("events"); -var ClientContext_1 = require("./ClientContext"); -var Constants_1 = require("./Constants"); -var core_1 = require("./core"); -var Enums_1 = require("./Enums"); -var Exceptions_1 = require("./Exceptions"); -var ReferContext_1 = require("./ReferContext"); -var ServerContext_1 = require("./ServerContext"); -var DTMF_1 = require("./Session/DTMF"); -var Utils_1 = require("./Utils"); -/* - * @param {function returning SIP.sessionDescriptionHandler} [sessionDescriptionHandlerFactory] - * (See the documentation for the sessionDescriptionHandlerFactory argument of the UA constructor.) - */ -var Session = /** @class */ (function (_super) { - tslib_1.__extends(Session, _super); - function Session(sessionDescriptionHandlerFactory) { - var _this = _super.call(this) || this; - _this.data = {}; - _this.type = Enums_1.TypeStrings.Session; - if (!sessionDescriptionHandlerFactory) { - throw new Exceptions_1.Exceptions.SessionDescriptionHandlerError("A session description handler is required for the session to function"); - } - _this.status = Session.C.STATUS_NULL; - _this.pendingReinvite = false; - _this.sessionDescriptionHandlerFactory = sessionDescriptionHandlerFactory; - _this.hasOffer = false; - _this.hasAnswer = false; - // Session Timers - _this.timers = { - ackTimer: undefined, - expiresTimer: undefined, - invite2xxTimer: undefined, - userNoAnswerTimer: undefined, - rel1xxTimer: undefined, - prackTimer: undefined - }; - // Session info - _this.startTime = undefined; - _this.endTime = undefined; - _this.tones = undefined; - // Hold state - _this.localHold = false; - _this.earlySdp = undefined; - _this.rel100 = Constants_1.C.supported.UNSUPPORTED; - return _this; - } - Session.prototype.dtmf = function (tones, options) { - var _this = this; - if (options === void 0) { options = {}; } - // Check Session Status - if (this.status !== Enums_1.SessionStatus.STATUS_CONFIRMED && this.status !== Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK) { - throw new Exceptions_1.Exceptions.InvalidStateError(this.status); - } - // Check tones - if (!tones || !tones.toString().match(/^[0-9A-D#*,]+$/i)) { - throw new TypeError("Invalid tones: " + tones); - } - var sendDTMF = function () { - if (_this.status === Enums_1.SessionStatus.STATUS_TERMINATED || !_this.tones || _this.tones.length === 0) { - // Stop sending DTMF - _this.tones = undefined; - return; - } - var dtmf = _this.tones.shift(); - var timeout; - if (dtmf.tone === ",") { - timeout = 2000; - } - else { - dtmf.on("failed", function () { _this.tones = undefined; }); - dtmf.send(options); - timeout = dtmf.duration + dtmf.interToneGap; - } - // Set timeout for the next tone - setTimeout(sendDTMF, timeout); - }; - tones = tones.toString(); - var dtmfType = this.ua.configuration.dtmfType; - if (this.sessionDescriptionHandler && dtmfType === Constants_1.C.dtmfType.RTP) { - var sent = this.sessionDescriptionHandler.sendDtmf(tones, options); - if (!sent) { - this.logger.warn("Attempt to use dtmfType 'RTP' has failed, falling back to INFO packet method"); - dtmfType = Constants_1.C.dtmfType.INFO; - } - } - if (dtmfType === Constants_1.C.dtmfType.INFO) { - var dtmfs = []; - var tonesArray = tones.split(""); - while (tonesArray.length > 0) { - dtmfs.push(new DTMF_1.DTMF(this, tonesArray.shift(), options)); - } - if (this.tones) { - // Tones are already queued, just add to the queue - this.tones = this.tones.concat(dtmfs); - return this; - } - this.tones = dtmfs; - sendDTMF(); - } - return this; - }; - Session.prototype.bye = function (options) { - if (options === void 0) { options = {}; } - // Check Session Status - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - this.logger.error("Error: Attempted to send BYE in a terminated session."); - return this; - } - this.logger.log("terminating Session"); - var statusCode = options.statusCode; - if (statusCode && (statusCode < 200 || statusCode >= 700)) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - options.receiveResponse = function () { }; - return this.sendRequest(Constants_1.C.BYE, options).terminated(); - }; - Session.prototype.refer = function (target, options) { - if (options === void 0) { options = {}; } - // Check Session Status - if (this.status !== Enums_1.SessionStatus.STATUS_CONFIRMED) { - throw new Exceptions_1.Exceptions.InvalidStateError(this.status); - } - this.referContext = new ReferContext_1.ReferClientContext(this.ua, this, target, options); - this.emit("referRequested", this.referContext); - this.referContext.refer(options); - return this.referContext; - }; - /** - * Sends in dialog request. - * @param method Request method. - * @param options Options bucket. - */ - Session.prototype.sendRequest = function (method, options) { - if (options === void 0) { options = {}; } - if (!this.session) { - throw new Error("Session undefined."); - } - // Convert any "body" option to a Body. - if (options.body) { - options.body = Utils_1.Utils.fromBodyObj(options.body); - } - // Convert any "receiveResponse" callback option passed to an OutgoingRequestDelegate. - var delegate; - var callback = options.receiveResponse; - if (callback) { - delegate = { - onAccept: function (response) { return callback(response.message); }, - onProgress: function (response) { return callback(response.message); }, - onRedirect: function (response) { return callback(response.message); }, - onReject: function (response) { return callback(response.message); }, - onTrying: function (response) { return callback(response.message); } - }; - } - var request; - var requestOptions = options; - switch (method) { - case Constants_1.C.BYE: - request = this.session.bye(delegate, requestOptions); - break; - case Constants_1.C.INVITE: - request = this.session.invite(delegate, requestOptions); - break; - case Constants_1.C.REFER: - request = this.session.refer(delegate, requestOptions); - break; - default: - throw new Error("Unexpected " + method + ". Method not implemented by user agent core."); - } - // Ported - Emit the request event - this.emit(method.toLowerCase(), request.message); - return this; - }; - Session.prototype.close = function () { - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return this; - } - this.logger.log("closing INVITE session " + this.id); - // 1st Step. Terminate media. - if (this.sessionDescriptionHandler) { - this.sessionDescriptionHandler.close(); - } - // 2nd Step. Terminate signaling. - // Clear session timers - for (var timer in this.timers) { - if (this.timers[timer]) { - clearTimeout(this.timers[timer]); - } - } - this.status = Enums_1.SessionStatus.STATUS_TERMINATED; - if (this.ua.transport) { - this.ua.transport.removeListener("transportError", this.errorListener); - } - delete this.ua.sessions[this.id]; - return this; - }; - Session.prototype.hold = function (options, modifiers) { - if (options === void 0) { options = {}; } - if (modifiers === void 0) { modifiers = []; } - if (this.status !== Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK && this.status !== Enums_1.SessionStatus.STATUS_CONFIRMED) { - throw new Exceptions_1.Exceptions.InvalidStateError(this.status); - } - if (this.localHold) { - this.logger.log("Session is already on hold, cannot put it on hold again"); - return; - } - options.modifiers = modifiers; - if (this.sessionDescriptionHandler) { - options.modifiers.push(this.sessionDescriptionHandler.holdModifier); - } - this.localHold = true; - this.sendReinvite(options); - }; - Session.prototype.unhold = function (options, modifiers) { - if (options === void 0) { options = {}; } - if (modifiers === void 0) { modifiers = []; } - if (this.status !== Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK && this.status !== Enums_1.SessionStatus.STATUS_CONFIRMED) { - throw new Exceptions_1.Exceptions.InvalidStateError(this.status); - } - if (!this.localHold) { - this.logger.log("Session is not on hold, cannot unhold it"); - return; - } - options.modifiers = modifiers; - this.localHold = false; - this.sendReinvite(options); - }; - Session.prototype.reinvite = function (options, modifiers) { - if (options === void 0) { options = {}; } - if (modifiers === void 0) { modifiers = []; } - options.modifiers = modifiers; - return this.sendReinvite(options); - }; - Session.prototype.terminate = function (options) { - // here for types and to be overridden - return this; - }; - Session.prototype.onTransportError = function () { - if (this.status !== Enums_1.SessionStatus.STATUS_CONFIRMED && this.status !== Enums_1.SessionStatus.STATUS_TERMINATED) { - this.failed(undefined, Constants_1.C.causes.CONNECTION_ERROR); - } - }; - Session.prototype.onRequestTimeout = function () { - if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { - this.terminated(undefined, Constants_1.C.causes.REQUEST_TIMEOUT); - } - else if (this.status !== Enums_1.SessionStatus.STATUS_TERMINATED) { - this.failed(undefined, Constants_1.C.causes.REQUEST_TIMEOUT); - this.terminated(undefined, Constants_1.C.causes.REQUEST_TIMEOUT); - } - }; - Session.prototype.onDialogError = function (response) { - if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { - this.terminated(response, Constants_1.C.causes.DIALOG_ERROR); - } - else if (this.status !== Enums_1.SessionStatus.STATUS_TERMINATED) { - this.failed(response, Constants_1.C.causes.DIALOG_ERROR); - this.terminated(response, Constants_1.C.causes.DIALOG_ERROR); - } - }; - Session.prototype.on = function (name, callback) { - return _super.prototype.on.call(this, name, callback); - }; - Session.prototype.onAck = function (incomingRequest) { - var _this = this; - var confirmSession = function () { - clearTimeout(_this.timers.ackTimer); - clearTimeout(_this.timers.invite2xxTimer); - _this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; - var contentDisp = incomingRequest.message.getHeader("Content-Disposition"); - if (contentDisp && contentDisp.type === "render") { - _this.renderbody = incomingRequest.message.body; - _this.rendertype = incomingRequest.message.getHeader("Content-Type"); - } - _this.emit("confirmed", incomingRequest.message); - }; - if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK) { - if (this.sessionDescriptionHandler && - this.sessionDescriptionHandler.hasDescription(incomingRequest.message.getHeader("Content-Type") || "")) { - this.hasAnswer = true; - this.sessionDescriptionHandler.setDescription(incomingRequest.message.body, this.sessionDescriptionHandlerOptions, this.modifiers).catch(function (e) { - _this.logger.warn(e); - _this.terminate({ - statusCode: "488", - reasonPhrase: "Bad Media Description" - }); - _this.failed(incomingRequest.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - _this.terminated(incomingRequest.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - throw e; - }).then(function () { return confirmSession(); }); - } - else { - confirmSession(); - } - } - }; - Session.prototype.receiveRequest = function (incomingRequest) { - switch (incomingRequest.message.method) { // TODO: This needs a default case - case Constants_1.C.BYE: - incomingRequest.accept(); - if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { - this.emit("bye", incomingRequest.message); - this.terminated(incomingRequest.message, Constants_1.C.BYE); - } - break; - case Constants_1.C.INVITE: - if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { - this.logger.log("re-INVITE received"); - this.receiveReinvite(incomingRequest); - } - break; - case Constants_1.C.INFO: - if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED || this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK) { - if (this.onInfo) { - return this.onInfo(incomingRequest.message); - } - var contentType = incomingRequest.message.getHeader("content-type"); - if (contentType) { - if (contentType.match(/^application\/dtmf-relay/i)) { - if (incomingRequest.message.body) { - var body = incomingRequest.message.body.split("\r\n", 2); - if (body.length === 2) { - var tone = void 0; - var duration = void 0; - var regTone = /^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/; - if (regTone.test(body[0])) { - tone = body[0].replace(regTone, "$2"); - } - var regDuration = /^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/; - if (regDuration.test(body[1])) { - duration = parseInt(body[1].replace(regDuration, "$2"), 10); - } - if (tone && duration) { - new DTMF_1.DTMF(this, tone, { duration: duration }).init_incoming(incomingRequest); - } - } - } - } - else { - incomingRequest.reject({ - statusCode: 415, - extraHeaders: ["Accept: application/dtmf-relay"] - }); - } - } - } - break; - case Constants_1.C.REFER: - if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { - this.logger.log("REFER received"); - this.referContext = new ReferContext_1.ReferServerContext(this.ua, incomingRequest, this.session); - if (this.listeners("referRequested").length) { - this.emit("referRequested", this.referContext); - } - else { - this.logger.log("No referRequested listeners, automatically accepting and following the refer"); - var options = { followRefer: true }; - if (this.passedOptions) { - options.inviteOptions = this.passedOptions; - } - this.referContext.accept(options, this.modifiers); - } - } - break; - case Constants_1.C.NOTIFY: - if (this.referContext && - this.referContext.type === Enums_1.TypeStrings.ReferClientContext && - incomingRequest.message.hasHeader("event") && - /^refer(;.*)?$/.test(incomingRequest.message.getHeader("event"))) { - this.referContext.receiveNotify(incomingRequest); - return; - } - incomingRequest.accept(); - this.emit("notify", incomingRequest.message); - break; - } - }; - // In dialog INVITE Reception - Session.prototype.receiveReinvite = function (incomingRequest) { - // TODO: Should probably check state of the session - var _this = this; - this.emit("reinvite", this, incomingRequest.message); - if (incomingRequest.message.hasHeader("P-Asserted-Identity")) { - this.assertedIdentity = - core_1.Grammar.nameAddrHeaderParse(incomingRequest.message.getHeader("P-Asserted-Identity")); - } - var promise; - if (!this.sessionDescriptionHandler) { - this.logger.warn("No SessionDescriptionHandler to reinvite"); - return; - } - if (incomingRequest.message.getHeader("Content-Length") === "0" && - !incomingRequest.message.getHeader("Content-Type")) { // Invite w/o SDP - promise = this.sessionDescriptionHandler.getDescription(this.sessionDescriptionHandlerOptions, this.modifiers); - } - else if (this.sessionDescriptionHandler.hasDescription(incomingRequest.message.getHeader("Content-Type") || "")) { - // Invite w/ SDP - promise = this.sessionDescriptionHandler.setDescription(incomingRequest.message.body, this.sessionDescriptionHandlerOptions, this.modifiers).then(this.sessionDescriptionHandler.getDescription.bind(this.sessionDescriptionHandler, this.sessionDescriptionHandlerOptions, this.modifiers)); - } - else { // Bad Packet (should never get hit) - incomingRequest.reject({ statusCode: 415 }); - this.emit("reinviteFailed", this); - return; - } - promise.catch(function (e) { - var statusCode; - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - statusCode = 500; - } - else if (e.type === Enums_1.TypeStrings.RenegotiationError) { - _this.emit("renegotiationError", e); - _this.logger.warn(e.toString()); - statusCode = 488; - } - else { - _this.logger.error(e); - statusCode = 488; - } - incomingRequest.reject({ statusCode: statusCode }); - _this.emit("reinviteFailed", _this); - // TODO: This could be better - throw e; - }).then(function (description) { - var extraHeaders = ["Contact: " + _this.contact]; - incomingRequest.accept({ - statusCode: 200, - extraHeaders: extraHeaders, - body: Utils_1.Utils.fromBodyObj(description) - }); - _this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK; - _this.emit("reinviteAccepted", _this); - }); - }; - Session.prototype.sendReinvite = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - if (this.pendingReinvite) { - this.logger.warn("Reinvite in progress. Please wait until complete, then try again."); - return; - } - if (!this.sessionDescriptionHandler) { - this.logger.warn("No SessionDescriptionHandler, can't reinvite.."); - return; - } - this.pendingReinvite = true; - options.modifiers = options.modifiers || []; - var extraHeaders = (options.extraHeaders || []).slice(); - extraHeaders.push("Contact: " + this.contact); - // this is UA.C.ALLOWED_METHODS, removed to get around circular dependency - extraHeaders.push("Allow: " + [ - "ACK", - "CANCEL", - "INVITE", - "MESSAGE", - "BYE", - "OPTIONS", - "INFO", - "NOTIFY", - "REFER" - ].toString()); - this.sessionDescriptionHandler.getDescription(options.sessionDescriptionHandlerOptions, options.modifiers) - .then(function (description) { - if (!_this.session) { - throw new Error("Session undefined."); - } - var delegate = { - onAccept: function (response) { - if (_this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - _this.logger.error("Received reinvite response, but in STATUS_TERMINATED"); - // TODO: Do we need to send a SIP response? - return; - } - if (!_this.pendingReinvite) { - _this.logger.error("Received reinvite response, but have no pending reinvite"); - // TODO: Do we need to send a SIP response? - return; - } - // FIXME: Why is this set here? - _this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; - // 17.1.1.1 - For each final response that is received at the client transaction, - // the client transaction sends an ACK, - _this.emit("ack", response.ack()); - _this.pendingReinvite = false; - // TODO: All of these timers should move into the Transaction layer - clearTimeout(_this.timers.invite2xxTimer); - if (!_this.sessionDescriptionHandler || - !_this.sessionDescriptionHandler.hasDescription(response.message.getHeader("Content-Type") || "")) { - _this.logger.error("2XX response received to re-invite but did not have a description"); - _this.emit("reinviteFailed", _this); - _this.emit("renegotiationError", new Exceptions_1.Exceptions.RenegotiationError("2XX response received to re-invite but did not have a description")); - return; - } - _this.sessionDescriptionHandler - .setDescription(response.message.body, _this.sessionDescriptionHandlerOptions, _this.modifiers) - .catch(function (e) { - _this.logger.error("Could not set the description in 2XX response"); - _this.logger.error(e); - _this.emit("reinviteFailed", _this); - _this.emit("renegotiationError", e); - _this.sendRequest(Constants_1.C.BYE, { - extraHeaders: ["Reason: " + Utils_1.Utils.getReasonHeaderValue(488, "Not Acceptable Here")] - }); - _this.terminated(undefined, Constants_1.C.causes.INCOMPATIBLE_SDP); - throw e; - }) - .then(function () { - _this.emit("reinviteAccepted", _this); - }); - }, - onProgress: function (response) { - return; - }, - onRedirect: function (response) { - // FIXME: Does ACK need to be sent? - _this.pendingReinvite = false; - _this.logger.log("Received a non 1XX or 2XX response to a re-invite"); - _this.emit("reinviteFailed", _this); - _this.emit("renegotiationError", new Exceptions_1.Exceptions.RenegotiationError("Invalid response to a re-invite")); - }, - onReject: function (response) { - // FIXME: Does ACK need to be sent? - _this.pendingReinvite = false; - _this.logger.log("Received a non 1XX or 2XX response to a re-invite"); - _this.emit("reinviteFailed", _this); - _this.emit("renegotiationError", new Exceptions_1.Exceptions.RenegotiationError("Invalid response to a re-invite")); - }, - onTrying: function (response) { - return; - } - }; - var requestOptions = { - extraHeaders: extraHeaders, - body: Utils_1.Utils.fromBodyObj(description) - }; - _this.session.invite(delegate, requestOptions); - }).catch(function (e) { - if (e.type === Enums_1.TypeStrings.RenegotiationError) { - _this.pendingReinvite = false; - _this.emit("renegotiationError", e); - _this.logger.warn("Renegotiation Error"); - _this.logger.warn(e.toString()); - throw e; - } - _this.logger.error("sessionDescriptionHandler error"); - _this.logger.error(e); - throw e; - }); - }; - Session.prototype.failed = function (response, cause) { - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return this; - } - this.emit("failed", response, cause); - return this; - }; - Session.prototype.rejected = function (response, cause) { - this.emit("rejected", response, cause); - return this; - }; - Session.prototype.canceled = function () { - if (this.sessionDescriptionHandler) { - this.sessionDescriptionHandler.close(); - } - this.emit("cancel"); - return this; - }; - Session.prototype.accepted = function (response, cause) { - if (!(response instanceof String)) { - cause = Utils_1.Utils.getReasonPhrase((response && response.statusCode) || 0, cause); - } - this.startTime = new Date(); - if (this.replacee) { - this.replacee.emit("replaced", this); - this.replacee.terminate(); - } - this.emit("accepted", response, cause); - return this; - }; - Session.prototype.terminated = function (message, cause) { - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return this; - } - this.endTime = new Date(); - this.close(); - this.emit("terminated", message, cause); - return this; - }; - Session.prototype.connecting = function (request) { - this.emit("connecting", { request: request }); - return this; - }; - Session.C = Enums_1.SessionStatus; - return Session; -}(events_1.EventEmitter)); -exports.Session = Session; -// tslint:disable-next-line:max-classes-per-file -var InviteServerContext = /** @class */ (function (_super) { - tslib_1.__extends(InviteServerContext, _super); - function InviteServerContext(ua, incomingInviteRequest) { - var _this = this; - if (!ua.configuration.sessionDescriptionHandlerFactory) { - ua.logger.warn("Can't build ISC without SDH Factory"); - throw new Error("ISC Constructor Failed"); - } - _this = _super.call(this, ua.configuration.sessionDescriptionHandlerFactory) || this; - _this._canceled = false; - _this.rseq = Math.floor(Math.random() * 10000); - _this.incomingRequest = incomingInviteRequest; - var request = incomingInviteRequest.message; - ServerContext_1.ServerContext.initializer(_this, ua, incomingInviteRequest); - _this.type = Enums_1.TypeStrings.InviteServerContext; - var contentDisp = request.parseHeader("Content-Disposition"); - if (contentDisp && contentDisp.type === "render") { - _this.renderbody = request.body; - _this.rendertype = request.getHeader("Content-Type"); - } - _this.status = Enums_1.SessionStatus.STATUS_INVITE_RECEIVED; - _this.fromTag = request.fromTag; - _this.id = request.callId + _this.fromTag; - _this.request = request; - _this.contact = _this.ua.contact.toString(); - _this.logger = ua.getLogger("sip.inviteservercontext", _this.id); - // Save the session into the ua sessions collection. - _this.ua.sessions[_this.id] = _this; - // Set 100rel if necessary - var set100rel = function (header, relSetting) { - if (request.hasHeader(header) && request.getHeader(header).toLowerCase().indexOf("100rel") >= 0) { - _this.rel100 = relSetting; - } - }; - set100rel("require", Constants_1.C.supported.REQUIRED); - set100rel("supported", Constants_1.C.supported.SUPPORTED); - // Set the toTag on the incoming request to the toTag which - // will be used in the response to the incoming request!!! - // FIXME: HACK: This is a hack to port an existing behavior. - // The behavior being ported appears to be a hack itself, - // so this is a hack to port a hack. At least one test spec - // relies on it (which is yet another hack). - _this.request.toTag = incomingInviteRequest.toTag; - _this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER; - // Set userNoAnswerTimer - _this.timers.userNoAnswerTimer = setTimeout(function () { - incomingInviteRequest.reject({ statusCode: 408 }); - _this.failed(request, Constants_1.C.causes.NO_ANSWER); - _this.terminated(request, Constants_1.C.causes.NO_ANSWER); - }, _this.ua.configuration.noAnswerTimeout || 60); - /* Set expiresTimer - * RFC3261 13.3.1 - */ - // Get the Expires header value if exists - if (request.hasHeader("expires")) { - var expires = Number(request.getHeader("expires") || 0) * 1000; - _this.timers.expiresTimer = setTimeout(function () { - if (_this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER) { - incomingInviteRequest.reject({ statusCode: 487 }); - _this.failed(request, Constants_1.C.causes.EXPIRES); - _this.terminated(request, Constants_1.C.causes.EXPIRES); - } - }, expires); - } - _this.errorListener = _this.onTransportError.bind(_this); - if (ua.transport) { - ua.transport.on("transportError", _this.errorListener); - } - return _this; - } - Object.defineProperty(InviteServerContext.prototype, "autoSendAnInitialProvisionalResponse", { - /** - * If true, a first provisional response after the 100 Trying - * will be sent automatically. This is false it the UAC required - * reliable provisional responses (100rel in Require header), - * otherwise it is true. The provisional is sent by calling - * `progress()` without any options. - * - * FIXME: TODO: It seems reasonable that the ISC user should - * be able to optionally disable this behavior. As the provisional - * is sent prior to the "invite" event being emitted, it's a known - * issue that the ISC user cannot register listeners or do any other - * setup prior to the call to `progress()`. As an example why this is - * an issue, setting `ua.configuration.rel100` to REQUIRED will result - * in an attempt by `progress()` to send a 183 with SDP produced by - * calling `getDescription()` on a session description handler, but - * the ISC user cannot perform any potentially required session description - * handler initialization (thus preventing the utilization of setting - * `ua.configuration.rel100` to REQUIRED). That begs the question of - * why this behavior is disabled when the UAC requires 100rel but not - * when the UAS requires 100rel? But ignoring that, it's just one example - * of a class of cases where the ISC user needs to do something prior - * to the first call to `progress()` and is unable to do so. - */ - get: function () { - return this.rel100 === Constants_1.C.supported.REQUIRED ? false : true; - }, - enumerable: true, - configurable: true - }); - // type hack for servercontext interface - InviteServerContext.prototype.reply = function (options) { - if (options === void 0) { options = {}; } - return this; - }; - // typing note: this was the only function using its super in ServerContext - // so the bottom half of this function is copied and paired down from that - InviteServerContext.prototype.reject = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - // Check Session Status - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - throw new Exceptions_1.Exceptions.InvalidStateError(this.status); - } - this.logger.log("rejecting RTCSession"); - var statusCode = options.statusCode || 480; - var reasonPhrase = Utils_1.Utils.getReasonPhrase(statusCode, options.reasonPhrase); - var extraHeaders = options.extraHeaders || []; - if (statusCode < 300 || statusCode > 699) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - var body = options.body ? core_1.fromBodyLegacy(options.body) : undefined; - // FIXME: Need to redirect to someplae - var response = statusCode < 400 ? - this.incomingRequest.redirect([], { statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }) : - this.incomingRequest.reject({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); - (["rejected", "failed"]).forEach(function (event) { - _this.emit(event, response.message, reasonPhrase); - }); - return this.terminated(); - }; - /** - * Accept the incoming INVITE request to start a Session. - * Replies to the INVITE request with a 200 Ok response. - * @param options Options bucket. - */ - InviteServerContext.prototype.accept = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - // FIXME: Need guard against calling more than once. - this._accept(options) - .then(function (_a) { - var message = _a.message, session = _a.session; - session.delegate = { - onAck: function (ackRequest) { return _this.onAck(ackRequest); }, - onAckTimeout: function () { return _this.onAckTimeout(); }, - onBye: function (byeRequest) { return _this.receiveRequest(byeRequest); }, - onInfo: function (infoRequest) { return _this.receiveRequest(infoRequest); }, - onInvite: function (inviteRequest) { return _this.receiveRequest(inviteRequest); }, - onNotify: function (notifyRequest) { return _this.receiveRequest(notifyRequest); }, - onPrack: function (prackRequest) { return _this.receiveRequest(prackRequest); }, - onRefer: function (referRequest) { return _this.receiveRequest(referRequest); } - }; - _this.session = session; - _this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK; - _this.accepted(message, Utils_1.Utils.getReasonPhrase(200)); - }) - .catch(function (error) { - _this.onContextError(error); - // FIXME: Assuming error due to async race on CANCEL and eating error. - if (!_this._canceled) { - throw error; - } - }); - return this; - }; - /** - * Report progress to the the caller. - * Replies to the INVITE request with a 1xx provisional response. - * @param options Options bucket. - */ - InviteServerContext.prototype.progress = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - // Ported - var statusCode = options.statusCode || 180; - if (statusCode < 100 || statusCode > 199) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - // Ported - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - this.logger.warn("Unexpected call for progress while terminated, ignoring"); - return this; - } - // Added - if (this.status === Enums_1.SessionStatus.STATUS_ANSWERED) { - this.logger.warn("Unexpected call for progress while answered, ignoring"); - return this; - } - // Added - if (this.status === Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK) { - this.logger.warn("Unexpected call for progress while answered (waiting for prack), ignoring"); - return this; - } - // After the first reliable provisional response for a request has been - // acknowledged, the UAS MAY send additional reliable provisional - // responses. The UAS MUST NOT send a second reliable provisional - // response until the first is acknowledged. After the first, it is - // RECOMMENDED that the UAS not send an additional reliable provisional - // response until the previous is acknowledged. The first reliable - // provisional response receives special treatment because it conveys - // the initial sequence number. If additional reliable provisional - // responses were sent before the first was acknowledged, the UAS could - // not be certain these were received in order. - // https://tools.ietf.org/html/rfc3262#section-3 - if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK) { - this.logger.warn("Unexpected call for progress while waiting for prack, ignoring"); - return this; - } - // Ported - if (options.statusCode === 100) { - try { - this.incomingRequest.trying(); - } - catch (error) { - this.onContextError(error); - // FIXME: Assuming error due to async race on CANCEL and eating error. - if (!this._canceled) { - throw error; - } - } - return this; - } - // Standard provisional response. - if (!(this.rel100 === Constants_1.C.supported.REQUIRED) && - !(this.rel100 === Constants_1.C.supported.SUPPORTED && options.rel100) && - !(this.rel100 === Constants_1.C.supported.SUPPORTED && this.ua.configuration.rel100 === Constants_1.C.supported.REQUIRED)) { - this._progress(options) - .catch(function (error) { - _this.onContextError(error); - // FIXME: Assuming error due to async race on CANCEL and eating error. - if (!_this._canceled) { - throw error; - } - }); - return this; - } - // Reliable provisional response. - this._reliableProgressWaitForPrack(options) - .catch(function (error) { - _this.onContextError(error); - // FIXME: Assuming error due to async race on CANCEL and eating error. - if (!_this._canceled) { - throw error; - } - }); - return this; - }; - /** - * Reject an unaccepted incoming INVITE request or send BYE if established session. - * @param options Options bucket. FIXME: This options bucket needs to be typed. - */ - InviteServerContext.prototype.terminate = function (options) { - // The caller's UA MAY send a BYE for either confirmed or early dialogs, - // and the callee's UA MAY send a BYE on confirmed dialogs, but MUST NOT - // send a BYE on early dialogs. However, the callee's UA MUST NOT send a - // BYE on a confirmed dialog until it has received an ACK for its 2xx - // response or until the server transaction times out. - // https://tools.ietf.org/html/rfc3261#section-15 - var _this = this; - if (options === void 0) { options = {}; } - // We don't yet have a dialog, so reject request. - if (!this.session) { - this.reject(options); - return this; - } - switch (this.session.sessionState) { - case core_1.SessionState.Initial: - this.reject(options); - return this; - case core_1.SessionState.Early: - this.reject(options); - return this; - case core_1.SessionState.AckWait: - this.session.delegate = { - // When ACK shows up, say BYE. - onAck: function () { - _this.sendRequest(Constants_1.C.BYE, options); - }, - // Or the server transaction times out before the ACK arrives. - onAckTimeout: function () { - _this.sendRequest(Constants_1.C.BYE, options); - } - }; - // Ported - this.emit("bye", this.request); - this.terminated(); - return this; - case core_1.SessionState.Confirmed: - this.bye(options); - return this; - case core_1.SessionState.Terminated: - return this; - default: - return this; - } - }; - InviteServerContext.prototype.onCancel = function (message) { - if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER || - this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK || - this.status === Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK || - this.status === Enums_1.SessionStatus.STATUS_EARLY_MEDIA || - this.status === Enums_1.SessionStatus.STATUS_ANSWERED) { - this.status = Enums_1.SessionStatus.STATUS_CANCELED; - this.incomingRequest.reject({ statusCode: 487 }); - this.canceled(); - this.rejected(message, Constants_1.C.causes.CANCELED); - this.failed(message, Constants_1.C.causes.CANCELED); - this.terminated(message, Constants_1.C.causes.CANCELED); - } - }; - InviteServerContext.prototype.receiveRequest = function (incomingRequest) { - var _this = this; - switch (incomingRequest.message.method) { - case Constants_1.C.PRACK: - if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK || - this.status === Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK) { - if (!this.hasAnswer) { - this.sessionDescriptionHandler = this.setupSessionDescriptionHandler(); - this.emit("SessionDescriptionHandler-created", this.sessionDescriptionHandler); - if (this.sessionDescriptionHandler.hasDescription(incomingRequest.message.getHeader("Content-Type") || "")) { - this.hasAnswer = true; - this.sessionDescriptionHandler.setDescription(incomingRequest.message.body, this.sessionDescriptionHandlerOptions, this.modifiers).then(function () { - clearTimeout(_this.timers.rel1xxTimer); - clearTimeout(_this.timers.prackTimer); - incomingRequest.accept(); - if (_this.status === Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK) { - _this.status = Enums_1.SessionStatus.STATUS_EARLY_MEDIA; - _this.accept(); - } - _this.status = Enums_1.SessionStatus.STATUS_EARLY_MEDIA; - }, function (e) { - _this.logger.warn(e); - _this.terminate({ - statusCode: "488", - reasonPhrase: "Bad Media Description" - }); - _this.failed(incomingRequest.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - _this.terminated(incomingRequest.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - }); - } - else { - this.terminate({ - statusCode: "488", - reasonPhrase: "Bad Media Description" - }); - this.failed(incomingRequest.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - this.terminated(incomingRequest.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - } - } - else { - clearTimeout(this.timers.rel1xxTimer); - clearTimeout(this.timers.prackTimer); - incomingRequest.accept(); - if (this.status === Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK) { - this.status = Enums_1.SessionStatus.STATUS_EARLY_MEDIA; - this.accept(); - } - this.status = Enums_1.SessionStatus.STATUS_EARLY_MEDIA; - } - } - else if (this.status === Enums_1.SessionStatus.STATUS_EARLY_MEDIA) { - incomingRequest.accept(); - } - break; - default: - _super.prototype.receiveRequest.call(this, incomingRequest); - break; - } - }; - // Internal Function to setup the handler consistently - InviteServerContext.prototype.setupSessionDescriptionHandler = function () { - if (this.sessionDescriptionHandler) { - return this.sessionDescriptionHandler; - } - return this.sessionDescriptionHandlerFactory(this, this.ua.configuration.sessionDescriptionHandlerFactoryOptions); - }; - InviteServerContext.prototype.generateResponseOfferAnswer = function (options) { - if (!this.session) { - var body = core_1.getBody(this.incomingRequest.message); - if (!body || body.contentDisposition !== "session") { - return this.getOffer(options); - } - else { - return this.setOfferAndGetAnswer(body, options); - } - } - else { - switch (this.session.signalingState) { - case core_1.SignalingState.Initial: - return this.getOffer(options); - case core_1.SignalingState.Stable: - return Promise.resolve(undefined); - case core_1.SignalingState.HaveLocalOffer: - // o Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - return Promise.resolve(undefined); - case core_1.SignalingState.HaveRemoteOffer: - if (!this.session.offer) { - throw new Error("Session offer undefined"); - } - return this.setOfferAndGetAnswer(this.session.offer, options); - case core_1.SignalingState.Closed: - throw new Error("Invalid signaling state " + this.session.signalingState + "."); - default: - throw new Error("Invalid signaling state " + this.session.signalingState + "."); - } - } - }; - InviteServerContext.prototype.handlePrackOfferAnswer = function (request, options) { - if (!this.session) { - throw new Error("Session undefined."); - } - // If the PRACK doesn't have an offer/answer, nothing to be done. - var body = core_1.getBody(request.message); - if (!body || body.contentDisposition !== "session") { - return Promise.resolve(undefined); - } - // If the UAC receives a reliable provisional response with an offer - // (this would occur if the UAC sent an INVITE without an offer, in - // which case the first reliable provisional response will contain the - // offer), it MUST generate an answer in the PRACK. If the UAC receives - // a reliable provisional response with an answer, it MAY generate an - // additional offer in the PRACK. If the UAS receives a PRACK with an - // offer, it MUST place the answer in the 2xx to the PRACK. - // https://tools.ietf.org/html/rfc3262#section-5 - switch (this.session.signalingState) { - case core_1.SignalingState.Initial: - // State should never be reached as first reliable provisional response must have answer/offer. - throw new Error("Invalid signaling state " + this.session.signalingState + "."); - case core_1.SignalingState.Stable: - // Receved answer. - return this.setAnswer(body, options).then(function () { return undefined; }); - case core_1.SignalingState.HaveLocalOffer: - // State should never be reached as local offer would be answered by this PRACK - throw new Error("Invalid signaling state " + this.session.signalingState + "."); - case core_1.SignalingState.HaveRemoteOffer: - // Receved offer, generate answer. - return this.setOfferAndGetAnswer(body, options); - case core_1.SignalingState.Closed: - throw new Error("Invalid signaling state " + this.session.signalingState + "."); - default: - throw new Error("Invalid signaling state " + this.session.signalingState + "."); - } - }; - /** - * Called when session canceled. - */ - InviteServerContext.prototype.canceled = function () { - this._canceled = true; - return _super.prototype.canceled.call(this); - }; - /** - * Called when session terminated. - * Using it here just for the PRACK timeout. - */ - InviteServerContext.prototype.terminated = function (message, cause) { - this.prackNeverArrived(); - return _super.prototype.terminated.call(this, message, cause); - }; - /** - * A version of `accept` which resolves a session when the 200 Ok response is sent. - * @param options Options bucket. - * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. - * @throws {TransactionStateError} The transaction state does not allow for `accept()` to be called. - * Note that the transaction state can change while this call is in progress. - */ - InviteServerContext.prototype._accept = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - // FIXME: Ported - callback for in dialog INFO requests. - // Turns out accept() can be called more than once if we are waiting - // for a PRACK in which case "options" get completely tossed away. - // So this is broken in that case (and potentially other uses of options). - // Tempted to just try to fix it now, but leaving it broken for the moment. - this.onInfo = options.onInfo; - // The UAS MAY send a final response to the initial request before - // having received PRACKs for all unacknowledged reliable provisional - // responses, unless the final response is 2xx and any of the - // unacknowledged reliable provisional responses contained a session - // description. In that case, it MUST NOT send a final response until - // those provisional responses are acknowledged. If the UAS does send a - // final response when reliable responses are still unacknowledged, it - // SHOULD NOT continue to retransmit the unacknowledged reliable - // provisional responses, but it MUST be prepared to process PRACK - // requests for those outstanding responses. A UAS MUST NOT send new - // reliable provisional responses (as opposed to retransmissions of - // unacknowledged ones) after sending a final response to a request. - // https://tools.ietf.org/html/rfc3262#section-3 - if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK) { - this.status = Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK; - return this.waitForArrivalOfPrack() - .then(function () { - _this.status = Enums_1.SessionStatus.STATUS_ANSWERED; - clearTimeout(_this.timers.userNoAnswerTimer); // Ported - }) - .then(function () { return _this.generateResponseOfferAnswer(options); }) - .then(function (body) { return _this.incomingRequest.accept({ statusCode: 200, body: body }); }); - } - // Ported - if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER) { - this.status = Enums_1.SessionStatus.STATUS_ANSWERED; - } - else { - return Promise.reject(new Exceptions_1.Exceptions.InvalidStateError(this.status)); - } - this.status = Enums_1.SessionStatus.STATUS_ANSWERED; - clearTimeout(this.timers.userNoAnswerTimer); // Ported - return this.generateResponseOfferAnswer(options) - .then(function (body) { return _this.incomingRequest.accept({ statusCode: 200, body: body }); }); - }; - /** - * A version of `progress` which resolves when the provisional response is sent. - * @param options Options bucket. - * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. - * @throws {TransactionStateError} The transaction state does not allow for `progress()` to be called. - * Note that the transaction state can change while this call is in progress. - */ - InviteServerContext.prototype._progress = function (options) { - if (options === void 0) { options = {}; } - // Ported - var statusCode = options.statusCode || 180; - var reasonPhrase = options.reasonPhrase; - var extraHeaders = (options.extraHeaders || []).slice(); - var body = options.body ? core_1.fromBodyLegacy(options.body) : undefined; - // The 183 (Session Progress) response is used to convey information - // about the progress of the call that is not otherwise classified. The - // Reason-Phrase, header fields, or message body MAY be used to convey - // more details about the call progress. - // https://tools.ietf.org/html/rfc3261#section-21.1.5 - // It is the de facto industry standard to utilize 183 with SDP to provide "early media". - // While it is unlikely someone would want to send a 183 without SDP, so it should be an option. - if (statusCode === 183 && !body) { - return this._progressWithSDP(options); - } - try { - var progressResponse = this.incomingRequest.progress({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); - this.emit("progress", progressResponse.message, reasonPhrase); // Ported - this.session = progressResponse.session; - return Promise.resolve(progressResponse); - } - catch (error) { - return Promise.reject(error); - } - }; - /** - * A version of `progress` which resolves when the provisional response with sdp is sent. - * @param options Options bucket. - * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. - * @throws {TransactionStateError} The transaction state does not allow for `progress()` to be called. - * Note that the transaction state can change while this call is in progress. - */ - InviteServerContext.prototype._progressWithSDP = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - var statusCode = options.statusCode || 183; - var reasonPhrase = options.reasonPhrase; - var extraHeaders = (options.extraHeaders || []).slice(); - // Get an offer/answer and send a reply. - return this.generateResponseOfferAnswer(options) - .then(function (body) { return _this.incomingRequest.progress({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); }) - .then(function (progressResponse) { - _this.emit("progress", progressResponse.message, reasonPhrase); // Ported - _this.session = progressResponse.session; - return progressResponse; - }); - }; - /** - * A version of `progress` which resolves when the reliable provisional response is sent. - * @param options Options bucket. - * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. - * @throws {TransactionStateError} The transaction state does not allow for `progress()` to be called. - * Note that the transaction state can change while this call is in progress. - */ - InviteServerContext.prototype._reliableProgress = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - var statusCode = options.statusCode || 183; - var reasonPhrase = options.reasonPhrase; - var extraHeaders = (options.extraHeaders || []).slice(); - extraHeaders.push("Require: 100rel"); - extraHeaders.push("RSeq: " + Math.floor(Math.random() * 10000)); - // Get an offer/answer and send a reply. - return this.generateResponseOfferAnswer(options) - .then(function (body) { return _this.incomingRequest.progress({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); }) - .then(function (progressResponse) { - _this.emit("progress", progressResponse.message, reasonPhrase); // Ported - _this.session = progressResponse.session; - return progressResponse; - }); - }; - /** - * A version of `progress` which resolves when the reliable provisional response is acknowledged. - * @param options Options bucket. - * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. - * @throws {TransactionStateError} The transaction state does not allow for `progress()` to be called. - * Note that the transaction state can change while this call is in progress. - */ - InviteServerContext.prototype._reliableProgressWaitForPrack = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - var statusCode = options.statusCode || 183; - var reasonPhrase = options.reasonPhrase; - var extraHeaders = (options.extraHeaders || []).slice(); - extraHeaders.push("Require: 100rel"); - extraHeaders.push("RSeq: " + this.rseq++); - var body; - // Ported - set status. - this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK; - return new Promise(function (resolve, reject) { - var waitingForPrack = true; - return _this.generateResponseOfferAnswer(options) - .then(function (offerAnswer) { - body = offerAnswer; - return _this.incomingRequest.progress({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); - }) - .then(function (progressResponse) { - _this.emit("progress", progressResponse.message, reasonPhrase); // Ported - _this.session = progressResponse.session; - var prackRequest; - var prackResponse; - progressResponse.session.delegate = { - onPrack: function (request) { - prackRequest = request; - clearTimeout(prackWaitTimeoutTimer); - clearTimeout(rel1xxRetransmissionTimer); - if (!waitingForPrack) { - return; - } - waitingForPrack = false; - _this.handlePrackOfferAnswer(prackRequest, options) - .then(function (prackResponseBody) { - try { - prackResponse = prackRequest.accept({ statusCode: 200, body: prackResponseBody }); - // Ported - set status. - if (_this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK) { - _this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER; - } - _this.prackArrived(); - resolve({ prackRequest: prackRequest, prackResponse: prackResponse, progressResponse: progressResponse }); - } - catch (error) { - reject(error); - } - }); - } - }; - // https://tools.ietf.org/html/rfc3262#section-3 - var prackWaitTimeout = function () { - if (!waitingForPrack) { - return; - } - waitingForPrack = false; - _this.logger.warn("No PRACK received, rejecting INVITE."); - clearTimeout(rel1xxRetransmissionTimer); - try { - _this.incomingRequest.reject({ statusCode: 504 }); - _this.terminated(undefined, Constants_1.C.causes.NO_PRACK); - reject(new Exceptions_1.Exceptions.TerminatedSessionError()); - } - catch (error) { - reject(error); - } - }; - var prackWaitTimeoutTimer = setTimeout(prackWaitTimeout, core_1.Timers.T1 * 64); - // https://tools.ietf.org/html/rfc3262#section-3 - var rel1xxRetransmission = function () { - try { - _this.incomingRequest.progress({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); - } - catch (error) { - waitingForPrack = false; - reject(error); - return; - } - rel1xxRetransmissionTimer = setTimeout(rel1xxRetransmission, timeout *= 2); - }; - var timeout = core_1.Timers.T1; - var rel1xxRetransmissionTimer = setTimeout(rel1xxRetransmission, timeout); - }); - }); - }; - /** - * Callback for when ACK for a 2xx response is never received. - * @param session Session the ACK never arrived for - */ - InviteServerContext.prototype.onAckTimeout = function () { - if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK) { - this.logger.log("no ACK received for an extended period of time, terminating the call"); - if (!this.session) { - throw new Error("Session undefined."); - } - this.session.bye(); - this.terminated(undefined, Constants_1.C.causes.NO_ACK); - } - }; - /** - * FIXME: TODO: The current library interface presents async methods without a - * proper async error handling mechanism. Arguably a promise based interface - * would be an improvement over the pattern of returning `this`. The approach has - * been generally along the lines of log a error and terminate. - */ - InviteServerContext.prototype.onContextError = function (error) { - var statusCode = 480; - if (error instanceof core_1.Exception) { // There might be interest in catching these Exceptions. - if (error instanceof Exceptions_1.Exceptions.SessionDescriptionHandlerError) { - this.logger.error(error.message); - if (error.error) { - this.logger.error(error.error); - } - } - else if (error instanceof Exceptions_1.Exceptions.TerminatedSessionError) { - // PRACK never arrived, so we timed out waiting for it. - this.logger.warn("Incoming session terminated while waiting for PRACK."); - } - else if (error instanceof Exceptions_1.Exceptions.UnsupportedSessionDescriptionContentTypeError) { - statusCode = 415; - } - else if (error instanceof core_1.Exception) { - this.logger.error(error.message); - } - } - else if (error instanceof Error) { // Other Errors hould go uncaught. - this.logger.error(error.message); - } - else { - // We don't actually know what a session description handler implementation might throw - // our way, so as a last resort, just assume we are getting an "any" and log it. - this.logger.error("An error occurred in the session description handler."); - this.logger.error(error); - } - try { - this.incomingRequest.reject({ statusCode: statusCode }); // "Temporarily Unavailable" - this.failed(this.incomingRequest.message, error.message); - this.terminated(this.incomingRequest.message, error.message); - } - catch (error) { - return; - } - }; - InviteServerContext.prototype.prackArrived = function () { - if (this.waitingForPrackResolve) { - this.waitingForPrackResolve(); - } - this.waitingForPrackPromise = undefined; - this.waitingForPrackResolve = undefined; - this.waitingForPrackReject = undefined; - }; - InviteServerContext.prototype.prackNeverArrived = function () { - if (this.waitingForPrackReject) { - this.waitingForPrackReject(new Exceptions_1.Exceptions.TerminatedSessionError()); - } - this.waitingForPrackPromise = undefined; - this.waitingForPrackResolve = undefined; - this.waitingForPrackReject = undefined; - }; - /** - * @throws {Exceptions.TerminatedSessionError} The session terminated before being accepted (i.e. cancel arrived). - */ - InviteServerContext.prototype.waitForArrivalOfPrack = function () { - var _this = this; - if (this.waitingForPrackPromise) { - throw new Error("Already waiting for PRACK"); - } - this.waitingForPrackPromise = new Promise(function (resolve, reject) { - _this.waitingForPrackResolve = resolve; - _this.waitingForPrackReject = reject; - }); - return this.waitingForPrackPromise; - }; - InviteServerContext.prototype.getOffer = function (options) { - this.hasOffer = true; - var sdh = this.getSessionDescriptionHandler(); - return sdh - .getDescription(options.sessionDescriptionHandlerOptions, options.modifiers) - .then(function (bodyObj) { return Utils_1.Utils.fromBodyObj(bodyObj); }); - }; - InviteServerContext.prototype.setAnswer = function (answer, options) { - this.hasAnswer = true; - var sdh = this.getSessionDescriptionHandler(); - if (!sdh.hasDescription(answer.contentType)) { - return Promise.reject(new Exceptions_1.Exceptions.UnsupportedSessionDescriptionContentTypeError()); - } - return sdh - .setDescription(answer.content, options.sessionDescriptionHandlerOptions, options.modifiers); - }; - InviteServerContext.prototype.setOfferAndGetAnswer = function (offer, options) { - this.hasOffer = true; - this.hasAnswer = true; - var sdh = this.getSessionDescriptionHandler(); - if (!sdh.hasDescription(offer.contentType)) { - return Promise.reject(new Exceptions_1.Exceptions.UnsupportedSessionDescriptionContentTypeError()); - } - return sdh - .setDescription(offer.content, options.sessionDescriptionHandlerOptions, options.modifiers) - .then(function () { return sdh.getDescription(options.sessionDescriptionHandlerOptions, options.modifiers); }) - .then(function (bodyObj) { return Utils_1.Utils.fromBodyObj(bodyObj); }); - }; - InviteServerContext.prototype.getSessionDescriptionHandler = function () { - // Create our session description handler if not already done so... - var sdh = this.sessionDescriptionHandler = this.setupSessionDescriptionHandler(); - // FIXME: Ported - this can get emitted multiple times even when only created once... don't we care? - this.emit("SessionDescriptionHandler-created", this.sessionDescriptionHandler); - // Return. - return sdh; - }; - return InviteServerContext; -}(Session)); -exports.InviteServerContext = InviteServerContext; -// tslint:disable-next-line:max-classes-per-file -var InviteClientContext = /** @class */ (function (_super) { - tslib_1.__extends(InviteClientContext, _super); - function InviteClientContext(ua, target, options, modifiers) { - if (options === void 0) { options = {}; } - if (modifiers === void 0) { modifiers = []; } - var _this = this; - if (!ua.configuration.sessionDescriptionHandlerFactory) { - ua.logger.warn("Can't build ISC without SDH Factory"); - throw new Error("ICC Constructor Failed"); - } - options.params = options.params || {}; - var anonymous = options.anonymous || false; - var fromTag = Utils_1.Utils.newTag(); - options.params.fromTag = fromTag; - /* Do not add ;ob in initial forming dialog requests if the registration over - * the current connection got a GRUU URI. - */ - var contact = ua.contact.toString({ - anonymous: anonymous, - outbound: anonymous ? !ua.contact.tempGruu : !ua.contact.pubGruu - }); - var extraHeaders = (options.extraHeaders || []).slice(); - if (anonymous && ua.configuration.uri) { - options.params.fromDisplayName = "Anonymous"; - options.params.fromUri = "sip:anonymous@anonymous.invalid"; - extraHeaders.push("P-Preferred-Identity: " + ua.configuration.uri.toString()); - extraHeaders.push("Privacy: id"); - } - extraHeaders.push("Contact: " + contact); - // this is UA.C.ALLOWED_METHODS, removed to get around circular dependency - extraHeaders.push("Allow: " + [ - "ACK", - "CANCEL", - "INVITE", - "MESSAGE", - "BYE", - "OPTIONS", - "INFO", - "NOTIFY", - "REFER" - ].toString()); - if (ua.configuration.rel100 === Constants_1.C.supported.REQUIRED) { - extraHeaders.push("Require: 100rel"); - } - if (ua.configuration.replaces === Constants_1.C.supported.REQUIRED) { - extraHeaders.push("Require: replaces"); - } - options.extraHeaders = extraHeaders; - _this = _super.call(this, ua.configuration.sessionDescriptionHandlerFactory) || this; - ClientContext_1.ClientContext.initializer(_this, ua, Constants_1.C.INVITE, target, options); - _this.earlyMediaSessionDescriptionHandlers = new Map(); - _this.type = Enums_1.TypeStrings.InviteClientContext; - _this.passedOptions = options; // Save for later to use with refer - _this.sessionDescriptionHandlerOptions = options.sessionDescriptionHandlerOptions || {}; - _this.modifiers = modifiers; - _this.inviteWithoutSdp = options.inviteWithoutSdp || false; - // Set anonymous property - _this.anonymous = options.anonymous || false; - // Custom data to be sent either in INVITE or in ACK - _this.renderbody = options.renderbody || undefined; - _this.rendertype = options.rendertype || "text/plain"; - // Session parameter initialization - _this.fromTag = fromTag; - _this.contact = contact; - // Check Session Status - if (_this.status !== Enums_1.SessionStatus.STATUS_NULL) { - throw new Exceptions_1.Exceptions.InvalidStateError(_this.status); - } - // OutgoingSession specific parameters - _this.isCanceled = false; - _this.received100 = false; - _this.method = Constants_1.C.INVITE; - _this.logger = ua.getLogger("sip.inviteclientcontext"); - ua.applicants[_this.toString()] = _this; - _this.id = _this.request.callId + _this.fromTag; - _this.onInfo = options.onInfo; - _this.errorListener = _this.onTransportError.bind(_this); - if (ua.transport) { - ua.transport.on("transportError", _this.errorListener); - } - return _this; - } - InviteClientContext.prototype.receiveResponse = function (response) { - throw new Error("Unimplemented."); - }; - // hack for getting around ClientContext interface - InviteClientContext.prototype.send = function () { - this.sendInvite(); - return this; - }; - InviteClientContext.prototype.invite = function () { - var _this = this; - // Save the session into the ua sessions collection. - // Note: placing in constructor breaks call to request.cancel on close... User does not need this anyway - this.ua.sessions[this.id] = this; - // This should allow the function to return so that listeners can be set up for these events - Promise.resolve().then(function () { - // FIXME: There is a race condition where cancel (or terminate) can be called synchronously after invite. - if (_this.isCanceled || _this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return; - } - if (_this.inviteWithoutSdp) { - // just send an invite with no sdp... - if (_this.renderbody && _this.rendertype) { - _this.request.body = { - body: _this.renderbody, - contentType: _this.rendertype - }; - } - _this.status = Enums_1.SessionStatus.STATUS_INVITE_SENT; - _this.send(); - } - else { - // Initialize Media Session - _this.sessionDescriptionHandler = _this.sessionDescriptionHandlerFactory(_this, _this.ua.configuration.sessionDescriptionHandlerFactoryOptions || {}); - _this.emit("SessionDescriptionHandler-created", _this.sessionDescriptionHandler); - _this.sessionDescriptionHandler.getDescription(_this.sessionDescriptionHandlerOptions, _this.modifiers) - .then(function (description) { - // FIXME: There is a race condition where cancel (or terminate) can be called (a)synchronously after invite. - if (_this.isCanceled || _this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return; - } - _this.hasOffer = true; - _this.request.body = description; - _this.status = Enums_1.SessionStatus.STATUS_INVITE_SENT; - _this.send(); - }, function (err) { - if (err.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - _this.logger.log(err.message); - if (err.error) { - _this.logger.log(err.error); - } - } - if (_this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return; - } - _this.failed(undefined, Constants_1.C.causes.WEBRTC_ERROR); - _this.terminated(undefined, Constants_1.C.causes.WEBRTC_ERROR); - }); - } - }); - return this; - }; - InviteClientContext.prototype.cancel = function (options) { - if (options === void 0) { options = {}; } - // Check Session Status - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED || this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { - throw new Exceptions_1.Exceptions.InvalidStateError(this.status); - } - if (this.isCanceled) { - throw new Exceptions_1.Exceptions.InvalidStateError(Enums_1.SessionStatus.STATUS_CANCELED); - } - this.isCanceled = true; - this.logger.log("Canceling session"); - var cancelReason = Utils_1.Utils.getCancelReason(options.statusCode, options.reasonPhrase); - options.extraHeaders = (options.extraHeaders || []).slice(); - if (this.outgoingInviteRequest) { - this.logger.warn("Canceling session before it was created"); - this.outgoingInviteRequest.cancel(cancelReason, options); - } - return this.canceled(); - }; - InviteClientContext.prototype.terminate = function (options) { - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return this; - } - if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK || this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { - this.bye(options); - } - else { - this.cancel(options); - } - return this; - }; - /** - * 13.2.1 Creating the Initial INVITE - * - * Since the initial INVITE represents a request outside of a dialog, - * its construction follows the procedures of Section 8.1.1. Additional - * processing is required for the specific case of INVITE. - * - * An Allow header field (Section 20.5) SHOULD be present in the INVITE. - * It indicates what methods can be invoked within a dialog, on the UA - * sending the INVITE, for the duration of the dialog. For example, a - * UA capable of receiving INFO requests within a dialog [34] SHOULD - * include an Allow header field listing the INFO method. - * - * A Supported header field (Section 20.37) SHOULD be present in the - * INVITE. It enumerates all the extensions understood by the UAC. - * - * An Accept (Section 20.1) header field MAY be present in the INVITE. - * It indicates which Content-Types are acceptable to the UA, in both - * the response received by it, and in any subsequent requests sent to - * it within dialogs established by the INVITE. The Accept header field - * is especially useful for indicating support of various session - * description formats. - * - * The UAC MAY add an Expires header field (Section 20.19) to limit the - * validity of the invitation. If the time indicated in the Expires - * header field is reached and no final answer for the INVITE has been - * received, the UAC core SHOULD generate a CANCEL request for the - * INVITE, as per Section 9. - * - * A UAC MAY also find it useful to add, among others, Subject (Section - * 20.36), Organization (Section 20.25) and User-Agent (Section 20.41) - * header fields. They all contain information related to the INVITE. - * - * The UAC MAY choose to add a message body to the INVITE. Section - * 8.1.1.10 deals with how to construct the header fields -- Content- - * Type among others -- needed to describe the message body. - * - * https://tools.ietf.org/html/rfc3261#section-13.2.1 - */ - InviteClientContext.prototype.sendInvite = function () { - // There are special rules for message bodies that contain a session - // description - their corresponding Content-Disposition is "session". - // SIP uses an offer/answer model where one UA sends a session - // description, called the offer, which contains a proposed description - // of the session. The offer indicates the desired communications means - // (audio, video, games), parameters of those means (such as codec - // types) and addresses for receiving media from the answerer. The - // other UA responds with another session description, called the - // answer, which indicates which communications means are accepted, the - // parameters that apply to those means, and addresses for receiving - // media from the offerer. An offer/answer exchange is within the - // context of a dialog, so that if a SIP INVITE results in multiple - // dialogs, each is a separate offer/answer exchange. The offer/answer - // model defines restrictions on when offers and answers can be made - // (for example, you cannot make a new offer while one is in progress). - // This results in restrictions on where the offers and answers can - // appear in SIP messages. In this specification, offers and answers - // can only appear in INVITE requests and responses, and ACK. The usage - // of offers and answers is further restricted. For the initial INVITE - // transaction, the rules are: - // - // o The initial offer MUST be in either an INVITE or, if not there, - // in the first reliable non-failure message from the UAS back to - // the UAC. In this specification, that is the final 2xx - // response. - // - // o If the initial offer is in an INVITE, the answer MUST be in a - // reliable non-failure message from UAS back to UAC which is - // correlated to that INVITE. For this specification, that is - // only the final 2xx response to that INVITE. That same exact - // answer MAY also be placed in any provisional responses sent - // prior to the answer. The UAC MUST treat the first session - // description it receives as the answer, and MUST ignore any - // session descriptions in subsequent responses to the initial - // INVITE. - // - // o If the initial offer is in the first reliable non-failure - // message from the UAS back to UAC, the answer MUST be in the - // acknowledgement for that message (in this specification, ACK - // for a 2xx response). - // - // o After having sent or received an answer to the first offer, the - // UAC MAY generate subsequent offers in requests based on rules - // specified for that method, but only if it has received answers - // to any previous offers, and has not sent any offers to which it - // hasn't gotten an answer. - // - // o Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - var _this = this; - // 5 The Offer/Answer Model and PRACK - // - // RFC 3261 describes guidelines for the sets of messages in which - // offers and answers [3] can appear. Based on those guidelines, this - // extension provides additional opportunities for offer/answer - // exchanges. - // If the INVITE contained an offer, the UAS MAY generate an answer in a - // reliable provisional response (assuming these are supported by the - // UAC). That results in the establishment of the session before - // completion of the call. Similarly, if a reliable provisional - // response is the first reliable message sent back to the UAC, and the - // INVITE did not contain an offer, one MUST appear in that reliable - // provisional response. - // If the UAC receives a reliable provisional response with an offer - // (this would occur if the UAC sent an INVITE without an offer, in - // which case the first reliable provisional response will contain the - // offer), it MUST generate an answer in the PRACK. If the UAC receives - // a reliable provisional response with an answer, it MAY generate an - // additional offer in the PRACK. If the UAS receives a PRACK with an - // offer, it MUST place the answer in the 2xx to the PRACK. - // Once an answer has been sent or received, the UA SHOULD establish the - // session based on the parameters of the offer and answer, even if the - // original INVITE itself has not been responded to. - // If the UAS had placed a session description in any reliable - // provisional response that is unacknowledged when the INVITE is - // accepted, the UAS MUST delay sending the 2xx until the provisional - // response is acknowledged. Otherwise, the reliability of the 1xx - // cannot be guaranteed, and reliability is needed for proper operation - // of the offer/answer exchange. - // All user agents that support this extension MUST support all - // offer/answer exchanges that are possible based on the rules in - // Section 13.2 of RFC 3261, based on the existence of INVITE and PRACK - // as requests, and 2xx and reliable 1xx as non-failure reliable - // responses. - // - // https://tools.ietf.org/html/rfc3262#section-5 - //// - // The Offer/Answer Model Implementation - // - // The offer/answer model is straight forward, but one MUST READ the specifications... - // - // 13.2.1 Creating the Initial INVITE (paragraph 8 in particular) - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // - // 5 The Offer/Answer Model and PRACK - // https://tools.ietf.org/html/rfc3262#section-5 - // - // Session Initiation Protocol (SIP) Usage of the Offer/Answer Model - // https://tools.ietf.org/html/rfc6337 - // - // *** IMPORTANT IMPLEMENTATION CHOICES *** - // - // TLDR... - // - // 1) Only one offer/answer exchange permitted during initial INVITE. - // 2) No "early media" if the initial offer is in an INVITE. - // - // - // 1) Initial Offer/Answer Restriction. - // - // Our implementation replaces the following bullet point... - // - // o After having sent or received an answer to the first offer, the - // UAC MAY generate subsequent offers in requests based on rules - // specified for that method, but only if it has received answers - // to any previous offers, and has not sent any offers to which it - // hasn't gotten an answer. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // - // ...with... - // - // o After having sent or received an answer to the first offer, the - // UAC MUST NOT generate subsequent offers in requests based on rules - // specified for that method. - // - // ...which in combination with this bullet point... - // - // o Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // - // ...ensures that EXACTLY ONE offer/answer exchange will occur - // during an initial out of dialog INVITE request made by our UAC. - // - // - // 2) Early Media Restriction. - // - // While our implementation adheres to the following bullet point... - // - // o If the initial offer is in an INVITE, the answer MUST be in a - // reliable non-failure message from UAS back to UAC which is - // correlated to that INVITE. For this specification, that is - // only the final 2xx response to that INVITE. That same exact - // answer MAY also be placed in any provisional responses sent - // prior to the answer. The UAC MUST treat the first session - // description it receives as the answer, and MUST ignore any - // session descriptions in subsequent responses to the initial - // INVITE. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // - // We have made the following implementation decision with regard to early media... - // - // o If the initial offer is in the INVITE, the answer from the - // UAS back to the UAC will establish a media session only - // only after the final 2xx response to that INVITE is received. - // - // The reason for this decision is rooted in a restriction currently - // inherent in WebRTC. Specifically, while a SIP INVITE request with an - // initial offer may fork resulting in more than one provisional answer, - // there is currently no easy/good way to to "fork" an offer generated - // by a peer connection. In particular, a WebRTC offer currently may only - // be matched with one answer and we have no good way to know which - // "provisional answer" is going to be the "final answer". So we have - // decided to punt and not create any "early media" sessions in this case. - // - // The upshot is that if you want "early media", you must not put the - // initial offer in the INVITE. Instead, force the UAS to provide the - // initial offer by sending an INVITE without an offer. In the WebRTC - // case this allows us to create a unique peer connection with a unique - // answer for every provisional offer with "early media" on all of them. - //// - //// - // ROADMAP: The Offer/Answer Model Implementation - // - // The "no early media if offer in INVITE" implementation is not a - // welcome one. The masses want it. The want it and they want it - // to work for WebRTC (so they want to have their cake and eat too). - // - // So while we currently cannot make the offer in INVITE+forking+webrtc - // case work, we decided to do the following... - // - // 1) modify SDH Factory to provide an initial offer without giving us the SDH, and then... - // 2) stick that offer in the initial INVITE, and when 183 with initial answer is received... - // 3) ask SDH Factory if it supports "earlyRemoteAnswer" - // a) if true, ask SDH Factory to createSDH(localOffer).then((sdh) => sdh.setDescription(remoteAnswer) - // b) if false, defer getting a SDH until 2xx response is received - // - // Our supplied WebRTC SDH will default to behavior 3b which works in forking environment (without) - // early media if initial offer is in the INVITE). We will, however, provide an "inviteWillNotFork" - // option which if set to "true" will have our supplied WebRTC SDH behave in the 3a manner. - // That will result in - // - early media working with initial offer in the INVITE, and... - // - if the INVITE forks, the session terminating with an ERROR that reads like - // "You set 'inviteWillNotFork' to true but the INVITE forked. You can't eat your cake, and have it too." - // - furthermore, we accept that users will report that error to us as "bug" regardless - // - // So, SDH Factory is going to end up with a new interface along the lines of... - // - // interface SessionDescriptionHandlerFactory { - // makeLocalOffer(): Promise; - // makeSessionDescriptionHandler( - // initialOffer: ContentTypeAndBody, offerType: "local" | "remote" - // ): Promise; - // supportsEarlyRemoteAnswer: boolean; - // supportsContentType(contentType: string): boolean; - // getDescription(description: ContentTypeAndBody): Promise - // setDescription(description: ContentTypeAndBody): Promise - // } - // - // We should be able to get rid of all the hasOffer/hasAnswer tracking code and otherwise code - // it up to the same interaction with the SDH Factory and SDH regardless of signaling scenario. - //// - // Send the INVITE request. - this.outgoingInviteRequest = this.ua.userAgentCore.invite(this.request, { - onAccept: function (inviteResponse) { return _this.onAccept(inviteResponse); }, - onProgress: function (inviteResponse) { return _this.onProgress(inviteResponse); }, - onRedirect: function (inviteResponse) { return _this.onRedirect(inviteResponse); }, - onReject: function (inviteResponse) { return _this.onReject(inviteResponse); }, - onTrying: function (inviteResponse) { return _this.onTrying(inviteResponse); } - }); - }; - InviteClientContext.prototype.ackAndBye = function (inviteResponse, session, statusCode, reasonPhrase) { - if (!this.ua.userAgentCore) { - throw new Error("Method requires user agent core."); - } - var extraHeaders = []; - if (statusCode) { - extraHeaders.push("Reason: " + Utils_1.Utils.getReasonHeaderValue(statusCode, reasonPhrase)); - } - var outgoingAckRequest = inviteResponse.ack(); - this.emit("ack", outgoingAckRequest.message); - var outgoingByeRequest = session.bye(undefined, { extraHeaders: extraHeaders }); - this.emit("bye", outgoingByeRequest.message); - }; - InviteClientContext.prototype.disposeEarlyMedia = function () { - if (!this.earlyMediaSessionDescriptionHandlers) { - throw new Error("Early media session description handlers undefined."); - } - this.earlyMediaSessionDescriptionHandlers.forEach(function (sessionDescriptionHandler) { - sessionDescriptionHandler.close(); - }); - }; - /** - * Handle final response to initial INVITE. - * @param inviteResponse 2xx response. - */ - InviteClientContext.prototype.onAccept = function (inviteResponse) { - var _this = this; - if (!this.earlyMediaSessionDescriptionHandlers) { - throw new Error("Early media session description handlers undefined."); - } - var response = inviteResponse.message; - var session = inviteResponse.session; - // Our transaction layer is "non-standard" in that it will only - // pass us a 2xx response once per branch, so there is no need to - // worry about dealing with 2xx retransmissions. However, we can - // and do still get 2xx responses for multiple branches (when an - // INVITE is forked) which may create multiple confirmed dialogs. - // Herein we are acking and sending a bye to any confirmed dialogs - // which arrive beyond the first one. This is the desired behavior - // for most applications (but certainly not all). - // If we already received a confirmed dialog, ack & bye this session. - if (this.session) { - this.ackAndBye(inviteResponse, session); - return; - } - // If the user requested cancellation, ack & bye this session. - if (this.isCanceled) { - this.ackAndBye(inviteResponse, session); - this.emit("bye", this.request); // FIXME: Ported this odd second "bye" emit - return; - } - // Ported behavior. - if (response.hasHeader("P-Asserted-Identity")) { - this.assertedIdentity = core_1.Grammar.nameAddrHeaderParse(response.getHeader("P-Asserted-Identity")); - } - // We have a confirmed dialog. - this.session = session; - this.session.delegate = { - onAck: function (ackRequest) { return _this.onAck(ackRequest); }, - onBye: function (byeRequest) { return _this.receiveRequest(byeRequest); }, - onInfo: function (infoRequest) { return _this.receiveRequest(infoRequest); }, - onInvite: function (inviteRequest) { return _this.receiveRequest(inviteRequest); }, - onNotify: function (notifyRequest) { return _this.receiveRequest(notifyRequest); }, - onPrack: function (prackRequest) { return _this.receiveRequest(prackRequest); }, - onRefer: function (referRequest) { return _this.receiveRequest(referRequest); } - }; - switch (session.signalingState) { - case core_1.SignalingState.Initial: - // INVITE without Offer, so MUST have Offer at this point, so invalid state. - this.ackAndBye(inviteResponse, session, 400, "Missing session description"); - this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - break; - case core_1.SignalingState.HaveLocalOffer: - // INVITE with Offer, so MUST have Answer at this point, so invalid state. - this.ackAndBye(inviteResponse, session, 400, "Missing session description"); - this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - break; - case core_1.SignalingState.HaveRemoteOffer: - // INVITE without Offer, received offer in 2xx, so MUST send Answer in ACK. - var sdh_1 = this.sessionDescriptionHandlerFactory(this, this.ua.configuration.sessionDescriptionHandlerFactoryOptions || {}); - this.sessionDescriptionHandler = sdh_1; - this.emit("SessionDescriptionHandler-created", this.sessionDescriptionHandler); - if (!sdh_1.hasDescription(response.getHeader("Content-Type") || "")) { - this.ackAndBye(inviteResponse, session, 400, "Missing session description"); - this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - break; - } - this.hasOffer = true; - sdh_1 - .setDescription(response.body, this.sessionDescriptionHandlerOptions, this.modifiers) - .then(function () { return sdh_1.getDescription(_this.sessionDescriptionHandlerOptions, _this.modifiers); }) - .then(function (description) { - if (_this.isCanceled || _this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return; - } - _this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; - _this.hasAnswer = true; - var body = { - contentDisposition: "session", contentType: description.contentType, content: description.body - }; - var ackRequest = inviteResponse.ack({ body: body }); - _this.emit("ack", ackRequest.message); - _this.accepted(response); - }) - .catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - _this.logger.warn("invalid description"); - _this.logger.warn(e.toString()); - // TODO: This message is inconsistent - _this.ackAndBye(inviteResponse, session, 488, "Invalid session description"); - _this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - } - else { - throw e; - } - }); - break; - case core_1.SignalingState.Stable: - // This session has completed an initial offer/answer exchange... - var options_1; - if (this.renderbody && this.rendertype) { - options_1 = { body: { contentDisposition: "render", contentType: this.rendertype, content: this.renderbody } }; - } - // If INVITE with Offer and we have been waiting till now to apply the answer. - if (this.hasOffer && !this.hasAnswer) { - if (!this.sessionDescriptionHandler) { - throw new Error("Session description handler undefined."); - } - var answer = session.answer; - if (!answer) { - throw new Error("Answer is undefined."); - } - this.sessionDescriptionHandler - .setDescription(answer.content, this.sessionDescriptionHandlerOptions, this.modifiers) - .then(function () { - _this.hasAnswer = true; - _this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; - var ackRequest = inviteResponse.ack(options_1); - _this.emit("ack", ackRequest.message); - _this.accepted(response); - }) - .catch(function (error) { - _this.logger.error(error); - _this.ackAndBye(inviteResponse, session, 488, "Not Acceptable Here"); - _this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - // FIME: DON'T EAT UNHANDLED ERRORS! - }); - } - else { - // Otherwise INVITE with or without Offer and we have already completed the initial exchange. - this.sessionDescriptionHandler = this.earlyMediaSessionDescriptionHandlers.get(session.id); - if (!this.sessionDescriptionHandler) { - throw new Error("Session description handler undefined."); - } - this.earlyMediaSessionDescriptionHandlers.delete(session.id); - this.hasOffer = true; - this.hasAnswer = true; - this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; - var ackRequest = inviteResponse.ack(); - this.emit("ack", ackRequest.message); - this.accepted(response); - } - break; - case core_1.SignalingState.Closed: - // Dialog has terminated. - break; - default: - throw new Error("Unknown session signaling state."); - } - this.disposeEarlyMedia(); - }; - /** - * Handle provisional response to initial INVITE. - * @param inviteResponse 1xx response. - */ - InviteClientContext.prototype.onProgress = function (inviteResponse) { - var _this = this; - // Ported - User requested cancellation. - if (this.isCanceled) { - return; - } - if (!this.outgoingInviteRequest) { - throw new Error("Outgoing INVITE request undefined."); - } - if (!this.earlyMediaSessionDescriptionHandlers) { - throw new Error("Early media session description handlers undefined."); - } - var response = inviteResponse.message; - var session = inviteResponse.session; - // Ported - Set status. - this.status = Enums_1.SessionStatus.STATUS_1XX_RECEIVED; - // Ported - Set assertedIdentity. - if (response.hasHeader("P-Asserted-Identity")) { - this.assertedIdentity = core_1.Grammar.nameAddrHeaderParse(response.getHeader("P-Asserted-Identity")); - } - // The provisional response MUST establish a dialog if one is not yet created. - // https://tools.ietf.org/html/rfc3262#section-4 - if (!session) { - // A response with a to tag MUST create a session (should never get here). - throw new Error("Session undefined."); - } - // If a provisional response is received for an initial request, and - // that response contains a Require header field containing the option - // tag 100rel, the response is to be sent reliably. If the response is - // a 100 (Trying) (as opposed to 101 to 199), this option tag MUST be - // ignored, and the procedures below MUST NOT be used. - // https://tools.ietf.org/html/rfc3262#section-4 - var requireHeader = response.getHeader("require"); - var rseqHeader = response.getHeader("rseq"); - var rseq = requireHeader && requireHeader.includes("100rel") && rseqHeader ? Number(rseqHeader) : undefined; - var responseReliable = !!rseq; - var extraHeaders = []; - if (responseReliable) { - extraHeaders.push("RAck: " + response.getHeader("rseq") + " " + response.getHeader("cseq")); - } - // INVITE without Offer and session still has no offer (and no answer). - if (session.signalingState === core_1.SignalingState.Initial) { - // Similarly, if a reliable provisional - // response is the first reliable message sent back to the UAC, and the - // INVITE did not contain an offer, one MUST appear in that reliable - // provisional response. - // https://tools.ietf.org/html/rfc3262#section-5 - if (responseReliable) { - this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."); - // FIXME: Known popular UA's currently end up here... - inviteResponse.prack({ extraHeaders: extraHeaders }); - } - this.emit("progress", response); - return; - } - // INVITE with Offer and session only has that initial local offer. - if (session.signalingState === core_1.SignalingState.HaveLocalOffer) { - if (responseReliable) { - inviteResponse.prack({ extraHeaders: extraHeaders }); - } - this.emit("progress", response); - return; - } - // INVITE without Offer and received initial offer in provisional response - if (session.signalingState === core_1.SignalingState.HaveRemoteOffer) { - // The initial offer MUST be in either an INVITE or, if not there, - // in the first reliable non-failure message from the UAS back to - // the UAC. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // According to Section 13.2.1 of [RFC3261], 'The first reliable - // non-failure message' must have an offer if there is no offer in the - // INVITE request. This means that the User Agent (UA) that receives - // the INVITE request without an offer must include an offer in the - // first reliable response with 100rel extension. If no reliable - // provisional response has been sent, the User Agent Server (UAS) must - // include an offer when sending 2xx response. - // https://tools.ietf.org/html/rfc6337#section-2.2 - if (!responseReliable) { - this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response."); - return; - } - // If the initial offer is in the first reliable non-failure - // message from the UAS back to UAC, the answer MUST be in the - // acknowledgement for that message - var sdh_2 = this.sessionDescriptionHandlerFactory(this, this.ua.configuration.sessionDescriptionHandlerFactoryOptions || {}); - this.emit("SessionDescriptionHandler-created", sdh_2); - this.earlyMediaSessionDescriptionHandlers.set(session.id, sdh_2); - sdh_2 - .setDescription(response.body, this.sessionDescriptionHandlerOptions, this.modifiers) - .then(function () { return sdh_2.getDescription(_this.sessionDescriptionHandlerOptions, _this.modifiers); }) - .then(function (description) { - var body = { - contentDisposition: "session", contentType: description.contentType, content: description.body - }; - inviteResponse.prack({ extraHeaders: extraHeaders, body: body }); - _this.status = Enums_1.SessionStatus.STATUS_EARLY_MEDIA; - _this.emit("progress", response); - }) - .catch(function (error) { - if (_this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return; - } - _this.failed(undefined, Constants_1.C.causes.WEBRTC_ERROR); - _this.terminated(undefined, Constants_1.C.causes.WEBRTC_ERROR); - }); - return; - } - // This session has completed an initial offer/answer exchange, so... - // - INVITE with SDP and this provisional response MAY be reliable - // - INVITE without SDP and this provisional response MAY be reliable - if (session.signalingState === core_1.SignalingState.Stable) { - if (responseReliable) { - inviteResponse.prack({ extraHeaders: extraHeaders }); - } - // Note: As documented, no early media if offer was in INVITE, so nothing to be done. - // FIXME: TODO: Add a flag/hack to allow early media in this case. There are people - // in non-forking environments (think straight to FreeSWITCH) who want - // early media on a 183. Not sure how to actually make it work, basically - // something like... - if (0 /* flag */ && this.hasOffer && !this.hasAnswer && this.sessionDescriptionHandler) { - this.hasAnswer = true; - this.status = Enums_1.SessionStatus.STATUS_EARLY_MEDIA; - this.sessionDescriptionHandler - .setDescription(response.body, this.sessionDescriptionHandlerOptions, this.modifiers) - .then(function () { - _this.status = Enums_1.SessionStatus.STATUS_EARLY_MEDIA; - }) - .catch(function (error) { - if (_this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return; - } - _this.failed(undefined, Constants_1.C.causes.WEBRTC_ERROR); - _this.terminated(undefined, Constants_1.C.causes.WEBRTC_ERROR); - }); - } - this.emit("progress", response); - return; - } - }; - /** - * Handle final response to initial INVITE. - * @param inviteResponse 3xx response. - */ - InviteClientContext.prototype.onRedirect = function (inviteResponse) { - this.disposeEarlyMedia(); - var response = inviteResponse.message; - var statusCode = response.statusCode; - var cause = Utils_1.Utils.sipErrorCause(statusCode || 0); - this.rejected(response, cause); - this.failed(response, cause); - this.terminated(response, cause); - }; - /** - * Handle final response to initial INVITE. - * @param inviteResponse 4xx, 5xx, or 6xx response. - */ - InviteClientContext.prototype.onReject = function (inviteResponse) { - this.disposeEarlyMedia(); - var response = inviteResponse.message; - var statusCode = response.statusCode; - var cause = Utils_1.Utils.sipErrorCause(statusCode || 0); - this.rejected(response, cause); - this.failed(response, cause); - this.terminated(response, cause); - }; - /** - * Handle final response to initial INVITE. - * @param inviteResponse 100 response. - */ - InviteClientContext.prototype.onTrying = function (inviteResponse) { - this.received100 = true; - this.emit("progress", inviteResponse.message); - }; - return InviteClientContext; -}(Session)); -exports.InviteClientContext = InviteClientContext; diff --git a/lib/Session/DTMF.d.ts b/lib/Session/DTMF.d.ts deleted file mode 100644 index a996d6ed8..000000000 --- a/lib/Session/DTMF.d.ts +++ /dev/null @@ -1,26 +0,0 @@ -/// -import { EventEmitter } from "events"; -import { IncomingRequest, IncomingResponseMessage } from "../core"; -import { TypeStrings } from "../Enums"; -import { Session } from "../Session"; -/** - * @class DTMF - * @param {SIP.Session} session - */ -export declare class DTMF extends EventEmitter { - type: TypeStrings; - tone: string; - duration: number; - interToneGap: number; - private C; - private logger; - private owner; - constructor(session: Session, tone: string | number, options?: any); - send(options?: any): void; - init_incoming(request: IncomingRequest): void; - receiveResponse(response: IncomingResponseMessage): void; - onRequestTimeout(): void; - onTransportError(): void; - onDialogError(response: IncomingResponseMessage): void; -} -//# sourceMappingURL=DTMF.d.ts.map \ No newline at end of file diff --git a/lib/Session/DTMF.d.ts.map b/lib/Session/DTMF.d.ts.map deleted file mode 100644 index 859a0f462..000000000 --- a/lib/Session/DTMF.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"DTMF.d.ts","sourceRoot":"","sources":["../../src/Session/DTMF.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAGtC,OAAO,EAAE,eAAe,EAAE,uBAAuB,EAAU,MAAM,SAAS,CAAC;AAC3E,OAAO,EAAiB,WAAW,EAAE,MAAM,UAAU,CAAC;AAEtD,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAGrC;;;GAGG;AACH,qBAAa,IAAK,SAAQ,YAAY;IAC7B,IAAI,EAAE,WAAW,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,YAAY,EAAE,MAAM,CAAC;IAC5B,OAAO,CAAC,CAAC,CAMP;IACF,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,KAAK,CAAU;gBAEX,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,OAAO,GAAE,GAAQ;IA8D/D,IAAI,CAAC,OAAO,GAAE,GAAQ,GAAG,IAAI;IAyB7B,aAAa,CAAC,OAAO,EAAE,eAAe,GAAG,IAAI;IAU7C,eAAe,CAAC,QAAQ,EAAE,uBAAuB,GAAG,IAAI;IAsBxD,gBAAgB,IAAI,IAAI;IAKxB,gBAAgB,IAAI,IAAI;IAKxB,aAAa,CAAC,QAAQ,EAAE,uBAAuB,GAAG,IAAI;CAI9D"} \ No newline at end of file diff --git a/lib/Session/DTMF.js b/lib/Session/DTMF.js deleted file mode 100644 index 41ca9b646..000000000 --- a/lib/Session/DTMF.js +++ /dev/null @@ -1,152 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var events_1 = require("events"); -var Constants_1 = require("../Constants"); -var Enums_1 = require("../Enums"); -var Exceptions_1 = require("../Exceptions"); -var Utils_1 = require("../Utils"); -/** - * @class DTMF - * @param {SIP.Session} session - */ -var DTMF = /** @class */ (function (_super) { - tslib_1.__extends(DTMF, _super); - function DTMF(session, tone, options) { - if (options === void 0) { options = {}; } - var _this = _super.call(this) || this; - _this.C = { - MIN_DURATION: 70, - MAX_DURATION: 6000, - DEFAULT_DURATION: 100, - MIN_INTER_TONE_GAP: 50, - DEFAULT_INTER_TONE_GAP: 500 - }; - _this.type = Enums_1.TypeStrings.DTMF; - if (tone === undefined) { - throw new TypeError("Not enough arguments"); - } - _this.logger = session.ua.getLogger("sip.invitecontext.dtmf", session.id); - _this.owner = session; - // Check tone type - if (typeof tone === "string") { - tone = tone.toUpperCase(); - } - else if (typeof tone === "number") { - tone = tone.toString(); - } - else { - throw new TypeError("Invalid tone: " + tone); - } - // Check tone value - if (!tone.match(/^[0-9A-D#*]$/)) { - throw new TypeError("Invalid tone: " + tone); - } - else { - _this.tone = tone; - } - var duration = options.duration; - var interToneGap = options.interToneGap; - // Check duration - if (duration && !Utils_1.Utils.isDecimal(duration)) { - throw new TypeError("Invalid tone duration: " + duration); - } - else if (!duration) { - duration = _this.C.DEFAULT_DURATION; - } - else if (duration < _this.C.MIN_DURATION) { - _this.logger.warn("'duration' value is lower than the minimum allowed, setting it to " + - _this.C.MIN_DURATION + " milliseconds"); - duration = _this.C.MIN_DURATION; - } - else if (duration > _this.C.MAX_DURATION) { - _this.logger.warn("'duration' value is greater than the maximum allowed, setting it to " + - _this.C.MAX_DURATION + " milliseconds"); - duration = _this.C.MAX_DURATION; - } - else { - duration = Math.abs(duration); - } - _this.duration = duration; - // Check interToneGap - if (interToneGap && !Utils_1.Utils.isDecimal(interToneGap)) { - throw new TypeError("Invalid interToneGap: " + interToneGap); - } - else if (!interToneGap) { - interToneGap = _this.C.DEFAULT_INTER_TONE_GAP; - } - else if (interToneGap < _this.C.MIN_INTER_TONE_GAP) { - _this.logger.warn("'interToneGap' value is lower than the minimum allowed, setting it to " + - _this.C.MIN_INTER_TONE_GAP + " milliseconds"); - interToneGap = _this.C.MIN_INTER_TONE_GAP; - } - else { - interToneGap = Math.abs(interToneGap); - } - _this.interToneGap = interToneGap; - return _this; - } - DTMF.prototype.send = function (options) { - if (options === void 0) { options = {}; } - // Check RTCSession Status - if (this.owner.status !== Enums_1.SessionStatus.STATUS_CONFIRMED && - this.owner.status !== Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK) { - throw new Exceptions_1.Exceptions.InvalidStateError(this.owner.status); - } - // Get DTMF options - var extraHeaders = options.extraHeaders ? options.extraHeaders.slice() : []; - var body = { - contentType: "application/dtmf-relay", - body: "Signal= " + this.tone + "\r\nDuration= " + this.duration - }; - if (this.owner.session) { - var request = this.owner.session.info(undefined, { - extraHeaders: extraHeaders, - body: Utils_1.Utils.fromBodyObj(body) - }); - this.owner.emit("dtmf", request.message, this); - return; - } - }; - DTMF.prototype.init_incoming = function (request) { - request.accept(); - if (!this.tone || !this.duration) { - this.logger.warn("invalid INFO DTMF received, discarded"); - } - else { - this.owner.emit("dtmf", request.message, this); - } - }; - DTMF.prototype.receiveResponse = function (response) { - var statusCode = response && response.statusCode ? response.statusCode : 0; - switch (true) { - case /^1[0-9]{2}$/.test(statusCode.toString()): - // Ignore provisional responses. - break; - case /^2[0-9]{2}$/.test(statusCode.toString()): - this.emit("succeeded", { - originator: "remote", - response: response - }); - break; - default: - var cause = Utils_1.Utils.sipErrorCause(statusCode); - this.emit("failed", response, cause); - break; - } - }; - DTMF.prototype.onRequestTimeout = function () { - this.emit("failed", undefined, Constants_1.C.causes.REQUEST_TIMEOUT); - this.owner.onRequestTimeout(); - }; - DTMF.prototype.onTransportError = function () { - this.emit("failed", undefined, Constants_1.C.causes.CONNECTION_ERROR); - this.owner.onTransportError(); - }; - DTMF.prototype.onDialogError = function (response) { - this.emit("failed", response, Constants_1.C.causes.DIALOG_ERROR); - this.owner.onDialogError(response); - }; - return DTMF; -}(events_1.EventEmitter)); -exports.DTMF = DTMF; diff --git a/lib/Subscription.d.ts b/lib/Subscription.d.ts deleted file mode 100644 index 9f9616f31..000000000 --- a/lib/Subscription.d.ts +++ /dev/null @@ -1,128 +0,0 @@ -/// -import { EventEmitter } from "events"; -import { ClientContext } from "./ClientContext"; -import { IncomingNotifyRequest, IncomingRequestMessage, IncomingResponse, IncomingResponseMessage, Logger, NameAddrHeader, OutgoingRequestMessage, OutgoingSubscribeRequest, URI } from "./core"; -import { TypeStrings } from "./Enums"; -import { BodyObj } from "./session-description-handler"; -import { UA } from "./UA"; -interface SubscriptionOptions { - expires?: number; - extraHeaders?: Array; - body?: string; - contentType?: string; -} -/** - * While this class is named `Subscription`, it is closer to - * an implementation of a "subscriber" as defined in RFC 6665 - * "SIP-Specific Event Notifications". - * https://tools.ietf.org/html/rfc6665 - * @class Class creating a SIP Subscriber. - */ -export declare class Subscription extends EventEmitter implements ClientContext { - type: TypeStrings; - ua: UA; - logger: Logger; - data: any; - method: string; - body: BodyObj | undefined; - localIdentity: NameAddrHeader; - remoteIdentity: NameAddrHeader; - request: OutgoingRequestMessage; - onRequestTimeout: () => void; - onTransportError: () => void; - receiveResponse: () => void; - send: () => this; - private id; - private context; - private disposed; - private event; - private expires; - private extraHeaders; - private retryAfterTimer; - private subscription; - private uri; - /** - * Constructor. - * @param ua User agent. - * @param target Subscription target. - * @param event Subscription event. - * @param options Options bucket. - */ - constructor(ua: UA, target: string | URI, event: string, options?: SubscriptionOptions); - /** - * Destructor. - */ - dispose(): void; - /** - * Registration of event listeners. - * - * The following events are emitted... - * - "accepted" A 200-class final response to a SUBSCRIBE request was received. - * - "failed" A non-200-class final response to a SUBSCRIBE request was received. - * - "rejected" Emitted immediately after a "failed" event (yes, it's redundant). - * - "notify" A NOTIFY request was received. - * - "terminated" The subscription is moving to or has moved to a terminated state. - * - * More than one SUBSCRIBE request may be sent, so "accepted", "failed" and "rejected" - * may be emitted multiple times. However these event will NOT be emitted for SUBSCRIBE - * requests with expires of zero (unsubscribe requests). - * - * Note that a "terminated" event does NOT indicate the subscription is in the "terminated" - * state as described in RFC 6665. Instead, a "terminated" event indicates that this class - * is no longer usable and/or is in the process of becoming no longer usable. - * - * The order the events are emitted in is not deterministic. Some examples... - * - "accepted" may occur multiple times - * - "accepted" may follow "notify" and "notify" may follow "accepted" - * - "terminated" may follow "accepted" and "accepted" may follow "terminated" - * - "terminated" may follow "notify" and "notify" may follow "terminated" - * - * Hint: Experience suggests one workable approach to utilizing these events - * is to make use of "notify" and "terminated" only. That is, call `subscribe()` - * and if a "notify" occurs then you have a subscription. If a "terminated" - * event occurs then either a new subscription failed to be established or an - * established subscription has terminated or is in the process of terminating. - * Note that "notify" events may follow a "terminated" event, but experience - * suggests it is reasonable to discontinue usage of this class after receipt - * of a "terminated" event. The other events are informational, but as they do not - * arrive in a deterministic manner it is difficult to make use of them otherwise. - * - * @param name Event name. - * @param callback Callback. - */ - on(name: "accepted" | "failed" | "rejected", callback: (message: IncomingResponseMessage, cause: string) => void): this; - on(name: "notify", callback: (notification: { - request: IncomingRequestMessage; - }) => void): this; - on(name: "terminated", callback: () => void): this; - emit(event: "accepted" | "failed" | "rejected", message: IncomingResponseMessage, cause: string): boolean; - emit(event: "notify", notification: { - request: IncomingRequestMessage; - }): boolean; - emit(event: "terminated"): boolean; - /** - * Gracefully terminate. - */ - close(): void; - /** - * Send a re-SUBSCRIBE request if there is an "active" subscription. - */ - refresh(): void; - /** - * Send an initial SUBSCRIBE request if no subscription. - * Send a re-SUBSCRIBE request if there is an "active" subscription. - */ - subscribe(): this; - /** - * Send a re-SUBSCRIBE request if there is a "pending" or "active" subscription. - */ - unsubscribe(): void; - protected onAccepted(response: IncomingResponse): void; - protected onFailed(response?: IncomingResponse): void; - protected onNotify(request: IncomingNotifyRequest): void; - protected onRefresh(request: OutgoingSubscribeRequest): void; - protected onTerminated(): void; - private initContext; -} -export {}; -//# sourceMappingURL=Subscription.d.ts.map \ No newline at end of file diff --git a/lib/Subscription.d.ts.map b/lib/Subscription.d.ts.map deleted file mode 100644 index e3ab3af80..000000000 --- a/lib/Subscription.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"Subscription.d.ts","sourceRoot":"","sources":["../src/Subscription.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAEtC,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAEhD,OAAO,EACL,qBAAqB,EACrB,sBAAsB,EAEtB,gBAAgB,EAChB,uBAAuB,EACvB,MAAM,EACN,cAAc,EACd,sBAAsB,EACtB,wBAAwB,EAIxB,GAAG,EAEJ,MAAM,QAAQ,CAAC;AAEhB,OAAO,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AACtC,OAAO,EAAE,OAAO,EAAE,MAAM,+BAA+B,CAAC;AACxD,OAAO,EAAE,EAAE,EAAE,MAAM,MAAM,CAAC;AAG1B,UAAU,mBAAmB;IAC3B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,YAAY,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAC7B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED;;;;;;GAMG;AACH,qBAAa,YAAa,SAAQ,YAAa,YAAW,aAAa;IAG9D,IAAI,EAAE,WAAW,CAAC;IAClB,EAAE,EAAE,EAAE,CAAC;IACP,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,GAAG,CAAM;IACf,MAAM,EAAE,MAAM,CAAe;IAC7B,IAAI,EAAE,OAAO,GAAG,SAAS,CAAa;IACtC,aAAa,EAAE,cAAc,CAAC;IAC9B,cAAc,EAAE,cAAc,CAAC;IAC/B,OAAO,EAAE,sBAAsB,CAAC;IAChC,gBAAgB,EAAG,MAAM,IAAI,CAAC;IAC9B,gBAAgB,EAAG,MAAM,IAAI,CAAC;IAC9B,eAAe,EAAG,MAAM,IAAI,CAAC;IAC7B,IAAI,EAAG,MAAM,IAAI,CAAC;IAGzB,OAAO,CAAC,EAAE,CAAS;IACnB,OAAO,CAAC,OAAO,CAAyB;IACxC,OAAO,CAAC,QAAQ,CAAU;IAC1B,OAAO,CAAC,KAAK,CAAS;IACtB,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,YAAY,CAAgB;IACpC,OAAO,CAAC,eAAe,CAAkB;IACzC,OAAO,CAAC,YAAY,CAA+B;IACnD,OAAO,CAAC,GAAG,CAAM;IAEjB;;;;;;OAMG;gBACS,EAAE,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,GAAG,GAAG,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,GAAE,mBAAwB;IA0D1F;;OAEG;IACI,OAAO,IAAI,IAAI;IAetB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAoCG;IACI,EAAE,CACP,IAAI,EAAE,UAAU,GAAG,QAAQ,GAAG,UAAU,EACxC,QAAQ,EAAE,CAAC,OAAO,EAAE,uBAAuB,EAAE,KAAK,EAAE,MAAM,KAAK,IAAI,GAClE,IAAI;IACA,EAAE,CAAC,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,CAAC,YAAY,EAAE;QAAE,OAAO,EAAE,sBAAsB,CAAA;KAAE,KAAK,IAAI,GAAG,IAAI;IAC/F,EAAE,CAAC,IAAI,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,IAAI,GAAG,IAAI;IAKlD,IAAI,CACT,KAAK,EAAE,UAAU,GAAG,QAAQ,GAAG,UAAU,EACzC,OAAO,EAAE,uBAAuB,EAAE,KAAK,EAAE,MAAM,GAC9C,OAAO;IACH,IAAI,CAAC,KAAK,EAAE,QAAQ,EAAE,YAAY,EAAE;QAAE,OAAO,EAAE,sBAAsB,CAAA;KAAE,GAAG,OAAO;IACjF,IAAI,CAAC,KAAK,EAAE,YAAY,GAAG,OAAO;IAKzC;;OAEG;IACI,KAAK,IAAI,IAAI;IA2BpB;;OAEG;IACI,OAAO,IAAI,IAAI;IAyBtB;;;OAGG;IACI,SAAS,IAAI,IAAI;IAmCxB;;OAEG;IACI,WAAW,IAAI,IAAI;IA6B1B,SAAS,CAAC,UAAU,CAAC,QAAQ,EAAE,gBAAgB,GAAG,IAAI;IAMtD,SAAS,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,gBAAgB,GAAG,IAAI;IAUrD,SAAS,CAAC,QAAQ,CAAC,OAAO,EAAE,qBAAqB,GAAG,IAAI;IA0DxD,SAAS,CAAC,SAAS,CAAC,OAAO,EAAE,wBAAwB,GAAG,IAAI;IAM5D,SAAS,CAAC,YAAY,IAAI,IAAI;IAI9B,OAAO,CAAC,WAAW;CAWpB"} \ No newline at end of file diff --git a/lib/Subscription.js b/lib/Subscription.js deleted file mode 100644 index 25b14ca17..000000000 --- a/lib/Subscription.js +++ /dev/null @@ -1,433 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var events_1 = require("events"); -var Constants_1 = require("./Constants"); -var core_1 = require("./core"); -var allowed_methods_1 = require("./core/user-agent-core/allowed-methods"); -var Enums_1 = require("./Enums"); -var Utils_1 = require("./Utils"); -/** - * While this class is named `Subscription`, it is closer to - * an implementation of a "subscriber" as defined in RFC 6665 - * "SIP-Specific Event Notifications". - * https://tools.ietf.org/html/rfc6665 - * @class Class creating a SIP Subscriber. - */ -var Subscription = /** @class */ (function (_super) { - tslib_1.__extends(Subscription, _super); - /** - * Constructor. - * @param ua User agent. - * @param target Subscription target. - * @param event Subscription event. - * @param options Options bucket. - */ - function Subscription(ua, target, event, options) { - if (options === void 0) { options = {}; } - var _this = _super.call(this) || this; - _this.data = {}; - _this.method = Constants_1.C.SUBSCRIBE; - _this.body = undefined; - // ClientContext interface - _this.type = Enums_1.TypeStrings.Subscription; - _this.ua = ua; - _this.logger = ua.getLogger("sip.subscription"); - if (options.body) { - _this.body = { - body: options.body, - contentType: options.contentType ? options.contentType : "application/sdp" - }; - } - // Target URI - var uri = ua.normalizeTarget(target); - if (!uri) { - throw new TypeError("Invalid target: " + target); - } - _this.uri = uri; - // Subscription event - _this.event = event; - // Subscription expires - if (options.expires === undefined) { - _this.expires = 3600; - } - else if (typeof options.expires !== "number") { // pre-typescript type guard - ua.logger.warn("Option \"expires\" must be a number. Using default of 3600."); - _this.expires = 3600; - } - else { - _this.expires = options.expires; - } - // Subscription extra headers - _this.extraHeaders = (options.extraHeaders || []).slice(); - // Subscription context. - _this.context = _this.initContext(); - _this.disposed = false; - // ClientContext interface - _this.request = _this.context.message; - if (!_this.request.from) { - throw new Error("From undefined."); - } - if (!_this.request.to) { - throw new Error("From undefined."); - } - _this.localIdentity = _this.request.from; - _this.remoteIdentity = _this.request.to; - // Add to UA's collection - _this.id = _this.request.callId + _this.request.from.parameters.tag + _this.event; - _this.ua.subscriptions[_this.id] = _this; - return _this; - } - /** - * Destructor. - */ - Subscription.prototype.dispose = function () { - if (this.disposed) { - return; - } - if (this.retryAfterTimer) { - clearTimeout(this.retryAfterTimer); - this.retryAfterTimer = undefined; - } - this.context.dispose(); - this.disposed = true; - // Remove from UA's collection - delete this.ua.subscriptions[this.id]; - }; - Subscription.prototype.on = function (name, callback) { - return _super.prototype.on.call(this, name, callback); - }; - Subscription.prototype.emit = function (event) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - return _super.prototype.emit.apply(this, [event].concat(args)); - }; - /** - * Gracefully terminate. - */ - Subscription.prototype.close = function () { - if (this.disposed) { - return; - } - this.dispose(); - switch (this.context.state) { - case core_1.SubscriptionState.Initial: - this.onTerminated(); - break; - case core_1.SubscriptionState.NotifyWait: - this.onTerminated(); - break; - case core_1.SubscriptionState.Pending: - this.unsubscribe(); - break; - case core_1.SubscriptionState.Active: - this.unsubscribe(); - break; - case core_1.SubscriptionState.Terminated: - this.onTerminated(); - break; - default: - break; - } - }; - /** - * Send a re-SUBSCRIBE request if there is an "active" subscription. - */ - Subscription.prototype.refresh = function () { - var _this = this; - switch (this.context.state) { - case core_1.SubscriptionState.Initial: - break; - case core_1.SubscriptionState.NotifyWait: - break; - case core_1.SubscriptionState.Pending: - break; - case core_1.SubscriptionState.Active: - if (this.subscription) { - var request = this.subscription.refresh(); - request.delegate = { - onAccept: (function (response) { return _this.onAccepted(response); }), - onRedirect: (function (response) { return _this.onFailed(response); }), - onReject: (function (response) { return _this.onFailed(response); }), - }; - } - break; - case core_1.SubscriptionState.Terminated: - break; - default: - break; - } - }; - /** - * Send an initial SUBSCRIBE request if no subscription. - * Send a re-SUBSCRIBE request if there is an "active" subscription. - */ - Subscription.prototype.subscribe = function () { - var _this = this; - switch (this.context.state) { - case core_1.SubscriptionState.Initial: - this.context.subscribe().then(function (result) { - if (result.success) { - if (result.success.subscription) { - _this.subscription = result.success.subscription; - _this.subscription.delegate = { - onNotify: function (request) { return _this.onNotify(request); }, - onRefresh: function (request) { return _this.onRefresh(request); }, - onTerminated: function () { return _this.close(); } - }; - } - _this.onNotify(result.success.request); - } - else if (result.failure) { - _this.onFailed(result.failure.response); - } - }); - break; - case core_1.SubscriptionState.NotifyWait: - break; - case core_1.SubscriptionState.Pending: - break; - case core_1.SubscriptionState.Active: - this.refresh(); - break; - case core_1.SubscriptionState.Terminated: - break; - default: - break; - } - return this; - }; - /** - * Send a re-SUBSCRIBE request if there is a "pending" or "active" subscription. - */ - Subscription.prototype.unsubscribe = function () { - this.dispose(); - switch (this.context.state) { - case core_1.SubscriptionState.Initial: - break; - case core_1.SubscriptionState.NotifyWait: - break; - case core_1.SubscriptionState.Pending: - if (this.subscription) { - this.subscription.unsubscribe(); - // responses intentionally ignored - } - break; - case core_1.SubscriptionState.Active: - if (this.subscription) { - this.subscription.unsubscribe(); - // responses intentionally ignored - } - break; - case core_1.SubscriptionState.Terminated: - break; - default: - break; - } - this.onTerminated(); - }; - Subscription.prototype.onAccepted = function (response) { - var statusCode = response.message.statusCode ? response.message.statusCode : 0; - var cause = Utils_1.Utils.getReasonPhrase(statusCode); - this.emit("accepted", response.message, cause); - }; - Subscription.prototype.onFailed = function (response) { - this.close(); - if (response) { - var statusCode = response.message.statusCode ? response.message.statusCode : 0; - var cause = Utils_1.Utils.getReasonPhrase(statusCode); - this.emit("failed", response.message, cause); - this.emit("rejected", response.message, cause); - } - }; - Subscription.prototype.onNotify = function (request) { - var _this = this; - request.accept(); // Send 200 response. - this.emit("notify", { request: request.message }); - // If we've set state to done, no further processing should take place - // and we are only interested in cleaning up after the appropriate NOTIFY. - if (this.disposed) { - return; - } - // If the "Subscription-State" value is "terminated", the subscriber - // MUST consider the subscription terminated. The "expires" parameter - // has no semantics for "terminated" -- notifiers SHOULD NOT include an - // "expires" parameter on a "Subscription-State" header field with a - // value of "terminated", and subscribers MUST ignore any such - // parameter, if present. If a reason code is present, the client - // should behave as described below. If no reason code or an unknown - // reason code is present, the client MAY attempt to re-subscribe at any - // time (unless a "retry-after" parameter is present, in which case the - // client SHOULD NOT attempt re-subscription until after the number of - // seconds specified by the "retry-after" parameter). The reason codes - // defined by this document are: - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - var subscriptionState = request.message.parseHeader("Subscription-State"); - if (subscriptionState && subscriptionState.state) { - switch (subscriptionState.state) { - case "terminated": - if (subscriptionState.reason) { - this.logger.log("Terminated subscription with reason " + subscriptionState.reason); - switch (subscriptionState.reason) { - case "deactivated": - case "timeout": - this.initContext(); - this.subscribe(); - return; - case "probation": - case "giveup": - this.initContext(); - if (subscriptionState.params && subscriptionState.params["retry-after"]) { - this.retryAfterTimer = setTimeout(function () { return _this.subscribe(); }, subscriptionState.params["retry-after"]); - } - else { - this.subscribe(); - } - return; - case "rejected": - case "noresource": - case "invariant": - break; - } - } - this.close(); - break; - default: - break; - } - } - }; - Subscription.prototype.onRefresh = function (request) { - var _this = this; - request.delegate = { - onAccept: function (response) { return _this.onAccepted(response); } - }; - }; - Subscription.prototype.onTerminated = function () { - this.emit("terminated"); - }; - Subscription.prototype.initContext = function () { - var _this = this; - var options = { - extraHeaders: this.extraHeaders, - body: this.body ? Utils_1.Utils.fromBodyObj(this.body) : undefined - }; - this.context = new SubscribeClientContext(this.ua.userAgentCore, this.uri, this.event, this.expires, options); - this.context.delegate = { - onAccept: (function (response) { return _this.onAccepted(response); }) - }; - return this.context; - }; - return Subscription; -}(events_1.EventEmitter)); -exports.Subscription = Subscription; -// tslint:disable-next-line:max-classes-per-file -var SubscribeClientContext = /** @class */ (function () { - function SubscribeClientContext(core, target, event, expires, options, delegate) { - this.core = core; - this.target = target; - this.event = event; - this.expires = expires; - this.subscribed = false; - this.logger = core.loggerFactory.getLogger("sip.subscription"); - this.delegate = delegate; - var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); - var extraHeaders = (options && options.extraHeaders || []).slice(); - extraHeaders.push(allowHeader); - extraHeaders.push("Event: " + this.event); - extraHeaders.push("Expires: " + this.expires); - extraHeaders.push("Contact: " + this.core.configuration.contact.toString()); - var body = options && options.body; - this.message = core.makeOutgoingRequestMessage(Constants_1.C.SUBSCRIBE, this.target, this.core.configuration.aor, this.target, {}, extraHeaders, body); - } - /** Destructor. */ - SubscribeClientContext.prototype.dispose = function () { - if (this.subscription) { - this.subscription.dispose(); - } - if (this.request) { - this.request.waitNotifyStop(); - this.request.dispose(); - } - }; - Object.defineProperty(SubscribeClientContext.prototype, "state", { - /** Subscription state. */ - get: function () { - if (this.subscription) { - return this.subscription.subscriptionState; - } - else if (this.subscribed) { - return core_1.SubscriptionState.NotifyWait; - } - else { - return core_1.SubscriptionState.Initial; - } - }, - enumerable: true, - configurable: true - }); - /** - * Establish subscription. - * @param options Options bucket. - */ - SubscribeClientContext.prototype.subscribe = function () { - var _this = this; - if (this.subscribed) { - return Promise.reject(new Error("Not in initial state. Did you call subscribe more than once?")); - } - this.subscribed = true; - return new Promise(function (resolve, reject) { - if (!_this.message) { - throw new Error("Message undefined."); - } - _this.request = _this.core.subscribe(_this.message, { - // This SUBSCRIBE request will be confirmed with a final response. - // 200-class responses indicate that the subscription has been accepted - // and that a NOTIFY request will be sent immediately. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - onAccept: function (response) { - if (_this.delegate && _this.delegate.onAccept) { - _this.delegate.onAccept(response); - } - }, - // Due to the potential for out-of-order messages, packet loss, and - // forking, the subscriber MUST be prepared to receive NOTIFY requests - // before the SUBSCRIBE transaction has completed. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.4 - onNotify: function (requestWithSubscription) { - _this.subscription = requestWithSubscription.subscription; - if (_this.subscription) { - _this.subscription.autoRefresh = true; - } - resolve({ success: requestWithSubscription }); - }, - // If this Timer N expires prior to the receipt of a NOTIFY request, - // the subscriber considers the subscription failed, and cleans up - // any state associated with the subscription attempt. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.4 - onNotifyTimeout: function () { - resolve({ failure: {} }); - }, - // This SUBSCRIBE request will be confirmed with a final response. - // Non-200-class final responses indicate that no subscription or new - // dialog usage has been created, and no subsequent NOTIFY request will - // be sent. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - onRedirect: function (response) { - resolve({ failure: { response: response } }); - }, - // This SUBSCRIBE request will be confirmed with a final response. - // Non-200-class final responses indicate that no subscription or new - // dialog usage has been created, and no subsequent NOTIFY request will - // be sent. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - onReject: function (response) { - resolve({ failure: { response: response } }); - } - }); - }); - }; - return SubscribeClientContext; -}()); diff --git a/lib/UA.d.ts b/lib/UA.d.ts deleted file mode 100644 index 2b0c87f4b..000000000 --- a/lib/UA.d.ts +++ /dev/null @@ -1,230 +0,0 @@ -/// -import { EventEmitter } from "events"; -import { ClientContext } from "./ClientContext"; -import { C as SIPConstants } from "./Constants"; -import { DigestAuthentication, IncomingRequestMessage, IncomingSubscribeRequest, Logger, LoggerFactory, Transport, URI, UserAgentCore, UserAgentCoreConfiguration } from "./core"; -import { TypeStrings, UAStatus } from "./Enums"; -import { PublishContext } from "./PublishContext"; -import { ReferServerContext } from "./ReferContext"; -import { InviteClientContext, InviteServerContext } from "./Session"; -import { SessionDescriptionHandlerModifiers } from "./session-description-handler"; -import { SessionDescriptionHandlerFactory, SessionDescriptionHandlerFactoryOptions } from "./session-description-handler-factory"; -import { Subscription } from "./Subscription"; -export declare namespace UA { - interface Options { - uri?: string | URI; - allowLegacyNotifications?: boolean; - allowOutOfDialogRefers?: boolean; - authenticationFactory?: (ua: UA) => DigestAuthentication | any; - authorizationUser?: string; - autostart?: boolean; - autostop?: boolean; - displayName?: string; - dtmfType?: DtmfType; - experimentalFeatures?: boolean; - extraSupported?: Array; - forceRport?: boolean; - hackIpInContact?: boolean; - hackAllowUnregisteredOptionTags?: boolean; - hackViaTcp?: boolean; - hackWssInTransport?: boolean; - hostportParams?: any; - log?: { - builtinEnabled: boolean; - level?: string | number; - connector?: (level: string, category: string, label: string | undefined, content: any) => void; - }; - noAnswerTimeout?: number; - password?: string; - register?: boolean; - registerOptions?: RegisterOptions; - rel100?: SIPConstants.supported; - replaces?: SIPConstants.supported; - sessionDescriptionHandlerFactory?: SessionDescriptionHandlerFactory; - sessionDescriptionHandlerFactoryOptions?: SessionDescriptionHandlerFactoryOptions; - sipjsId?: string; - transportConstructor?: new (logger: any, options: any) => Transport; - transportOptions?: any; - userAgentString?: string; - usePreloadedRoute?: boolean; - viaHost?: string; - } - interface RegisterOptions { - expires?: number; - extraContactHeaderParams?: Array; - instanceId?: string; - params?: any; - regId?: number; - registrar?: string; - } -} -/** - * @class Class creating a SIP User Agent. - * @param {function returning SIP.sessionDescriptionHandler} [configuration.sessionDescriptionHandlerFactory] - * A function will be invoked by each of the UA's Sessions to build the sessionDescriptionHandler for that Session. - * If no (or a falsy) value is provided, each Session will use a default (WebRTC) sessionDescriptionHandler. - */ -export declare class UA extends EventEmitter { - static readonly C: { - STATUS_INIT: number; - STATUS_STARTING: number; - STATUS_READY: number; - STATUS_USER_CLOSED: number; - STATUS_NOT_READY: number; - CONFIGURATION_ERROR: number; - NETWORK_ERROR: number; - ALLOWED_METHODS: string[]; - ACCEPTED_BODY_TYPES: string[]; - MAX_FORWARDS: number; - TAG_LENGTH: number; - }; - type: TypeStrings; - configuration: UA.Options; - applicants: { - [id: string]: InviteClientContext; - }; - publishers: { - [id: string]: PublishContext; - }; - contact: { - pubGruu: URI | undefined; - tempGruu: URI | undefined; - uri: URI; - toString: (options?: any) => string; - }; - status: UAStatus; - transport: Transport; - sessions: { - [id: string]: InviteClientContext | InviteServerContext; - }; - subscriptions: { - [id: string]: Subscription; - }; - data: any; - logger: Logger; - userAgentCore: UserAgentCore; - private log; - private error; - private registerContext; - /** Unload listener. */ - private unloadListener; - constructor(configuration?: UA.Options); - register(options?: any): this; - /** - * Unregister. - * - * @param {Boolean} [all] unregister all user bindings. - * - */ - unregister(options?: any): this; - isRegistered(): boolean; - /** - * Make an outgoing call. - * - * @param {String} target - * @param {Object} views - * @param {Object} [options.media] gets passed to SIP.sessionDescriptionHandler.getDescription as mediaHint - * - * @throws {TypeError} - * - */ - invite(target: string | URI, options?: InviteClientContext.Options, modifiers?: SessionDescriptionHandlerModifiers): InviteClientContext; - subscribe(target: string | URI, event: string, options: any): Subscription; - /** - * Send PUBLISH Event State Publication (RFC3903) - * - * @param {String} target - * @param {String} event - * @param {String} body - * @param {Object} [options] - * - * @throws {SIP.Exceptions.MethodParameterError} - */ - publish(target: string | URI, event: string, body: string, options: any): PublishContext; - /** - * Send a message. - * - * @param {String} target - * @param {String} body - * @param {Object} [options] - * - * @throws {TypeError} - */ - message(target: string | URI, body: string, options?: any): ClientContext; - request(method: string, target: string | URI, options?: any): ClientContext; - /** - * Gracefully close. - */ - stop(): this; - /** - * Connect to the WS server if status = STATUS_INIT. - * Resume UA after being closed. - * - */ - start(): this; - /** - * Normalize a string into a valid SIP request URI - * - * @param {String} target - * - * @returns {SIP.URI|undefined} - */ - normalizeTarget(target: string | URI): URI | undefined; - getLogger(category: string, label?: string): Logger; - getLoggerFactory(): LoggerFactory; - getSupportedResponseOptions(): Array; - /** - * Get the session to which the request belongs to, if any. - * @param {SIP.IncomingRequest} request. - * @returns {SIP.OutgoingSession|SIP.IncomingSession|undefined} - */ - findSession(request: IncomingRequestMessage): InviteClientContext | InviteServerContext | undefined; - on(name: "invite", callback: (session: InviteServerContext) => void): this; - on(name: "inviteSent", callback: (session: InviteClientContext) => void): this; - on(name: "outOfDialogReferRequested", callback: (context: ReferServerContext) => void): this; - on(name: "transportCreated", callback: (transport: Transport) => void): this; - on(name: "message", callback: (message: any) => void): this; - on(name: "notify", callback: (request: any) => void): this; - on(name: "subscribe", callback: (subscribe: IncomingSubscribeRequest) => void): this; - on(name: "registered", callback: (response?: any) => void): this; - on(name: "unregistered" | "registrationFailed", callback: (response?: any, cause?: any) => void): this; - private onTransportError; - /** - * Helper function. Sets transport listeners - */ - private setTransportListeners; - /** - * Transport connection event. - * @event - * @param {SIP.Transport} transport. - */ - private onTransportConnected; - /** - * Handle SIP message received from the transport. - * @param messageString The message. - */ - private onTransportReceiveMsg; - private checkAuthenticationFactory; - /** - * Configuration load. - * returns {void} - */ - private loadConfig; - /** - * Configuration checker. - * @return {Boolean} - */ - private getConfigurationCheck; -} -export declare namespace UA { - enum DtmfType { - RTP = "rtp", - INFO = "info" - } -} -/** - * Factory function to generate configuration give a UA. - * @param ua UA - */ -export declare function makeUserAgentCoreConfigurationFromUA(ua: UA): UserAgentCoreConfiguration; -//# sourceMappingURL=UA.d.ts.map \ No newline at end of file diff --git a/lib/UA.d.ts.map b/lib/UA.d.ts.map deleted file mode 100644 index 0dafb8ba6..000000000 --- a/lib/UA.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"UA.d.ts","sourceRoot":"","sources":["../src/UA.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAEtC,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,CAAC,IAAI,YAAY,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EACL,oBAAoB,EAMpB,sBAAsB,EAEtB,wBAAwB,EAExB,MAAM,EACN,aAAa,EACb,SAAS,EAET,GAAG,EACH,aAAa,EACb,0BAA0B,EAE3B,MAAM,QAAQ,CAAC;AAChB,OAAO,EAAiB,WAAW,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAG/D,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAGpD,OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AACrE,OAAO,EAEL,kCAAkC,EACnC,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,gCAAgC,EAChC,uCAAuC,EACxC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAS9C,yBAAiB,EAAE,CAAC;IAClB,UAAiB,OAAO;QACtB,GAAG,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC;QACnB,wBAAwB,CAAC,EAAE,OAAO,CAAC;QACnC,sBAAsB,CAAC,EAAE,OAAO,CAAC;QACjC,qBAAqB,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,KAAK,oBAAoB,GAAG,GAAG,CAAC;QAC/D,iBAAiB,CAAC,EAAE,MAAM,CAAC;QAC3B,SAAS,CAAC,EAAE,OAAO,CAAC;QACpB,QAAQ,CAAC,EAAE,OAAO,CAAC;QACnB,WAAW,CAAC,EAAE,MAAM,CAAC;QACrB,QAAQ,CAAC,EAAE,QAAQ,CAAC;QACpB,oBAAoB,CAAC,EAAE,OAAO,CAAC;QAC/B,cAAc,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;QAC/B,UAAU,CAAC,EAAE,OAAO,CAAC;QACrB,eAAe,CAAC,EAAE,OAAO,CAAC;QAC1B,+BAA+B,CAAC,EAAE,OAAO,CAAC;QAC1C,UAAU,CAAC,EAAE,OAAO,CAAC;QACrB,kBAAkB,CAAC,EAAE,OAAO,CAAC;QAC7B,cAAc,CAAC,EAAE,GAAG,CAAC;QACrB,GAAG,CAAC,EAAE;YACJ,cAAc,EAAE,OAAO,CAAC;YACxB,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;YACxB,SAAS,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,SAAS,EAAE,OAAO,EAAE,GAAG,KAAK,IAAI,CAAC;SAChG,CAAC;QACF,eAAe,CAAC,EAAE,MAAM,CAAC;QACzB,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,QAAQ,CAAC,EAAE,OAAO,CAAC;QACnB,eAAe,CAAC,EAAE,eAAe,CAAC;QAClC,MAAM,CAAC,EAAE,YAAY,CAAC,SAAS,CAAC;QAChC,QAAQ,CAAC,EAAE,YAAY,CAAC,SAAS,CAAC;QAClC,gCAAgC,CAAC,EAAE,gCAAgC,CAAC;QACpE,uCAAuC,CAAC,EAAE,uCAAuC,CAAC;QAClF,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,oBAAoB,CAAC,EAAE,KAAK,MAAM,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,KAAK,SAAS,CAAC;QACpE,gBAAgB,CAAC,EAAE,GAAG,CAAC;QACvB,eAAe,CAAC,EAAE,MAAM,CAAC;QACzB,iBAAiB,CAAC,EAAE,OAAO,CAAC;QAC5B,OAAO,CAAC,EAAE,MAAM,CAAC;KAClB;IAED,UAAiB,eAAe;QAC9B,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,wBAAwB,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;QACzC,UAAU,CAAC,EAAE,MAAM,CAAC;QACpB,MAAM,CAAC,EAAE,GAAG,CAAC;QACb,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,SAAS,CAAC,EAAE,MAAM,CAAC;KACpB;CACF;AAED;;;;;GAKG;AAEH,qBAAa,EAAG,SAAQ,YAAY;IAClC,gBAAuB,CAAC;;;;;;;;;;;;MA+BtB;IAEK,IAAI,EAAE,WAAW,CAAC;IAClB,aAAa,EAAE,EAAE,CAAC,OAAO,CAAC;IAC1B,UAAU,EAAE;QAAC,CAAC,EAAE,EAAE,MAAM,GAAG,mBAAmB,CAAA;KAAC,CAAC;IAChD,UAAU,EAAE;QAAC,CAAC,EAAE,EAAE,MAAM,GAAG,cAAc,CAAA;KAAC,CAAC;IAC3C,OAAO,EACZ;QACE,OAAO,EAAE,GAAG,GAAG,SAAS,CAAC;QACzB,QAAQ,EAAE,GAAG,GAAG,SAAS,CAAC;QAC1B,GAAG,EAAE,GAAG,CAAC;QACT,QAAQ,EAAE,CAAC,OAAO,CAAC,EAAE,GAAG,KAAK,MAAM,CAAA;KACpC,CAAC;IACG,MAAM,EAAE,QAAQ,CAAC;IACjB,SAAS,EAAE,SAAS,CAAC;IACrB,QAAQ,EAAE;QAAC,CAAC,EAAE,EAAE,MAAM,GAAG,mBAAmB,GAAG,mBAAmB,CAAA;KAAC,CAAC;IACpE,aAAa,EAAE;QAAC,CAAC,EAAE,EAAE,MAAM,GAAG,YAAY,CAAA;KAAC,CAAC;IAC5C,IAAI,EAAE,GAAG,CAAC;IACV,MAAM,EAAE,MAAM,CAAC;IAEf,aAAa,EAAE,aAAa,CAAC;IAEpC,OAAO,CAAC,GAAG,CAAgB;IAC3B,OAAO,CAAC,KAAK,CAAqB;IAClC,OAAO,CAAC,eAAe,CAAkB;IAEzC,uBAAuB;IACvB,OAAO,CAAC,cAAc,CAA4B;gBAEtC,aAAa,CAAC,EAAE,EAAE,CAAC,OAAO;IAsO/B,QAAQ,CAAC,OAAO,GAAE,GAAQ,GAAG,IAAI;IASxC;;;;;OAKG;IACI,UAAU,CAAC,OAAO,CAAC,EAAE,GAAG,GAAG,IAAI;IAU/B,YAAY,IAAI,OAAO;IAI9B;;;;;;;;;OASG;IACI,MAAM,CACX,MAAM,EAAE,MAAM,GAAG,GAAG,EACpB,OAAO,CAAC,EAAE,mBAAmB,CAAC,OAAO,EACrC,SAAS,CAAC,EAAE,kCAAkC,GAC7C,mBAAmB;IAYf,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,GAAG,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,GAAG,YAAY;IAMjF;;;;;;;;;OASG;IACI,OAAO,CAAC,MAAM,EAAE,MAAM,GAAG,GAAG,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,GAAG,cAAc;IAS/F;;;;;;;;OAQG;IACI,OAAO,CAAC,MAAM,EAAE,MAAM,GAAG,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,GAAE,GAAQ,GAAG,aAAa;IAY7E,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,GAAG,EAAE,OAAO,CAAC,EAAE,GAAG,GAAG,aAAa;IAOlF;;OAEG;IACI,IAAI,IAAI,IAAI;IAgEnB;;;;OAIG;IACI,KAAK,IAAI,IAAI;IAkCpB;;;;;;OAMG;IACI,eAAe,CAAC,MAAM,EAAE,MAAM,GAAG,GAAG,GAAG,GAAG,GAAG,SAAS;IAItD,SAAS,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM;IAInD,gBAAgB,IAAI,aAAa;IAIjC,2BAA2B,IAAI,KAAK,CAAC,MAAM,CAAC;IA6BnD;;;;OAIG;IACI,WAAW,CAAC,OAAO,EAAE,sBAAsB,GAAG,mBAAmB,GAAG,mBAAmB,GAAG,SAAS;IAMnG,EAAE,CAAC,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,CAAC,OAAO,EAAE,mBAAmB,KAAK,IAAI,GAAG,IAAI;IAC1E,EAAE,CAAC,IAAI,EAAE,YAAY,EAAE,QAAQ,EAAE,CAAC,OAAO,EAAE,mBAAmB,KAAK,IAAI,GAAG,IAAI;IAC9E,EAAE,CAAC,IAAI,EAAE,2BAA2B,EAAE,QAAQ,EAAE,CAAC,OAAO,EAAE,kBAAkB,KAAK,IAAI,GAAG,IAAI;IAC5F,EAAE,CAAC,IAAI,EAAE,kBAAkB,EAAE,QAAQ,EAAE,CAAC,SAAS,EAAE,SAAS,KAAK,IAAI,GAAG,IAAI;IAC5E,EAAE,CAAC,IAAI,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC,OAAO,EAAE,GAAG,KAAK,IAAI,GAAG,IAAI;IAC3D,EAAE,CAAC,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,CAAC,OAAO,EAAE,GAAG,KAAK,IAAI,GAAG,IAAI;IAC1D,EAAE,CAAC,IAAI,EAAE,WAAW,EAAE,QAAQ,EAAE,CAAC,SAAS,EAAE,wBAAwB,KAAK,IAAI,GAAG,IAAI;IACpF,EAAE,CAAC,IAAI,EAAE,YAAY,EAAE,QAAQ,EAAE,CAAC,QAAQ,CAAC,EAAE,GAAG,KAAK,IAAI,GAAG,IAAI;IAChE,EAAE,CAAC,IAAI,EAAE,cAAc,GAAG,oBAAoB,EAAE,QAAQ,EAAE,CAAC,QAAQ,CAAC,EAAE,GAAG,EAAE,KAAK,CAAC,EAAE,GAAG,KAAK,IAAI,GAAG,IAAI;IAO7G,OAAO,CAAC,gBAAgB;IAWxB;;OAEG;IACH,OAAO,CAAC,qBAAqB;IAM7B;;;;OAIG;IACH,OAAO,CAAC,oBAAoB;IAQ5B;;;OAGG;IACH,OAAO,CAAC,qBAAqB;IA2G7B,OAAO,CAAC,0BAA0B;IAYlC;;;OAGG;IACH,OAAO,CAAC,UAAU;IAsOlB;;;OAGG;IACH,OAAO,CAAC,qBAAqB;CA6N9B;AAED,yBAAiB,EAAE,CAAC;IAClB,KAAY,QAAQ;QAClB,GAAG,QAAQ;QACX,IAAI,SAAS;KACd;CACF;AAED;;;GAGG;AACH,wBAAgB,oCAAoC,CAAC,EAAE,EAAE,EAAE,GAAG,0BAA0B,CAgEvF"} \ No newline at end of file diff --git a/lib/UA.js b/lib/UA.js deleted file mode 100644 index dba5d8e58..000000000 --- a/lib/UA.js +++ /dev/null @@ -1,1107 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var events_1 = require("events"); -var ClientContext_1 = require("./ClientContext"); -var Constants_1 = require("./Constants"); -var core_1 = require("./core"); -var Enums_1 = require("./Enums"); -var Exceptions_1 = require("./Exceptions"); -var Parser_1 = require("./Parser"); -var PublishContext_1 = require("./PublishContext"); -var ReferContext_1 = require("./ReferContext"); -var RegisterContext_1 = require("./RegisterContext"); -var ServerContext_1 = require("./ServerContext"); -var Session_1 = require("./Session"); -var Subscription_1 = require("./Subscription"); -var Utils_1 = require("./Utils"); -var SessionDescriptionHandler_1 = require("./Web/SessionDescriptionHandler"); -var Transport_1 = require("./Web/Transport"); -/** - * @class Class creating a SIP User Agent. - * @param {function returning SIP.sessionDescriptionHandler} [configuration.sessionDescriptionHandlerFactory] - * A function will be invoked by each of the UA's Sessions to build the sessionDescriptionHandler for that Session. - * If no (or a falsy) value is provided, each Session will use a default (WebRTC) sessionDescriptionHandler. - */ -var UA = /** @class */ (function (_super) { - tslib_1.__extends(UA, _super); - function UA(configuration) { - var _this = _super.call(this) || this; - /** Unload listener. */ - _this.unloadListener = (function () { _this.stop(); }); - _this.type = Enums_1.TypeStrings.UA; - _this.log = new core_1.LoggerFactory(); - _this.logger = _this.getLogger("sip.ua"); - _this.configuration = {}; - // User actions outside any session/dialog (MESSAGE) - _this.applicants = {}; - _this.data = {}; - _this.sessions = {}; - _this.subscriptions = {}; - _this.publishers = {}; - _this.status = Enums_1.UAStatus.STATUS_INIT; - /** - * Load configuration - * - * @throws {SIP.Exceptions.ConfigurationError} - * @throws {TypeError} - */ - if (configuration === undefined) { - configuration = {}; - } - else if (typeof configuration === "string" || configuration instanceof String) { - configuration = { - uri: configuration - }; - } - // Apply log configuration if present - if (configuration.log) { - _this.log.builtinEnabled = configuration.log.builtinEnabled; - if (configuration.log.hasOwnProperty("connector")) { - _this.log.connector = configuration.log.connector; - } - if (configuration.log.hasOwnProperty("level")) { - var level = configuration.log.level; - var normalized = void 0; - if (typeof level === "string") { - switch (level) { - case "error": - normalized = core_1.Levels.error; - break; - case "warn": - normalized = core_1.Levels.warn; - break; - case "log": - normalized = core_1.Levels.log; - break; - case "debug": - normalized = core_1.Levels.debug; - break; - default: - break; - } - } - else { - switch (level) { - case 0: - normalized = core_1.Levels.error; - break; - case 1: - normalized = core_1.Levels.warn; - break; - case 2: - normalized = core_1.Levels.log; - break; - case 3: - normalized = core_1.Levels.debug; - break; - default: - break; - } - } - // avoid setting level when invalid, use default level instead - if (normalized === undefined) { - _this.logger.error("Invalid \"level\" parameter value: " + JSON.stringify(level)); - } - else { - _this.log.level = normalized; - } - } - } - var deprecatedMessage = "The UA class has been deprecated and will no longer be available starting with SIP.js release 0.16.0. " + - "The UA has been replaced by the UserAgent class. Please update accordingly."; - _this.logger.warn(deprecatedMessage); - try { - _this.loadConfig(configuration); - } - catch (e) { - _this.status = Enums_1.UAStatus.STATUS_NOT_READY; - _this.error = UA.C.CONFIGURATION_ERROR; - throw e; - } - if (!_this.configuration.transportConstructor) { - throw new core_1.TransportError("Transport constructor not set"); - } - _this.transport = new _this.configuration.transportConstructor(_this.getLogger("sip.transport"), _this.configuration.transportOptions); - var userAgentCoreConfiguration = makeUserAgentCoreConfigurationFromUA(_this); - // The Replaces header contains information used to match an existing - // SIP dialog (call-id, to-tag, and from-tag). Upon receiving an INVITE - // with a Replaces header, the User Agent (UA) attempts to match this - // information with a confirmed or early dialog. - // https://tools.ietf.org/html/rfc3891#section-3 - var handleInviteWithReplacesHeader = function (context, request) { - if (_this.configuration.replaces !== Constants_1.C.supported.UNSUPPORTED) { - var replaces = request.parseHeader("replaces"); - if (replaces) { - var targetSession = _this.sessions[replaces.call_id + replaces.replaces_from_tag] || - _this.sessions[replaces.call_id + replaces.replaces_to_tag] || - undefined; - if (!targetSession) { - _this.userAgentCore.replyStateless(request, { statusCode: 481 }); - return; - } - if (targetSession.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - _this.userAgentCore.replyStateless(request, { statusCode: 603 }); - return; - } - var targetDialogId = replaces.call_id + replaces.replaces_to_tag + replaces.replaces_from_tag; - var targetDialog = _this.userAgentCore.dialogs.get(targetDialogId); - if (!targetDialog) { - _this.userAgentCore.replyStateless(request, { statusCode: 481 }); - return; - } - if (!targetDialog.early && replaces.early_only) { - _this.userAgentCore.replyStateless(request, { statusCode: 486 }); - return; - } - context.replacee = targetSession; - } - } - }; - var userAgentCoreDelegate = { - onInvite: function (incomingInviteRequest) { - // FIXME: Ported - 100 Trying send should be configurable. - // Only required if TU will not respond in 200ms. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - incomingInviteRequest.trying(); - incomingInviteRequest.delegate = { - onCancel: function (cancel) { - context.onCancel(cancel); - }, - onTransportError: function (error) { - context.onTransportError(); - } - }; - var context = new Session_1.InviteServerContext(_this, incomingInviteRequest); - // Ported - handling of out of dialog INVITE with Replaces. - handleInviteWithReplacesHeader(context, incomingInviteRequest.message); - // Ported - make the first call to progress automatically. - if (context.autoSendAnInitialProvisionalResponse) { - context.progress(); - } - _this.emit("invite", context); - }, - onMessage: function (incomingMessageRequest) { - // Ported - handling of out of dialog MESSAGE. - var serverContext = new ServerContext_1.ServerContext(_this, incomingMessageRequest); - serverContext.body = incomingMessageRequest.message.body; - serverContext.contentType = incomingMessageRequest.message.getHeader("Content-Type") || "text/plain"; - incomingMessageRequest.accept(); - _this.emit("message", serverContext); // TODO: Review. Why is a "ServerContext" emitted? What use it is? - }, - onNotify: function (incomingNotifyRequest) { - // DEPRECATED: Out of dialog NOTIFY is an obsolete usage. - // Ported - handling of out of dialog NOTIFY. - if (_this.configuration.allowLegacyNotifications && _this.listeners("notify").length > 0) { - incomingNotifyRequest.accept(); - _this.emit("notify", { request: incomingNotifyRequest.message }); - } - else { - incomingNotifyRequest.reject({ statusCode: 481 }); - } - }, - onRefer: function (incomingReferRequest) { - // Ported - handling of out of dialog REFER. - _this.logger.log("Received an out of dialog refer"); - if (!_this.configuration.allowOutOfDialogRefers) { - incomingReferRequest.reject({ statusCode: 405 }); - } - _this.logger.log("Allow out of dialog refers is enabled on the UA"); - var referContext = new ReferContext_1.ReferServerContext(_this, incomingReferRequest); - if (_this.listeners("outOfDialogReferRequested").length) { - _this.emit("outOfDialogReferRequested", referContext); - } - else { - _this.logger.log("No outOfDialogReferRequest listeners, automatically accepting and following the out of dialog refer"); - referContext.accept({ followRefer: true }); - } - }, - onSubscribe: function (incomingSubscribeRequest) { - _this.emit("subscribe", incomingSubscribeRequest); - }, - }; - _this.userAgentCore = new core_1.UserAgentCore(userAgentCoreConfiguration, userAgentCoreDelegate); - // Initialize registerContext - _this.registerContext = new RegisterContext_1.RegisterContext(_this, configuration.registerOptions); - _this.registerContext.on("failed", _this.emit.bind(_this, "registrationFailed")); - _this.registerContext.on("registered", _this.emit.bind(_this, "registered")); - _this.registerContext.on("unregistered", _this.emit.bind(_this, "unregistered")); - if (_this.configuration.autostart) { - _this.start(); - } - return _this; - } - // ================= - // High Level API - // ================= - UA.prototype.register = function (options) { - if (options === void 0) { options = {}; } - if (options.register) { - this.configuration.register = true; - } - this.registerContext.register(options); - return this; - }; - /** - * Unregister. - * - * @param {Boolean} [all] unregister all user bindings. - * - */ - UA.prototype.unregister = function (options) { - var _this = this; - this.configuration.register = false; - this.transport.afterConnected(function () { - _this.registerContext.unregister(options); - }); - return this; - }; - UA.prototype.isRegistered = function () { - return this.registerContext.registered; - }; - /** - * Make an outgoing call. - * - * @param {String} target - * @param {Object} views - * @param {Object} [options.media] gets passed to SIP.sessionDescriptionHandler.getDescription as mediaHint - * - * @throws {TypeError} - * - */ - UA.prototype.invite = function (target, options, modifiers) { - var _this = this; - var context = new Session_1.InviteClientContext(this, target, options, modifiers); - // Delay sending actual invite until the next 'tick' if we are already - // connected, so that API consumers can register to events fired by the - // the session. - this.transport.afterConnected(function () { - context.invite(); - _this.emit("inviteSent", context); - }); - return context; - }; - UA.prototype.subscribe = function (target, event, options) { - var sub = new Subscription_1.Subscription(this, target, event, options); - this.transport.afterConnected(function () { return sub.subscribe(); }); - return sub; - }; - /** - * Send PUBLISH Event State Publication (RFC3903) - * - * @param {String} target - * @param {String} event - * @param {String} body - * @param {Object} [options] - * - * @throws {SIP.Exceptions.MethodParameterError} - */ - UA.prototype.publish = function (target, event, body, options) { - var pub = new PublishContext_1.PublishContext(this, target, event, options); - this.transport.afterConnected(function () { - pub.publish(body); - }); - return pub; - }; - /** - * Send a message. - * - * @param {String} target - * @param {String} body - * @param {Object} [options] - * - * @throws {TypeError} - */ - UA.prototype.message = function (target, body, options) { - if (options === void 0) { options = {}; } - if (body === undefined) { - throw new TypeError("Not enough arguments"); - } - // There is no Message module, so it is okay that the UA handles defaults here. - options.contentType = options.contentType || "text/plain"; - options.body = body; - return this.request(Constants_1.C.MESSAGE, target, options); - }; - UA.prototype.request = function (method, target, options) { - var req = new ClientContext_1.ClientContext(this, method, target, options); - this.transport.afterConnected(function () { return req.send(); }); - return req; - }; - /** - * Gracefully close. - */ - UA.prototype.stop = function () { - this.logger.log("user requested closure..."); - if (this.status === Enums_1.UAStatus.STATUS_USER_CLOSED) { - this.logger.warn("UA already closed"); - return this; - } - // Close registerContext - this.logger.log("closing registerContext"); - this.registerContext.close(); - // Run terminate on every Session - for (var session in this.sessions) { - if (this.sessions[session]) { - this.logger.log("closing session " + session); - this.sessions[session].terminate(); - } - } - // Run unsubscribe on every Subscription - for (var subscription in this.subscriptions) { - if (this.subscriptions[subscription]) { - this.logger.log("unsubscribe " + subscription); - this.subscriptions[subscription].unsubscribe(); - } - } - // Run close on every Publisher - for (var publisher in this.publishers) { - if (this.publishers[publisher]) { - this.logger.log("unpublish " + publisher); - this.publishers[publisher].close(); - } - } - // Run close on every applicant - for (var applicant in this.applicants) { - if (this.applicants[applicant]) { - this.applicants[applicant].close(); - } - } - this.status = Enums_1.UAStatus.STATUS_USER_CLOSED; - // Disconnect the transport and reset user agent core - this.transport.disconnect(); - this.userAgentCore.reset(); - if (this.configuration.autostop) { - // Google Chrome Packaged Apps don't allow 'unload' listeners: unload is not available in packaged apps - var googleChromePackagedApp = typeof chrome !== "undefined" && chrome.app && chrome.app.runtime ? true : false; - if (typeof window !== "undefined" && - typeof window.removeEventListener === "function" && - !googleChromePackagedApp) { - window.removeEventListener("unload", this.unloadListener); - } - } - return this; - }; - /** - * Connect to the WS server if status = STATUS_INIT. - * Resume UA after being closed. - * - */ - UA.prototype.start = function () { - this.logger.log("user requested startup..."); - if (this.status === Enums_1.UAStatus.STATUS_INIT) { - this.status = Enums_1.UAStatus.STATUS_STARTING; - this.setTransportListeners(); - this.emit("transportCreated", this.transport); - this.transport.connect(); - } - else if (this.status === Enums_1.UAStatus.STATUS_USER_CLOSED) { - this.logger.log("resuming"); - this.status = Enums_1.UAStatus.STATUS_READY; - this.transport.connect(); - } - else if (this.status === Enums_1.UAStatus.STATUS_STARTING) { - this.logger.log("UA is in STARTING status, not opening new connection"); - } - else if (this.status === Enums_1.UAStatus.STATUS_READY) { - this.logger.log("UA is in READY status, not resuming"); - } - else { - this.logger.error("Connection is down. Auto-Recovery system is trying to connect"); - } - if (this.configuration.autostop) { - // Google Chrome Packaged Apps don't allow 'unload' listeners: unload is not available in packaged apps - var googleChromePackagedApp = typeof chrome !== "undefined" && chrome.app && chrome.app.runtime ? true : false; - if (typeof window !== "undefined" && - typeof window.addEventListener === "function" && - !googleChromePackagedApp) { - window.addEventListener("unload", this.unloadListener); - } - } - return this; - }; - /** - * Normalize a string into a valid SIP request URI - * - * @param {String} target - * - * @returns {SIP.URI|undefined} - */ - UA.prototype.normalizeTarget = function (target) { - return Utils_1.Utils.normalizeTarget(target, this.configuration.hostportParams); - }; - UA.prototype.getLogger = function (category, label) { - return this.log.getLogger(category, label); - }; - UA.prototype.getLoggerFactory = function () { - return this.log; - }; - UA.prototype.getSupportedResponseOptions = function () { - var optionTags = []; - if (this.contact.pubGruu || this.contact.tempGruu) { - optionTags.push("gruu"); - } - if (this.configuration.rel100 === Constants_1.C.supported.SUPPORTED) { - optionTags.push("100rel"); - } - if (this.configuration.replaces === Constants_1.C.supported.SUPPORTED) { - optionTags.push("replaces"); - } - optionTags.push("outbound"); - optionTags = optionTags.concat(this.configuration.extraSupported || []); - var allowUnregistered = this.configuration.hackAllowUnregisteredOptionTags || false; - var optionTagSet = {}; - optionTags = optionTags.filter(function (optionTag) { - var registered = Constants_1.C.OPTION_TAGS[optionTag]; - var unique = !optionTagSet[optionTag]; - optionTagSet[optionTag] = true; - return (registered || allowUnregistered) && unique; - }); - return optionTags; - }; - /** - * Get the session to which the request belongs to, if any. - * @param {SIP.IncomingRequest} request. - * @returns {SIP.OutgoingSession|SIP.IncomingSession|undefined} - */ - UA.prototype.findSession = function (request) { - return this.sessions[request.callId + request.fromTag] || - this.sessions[request.callId + request.toTag] || - undefined; - }; - UA.prototype.on = function (name, callback) { return _super.prototype.on.call(this, name, callback); }; - // ============================== - // Event Handlers - // ============================== - UA.prototype.onTransportError = function () { - if (this.status === Enums_1.UAStatus.STATUS_USER_CLOSED) { - return; - } - if (!this.error || this.error !== UA.C.NETWORK_ERROR) { - this.status = Enums_1.UAStatus.STATUS_NOT_READY; - this.error = UA.C.NETWORK_ERROR; - } - }; - /** - * Helper function. Sets transport listeners - */ - UA.prototype.setTransportListeners = function () { - var _this = this; - this.transport.on("connected", function () { return _this.onTransportConnected(); }); - this.transport.on("message", function (message) { return _this.onTransportReceiveMsg(message); }); - this.transport.on("transportError", function () { return _this.onTransportError(); }); - }; - /** - * Transport connection event. - * @event - * @param {SIP.Transport} transport. - */ - UA.prototype.onTransportConnected = function () { - var _this = this; - if (this.configuration.register) { - // In an effor to maintain behavior from when we "initialized" an - // authentication factory, this is in a Promise.then - Promise.resolve().then(function () { return _this.registerContext.register(); }); - } - }; - /** - * Handle SIP message received from the transport. - * @param messageString The message. - */ - UA.prototype.onTransportReceiveMsg = function (messageString) { - var _this = this; - var message = Parser_1.Parser.parseMessage(messageString, this.getLogger("sip.parser")); - if (!message) { - this.logger.warn("UA failed to parse incoming SIP message - discarding."); - return; - } - if (this.status === Enums_1.UAStatus.STATUS_USER_CLOSED && message instanceof core_1.IncomingRequestMessage) { - this.logger.warn("UA received message when status = USER_CLOSED - aborting"); - return; - } - // A valid SIP request formulated by a UAC MUST, at a minimum, contain - // the following header fields: To, From, CSeq, Call-ID, Max-Forwards, - // and Via; all of these header fields are mandatory in all SIP - // requests. - // https://tools.ietf.org/html/rfc3261#section-8.1.1 - var hasMinimumHeaders = function () { - var mandatoryHeaders = ["from", "to", "call_id", "cseq", "via"]; - for (var _i = 0, mandatoryHeaders_1 = mandatoryHeaders; _i < mandatoryHeaders_1.length; _i++) { - var header = mandatoryHeaders_1[_i]; - if (!message.hasHeader(header)) { - _this.logger.warn("Missing mandatory header field : " + header + "."); - return false; - } - } - return true; - }; - // Request Checks - if (message instanceof core_1.IncomingRequestMessage) { - // This is port of SanityCheck.minimumHeaders(). - if (!hasMinimumHeaders()) { - this.logger.warn("Request missing mandatory header field. Dropping."); - return; - } - // FIXME: This is non-standard and should be a configruable behavior (desirable regardless). - // Custom SIP.js check to reject request from ourself (this instance of SIP.js). - // This is port of SanityCheck.rfc3261_16_3_4(). - if (!message.toTag && message.callId.substr(0, 5) === this.configuration.sipjsId) { - this.userAgentCore.replyStateless(message, { statusCode: 482 }); - return; - } - // FIXME: This should be Transport check before we get here (Section 18). - // Custom SIP.js check to reject requests if body length wrong. - // This is port of SanityCheck.rfc3261_18_3_request(). - var len = Utils_1.Utils.str_utf8_length(message.body); - var contentLength = message.getHeader("content-length"); - if (contentLength && len < Number(contentLength)) { - this.userAgentCore.replyStateless(message, { statusCode: 400 }); - return; - } - } - // Reponse Checks - if (message instanceof core_1.IncomingResponseMessage) { - // This is port of SanityCheck.minimumHeaders(). - if (!hasMinimumHeaders()) { - this.logger.warn("Response missing mandatory header field. Dropping."); - return; - } - // Custom SIP.js check to drop responses if multiple Via headers. - // This is port of SanityCheck.rfc3261_8_1_3_3(). - if (message.getHeaders("via").length > 1) { - this.logger.warn("More than one Via header field present in the response. Dropping."); - return; - } - // FIXME: This should be Transport check before we get here (Section 18). - // Custom SIP.js check to drop responses if bad Via header. - // This is port of SanityCheck.rfc3261_18_1_2(). - if (message.via.host !== this.configuration.viaHost || message.via.port !== undefined) { - this.logger.warn("Via sent-by in the response does not match UA Via host value. Dropping."); - return; - } - // FIXME: This should be Transport check before we get here (Section 18). - // Custom SIP.js check to reject requests if body length wrong. - // This is port of SanityCheck.rfc3261_18_3_response(). - var len = Utils_1.Utils.str_utf8_length(message.body); - var contentLength = message.getHeader("content-length"); - if (contentLength && len < Number(contentLength)) { - this.logger.warn("Message body length is lower than the value in Content-Length header field. Dropping."); - return; - } - } - // Handle Request - if (message instanceof core_1.IncomingRequestMessage) { - this.userAgentCore.receiveIncomingRequestFromTransport(message); - return; - } - // Handle Response - if (message instanceof core_1.IncomingResponseMessage) { - this.userAgentCore.receiveIncomingResponseFromTransport(message); - return; - } - throw new Error("Invalid message type."); - }; - // ================= - // Utils - // ================= - UA.prototype.checkAuthenticationFactory = function (authenticationFactory) { - if (!(authenticationFactory instanceof Function)) { - return; - } - if (!authenticationFactory.initialize) { - authenticationFactory.initialize = function () { - return Promise.resolve(); - }; - } - return authenticationFactory; - }; - /** - * Configuration load. - * returns {void} - */ - UA.prototype.loadConfig = function (configuration) { - var _this = this; - // Settings and default values - var settings = { - /* Host address - * Value to be set in Via sent_by and host part of Contact FQDN - */ - viaHost: Utils_1.Utils.createRandomToken(12) + ".invalid", - uri: new core_1.URI("sip", "anonymous." + Utils_1.Utils.createRandomToken(6), "anonymous.invalid", undefined, undefined), - // Custom Configuration Settings - custom: {}, - // Display name - displayName: "", - // Password - password: undefined, - register: true, - // Registration parameters - registerOptions: {}, - // Transport related parameters - transportConstructor: Transport_1.Transport, - transportOptions: {}, - usePreloadedRoute: false, - // string to be inserted into User-Agent request header - userAgentString: Constants_1.C.USER_AGENT, - // Session parameters - noAnswerTimeout: 60, - // Hacks - hackViaTcp: false, - hackIpInContact: false, - hackWssInTransport: false, - hackAllowUnregisteredOptionTags: false, - // Session Description Handler Options - sessionDescriptionHandlerFactoryOptions: { - constraints: {}, - peerConnectionOptions: {} - }, - extraSupported: [], - contactName: Utils_1.Utils.createRandomToken(8), - contactTransport: "ws", - forceRport: false, - // autostarting - autostart: true, - autostop: true, - // Reliable Provisional Responses - rel100: Constants_1.C.supported.UNSUPPORTED, - // DTMF type: 'info' or 'rtp' (RFC 4733) - // RTP Payload Spec: https://tools.ietf.org/html/rfc4733 - // WebRTC Audio Spec: https://tools.ietf.org/html/rfc7874 - dtmfType: Constants_1.C.dtmfType.INFO, - // Replaces header (RFC 3891) - // http://tools.ietf.org/html/rfc3891 - replaces: Constants_1.C.supported.UNSUPPORTED, - sessionDescriptionHandlerFactory: SessionDescriptionHandler_1.SessionDescriptionHandler.defaultFactory, - authenticationFactory: this.checkAuthenticationFactory(function (ua) { - return new core_1.DigestAuthentication(ua.getLoggerFactory(), _this.configuration.authorizationUser, _this.configuration.password); - }), - allowLegacyNotifications: false, - allowOutOfDialogRefers: false, - experimentalFeatures: false - }; - var configCheck = this.getConfigurationCheck(); - // Check Mandatory parameters - for (var parameter in configCheck.mandatory) { - if (!configuration.hasOwnProperty(parameter)) { - throw new Exceptions_1.Exceptions.ConfigurationError(parameter); - } - else { - var value = configuration[parameter]; - var checkedValue = configCheck.mandatory[parameter](value); - if (checkedValue !== undefined) { - settings[parameter] = checkedValue; - } - else { - throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); - } - } - } - // Check Optional parameters - for (var parameter in configCheck.optional) { - if (configuration.hasOwnProperty(parameter)) { - var value = configuration[parameter]; - // If the parameter value is an empty array, but shouldn't be, apply its default value. - // If the parameter value is null, empty string, or undefined then apply its default value. - // If it's a number with NaN value then also apply its default value. - // NOTE: JS does not allow "value === NaN", the following does the work: - if ((value instanceof Array && value.length === 0) || - (value === null || value === "" || value === undefined) || - (typeof (value) === "number" && isNaN(value))) { - continue; - } - var checkedValue = configCheck.optional[parameter](value); - if (checkedValue !== undefined) { - settings[parameter] = checkedValue; - } - else { - throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); - } - } - } - // Post Configuration Process - // Allow passing 0 number as displayName. - if (settings.displayName === 0) { - settings.displayName = "0"; - } - // sipjsId instance parameter. Static random tag of length 5 - settings.sipjsId = Utils_1.Utils.createRandomToken(5); - // String containing settings.uri without scheme and user. - var hostportParams = settings.uri.clone(); - hostportParams.user = undefined; - settings.hostportParams = hostportParams.toRaw().replace(/^sip:/i, ""); - /* Check whether authorizationUser is explicitly defined. - * Take 'settings.uri.user' value if not. - */ - if (!settings.authorizationUser) { - settings.authorizationUser = settings.uri.user; - } - // User noAnswerTimeout - settings.noAnswerTimeout = settings.noAnswerTimeout * 1000; - // Via Host - if (settings.hackIpInContact) { - if (typeof settings.hackIpInContact === "boolean") { - var from = 1; - var to = 254; - var octet = Math.floor(Math.random() * (to - from + 1) + from); - // random Test-Net IP (http://tools.ietf.org/html/rfc5735) - settings.viaHost = "192.0.2." + octet; - } - else if (typeof settings.hackIpInContact === "string") { - settings.viaHost = settings.hackIpInContact; - } - } - // Contact transport parameter - if (settings.hackWssInTransport) { - settings.contactTransport = "wss"; - } - this.contact = { - pubGruu: undefined, - tempGruu: undefined, - uri: new core_1.URI("sip", settings.contactName, settings.viaHost, undefined, { transport: settings.contactTransport }), - toString: function (options) { - if (options === void 0) { options = {}; } - var anonymous = options.anonymous || false; - var outbound = options.outbound || false; - var contact = "<"; - if (anonymous) { - contact += (_this.contact.tempGruu || - ("sip:anonymous@anonymous.invalid;transport=" + settings.contactTransport)).toString(); - } - else { - contact += (_this.contact.pubGruu || _this.contact.uri).toString(); - } - if (outbound) { - contact += ";ob"; - } - contact += ">"; - return contact; - } - }; - var skeleton = {}; - // Fill the value of the configuration_skeleton - for (var parameter in settings) { - if (settings.hasOwnProperty(parameter)) { - skeleton[parameter] = settings[parameter]; - } - } - Object.assign(this.configuration, skeleton); - this.logger.log("configuration parameters after validation:"); - for (var parameter in settings) { - if (settings.hasOwnProperty(parameter)) { - switch (parameter) { - case "uri": - case "sessionDescriptionHandlerFactory": - this.logger.log("· " + parameter + ": " + settings[parameter]); - break; - case "password": - this.logger.log("· " + parameter + ": " + "NOT SHOWN"); - break; - case "transportConstructor": - this.logger.log("· " + parameter + ": " + settings[parameter].name); - break; - default: - this.logger.log("· " + parameter + ": " + JSON.stringify(settings[parameter])); - } - } - } - return; - }; - /** - * Configuration checker. - * @return {Boolean} - */ - UA.prototype.getConfigurationCheck = function () { - return { - mandatory: {}, - optional: { - uri: function (uri) { - if (!(/^sip:/i).test(uri)) { - uri = Constants_1.C.SIP + ":" + uri; - } - var parsed = core_1.Grammar.URIParse(uri); - if (!parsed || !parsed.user) { - return; - } - else { - return parsed; - } - }, - transportConstructor: function (transportConstructor) { - if (transportConstructor instanceof Function) { - return transportConstructor; - } - }, - transportOptions: function (transportOptions) { - if (typeof transportOptions === "object") { - return transportOptions; - } - }, - authorizationUser: function (authorizationUser) { - if (core_1.Grammar.parse('"' + authorizationUser + '"', "quoted_string") === -1) { - return; - } - else { - return authorizationUser; - } - }, - displayName: function (displayName) { - if (core_1.Grammar.parse('"' + displayName + '"', "displayName") === -1) { - return; - } - else { - return displayName; - } - }, - dtmfType: function (dtmfType) { - switch (dtmfType) { - case Constants_1.C.dtmfType.RTP: - return Constants_1.C.dtmfType.RTP; - case Constants_1.C.dtmfType.INFO: - // Fall through - default: - return Constants_1.C.dtmfType.INFO; - } - }, - hackViaTcp: function (hackViaTcp) { - if (typeof hackViaTcp === "boolean") { - return hackViaTcp; - } - }, - hackIpInContact: function (hackIpInContact) { - if (typeof hackIpInContact === "boolean") { - return hackIpInContact; - } - else if (typeof hackIpInContact === "string" && core_1.Grammar.parse(hackIpInContact, "host") !== -1) { - return hackIpInContact; - } - }, - hackWssInTransport: function (hackWssInTransport) { - if (typeof hackWssInTransport === "boolean") { - return hackWssInTransport; - } - }, - hackAllowUnregisteredOptionTags: function (hackAllowUnregisteredOptionTags) { - if (typeof hackAllowUnregisteredOptionTags === "boolean") { - return hackAllowUnregisteredOptionTags; - } - }, - contactTransport: function (contactTransport) { - if (typeof contactTransport === "string") { - return contactTransport; - } - }, - extraSupported: function (optionTags) { - if (!(optionTags instanceof Array)) { - return; - } - for (var _i = 0, optionTags_1 = optionTags; _i < optionTags_1.length; _i++) { - var tag = optionTags_1[_i]; - if (typeof tag !== "string") { - return; - } - } - return optionTags; - }, - forceRport: function (forceRport) { - if (typeof forceRport === "boolean") { - return forceRport; - } - }, - noAnswerTimeout: function (noAnswerTimeout) { - if (Utils_1.Utils.isDecimal(noAnswerTimeout)) { - var value = Number(noAnswerTimeout); - if (value > 0) { - return value; - } - } - }, - password: function (password) { - return String(password); - }, - rel100: function (rel100) { - if (rel100 === Constants_1.C.supported.REQUIRED) { - return Constants_1.C.supported.REQUIRED; - } - else if (rel100 === Constants_1.C.supported.SUPPORTED) { - return Constants_1.C.supported.SUPPORTED; - } - else { - return Constants_1.C.supported.UNSUPPORTED; - } - }, - replaces: function (replaces) { - if (replaces === Constants_1.C.supported.REQUIRED) { - return Constants_1.C.supported.REQUIRED; - } - else if (replaces === Constants_1.C.supported.SUPPORTED) { - return Constants_1.C.supported.SUPPORTED; - } - else { - return Constants_1.C.supported.UNSUPPORTED; - } - }, - register: function (register) { - if (typeof register === "boolean") { - return register; - } - }, - registerOptions: function (registerOptions) { - if (typeof registerOptions === "object") { - return registerOptions; - } - }, - usePreloadedRoute: function (usePreloadedRoute) { - if (typeof usePreloadedRoute === "boolean") { - return usePreloadedRoute; - } - }, - userAgentString: function (userAgentString) { - if (typeof userAgentString === "string") { - return userAgentString; - } - }, - autostart: function (autostart) { - if (typeof autostart === "boolean") { - return autostart; - } - }, - autostop: function (autostop) { - if (typeof autostop === "boolean") { - return autostop; - } - }, - sessionDescriptionHandlerFactory: function (sessionDescriptionHandlerFactory) { - if (sessionDescriptionHandlerFactory instanceof Function) { - return sessionDescriptionHandlerFactory; - } - }, - sessionDescriptionHandlerFactoryOptions: function (options) { - if (typeof options === "object") { - return options; - } - }, - authenticationFactory: this.checkAuthenticationFactory, - allowLegacyNotifications: function (allowLegacyNotifications) { - if (typeof allowLegacyNotifications === "boolean") { - return allowLegacyNotifications; - } - }, - custom: function (custom) { - if (typeof custom === "object") { - return custom; - } - }, - contactName: function (contactName) { - if (typeof contactName === "string") { - return contactName; - } - }, - experimentalFeatures: function (experimentalFeatures) { - if (typeof experimentalFeatures === "boolean") { - return experimentalFeatures; - } - }, - } - }; - }; - UA.C = { - // UA status codes - STATUS_INIT: 0, - STATUS_STARTING: 1, - STATUS_READY: 2, - STATUS_USER_CLOSED: 3, - STATUS_NOT_READY: 4, - // UA error codes - CONFIGURATION_ERROR: 1, - NETWORK_ERROR: 2, - ALLOWED_METHODS: [ - "ACK", - "CANCEL", - "INVITE", - "MESSAGE", - "BYE", - "OPTIONS", - "INFO", - "NOTIFY", - "REFER" - ], - ACCEPTED_BODY_TYPES: [ - "application/sdp", - "application/dtmf-relay" - ], - MAX_FORWARDS: 70, - TAG_LENGTH: 10 - }; - return UA; -}(events_1.EventEmitter)); -exports.UA = UA; -(function (UA) { - var DtmfType; - (function (DtmfType) { - DtmfType["RTP"] = "rtp"; - DtmfType["INFO"] = "info"; - })(DtmfType = UA.DtmfType || (UA.DtmfType = {})); -})(UA = exports.UA || (exports.UA = {})); -exports.UA = UA; -/** - * Factory function to generate configuration give a UA. - * @param ua UA - */ -function makeUserAgentCoreConfigurationFromUA(ua) { - // FIXME: Configuration URI is a bad mix of types currently. It also needs to exist. - if (!(ua.configuration.uri instanceof core_1.URI)) { - throw new Error("Configuration URI not instance of URI."); - } - var aor = ua.configuration.uri; - var contact = ua.contact; - var displayName = ua.configuration.displayName ? ua.configuration.displayName : ""; - var hackViaTcp = ua.configuration.hackViaTcp ? true : false; - var routeSet = ua.configuration.usePreloadedRoute && ua.transport.server && ua.transport.server.sipUri ? - [ua.transport.server.sipUri] : - []; - var sipjsId = ua.configuration.sipjsId || Utils_1.Utils.createRandomToken(5); - var supportedOptionTags = []; - supportedOptionTags.push("outbound"); // TODO: is this really supported? - if (ua.configuration.rel100 === Constants_1.C.supported.SUPPORTED) { - supportedOptionTags.push("100rel"); - } - if (ua.configuration.replaces === Constants_1.C.supported.SUPPORTED) { - supportedOptionTags.push("replaces"); - } - if (ua.configuration.extraSupported) { - supportedOptionTags.push.apply(supportedOptionTags, ua.configuration.extraSupported); - } - if (!ua.configuration.hackAllowUnregisteredOptionTags) { - supportedOptionTags = supportedOptionTags.filter(function (optionTag) { return Constants_1.C.OPTION_TAGS[optionTag]; }); - } - supportedOptionTags = Array.from(new Set(supportedOptionTags)); // array of unique values - var supportedOptionTagsResponse = ua.getSupportedResponseOptions(); - var userAgentHeaderFieldValue = ua.configuration.userAgentString || "sipjs"; - if (!(ua.configuration.viaHost)) { - throw new Error("Configuration via host undefined"); - } - var viaForceRport = ua.configuration.forceRport ? true : false; - var viaHost = ua.configuration.viaHost; - var configuration = { - aor: aor, - contact: contact, - displayName: displayName, - hackViaTcp: hackViaTcp, - loggerFactory: ua.getLoggerFactory(), - routeSet: routeSet, - sipjsId: sipjsId, - supportedOptionTags: supportedOptionTags, - supportedOptionTagsResponse: supportedOptionTagsResponse, - userAgentHeaderFieldValue: userAgentHeaderFieldValue, - viaForceRport: viaForceRport, - viaHost: viaHost, - authenticationFactory: function () { - if (ua.configuration.authenticationFactory) { - return ua.configuration.authenticationFactory(ua); - } - return undefined; - }, - transportAccessor: function () { return ua.transport; } - }; - return configuration; -} -exports.makeUserAgentCoreConfigurationFromUA = makeUserAgentCoreConfigurationFromUA; diff --git a/lib/Utils.d.ts b/lib/Utils.d.ts deleted file mode 100644 index 555e0f8d9..000000000 --- a/lib/Utils.d.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { Body } from "./core/messages/body"; -import { URI } from "./core/messages/uri"; -import { BodyObj, SessionDescriptionHandlerModifier } from "./session-description-handler"; -export declare namespace Utils { - interface Deferred { - promise: Promise; - resolve: () => T; - reject: () => T; - } - function defer(): Deferred; - function reducePromises(arr: Array, val: any): Promise; - function str_utf8_length(str: string): number; - function generateFakeSDP(body: string): string | undefined; - function isDecimal(num: string): boolean; - function createRandomToken(size: number, base?: number): string; - function newTag(): string; - function newUUID(): string; - function normalizeTarget(target: string | URI, domain?: string): URI | undefined; - function escapeUser(user: string): string; - function headerize(str: string): string; - function sipErrorCause(statusCode: number): string; - function getReasonPhrase(code: number, specific?: string): string; - function getReasonHeaderValue(code: number, reason?: string): string; - function getCancelReason(code: number, reason: string): string | undefined; - function buildStatusLine(code: number, reason?: string): string; - /** - * Create a Body given a BodyObj. - * @param bodyObj Body Object - */ - function fromBodyObj(bodyObj: BodyObj): Body; - /** - * Create a BodyObj given a Body. - * @param bodyObj Body Object - */ - function toBodyObj(body: Body): BodyObj; -} -//# sourceMappingURL=Utils.d.ts.map \ No newline at end of file diff --git a/lib/Utils.d.ts.map b/lib/Utils.d.ts.map deleted file mode 100644 index e275112c2..000000000 --- a/lib/Utils.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"Utils.d.ts","sourceRoot":"","sources":["../src/Utils.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,sBAAsB,CAAC;AAE5C,OAAO,EAAE,GAAG,EAAE,MAAM,qBAAqB,CAAC;AAC1C,OAAO,EAAE,OAAO,EAAE,iCAAiC,EAAE,MAAM,+BAA+B,CAAC;AAE3F,yBAAiB,KAAK,CAAC;IACrB,UAAiB,QAAQ,CAAC,CAAC;QACzB,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC;QACpB,OAAO,EAAE,MAAM,CAAC,CAAC;QACjB,MAAM,EAAE,MAAM,CAAC,CAAC;KACjB;IAED,SAAgB,KAAK,IAAI,QAAQ,CAAC,GAAG,CAAC,CAOrC;IAED,SAAgB,cAAc,CAAC,GAAG,EAAE,KAAK,CAAC,iCAAiC,CAAC,EAAE,GAAG,EAAE,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,CAKpG;IAED,SAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAEnD;IAED,SAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAShE;IAED,SAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAG9C;IAED,SAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,GAAE,MAAW,GAAG,MAAM,CASzE;IAED,SAAgB,MAAM,IAAI,MAAM,CAG/B;IAGD,SAAgB,OAAO,IAAI,MAAM,CAQhC;IAYD,SAAgB,eAAe,CAAC,MAAM,EAAE,MAAM,GAAG,GAAG,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,GAAG,GAAG,SAAS,CAiDtF;IAOD,SAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAO/C;IAED,SAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAuB7C;IAED,SAAgB,aAAa,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CASxD;IAED,SAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,GAAG,MAAM,CAEvE;IAED,SAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,CAG1E;IAED,SAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAMhF;IAED,SAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,CAWrE;IAED;;;OAGG;IACH,SAAgB,WAAW,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAMlD;IAED;;;OAGG;IACH,SAAgB,SAAS,CAAC,IAAI,EAAE,IAAI,GAAG,OAAO,CAM7C;CAaF"} \ No newline at end of file diff --git a/lib/Utils.js b/lib/Utils.js deleted file mode 100644 index b937ab9fe..000000000 --- a/lib/Utils.js +++ /dev/null @@ -1,238 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var Constants_1 = require("./Constants"); -var grammar_1 = require("./core/messages/grammar"); -var uri_1 = require("./core/messages/uri"); -var Utils; -(function (Utils) { - function defer() { - var deferred = {}; - deferred.promise = new Promise(function (resolve, reject) { - deferred.resolve = resolve; - deferred.reject = reject; - }); - return deferred; - } - Utils.defer = defer; - function reducePromises(arr, val) { - return arr.reduce(function (acc, fn) { - acc = acc.then(fn); - return acc; - }, Promise.resolve(val)); - } - Utils.reducePromises = reducePromises; - function str_utf8_length(str) { - return encodeURIComponent(str).replace(/%[A-F\d]{2}/g, "U").length; - } - Utils.str_utf8_length = str_utf8_length; - function generateFakeSDP(body) { - if (!body) { - return; - } - var start = body.indexOf("o="); - var end = body.indexOf("\r\n", start); - return "v=0\r\n" + body.slice(start, end) + "\r\ns=-\r\nt=0 0\r\nc=IN IP4 0.0.0.0"; - } - Utils.generateFakeSDP = generateFakeSDP; - function isDecimal(num) { - var numAsNum = parseInt(num, 10); - return !isNaN(numAsNum) && (parseFloat(num) === numAsNum); - } - Utils.isDecimal = isDecimal; - function createRandomToken(size, base) { - if (base === void 0) { base = 32; } - var token = ""; - for (var i = 0; i < size; i++) { - var r = Math.floor(Math.random() * base); - token += r.toString(base); - } - return token; - } - Utils.createRandomToken = createRandomToken; - function newTag() { - // used to use the constant in UA - return Utils.createRandomToken(10); - } - Utils.newTag = newTag; - // http://stackoverflow.com/users/109538/broofa - function newUUID() { - var UUID = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) { - var r = Math.floor(Math.random() * 16); - var v = c === "x" ? r : (r % 4 + 8); - return v.toString(16); - }); - return UUID; - } - Utils.newUUID = newUUID; - /* - * Normalize SIP URI. - * NOTE: It does not allow a SIP URI without username. - * Accepts 'sip', 'sips' and 'tel' URIs and convert them into 'sip'. - * Detects the domain part (if given) and properly hex-escapes the user portion. - * If the user portion has only 'tel' number symbols the user portion is clean of 'tel' visual separators. - * @private - * @param {String} target - * @param {String} [domain] - */ - function normalizeTarget(target, domain) { - // If no target is given then raise an error. - if (!target) { - return; - // If a SIP.URI instance is given then return it. - } - else if (target instanceof uri_1.URI) { - return target; - // If a string is given split it by '@': - // - Last fragment is the desired domain. - // - Otherwise append the given domain argument. - } - else if (typeof target === "string") { - var targetArray = target.split("@"); - var targetUser = void 0; - var targetDomain = void 0; - switch (targetArray.length) { - case 1: - if (!domain) { - return; - } - targetUser = target; - targetDomain = domain; - break; - case 2: - targetUser = targetArray[0]; - targetDomain = targetArray[1]; - break; - default: - targetUser = targetArray.slice(0, targetArray.length - 1).join("@"); - targetDomain = targetArray[targetArray.length - 1]; - } - // Remove the URI scheme (if present). - targetUser = targetUser.replace(/^(sips?|tel):/i, ""); - // Remove 'tel' visual separators if the user portion just contains 'tel' number symbols. - if (/^[\-\.\(\)]*\+?[0-9\-\.\(\)]+$/.test(targetUser)) { - targetUser = targetUser.replace(/[\-\.\(\)]/g, ""); - } - // Build the complete SIP URI. - target = Constants_1.C.SIP + ":" + Utils.escapeUser(targetUser) + "@" + targetDomain; - // Finally parse the resulting URI. - return grammar_1.Grammar.URIParse(target); - } - else { - return; - } - } - Utils.normalizeTarget = normalizeTarget; - /* - * Hex-escape a SIP URI user. - * @private - * @param {String} user - */ - function escapeUser(user) { - // Don't hex-escape ':' (%3A), '+' (%2B), '?' (%3F"), '/' (%2F). - return encodeURIComponent(decodeURIComponent(user)) - .replace(/%3A/ig, ":") - .replace(/%2B/ig, "+") - .replace(/%3F/ig, "?") - .replace(/%2F/ig, "/"); - } - Utils.escapeUser = escapeUser; - function headerize(str) { - var exceptions = { - "Call-Id": "Call-ID", - "Cseq": "CSeq", - "Min-Se": "Min-SE", - "Rack": "RAck", - "Rseq": "RSeq", - "Www-Authenticate": "WWW-Authenticate", - }; - var name = str.toLowerCase().replace(/_/g, "-").split("-"); - var parts = name.length; - var hname = ""; - for (var part = 0; part < parts; part++) { - if (part !== 0) { - hname += "-"; - } - hname += name[part].charAt(0).toUpperCase() + name[part].substring(1); - } - if (exceptions[hname]) { - hname = exceptions[hname]; - } - return hname; - } - Utils.headerize = headerize; - function sipErrorCause(statusCode) { - for (var cause in Constants_1.C.SIP_ERROR_CAUSES) { - if (Constants_1.C.SIP_ERROR_CAUSES[cause].indexOf(statusCode) !== -1) { - return Constants_1.C.causes[cause]; - } - } - return Constants_1.C.causes.SIP_FAILURE_CODE; - } - Utils.sipErrorCause = sipErrorCause; - function getReasonPhrase(code, specific) { - return specific || Constants_1.C.REASON_PHRASE[code] || ""; - } - Utils.getReasonPhrase = getReasonPhrase; - function getReasonHeaderValue(code, reason) { - reason = Utils.getReasonPhrase(code, reason); - return "SIP;cause=" + code + ';text="' + reason + '"'; - } - Utils.getReasonHeaderValue = getReasonHeaderValue; - function getCancelReason(code, reason) { - if (code && code < 200 || code > 699) { - throw new TypeError("Invalid statusCode: " + code); - } - else if (code) { - return Utils.getReasonHeaderValue(code, reason); - } - } - Utils.getCancelReason = getCancelReason; - function buildStatusLine(code, reason) { - // Validate code and reason values - if (!code || (code < 100 || code > 699)) { - throw new TypeError("Invalid statusCode: " + code); - } - else if (reason && typeof reason !== "string" && !(reason instanceof String)) { - throw new TypeError("Invalid reason: " + reason); - } - reason = Utils.getReasonPhrase(code, reason); - return "SIP/2.0 " + code + " " + reason + "\r\n"; - } - Utils.buildStatusLine = buildStatusLine; - /** - * Create a Body given a BodyObj. - * @param bodyObj Body Object - */ - function fromBodyObj(bodyObj) { - var content = bodyObj.body; - var contentType = bodyObj.contentType; - var contentDisposition = contentTypeToContentDisposition(contentType); - var body = { contentDisposition: contentDisposition, contentType: contentType, content: content }; - return body; - } - Utils.fromBodyObj = fromBodyObj; - /** - * Create a BodyObj given a Body. - * @param bodyObj Body Object - */ - function toBodyObj(body) { - var bodyObj = { - body: body.content, - contentType: body.contentType - }; - return bodyObj; - } - Utils.toBodyObj = toBodyObj; - // If the Content-Disposition header field is missing, bodies of - // Content-Type application/sdp imply the disposition "session", while - // other content types imply "render". - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - function contentTypeToContentDisposition(contentType) { - if (contentType === "application/sdp") { - return "session"; - } - else { - return "render"; - } - } -})(Utils = exports.Utils || (exports.Utils = {})); diff --git a/lib/Web/Modifiers.d.ts b/lib/Web/Modifiers.d.ts deleted file mode 100644 index edd7f2060..000000000 --- a/lib/Web/Modifiers.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { SessionDescriptionHandlerModifier } from "../session-description-handler"; -export declare function stripTcpCandidates(description: RTCSessionDescriptionInit): Promise; -export declare function stripTelephoneEvent(description: RTCSessionDescriptionInit): Promise; -export declare function cleanJitsiSdpImageattr(description: RTCSessionDescriptionInit): Promise; -export declare function stripG722(description: RTCSessionDescriptionInit): Promise; -export declare function stripRtpPayload(payload: string): SessionDescriptionHandlerModifier; -export declare function stripVideo(description: RTCSessionDescriptionInit): Promise; -export declare function addMidLines(description: RTCSessionDescriptionInit): Promise; -//# sourceMappingURL=Modifiers.d.ts.map \ No newline at end of file diff --git a/lib/Web/Modifiers.d.ts.map b/lib/Web/Modifiers.d.ts.map deleted file mode 100644 index f79b83443..000000000 --- a/lib/Web/Modifiers.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"Modifiers.d.ts","sourceRoot":"","sources":["../../src/Web/Modifiers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iCAAiC,EAAE,MAAM,gCAAgC,CAAC;AA4EnF,wBAAgB,kBAAkB,CAAC,WAAW,EAAE,yBAAyB,GAAG,OAAO,CAAC,yBAAyB,CAAC,CAG7G;AAED,wBAAgB,mBAAmB,CAAC,WAAW,EAAE,yBAAyB,GAAG,OAAO,CAAC,yBAAyB,CAAC,CAG9G;AAED,wBAAgB,sBAAsB,CAAC,WAAW,EAAE,yBAAyB,GAAG,OAAO,CAAC,yBAAyB,CAAC,CAGjH;AAED,wBAAgB,SAAS,CAAC,WAAW,EAAE,yBAAyB,GAAG,OAAO,CAAC,yBAAyB,CAAC,CAGpG;AAED,wBAAgB,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,iCAAiC,CAKlF;AAED,wBAAgB,UAAU,CAAC,WAAW,EAAE,yBAAyB,GAAG,OAAO,CAAC,yBAAyB,CAAC,CAGrG;AAED,wBAAgB,WAAW,CAAC,WAAW,EAAE,yBAAyB,GAAG,OAAO,CAAC,yBAAyB,CAAC,CAmBtG"} \ No newline at end of file diff --git a/lib/Web/Modifiers.js b/lib/Web/Modifiers.js deleted file mode 100644 index 97d2ec179..000000000 --- a/lib/Web/Modifiers.js +++ /dev/null @@ -1,121 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var stripPayload = function (sdp, payload) { - var mediaDescs = []; - var lines = sdp.split(/\r\n/); - var currentMediaDesc; - for (var i = 0; i < lines.length;) { - var line = lines[i]; - if (/^m=(?:audio|video)/.test(line)) { - currentMediaDesc = { - index: i, - stripped: [] - }; - mediaDescs.push(currentMediaDesc); - } - else if (currentMediaDesc) { - var rtpmap = /^a=rtpmap:(\d+) ([^/]+)\//.exec(line); - if (rtpmap && payload === rtpmap[2]) { - lines.splice(i, 1); - currentMediaDesc.stripped.push(rtpmap[1]); - continue; // Don't increment 'i' - } - } - i++; - } - for (var _i = 0, mediaDescs_1 = mediaDescs; _i < mediaDescs_1.length; _i++) { - var mediaDesc = mediaDescs_1[_i]; - var mline = lines[mediaDesc.index].split(" "); - // Ignore the first 3 parameters of the mline. The codec information is after that - for (var j = 3; j < mline.length;) { - if (mediaDesc.stripped.indexOf(mline[j]) !== -1) { - mline.splice(j, 1); - continue; - } - j++; - } - lines[mediaDesc.index] = mline.join(" "); - } - return lines.join("\r\n"); -}; -var stripMediaDescription = function (sdp, description) { - var descriptionRegExp = new RegExp("m=" + description + ".*$", "gm"); - var groupRegExp = new RegExp("^a=group:.*$", "gm"); - if (descriptionRegExp.test(sdp)) { - var midLineToRemove_1; - sdp = sdp.split(/^m=/gm).filter(function (section) { - if (section.substr(0, description.length) === description) { - midLineToRemove_1 = section.match(/^a=mid:.*$/gm); - if (midLineToRemove_1) { - var step = midLineToRemove_1[0].match(/:.+$/g); - if (step) { - midLineToRemove_1 = step[0].substr(1); - } - } - return false; - } - return true; - }).join("m="); - var groupLine = sdp.match(groupRegExp); - if (groupLine && groupLine.length === 1) { - var groupLinePortion = groupLine[0]; - var groupRegExpReplace = new RegExp("\ *" + midLineToRemove_1 + "[^\ ]*", "g"); - groupLinePortion = groupLinePortion.replace(groupRegExpReplace, ""); - sdp = sdp.split(groupRegExp).join(groupLinePortion); - } - } - return sdp; -}; -function stripTcpCandidates(description) { - description.sdp = (description.sdp || "").replace(/^a=candidate:\d+ \d+ tcp .*?\r\n/img, ""); - return Promise.resolve(description); -} -exports.stripTcpCandidates = stripTcpCandidates; -function stripTelephoneEvent(description) { - description.sdp = stripPayload(description.sdp || "", "telephone-event"); - return Promise.resolve(description); -} -exports.stripTelephoneEvent = stripTelephoneEvent; -function cleanJitsiSdpImageattr(description) { - description.sdp = (description.sdp || "").replace(/^(a=imageattr:.*?)(x|y)=\[0-/gm, "$1$2=[1:"); - return Promise.resolve(description); -} -exports.cleanJitsiSdpImageattr = cleanJitsiSdpImageattr; -function stripG722(description) { - description.sdp = stripPayload(description.sdp || "", "G722"); - return Promise.resolve(description); -} -exports.stripG722 = stripG722; -function stripRtpPayload(payload) { - return function (description) { - description.sdp = stripPayload(description.sdp || "", payload); - return Promise.resolve(description); - }; -} -exports.stripRtpPayload = stripRtpPayload; -function stripVideo(description) { - description.sdp = stripMediaDescription(description.sdp || "", "video"); - return Promise.resolve(description); -} -exports.stripVideo = stripVideo; -function addMidLines(description) { - var sdp = description.sdp || ""; - if (sdp.search(/^a=mid.*$/gm) === -1) { - var mlines_1 = sdp.match(/^m=.*$/gm); - var sdpArray_1 = sdp.split(/^m=.*$/gm); - if (mlines_1) { - mlines_1.forEach(function (elem, idx) { - mlines_1[idx] = elem + "\na=mid:" + idx; - }); - } - sdpArray_1.forEach(function (elem, idx) { - if (mlines_1 && mlines_1[idx]) { - sdpArray_1[idx] = elem + mlines_1[idx]; - } - }); - sdp = sdpArray_1.join(""); - description.sdp = sdp; - } - return Promise.resolve(description); -} -exports.addMidLines = addMidLines; diff --git a/lib/Web/SessionDescriptionHandler.d.ts b/lib/Web/SessionDescriptionHandler.d.ts deleted file mode 100644 index 0c553b5d9..000000000 --- a/lib/Web/SessionDescriptionHandler.d.ts +++ /dev/null @@ -1,124 +0,0 @@ -/// -import { EventEmitter } from "events"; -import { Session } from "../api/session"; -import { Logger } from "../core"; -import { TypeStrings } from "../Enums"; -import { InviteClientContext, InviteServerContext } from "../Session"; -import { BodyObj, SessionDescriptionHandler as SessionDescriptionHandlerDefinition, SessionDescriptionHandlerModifiers, SessionDescriptionHandlerOptions } from "../session-description-handler"; -import { SessionDescriptionHandlerObserver } from "./SessionDescriptionHandlerObserver"; -export interface WebSessionDescriptionHandlerOptions extends SessionDescriptionHandlerOptions { - peerConnectionOptions?: PeerConnectionOptions; - alwaysAcquireMediaFirst?: boolean; - disableAudioFallback?: boolean; - RTCOfferOptions?: any; - constraints?: MediaStreamConstraints; -} -export interface PeerConnectionOptions { - iceCheckingTimeout?: number; - rtcConfiguration?: RTCConfiguration; -} -export declare class SessionDescriptionHandler extends EventEmitter implements SessionDescriptionHandlerDefinition { - /** - * @param {SIP.Session} session - * @param {Object} [options] - */ - static defaultFactory(session: InviteClientContext | InviteServerContext | Session, options: any): SessionDescriptionHandler; - type: TypeStrings; - peerConnection: RTCPeerConnection; - private options; - private logger; - private observer; - private dtmfSender; - private shouldAcquireMedia; - private CONTENT_TYPE; - private direction; - private C; - private modifiers; - private iceGatheringDeferred; - private iceGatheringTimeout; - private iceGatheringTimer; - private constraints; - constructor(logger: Logger, observer: SessionDescriptionHandlerObserver, options: any); - /** - * Destructor - */ - close(): void; - /** - * Gets the local description from the underlying media implementation - * @param {Object} [options] Options object to be used by getDescription - * @param {MediaStreamConstraints} [options.constraints] MediaStreamConstraints - * https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints - * @param {Object} [options.peerConnectionOptions] If this is set it will recreate the peer - * connection with the new options - * @param {Array} [modifiers] Array with one time use description modifiers - * @returns {Promise} Promise that resolves with the local description to be used for the session - */ - getDescription(options?: WebSessionDescriptionHandlerOptions, modifiers?: SessionDescriptionHandlerModifiers): Promise; - /** - * Check if the Session Description Handler can handle the Content-Type described by a SIP Message - * @param {String} contentType The content type that is in the SIP Message - * @returns {boolean} - */ - hasDescription(contentType: string): boolean; - /** - * The modifier that should be used when the session would like to place the call on hold - * @param {String} [sdp] The description that will be modified - * @returns {Promise} Promise that resolves with modified SDP - */ - holdModifier(description: RTCSessionDescriptionInit): Promise; - /** - * Set the remote description to the underlying media implementation - * @param {String} sessionDescription The description provided by a SIP message to be set on the media implementation - * @param {Object} [options] Options object to be used by getDescription - * @param {MediaStreamConstraints} [options.constraints] MediaStreamConstraints - * https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints - * @param {Object} [options.peerConnectionOptions] If this is set it will recreate the peer - * connection with the new options - * @param {Array} [modifiers] Array with one time use description modifiers - * @returns {Promise} Promise that resolves once the description is set - */ - setDescription(sessionDescription: string, options?: WebSessionDescriptionHandlerOptions, modifiers?: SessionDescriptionHandlerModifiers): Promise; - /** - * Send DTMF via RTP (RFC 4733) - * @param {String} tones A string containing DTMF digits - * @param {Object} [options] Options object to be used by sendDtmf - * @returns {boolean} true if DTMF send is successful, false otherwise - */ - sendDtmf(tones: string, options?: any): boolean; - /** - * Get the direction of the session description - * @returns {String} direction of the description - */ - getDirection(): string; - on(event: "getDescription" | "setDescription", listener: (description: RTCSessionDescriptionInit) => void): this; - on(event: "peerConnection-setRemoteDescriptionFailed", listener: (error: any) => void): this; - on(event: "setRemoteDescription", listener: (receivers: Array) => void): this; - on(event: "confirmed", listener: (sessionDescriptionHandler: SessionDescriptionHandler) => void): this; - on(event: "peerConnection-createAnswerFailed" | "peerConnection-createOfferFailed", listener: (error: any) => void): this; - on(event: "peerConnection-SetLocalDescriptionFailed", listener: (error: any) => void): this; - on(event: "addTrack", listener: (track: MediaStreamTrack) => void): this; - on(event: "addStream", listener: (track: MediaStream) => void): this; - on(event: "iceCandidate", listener: (candidate: RTCIceCandidate) => void): this; - on(event: "iceConnection" | "iceConnectionChecking" | "iceConnectionConnected" | "iceConnectionCompleted" | "iceConnectionFailed" | "iceConnectionDisconnected" | "iceConectionClosed", listener: (sessionDescriptionHandler: SessionDescriptionHandler) => void): this; - on(event: "iceGathering" | "iceGatheringComplete", listener: (sessionDescriptionHandler: SessionDescriptionHandler) => void): this; - on(event: "userMediaRequest", listener: (constraints: MediaStreamConstraints) => void): this; - on(event: "userMedia", listener: (streams: MediaStream) => void): this; - on(event: "userMediaFailed", listener: (error: any) => void): this; - protected getMediaStream(constraints: MediaStreamConstraints): Promise; - private createOfferOrAnswer; - private createRTCSessionDescriptionInit; - private addDefaultIceCheckingTimeout; - private addDefaultIceServers; - private checkAndDefaultConstraints; - private hasBrowserTrackSupport; - private hasBrowserGetSenderSupport; - private initPeerConnection; - private acquire; - private hasOffer; - private isIceGatheringComplete; - private resetIceGatheringComplete; - private setDirection; - private triggerIceGatheringComplete; - private waitForIceGatheringComplete; -} -//# sourceMappingURL=SessionDescriptionHandler.d.ts.map \ No newline at end of file diff --git a/lib/Web/SessionDescriptionHandler.d.ts.map b/lib/Web/SessionDescriptionHandler.d.ts.map deleted file mode 100644 index 3329c9e55..000000000 --- a/lib/Web/SessionDescriptionHandler.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"SessionDescriptionHandler.d.ts","sourceRoot":"","sources":["../../src/Web/SessionDescriptionHandler.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAEtC,OAAO,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AACzC,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAEvC,OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AACtE,OAAO,EACL,OAAO,EACP,yBAAyB,IAAI,mCAAmC,EAChE,kCAAkC,EAClC,gCAAgC,EACjC,MAAM,gCAAgC,CAAC;AAIxC,OAAO,EAAE,iCAAiC,EAAE,MAAM,qCAAqC,CAAC;AAExF,MAAM,WAAW,mCAAoC,SAAQ,gCAAgC;IAC3F,qBAAqB,CAAC,EAAE,qBAAqB,CAAC;IAC9C,uBAAuB,CAAC,EAAE,OAAO,CAAC;IAClC,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAC/B,eAAe,CAAC,EAAE,GAAG,CAAC;IACtB,WAAW,CAAC,EAAE,sBAAsB,CAAC;CACtC;AAED,MAAM,WAAW,qBAAqB;IACpC,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,gBAAgB,CAAC,EAAE,gBAAgB,CAAC;CACrC;AAQD,qBAAa,yBAA0B,SAAQ,YAAa,YAAW,mCAAmC;IACxG;;;OAGG;WACW,cAAc,CAC1B,OAAO,EAAE,mBAAmB,GAAG,mBAAmB,GAAG,OAAO,EAC5D,OAAO,EAAE,GAAG,GACX,yBAAyB;IASrB,IAAI,EAAE,WAAW,CAAC;IAClB,cAAc,EAAG,iBAAiB,CAAC;IAC1C,OAAO,CAAC,OAAO,CAAM;IACrB,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,QAAQ,CAAoC;IACpD,OAAO,CAAC,UAAU,CAAM;IACxB,OAAO,CAAC,kBAAkB,CAAU;IACpC,OAAO,CAAC,YAAY,CAAS;IAC7B,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,CAAC,CAAM;IACf,OAAO,CAAC,SAAS,CAAqC;IACtD,OAAO,CAAC,oBAAoB,CAAkC;IAC9D,OAAO,CAAC,mBAAmB,CAAU;IACrC,OAAO,CAAC,iBAAiB,CAAkB;IAC3C,OAAO,CAAC,WAAW,CAAyB;gBAEhC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,iCAAiC,EAAE,OAAO,EAAE,GAAG;IA0CrF;;OAEG;IACI,KAAK,IAAI,IAAI;IAqCpB;;;;;;;;;OASG;IACI,cAAc,CACnB,OAAO,GAAE,mCAAwC,EACjD,SAAS,GAAE,kCAAuC,GACjD,OAAO,CAAC,OAAO,CAAC;IAqCnB;;;;OAIG;IACI,cAAc,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO;IAInD;;;;OAIG;IACI,YAAY,CAAC,WAAW,EAAE,yBAAyB,GAAG,OAAO,CAAC,yBAAyB,CAAC;IAc/F;;;;;;;;;;OAUG;IACI,cAAc,CACnB,kBAAkB,EAAE,MAAM,EAC1B,OAAO,GAAE,mCAAwC,EACjD,SAAS,GAAE,kCAAuC,GACjD,OAAO,CAAC,IAAI,CAAC;IAiEhB;;;;;OAKG;IACI,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,GAAE,GAAQ,GAAG,OAAO;IAiC1D;;;OAGG;IACI,YAAY,IAAI,MAAM;IAItB,EAAE,CACP,KAAK,EAAE,gBAAgB,GAAG,gBAAgB,EAC1C,QAAQ,EAAE,CAAC,WAAW,EAAE,yBAAyB,KAAK,IAAI,GACzD,IAAI;IACA,EAAE,CACP,KAAK,EAAE,2CAA2C,EAClD,QAAQ,EAAE,CAAC,KAAK,EAAE,GAAG,KAAK,IAAI,GAC7B,IAAI;IACA,EAAE,CAAC,KAAK,EAAE,sBAAsB,EAAE,QAAQ,EAAE,CAAC,SAAS,EAAE,KAAK,CAAC,cAAc,CAAC,KAAK,IAAI,GAAG,IAAI;IAC7F,EAAE,CAAC,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,CAAC,yBAAyB,EAAE,yBAAyB,KAAK,IAAI,GAAG,IAAI;IAEtG,EAAE,CAEP,KAAK,EAAE,mCAAmC,GAAG,kCAAkC,EAC/E,QAAQ,EAAE,CAAC,KAAK,EAAE,GAAG,KAAK,IAAI,GAC7B,IAAI;IAEA,EAAE,CAAC,KAAK,EAAE,0CAA0C,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE,GAAG,KAAK,IAAI,GAAG,IAAI;IAC3F,EAAE,CAAC,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE,gBAAgB,KAAK,IAAI,GAAG,IAAI;IACxE,EAAE,CAAC,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE,WAAW,KAAK,IAAI,GAAG,IAAI;IACpE,EAAE,CAAC,KAAK,EAAE,cAAc,EAAE,QAAQ,EAAE,CAAC,SAAS,EAAE,eAAe,KAAK,IAAI,GAAG,IAAI;IAC/E,EAAE,CAEP,KAAK,EACL,eAAe,GACf,uBAAuB,GACvB,wBAAwB,GACxB,wBAAwB,GACxB,qBAAqB,GACrB,2BAA2B,GAC3B,oBAAoB,EACpB,QAAQ,EAAE,CAAC,yBAAyB,EAAE,yBAAyB,KAAK,IAAI,GACvE,IAAI;IACA,EAAE,CACP,KAAK,EAAE,cAAc,GAAG,sBAAsB,EAC9C,QAAQ,EAAE,CAAC,yBAAyB,EAAE,yBAAyB,KAC5D,IAAI,GAAG,IAAI;IAET,EAAE,CAAC,KAAK,EAAE,kBAAkB,EAAE,QAAQ,EAAE,CAAC,WAAW,EAAE,sBAAsB,KAAK,IAAI,GAAG,IAAI;IAC5F,EAAE,CAAC,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,CAAC,OAAO,EAAE,WAAW,KAAK,IAAI,GAAG,IAAI;IAEtE,EAAE,CAAC,KAAK,EAAE,iBAAiB,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE,GAAG,KAAK,IAAI,GAAG,IAAI;IAGzE,SAAS,CAAC,cAAc,CAAC,WAAW,EAAE,sBAAsB,GAAG,OAAO,CAAC,WAAW,CAAC;IAKnF,OAAO,CAAC,mBAAmB;IA2D3B,OAAO,CAAC,+BAA+B;IASvC,OAAO,CAAC,4BAA4B;IAOpC,OAAO,CAAC,oBAAoB;IAO5B,OAAO,CAAC,0BAA0B;IAWlC,OAAO,CAAC,sBAAsB;IAI9B,OAAO,CAAC,0BAA0B;IAIlC,OAAO,CAAC,kBAAkB;IAiG1B,OAAO,CAAC,OAAO;IAgFf,OAAO,CAAC,QAAQ;IAMhB,OAAO,CAAC,sBAAsB;IAI9B,OAAO,CAAC,yBAAyB;IAgBjC,OAAO,CAAC,YAAY;IAsBpB,OAAO,CAAC,2BAA2B;IAgBnC,OAAO,CAAC,2BAA2B;CAWpC"} \ No newline at end of file diff --git a/lib/Web/SessionDescriptionHandler.js b/lib/Web/SessionDescriptionHandler.js deleted file mode 100644 index 058ea62c3..000000000 --- a/lib/Web/SessionDescriptionHandler.js +++ /dev/null @@ -1,619 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var events_1 = require("events"); -var session_1 = require("../api/session"); -var Enums_1 = require("../Enums"); -var Exceptions_1 = require("../Exceptions"); -var Utils_1 = require("../Utils"); -var Modifiers = tslib_1.__importStar(require("./Modifiers")); -var SessionDescriptionHandlerObserver_1 = require("./SessionDescriptionHandlerObserver"); -/* SessionDescriptionHandler - * @class PeerConnection helper Class. - * @param {SIP.Session} session - * @param {Object} [options] - */ -var SessionDescriptionHandler = /** @class */ (function (_super) { - tslib_1.__extends(SessionDescriptionHandler, _super); - function SessionDescriptionHandler(logger, observer, options) { - var _this = _super.call(this) || this; - _this.type = Enums_1.TypeStrings.SessionDescriptionHandler; - // TODO: Validate the options - _this.options = options || {}; - _this.logger = logger; - _this.observer = observer; - _this.dtmfSender = undefined; - _this.shouldAcquireMedia = true; - _this.CONTENT_TYPE = "application/sdp"; - _this.C = { - DIRECTION: { - NULL: null, - SENDRECV: "sendrecv", - SENDONLY: "sendonly", - RECVONLY: "recvonly", - INACTIVE: "inactive" - } - }; - _this.logger.log("SessionDescriptionHandlerOptions: " + JSON.stringify(_this.options)); - _this.direction = _this.C.DIRECTION.NULL; - _this.modifiers = _this.options.modifiers || []; - if (!Array.isArray(_this.modifiers)) { - _this.modifiers = [_this.modifiers]; - } - _this.iceGatheringTimeout = false; - _this.initPeerConnection(_this.options.peerConnectionOptions); - _this.constraints = _this.checkAndDefaultConstraints(_this.options.constraints); - return _this; - } - /** - * @param {SIP.Session} session - * @param {Object} [options] - */ - SessionDescriptionHandler.defaultFactory = function (session, options) { - var logger = (session instanceof session_1.Session) ? - session.userAgent.getLogger("sip.sessionDescriptionHandler", session.id) : - session.ua.getLogger("sip.invitecontext.sessionDescriptionHandler", session.id); - var observer = new SessionDescriptionHandlerObserver_1.SessionDescriptionHandlerObserver(session, options); - return new SessionDescriptionHandler(logger, observer, options); - }; - // Functions the sesssion can use - /** - * Destructor - */ - SessionDescriptionHandler.prototype.close = function () { - this.logger.log("closing PeerConnection"); - // have to check signalingState since this.close() gets called multiple times - if (this.peerConnection && this.peerConnection.signalingState !== "closed") { - if (this.peerConnection.getSenders) { - this.peerConnection.getSenders().forEach(function (sender) { - if (sender.track) { - sender.track.stop(); - } - }); - } - else { - this.logger.warn("Using getLocalStreams which is deprecated"); - this.peerConnection.getLocalStreams().forEach(function (stream) { - stream.getTracks().forEach(function (track) { - track.stop(); - }); - }); - } - if (this.peerConnection.getReceivers) { - this.peerConnection.getReceivers().forEach(function (receiver) { - if (receiver.track) { - receiver.track.stop(); - } - }); - } - else { - this.logger.warn("Using getRemoteStreams which is deprecated"); - this.peerConnection.getRemoteStreams().forEach(function (stream) { - stream.getTracks().forEach(function (track) { - track.stop(); - }); - }); - } - this.resetIceGatheringComplete(); - this.peerConnection.close(); - } - }; - /** - * Gets the local description from the underlying media implementation - * @param {Object} [options] Options object to be used by getDescription - * @param {MediaStreamConstraints} [options.constraints] MediaStreamConstraints - * https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints - * @param {Object} [options.peerConnectionOptions] If this is set it will recreate the peer - * connection with the new options - * @param {Array} [modifiers] Array with one time use description modifiers - * @returns {Promise} Promise that resolves with the local description to be used for the session - */ - SessionDescriptionHandler.prototype.getDescription = function (options, modifiers) { - var _this = this; - if (options === void 0) { options = {}; } - if (modifiers === void 0) { modifiers = []; } - if (options.peerConnectionOptions) { - this.initPeerConnection(options.peerConnectionOptions); - } - // Merge passed constraints with saved constraints and save - var newConstraints = Object.assign({}, this.constraints, options.constraints); - newConstraints = this.checkAndDefaultConstraints(newConstraints); - if (JSON.stringify(newConstraints) !== JSON.stringify(this.constraints)) { - this.constraints = newConstraints; - this.shouldAcquireMedia = true; - } - if (!Array.isArray(modifiers)) { - modifiers = [modifiers]; - } - modifiers = modifiers.concat(this.modifiers); - return Promise.resolve().then(function () { - if (_this.shouldAcquireMedia) { - return _this.acquire(_this.constraints).then(function () { - _this.shouldAcquireMedia = false; - }); - } - }).then(function () { return _this.createOfferOrAnswer(options.RTCOfferOptions, modifiers); }) - .then(function (description) { - if (description.sdp === undefined) { - throw new Exceptions_1.Exceptions.SessionDescriptionHandlerError("getDescription", undefined, "SDP undefined"); - } - _this.emit("getDescription", description); - return { - body: description.sdp, - contentType: _this.CONTENT_TYPE - }; - }); - }; - /** - * Check if the Session Description Handler can handle the Content-Type described by a SIP Message - * @param {String} contentType The content type that is in the SIP Message - * @returns {boolean} - */ - SessionDescriptionHandler.prototype.hasDescription = function (contentType) { - return contentType === this.CONTENT_TYPE; - }; - /** - * The modifier that should be used when the session would like to place the call on hold - * @param {String} [sdp] The description that will be modified - * @returns {Promise} Promise that resolves with modified SDP - */ - SessionDescriptionHandler.prototype.holdModifier = function (description) { - if (!description.sdp) { - return Promise.resolve(description); - } - if (!(/a=(sendrecv|sendonly|recvonly|inactive)/).test(description.sdp)) { - description.sdp = description.sdp.replace(/(m=[^\r]*\r\n)/g, "$1a=sendonly\r\n"); - } - else { - description.sdp = description.sdp.replace(/a=sendrecv\r\n/g, "a=sendonly\r\n"); - description.sdp = description.sdp.replace(/a=recvonly\r\n/g, "a=inactive\r\n"); - } - return Promise.resolve(description); - }; - /** - * Set the remote description to the underlying media implementation - * @param {String} sessionDescription The description provided by a SIP message to be set on the media implementation - * @param {Object} [options] Options object to be used by getDescription - * @param {MediaStreamConstraints} [options.constraints] MediaStreamConstraints - * https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints - * @param {Object} [options.peerConnectionOptions] If this is set it will recreate the peer - * connection with the new options - * @param {Array} [modifiers] Array with one time use description modifiers - * @returns {Promise} Promise that resolves once the description is set - */ - SessionDescriptionHandler.prototype.setDescription = function (sessionDescription, options, modifiers) { - var _this = this; - if (options === void 0) { options = {}; } - if (modifiers === void 0) { modifiers = []; } - if (options.peerConnectionOptions) { - this.initPeerConnection(options.peerConnectionOptions); - } - if (!Array.isArray(modifiers)) { - modifiers = [modifiers]; - } - modifiers = modifiers.concat(this.modifiers); - var description = { - type: this.hasOffer("local") ? "answer" : "offer", - sdp: sessionDescription - }; - return Promise.resolve().then(function () { - // Media should be acquired in getDescription unless we need to do it sooner for some reason (FF61+) - if (_this.shouldAcquireMedia && _this.options.alwaysAcquireMediaFirst) { - return _this.acquire(_this.constraints).then(function () { - _this.shouldAcquireMedia = false; - }); - } - }).then(function () { return Utils_1.Utils.reducePromises(modifiers, description); }) - .catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("setDescription", e, "The modifiers did not resolve successfully"); - _this.logger.error(error.message); - _this.emit("peerConnection-setRemoteDescriptionFailed", error); - throw error; - }).then(function (modifiedDescription) { - _this.emit("setDescription", modifiedDescription); - return _this.peerConnection.setRemoteDescription(modifiedDescription); - }).catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - // Check the original SDP for video, and ensure that we have want to do audio fallback - if ((/^m=video.+$/gm).test(sessionDescription) && !options.disableAudioFallback) { - // Do not try to audio fallback again - options.disableAudioFallback = true; - // Remove video first, then do the other modifiers - return _this.setDescription(sessionDescription, options, [Modifiers.stripVideo].concat(modifiers)); - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("setDescription", e); - if (error.error) { - _this.logger.error(error.error); - } - _this.emit("peerConnection-setRemoteDescriptionFailed", error); - throw error; - }).then(function () { - if (_this.peerConnection.getReceivers) { - _this.emit("setRemoteDescription", _this.peerConnection.getReceivers()); - } - else { - _this.emit("setRemoteDescription", _this.peerConnection.getRemoteStreams()); - } - _this.emit("confirmed", _this); - }); - }; - /** - * Send DTMF via RTP (RFC 4733) - * @param {String} tones A string containing DTMF digits - * @param {Object} [options] Options object to be used by sendDtmf - * @returns {boolean} true if DTMF send is successful, false otherwise - */ - SessionDescriptionHandler.prototype.sendDtmf = function (tones, options) { - if (options === void 0) { options = {}; } - if (!this.dtmfSender && this.hasBrowserGetSenderSupport()) { - var senders = this.peerConnection.getSenders(); - if (senders.length > 0) { - this.dtmfSender = senders[0].dtmf; - } - } - if (!this.dtmfSender && this.hasBrowserTrackSupport()) { - var streams = this.peerConnection.getLocalStreams(); - if (streams.length > 0) { - var audioTracks = streams[0].getAudioTracks(); - if (audioTracks.length > 0) { - this.dtmfSender = this.peerConnection.createDTMFSender(audioTracks[0]); - } - } - } - if (!this.dtmfSender) { - return false; - } - try { - this.dtmfSender.insertDTMF(tones, options.duration, options.interToneGap); - } - catch (e) { - if (e.type === "InvalidStateError" || e.type === "InvalidCharacterError") { - this.logger.error(e); - return false; - } - else { - throw e; - } - } - this.logger.log("DTMF sent via RTP: " + tones.toString()); - return true; - }; - /** - * Get the direction of the session description - * @returns {String} direction of the description - */ - SessionDescriptionHandler.prototype.getDirection = function () { - return this.direction; - }; - SessionDescriptionHandler.prototype.on = function (name, callback) { return _super.prototype.on.call(this, name, callback); }; - SessionDescriptionHandler.prototype.getMediaStream = function (constraints) { - return navigator.mediaDevices.getUserMedia(constraints); - }; - // Internal functions - SessionDescriptionHandler.prototype.createOfferOrAnswer = function (RTCOfferOptions, modifiers) { - var _this = this; - if (RTCOfferOptions === void 0) { RTCOfferOptions = {}; } - if (modifiers === void 0) { modifiers = []; } - var methodName = this.hasOffer("remote") ? "createAnswer" : "createOffer"; - var pc = this.peerConnection; - this.logger.log(methodName); - var method = this.hasOffer("remote") ? pc.createAnswer : pc.createOffer; - return method.apply(pc, RTCOfferOptions).catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer", e, "peerConnection-" + methodName + "Failed"); - _this.emit("peerConnection-" + methodName + "Failed", error); - throw error; - }).then(function (sdp) { - return Utils_1.Utils.reducePromises(modifiers, _this.createRTCSessionDescriptionInit(sdp)); - }).then(function (sdp) { - _this.resetIceGatheringComplete(); - _this.logger.log("Setting local sdp."); - _this.logger.log("sdp is " + sdp.sdp || "undefined"); - return pc.setLocalDescription(sdp); - }).catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer", e, "peerConnection-SetLocalDescriptionFailed"); - _this.emit("peerConnection-SetLocalDescriptionFailed", error); - throw error; - }).then(function () { return _this.waitForIceGatheringComplete(); }) - .then(function () { - if (!_this.peerConnection.localDescription) { - throw new Exceptions_1.Exceptions.SessionDescriptionHandlerError("Missing local description"); - } - var localDescription = _this.createRTCSessionDescriptionInit(_this.peerConnection.localDescription); - return Utils_1.Utils.reducePromises(modifiers, localDescription); - }).then(function (localDescription) { - _this.setDirection(localDescription.sdp || ""); - return localDescription; - }).catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer", e); - _this.logger.error(error.toString()); - throw error; - }); - }; - // Creates an RTCSessionDescriptionInit from an RTCSessionDescription - SessionDescriptionHandler.prototype.createRTCSessionDescriptionInit = function (RTCSessionDescription) { - return { - type: RTCSessionDescription.type, - sdp: RTCSessionDescription.sdp - }; - }; - SessionDescriptionHandler.prototype.addDefaultIceCheckingTimeout = function (peerConnectionOptions) { - if (peerConnectionOptions.iceCheckingTimeout === undefined) { - peerConnectionOptions.iceCheckingTimeout = 5000; - } - return peerConnectionOptions; - }; - SessionDescriptionHandler.prototype.addDefaultIceServers = function (rtcConfiguration) { - if (!rtcConfiguration.iceServers) { - rtcConfiguration.iceServers = [{ urls: "stun:stun.l.google.com:19302" }]; - } - return rtcConfiguration; - }; - SessionDescriptionHandler.prototype.checkAndDefaultConstraints = function (constraints) { - var defaultConstraints = { audio: true, video: !this.options.alwaysAcquireMediaFirst }; - constraints = constraints || defaultConstraints; - // Empty object check - if (Object.keys(constraints).length === 0 && constraints.constructor === Object) { - return defaultConstraints; - } - return constraints; - }; - SessionDescriptionHandler.prototype.hasBrowserTrackSupport = function () { - return Boolean(this.peerConnection.addTrack); - }; - SessionDescriptionHandler.prototype.hasBrowserGetSenderSupport = function () { - return Boolean(this.peerConnection.getSenders); - }; - SessionDescriptionHandler.prototype.initPeerConnection = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - options = this.addDefaultIceCheckingTimeout(options); - options.rtcConfiguration = options.rtcConfiguration || {}; - options.rtcConfiguration = this.addDefaultIceServers(options.rtcConfiguration); - this.logger.log("initPeerConnection"); - if (this.peerConnection) { - this.logger.log("Already have a peer connection for this session. Tearing down."); - this.resetIceGatheringComplete(); - this.peerConnection.close(); - } - this.peerConnection = new RTCPeerConnection(options.rtcConfiguration); - this.logger.log("New peer connection created"); - if ("ontrack" in this.peerConnection) { - this.peerConnection.addEventListener("track", function (e) { - _this.logger.log("track added"); - _this.observer.trackAdded(); - _this.emit("addTrack", e); - }); - } - else { - this.logger.warn("Using onaddstream which is deprecated"); - this.peerConnection.onaddstream = function (e) { - _this.logger.log("stream added"); - _this.emit("addStream", e); - }; - } - this.peerConnection.onicecandidate = function (e) { - _this.emit("iceCandidate", e); - if (e.candidate) { - _this.logger.log("ICE candidate received: " + - (e.candidate.candidate === null ? null : e.candidate.candidate.trim())); - } - else if (e.candidate === null) { - // indicates the end of candidate gathering - _this.logger.log("ICE candidate gathering complete"); - _this.triggerIceGatheringComplete(); - } - }; - this.peerConnection.onicegatheringstatechange = function () { - _this.logger.log("RTCIceGatheringState changed: " + _this.peerConnection.iceGatheringState); - switch (_this.peerConnection.iceGatheringState) { - case "gathering": - _this.emit("iceGathering", _this); - if (!_this.iceGatheringTimer && options.iceCheckingTimeout) { - _this.iceGatheringTimeout = false; - _this.iceGatheringTimer = setTimeout(function () { - _this.logger.log("RTCIceChecking Timeout Triggered after " + options.iceCheckingTimeout + " milliseconds"); - _this.iceGatheringTimeout = true; - _this.triggerIceGatheringComplete(); - }, options.iceCheckingTimeout); - } - break; - case "complete": - _this.triggerIceGatheringComplete(); - break; - } - }; - this.peerConnection.oniceconnectionstatechange = function () { - var stateEvent; - switch (_this.peerConnection.iceConnectionState) { - case "new": - stateEvent = "iceConnection"; - break; - case "checking": - stateEvent = "iceConnectionChecking"; - break; - case "connected": - stateEvent = "iceConnectionConnected"; - break; - case "completed": - stateEvent = "iceConnectionCompleted"; - break; - case "failed": - stateEvent = "iceConnectionFailed"; - break; - case "disconnected": - stateEvent = "iceConnectionDisconnected"; - break; - case "closed": - stateEvent = "iceConnectionClosed"; - break; - default: - _this.logger.warn("Unknown iceConnection state: " + _this.peerConnection.iceConnectionState); - return; - } - _this.logger.log("ICE Connection State changed to " + stateEvent); - _this.emit(stateEvent, _this); - }; - }; - SessionDescriptionHandler.prototype.acquire = function (constraints) { - var _this = this; - // Default audio & video to true - constraints = this.checkAndDefaultConstraints(constraints); - return new Promise(function (resolve, reject) { - /* - * Make the call asynchronous, so that ICCs have a chance - * to define callbacks to `userMediaRequest` - */ - _this.logger.log("acquiring local media"); - _this.emit("userMediaRequest", constraints); - if (constraints.audio || constraints.video) { - _this.getMediaStream(constraints).then(function (streams) { - _this.observer.trackAdded(); - _this.emit("userMedia", streams); - resolve(streams); - }).catch(function (e) { - _this.emit("userMediaFailed", e); - reject(e); - }); - } - else { - // Local streams were explicitly excluded. - resolve([]); - } - }).catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("acquire", e, "unable to acquire streams"); - _this.logger.error(error.message); - if (error.error) { - _this.logger.error(error.error); - } - throw error; - }).then(function (streams) { - _this.logger.log("acquired local media streams"); - // Remove old tracks - if (_this.peerConnection.removeTrack) { - _this.peerConnection.getSenders().forEach(function (sender) { - _this.peerConnection.removeTrack(sender); - }); - } - return streams; - }).catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("acquire", e, "error removing streams"); - _this.logger.error(error.message); - if (error.error) { - _this.logger.error(error.error); - } - throw error; - }).then(function (streams) { - var streamsArr = [].concat(streams); - streamsArr.forEach(function (stream) { - if (_this.peerConnection.addTrack) { - stream.getTracks().forEach(function (track) { - _this.peerConnection.addTrack(track, stream); - }); - } - else { - // Chrome 59 does not support addTrack - _this.peerConnection.addStream(stream); - } - }); - return Promise.resolve(); - }).catch(function (e) { - if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { - throw e; - } - var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("acquire", e, "error adding stream"); - _this.logger.error(error.message); - if (error.error) { - _this.logger.error(error.error); - } - throw error; - }); - }; - SessionDescriptionHandler.prototype.hasOffer = function (where) { - var offerState = "have-" + where + "-offer"; - return this.peerConnection.signalingState === offerState; - }; - // ICE gathering state handling - SessionDescriptionHandler.prototype.isIceGatheringComplete = function () { - return this.peerConnection.iceGatheringState === "complete" || this.iceGatheringTimeout; - }; - SessionDescriptionHandler.prototype.resetIceGatheringComplete = function () { - this.iceGatheringTimeout = false; - this.logger.log("resetIceGatheringComplete"); - if (this.iceGatheringTimer) { - clearTimeout(this.iceGatheringTimer); - this.iceGatheringTimer = undefined; - } - if (this.iceGatheringDeferred) { - this.iceGatheringDeferred.reject(); - this.iceGatheringDeferred = undefined; - } - }; - SessionDescriptionHandler.prototype.setDirection = function (sdp) { - var match = sdp.match(/a=(sendrecv|sendonly|recvonly|inactive)/); - if (match === null) { - this.direction = this.C.DIRECTION.NULL; - this.observer.directionChanged(); - return; - } - var direction = match[1]; - switch (direction) { - case this.C.DIRECTION.SENDRECV: - case this.C.DIRECTION.SENDONLY: - case this.C.DIRECTION.RECVONLY: - case this.C.DIRECTION.INACTIVE: - this.direction = direction; - break; - default: - this.direction = this.C.DIRECTION.NULL; - break; - } - this.observer.directionChanged(); - }; - SessionDescriptionHandler.prototype.triggerIceGatheringComplete = function () { - if (this.isIceGatheringComplete()) { - this.emit("iceGatheringComplete", this); - if (this.iceGatheringTimer) { - clearTimeout(this.iceGatheringTimer); - this.iceGatheringTimer = undefined; - } - if (this.iceGatheringDeferred) { - this.iceGatheringDeferred.resolve(); - this.iceGatheringDeferred = undefined; - } - } - }; - SessionDescriptionHandler.prototype.waitForIceGatheringComplete = function () { - this.logger.log("waitForIceGatheringComplete"); - if (this.isIceGatheringComplete()) { - this.logger.log("ICE is already complete. Return resolved."); - return Promise.resolve(); - } - else if (!this.iceGatheringDeferred) { - this.iceGatheringDeferred = Utils_1.Utils.defer(); - } - this.logger.log("ICE is not complete. Returning promise"); - return this.iceGatheringDeferred ? this.iceGatheringDeferred.promise : Promise.resolve(); - }; - return SessionDescriptionHandler; -}(events_1.EventEmitter)); -exports.SessionDescriptionHandler = SessionDescriptionHandler; diff --git a/lib/Web/SessionDescriptionHandlerObserver.d.ts b/lib/Web/SessionDescriptionHandlerObserver.d.ts deleted file mode 100644 index 7255f3056..000000000 --- a/lib/Web/SessionDescriptionHandlerObserver.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { Session } from "../api/session"; -import { TypeStrings } from "../Enums"; -import { InviteClientContext, InviteServerContext } from "../Session"; -export declare class SessionDescriptionHandlerObserver { - type: TypeStrings; - private session; - private options; - constructor(session: InviteClientContext | InviteServerContext | Session, options: any); - trackAdded(): void; - directionChanged(): void; -} -//# sourceMappingURL=SessionDescriptionHandlerObserver.d.ts.map \ No newline at end of file diff --git a/lib/Web/SessionDescriptionHandlerObserver.d.ts.map b/lib/Web/SessionDescriptionHandlerObserver.d.ts.map deleted file mode 100644 index 8309a0816..000000000 --- a/lib/Web/SessionDescriptionHandlerObserver.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"SessionDescriptionHandlerObserver.d.ts","sourceRoot":"","sources":["../../src/Web/SessionDescriptionHandlerObserver.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AACzC,OAAO,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AACvC,OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAQtE,qBAAa,iCAAiC;IACrC,IAAI,EAAE,WAAW,CAAC;IACzB,OAAO,CAAC,OAAO,CAAsD;IACrE,OAAO,CAAC,OAAO,CAAM;gBAET,OAAO,EAAE,mBAAmB,GAAG,mBAAmB,GAAG,OAAO,EAAE,OAAO,EAAE,GAAG;IAM/E,UAAU,IAAI,IAAI;IAIlB,gBAAgB,IAAI,IAAI;CAGhC"} \ No newline at end of file diff --git a/lib/Web/SessionDescriptionHandlerObserver.js b/lib/Web/SessionDescriptionHandlerObserver.js deleted file mode 100644 index d410c8968..000000000 --- a/lib/Web/SessionDescriptionHandlerObserver.js +++ /dev/null @@ -1,23 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var Enums_1 = require("../Enums"); -/* SessionDescriptionHandlerObserver - * @class SessionDescriptionHandler Observer Class. - * @param {SIP.Session} session - * @param {Object} [options] - */ -var SessionDescriptionHandlerObserver = /** @class */ (function () { - function SessionDescriptionHandlerObserver(session, options) { - this.type = Enums_1.TypeStrings.SessionDescriptionHandlerObserver; - this.session = session; - this.options = options; - } - SessionDescriptionHandlerObserver.prototype.trackAdded = function () { - this.session.emit("trackAdded"); - }; - SessionDescriptionHandlerObserver.prototype.directionChanged = function () { - this.session.emit("directionChanged"); - }; - return SessionDescriptionHandlerObserver; -}()); -exports.SessionDescriptionHandlerObserver = SessionDescriptionHandlerObserver; diff --git a/lib/Web/Simple.d.ts b/lib/Web/Simple.d.ts deleted file mode 100644 index ea693e965..000000000 --- a/lib/Web/Simple.d.ts +++ /dev/null @@ -1,46 +0,0 @@ -/// -import { EventEmitter } from "events"; -import { Logger } from "../core"; -import { InviteClientContext, InviteServerContext } from "../Session"; -import { UA } from "../UA"; -export declare enum SimpleStatus { - STATUS_NULL = 0, - STATUS_NEW = 1, - STATUS_CONNECTING = 2, - STATUS_CONNECTED = 3, - STATUS_COMPLETED = 4 -} -export declare class Simple extends EventEmitter { - static readonly C: typeof SimpleStatus; - video: boolean; - audio: boolean; - anonymous: boolean; - options: any; - ua: UA; - state: SimpleStatus; - logger: Logger; - session: InviteClientContext | InviteServerContext | undefined; - constructor(options: any); - call(destination: string): InviteClientContext | InviteServerContext | void; - answer(): InviteServerContext | void; - reject(): InviteServerContext | undefined; - hangup(): InviteClientContext | InviteServerContext | undefined; - hold(): InviteClientContext | InviteServerContext | void; - unhold(): InviteClientContext | InviteServerContext | void; - mute(): void; - unmute(): void; - sendDTMF(tone: string): void; - message(destination: string, message: string): void; - private checkRegistration; - private setupRemoteMedia; - private setupLocalMedia; - private cleanupMedia; - private setupSession; - private destroyMedia; - private toggleMute; - private onAccepted; - private onProgress; - private onFailed; - private onEnded; -} -//# sourceMappingURL=Simple.d.ts.map \ No newline at end of file diff --git a/lib/Web/Simple.d.ts.map b/lib/Web/Simple.d.ts.map deleted file mode 100644 index 5726a2885..000000000 --- a/lib/Web/Simple.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"Simple.d.ts","sourceRoot":"","sources":["../../src/Web/Simple.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAEtC,OAAO,EAA0B,MAAM,EAA0B,MAAM,SAAS,CAAC;AACjF,OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAEtE,OAAO,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC;AAS3B,oBAAY,YAAY;IACtB,WAAW,IAAA;IACX,UAAU,IAAA;IACV,iBAAiB,IAAA;IACjB,gBAAgB,IAAA;IAChB,gBAAgB,IAAA;CACjB;AAED,qBAAa,MAAO,SAAQ,YAAY;IACtC,gBAAuB,CAAC,sBAAgB;IAEjC,KAAK,EAAE,OAAO,CAAC;IACf,KAAK,EAAE,OAAO,CAAC;IACf,SAAS,EAAE,OAAO,CAAC;IACnB,OAAO,EAAE,GAAG,CAAC;IACb,EAAE,EAAE,EAAE,CAAC;IACP,KAAK,EAAE,YAAY,CAAC;IACpB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,mBAAmB,GAAG,mBAAmB,GAAG,SAAS,CAAC;gBAE1D,OAAO,EAAE,GAAG;IAiHjB,IAAI,CAAC,WAAW,EAAE,MAAM,GAAG,mBAAmB,GAAG,mBAAmB,GAAG,IAAI;IAiC3E,MAAM,IAAI,mBAAmB,GAAG,IAAI;IAuBpC,MAAM,IAAI,mBAAmB,GAAG,SAAS;IAQzC,MAAM,IAAI,mBAAmB,GAAG,mBAAmB,GAAG,SAAS;IAc/D,IAAI,IAAI,mBAAmB,GAAG,mBAAmB,GAAG,IAAI;IAUxD,MAAM,IAAI,mBAAmB,GAAG,mBAAmB,GAAG,IAAI;IAU1D,IAAI,IAAI,IAAI;IAUZ,MAAM,IAAI,IAAI;IAUd,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI;IAS5B,OAAO,CAAC,WAAW,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI;IAc1D,OAAO,CAAC,iBAAiB;IAIzB,OAAO,CAAC,gBAAgB;IAiCxB,OAAO,CAAC,eAAe;IAyBvB,OAAO,CAAC,YAAY;IAepB,OAAO,CAAC,YAAY;IAepB,OAAO,CAAC,YAAY;IAMpB,OAAO,CAAC,UAAU;IAwBlB,OAAO,CAAC,UAAU;IA4BlB,OAAO,CAAC,UAAU;IAKlB,OAAO,CAAC,QAAQ;IAIhB,OAAO,CAAC,OAAO;CAKhB"} \ No newline at end of file diff --git a/lib/Web/Simple.js b/lib/Web/Simple.js deleted file mode 100644 index 00c22ff3b..000000000 --- a/lib/Web/Simple.js +++ /dev/null @@ -1,411 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var events_1 = require("events"); -var UA_1 = require("../UA"); -var Modifiers = tslib_1.__importStar(require("./Modifiers")); -/* Simple - * @class Simple - */ -var SimpleStatus; -(function (SimpleStatus) { - SimpleStatus[SimpleStatus["STATUS_NULL"] = 0] = "STATUS_NULL"; - SimpleStatus[SimpleStatus["STATUS_NEW"] = 1] = "STATUS_NEW"; - SimpleStatus[SimpleStatus["STATUS_CONNECTING"] = 2] = "STATUS_CONNECTING"; - SimpleStatus[SimpleStatus["STATUS_CONNECTED"] = 3] = "STATUS_CONNECTED"; - SimpleStatus[SimpleStatus["STATUS_COMPLETED"] = 4] = "STATUS_COMPLETED"; -})(SimpleStatus = exports.SimpleStatus || (exports.SimpleStatus = {})); -var Simple = /** @class */ (function (_super) { - tslib_1.__extends(Simple, _super); - function Simple(options) { - var _this = _super.call(this) || this; - /* - * { - * media: { - * remote: { - * audio: , - * video: - * }, - * local: { - * video: - * } - * }, - * ua: { - * - * } - * } - */ - if (options.media.remote.video) { - _this.video = true; - } - else { - _this.video = false; - } - if (options.media.remote.audio) { - _this.audio = true; - } - else { - _this.audio = false; - } - if (!_this.audio && !_this.video) { - // Need to do at least audio or video - // Error - throw new Error("At least one remote audio or video element is required for Simple."); - } - _this.options = options; - // https://stackoverflow.com/questions/7944460/detect-safari-browser - var browserUa = navigator.userAgent.toLowerCase(); - var isSafari = false; - var isFirefox = false; - if (browserUa.indexOf("safari") > -1 && browserUa.indexOf("chrome") < 0) { - isSafari = true; - } - else if (browserUa.indexOf("firefox") > -1 && browserUa.indexOf("chrome") < 0) { - isFirefox = true; - } - var sessionDescriptionHandlerFactoryOptions = {}; - if (isSafari) { - sessionDescriptionHandlerFactoryOptions.modifiers = [Modifiers.stripG722]; - } - if (isFirefox) { - sessionDescriptionHandlerFactoryOptions.alwaysAcquireMediaFirst = true; - } - if (!_this.options.ua.uri) { - _this.anonymous = true; - } - else { - _this.anonymous = false; - } - _this.ua = new UA_1.UA({ - // User Configurable Options - uri: _this.options.ua.uri, - authorizationUser: _this.options.ua.authorizationUser, - password: _this.options.ua.password, - displayName: _this.options.ua.displayName, - // Undocumented "Advanced" Options - userAgentString: _this.options.ua.userAgentString, - // Fixed Options - register: true, - sessionDescriptionHandlerFactoryOptions: sessionDescriptionHandlerFactoryOptions, - transportOptions: { - traceSip: _this.options.ua.traceSip, - wsServers: _this.options.ua.wsServers - } - }); - _this.state = SimpleStatus.STATUS_NULL; - _this.logger = _this.ua.getLogger("sip.simple"); - _this.ua.on("registered", function () { - _this.emit("registered", _this.ua); - }); - _this.ua.on("unregistered", function () { - _this.emit("unregistered", _this.ua); - }); - _this.ua.on("registrationFailed", function () { - _this.emit("unregistered", _this.ua); - }); - _this.ua.on("invite", function (session) { - // If there is already an active session reject the incoming session - if (_this.state !== SimpleStatus.STATUS_NULL && _this.state !== SimpleStatus.STATUS_COMPLETED) { - _this.logger.warn("Rejecting incoming call. Simple only supports 1 call at a time"); - session.reject(); - return; - } - _this.session = session; - _this.setupSession(); - _this.emit("ringing", _this.session); - }); - _this.ua.on("message", function (message) { - _this.emit("message", message); - }); - return _this; - } - Simple.prototype.call = function (destination) { - if (!this.ua || !this.checkRegistration()) { - this.logger.warn("A registered UA is required for calling"); - return; - } - if (this.state !== SimpleStatus.STATUS_NULL && this.state !== SimpleStatus.STATUS_COMPLETED) { - this.logger.warn("Cannot make more than a single call with Simple"); - return; - } - // Safari hack, because you cannot call .play() from a non user action - if (this.options.media.remote.audio) { - this.options.media.remote.audio.autoplay = true; - } - if (this.options.media.remote.video) { - this.options.media.remote.video.autoplay = true; - } - if (this.options.media.local && this.options.media.local.video) { - this.options.media.local.video.autoplay = true; - this.options.media.local.video.volume = 0; - } - this.session = this.ua.invite(destination, { - sessionDescriptionHandlerOptions: { - constraints: { - audio: this.audio, - video: this.video - } - } - }); - this.setupSession(); - return this.session; - }; - Simple.prototype.answer = function () { - if (this.state !== SimpleStatus.STATUS_NEW && this.state !== SimpleStatus.STATUS_CONNECTING) { - this.logger.warn("No call to answer"); - return; - } - // Safari hack, because you cannot call .play() from a non user action - if (this.options.media.remote.audio) { - this.options.media.remote.audio.autoplay = true; - } - if (this.options.media.remote.video) { - this.options.media.remote.video.autoplay = true; - } - return this.session.accept({ - sessionDescriptionHandlerOptions: { - constraints: { - audio: this.audio, - video: this.video - } - } - }); - // emit call is active - }; - Simple.prototype.reject = function () { - if (this.state !== SimpleStatus.STATUS_NEW && this.state !== SimpleStatus.STATUS_CONNECTING) { - this.logger.warn("Call is already answered"); - return; - } - return this.session.reject(); - }; - Simple.prototype.hangup = function () { - if (this.state !== SimpleStatus.STATUS_CONNECTED && - this.state !== SimpleStatus.STATUS_CONNECTING && - this.state !== SimpleStatus.STATUS_NEW) { - this.logger.warn("No active call to hang up on"); - return; - } - if (this.state !== SimpleStatus.STATUS_CONNECTED) { - return this.session.cancel(); - } - else if (this.session) { - return this.session.bye(); - } - }; - Simple.prototype.hold = function () { - if (this.state !== SimpleStatus.STATUS_CONNECTED || !this.session || this.session.localHold) { - this.logger.warn("Cannot put call on hold"); - return; - } - this.mute(); - this.logger.log("Placing session on hold"); - return this.session.hold(); - }; - Simple.prototype.unhold = function () { - if (this.state !== SimpleStatus.STATUS_CONNECTED || !this.session || !this.session.localHold) { - this.logger.warn("Cannot unhold a call that is not on hold"); - return; - } - this.unmute(); - this.logger.log("Placing call off hold"); - return this.session.unhold(); - }; - Simple.prototype.mute = function () { - if (this.state !== SimpleStatus.STATUS_CONNECTED) { - this.logger.warn("An acitve call is required to mute audio"); - return; - } - this.logger.log("Muting Audio"); - this.toggleMute(true); - this.emit("mute", this); - }; - Simple.prototype.unmute = function () { - if (this.state !== SimpleStatus.STATUS_CONNECTED) { - this.logger.warn("An active call is required to unmute audio"); - return; - } - this.logger.log("Unmuting Audio"); - this.toggleMute(false); - this.emit("unmute", this); - }; - Simple.prototype.sendDTMF = function (tone) { - if (this.state !== SimpleStatus.STATUS_CONNECTED || !this.session) { - this.logger.warn("An active call is required to send a DTMF tone"); - return; - } - this.logger.log("Sending DTMF tone: " + tone); - this.session.dtmf(tone); - }; - Simple.prototype.message = function (destination, message) { - if (!this.ua || !this.checkRegistration()) { - this.logger.warn("A registered UA is required to send a message"); - return; - } - if (!destination || !message) { - this.logger.warn("A destination and message are required to send a message"); - return; - } - this.ua.message(destination, message); - }; - // Private Helpers - Simple.prototype.checkRegistration = function () { - return (this.anonymous || (this.ua && this.ua.isRegistered())); - }; - Simple.prototype.setupRemoteMedia = function () { - var _this = this; - if (!this.session) { - this.logger.warn("No session to set remote media on"); - return; - } - // If there is a video track, it will attach the video and audio to the same element - var pc = this.session.sessionDescriptionHandler.peerConnection; - var remoteStream; - if (pc.getReceivers) { - remoteStream = new MediaStream(); - pc.getReceivers().forEach(function (receiver) { - var track = receiver.track; - if (track) { - remoteStream.addTrack(track); - } - }); - } - else { - remoteStream = pc.getRemoteStreams()[0]; - } - if (this.video) { - this.options.media.remote.video.srcObject = remoteStream; - this.options.media.remote.video.play().catch(function () { - _this.logger.log("play was rejected"); - }); - } - else if (this.audio) { - this.options.media.remote.audio.srcObject = remoteStream; - this.options.media.remote.audio.play().catch(function () { - _this.logger.log("play was rejected"); - }); - } - }; - Simple.prototype.setupLocalMedia = function () { - if (!this.session) { - this.logger.warn("No session to set local media on"); - return; - } - if (this.video && this.options.media.local && this.options.media.local.video) { - var pc = this.session.sessionDescriptionHandler.peerConnection; - var localStream_1; - if (pc.getSenders) { - localStream_1 = new MediaStream(); - pc.getSenders().forEach(function (sender) { - var track = sender.track; - if (track && track.kind === "video") { - localStream_1.addTrack(track); - } - }); - } - else { - localStream_1 = pc.getLocalStreams()[0]; - } - this.options.media.local.video.srcObject = localStream_1; - this.options.media.local.video.volume = 0; - this.options.media.local.video.play(); - } - }; - Simple.prototype.cleanupMedia = function () { - if (this.video) { - this.options.media.remote.video.srcObject = null; - this.options.media.remote.video.pause(); - if (this.options.media.local && this.options.media.local.video) { - this.options.media.local.video.srcObject = null; - this.options.media.local.video.pause(); - } - } - if (this.audio) { - this.options.media.remote.audio.srcObject = null; - this.options.media.remote.audio.pause(); - } - }; - Simple.prototype.setupSession = function () { - var _this = this; - if (!this.session) { - this.logger.warn("No session to set up"); - return; - } - this.state = SimpleStatus.STATUS_NEW; - this.emit("new", this.session); - this.session.on("progress", function () { return _this.onProgress(); }); - this.session.on("accepted", function () { return _this.onAccepted(); }); - this.session.on("rejected", function () { return _this.onEnded(); }); - this.session.on("failed", function () { return _this.onFailed(); }); - this.session.on("terminated", function () { return _this.onEnded(); }); - }; - Simple.prototype.destroyMedia = function () { - if (this.session && this.session.sessionDescriptionHandler) { - this.session.sessionDescriptionHandler.close(); - } - }; - Simple.prototype.toggleMute = function (mute) { - if (!this.session) { - this.logger.warn("No session to toggle mute"); - return; - } - var pc = this.session.sessionDescriptionHandler.peerConnection; - if (pc.getSenders) { - pc.getSenders().forEach(function (sender) { - if (sender.track) { - sender.track.enabled = !mute; - } - }); - } - else { - pc.getLocalStreams().forEach(function (stream) { - stream.getAudioTracks().forEach(function (track) { - track.enabled = !mute; - }); - stream.getVideoTracks().forEach(function (track) { - track.enabled = !mute; - }); - }); - } - }; - Simple.prototype.onAccepted = function () { - var _this = this; - if (!this.session) { - this.logger.warn("No session for accepting"); - return; - } - this.state = SimpleStatus.STATUS_CONNECTED; - this.emit("connected", this.session); - this.setupLocalMedia(); - this.setupRemoteMedia(); - if (this.session.sessionDescriptionHandler) { - this.session.sessionDescriptionHandler.on("addTrack", function () { - _this.logger.log("A track has been added, triggering new remoteMedia setup"); - _this.setupRemoteMedia(); - }); - this.session.sessionDescriptionHandler.on("addStream", function () { - _this.logger.log("A stream has been added, trigger new remoteMedia setup"); - _this.setupRemoteMedia(); - }); - } - this.session.on("dtmf", function (request, dtmf) { - _this.emit("dtmf", dtmf.tone); - }); - this.session.on("bye", function () { return _this.onEnded(); }); - }; - Simple.prototype.onProgress = function () { - this.state = SimpleStatus.STATUS_CONNECTING; - this.emit("connecting", this.session); - }; - Simple.prototype.onFailed = function () { - this.onEnded(); - }; - Simple.prototype.onEnded = function () { - this.state = SimpleStatus.STATUS_COMPLETED; - this.emit("ended", this.session); - this.cleanupMedia(); - }; - Simple.C = SimpleStatus; - return Simple; -}(events_1.EventEmitter)); -exports.Simple = Simple; diff --git a/lib/Web/Transport.d.ts b/lib/Web/Transport.d.ts deleted file mode 100644 index dcba9a759..000000000 --- a/lib/Web/Transport.d.ts +++ /dev/null @@ -1,159 +0,0 @@ -import { Logger, OutgoingRequestMessage, Transport as TransportBase } from "../core"; -import { TypeStrings } from "../Enums"; -export declare enum TransportStatus { - STATUS_CONNECTING = 0, - STATUS_OPEN = 1, - STATUS_CLOSING = 2, - STATUS_CLOSED = 3 -} -export interface WsServer { - scheme: string; - sipUri: string; - wsUri: string; - weight: number; - isError: boolean; -} -export interface Configuration { - wsServers: Array; - connectionTimeout: number; - maxReconnectionAttempts: number; - reconnectionTimeout: number; - keepAliveInterval: number; - keepAliveDebounce: number; - traceSip: boolean; -} -/** - * @class Transport - * @param {Object} options - */ -export declare class Transport extends TransportBase { - static readonly C: typeof TransportStatus; - type: TypeStrings; - server: WsServer; - ws: any; - private connectionPromise; - private connectDeferredResolve; - private connectDeferredReject; - private connectionTimeout; - private disconnectionPromise; - private disconnectDeferredResolve; - private reconnectionAttempts; - private reconnectTimer; - private keepAliveInterval; - private keepAliveDebounceTimeout; - private status; - private configuration; - private boundOnOpen; - private boundOnMessage; - private boundOnClose; - private boundOnError; - constructor(logger: Logger, options?: any); - /** - * @returns {Boolean} - */ - isConnected(): boolean; - /** - * Send a message. - * @param {SIP.OutgoingRequest|String} msg - * @param {Object} [options] - * @returns {Promise} - */ - protected sendPromise(msg: OutgoingRequestMessage | string, options?: any): Promise<{ - msg: string; - }>; - /** - * Disconnect socket. - */ - protected disconnectPromise(options?: any): Promise; - /** - * Connect socket. - */ - protected connectPromise(options?: any): Promise; - /** - * @event - * @param {event} e - */ - protected onMessage(e: any): void; - /** - * @event - * @param {event} e - */ - private onOpen; - /** - * @event - * @param {event} e - */ - private onClose; - /** - * Removes event listeners and clears the instance ws - */ - private disposeWs; - /** - * @event - * @param {string} e - */ - private onError; - /** - * @event - * @private - */ - private onWebsocketError; - /** - * Reconnection attempt logic. - */ - private reconnect; - /** - * Resets the error state of all servers in the configuration - */ - private resetServerErrorStatus; - /** - * Retrieve the next server to which connect. - * @param {Boolean} force allows bypass of server error status checking - * @returns {Object} WsServer - */ - private getNextWsServer; - /** - * Checks all configuration servers, returns true if all of them have isError: true and false otherwise - * @returns {Boolean} - */ - private noAvailableServers; - /** - * Send a keep-alive (a double-CRLF sequence). - * @returns {Boolean} - */ - private sendKeepAlive; - private clearKeepAliveTimeout; - /** - * Start sending keep-alives. - */ - private startSendingKeepAlives; - /** - * Stop sending keep-alives. - */ - private stopSendingKeepAlives; - /** - * Checks given status against instance current status. Returns true if they match - * @param {Number} status - * @param {Boolean} [force] - * @returns {Boolean} - */ - private statusAssert; - /** - * Transitions the status. Checks for legal transition via assertion beforehand - * @param {Number} status - * @param {Boolean} [force] - * @returns {Boolean} - */ - private statusTransition; - /** - * Configuration load. - * returns {Configuration} - */ - private loadConfig; - /** - * Configuration checker. - * @return {Boolean} - */ - private getConfigurationCheck; -} -//# sourceMappingURL=Transport.d.ts.map \ No newline at end of file diff --git a/lib/Web/Transport.d.ts.map b/lib/Web/Transport.d.ts.map deleted file mode 100644 index 46222377a..000000000 --- a/lib/Web/Transport.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"Transport.d.ts","sourceRoot":"","sources":["../../src/Web/Transport.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,MAAM,EACN,sBAAsB,EACtB,SAAS,IAAI,aAAa,EAC3B,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAIvC,oBAAY,eAAe;IACzB,iBAAiB,IAAA;IACjB,WAAW,IAAA;IACX,cAAc,IAAA;IACd,aAAa,IAAA;CACd;AAED,MAAM,WAAW,QAAQ;IACvB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,OAAO,CAAC;CAClB;AAED,MAAM,WAAW,aAAa;IAC5B,SAAS,EAAE,KAAK,CAAC,QAAQ,CAAC,CAAC;IAC3B,iBAAiB,EAAE,MAAM,CAAC;IAC1B,uBAAuB,EAAE,MAAM,CAAC;IAChC,mBAAmB,EAAE,MAAM,CAAC;IAC5B,iBAAiB,EAAE,MAAM,CAAC;IAC1B,iBAAiB,EAAE,MAAM,CAAC;IAC1B,QAAQ,EAAE,OAAO,CAAC;CACnB;AAYD;;;GAGG;AACH,qBAAa,SAAU,SAAQ,aAAa;IAC1C,gBAAuB,CAAC,yBAAmB;IACpC,IAAI,EAAE,WAAW,CAAC;IAClB,MAAM,EAAE,QAAQ,CAAC;IACjB,EAAE,EAAE,GAAG,CAAC;IAEf,OAAO,CAAC,iBAAiB,CAA2B;IACpD,OAAO,CAAC,sBAAsB,CAAmC;IACjE,OAAO,CAAC,qBAAqB,CAAmC;IAChE,OAAO,CAAC,iBAAiB,CAAkB;IAE3C,OAAO,CAAC,oBAAoB,CAA2B;IACvD,OAAO,CAAC,yBAAyB,CAAmC;IAEpE,OAAO,CAAC,oBAAoB,CAAS;IACrC,OAAO,CAAC,cAAc,CAAkB;IAGxC,OAAO,CAAC,iBAAiB,CAAkB;IAC3C,OAAO,CAAC,wBAAwB,CAAkB;IAElD,OAAO,CAAC,MAAM,CAAkB;IAChC,OAAO,CAAC,aAAa,CAAgB;IACrC,OAAO,CAAC,WAAW,CAAM;IACzB,OAAO,CAAC,cAAc,CAAM;IAC5B,OAAO,CAAC,YAAY,CAAM;IAC1B,OAAO,CAAC,YAAY,CAAM;gBAEd,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,GAAQ;IAU7C;;OAEG;IACI,WAAW,IAAI,OAAO;IAI7B;;;;;OAKG;IACH,SAAS,CAAC,WAAW,CAAC,GAAG,EAAE,sBAAsB,GAAG,MAAM,EAAE,OAAO,GAAE,GAAQ,GAAG,OAAO,CAAC;QAAC,GAAG,EAAE,MAAM,CAAA;KAAC,CAAC;IAoBtG;;OAEG;IACH,SAAS,CAAC,iBAAiB,CAAC,OAAO,GAAE,GAAQ,GAAG,OAAO,CAAC,GAAG,CAAC;IAuC5D;;OAEG;IACH,SAAS,CAAC,cAAc,CAAC,OAAO,GAAE,GAAQ;IAuE1C;;;OAGG;IACH,SAAS,CAAC,SAAS,CAAC,CAAC,EAAE,GAAG,GAAG,IAAI;IAsCjC;;;OAGG;IACH,OAAO,CAAC,MAAM;IAwCd;;;OAGG;IACH,OAAO,CAAC,OAAO;IAqCf;;OAEG;IACH,OAAO,CAAC,SAAS;IAUjB;;;OAGG;IACH,OAAO,CAAC,OAAO;IAKf;;;OAGG;IACH,OAAO,CAAC,gBAAgB;IAIxB;;OAEG;IACH,OAAO,CAAC,SAAS;IA2CjB;;OAEG;IACH,OAAO,CAAC,sBAAsB;IAM9B;;;;OAIG;IACH,OAAO,CAAC,eAAe;IAwBvB;;;OAGG;IACH,OAAO,CAAC,kBAAkB;IAa1B;;;OAGG;IACH,OAAO,CAAC,aAAa;IAcrB,OAAO,CAAC,qBAAqB;IAO7B;;OAEG;IACH,OAAO,CAAC,sBAAsB;IAS9B;;OAEG;IACH,OAAO,CAAC,qBAAqB;IAe7B;;;;;OAKG;IACH,OAAO,CAAC,YAAY;IAkBpB;;;;;OAKG;IACH,OAAO,CAAC,gBAAgB;IAqBxB;;;OAGG;IACH,OAAO,CAAC,UAAU;IAkFlB;;;OAGG;IACH,OAAO,CAAC,qBAAqB;CAkH9B"} \ No newline at end of file diff --git a/lib/Web/Transport.js b/lib/Web/Transport.js deleted file mode 100644 index 18c39e140..000000000 --- a/lib/Web/Transport.js +++ /dev/null @@ -1,709 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var core_1 = require("../core"); -var Enums_1 = require("../Enums"); -var Exceptions_1 = require("../Exceptions"); -var Utils_1 = require("../Utils"); -var TransportStatus; -(function (TransportStatus) { - TransportStatus[TransportStatus["STATUS_CONNECTING"] = 0] = "STATUS_CONNECTING"; - TransportStatus[TransportStatus["STATUS_OPEN"] = 1] = "STATUS_OPEN"; - TransportStatus[TransportStatus["STATUS_CLOSING"] = 2] = "STATUS_CLOSING"; - TransportStatus[TransportStatus["STATUS_CLOSED"] = 3] = "STATUS_CLOSED"; -})(TransportStatus = exports.TransportStatus || (exports.TransportStatus = {})); -/** - * Compute an amount of time in seconds to wait before sending another - * keep-alive. - * @returns {Number} - */ -var computeKeepAliveTimeout = function (upperBound) { - var lowerBound = upperBound * 0.8; - return 1000 * (Math.random() * (upperBound - lowerBound) + lowerBound); -}; -/** - * @class Transport - * @param {Object} options - */ -var Transport = /** @class */ (function (_super) { - tslib_1.__extends(Transport, _super); - function Transport(logger, options) { - if (options === void 0) { options = {}; } - var _this = _super.call(this, logger, options) || this; - _this.type = Enums_1.TypeStrings.Transport; - _this.reconnectionAttempts = 0; - _this.status = TransportStatus.STATUS_CONNECTING; - _this.configuration = _this.loadConfig(options); - _this.server = _this.configuration.wsServers[0]; - return _this; - } - /** - * @returns {Boolean} - */ - Transport.prototype.isConnected = function () { - return this.status === TransportStatus.STATUS_OPEN; - }; - /** - * Send a message. - * @param {SIP.OutgoingRequest|String} msg - * @param {Object} [options] - * @returns {Promise} - */ - Transport.prototype.sendPromise = function (msg, options) { - if (options === void 0) { options = {}; } - if (!this.statusAssert(TransportStatus.STATUS_OPEN, options.force)) { - this.onError("unable to send message - WebSocket not open"); - return Promise.reject(); - } - var message = msg.toString(); - if (this.ws) { - if (this.configuration.traceSip === true) { - this.logger.log("sending WebSocket message:\n\n" + message + "\n"); - } - this.ws.send(message); - return Promise.resolve({ msg: message }); - } - else { - this.onError("unable to send message - WebSocket does not exist"); - return Promise.reject(); - } - }; - /** - * Disconnect socket. - */ - Transport.prototype.disconnectPromise = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - if (this.disconnectionPromise) { // Already disconnecting. Just return this. - return this.disconnectionPromise; - } - options.code = options.code || 1000; - if (!this.statusTransition(TransportStatus.STATUS_CLOSING, options.force)) { - if (this.status === TransportStatus.STATUS_CLOSED) { // Websocket is already closed - return Promise.resolve({ overrideEvent: true }); - } - else if (this.connectionPromise) { // Websocket is connecting, cannot move to disconneting yet - return this.connectionPromise.then(function () { return Promise.reject("The websocket did not disconnect"); }) - .catch(function () { return Promise.resolve({ overrideEvent: true }); }); - } - else { - // Cannot move to disconnecting, but not in connecting state. - return Promise.reject("The websocket did not disconnect"); - } - } - this.emit("disconnecting"); - this.disconnectionPromise = new Promise(function (resolve, reject) { - _this.disconnectDeferredResolve = resolve; - if (_this.reconnectTimer) { - clearTimeout(_this.reconnectTimer); - _this.reconnectTimer = undefined; - } - if (_this.ws) { - _this.stopSendingKeepAlives(); - _this.logger.log("closing WebSocket " + _this.server.wsUri); - _this.ws.close(options.code, options.reason); - } - else { - reject("Attempted to disconnect but the websocket doesn't exist"); - } - }); - return this.disconnectionPromise; - }; - /** - * Connect socket. - */ - Transport.prototype.connectPromise = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - if (this.status === TransportStatus.STATUS_CLOSING && !options.force) { - return Promise.reject("WebSocket " + this.server.wsUri + " is closing"); - } - if (this.connectionPromise) { - return this.connectionPromise; - } - this.server = this.server || this.getNextWsServer(options.force); - this.connectionPromise = new Promise(function (resolve, reject) { - if ((_this.status === TransportStatus.STATUS_OPEN || _this.status === TransportStatus.STATUS_CLOSING) - && !options.force) { - _this.logger.warn("WebSocket " + _this.server.wsUri + " is already connected"); - reject("Failed status check - attempted to open a connection but already open/closing"); - return; - } - _this.connectDeferredResolve = resolve; - _this.connectDeferredReject = reject; - _this.status = TransportStatus.STATUS_CONNECTING; - _this.emit("connecting"); - _this.logger.log("connecting to WebSocket " + _this.server.wsUri); - _this.disposeWs(); - try { - _this.ws = new WebSocket(_this.server.wsUri, "sip"); - } - catch (e) { - _this.ws = null; - _this.statusTransition(TransportStatus.STATUS_CLOSED, true); - _this.onError("error connecting to WebSocket " + _this.server.wsUri + ":" + e); - reject("Failed to create a websocket"); - _this.connectDeferredResolve = undefined; - _this.connectDeferredReject = undefined; - return; - } - if (!_this.ws) { - reject("Unexpected instance websocket not set"); - _this.connectDeferredResolve = undefined; - _this.connectDeferredReject = undefined; - return; - } - _this.connectionTimeout = setTimeout(function () { - _this.statusTransition(TransportStatus.STATUS_CLOSED); - _this.logger.warn("took too long to connect - exceeded time set in configuration.connectionTimeout: " + - _this.configuration.connectionTimeout + "s"); - _this.emit("disconnected", { code: 1000 }); - _this.connectionPromise = undefined; - reject("Connection timeout"); - _this.connectDeferredResolve = undefined; - _this.connectDeferredReject = undefined; - var ws = _this.ws; - _this.disposeWs(); - ws.close(1000); - }, _this.configuration.connectionTimeout * 1000); - _this.boundOnOpen = _this.onOpen.bind(_this); - _this.boundOnMessage = _this.onMessage.bind(_this); - _this.boundOnClose = _this.onClose.bind(_this); - _this.boundOnError = _this.onWebsocketError.bind(_this); - _this.ws.addEventListener("open", _this.boundOnOpen); - _this.ws.addEventListener("message", _this.boundOnMessage); - _this.ws.addEventListener("close", _this.boundOnClose); - _this.ws.addEventListener("error", _this.boundOnError); - }); - return this.connectionPromise; - }; - /** - * @event - * @param {event} e - */ - Transport.prototype.onMessage = function (e) { - var data = e.data; - var finishedData; - // CRLF Keep Alive response from server. Clear our keep alive timeout. - if (/^(\r\n)+$/.test(data)) { - this.clearKeepAliveTimeout(); - if (this.configuration.traceSip === true) { - this.logger.log("received WebSocket message with CRLF Keep Alive response"); - } - return; - } - else if (!data) { - this.logger.warn("received empty message, message discarded"); - return; - } - else if (typeof data !== "string") { // WebSocket binary message. - try { - // the UInt8Data was here prior to types, and doesn't check - finishedData = String.fromCharCode.apply(null, new Uint8Array(data)); - } - catch (err) { - this.logger.warn("received WebSocket binary message failed to be converted into string, message discarded"); - return; - } - if (this.configuration.traceSip === true) { - this.logger.log("received WebSocket binary message:\n\n" + data + "\n"); - } - } - else { // WebSocket text message. - if (this.configuration.traceSip === true) { - this.logger.log("received WebSocket text message:\n\n" + data + "\n"); - } - finishedData = data; - } - this.emit("message", finishedData); - }; - // Transport Event Handlers - /** - * @event - * @param {event} e - */ - Transport.prototype.onOpen = function () { - if (this.status === TransportStatus.STATUS_CLOSED) { // Indicated that the transport thinks the ws is dead already - var ws = this.ws; - this.disposeWs(); - ws.close(1000); - return; - } - this.statusTransition(TransportStatus.STATUS_OPEN, true); - this.emit("connected"); - if (this.connectionTimeout) { - clearTimeout(this.connectionTimeout); - this.connectionTimeout = undefined; - } - this.logger.log("WebSocket " + this.server.wsUri + " connected"); - // Clear reconnectTimer since we are not disconnected - if (this.reconnectTimer !== undefined) { - clearTimeout(this.reconnectTimer); - this.reconnectTimer = undefined; - } - // Reset reconnectionAttempts - this.reconnectionAttempts = 0; - // Reset disconnection promise so we can disconnect from a fresh state - this.disconnectionPromise = undefined; - this.disconnectDeferredResolve = undefined; - // Start sending keep-alives - this.startSendingKeepAlives(); - if (this.connectDeferredResolve) { - this.connectDeferredResolve({ overrideEvent: true }); - this.connectDeferredResolve = undefined; - this.connectDeferredReject = undefined; - } - else { - this.logger.warn("Unexpected websocket.onOpen with no connectDeferredResolve"); - } - }; - /** - * @event - * @param {event} e - */ - Transport.prototype.onClose = function (e) { - this.logger.log("WebSocket disconnected (code: " + e.code + (e.reason ? "| reason: " + e.reason : "") + ")"); - if (this.status !== TransportStatus.STATUS_CLOSING) { - this.logger.warn("WebSocket closed without SIP.js requesting it"); - this.emit("transportError"); - } - this.stopSendingKeepAlives(); - // Clean up connection variables so we can connect again from a fresh state - if (this.connectionTimeout) { - clearTimeout(this.connectionTimeout); - } - if (this.connectDeferredReject) { - this.connectDeferredReject("Websocket Closed"); - } - this.connectionTimeout = undefined; - this.connectionPromise = undefined; - this.connectDeferredResolve = undefined; - this.connectDeferredReject = undefined; - // Check whether the user requested to close. - if (this.disconnectDeferredResolve) { - this.disconnectDeferredResolve({ overrideEvent: true }); - this.statusTransition(TransportStatus.STATUS_CLOSED); - this.disconnectDeferredResolve = undefined; - return; - } - this.statusTransition(TransportStatus.STATUS_CLOSED, true); - this.emit("disconnected", { code: e.code, reason: e.reason }); - this.disposeWs(); - this.reconnect(); - }; - /** - * Removes event listeners and clears the instance ws - */ - Transport.prototype.disposeWs = function () { - if (this.ws) { - this.ws.removeEventListener("open", this.boundOnOpen); - this.ws.removeEventListener("message", this.boundOnMessage); - this.ws.removeEventListener("close", this.boundOnClose); - this.ws.removeEventListener("error", this.boundOnError); - this.ws = undefined; - } - }; - /** - * @event - * @param {string} e - */ - Transport.prototype.onError = function (e) { - this.logger.warn("Transport error: " + e); - this.emit("transportError"); - }; - /** - * @event - * @private - */ - Transport.prototype.onWebsocketError = function () { - this.onError("The Websocket had an error"); - }; - /** - * Reconnection attempt logic. - */ - Transport.prototype.reconnect = function () { - var _this = this; - if (this.reconnectionAttempts > 0) { - this.logger.log("Reconnection attempt " + this.reconnectionAttempts + " failed"); - } - if (this.noAvailableServers()) { - this.logger.warn("attempted to get next ws server but there are no available ws servers left"); - this.logger.warn("no available ws servers left - going to closed state"); - this.statusTransition(TransportStatus.STATUS_CLOSED, true); - this.emit("closed"); - this.resetServerErrorStatus(); - return; - } - if (this.isConnected()) { - this.logger.warn("attempted to reconnect while connected - forcing disconnect"); - this.disconnect({ force: true }); - } - this.reconnectionAttempts += 1; - if (this.reconnectionAttempts > this.configuration.maxReconnectionAttempts) { - this.logger.warn("maximum reconnection attempts for WebSocket " + this.server.wsUri); - this.logger.log("transport " + this.server.wsUri + " failed | connection state set to 'error'"); - this.server.isError = true; - this.emit("transportError"); - if (!this.noAvailableServers()) { - this.server = this.getNextWsServer(); - } - // When there are no available servers, the reconnect function ends on the next recursive call - // after checking for no available servers again. - this.reconnectionAttempts = 0; - this.reconnect(); - } - else { - this.logger.log("trying to reconnect to WebSocket " + - this.server.wsUri + " (reconnection attempt " + this.reconnectionAttempts + ")"); - this.reconnectTimer = setTimeout(function () { - _this.connect(); - _this.reconnectTimer = undefined; - }, (this.reconnectionAttempts === 1) ? 0 : this.configuration.reconnectionTimeout * 1000); - } - }; - /** - * Resets the error state of all servers in the configuration - */ - Transport.prototype.resetServerErrorStatus = function () { - for (var _i = 0, _a = this.configuration.wsServers; _i < _a.length; _i++) { - var websocket = _a[_i]; - websocket.isError = false; - } - }; - /** - * Retrieve the next server to which connect. - * @param {Boolean} force allows bypass of server error status checking - * @returns {Object} WsServer - */ - Transport.prototype.getNextWsServer = function (force) { - if (force === void 0) { force = false; } - if (this.noAvailableServers()) { - this.logger.warn("attempted to get next ws server but there are no available ws servers left"); - throw new Error("Attempted to get next ws server, but there are no available ws servers left."); - } - // Order servers by weight - var candidates = []; - for (var _i = 0, _a = this.configuration.wsServers; _i < _a.length; _i++) { - var wsServer = _a[_i]; - if (wsServer.isError && !force) { - continue; - } - else if (candidates.length === 0) { - candidates.push(wsServer); - } - else if (wsServer.weight > candidates[0].weight) { - candidates = [wsServer]; - } - else if (wsServer.weight === candidates[0].weight) { - candidates.push(wsServer); - } - } - var idx = Math.floor(Math.random() * candidates.length); - return candidates[idx]; - }; - /** - * Checks all configuration servers, returns true if all of them have isError: true and false otherwise - * @returns {Boolean} - */ - Transport.prototype.noAvailableServers = function () { - for (var _i = 0, _a = this.configuration.wsServers; _i < _a.length; _i++) { - var server = _a[_i]; - if (!server.isError) { - return false; - } - } - return true; - }; - // ============================== - // KeepAlive Stuff - // ============================== - /** - * Send a keep-alive (a double-CRLF sequence). - * @returns {Boolean} - */ - Transport.prototype.sendKeepAlive = function () { - var _this = this; - if (this.keepAliveDebounceTimeout) { - // We already have an outstanding keep alive, do not send another. - return; - } - this.keepAliveDebounceTimeout = setTimeout(function () { - _this.emit("keepAliveDebounceTimeout"); - _this.clearKeepAliveTimeout(); - }, this.configuration.keepAliveDebounce * 1000); - return this.send("\r\n\r\n"); - }; - Transport.prototype.clearKeepAliveTimeout = function () { - if (this.keepAliveDebounceTimeout) { - clearTimeout(this.keepAliveDebounceTimeout); - } - this.keepAliveDebounceTimeout = undefined; - }; - /** - * Start sending keep-alives. - */ - Transport.prototype.startSendingKeepAlives = function () { - var _this = this; - if (this.configuration.keepAliveInterval && !this.keepAliveInterval) { - this.keepAliveInterval = setInterval(function () { - _this.sendKeepAlive(); - _this.startSendingKeepAlives(); - }, computeKeepAliveTimeout(this.configuration.keepAliveInterval)); - } - }; - /** - * Stop sending keep-alives. - */ - Transport.prototype.stopSendingKeepAlives = function () { - if (this.keepAliveInterval) { - clearInterval(this.keepAliveInterval); - } - if (this.keepAliveDebounceTimeout) { - clearTimeout(this.keepAliveDebounceTimeout); - } - this.keepAliveInterval = undefined; - this.keepAliveDebounceTimeout = undefined; - }; - // ============================== - // Status Stuff - // ============================== - /** - * Checks given status against instance current status. Returns true if they match - * @param {Number} status - * @param {Boolean} [force] - * @returns {Boolean} - */ - Transport.prototype.statusAssert = function (status, force) { - if (status === this.status) { - return true; - } - else { - if (force) { - this.logger.warn("Attempted to assert " + - Object.keys(TransportStatus)[this.status] + " as " + - Object.keys(TransportStatus)[status] + "- continuing with option: 'force'"); - return true; - } - else { - this.logger.warn("Tried to assert " + - Object.keys(TransportStatus)[status] + " but is currently " + - Object.keys(TransportStatus)[this.status]); - return false; - } - } - }; - /** - * Transitions the status. Checks for legal transition via assertion beforehand - * @param {Number} status - * @param {Boolean} [force] - * @returns {Boolean} - */ - Transport.prototype.statusTransition = function (status, force) { - if (force === void 0) { force = false; } - this.logger.log("Attempting to transition status from " + - Object.keys(TransportStatus)[this.status] + " to " + - Object.keys(TransportStatus)[status]); - if ((status === TransportStatus.STATUS_CONNECTING && this.statusAssert(TransportStatus.STATUS_CLOSED, force)) || - (status === TransportStatus.STATUS_OPEN && this.statusAssert(TransportStatus.STATUS_CONNECTING, force)) || - (status === TransportStatus.STATUS_CLOSING && this.statusAssert(TransportStatus.STATUS_OPEN, force)) || - (status === TransportStatus.STATUS_CLOSED)) { - this.status = status; - return true; - } - else { - this.logger.warn("Status transition failed - result: no-op - reason:" + - " either gave an nonexistent status or attempted illegal transition"); - return false; - } - }; - // ============================== - // Configuration Handling - // ============================== - /** - * Configuration load. - * returns {Configuration} - */ - Transport.prototype.loadConfig = function (configuration) { - var settings = { - wsServers: [{ - scheme: "WSS", - sipUri: "", - weight: 0, - wsUri: "wss://edge.sip.onsip.com", - isError: false - }], - connectionTimeout: 5, - maxReconnectionAttempts: 3, - reconnectionTimeout: 4, - keepAliveInterval: 0, - keepAliveDebounce: 10, - // Logging - traceSip: false - }; - var configCheck = this.getConfigurationCheck(); - // Check Mandatory parameters - for (var parameter in configCheck.mandatory) { - if (!configuration.hasOwnProperty(parameter)) { - throw new Exceptions_1.Exceptions.ConfigurationError(parameter); - } - else { - var value = configuration[parameter]; - var checkedValue = configCheck.mandatory[parameter](value); - if (checkedValue !== undefined) { - settings[parameter] = checkedValue; - } - else { - throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); - } - } - } - // Check Optional parameters - for (var parameter in configCheck.optional) { - if (configuration.hasOwnProperty(parameter)) { - var value = configuration[parameter]; - // If the parameter value is an empty array, but shouldn't be, apply its default value. - // If the parameter value is null, empty string, or undefined then apply its default value. - // If it's a number with NaN value then also apply its default value. - // NOTE: JS does not allow "value === NaN", the following does the work: - if ((value instanceof Array && value.length === 0) || - (value === null || value === "" || value === undefined) || - (typeof (value) === "number" && isNaN(value))) { - continue; - } - var checkedValue = configCheck.optional[parameter](value); - if (checkedValue !== undefined) { - settings[parameter] = checkedValue; - } - else { - throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); - } - } - } - var skeleton = {}; // Fill the value of the configuration_skeleton - for (var parameter in settings) { - if (settings.hasOwnProperty(parameter)) { - skeleton[parameter] = { - value: settings[parameter], - }; - } - } - var returnConfiguration = Object.defineProperties({}, skeleton); - this.logger.log("configuration parameters after validation:"); - for (var parameter in settings) { - if (settings.hasOwnProperty(parameter)) { - this.logger.log("· " + parameter + ": " + JSON.stringify(settings[parameter])); - } - } - return returnConfiguration; - }; - /** - * Configuration checker. - * @return {Boolean} - */ - Transport.prototype.getConfigurationCheck = function () { - return { - mandatory: {}, - optional: { - // Note: this function used to call 'this.logger.error' but calling 'this' with anything here is invalid - wsServers: function (wsServers) { - /* Allow defining wsServers parameter as: - * String: "host" - * Array of Strings: ["host1", "host2"] - * Array of Objects: [{wsUri:"host1", weight:1}, {wsUri:"host2", weight:0}] - * Array of Objects and Strings: [{wsUri:"host1"}, "host2"] - */ - if (typeof wsServers === "string") { - wsServers = [{ wsUri: wsServers }]; - } - else if (wsServers instanceof Array) { - for (var idx = 0; idx < wsServers.length; idx++) { - if (typeof wsServers[idx] === "string") { - wsServers[idx] = { wsUri: wsServers[idx] }; - } - } - } - else { - return; - } - if (wsServers.length === 0) { - return false; - } - for (var _i = 0, wsServers_1 = wsServers; _i < wsServers_1.length; _i++) { - var wsServer = wsServers_1[_i]; - if (!wsServer.wsUri) { - return; - } - if (wsServer.weight && !Number(wsServer.weight)) { - return; - } - var url = core_1.Grammar.parse(wsServer.wsUri, "absoluteURI"); - if (url === -1) { - return; - } - else if (["wss", "ws", "udp"].indexOf(url.scheme) < 0) { - return; - } - else { - wsServer.sipUri = ""; - if (!wsServer.weight) { - wsServer.weight = 0; - } - wsServer.isError = false; - wsServer.scheme = url.scheme.toUpperCase(); - } - } - return wsServers; - }, - keepAliveInterval: function (keepAliveInterval) { - if (Utils_1.Utils.isDecimal(keepAliveInterval)) { - var value = Number(keepAliveInterval); - if (value > 0) { - return value; - } - } - }, - keepAliveDebounce: function (keepAliveDebounce) { - if (Utils_1.Utils.isDecimal(keepAliveDebounce)) { - var value = Number(keepAliveDebounce); - if (value > 0) { - return value; - } - } - }, - traceSip: function (traceSip) { - if (typeof traceSip === "boolean") { - return traceSip; - } - }, - connectionTimeout: function (connectionTimeout) { - if (Utils_1.Utils.isDecimal(connectionTimeout)) { - var value = Number(connectionTimeout); - if (value > 0) { - return value; - } - } - }, - maxReconnectionAttempts: function (maxReconnectionAttempts) { - if (Utils_1.Utils.isDecimal(maxReconnectionAttempts)) { - var value = Number(maxReconnectionAttempts); - if (value >= 0) { - return value; - } - } - }, - reconnectionTimeout: function (reconnectionTimeout) { - if (Utils_1.Utils.isDecimal(reconnectionTimeout)) { - var value = Number(reconnectionTimeout); - if (value > 0) { - return value; - } - } - } - } - }; - }; - Transport.C = TransportStatus; - return Transport; -}(core_1.Transport)); -exports.Transport = Transport; diff --git a/lib/Web/index.d.ts b/lib/Web/index.d.ts deleted file mode 100644 index e65446ce8..000000000 --- a/lib/Web/index.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -import * as Modifiers from "./Modifiers"; -export { Modifiers }; -export { Simple } from "./Simple"; -export { SessionDescriptionHandler } from "./SessionDescriptionHandler"; -export { Transport } from "./Transport"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/Web/index.d.ts.map b/lib/Web/index.d.ts.map deleted file mode 100644 index 519f5c402..000000000 --- a/lib/Web/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/Web/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,SAAS,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,CAAC;AACrB,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAClC,OAAO,EAAE,yBAAyB,EAAE,MAAM,6BAA6B,CAAC;AACxE,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC"} \ No newline at end of file diff --git a/lib/Web/index.js b/lib/Web/index.js deleted file mode 100644 index 0892aa284..000000000 --- a/lib/Web/index.js +++ /dev/null @@ -1,11 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var Modifiers = tslib_1.__importStar(require("./Modifiers")); -exports.Modifiers = Modifiers; -var Simple_1 = require("./Simple"); -exports.Simple = Simple_1.Simple; -var SessionDescriptionHandler_1 = require("./SessionDescriptionHandler"); -exports.SessionDescriptionHandler = SessionDescriptionHandler_1.SessionDescriptionHandler; -var Transport_1 = require("./Transport"); -exports.Transport = Transport_1.Transport; diff --git a/lib/api/byer-bye-options.d.ts b/lib/api/byer-bye-options.d.ts deleted file mode 100644 index 3fbaac62f..000000000 --- a/lib/api/byer-bye-options.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { OutgoingRequestDelegate, RequestOptions } from "../core"; -/** - * Options for {@link Byer.bye}. - * @public - */ -export interface ByerByeOptions { - /** See `core` API. */ - requestDelegate?: OutgoingRequestDelegate; - /** See `core` API. */ - requestOptions?: RequestOptions; -} -//# sourceMappingURL=byer-bye-options.d.ts.map \ No newline at end of file diff --git a/lib/api/byer-bye-options.d.ts.map b/lib/api/byer-bye-options.d.ts.map deleted file mode 100644 index d147a3da1..000000000 --- a/lib/api/byer-bye-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"byer-bye-options.d.ts","sourceRoot":"","sources":["../../src/api/byer-bye-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAElE;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC7B,sBAAsB;IACtB,eAAe,CAAC,EAAE,uBAAuB,CAAC;IAC1C,sBAAsB;IACtB,cAAc,CAAC,EAAE,cAAc,CAAC;CACjC"} \ No newline at end of file diff --git a/lib/api/byer-bye-options.js b/lib/api/byer-bye-options.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/api/byer-bye-options.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/api/byer-options.d.ts b/lib/api/byer-options.d.ts deleted file mode 100644 index 5e8940c19..000000000 --- a/lib/api/byer-options.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -/** - * Options for {@link Byer} constructor. - * @public - */ -export interface ByerOptions { -} -//# sourceMappingURL=byer-options.d.ts.map \ No newline at end of file diff --git a/lib/api/byer-options.d.ts.map b/lib/api/byer-options.d.ts.map deleted file mode 100644 index 5f6b82467..000000000 --- a/lib/api/byer-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"byer-options.d.ts","sourceRoot":"","sources":["../../src/api/byer-options.ts"],"names":[],"mappings":"AACA;;;GAGG;AACH,MAAM,WAAW,WAAW;CAC3B"} \ No newline at end of file diff --git a/lib/api/byer-options.js b/lib/api/byer-options.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/api/byer-options.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/api/byer.d.ts b/lib/api/byer.d.ts deleted file mode 100644 index 607553b05..000000000 --- a/lib/api/byer.d.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { OutgoingByeRequest } from "../core"; -import { ByerByeOptions } from "./byer-bye-options"; -import { ByerOptions } from "./byer-options"; -import { Session } from "./session"; -/** - * A byer ends a {@link Session} (outgoing BYE). - * @remarks - * Sends an outgoing in dialog BYE request. - * @public - */ -export declare class Byer { - /** The byer session. */ - private _session; - /** - * Constructs a new instance of the `Byer` class. - * @param session - The session the BYE will be sent from. See {@link Session} for details. - * @param options - An options bucket. See {@link ByerOptions} for details. - */ - constructor(session: Session, options?: ByerOptions); - /** The byer session. */ - readonly session: Session; - /** - * Sends the BYE request. - * @param options - {@link ByerByeOptions} options bucket. - */ - bye(options?: ByerByeOptions): Promise; -} -//# sourceMappingURL=byer.d.ts.map \ No newline at end of file diff --git a/lib/api/byer.d.ts.map b/lib/api/byer.d.ts.map deleted file mode 100644 index efe1caf13..000000000 --- a/lib/api/byer.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"byer.d.ts","sourceRoot":"","sources":["../../src/api/byer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAC;AAC7C,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAE7C,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAGpC;;;;;GAKG;AACH,qBAAa,IAAI;IACf,wBAAwB;IACxB,OAAO,CAAC,QAAQ,CAAU;IAE1B;;;;OAIG;gBACS,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,WAAW;IAInD,wBAAwB;aACpB,OAAO,EAAI,OAAO;IAItB;;;OAGG;IACI,GAAG,CAAC,OAAO,GAAE,cAAmB,GAAG,OAAO,CAAC,kBAAkB,CAAC;CAwBtE"} \ No newline at end of file diff --git a/lib/api/byer.js b/lib/api/byer.js deleted file mode 100644 index 2f6c5d123..000000000 --- a/lib/api/byer.js +++ /dev/null @@ -1,58 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var invitation_1 = require("./invitation"); -var session_state_1 = require("./session-state"); -/** - * A byer ends a {@link Session} (outgoing BYE). - * @remarks - * Sends an outgoing in dialog BYE request. - * @public - */ -var Byer = /** @class */ (function () { - /** - * Constructs a new instance of the `Byer` class. - * @param session - The session the BYE will be sent from. See {@link Session} for details. - * @param options - An options bucket. See {@link ByerOptions} for details. - */ - function Byer(session, options) { - this._session = session; - } - Object.defineProperty(Byer.prototype, "session", { - /** The byer session. */ - get: function () { - return this._session; - }, - enumerable: true, - configurable: true - }); - /** - * Sends the BYE request. - * @param options - {@link ByerByeOptions} options bucket. - */ - Byer.prototype.bye = function (options) { - if (options === void 0) { options = {}; } - // guard session state - if (this.session.state !== session_state_1.SessionState.Established && - this.session.state !== session_state_1.SessionState.Terminating) { - var message = "Byer.bye() may only be called if established session."; - if (this.session.state === session_state_1.SessionState.Terminated) { - message += " However this session is already terminated."; - } - else { - if (this.session instanceof invitation_1.Invitation) { - message += " However Invitation.accept() has not yet been called."; - message += " Perhaps you should have called Invitation.reject()?"; - } - else { - message += " However a dialog does not yet exist."; - message += " Perhaps you should have called Inviter.cancel()?"; - } - } - this.session.logger.error(message); - return Promise.reject(new Error("Invalid session state " + this.session.state)); - } - return this.session.bye(options.requestDelegate, options.requestOptions); - }; - return Byer; -}()); -exports.Byer = Byer; diff --git a/lib/api/dtmf.d.ts b/lib/api/dtmf.d.ts deleted file mode 100644 index e64ecd9d2..000000000 --- a/lib/api/dtmf.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { IncomingInfoRequest } from "../core"; -import { Info } from "./info"; -/** - * A DTMF signal (incoming INFO). - * @deprecated Use `Info`. - * @internal - */ -export declare class DTMF extends Info { - private _tone; - private _duration; - /** @internal */ - constructor(incomingInfoRequest: IncomingInfoRequest, tone: string, duration: number); - readonly tone: string; - readonly duration: number; -} -//# sourceMappingURL=dtmf.d.ts.map \ No newline at end of file diff --git a/lib/api/dtmf.d.ts.map b/lib/api/dtmf.d.ts.map deleted file mode 100644 index db1fa199f..000000000 --- a/lib/api/dtmf.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"dtmf.d.ts","sourceRoot":"","sources":["../../src/api/dtmf.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAC9C,OAAO,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AAE9B;;;;GAIG;AACH,qBAAa,IAAK,SAAQ,IAAI;IAE5B,OAAO,CAAC,KAAK,CAAS;IACtB,OAAO,CAAC,SAAS,CAAS;IAE1B,gBAAgB;gBAEd,mBAAmB,EAAE,mBAAmB,EACxC,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,MAAM;aAOd,IAAI,EAAI,MAAM;aAId,QAAQ,EAAI,MAAM;CAGvB"} \ No newline at end of file diff --git a/lib/api/dtmf.js b/lib/api/dtmf.js deleted file mode 100644 index c0ade6eec..000000000 --- a/lib/api/dtmf.js +++ /dev/null @@ -1,35 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var info_1 = require("./info"); -/** - * A DTMF signal (incoming INFO). - * @deprecated Use `Info`. - * @internal - */ -var DTMF = /** @class */ (function (_super) { - tslib_1.__extends(DTMF, _super); - /** @internal */ - function DTMF(incomingInfoRequest, tone, duration) { - var _this = _super.call(this, incomingInfoRequest) || this; - _this._tone = tone; - _this._duration = duration; - return _this; - } - Object.defineProperty(DTMF.prototype, "tone", { - get: function () { - return this._tone; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(DTMF.prototype, "duration", { - get: function () { - return this._duration; - }, - enumerable: true, - configurable: true - }); - return DTMF; -}(info_1.Info)); -exports.DTMF = DTMF; diff --git a/lib/api/emitter.d.ts b/lib/api/emitter.d.ts deleted file mode 100644 index 096684a4c..000000000 --- a/lib/api/emitter.d.ts +++ /dev/null @@ -1,31 +0,0 @@ -/// -import { EventEmitter } from "events"; -/** - * Generic observable. - * @public - */ -export interface Emitter { - /** - * Registers a listener. - * @param listener - Callback function. - */ - on(listener: (data: T) => void): void; - /** - * Unregisters a listener. - * @param listener - Callback function. - */ - off(listener: (data: T) => void): void; - /** - * Registers a listener then unregisters the listener after one event emission. - * @param listener - Callback function. - */ - once(listener: (data: T) => void): void; -} -/** - * Creates an {@link Emitter}. - * @param eventEmitter - An event emitter. - * @param eventName - Event name. - * @internal - */ -export declare function makeEmitter(eventEmitter: EventEmitter, eventName?: string): Emitter; -//# sourceMappingURL=emitter.d.ts.map \ No newline at end of file diff --git a/lib/api/emitter.d.ts.map b/lib/api/emitter.d.ts.map deleted file mode 100644 index 2b7bc5ba7..000000000 --- a/lib/api/emitter.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"emitter.d.ts","sourceRoot":"","sources":["../../src/api/emitter.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAEtC;;;GAGG;AACH,MAAM,WAAW,OAAO,CAAC,CAAC;IACxB;;;OAGG;IACH,EAAE,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,IAAI,GAAG,IAAI,CAAC;IACtC;;;OAGG;IACH,GAAG,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,IAAI,GAAG,IAAI,CAAC;IACvC;;;OAGG;IACH,IAAI,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,IAAI,GAAG,IAAI,CAAC;CACzC;AAED;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,CAAC,EAAE,YAAY,EAAE,YAAY,EAAE,SAAS,GAAE,MAAgB,GAAG,OAAO,CAAC,CAAC,CAAC,CAYlG"} \ No newline at end of file diff --git a/lib/api/emitter.js b/lib/api/emitter.js deleted file mode 100644 index 468578981..000000000 --- a/lib/api/emitter.js +++ /dev/null @@ -1,23 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * Creates an {@link Emitter}. - * @param eventEmitter - An event emitter. - * @param eventName - Event name. - * @internal - */ -function makeEmitter(eventEmitter, eventName) { - if (eventName === void 0) { eventName = "event"; } - return { - on: function (listener) { - eventEmitter.on(eventName, listener); - }, - off: function (listener) { - eventEmitter.removeListener(eventName, listener); - }, - once: function (listener) { - eventEmitter.once(eventName, listener); - } - }; -} -exports.makeEmitter = makeEmitter; diff --git a/lib/api/index.d.ts b/lib/api/index.d.ts deleted file mode 100644 index 11397c1d0..000000000 --- a/lib/api/index.d.ts +++ /dev/null @@ -1,58 +0,0 @@ -/** - * A simple yet powerful API which takes care of SIP signaling and WebRTC media sessions for you. - * @packageDocumentation - */ -export * from "./byer-bye-options"; -export * from "./byer-options"; -export * from "./byer"; -export * from "./emitter"; -export * from "./info"; -export * from "./infoer-info-options"; -export * from "./infoer-options"; -export * from "./infoer"; -export * from "./invitation-accept-options"; -export * from "./invitation-progress-options"; -export * from "./invitation-reject-options"; -export * from "./invitation"; -export * from "./inviter-cancel-options"; -export * from "./inviter-invite-options"; -export * from "./inviter-options"; -export * from "./inviter"; -export * from "./message"; -export * from "./messager-options"; -export * from "./messager"; -export * from "./notification"; -export * from "./publisher-options"; -export * from "./publisher-publish-options"; -export * from "./publisher-unpublish-options"; -export * from "./publisher"; -export * from "./referral"; -export * from "./referrer-delegate"; -export * from "./referrer-options"; -export * from "./referrer-refer-options"; -export * from "./referrer"; -export * from "./registerer-options"; -export * from "./registerer-register-options"; -export * from "./registerer-state"; -export * from "./registerer-unregister-options"; -export * from "./registerer"; -export * from "./session-delegate"; -export * from "./session-description-handler-factory"; -export * from "./session-description-handler"; -export * from "./session-invite-options"; -export * from "./session-options"; -export * from "./session-state"; -export * from "./session"; -export * from "./subscriber-options"; -export * from "./subscriber-subscribe-options"; -export * from "./subscriber"; -export * from "./subscription-delegate"; -export * from "./subscription-options"; -export * from "./subscription-state"; -export * from "./subscription-subscribe-options"; -export * from "./subscription-unsubscribe-options"; -export * from "./subscription"; -export * from "./user-agent-delegate"; -export * from "./user-agent-options"; -export * from "./user-agent"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/api/index.d.ts.map b/lib/api/index.d.ts.map deleted file mode 100644 index 67852d6ed..000000000 --- a/lib/api/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/api/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,cAAc,oBAAoB,CAAC;AACnC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,QAAQ,CAAC;AACvB,cAAc,WAAW,CAAC;AAC1B,cAAc,QAAQ,CAAC;AACvB,cAAc,uBAAuB,CAAC;AACtC,cAAc,kBAAkB,CAAC;AACjC,cAAc,UAAU,CAAC;AACzB,cAAc,6BAA6B,CAAC;AAC5C,cAAc,+BAA+B,CAAC;AAC9C,cAAc,6BAA6B,CAAC;AAC5C,cAAc,cAAc,CAAC;AAC7B,cAAc,0BAA0B,CAAC;AACzC,cAAc,0BAA0B,CAAC;AACzC,cAAc,mBAAmB,CAAC;AAClC,cAAc,WAAW,CAAC;AAC1B,cAAc,WAAW,CAAC;AAC1B,cAAc,oBAAoB,CAAC;AACnC,cAAc,YAAY,CAAC;AAC3B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,qBAAqB,CAAC;AACpC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,+BAA+B,CAAC;AAC9C,cAAc,aAAa,CAAC;AAC5B,cAAc,YAAY,CAAC;AAC3B,cAAc,qBAAqB,CAAC;AACpC,cAAc,oBAAoB,CAAC;AACnC,cAAc,0BAA0B,CAAC;AACzC,cAAc,YAAY,CAAC;AAC3B,cAAc,sBAAsB,CAAC;AACrC,cAAc,+BAA+B,CAAC;AAC9C,cAAc,oBAAoB,CAAC;AACnC,cAAc,iCAAiC,CAAC;AAChD,cAAc,cAAc,CAAC;AAC7B,cAAc,oBAAoB,CAAC;AACnC,cAAc,uCAAuC,CAAC;AACtD,cAAc,+BAA+B,CAAC;AAC9C,cAAc,0BAA0B,CAAC;AACzC,cAAc,mBAAmB,CAAC;AAClC,cAAc,iBAAiB,CAAC;AAChC,cAAc,WAAW,CAAC;AAC1B,cAAc,sBAAsB,CAAC;AACrC,cAAc,gCAAgC,CAAC;AAC/C,cAAc,cAAc,CAAC;AAC7B,cAAc,yBAAyB,CAAC;AACxC,cAAc,wBAAwB,CAAC;AACvC,cAAc,sBAAsB,CAAC;AACrC,cAAc,kCAAkC,CAAC;AACjD,cAAc,oCAAoC,CAAC;AACnD,cAAc,gBAAgB,CAAC;AAC/B,cAAc,uBAAuB,CAAC;AACtC,cAAc,sBAAsB,CAAC;AACrC,cAAc,cAAc,CAAC"} \ No newline at end of file diff --git a/lib/api/index.js b/lib/api/index.js deleted file mode 100644 index 91af2d22a..000000000 --- a/lib/api/index.js +++ /dev/null @@ -1,24 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -tslib_1.__exportStar(require("./byer"), exports); -tslib_1.__exportStar(require("./emitter"), exports); -tslib_1.__exportStar(require("./info"), exports); -tslib_1.__exportStar(require("./infoer"), exports); -tslib_1.__exportStar(require("./invitation"), exports); -tslib_1.__exportStar(require("./inviter"), exports); -tslib_1.__exportStar(require("./message"), exports); -tslib_1.__exportStar(require("./messager"), exports); -tslib_1.__exportStar(require("./notification"), exports); -tslib_1.__exportStar(require("./publisher"), exports); -tslib_1.__exportStar(require("./referral"), exports); -tslib_1.__exportStar(require("./referrer"), exports); -tslib_1.__exportStar(require("./registerer-state"), exports); -tslib_1.__exportStar(require("./registerer"), exports); -tslib_1.__exportStar(require("./session-state"), exports); -tslib_1.__exportStar(require("./session"), exports); -tslib_1.__exportStar(require("./subscriber"), exports); -tslib_1.__exportStar(require("./subscription-state"), exports); -tslib_1.__exportStar(require("./subscription"), exports); -tslib_1.__exportStar(require("./user-agent-options"), exports); -tslib_1.__exportStar(require("./user-agent"), exports); diff --git a/lib/api/info.d.ts b/lib/api/info.d.ts deleted file mode 100644 index 8eb6b3745..000000000 --- a/lib/api/info.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { IncomingInfoRequest, IncomingRequestMessage, ResponseOptions } from "../core"; -/** - * An exchange of information (incoming INFO). - * @public - */ -export declare class Info { - private incomingInfoRequest; - /** @internal */ - constructor(incomingInfoRequest: IncomingInfoRequest); - /** Incoming MESSAGE request message. */ - readonly request: IncomingRequestMessage; - /** Accept the request. */ - accept(options?: ResponseOptions): Promise; - /** Reject the request. */ - reject(options?: ResponseOptions): Promise; -} -//# sourceMappingURL=info.d.ts.map \ No newline at end of file diff --git a/lib/api/info.d.ts.map b/lib/api/info.d.ts.map deleted file mode 100644 index bb947dc60..000000000 --- a/lib/api/info.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"info.d.ts","sourceRoot":"","sources":["../../src/api/info.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mBAAmB,EACnB,sBAAsB,EACtB,eAAe,EAChB,MAAM,SAAS,CAAC;AAEjB;;;GAGG;AACH,qBAAa,IAAI;IAGH,OAAO,CAAC,mBAAmB;IADvC,gBAAgB;gBACI,mBAAmB,EAAE,mBAAmB;IAG5D,wCAAwC;aACpC,OAAO,EAAI,sBAAsB;IAIrC,0BAA0B;IACnB,MAAM,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC;IAKvD,0BAA0B;IACnB,MAAM,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC;CAIxD"} \ No newline at end of file diff --git a/lib/api/info.js b/lib/api/info.js deleted file mode 100644 index 9c2dc09b3..000000000 --- a/lib/api/info.js +++ /dev/null @@ -1,32 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * An exchange of information (incoming INFO). - * @public - */ -var Info = /** @class */ (function () { - /** @internal */ - function Info(incomingInfoRequest) { - this.incomingInfoRequest = incomingInfoRequest; - } - Object.defineProperty(Info.prototype, "request", { - /** Incoming MESSAGE request message. */ - get: function () { - return this.incomingInfoRequest.message; - }, - enumerable: true, - configurable: true - }); - /** Accept the request. */ - Info.prototype.accept = function (options) { - this.incomingInfoRequest.accept(options); - return Promise.resolve(); - }; - /** Reject the request. */ - Info.prototype.reject = function (options) { - this.incomingInfoRequest.reject(options); - return Promise.resolve(); - }; - return Info; -}()); -exports.Info = Info; diff --git a/lib/api/infoer-info-options.d.ts b/lib/api/infoer-info-options.d.ts deleted file mode 100644 index a72052207..000000000 --- a/lib/api/infoer-info-options.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { OutgoingRequestDelegate, RequestOptions } from "../core"; -/** - * Options for {@link Infoer.info}. - * @public - */ -export interface InfoerInfoOptions { - /** See `core` API. */ - requestDelegate?: OutgoingRequestDelegate; - /** See `core` API. */ - requestOptions?: RequestOptions; -} -//# sourceMappingURL=infoer-info-options.d.ts.map \ No newline at end of file diff --git a/lib/api/infoer-info-options.d.ts.map b/lib/api/infoer-info-options.d.ts.map deleted file mode 100644 index d68ce8563..000000000 --- a/lib/api/infoer-info-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"infoer-info-options.d.ts","sourceRoot":"","sources":["../../src/api/infoer-info-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAElE;;;GAGG;AACH,MAAM,WAAW,iBAAiB;IAChC,sBAAsB;IACtB,eAAe,CAAC,EAAE,uBAAuB,CAAC;IAC1C,sBAAsB;IACtB,cAAc,CAAC,EAAE,cAAc,CAAC;CACjC"} \ No newline at end of file diff --git a/lib/api/infoer-info-options.js b/lib/api/infoer-info-options.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/api/infoer-info-options.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/api/infoer-options.d.ts b/lib/api/infoer-options.d.ts deleted file mode 100644 index 0371b713a..000000000 --- a/lib/api/infoer-options.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -/** - * Options for {@link Infoer} constructor. - * @public - */ -export interface InfoerOptions { -} -//# sourceMappingURL=infoer-options.d.ts.map \ No newline at end of file diff --git a/lib/api/infoer-options.d.ts.map b/lib/api/infoer-options.d.ts.map deleted file mode 100644 index 953660fd5..000000000 --- a/lib/api/infoer-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"infoer-options.d.ts","sourceRoot":"","sources":["../../src/api/infoer-options.ts"],"names":[],"mappings":"AACA;;;GAGG;AACH,MAAM,WAAW,aAAa;CAC7B"} \ No newline at end of file diff --git a/lib/api/infoer-options.js b/lib/api/infoer-options.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/api/infoer-options.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/api/infoer.d.ts b/lib/api/infoer.d.ts deleted file mode 100644 index 1235e5c0b..000000000 --- a/lib/api/infoer.d.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { OutgoingInfoRequest } from "../core"; -import { InfoerInfoOptions } from "./infoer-info-options"; -import { InfoerOptions } from "./infoer-options"; -import { Session } from "./session"; -/** - * An Infoer sends {@link Info} (outgoing INFO). - * @remarks - * Sends an outgoing in dialog INFO request. - * @public - */ -export declare class Infoer { - /** The Infoer session. */ - private _session; - /** - * Constructs a new instance of the `Infoer` class. - * @param session - The session the INFO will be sent from. See {@link Session} for details. - * @param options - An options bucket. - */ - constructor(session: Session, options?: InfoerOptions); - /** The Infoer session. */ - readonly session: Session; - /** - * Sends the INFO request. - * @param options - {@link InfoerInfoOptions} options bucket. - */ - info(options?: InfoerInfoOptions): Promise; -} -//# sourceMappingURL=infoer.d.ts.map \ No newline at end of file diff --git a/lib/api/infoer.d.ts.map b/lib/api/infoer.d.ts.map deleted file mode 100644 index d91a3d8da..000000000 --- a/lib/api/infoer.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"infoer.d.ts","sourceRoot":"","sources":["../../src/api/infoer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAC9C,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAC1D,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAGpC;;;;;GAKG;AACH,qBAAa,MAAM;IACjB,0BAA0B;IAC1B,OAAO,CAAC,QAAQ,CAAU;IAE1B;;;;OAIG;gBACS,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,aAAa;IAIrD,0BAA0B;aACtB,OAAO,EAAI,OAAO;IAItB;;;OAGG;IACI,IAAI,CAAC,OAAO,GAAE,iBAAsB,GAAG,OAAO,CAAC,mBAAmB,CAAC;CAU3E"} \ No newline at end of file diff --git a/lib/api/infoer.js b/lib/api/infoer.js deleted file mode 100644 index c1a8b347d..000000000 --- a/lib/api/infoer.js +++ /dev/null @@ -1,43 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var session_state_1 = require("./session-state"); -/** - * An Infoer sends {@link Info} (outgoing INFO). - * @remarks - * Sends an outgoing in dialog INFO request. - * @public - */ -var Infoer = /** @class */ (function () { - /** - * Constructs a new instance of the `Infoer` class. - * @param session - The session the INFO will be sent from. See {@link Session} for details. - * @param options - An options bucket. - */ - function Infoer(session, options) { - this._session = session; - } - Object.defineProperty(Infoer.prototype, "session", { - /** The Infoer session. */ - get: function () { - return this._session; - }, - enumerable: true, - configurable: true - }); - /** - * Sends the INFO request. - * @param options - {@link InfoerInfoOptions} options bucket. - */ - Infoer.prototype.info = function (options) { - if (options === void 0) { options = {}; } - // guard session state - if (this.session.state !== session_state_1.SessionState.Established) { - var message = "Infoer.info() may only be called if established session."; - this.session.logger.error(message); - return Promise.reject(new Error("Invalid session state " + this.session.state)); - } - return this.session.info(options.requestDelegate, options.requestOptions); - }; - return Infoer; -}()); -exports.Infoer = Infoer; diff --git a/lib/api/invitation-accept-options.d.ts b/lib/api/invitation-accept-options.d.ts deleted file mode 100644 index 3591d349d..000000000 --- a/lib/api/invitation-accept-options.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { IncomingRequestMessage } from "../core"; -import { SessionDescriptionHandlerModifier, SessionDescriptionHandlerOptions } from "./session-description-handler"; -/** - * Options for {@link Invitation.accept}. - * @public - */ -export interface InvitationAcceptOptions { - /** - * Options to pass to SessionDescriptionHandler's getDescription() and setDescription(). - */ - sessionDescriptionHandlerOptions?: SessionDescriptionHandlerOptions; - /** - * Modifiers to pass to SessionDescriptionHandler's getDescription() and setDescription(). - */ - sessionDescriptionHandlerModifiers?: Array; - /** - * @deprecated Use delegate instead. - * @internal - */ - onInfo?: ((request: IncomingRequestMessage) => void); -} -//# sourceMappingURL=invitation-accept-options.d.ts.map \ No newline at end of file diff --git a/lib/api/invitation-accept-options.d.ts.map b/lib/api/invitation-accept-options.d.ts.map deleted file mode 100644 index 719b9dd1b..000000000 --- a/lib/api/invitation-accept-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"invitation-accept-options.d.ts","sourceRoot":"","sources":["../../src/api/invitation-accept-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,SAAS,CAAC;AACjD,OAAO,EACL,iCAAiC,EACjC,gCAAgC,EACjC,MAAM,+BAA+B,CAAC;AAEvC;;;GAGG;AACH,MAAM,WAAW,uBAAuB;IACtC;;OAEG;IACH,gCAAgC,CAAC,EAAE,gCAAgC,CAAC;IACpE;;OAEG;IACH,kCAAkC,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,CAAC;IAC9E;;;OAGG;IACH,MAAM,CAAC,EAAE,CAAC,CAAC,OAAO,EAAE,sBAAsB,KAAK,IAAI,CAAC,CAAC;CACtD"} \ No newline at end of file diff --git a/lib/api/invitation-accept-options.js b/lib/api/invitation-accept-options.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/api/invitation-accept-options.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/api/invitation-progress-options.d.ts b/lib/api/invitation-progress-options.d.ts deleted file mode 100644 index d7dae21a8..000000000 --- a/lib/api/invitation-progress-options.d.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { SessionDescriptionHandlerModifier, SessionDescriptionHandlerOptions } from "./session-description-handler"; -/** - * Options for {@link Invitation.progress}. - * @public - */ -export interface InvitationProgressOptions { - /** - * Body - */ - body?: string | { - body: string; - contentType: string; - }; - /** - * Array of extra headers added to the response. - */ - extraHeaders?: Array; - /** - * Options to pass to SessionDescriptionHandler's getDescription() and setDescription(). - */ - sessionDescriptionHandlerOptions?: SessionDescriptionHandlerOptions; - /** - * Modifiers to pass to SessionDescriptionHandler's getDescription() and setDescription(). - */ - sessionDescriptionHandlerModifiers?: Array; - /** - * Status code for response. - */ - statusCode?: number; - /** - * Reason phrase for response. - */ - reasonPhrase?: string; - /** - * Send reliable response. - */ - rel100?: boolean; -} -//# sourceMappingURL=invitation-progress-options.d.ts.map \ No newline at end of file diff --git a/lib/api/invitation-progress-options.d.ts.map b/lib/api/invitation-progress-options.d.ts.map deleted file mode 100644 index 55b702428..000000000 --- a/lib/api/invitation-progress-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"invitation-progress-options.d.ts","sourceRoot":"","sources":["../../src/api/invitation-progress-options.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iCAAiC,EACjC,gCAAgC,EACjC,MAAM,+BAA+B,CAAC;AAEvC;;;GAGG;AACH,MAAM,WAAW,yBAAyB;IACxC;;OAEG;IACH,IAAI,CAAC,EAAE,MAAM,GAAG;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,WAAW,EAAE,MAAM,CAAA;KAAE,CAAC;IACtD;;OAEG;IACH,YAAY,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAC7B;;OAEG;IACH,gCAAgC,CAAC,EAAE,gCAAgC,CAAC;IACpE;;OAEG;IACH,kCAAkC,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,CAAC;IAC9E;;OAEG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;OAEG;IACH,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB"} \ No newline at end of file diff --git a/lib/api/invitation-progress-options.js b/lib/api/invitation-progress-options.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/api/invitation-progress-options.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/api/invitation-reject-options.d.ts b/lib/api/invitation-reject-options.d.ts deleted file mode 100644 index 98221ac8c..000000000 --- a/lib/api/invitation-reject-options.d.ts +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Options for {@link Invitation.reject}. - * @public - */ -export interface InvitationRejectOptions { - /** - * Body - */ - body?: string | { - body: string; - contentType: string; - }; - /** - * Array of extra headers added to the response. - */ - extraHeaders?: Array; - /** - * Status code for response. - */ - statusCode?: number; - /** - * Reason phrase for response. - */ - reasonPhrase?: string; -} -//# sourceMappingURL=invitation-reject-options.d.ts.map \ No newline at end of file diff --git a/lib/api/invitation-reject-options.d.ts.map b/lib/api/invitation-reject-options.d.ts.map deleted file mode 100644 index 69c351da8..000000000 --- a/lib/api/invitation-reject-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"invitation-reject-options.d.ts","sourceRoot":"","sources":["../../src/api/invitation-reject-options.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,WAAW,uBAAuB;IACtC;;OAEG;IACH,IAAI,CAAC,EAAE,MAAM,GAAG;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,WAAW,EAAE,MAAM,CAAA;KAAE,CAAC;IACtD;;OAEG;IACH,YAAY,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAC7B;;OAEG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB"} \ No newline at end of file diff --git a/lib/api/invitation-reject-options.js b/lib/api/invitation-reject-options.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/api/invitation-reject-options.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/api/invitation.d.ts b/lib/api/invitation.d.ts deleted file mode 100644 index a1940b438..000000000 --- a/lib/api/invitation.d.ts +++ /dev/null @@ -1,146 +0,0 @@ -import { IncomingInviteRequest, IncomingRequestMessage, IncomingResponseMessage, InviteServerTransaction, NameAddrHeader, NonInviteServerTransaction } from "../core"; -import { InvitationAcceptOptions } from "./invitation-accept-options"; -import { InvitationProgressOptions } from "./invitation-progress-options"; -import { InvitationRejectOptions } from "./invitation-reject-options"; -import { Session } from "./session"; -import { UserAgent } from "./user-agent"; -/** - * An invitation is an offer to establish a {@link Session} (incoming INVITE). - * @public - */ -export declare class Invitation extends Session { - private incomingInviteRequest; - /** @internal */ - body: string | undefined; - /** @internal */ - localIdentity: NameAddrHeader; - /** @internal */ - remoteIdentity: NameAddrHeader; - /** @internal */ - transaction: InviteServerTransaction | NonInviteServerTransaction; - /** - * FIXME: TODO: - * Used to squelch throwing of errors due to async race condition. - * We have an internal race between calling `accept()` and handling - * an incoming CANCEL request. As there is no good way currently to - * delegate the handling of this async errors to the caller of - * `accept()`, we are squelching the throwing ALL errors when - * they occur after receiving a CANCEL to catch the ONE we know - * is a "normal" exceptional condition. While this is a completely - * reasonable appraoch, the decision should be left up to the library user. - */ - private _canceled; - private rseq; - private waitingForPrackPromise; - private waitingForPrackResolve; - private waitingForPrackReject; - /** @internal */ - constructor(userAgent: UserAgent, incomingInviteRequest: IncomingInviteRequest); - /** - * If true, a first provisional response after the 100 Trying - * will be sent automatically. This is false it the UAC required - * reliable provisional responses (100rel in Require header), - * otherwise it is true. The provisional is sent by calling - * `progress()` without any options. - * - * FIXME: TODO: It seems reasonable that the ISC user should - * be able to optionally disable this behavior. As the provisional - * is sent prior to the "invite" event being emitted, it's a known - * issue that the ISC user cannot register listeners or do any other - * setup prior to the call to `progress()`. As an example why this is - * an issue, setting `ua.configuration.rel100` to REQUIRED will result - * in an attempt by `progress()` to send a 183 with SDP produced by - * calling `getDescription()` on a session description handler, but - * the ISC user cannot perform any potentially required session description - * handler initialization (thus preventing the utilization of setting - * `ua.configuration.rel100` to REQUIRED). That begs the question of - * why this behavior is disabled when the UAC requires 100rel but not - * when the UAS requires 100rel? But ignoring that, it's just one example - * of a class of cases where the ISC user needs to do something prior - * to the first call to `progress()` and is unable to do so. - * @internal - */ - readonly autoSendAnInitialProvisionalResponse: boolean; - /** Incoming MESSAGE request message. */ - readonly request: IncomingRequestMessage; - /** - * Accept the invitation. - * @remarks - * Accept the incoming INVITE request to start a Session. - * Replies to the INVITE request with a 200 Ok response. - * @param options - Options bucket. - */ - accept(options?: InvitationAcceptOptions): Promise; - /** - * Indicate progress processing the invitation. - * @remarks - * Report progress to the the caller. - * Replies to the INVITE request with a 1xx provisional response. - * @param options - Options bucket. - */ - progress(options?: InvitationProgressOptions): Promise; - /** - * Reject the invitation. - * @param options - Options bucket. - */ - reject(options?: InvitationRejectOptions): Promise; - /** - * FIXME: Kill this legacy emission - * @internal - */ - byePending(): void; - /** - * Handle CANCEL request. - * @param message - CANCEL message. - * @internal - */ - onCancel(message: IncomingRequestMessage): void; - /** - * Called when session terminated. - * Using it here just for the PRACK timeout. - * @internal - */ - protected terminated(message?: IncomingResponseMessage | IncomingRequestMessage, cause?: string): void; - /** - * A version of `accept` which resolves a session when the 200 Ok response is sent. - * @param options - Options bucket. - */ - private _accept; - /** - * A version of `progress` which resolves when the provisional response is sent. - * @param options - Options bucket. - */ - private _progress; - /** - * A version of `progress` which resolves when the provisional response with sdp is sent. - * @param options - Options bucket. - */ - private _progressWithSDP; - /** - * A version of `progress` which resolves when the reliable provisional response is sent. - * @param options - Options bucket. - */ - private _progressReliable; - /** - * A version of `progress` which resolves when the reliable provisional response is acknowledged. - * @param options - Options bucket. - */ - private _progressReliableWaitForPrack; - private handlePrackOfferAnswer; - /** - * Callback for when ACK for a 2xx response is never received. - * @param session - Session the ACK never arrived for. - */ - private onAckTimeout; - /** - * FIXME: TODO: The current library interface presents async methods without a - * proper async error handling mechanism. Arguably a promise based interface - * would be an improvement over the pattern of returning `this`. The approach has - * been generally along the lines of log a error and terminate. - */ - private onContextError; - private prackArrived; - private prackNeverArrived; - private waitForArrivalOfPrack; -} -//# sourceMappingURL=invitation.d.ts.map \ No newline at end of file diff --git a/lib/api/invitation.d.ts.map b/lib/api/invitation.d.ts.map deleted file mode 100644 index 85f4ce4f0..000000000 --- a/lib/api/invitation.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"invitation.d.ts","sourceRoot":"","sources":["../../src/api/invitation.ts"],"names":[],"mappings":"AACA,OAAO,EAML,qBAAqB,EAErB,sBAAsB,EACtB,uBAAuB,EACvB,uBAAuB,EACvB,cAAc,EACd,0BAA0B,EAK3B,MAAM,SAAS,CAAC;AAKjB,OAAO,EAAE,uBAAuB,EAAE,MAAM,6BAA6B,CAAC;AACtE,OAAO,EAAE,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAC1E,OAAO,EAAE,uBAAuB,EAAE,MAAM,6BAA6B,CAAC;AACtE,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAMpC,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAMzC;;;GAGG;AACH,qBAAa,UAAW,SAAQ,OAAO;IA8CH,OAAO,CAAC,qBAAqB;IAtC/D,gBAAgB;IACT,IAAI,EAAE,MAAM,GAAG,SAAS,CAAa;IAE5C,gBAAgB;IACT,aAAa,EAAE,cAAc,CAAC;IACrC,gBAAgB;IACT,cAAc,EAAE,cAAc,CAAC;IAEtC,gBAAgB;IACT,WAAW,EAAG,uBAAuB,GAAG,0BAA0B,CAAC;IAS1E;;;;;;;;;;OAUG;IACH,OAAO,CAAC,SAAS,CAAS;IAE1B,OAAO,CAAC,IAAI,CAAqC;IAEjD,OAAO,CAAC,sBAAsB,CAA4B;IAC1D,OAAO,CAAC,sBAAsB,CAA8B;IAC5D,OAAO,CAAC,qBAAqB,CAA6B;IAE1D,gBAAgB;gBACJ,SAAS,EAAE,SAAS,EAAU,qBAAqB,EAAE,qBAAqB;IA4FtF;;;;;;;;;;;;;;;;;;;;;;;OAuBG;aACC,oCAAoC,EAAI,OAAO;IAInD,wCAAwC;aACpC,OAAO,EAAI,sBAAsB;IAIrC;;;;;;OAMG;IACI,MAAM,CAAC,OAAO,GAAE,uBAA4B,GAAG,OAAO,CAAC,IAAI,CAAC;IA2CnE;;;;;;OAMG;IACI,QAAQ,CAAC,OAAO,GAAE,yBAA8B,GAAG,OAAO,CAAC,IAAI,CAAC;IA4FvE;;;OAGG;IACI,MAAM,CAAC,OAAO,GAAE,uBAA4B,GAAG,OAAO,CAAC,IAAI,CAAC;IA2CnE;;;OAGG;IACI,UAAU,IAAI,IAAI;IAKzB;;;;OAIG;IACI,QAAQ,CAAC,OAAO,EAAE,sBAAsB,GAAG,IAAI;IA0BtD;;;;OAIG;IACH,SAAS,CAAC,UAAU,CAAC,OAAO,CAAC,EAAE,uBAAuB,GAAG,sBAAsB,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI;IAKtG;;;OAGG;IACH,OAAO,CAAC,OAAO;IA6Cf;;;OAGG;IACH,OAAO,CAAC,SAAS;IA6BjB;;;OAGG;IACH,OAAO,CAAC,gBAAgB;IAexB;;;OAGG;IACH,OAAO,CAAC,iBAAiB;IAOzB;;;OAGG;IACH,OAAO,CAAC,6BAA6B;IAyFrC,OAAO,CAAC,sBAAsB;IA6C9B;;;OAGG;IACH,OAAO,CAAC,YAAY;IAWpB;;;;;OAKG;IACH,OAAO,CAAC,cAAc;IAiCtB,OAAO,CAAC,YAAY;IASpB,OAAO,CAAC,iBAAiB;IASzB,OAAO,CAAC,qBAAqB;CAU9B"} \ No newline at end of file diff --git a/lib/api/invitation.js b/lib/api/invitation.js deleted file mode 100644 index 99fef91db..000000000 --- a/lib/api/invitation.js +++ /dev/null @@ -1,705 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var Constants_1 = require("../Constants"); -var core_1 = require("../core"); -var utils_1 = require("../core/messages/utils"); -var Enums_1 = require("../Enums"); -var Exceptions_1 = require("../Exceptions"); -var session_1 = require("./session"); -var session_state_1 = require("./session-state"); -var user_agent_options_1 = require("./user-agent-options"); -/** - * An invitation is an offer to establish a {@link Session} (incoming INVITE). - * @public - */ -var Invitation = /** @class */ (function (_super) { - tslib_1.__extends(Invitation, _super); - /** @internal */ - function Invitation(userAgent, incomingInviteRequest) { - var _this = _super.call(this, userAgent) || this; - _this.incomingInviteRequest = incomingInviteRequest; - // BEGIN ServerContext Interface - // public type: TypeStrings; - // public ua: UA; - // public logger: Logger; - // public data: any = {}; - // public method = C.INVITE; - /** @internal */ - _this.body = undefined; - // public accept: (options: any = {}) => any; - // public progress: (options: any = {}) => any; - // public reject: (options: any = {}) => any; - // public reply!: (options: any) => any; // not used - // public onRequestTimeout: () => void; - // public onTransportError: () => void; - // END ServerContext interface - /** - * FIXME: TODO: - * Used to squelch throwing of errors due to async race condition. - * We have an internal race between calling `accept()` and handling - * an incoming CANCEL request. As there is no good way currently to - * delegate the handling of this async errors to the caller of - * `accept()`, we are squelching the throwing ALL errors when - * they occur after receiving a CANCEL to catch the ONE we know - * is a "normal" exceptional condition. While this is a completely - * reasonable appraoch, the decision should be left up to the library user. - */ - _this._canceled = false; - _this.rseq = Math.floor(Math.random() * 10000); - // ServerContext properties - _this.type = Enums_1.TypeStrings.InviteServerContext; - _this.logger = userAgent.getLogger("sip.invitation", _this.id); - if (_this.request.body) { - _this.body = _this.request.body; - } - if (_this.request.hasHeader("Content-Type")) { - _this.contentType = _this.request.getHeader("Content-Type"); - } - _this.localIdentity = _this.request.to; - _this.remoteIdentity = _this.request.from; - var hasAssertedIdentity = _this.request.hasHeader("P-Asserted-Identity"); - if (hasAssertedIdentity) { - var assertedIdentity = _this.request.getHeader("P-Asserted-Identity"); - if (assertedIdentity) { - _this.assertedIdentity = core_1.Grammar.nameAddrHeaderParse(assertedIdentity); - } - } - // Session properties - _this.contact = _this.userAgent.contact.toString(); - _this.fromTag = _this.request.fromTag; - _this.id = _this.request.callId + _this.fromTag; - // this.modifiers = - // this.onInfo = - // this.passedOptions = - var contentDisposition = _this.request.parseHeader("Content-Disposition"); - if (contentDisposition && contentDisposition.type === "render") { - _this.renderbody = _this.request.body; - _this.rendertype = _this.request.getHeader("Content-Type"); - } - // FIXME: This is being done twice... - // Update logger - _this.logger = userAgent.getLogger("sip.invitation", _this.id); - // Update status - _this.status = Enums_1.SessionStatus.STATUS_INVITE_RECEIVED; - // Save the session into the ua sessions collection. - _this.userAgent.sessions[_this.id] = _this; - // Set 100rel if necessary - var request = _this.request; - var set100rel = function (header, relSetting) { - if (request.hasHeader(header) && request.getHeader(header).toLowerCase().indexOf("100rel") >= 0) { - _this.rel100 = relSetting; - } - }; - set100rel("require", Constants_1.C.supported.REQUIRED); - set100rel("supported", Constants_1.C.supported.SUPPORTED); - // Set the toTag on the incoming request to the toTag which - // will be used in the response to the incoming request!!! - // FIXME: HACK: This is a hack to port an existing behavior. - // The behavior being ported appears to be a hack itself, - // so this is a hack to port a hack. At least one test spec - // relies on it (which is yet another hack). - _this.request.toTag = incomingInviteRequest.toTag; - // Update status again - sigh - _this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER; - // Set userNoAnswerTimer - _this.userNoAnswerTimer = setTimeout(function () { - // FIXME: refactor the following bit - // transition state - _this.stateTransition(session_state_1.SessionState.Terminated); - incomingInviteRequest.reject({ statusCode: 408 }); - _this.failed(request, Constants_1.C.causes.NO_ANSWER); - _this.terminated(request, Constants_1.C.causes.NO_ANSWER); - }, _this.userAgent.configuration.noAnswerTimeout ? _this.userAgent.configuration.noAnswerTimeout * 1000 : 60000); - // Set expiresTimer (RFC3261 13.3.1) - if (request.hasHeader("expires")) { - var expires = Number(request.getHeader("expires") || 0) * 1000; - _this.expiresTimer = setTimeout(function () { - if (_this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER) { - // FIXME: refactor the following bit - // transition state - _this.stateTransition(session_state_1.SessionState.Terminated); - incomingInviteRequest.reject({ statusCode: 487 }); - _this.failed(request, Constants_1.C.causes.EXPIRES); - _this.terminated(request, Constants_1.C.causes.EXPIRES); - } - }, expires); - } - return _this; - } - Object.defineProperty(Invitation.prototype, "autoSendAnInitialProvisionalResponse", { - /** - * If true, a first provisional response after the 100 Trying - * will be sent automatically. This is false it the UAC required - * reliable provisional responses (100rel in Require header), - * otherwise it is true. The provisional is sent by calling - * `progress()` without any options. - * - * FIXME: TODO: It seems reasonable that the ISC user should - * be able to optionally disable this behavior. As the provisional - * is sent prior to the "invite" event being emitted, it's a known - * issue that the ISC user cannot register listeners or do any other - * setup prior to the call to `progress()`. As an example why this is - * an issue, setting `ua.configuration.rel100` to REQUIRED will result - * in an attempt by `progress()` to send a 183 with SDP produced by - * calling `getDescription()` on a session description handler, but - * the ISC user cannot perform any potentially required session description - * handler initialization (thus preventing the utilization of setting - * `ua.configuration.rel100` to REQUIRED). That begs the question of - * why this behavior is disabled when the UAC requires 100rel but not - * when the UAS requires 100rel? But ignoring that, it's just one example - * of a class of cases where the ISC user needs to do something prior - * to the first call to `progress()` and is unable to do so. - * @internal - */ - get: function () { - return this.rel100 === Constants_1.C.supported.REQUIRED ? false : true; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Invitation.prototype, "request", { - /** Incoming MESSAGE request message. */ - get: function () { - return this.incomingInviteRequest.message; - }, - enumerable: true, - configurable: true - }); - /** - * Accept the invitation. - * @remarks - * Accept the incoming INVITE request to start a Session. - * Replies to the INVITE request with a 200 Ok response. - * @param options - Options bucket. - */ - Invitation.prototype.accept = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - this.logger.log("Invitation.accept"); - // validate state - if (this.state !== session_state_1.SessionState.Initial) { - var error = new Error("Invalid session state " + this.state); - this.logger.error(error.message); - return Promise.reject(error); - } - // transition state - this.stateTransition(session_state_1.SessionState.Establishing); - return this._accept(options) - .then(function (_a) { - var message = _a.message, session = _a.session; - session.delegate = { - onAck: function (ackRequest) { return _this.onAckRequest(ackRequest); }, - onAckTimeout: function () { return _this.onAckTimeout(); }, - onBye: function (byeRequest) { return _this.onByeRequest(byeRequest); }, - onInfo: function (infoRequest) { return _this.onInfoRequest(infoRequest); }, - onInvite: function (inviteRequest) { return _this.onInviteRequest(inviteRequest); }, - onNotify: function (notifyRequest) { return _this.onNotifyRequest(notifyRequest); }, - onPrack: function (prackRequest) { return _this.onPrackRequest(prackRequest); }, - onRefer: function (referRequest) { return _this.onReferRequest(referRequest); } - }; - _this.dialog = session; - _this.stateTransition(session_state_1.SessionState.Established); - // TODO: Reconsider this "automagic" send of a BYE to replacee behavior. - // This behavoir has been ported forward from legacy versions. - if (_this.replacee) { - _this.replacee.bye(); - } - }) - .catch(function (error) { - _this.onContextError(error); - // FIXME: Assuming error due to async race on CANCEL and eating error. - if (!_this._canceled) { - throw error; - } - }); - }; - /** - * Indicate progress processing the invitation. - * @remarks - * Report progress to the the caller. - * Replies to the INVITE request with a 1xx provisional response. - * @param options - Options bucket. - */ - Invitation.prototype.progress = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - this.logger.log("Invitation.progress"); - // validate state - if (this.state !== session_state_1.SessionState.Initial) { - var error = new Error("Invalid session state " + this.state); - this.logger.error(error.message); - return Promise.reject(error); - } - // Ported - var statusCode = options.statusCode || 180; - if (statusCode < 100 || statusCode > 199) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - // Ported - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - this.logger.warn("Unexpected call for progress while terminated, ignoring"); - return Promise.resolve(); - } - // Added - if (this.status === Enums_1.SessionStatus.STATUS_ANSWERED) { - this.logger.warn("Unexpected call for progress while answered, ignoring"); - return Promise.resolve(); - } - // Added - if (this.status === Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK) { - this.logger.warn("Unexpected call for progress while answered (waiting for prack), ignoring"); - return Promise.resolve(); - } - // After the first reliable provisional response for a request has been - // acknowledged, the UAS MAY send additional reliable provisional - // responses. The UAS MUST NOT send a second reliable provisional - // response until the first is acknowledged. After the first, it is - // RECOMMENDED that the UAS not send an additional reliable provisional - // response until the previous is acknowledged. The first reliable - // provisional response receives special treatment because it conveys - // the initial sequence number. If additional reliable provisional - // responses were sent before the first was acknowledged, the UAS could - // not be certain these were received in order. - // https://tools.ietf.org/html/rfc3262#section-3 - if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK) { - this.logger.warn("Unexpected call for progress while waiting for prack, ignoring"); - return Promise.resolve(); - } - // Ported - if (options.statusCode === 100) { - try { - this.incomingInviteRequest.trying(); - } - catch (error) { - this.onContextError(error); - // FIXME: Assuming error due to async race on CANCEL and eating error. - if (!this._canceled) { - return Promise.reject(error); - } - } - return Promise.resolve(); - } - // Standard provisional response. - if (!(this.rel100 === Constants_1.C.supported.REQUIRED) && - !(this.rel100 === Constants_1.C.supported.SUPPORTED && options.rel100) && - !(this.rel100 === Constants_1.C.supported.SUPPORTED && - this.userAgent.configuration.sipExtension100rel === user_agent_options_1.SIPExtension.Required)) { - return this._progress(options) - .then(function (response) { return; }) - .catch(function (error) { - _this.onContextError(error); - // FIXME: Assuming error due to async race on CANCEL and eating error. - if (!_this._canceled) { - throw error; - } - }); - } - // Reliable provisional response. - return this._progressReliableWaitForPrack(options) - .then(function (response) { return; }) - .catch(function (error) { - _this.onContextError(error); - // FIXME: Assuming error due to async race on CANCEL and eating error. - if (!_this._canceled) { - throw error; - } - }); - }; - /** - * Reject the invitation. - * @param options - Options bucket. - */ - Invitation.prototype.reject = function (options) { - if (options === void 0) { options = {}; } - this.logger.log("Invitation.reject"); - // validate state - if (this.state !== session_state_1.SessionState.Initial) { - var error = new Error("Invalid session state " + this.state); - this.logger.error(error.message); - return Promise.reject(error); - } - // transition state - this.stateTransition(session_state_1.SessionState.Terminated); - // Check Session Status - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - throw new Exceptions_1.Exceptions.InvalidStateError(this.status); - } - this.logger.log("rejecting RTCSession"); - var statusCode = options.statusCode || 480; - var reasonPhrase = options.reasonPhrase ? options.reasonPhrase : utils_1.getReasonPhrase(statusCode); - var extraHeaders = options.extraHeaders || []; - if (statusCode < 300 || statusCode > 699) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - var body = options.body ? core_1.fromBodyLegacy(options.body) : undefined; - // FIXME: Need to redirect to someplae - var response = statusCode < 400 ? - this.incomingInviteRequest.redirect([], { statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }) : - this.incomingInviteRequest.reject({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); - this.emit("rejected", response.message, reasonPhrase); - this.emit("failed", response.message, reasonPhrase); - this.terminated(); - return Promise.resolve(); - }; - /** - * FIXME: Kill this legacy emission - * @internal - */ - Invitation.prototype.byePending = function () { - this.emit("bye", this.request); - _super.prototype.byePending.call(this); - }; - /** - * Handle CANCEL request. - * @param message - CANCEL message. - * @internal - */ - Invitation.prototype.onCancel = function (message) { - this.logger.log("Invitation.onCancel"); - // validate state - if (this.state !== session_state_1.SessionState.Initial && - this.state !== session_state_1.SessionState.Establishing) { - this.logger.error("CANCEL received while in state " + this.state + ", dropping request"); - return; - } - // flag canceled - this._canceled = true; - // transition state - this.stateTransition(session_state_1.SessionState.Terminated); - // reject INVITE with 487 status code - this.incomingInviteRequest.reject({ statusCode: 487 }); - this.rejected(message, Constants_1.C.causes.CANCELED); - this.failed(message, Constants_1.C.causes.CANCELED); - this.terminated(message, Constants_1.C.causes.CANCELED); - }; - /** - * Called when session terminated. - * Using it here just for the PRACK timeout. - * @internal - */ - Invitation.prototype.terminated = function (message, cause) { - this.prackNeverArrived(); - _super.prototype.terminated.call(this, message, cause); - }; - /** - * A version of `accept` which resolves a session when the 200 Ok response is sent. - * @param options - Options bucket. - */ - Invitation.prototype._accept = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - // FIXME: Ported - callback for in dialog INFO requests. - // Turns out accept() can be called more than once if we are waiting - // for a PRACK in which case "options" get completely tossed away. - // So this is broken in that case (and potentially other uses of options). - // Tempted to just try to fix it now, but leaving it broken for the moment. - this.onInfo = options.onInfo; - // The UAS MAY send a final response to the initial request before - // having received PRACKs for all unacknowledged reliable provisional - // responses, unless the final response is 2xx and any of the - // unacknowledged reliable provisional responses contained a session - // description. In that case, it MUST NOT send a final response until - // those provisional responses are acknowledged. If the UAS does send a - // final response when reliable responses are still unacknowledged, it - // SHOULD NOT continue to retransmit the unacknowledged reliable - // provisional responses, but it MUST be prepared to process PRACK - // requests for those outstanding responses. A UAS MUST NOT send new - // reliable provisional responses (as opposed to retransmissions of - // unacknowledged ones) after sending a final response to a request. - // https://tools.ietf.org/html/rfc3262#section-3 - if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK) { - this.status = Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK; - return this.waitForArrivalOfPrack() - .then(function () { - _this.status = Enums_1.SessionStatus.STATUS_ANSWERED; - clearTimeout(_this.userNoAnswerTimer); // Ported - }) - .then(function () { return _this.generateResponseOfferAnswer(_this.incomingInviteRequest, options); }) - .then(function (body) { return _this.incomingInviteRequest.accept({ statusCode: 200, body: body }); }); - } - // Ported - if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER) { - this.status = Enums_1.SessionStatus.STATUS_ANSWERED; - } - else { - return Promise.reject(new Exceptions_1.Exceptions.InvalidStateError(this.status)); - } - this.status = Enums_1.SessionStatus.STATUS_ANSWERED; - clearTimeout(this.userNoAnswerTimer); // Ported - return this.generateResponseOfferAnswer(this.incomingInviteRequest, options) - .then(function (body) { return _this.incomingInviteRequest.accept({ statusCode: 200, body: body }); }); - }; - /** - * A version of `progress` which resolves when the provisional response is sent. - * @param options - Options bucket. - */ - Invitation.prototype._progress = function (options) { - if (options === void 0) { options = {}; } - // Ported - var statusCode = options.statusCode || 180; - var reasonPhrase = options.reasonPhrase; - var extraHeaders = (options.extraHeaders || []).slice(); - var body = options.body ? core_1.fromBodyLegacy(options.body) : undefined; - // The 183 (Session Progress) response is used to convey information - // about the progress of the call that is not otherwise classified. The - // Reason-Phrase, header fields, or message body MAY be used to convey - // more details about the call progress. - // https://tools.ietf.org/html/rfc3261#section-21.1.5 - // It is the de facto industry standard to utilize 183 with SDP to provide "early media". - // While it is unlikely someone would want to send a 183 without SDP, so it should be an option. - if (statusCode === 183 && !body) { - return this._progressWithSDP(options); - } - try { - var progressResponse = this.incomingInviteRequest.progress({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); - this.emit("progress", progressResponse.message, reasonPhrase); // Ported - this.dialog = progressResponse.session; - return Promise.resolve(progressResponse); - } - catch (error) { - return Promise.reject(error); - } - }; - /** - * A version of `progress` which resolves when the provisional response with sdp is sent. - * @param options - Options bucket. - */ - Invitation.prototype._progressWithSDP = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - var statusCode = options.statusCode || 183; - var reasonPhrase = options.reasonPhrase; - var extraHeaders = (options.extraHeaders || []).slice(); - // Get an offer/answer and send a reply. - return this.generateResponseOfferAnswer(this.incomingInviteRequest, options) - .then(function (body) { return _this.incomingInviteRequest.progress({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); }) - .then(function (progressResponse) { - _this.emit("progress", progressResponse.message, reasonPhrase); // Ported - _this.dialog = progressResponse.session; - return progressResponse; - }); - }; - /** - * A version of `progress` which resolves when the reliable provisional response is sent. - * @param options - Options bucket. - */ - Invitation.prototype._progressReliable = function (options) { - if (options === void 0) { options = {}; } - options.extraHeaders = (options.extraHeaders || []).slice(); - options.extraHeaders.push("Require: 100rel"); - options.extraHeaders.push("RSeq: " + Math.floor(Math.random() * 10000)); - return this._progressWithSDP(options); - }; - /** - * A version of `progress` which resolves when the reliable provisional response is acknowledged. - * @param options - Options bucket. - */ - Invitation.prototype._progressReliableWaitForPrack = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - var statusCode = options.statusCode || 183; - var reasonPhrase = options.reasonPhrase; - var extraHeaders = (options.extraHeaders || []).slice(); - extraHeaders.push("Require: 100rel"); - extraHeaders.push("RSeq: " + this.rseq++); - var body; - // Ported - set status. - this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK; - return new Promise(function (resolve, reject) { - var waitingForPrack = true; - return _this.generateResponseOfferAnswer(_this.incomingInviteRequest, options) - .then(function (offerAnswer) { - body = offerAnswer; - return _this.incomingInviteRequest.progress({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); - }) - .then(function (progressResponse) { - _this.emit("progress", progressResponse.message, reasonPhrase); // Ported - _this.dialog = progressResponse.session; - var prackRequest; - var prackResponse; - progressResponse.session.delegate = { - onPrack: function (request) { - prackRequest = request; - clearTimeout(prackWaitTimeoutTimer); - clearTimeout(rel1xxRetransmissionTimer); - if (!waitingForPrack) { - return; - } - waitingForPrack = false; - _this.handlePrackOfferAnswer(prackRequest, options) - .then(function (prackResponseBody) { - try { - prackResponse = prackRequest.accept({ statusCode: 200, body: prackResponseBody }); - // Ported - set status. - if (_this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK) { - _this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER; - } - _this.prackArrived(); - resolve({ prackRequest: prackRequest, prackResponse: prackResponse, progressResponse: progressResponse }); - } - catch (error) { - reject(error); - } - }); - } - }; - // https://tools.ietf.org/html/rfc3262#section-3 - var prackWaitTimeout = function () { - if (!waitingForPrack) { - return; - } - waitingForPrack = false; - _this.logger.warn("No PRACK received, rejecting INVITE."); - clearTimeout(rel1xxRetransmissionTimer); - try { - _this.incomingInviteRequest.reject({ statusCode: 504 }); - _this.terminated(undefined, Constants_1.C.causes.NO_PRACK); - reject(new Exceptions_1.Exceptions.TerminatedSessionError()); - } - catch (error) { - reject(error); - } - }; - var prackWaitTimeoutTimer = setTimeout(prackWaitTimeout, core_1.Timers.T1 * 64); - // https://tools.ietf.org/html/rfc3262#section-3 - var rel1xxRetransmission = function () { - try { - _this.incomingInviteRequest.progress({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); - } - catch (error) { - waitingForPrack = false; - reject(error); - return; - } - rel1xxRetransmissionTimer = setTimeout(rel1xxRetransmission, timeout *= 2); - }; - var timeout = core_1.Timers.T1; - var rel1xxRetransmissionTimer = setTimeout(rel1xxRetransmission, timeout); - }); - }); - }; - Invitation.prototype.handlePrackOfferAnswer = function (request, options) { - if (!this.dialog) { - throw new Error("Dialog undefined."); - } - // If the PRACK doesn't have an offer/answer, nothing to be done. - var body = core_1.getBody(request.message); - if (!body || body.contentDisposition !== "session") { - return Promise.resolve(undefined); - } - // If the UAC receives a reliable provisional response with an offer - // (this would occur if the UAC sent an INVITE without an offer, in - // which case the first reliable provisional response will contain the - // offer), it MUST generate an answer in the PRACK. If the UAC receives - // a reliable provisional response with an answer, it MAY generate an - // additional offer in the PRACK. If the UAS receives a PRACK with an - // offer, it MUST place the answer in the 2xx to the PRACK. - // https://tools.ietf.org/html/rfc3262#section-5 - switch (this.dialog.signalingState) { - case core_1.SignalingState.Initial: - // State should never be reached as first reliable provisional response must have answer/offer. - throw new Error("Invalid signaling state " + this.dialog.signalingState + "."); - case core_1.SignalingState.Stable: - // Receved answer. - return this.setAnswer(body, options).then(function () { return undefined; }); - case core_1.SignalingState.HaveLocalOffer: - // State should never be reached as local offer would be answered by this PRACK - throw new Error("Invalid signaling state " + this.dialog.signalingState + "."); - case core_1.SignalingState.HaveRemoteOffer: - // Received offer, generate answer. - return this.setOfferAndGetAnswer(body, options); - case core_1.SignalingState.Closed: - throw new Error("Invalid signaling state " + this.dialog.signalingState + "."); - default: - throw new Error("Invalid signaling state " + this.dialog.signalingState + "."); - } - }; - /** - * Callback for when ACK for a 2xx response is never received. - * @param session - Session the ACK never arrived for. - */ - Invitation.prototype.onAckTimeout = function () { - this.logger.log("Invitation.onAckTimeout"); - if (!this.dialog) { - throw new Error("Dialog undefined."); - } - this.logger.log("No ACK received for an extended period of time, terminating session"); - this.dialog.bye(); - this.stateTransition(session_state_1.SessionState.Terminated); - this.terminated(undefined, Constants_1.C.causes.NO_ACK); - }; - /** - * FIXME: TODO: The current library interface presents async methods without a - * proper async error handling mechanism. Arguably a promise based interface - * would be an improvement over the pattern of returning `this`. The approach has - * been generally along the lines of log a error and terminate. - */ - Invitation.prototype.onContextError = function (error) { - var statusCode = 480; - if (error instanceof core_1.Exception) { // There might be interest in catching these Exceptions. - if (error instanceof Exceptions_1.Exceptions.SessionDescriptionHandlerError) { - this.logger.error(error.message); - if (error.error) { - this.logger.error(error.error); - } - } - else if (error instanceof Exceptions_1.Exceptions.TerminatedSessionError) { - // PRACK never arrived, so we timed out waiting for it. - this.logger.warn("Incoming session terminated while waiting for PRACK."); - } - else if (error instanceof Exceptions_1.Exceptions.UnsupportedSessionDescriptionContentTypeError) { - statusCode = 415; - } - else if (error instanceof core_1.Exception) { - this.logger.error(error.message); - } - } - else if (error instanceof Error) { // Other Errors hould go uncaught. - this.logger.error(error.message); - } - else { - // We don't actually know what a session description handler implementation might throw - // our way, so as a last resort, just assume we are getting an "any" and log it. - this.logger.error("An error occurred in the session description handler."); - this.logger.error(error); - } - try { - this.incomingInviteRequest.reject({ statusCode: statusCode }); // "Temporarily Unavailable" - this.failed(this.incomingInviteRequest.message, error.message); - this.terminated(this.incomingInviteRequest.message, error.message); - } - catch (error) { - return; - } - }; - Invitation.prototype.prackArrived = function () { - if (this.waitingForPrackResolve) { - this.waitingForPrackResolve(); - } - this.waitingForPrackPromise = undefined; - this.waitingForPrackResolve = undefined; - this.waitingForPrackReject = undefined; - }; - Invitation.prototype.prackNeverArrived = function () { - if (this.waitingForPrackReject) { - this.waitingForPrackReject(new Exceptions_1.Exceptions.TerminatedSessionError()); - } - this.waitingForPrackPromise = undefined; - this.waitingForPrackResolve = undefined; - this.waitingForPrackReject = undefined; - }; - Invitation.prototype.waitForArrivalOfPrack = function () { - var _this = this; - if (this.waitingForPrackPromise) { - throw new Error("Already waiting for PRACK"); - } - this.waitingForPrackPromise = new Promise(function (resolve, reject) { - _this.waitingForPrackResolve = resolve; - _this.waitingForPrackReject = reject; - }); - return this.waitingForPrackPromise; - }; - return Invitation; -}(session_1.Session)); -exports.Invitation = Invitation; diff --git a/lib/api/inviter-cancel-options.d.ts b/lib/api/inviter-cancel-options.d.ts deleted file mode 100644 index 1eee02922..000000000 --- a/lib/api/inviter-cancel-options.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -/** - * Options for {@link Inviter.cancel}. - * @public - */ -export interface InviterCancelOptions { - extraHeaders?: Array; - reasonPhrase?: string; - statusCode?: number; -} -//# sourceMappingURL=inviter-cancel-options.d.ts.map \ No newline at end of file diff --git a/lib/api/inviter-cancel-options.d.ts.map b/lib/api/inviter-cancel-options.d.ts.map deleted file mode 100644 index b605b337c..000000000 --- a/lib/api/inviter-cancel-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"inviter-cancel-options.d.ts","sourceRoot":"","sources":["../../src/api/inviter-cancel-options.ts"],"names":[],"mappings":"AACA;;;GAGG;AACH,MAAM,WAAW,oBAAoB;IACnC,YAAY,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAC7B,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB"} \ No newline at end of file diff --git a/lib/api/inviter-cancel-options.js b/lib/api/inviter-cancel-options.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/api/inviter-cancel-options.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/api/inviter-invite-options.d.ts b/lib/api/inviter-invite-options.d.ts deleted file mode 100644 index 1d590e047..000000000 --- a/lib/api/inviter-invite-options.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { OutgoingRequestDelegate, RequestOptions } from "../core"; -import { SessionDescriptionHandlerModifier, SessionDescriptionHandlerOptions } from "./session-description-handler"; -/** - * Options for {@link Inviter.invite}. - * @public - */ -export interface InviterInviteOptions { - /** See `core` API. */ - requestDelegate?: OutgoingRequestDelegate; - /** See `core` API. */ - requestOptions?: RequestOptions; - sessionDescriptionHandlerModifiers?: Array; - sessionDescriptionHandlerOptions?: SessionDescriptionHandlerOptions; - /** If true, send INVITE without SDP. Default is false. */ - withoutSdp?: boolean; -} -//# sourceMappingURL=inviter-invite-options.d.ts.map \ No newline at end of file diff --git a/lib/api/inviter-invite-options.d.ts.map b/lib/api/inviter-invite-options.d.ts.map deleted file mode 100644 index 76823c59e..000000000 --- a/lib/api/inviter-invite-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"inviter-invite-options.d.ts","sourceRoot":"","sources":["../../src/api/inviter-invite-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAClE,OAAO,EACL,iCAAiC,EACjC,gCAAgC,EACjC,MAAM,+BAA+B,CAAC;AAEvC;;;GAGG;AACH,MAAM,WAAW,oBAAoB;IACnC,sBAAsB;IACtB,eAAe,CAAC,EAAE,uBAAuB,CAAC;IAC1C,sBAAsB;IACtB,cAAc,CAAC,EAAE,cAAc,CAAC;IAChC,kCAAkC,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,CAAC;IAC9E,gCAAgC,CAAC,EAAE,gCAAgC,CAAC;IACpE,0DAA0D;IAC1D,UAAU,CAAC,EAAE,OAAO,CAAC;CACtB"} \ No newline at end of file diff --git a/lib/api/inviter-invite-options.js b/lib/api/inviter-invite-options.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/api/inviter-invite-options.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/api/inviter-options.d.ts b/lib/api/inviter-options.d.ts deleted file mode 100644 index 93b96b110..000000000 --- a/lib/api/inviter-options.d.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { URI } from "../core"; -import { SessionDescriptionHandlerModifier } from "./session-description-handler"; -import { SessionDescriptionHandlerOptions } from "./session-description-handler"; -import { SessionOptions } from "./session-options"; -/** - * Options for {@link Inviter} constructor. - * @public - */ -export interface InviterOptions extends SessionOptions { - /** If true, an anonymous call. */ - anonymous?: boolean; - /** @deprecated TODO: provide alternative. */ - body?: string; - /** @deprecated TODO: provide alternative. */ - contentType?: string; - /** - * If true, the first answer to the local offer is immediately utilized for media. - * Requires that the INVITE request MUST NOT fork. - * Has no effect if `inviteWtihoutSdp` is true. - * Default is false. - */ - earlyMedia?: boolean; - /** Array of extra headers added to the INVITE. */ - extraHeaders?: Array; - /** If true, send INVITE without SDP. Default is false. */ - inviteWithoutSdp?: boolean; - /** @deprecated TODO: provide alternative. */ - onInfo?: any; - /** @deprecated TODO: provide alternative. */ - params?: { - fromDisplayName?: string; - fromTag?: string; - fromUri?: string | URI; - toDisplayName?: string; - toUri?: string | URI; - }; - /** @deprecated TODO: provide alternative. */ - renderbody?: string; - /** @deprecated TODO: provide alternative. */ - rendertype?: string; - /** Modifiers to pass to SessionDescriptionHandler's getDescription() and setDescription(). */ - SessionDescriptionHandlerModifiers?: Array; - /** Options to pass to SessionDescriptionHandler's getDescription() and setDescription(). */ - sessionDescriptionHandlerOptions?: SessionDescriptionHandlerOptions; -} -//# sourceMappingURL=inviter-options.d.ts.map \ No newline at end of file diff --git a/lib/api/inviter-options.d.ts.map b/lib/api/inviter-options.d.ts.map deleted file mode 100644 index 18e8969e4..000000000 --- a/lib/api/inviter-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"inviter-options.d.ts","sourceRoot":"","sources":["../../src/api/inviter-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,EAAE,iCAAiC,EAAE,MAAM,+BAA+B,CAAC;AAClF,OAAO,EAAE,gCAAgC,EAAE,MAAM,+BAA+B,CAAC;AACjF,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAEnD;;;GAGG;AACH,MAAM,WAAW,cAAe,SAAQ,cAAc;IACpD,kCAAkC;IAClC,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,6CAA6C;IAC7C,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,6CAA6C;IAC7C,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;;;OAKG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,kDAAkD;IAClD,YAAY,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAC7B,0DAA0D;IAC1D,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,6CAA6C;IAC7C,MAAM,CAAC,EAAE,GAAG,CAAC;IACb,6CAA6C;IAC7C,MAAM,CAAC,EAAE;QACP,eAAe,CAAC,EAAE,MAAM,CAAC;QACzB,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,OAAO,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC;QACvB,aAAa,CAAC,EAAE,MAAM,CAAC;QACvB,KAAK,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC;KACtB,CAAC;IACF,6CAA6C;IAC7C,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,6CAA6C;IAC7C,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,8FAA8F;IAC9F,kCAAkC,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,CAAC;IAC9E,4FAA4F;IAC5F,gCAAgC,CAAC,EAAE,gCAAgC,CAAC;CACrE"} \ No newline at end of file diff --git a/lib/api/inviter-options.js b/lib/api/inviter-options.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/api/inviter-options.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/api/inviter.d.ts b/lib/api/inviter.d.ts deleted file mode 100644 index 1fd863a97..000000000 --- a/lib/api/inviter.d.ts +++ /dev/null @@ -1,196 +0,0 @@ -import { NameAddrHeader, OutgoingInviteRequest, OutgoingRequestMessage, URI } from "../core"; -import { InviterCancelOptions } from "./inviter-cancel-options"; -import { InviterInviteOptions } from "./inviter-invite-options"; -import { InviterOptions } from "./inviter-options"; -import { Session } from "./session"; -import { BodyAndContentType } from "./session-description-handler"; -import { UserAgent } from "./user-agent"; -/** - * An inviter offers to establish a {@link Session} (outgoing INVITE). - * @public - */ -export declare class Inviter extends Session { - /** @internal */ - body: BodyAndContentType | undefined; - /** @internal */ - localIdentity: NameAddrHeader; - /** @internal */ - remoteIdentity: NameAddrHeader; - /** @internal */ - request: OutgoingRequestMessage; - /** True if cancel() was called. */ - /** @internal */ - isCanceled: boolean; - /** If this Inviter was created as a result of a REFER, the reffered Session. Otherwise undefined. */ - /** @internal */ - referred: Session | undefined; - private earlyMedia; - private earlyMediaDialog; - private earlyMediaSessionDescriptionHandlers; - private inviteWithoutSdp; - private outgoingInviteRequest; - /** - * Constructs a new instance of the `Inviter` class. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @param targetURI - Request URI identifying the target of the message. - * @param options - Options bucket. See {@link InviterOptions} for details. - */ - constructor(userAgent: UserAgent, targetURI: URI, options?: InviterOptions); - /** - * Cancels the INVITE request. - * @param options - Options bucket. - */ - cancel(options?: InviterCancelOptions): Promise; - /** - * Sends the INVITE request. - * @remarks - * TLDR... - * 1) Only one offer/answer exchange permitted during initial INVITE. - * 2) No "early media" if the initial offer is in an INVITE (default behavior). - * 3) If "early media" and the initial offer is in an INVITE, no INVITE forking. - * - * 1) Only one offer/answer exchange permitted during initial INVITE. - * - * Our implementation replaces the following bullet point... - * - * o After having sent or received an answer to the first offer, the - * UAC MAY generate subsequent offers in requests based on rules - * specified for that method, but only if it has received answers - * to any previous offers, and has not sent any offers to which it - * hasn't gotten an answer. - * https://tools.ietf.org/html/rfc3261#section-13.2.1 - * - * ...with... - * - * o After having sent or received an answer to the first offer, the - * UAC MUST NOT generate subsequent offers in requests based on rules - * specified for that method. - * - * ...which in combination with this bullet point... - * - * o Once the UAS has sent or received an answer to the initial - * offer, it MUST NOT generate subsequent offers in any responses - * to the initial INVITE. This means that a UAS based on this - * specification alone can never generate subsequent offers until - * completion of the initial transaction. - * https://tools.ietf.org/html/rfc3261#section-13.2.1 - * - * ...ensures that EXACTLY ONE offer/answer exchange will occur - * during an initial out of dialog INVITE request made by our UAC. - * - * - * 2) No "early media" if the initial offer is in an INVITE (default behavior). - * - * While our implementation adheres to the following bullet point... - * - * o If the initial offer is in an INVITE, the answer MUST be in a - * reliable non-failure message from UAS back to UAC which is - * correlated to that INVITE. For this specification, that is - * only the final 2xx response to that INVITE. That same exact - * answer MAY also be placed in any provisional responses sent - * prior to the answer. The UAC MUST treat the first session - * description it receives as the answer, and MUST ignore any - * session descriptions in subsequent responses to the initial - * INVITE. - * https://tools.ietf.org/html/rfc3261#section-13.2.1 - * - * We have made the following implementation decision with regard to early media... - * - * o If the initial offer is in the INVITE, the answer from the - * UAS back to the UAC will establish a media session only - * only after the final 2xx response to that INVITE is received. - * - * The reason for this decision is rooted in a restriction currently - * inherent in WebRTC. Specifically, while a SIP INVITE request with an - * initial offer may fork resulting in more than one provisional answer, - * there is currently no easy/good way to to "fork" an offer generated - * by a peer connection. In particular, a WebRTC offer currently may only - * be matched with one answer and we have no good way to know which - * "provisional answer" is going to be the "final answer". So we have - * decided to punt and not create any "early media" sessions in this case. - * - * The upshot is that if you want "early media", you must not put the - * initial offer in the INVITE. Instead, force the UAS to provide the - * initial offer by sending an INVITE without an offer. In the WebRTC - * case this allows us to create a unique peer connection with a unique - * answer for every provisional offer with "early media" on all of them. - * - * - * 3) If "early media" and the initial offer is in an INVITE, no INVITE forking. - * - * The default behaviour may be altered and "early media" utilized if the - * initial offer is in the an INVITE by setting the `earlyMedia` options. - * However in that case the INVITE request MUST NOT fork. This allows for - * "early media" in environments where the forking behaviour of the SIP - * servers being utilized is configured to disallow forking. - */ - invite(options?: InviterInviteOptions): Promise; - /** - * 13.2.1 Creating the Initial INVITE - * - * Since the initial INVITE represents a request outside of a dialog, - * its construction follows the procedures of Section 8.1.1. Additional - * processing is required for the specific case of INVITE. - * - * An Allow header field (Section 20.5) SHOULD be present in the INVITE. - * It indicates what methods can be invoked within a dialog, on the UA - * sending the INVITE, for the duration of the dialog. For example, a - * UA capable of receiving INFO requests within a dialog [34] SHOULD - * include an Allow header field listing the INFO method. - * - * A Supported header field (Section 20.37) SHOULD be present in the - * INVITE. It enumerates all the extensions understood by the UAC. - * - * An Accept (Section 20.1) header field MAY be present in the INVITE. - * It indicates which Content-Types are acceptable to the UA, in both - * the response received by it, and in any subsequent requests sent to - * it within dialogs established by the INVITE. The Accept header field - * is especially useful for indicating support of various session - * description formats. - * - * The UAC MAY add an Expires header field (Section 20.19) to limit the - * validity of the invitation. If the time indicated in the Expires - * header field is reached and no final answer for the INVITE has been - * received, the UAC core SHOULD generate a CANCEL request for the - * INVITE, as per Section 9. - * - * A UAC MAY also find it useful to add, among others, Subject (Section - * 20.36), Organization (Section 20.25) and User-Agent (Section 20.41) - * header fields. They all contain information related to the INVITE. - * - * The UAC MAY choose to add a message body to the INVITE. Section - * 8.1.1.10 deals with how to construct the header fields -- Content- - * Type among others -- needed to describe the message body. - * - * https://tools.ietf.org/html/rfc3261#section-13.2.1 - */ - private sendInvite; - private disposeEarlyMedia; - private notifyReferer; - /** - * Handle final response to initial INVITE. - * @param inviteResponse - 2xx response. - */ - private onAccept; - /** - * Handle provisional response to initial INVITE. - * @param inviteResponse - 1xx response. - */ - private onProgress; - /** - * Handle final response to initial INVITE. - * @param inviteResponse - 3xx response. - */ - private onRedirect; - /** - * Handle final response to initial INVITE. - * @param inviteResponse - 4xx, 5xx, or 6xx response. - */ - private onReject; - /** - * Handle final response to initial INVITE. - * @param inviteResponse - 100 response. - */ - private onTrying; -} -//# sourceMappingURL=inviter.d.ts.map \ No newline at end of file diff --git a/lib/api/inviter.d.ts.map b/lib/api/inviter.d.ts.map deleted file mode 100644 index 32aef6806..000000000 --- a/lib/api/inviter.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"inviter.d.ts","sourceRoot":"","sources":["../../src/api/inviter.ts"],"names":[],"mappings":"AACA,OAAO,EAKL,cAAc,EACd,qBAAqB,EACrB,sBAAsB,EAMtB,GAAG,EACJ,MAAM,SAAS,CAAC;AAKjB,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAChE,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAChE,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EACL,kBAAkB,EAGnB,MAAM,+BAA+B,CAAC;AAEvC,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAGzC;;;GAGG;AACH,qBAAa,OAAQ,SAAQ,OAAO;IAQlC,gBAAgB;IACT,IAAI,EAAE,kBAAkB,GAAG,SAAS,CAAa;IACxD,gBAAgB;IACT,aAAa,EAAE,cAAc,CAAC;IACrC,gBAAgB;IACT,cAAc,EAAE,cAAc,CAAC;IACtC,gBAAgB;IACT,OAAO,EAAE,sBAAsB,CAAC;IAOvC,mCAAmC;IACnC,gBAAgB;IACT,UAAU,EAAE,OAAO,CAAC;IAE3B,qGAAqG;IACrG,gBAAgB;IACT,QAAQ,EAAE,OAAO,GAAG,SAAS,CAAC;IAErC,OAAO,CAAC,UAAU,CAAU;IAC5B,OAAO,CAAC,gBAAgB,CAA4B;IACpD,OAAO,CAAC,oCAAoC,CAAgD;IAC5F,OAAO,CAAC,gBAAgB,CAAU;IAClC,OAAO,CAAC,qBAAqB,CAAoC;IAEjE;;;;;OAKG;gBAED,SAAS,EAAE,SAAS,EACpB,SAAS,EAAE,GAAG,EACd,OAAO,GAAE,cAAmB;IAiJ9B;;;OAGG;IACI,MAAM,CAAC,OAAO,GAAE,oBAAyB,GAAG,OAAO,CAAC,IAAI,CAAC;IAwChE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAkFG;IACI,MAAM,CAAC,OAAO,GAAE,oBAAyB,GAAG,OAAO,CAAC,qBAAqB,CAAC;IA0DjF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAsCG;IACH,OAAO,CAAC,UAAU;IAmPlB,OAAO,CAAC,iBAAiB;IAMzB,OAAO,CAAC,aAAa;IAkDrB;;;OAGG;IACH,OAAO,CAAC,QAAQ;IAoJhB;;;OAGG;IACH,OAAO,CAAC,UAAU;IA2JlB;;;OAGG;IACH,OAAO,CAAC,UAAU;IAwBlB;;;OAGG;IACH,OAAO,CAAC,QAAQ;IAwBhB;;;OAGG;IACH,OAAO,CAAC,QAAQ;CAYjB"} \ No newline at end of file diff --git a/lib/api/inviter.js b/lib/api/inviter.js deleted file mode 100644 index 25089271c..000000000 --- a/lib/api/inviter.js +++ /dev/null @@ -1,987 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var Constants_1 = require("../Constants"); -var core_1 = require("../core"); -var Enums_1 = require("../Enums"); -var Exceptions_1 = require("../Exceptions"); -var Utils_1 = require("../Utils"); -var session_1 = require("./session"); -var session_state_1 = require("./session-state"); -var user_agent_options_1 = require("./user-agent-options"); -/** - * An inviter offers to establish a {@link Session} (outgoing INVITE). - * @public - */ -var Inviter = /** @class */ (function (_super) { - tslib_1.__extends(Inviter, _super); - /** - * Constructs a new instance of the `Inviter` class. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @param targetURI - Request URI identifying the target of the message. - * @param options - Options bucket. See {@link InviterOptions} for details. - */ - function Inviter(userAgent, targetURI, options) { - if (options === void 0) { options = {}; } - var _this = _super.call(this, userAgent, options) || this; - // BEGIN ClientContext interface - // public type: TypeStrings; - // public ua: UA; - // public logger: Logger; - // public data: any = {}; - // public method = C.INVITE; - /** @internal */ - _this.body = undefined; - _this.earlyMediaSessionDescriptionHandlers = new Map(); - // Default options params - options.params = options.params || {}; - // Check Session Status - if (_this.status !== Enums_1.SessionStatus.STATUS_NULL) { - throw new Exceptions_1.Exceptions.InvalidStateError(_this.status); - } - // ClientContext properties - _this.type = Enums_1.TypeStrings.InviteClientContext; - _this.logger = userAgent.getLogger("sip.inviter"); - if (options.body) { - _this.body = { - body: options.body, - contentType: options.contentType ? options.contentType : "application/sdp" - }; - } - // Anonymous call - var anonymous = options.anonymous || false; - if (anonymous && userAgent.configuration.uri) { - options.params.fromDisplayName = "Anonymous"; - options.params.fromUri = "sip:anonymous@anonymous.invalid"; - } - // From Tag - var fromTag = Utils_1.Utils.newTag(); - // Contact - // Do not add ;ob in initial forming dialog requests if the registration over - // the current connection got a GRUU URI. - var contact = userAgent.contact.toString({ - anonymous: anonymous, - outbound: anonymous ? !userAgent.contact.tempGruu : !userAgent.contact.pubGruu - }); - // Params - var params = options.params || {}; - params.fromTag = fromTag; - // URIs - var fromURI = userAgent.userAgentCore.configuration.aor; - if (options.params.fromUri) { - fromURI = - (typeof options.params.fromUri === "string") ? - core_1.Grammar.URIParse(options.params.fromUri) : - options.params.fromUri; - } - if (!fromURI) { - throw new TypeError("Invalid from URI: " + options.params.fromUri); - } - var toURI = targetURI; - if (options.params.toUri) { - toURI = - (typeof options.params.toUri === "string") ? - core_1.Grammar.URIParse(options.params.toUri) : - options.params.toUri; - } - if (!toURI) { - throw new TypeError("Invalid to URI: " + options.params.toUri); - } - // Extra headers - var extraHeaders = (options.extraHeaders || []).slice(); - if (anonymous && userAgent.configuration.uri) { - extraHeaders.push("P-Preferred-Identity: " + userAgent.configuration.uri.toString()); - extraHeaders.push("Privacy: id"); - } - extraHeaders.push("Contact: " + contact); - // This is UA.C.ALLOWED_METHODS, removed to get around circular dependency - extraHeaders.push("Allow: " + [ - "ACK", - "CANCEL", - "INVITE", - "MESSAGE", - "BYE", - "OPTIONS", - "INFO", - "NOTIFY", - "REFER" - ].toString()); - if (userAgent.configuration.sipExtension100rel === user_agent_options_1.SIPExtension.Required) { - extraHeaders.push("Require: 100rel"); - } - if (userAgent.configuration.sipExtensionReplaces === user_agent_options_1.SIPExtension.Required) { - extraHeaders.push("Require: replaces"); - } - var body; - if (_this.body) { - body = Utils_1.Utils.fromBodyObj(_this.body); - } - // Request - _this.request = userAgent.userAgentCore.makeOutgoingRequestMessage(_this.method, targetURI, fromURI, toURI, params, extraHeaders, body); - if (!_this.request.from) { - throw new Error("From undefined."); - } - if (!_this.request.to) { - throw new Error("From undefined."); - } - _this.localIdentity = _this.request.from; - _this.remoteIdentity = _this.request.to; - // Options - options.params = params; - options.extraHeaders = extraHeaders; - // Session properties - _this.contact = contact; - _this.fromTag = fromTag; - _this.id = _this.request.callId + _this.fromTag; - _this.onInfo = options.onInfo; - _this.passedOptions = options; // Save for later to use with refer - _this.renderbody = options.renderbody || undefined; - _this.rendertype = options.rendertype || "text/plain"; - _this.sessionDescriptionHandlerModifiers = options.SessionDescriptionHandlerModifiers || []; - _this.sessionDescriptionHandlerOptions = options.sessionDescriptionHandlerOptions || {}; - // InviteClientContext properties - _this.inviteWithoutSdp = options.inviteWithoutSdp || false; - _this.isCanceled = false; - _this.earlyMedia = options.earlyMedia || false; - userAgent.applicants[_this.toString()] = _this; - return _this; - } - /** - * Cancels the INVITE request. - * @param options - Options bucket. - */ - Inviter.prototype.cancel = function (options) { - if (options === void 0) { options = {}; } - this.logger.log("Inviter.cancel"); - // validate state - if (this.state !== session_state_1.SessionState.Initial && this.state !== session_state_1.SessionState.Establishing) { - var error = new Error("Invalid session state " + this.state); - this.logger.error(error.message); - return Promise.reject(error); - } - // canceled has some special cases - if (this.isCanceled) { - throw new Error("Already canceled."); - } - this.isCanceled = true; - // transition state - this.stateTransition(session_state_1.SessionState.Terminating); - // cleanup media as needed - this.disposeEarlyMedia(); - if (this.sessionDescriptionHandler) { - this.sessionDescriptionHandler.close(); - } - if (this.outgoingInviteRequest) { - // the CANCEL may not be respected by peer(s), so don't transition to terminated - var cancelReason = void 0; - if (options.statusCode && options.reasonPhrase) { - cancelReason = Utils_1.Utils.getCancelReason(options.statusCode, options.reasonPhrase); - } - this.outgoingInviteRequest.cancel(cancelReason, options); - } - else { - this.logger.warn("Canceled session before INVITE was sent"); - this.stateTransition(session_state_1.SessionState.Terminated); - } - return Promise.resolve(); - }; - /** - * Sends the INVITE request. - * @remarks - * TLDR... - * 1) Only one offer/answer exchange permitted during initial INVITE. - * 2) No "early media" if the initial offer is in an INVITE (default behavior). - * 3) If "early media" and the initial offer is in an INVITE, no INVITE forking. - * - * 1) Only one offer/answer exchange permitted during initial INVITE. - * - * Our implementation replaces the following bullet point... - * - * o After having sent or received an answer to the first offer, the - * UAC MAY generate subsequent offers in requests based on rules - * specified for that method, but only if it has received answers - * to any previous offers, and has not sent any offers to which it - * hasn't gotten an answer. - * https://tools.ietf.org/html/rfc3261#section-13.2.1 - * - * ...with... - * - * o After having sent or received an answer to the first offer, the - * UAC MUST NOT generate subsequent offers in requests based on rules - * specified for that method. - * - * ...which in combination with this bullet point... - * - * o Once the UAS has sent or received an answer to the initial - * offer, it MUST NOT generate subsequent offers in any responses - * to the initial INVITE. This means that a UAS based on this - * specification alone can never generate subsequent offers until - * completion of the initial transaction. - * https://tools.ietf.org/html/rfc3261#section-13.2.1 - * - * ...ensures that EXACTLY ONE offer/answer exchange will occur - * during an initial out of dialog INVITE request made by our UAC. - * - * - * 2) No "early media" if the initial offer is in an INVITE (default behavior). - * - * While our implementation adheres to the following bullet point... - * - * o If the initial offer is in an INVITE, the answer MUST be in a - * reliable non-failure message from UAS back to UAC which is - * correlated to that INVITE. For this specification, that is - * only the final 2xx response to that INVITE. That same exact - * answer MAY also be placed in any provisional responses sent - * prior to the answer. The UAC MUST treat the first session - * description it receives as the answer, and MUST ignore any - * session descriptions in subsequent responses to the initial - * INVITE. - * https://tools.ietf.org/html/rfc3261#section-13.2.1 - * - * We have made the following implementation decision with regard to early media... - * - * o If the initial offer is in the INVITE, the answer from the - * UAS back to the UAC will establish a media session only - * only after the final 2xx response to that INVITE is received. - * - * The reason for this decision is rooted in a restriction currently - * inherent in WebRTC. Specifically, while a SIP INVITE request with an - * initial offer may fork resulting in more than one provisional answer, - * there is currently no easy/good way to to "fork" an offer generated - * by a peer connection. In particular, a WebRTC offer currently may only - * be matched with one answer and we have no good way to know which - * "provisional answer" is going to be the "final answer". So we have - * decided to punt and not create any "early media" sessions in this case. - * - * The upshot is that if you want "early media", you must not put the - * initial offer in the INVITE. Instead, force the UAS to provide the - * initial offer by sending an INVITE without an offer. In the WebRTC - * case this allows us to create a unique peer connection with a unique - * answer for every provisional offer with "early media" on all of them. - * - * - * 3) If "early media" and the initial offer is in an INVITE, no INVITE forking. - * - * The default behaviour may be altered and "early media" utilized if the - * initial offer is in the an INVITE by setting the `earlyMedia` options. - * However in that case the INVITE request MUST NOT fork. This allows for - * "early media" in environments where the forking behaviour of the SIP - * servers being utilized is configured to disallow forking. - */ - Inviter.prototype.invite = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - this.logger.log("Inviter.invite"); - // validate state - if (this.state !== session_state_1.SessionState.Initial) { - // re-invite - return _super.prototype.invite.call(this, options); - } - if (!this.id) { - throw new Error("Session id undefined."); - } - // save the session into the user agent sessions collection. - this.userAgent.sessions[this.id] = this; - // just send an INVITE with no sdp... - if (options.withoutSdp || this.inviteWithoutSdp) { - if (this.renderbody && this.rendertype) { - this.request.body = { contentType: this.rendertype, body: this.renderbody }; - } - // transition state - this.stateTransition(session_state_1.SessionState.Establishing); - this.status = Enums_1.SessionStatus.STATUS_INVITE_SENT; - return Promise.resolve(this.sendInvite(options)); - } - // get an offer and send it in an INVITE - var offerOptions = { - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers - }; - return this.getOffer(offerOptions) - .then(function (body) { - // TODO: Review error handling... - // There are some race conditions which can occur, all of which will cause stateTransition() to throw. - // - invite() can be called (a)synchronously after invite() is called (second call to invite() fails) - // - cancel() or terminate()) can be called (a)synchronously after invite() (invite() fails) - // The caller should avoid the first case, but the second one is common. - // For now we are just letting the state transition fail in all cases. - // transition state - _this.stateTransition(session_state_1.SessionState.Establishing); - _this.status = Enums_1.SessionStatus.STATUS_INVITE_SENT; - _this.request.body = { body: body.content, contentType: body.contentType }; - return _this.sendInvite(options); - }) - .catch(function (error) { - _this.logger.log(error.message); - _this.failed(undefined, Constants_1.C.causes.WEBRTC_ERROR); - _this.terminated(undefined, Constants_1.C.causes.WEBRTC_ERROR); - throw error; - }); - }; - /** - * 13.2.1 Creating the Initial INVITE - * - * Since the initial INVITE represents a request outside of a dialog, - * its construction follows the procedures of Section 8.1.1. Additional - * processing is required for the specific case of INVITE. - * - * An Allow header field (Section 20.5) SHOULD be present in the INVITE. - * It indicates what methods can be invoked within a dialog, on the UA - * sending the INVITE, for the duration of the dialog. For example, a - * UA capable of receiving INFO requests within a dialog [34] SHOULD - * include an Allow header field listing the INFO method. - * - * A Supported header field (Section 20.37) SHOULD be present in the - * INVITE. It enumerates all the extensions understood by the UAC. - * - * An Accept (Section 20.1) header field MAY be present in the INVITE. - * It indicates which Content-Types are acceptable to the UA, in both - * the response received by it, and in any subsequent requests sent to - * it within dialogs established by the INVITE. The Accept header field - * is especially useful for indicating support of various session - * description formats. - * - * The UAC MAY add an Expires header field (Section 20.19) to limit the - * validity of the invitation. If the time indicated in the Expires - * header field is reached and no final answer for the INVITE has been - * received, the UAC core SHOULD generate a CANCEL request for the - * INVITE, as per Section 9. - * - * A UAC MAY also find it useful to add, among others, Subject (Section - * 20.36), Organization (Section 20.25) and User-Agent (Section 20.41) - * header fields. They all contain information related to the INVITE. - * - * The UAC MAY choose to add a message body to the INVITE. Section - * 8.1.1.10 deals with how to construct the header fields -- Content- - * Type among others -- needed to describe the message body. - * - * https://tools.ietf.org/html/rfc3261#section-13.2.1 - */ - Inviter.prototype.sendInvite = function (options) { - // There are special rules for message bodies that contain a session - // description - their corresponding Content-Disposition is "session". - // SIP uses an offer/answer model where one UA sends a session - // description, called the offer, which contains a proposed description - // of the session. The offer indicates the desired communications means - // (audio, video, games), parameters of those means (such as codec - // types) and addresses for receiving media from the answerer. The - // other UA responds with another session description, called the - // answer, which indicates which communications means are accepted, the - // parameters that apply to those means, and addresses for receiving - // media from the offerer. An offer/answer exchange is within the - // context of a dialog, so that if a SIP INVITE results in multiple - // dialogs, each is a separate offer/answer exchange. The offer/answer - // model defines restrictions on when offers and answers can be made - // (for example, you cannot make a new offer while one is in progress). - // This results in restrictions on where the offers and answers can - // appear in SIP messages. In this specification, offers and answers - // can only appear in INVITE requests and responses, and ACK. The usage - // of offers and answers is further restricted. For the initial INVITE - // transaction, the rules are: - // - // o The initial offer MUST be in either an INVITE or, if not there, - // in the first reliable non-failure message from the UAS back to - // the UAC. In this specification, that is the final 2xx - // response. - // - // o If the initial offer is in an INVITE, the answer MUST be in a - // reliable non-failure message from UAS back to UAC which is - // correlated to that INVITE. For this specification, that is - // only the final 2xx response to that INVITE. That same exact - // answer MAY also be placed in any provisional responses sent - // prior to the answer. The UAC MUST treat the first session - // description it receives as the answer, and MUST ignore any - // session descriptions in subsequent responses to the initial - // INVITE. - // - // o If the initial offer is in the first reliable non-failure - // message from the UAS back to UAC, the answer MUST be in the - // acknowledgement for that message (in this specification, ACK - // for a 2xx response). - // - // o After having sent or received an answer to the first offer, the - // UAC MAY generate subsequent offers in requests based on rules - // specified for that method, but only if it has received answers - // to any previous offers, and has not sent any offers to which it - // hasn't gotten an answer. - // - // o Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - var _this = this; - if (options === void 0) { options = {}; } - // 5 The Offer/Answer Model and PRACK - // - // RFC 3261 describes guidelines for the sets of messages in which - // offers and answers [3] can appear. Based on those guidelines, this - // extension provides additional opportunities for offer/answer - // exchanges. - // If the INVITE contained an offer, the UAS MAY generate an answer in a - // reliable provisional response (assuming these are supported by the - // UAC). That results in the establishment of the session before - // completion of the call. Similarly, if a reliable provisional - // response is the first reliable message sent back to the UAC, and the - // INVITE did not contain an offer, one MUST appear in that reliable - // provisional response. - // If the UAC receives a reliable provisional response with an offer - // (this would occur if the UAC sent an INVITE without an offer, in - // which case the first reliable provisional response will contain the - // offer), it MUST generate an answer in the PRACK. If the UAC receives - // a reliable provisional response with an answer, it MAY generate an - // additional offer in the PRACK. If the UAS receives a PRACK with an - // offer, it MUST place the answer in the 2xx to the PRACK. - // Once an answer has been sent or received, the UA SHOULD establish the - // session based on the parameters of the offer and answer, even if the - // original INVITE itself has not been responded to. - // If the UAS had placed a session description in any reliable - // provisional response that is unacknowledged when the INVITE is - // accepted, the UAS MUST delay sending the 2xx until the provisional - // response is acknowledged. Otherwise, the reliability of the 1xx - // cannot be guaranteed, and reliability is needed for proper operation - // of the offer/answer exchange. - // All user agents that support this extension MUST support all - // offer/answer exchanges that are possible based on the rules in - // Section 13.2 of RFC 3261, based on the existence of INVITE and PRACK - // as requests, and 2xx and reliable 1xx as non-failure reliable - // responses. - // - // https://tools.ietf.org/html/rfc3262#section-5 - //// - // The Offer/Answer Model Implementation - // - // The offer/answer model is straight forward, but one MUST READ the specifications... - // - // 13.2.1 Creating the Initial INVITE (paragraph 8 in particular) - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // - // 5 The Offer/Answer Model and PRACK - // https://tools.ietf.org/html/rfc3262#section-5 - // - // Session Initiation Protocol (SIP) Usage of the Offer/Answer Model - // https://tools.ietf.org/html/rfc6337 - //// - //// - // TODO: The Offer/Answer Model Implementation - // - // Currently if `earlyMedia` is enabled and the INVITE request forks, - // the session is terminated if the early dialog does not match the - // confirmed dialog. This restriction make sense in a WebRTC environment, - // but there are other enviroments where this restriction does not hold. - // - // So while we currently cannot make the offer in INVITE+forking+webrtc - // case work, we propose doing the following... - // - // OPTION 1 - // - add a `earlyMediaForking` option and - // - require SDH.setDescription() to be callable multiple times. - // - // OPTION 2 - // 1) modify SDH Factory to provide an initial offer without giving us the SDH, and then... - // 2) stick that offer in the initial INVITE, and when 183 with initial answer is received... - // 3) ask SDH Factory if it supports "earlyRemoteAnswer" - // a) if true, ask SDH Factory to createSDH(localOffer).then((sdh) => sdh.setDescription(remoteAnswer) - // b) if false, defer getting a SDH until 2xx response is received - // - // Our supplied WebRTC SDH will default to behavior 3b which works in forking environment (without) - // early media if initial offer is in the INVITE). We will, however, provide an "inviteWillNotFork" - // option which if set to "true" will have our supplied WebRTC SDH behave in the 3a manner. - // That will result in - // - early media working with initial offer in the INVITE, and... - // - if the INVITE forks, the session terminating with an ERROR that reads like - // "You set 'inviteWillNotFork' to true but the INVITE forked. You can't eat your cake, and have it too." - // - furthermore, we accept that users will report that error to us as "bug" regardless - // - // So, SDH Factory is going to end up with a new interface along the lines of... - // - // interface SessionDescriptionHandlerFactory { - // makeLocalOffer(): Promise; - // makeSessionDescriptionHandler( - // initialOffer: ContentTypeAndBody, offerType: "local" | "remote" - // ): Promise; - // supportsEarlyRemoteAnswer: boolean; - // supportsContentType(contentType: string): boolean; - // getDescription(description: ContentTypeAndBody): Promise - // setDescription(description: ContentTypeAndBody): Promise - // } - //// - // Send the INVITE request. - this.outgoingInviteRequest = this.userAgent.userAgentCore.invite(this.request, { - onAccept: function (inviteResponse) { - // Our transaction layer is "non-standard" in that it will only - // pass us a 2xx response once per branch, so there is no need to - // worry about dealing with 2xx retransmissions. However, we can - // and do still get 2xx responses for multiple branches (when an - // INVITE is forked) which may create multiple confirmed dialogs. - // Herein we are acking and sending a bye to any confirmed dialogs - // which arrive beyond the first one. This is the desired behavior - // for most applications (but certainly not all). - // If we already received a confirmed dialog, ack & bye this additional confirmed session. - if (_this.dialog) { - _this.logger.log("Additional confirmed dialog, sending ACK and BYE"); - _this.ackAndBye(inviteResponse); - // We do NOT transition state in this case (this is an "extra" dialog) - return; - } - // If the user requested cancellation, ack & bye this session. - if (_this.isCanceled) { - _this.logger.log("Canceled session accepted, sending ACK and BYE"); - _this.ackAndBye(inviteResponse); - _this.stateTransition(session_state_1.SessionState.Terminated); - _this.emit("bye", _this.request); // FIXME: Ported this odd second "bye" emit - return; - } - _this.notifyReferer(inviteResponse); - _this.onAccept(inviteResponse) - .then(function () { - _this.disposeEarlyMedia(); - }) - .catch(function (error) { - _this.disposeEarlyMedia(); - }) - .then(function () { - if (options.requestDelegate && options.requestDelegate.onAccept) { - options.requestDelegate.onAccept(inviteResponse); - } - }); - }, - onProgress: function (inviteResponse) { - // If the user requested cancellation, ignore response. - if (_this.isCanceled) { - return; - } - _this.notifyReferer(inviteResponse); - _this.onProgress(inviteResponse) - .catch(function (error) { - _this.disposeEarlyMedia(); - }) - .then(function () { - if (options.requestDelegate && options.requestDelegate.onProgress) { - options.requestDelegate.onProgress(inviteResponse); - } - }); - }, - onRedirect: function (inviteResponse) { - _this.notifyReferer(inviteResponse); - _this.onRedirect(inviteResponse); - if (options.requestDelegate && options.requestDelegate.onRedirect) { - options.requestDelegate.onRedirect(inviteResponse); - } - }, - onReject: function (inviteResponse) { - _this.notifyReferer(inviteResponse); - _this.onReject(inviteResponse); - if (options.requestDelegate && options.requestDelegate.onReject) { - options.requestDelegate.onReject(inviteResponse); - } - }, - onTrying: function (inviteResponse) { - _this.notifyReferer(inviteResponse); - _this.onTrying(inviteResponse); - if (options.requestDelegate && options.requestDelegate.onTrying) { - options.requestDelegate.onTrying(inviteResponse); - } - } - }); - return this.outgoingInviteRequest; - }; - Inviter.prototype.disposeEarlyMedia = function () { - this.earlyMediaSessionDescriptionHandlers.forEach(function (sessionDescriptionHandler) { - sessionDescriptionHandler.close(); - }); - }; - Inviter.prototype.notifyReferer = function (response) { - var _this = this; - if (!this.referred) { - return; - } - if (!(this.referred instanceof session_1.Session)) { - throw new Error("Referred session not instance of session"); - } - if (!this.referred.dialog) { - return; - } - if (!response.message.statusCode) { - throw new Error("Status code undefined."); - } - if (!response.message.reasonPhrase) { - throw new Error("Reason phrase undefined."); - } - var statusCode = response.message.statusCode; - var reasonPhrase = response.message.reasonPhrase; - var body = ("SIP/2.0 " + statusCode + " " + reasonPhrase).trim(); - var outgoingNotifyRequest = this.referred.dialog.notify(undefined, { - extraHeaders: [ - "Event: refer", - "Subscription-State: terminated", - ], - body: { - contentDisposition: "render", - contentType: "message/sipfrag", - content: body - } - }); - // The implicit subscription created by a REFER is the same as a - // subscription created with a SUBSCRIBE request. The agent issuing the - // REFER can terminate this subscription prematurely by unsubscribing - // using the mechanisms described in [2]. Terminating a subscription, - // either by explicitly unsubscribing or rejecting NOTIFY, is not an - // indication that the referenced request should be withdrawn or - // abandoned. - // https://tools.ietf.org/html/rfc3515#section-2.4.4 - // FIXME: TODO: This should be done in a subscribe dialog to satisfy the above. - // If the notify is rejected, stop sending NOTIFY requests. - outgoingNotifyRequest.delegate = { - onReject: function () { - _this.referred = undefined; - } - }; - }; - /** - * Handle final response to initial INVITE. - * @param inviteResponse - 2xx response. - */ - Inviter.prototype.onAccept = function (inviteResponse) { - var _this = this; - this.logger.log("Inviter.onAccept"); - // validate state - if (this.state !== session_state_1.SessionState.Establishing) { - this.logger.error("Accept received while in state " + this.state + ", dropping response"); - return Promise.reject(new Error("Invalid session state " + this.state)); - } - var response = inviteResponse.message; - var session = inviteResponse.session; - // Ported behavior. - if (response.hasHeader("P-Asserted-Identity")) { - this.assertedIdentity = core_1.Grammar.nameAddrHeaderParse(response.getHeader("P-Asserted-Identity")); - } - // We have a confirmed dialog. - this.dialog = session; - this.dialog.delegate = { - onAck: function (ackRequest) { return _this.onAckRequest(ackRequest); }, - onBye: function (byeRequest) { return _this.onByeRequest(byeRequest); }, - onInfo: function (infoRequest) { return _this.onInfoRequest(infoRequest); }, - onInvite: function (inviteRequest) { return _this.onInviteRequest(inviteRequest); }, - onNotify: function (notifyRequest) { return _this.onNotifyRequest(notifyRequest); }, - onPrack: function (prackRequest) { return _this.onPrackRequest(prackRequest); }, - onRefer: function (referRequest) { return _this.onReferRequest(referRequest); } - }; - var sdhOptions = this.sessionDescriptionHandlerOptions; - var sdhModifiers = this.sessionDescriptionHandlerModifiers; - switch (session.signalingState) { - case core_1.SignalingState.Initial: - // INVITE without offer, so MUST have offer at this point, so invalid state. - this.ackAndBye(inviteResponse, 400, "Missing session description"); - this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - return Promise.reject(new Error(Constants_1.C.causes.BAD_MEDIA_DESCRIPTION)); - case core_1.SignalingState.HaveLocalOffer: - // INVITE with offer, so MUST have answer at this point, so invalid state. - this.ackAndBye(inviteResponse, 400, "Missing session description"); - this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - return Promise.reject(new Error(Constants_1.C.causes.BAD_MEDIA_DESCRIPTION)); - case core_1.SignalingState.HaveRemoteOffer: { - // INVITE without offer, received offer in 2xx, so MUST send answer in ACK. - if (!this.dialog.offer) { - throw new Error("Session offer undefined in signaling state " + this.dialog.signalingState + "."); - } - var options = { - sessionDescriptionHandlerOptions: sdhOptions, - sessionDescriptionHandlerModifiers: sdhModifiers - }; - return this.setOfferAndGetAnswer(this.dialog.offer, options) - .then(function (body) { - _this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; - var ackRequest = inviteResponse.ack({ body: body }); - _this.stateTransition(session_state_1.SessionState.Established); - }) - .catch(function (error) { - _this.ackAndBye(inviteResponse, 488, "Invalid session description"); - _this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - throw error; - }); - } - case core_1.SignalingState.Stable: { - // If INVITE without offer and we have already completed the initial exchange. - if (this.earlyMediaSessionDescriptionHandlers.size > 0) { - var sdh = this.earlyMediaSessionDescriptionHandlers.get(session.id); - if (!sdh) { - throw new Error("Session description handler undefined."); - } - this.setSessionDescriptionHandler(sdh); - this.earlyMediaSessionDescriptionHandlers.delete(session.id); - this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; - var ackRequest = inviteResponse.ack(); - this.stateTransition(session_state_1.SessionState.Established); - return Promise.resolve(); - } - // If INVITE with offer and we used an "early" answer in a provisional response for media - if (this.earlyMediaDialog) { - // If early media dialog doesn't match confirmed dialog, we must unfortunately fail. - // This limitation stems from how WebRTC currently implements its offer/answer model. - // There are details elsewhere, but in short a WebRTC offer cannot be forked. - if (this.earlyMediaDialog !== session) { - if (this.earlyMedia) { - var message = "You have set the 'earlyMedia' option to 'true' which requires that your INVITE requests " + - "do not fork and yet this INVITE request did in fact fork. Consequentially and not surprisingly " + - "the end point which accepted the INVITE (confirmed dialog) does not match the end point with " + - "which early media has been setup (early dialog) and thus this session is unable to proceed. " + - "In accordance with the SIP specifications, the SIP servers your end point is connected to " + - "determine if an INVITE forks and the forking behaviour of those servers cannot be controlled " + - "by this library. If you wish to use early media with this library you must configure those " + - "servers accordingly. Alternatively you may set the 'earlyMedia' to 'false' which will allow " + - "this library to function with any INVITE requests which do fork."; - this.logger.error(message); - } - var error = new Error("Early media dialog does not equal confirmed dialog, terminating session"); - this.logger.error(error.message); - this.ackAndBye(inviteResponse, 488, "Not Acceptable Here"); - this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - return Promise.reject(error); - } - // Otherwise we are good to go. - this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; - var ackRequest = inviteResponse.ack(); - this.stateTransition(session_state_1.SessionState.Established); - return Promise.resolve(); - } - // If INVITE with offer and we have been waiting till now to apply the answer. - var answer = session.answer; - if (!answer) { - throw new Error("Answer is undefined."); - } - var options = { - sessionDescriptionHandlerOptions: sdhOptions, - sessionDescriptionHandlerModifiers: sdhModifiers - }; - return this.setAnswer(answer, options) - .then(function () { - // This session has completed an initial offer/answer exchange... - var ackOptions; - if (_this.renderbody && _this.rendertype) { - ackOptions = { - body: { contentDisposition: "render", contentType: _this.rendertype, content: _this.renderbody } - }; - } - _this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; - var ackRequest = inviteResponse.ack(ackOptions); - _this.stateTransition(session_state_1.SessionState.Established); - }) - .catch(function (error) { - _this.logger.error(error.message); - _this.ackAndBye(inviteResponse, 488, "Not Acceptable Here"); - _this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - throw error; - }); - } - case core_1.SignalingState.Closed: - // Dialog has terminated. - return Promise.reject(new Error("Terminated.")); - default: - throw new Error("Unknown session signaling state."); - } - }; - /** - * Handle provisional response to initial INVITE. - * @param inviteResponse - 1xx response. - */ - Inviter.prototype.onProgress = function (inviteResponse) { - var _this = this; - this.logger.log("Inviter.onProgress"); - // validate state - if (this.state !== session_state_1.SessionState.Establishing) { - this.logger.error("Progress received while in state " + this.state + ", dropping response"); - return Promise.reject(new Error("Invalid session state " + this.state)); - } - if (!this.outgoingInviteRequest) { - throw new Error("Outgoing INVITE request undefined."); - } - var response = inviteResponse.message; - var session = inviteResponse.session; - // Ported - Set status. - this.status = Enums_1.SessionStatus.STATUS_1XX_RECEIVED; - // Ported - Set assertedIdentity. - if (response.hasHeader("P-Asserted-Identity")) { - this.assertedIdentity = core_1.Grammar.nameAddrHeaderParse(response.getHeader("P-Asserted-Identity")); - } - // If a provisional response is received for an initial request, and - // that response contains a Require header field containing the option - // tag 100rel, the response is to be sent reliably. If the response is - // a 100 (Trying) (as opposed to 101 to 199), this option tag MUST be - // ignored, and the procedures below MUST NOT be used. - // https://tools.ietf.org/html/rfc3262#section-4 - var requireHeader = response.getHeader("require"); - var rseqHeader = response.getHeader("rseq"); - var rseq = requireHeader && requireHeader.includes("100rel") && rseqHeader ? Number(rseqHeader) : undefined; - var responseReliable = !!rseq; - var extraHeaders = []; - if (responseReliable) { - extraHeaders.push("RAck: " + response.getHeader("rseq") + " " + response.getHeader("cseq")); - } - var sdhOptions = this.sessionDescriptionHandlerOptions; - var sdhModifiers = this.sessionDescriptionHandlerModifiers; - switch (session.signalingState) { - case core_1.SignalingState.Initial: - // INVITE without offer and session still has no offer (and no answer). - if (responseReliable) { - // Similarly, if a reliable provisional - // response is the first reliable message sent back to the UAC, and the - // INVITE did not contain an offer, one MUST appear in that reliable - // provisional response. - // https://tools.ietf.org/html/rfc3262#section-5 - this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."); - // FIXME: Known popular UA's currently end up here... - inviteResponse.prack({ extraHeaders: extraHeaders }); - } - this.emit("progress", response); - return Promise.resolve(); - case core_1.SignalingState.HaveLocalOffer: - // INVITE with offer and session only has that initial local offer. - if (responseReliable) { - inviteResponse.prack({ extraHeaders: extraHeaders }); - } - this.emit("progress", response); - return Promise.resolve(); - case core_1.SignalingState.HaveRemoteOffer: - if (!responseReliable) { - // The initial offer MUST be in either an INVITE or, if not there, - // in the first reliable non-failure message from the UAS back to - // the UAC. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // According to Section 13.2.1 of [RFC3261], 'The first reliable - // non-failure message' must have an offer if there is no offer in the - // INVITE request. This means that the User Agent (UA) that receives - // the INVITE request without an offer must include an offer in the - // first reliable response with 100rel extension. If no reliable - // provisional response has been sent, the User Agent Server (UAS) must - // include an offer when sending 2xx response. - // https://tools.ietf.org/html/rfc6337#section-2.2 - this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response."); - return Promise.resolve(); - } - // If the initial offer is in the first reliable non-failure - // message from the UAS back to UAC, the answer MUST be in the - // acknowledgement for that message - var sdh_1 = this.sessionDescriptionHandlerFactory(this, this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions || {}); - this.emit("SessionDescriptionHandler-created", sdh_1); - this.earlyMediaSessionDescriptionHandlers.set(session.id, sdh_1); - return sdh_1 - .setDescription(response.body, sdhOptions, sdhModifiers) - .then(function () { return sdh_1.getDescription(sdhOptions, sdhModifiers); }) - .then(function (description) { - var body = { - contentDisposition: "session", contentType: description.contentType, content: description.body - }; - inviteResponse.prack({ extraHeaders: extraHeaders, body: body }); - _this.emit("progress", response); - }) - .catch(function (error) { - if (_this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - throw error; - } - _this.failed(undefined, Constants_1.C.causes.WEBRTC_ERROR); - _this.terminated(undefined, Constants_1.C.causes.WEBRTC_ERROR); - throw error; - }); - case core_1.SignalingState.Stable: - // This session has completed an initial offer/answer exchange, so... - // - INVITE with SDP and this provisional response MAY be reliable - // - INVITE without SDP and this provisional response MAY be reliable - if (responseReliable) { - inviteResponse.prack({ extraHeaders: extraHeaders }); - } - if (this.earlyMedia && !this.earlyMediaDialog) { - this.earlyMediaDialog = session; - var answer = session.answer; - if (!answer) { - throw new Error("Answer is undefined."); - } - var options = { - sessionDescriptionHandlerOptions: sdhOptions, - sessionDescriptionHandlerModifiers: sdhModifiers - }; - return this.setAnswer(answer, options) - .then(function () { - _this.emit("progress", response); - }) - .catch(function (error) { - if (_this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - throw error; - } - _this.failed(undefined, Constants_1.C.causes.WEBRTC_ERROR); - _this.terminated(undefined, Constants_1.C.causes.WEBRTC_ERROR); - throw error; - }); - } - this.emit("progress", response); - return Promise.resolve(); - case core_1.SignalingState.Closed: - // Dialog has terminated. - return Promise.reject(new Error("Terminated.")); - default: - throw new Error("Unknown session signaling state."); - } - }; - /** - * Handle final response to initial INVITE. - * @param inviteResponse - 3xx response. - */ - Inviter.prototype.onRedirect = function (inviteResponse) { - this.logger.log("Inviter.onRedirect"); - // validate state - if (this.state !== session_state_1.SessionState.Establishing && - this.state !== session_state_1.SessionState.Terminating) { - this.logger.error("Redirect received while in state " + this.state + ", dropping response"); - return; - } - // transition state - this.stateTransition(session_state_1.SessionState.Terminated); - this.disposeEarlyMedia(); - var response = inviteResponse.message; - var statusCode = response.statusCode; - var cause = Utils_1.Utils.sipErrorCause(statusCode || 0); - this.rejected(response, cause); - this.failed(response, cause); - this.terminated(response, cause); - }; - /** - * Handle final response to initial INVITE. - * @param inviteResponse - 4xx, 5xx, or 6xx response. - */ - Inviter.prototype.onReject = function (inviteResponse) { - this.logger.log("Inviter.onReject"); - // validate state - if (this.state !== session_state_1.SessionState.Establishing && - this.state !== session_state_1.SessionState.Terminating) { - this.logger.error("Reject received while in state " + this.state + ", dropping response"); - return; - } - // transition state - this.stateTransition(session_state_1.SessionState.Terminated); - this.disposeEarlyMedia(); - var response = inviteResponse.message; - var statusCode = response.statusCode; - var cause = Utils_1.Utils.sipErrorCause(statusCode || 0); - this.rejected(response, cause); - this.failed(response, cause); - this.terminated(response, cause); - }; - /** - * Handle final response to initial INVITE. - * @param inviteResponse - 100 response. - */ - Inviter.prototype.onTrying = function (inviteResponse) { - this.logger.log("Inviter.onTrying"); - // legacy behavior - doing this in any state seems broken - this.emit("progress", inviteResponse.message); - // validate state - if (this.state !== session_state_1.SessionState.Establishing) { - this.logger.error("Trying received while in state " + this.state + ", dropping response"); - return; - } - }; - return Inviter; -}(session_1.Session)); -exports.Inviter = Inviter; diff --git a/lib/api/message.d.ts b/lib/api/message.d.ts deleted file mode 100644 index 9e779023e..000000000 --- a/lib/api/message.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { IncomingMessageRequest, IncomingRequestMessage, ResponseOptions } from "../core"; -/** - * A received message (incoming MESSAGE). - * @public - */ -export declare class Message { - private incomingMessageRequest; - /** @internal */ - constructor(incomingMessageRequest: IncomingMessageRequest); - /** Incoming MESSAGE request message. */ - readonly request: IncomingRequestMessage; - /** Accept the request. */ - accept(options?: ResponseOptions): Promise; - /** Reject the request. */ - reject(options?: ResponseOptions): Promise; -} -//# sourceMappingURL=message.d.ts.map \ No newline at end of file diff --git a/lib/api/message.d.ts.map b/lib/api/message.d.ts.map deleted file mode 100644 index dfd8b4453..000000000 --- a/lib/api/message.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"message.d.ts","sourceRoot":"","sources":["../../src/api/message.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,sBAAsB,EACtB,sBAAsB,EACtB,eAAe,EAChB,MAAM,SAAS,CAAC;AAEjB;;;GAGG;AACH,qBAAa,OAAO;IAGN,OAAO,CAAC,sBAAsB;IAD1C,gBAAgB;gBACI,sBAAsB,EAAE,sBAAsB;IAGlE,wCAAwC;aACpC,OAAO,EAAI,sBAAsB;IAIrC,0BAA0B;IACnB,MAAM,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC;IAKvD,0BAA0B;IACnB,MAAM,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC;CAIxD"} \ No newline at end of file diff --git a/lib/api/message.js b/lib/api/message.js deleted file mode 100644 index a94ae5aef..000000000 --- a/lib/api/message.js +++ /dev/null @@ -1,32 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * A received message (incoming MESSAGE). - * @public - */ -var Message = /** @class */ (function () { - /** @internal */ - function Message(incomingMessageRequest) { - this.incomingMessageRequest = incomingMessageRequest; - } - Object.defineProperty(Message.prototype, "request", { - /** Incoming MESSAGE request message. */ - get: function () { - return this.incomingMessageRequest.message; - }, - enumerable: true, - configurable: true - }); - /** Accept the request. */ - Message.prototype.accept = function (options) { - this.incomingMessageRequest.accept(options); - return Promise.resolve(); - }; - /** Reject the request. */ - Message.prototype.reject = function (options) { - this.incomingMessageRequest.reject(options); - return Promise.resolve(); - }; - return Message; -}()); -exports.Message = Message; diff --git a/lib/api/messager-message-options.d.ts b/lib/api/messager-message-options.d.ts deleted file mode 100644 index 7a83a61b8..000000000 --- a/lib/api/messager-message-options.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { OutgoingRequestDelegate, RequestOptions } from "../core"; -/** - * Options for {@link Messager.message}. - * @public - */ -export interface MessagerMessageOptions { - /** See `core` API. */ - requestDelegate?: OutgoingRequestDelegate; - /** See `core` API. */ - requestOptions?: RequestOptions; -} -//# sourceMappingURL=messager-message-options.d.ts.map \ No newline at end of file diff --git a/lib/api/messager-message-options.d.ts.map b/lib/api/messager-message-options.d.ts.map deleted file mode 100644 index 5806244a8..000000000 --- a/lib/api/messager-message-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"messager-message-options.d.ts","sourceRoot":"","sources":["../../src/api/messager-message-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAElE;;;GAGG;AACH,MAAM,WAAW,sBAAsB;IACrC,sBAAsB;IACtB,eAAe,CAAC,EAAE,uBAAuB,CAAC;IAC1C,sBAAsB;IACtB,cAAc,CAAC,EAAE,cAAc,CAAC;CACjC"} \ No newline at end of file diff --git a/lib/api/messager-message-options.js b/lib/api/messager-message-options.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/api/messager-message-options.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/api/messager-options.d.ts b/lib/api/messager-options.d.ts deleted file mode 100644 index 2d2251208..000000000 --- a/lib/api/messager-options.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { URI } from "../core"; -/** - * Options for {@link Messager} constructor. - * @public - */ -export interface MessagerOptions { - /** Array of extra headers added to the MESSAGE. */ - extraHeaders?: Array; - /** @deprecated TODO: provide alternative. */ - params?: { - fromDisplayName?: string; - fromTag?: string; - fromUri?: string | URI; - toDisplayName?: string; - toUri?: string | URI; - }; -} -//# sourceMappingURL=messager-options.d.ts.map \ No newline at end of file diff --git a/lib/api/messager-options.d.ts.map b/lib/api/messager-options.d.ts.map deleted file mode 100644 index 48d8e72b9..000000000 --- a/lib/api/messager-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"messager-options.d.ts","sourceRoot":"","sources":["../../src/api/messager-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AAE9B;;;GAGG;AACH,MAAM,WAAW,eAAe;IAC9B,mDAAmD;IACnD,YAAY,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAC7B,6CAA6C;IAC7C,MAAM,CAAC,EAAE;QACP,eAAe,CAAC,EAAE,MAAM,CAAC;QACzB,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,OAAO,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC;QACvB,aAAa,CAAC,EAAE,MAAM,CAAC;QACvB,KAAK,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC;KACtB,CAAC;CACH"} \ No newline at end of file diff --git a/lib/api/messager-options.js b/lib/api/messager-options.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/api/messager-options.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/api/messager.d.ts b/lib/api/messager.d.ts deleted file mode 100644 index a524443ee..000000000 --- a/lib/api/messager.d.ts +++ /dev/null @@ -1,35 +0,0 @@ -/// -import { EventEmitter } from "events"; -import { URI } from "../core"; -import { MessagerMessageOptions } from "./messager-message-options"; -import { MessagerOptions } from "./messager-options"; -import { UserAgent } from "./user-agent"; -/** - * A messager sends a {@link Message} (outgoing MESSAGE). - * @public - */ -export declare class Messager extends EventEmitter { - private logger; - private request; - private userAgent; - private _disposed; - /** - * Constructs a new instance of the `Messager` class. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @param targetURI - Request URI identifying the target of the message. - * @param content - Content for the body of the message. - * @param contentType - Content type of the body of the message. - * @param options - Options bucket. See {@link MessagerOptions} for details. - */ - constructor(userAgent: UserAgent, targetURI: URI, content: string, contentType?: string, options?: MessagerOptions); - /** - * Destructor. - * @internal - */ - dispose(): void; - /** - * Send the message. - */ - message(options?: MessagerMessageOptions): Promise; -} -//# sourceMappingURL=messager.d.ts.map \ No newline at end of file diff --git a/lib/api/messager.d.ts.map b/lib/api/messager.d.ts.map deleted file mode 100644 index dece46dc1..000000000 --- a/lib/api/messager.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"messager.d.ts","sourceRoot":"","sources":["../../src/api/messager.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAEtC,OAAO,EAML,GAAG,EACJ,MAAM,SAAS,CAAC;AAEjB,OAAO,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AACpE,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC;;;GAGG;AACH,qBAAa,QAAS,SAAQ,YAAY;IACxC,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,OAAO,CAAyB;IACxC,OAAO,CAAC,SAAS,CAAY;IAE7B,OAAO,CAAC,SAAS,CAAS;IAE1B;;;;;;;OAOG;gBAED,SAAS,EAAE,SAAS,EACpB,SAAS,EAAE,GAAG,EACd,OAAO,EAAE,MAAM,EACf,WAAW,GAAE,MAAqB,EAClC,OAAO,GAAE,eAAoB;IA6D/B;;;OAGG;IACI,OAAO,IAAI,IAAI;IAOtB;;OAEG;IACI,OAAO,CAAC,OAAO,GAAE,sBAA2B,GAAG,OAAO,CAAC,IAAI,CAAC;CAIpE"} \ No newline at end of file diff --git a/lib/api/messager.js b/lib/api/messager.js deleted file mode 100644 index 4c1073e3c..000000000 --- a/lib/api/messager.js +++ /dev/null @@ -1,87 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var events_1 = require("events"); -var core_1 = require("../core"); -/** - * A messager sends a {@link Message} (outgoing MESSAGE). - * @public - */ -var Messager = /** @class */ (function (_super) { - tslib_1.__extends(Messager, _super); - /** - * Constructs a new instance of the `Messager` class. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @param targetURI - Request URI identifying the target of the message. - * @param content - Content for the body of the message. - * @param contentType - Content type of the body of the message. - * @param options - Options bucket. See {@link MessagerOptions} for details. - */ - function Messager(userAgent, targetURI, content, contentType, options) { - if (contentType === void 0) { contentType = "text/plain"; } - if (options === void 0) { options = {}; } - var _this = _super.call(this) || this; - _this._disposed = false; - // Logger - _this.logger = userAgent.getLogger("sip.messager"); - // Default options params - options.params = options.params || {}; - // URIs - var fromURI = userAgent.userAgentCore.configuration.aor; - if (options.params.fromUri) { - fromURI = - (typeof options.params.fromUri === "string") ? - core_1.Grammar.URIParse(options.params.fromUri) : - options.params.fromUri; - } - if (!fromURI) { - throw new TypeError("Invalid from URI: " + options.params.fromUri); - } - var toURI = targetURI; - if (options.params.toUri) { - toURI = - (typeof options.params.toUri === "string") ? - core_1.Grammar.URIParse(options.params.toUri) : - options.params.toUri; - } - if (!toURI) { - throw new TypeError("Invalid to URI: " + options.params.toUri); - } - // Message params - var params = options.params ? tslib_1.__assign({}, options.params) : {}; - // Extra headers - var extraHeaders = (options.extraHeaders || []).slice(); - // Body - var contentDisposition = "render"; - var body = { - contentDisposition: contentDisposition, - contentType: contentType, - content: content - }; - // Build the request - _this.request = userAgent.userAgentCore.makeOutgoingRequestMessage(core_1.C.MESSAGE, targetURI, fromURI, toURI, params, extraHeaders, body); - // User agent - _this.userAgent = userAgent; - return _this; - } - /** - * Destructor. - * @internal - */ - Messager.prototype.dispose = function () { - if (this._disposed) { - return; - } - this._disposed = true; - }; - /** - * Send the message. - */ - Messager.prototype.message = function (options) { - if (options === void 0) { options = {}; } - this.userAgent.userAgentCore.request(this.request, options.requestDelegate); - return Promise.resolve(); - }; - return Messager; -}(events_1.EventEmitter)); -exports.Messager = Messager; diff --git a/lib/api/notification.d.ts b/lib/api/notification.d.ts deleted file mode 100644 index f2dfea426..000000000 --- a/lib/api/notification.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { IncomingNotifyRequest, IncomingRequestMessage, ResponseOptions } from "../core"; -/** - * A notification of an event (incoming NOTIFY). - * @public - */ -export declare class Notification { - private incomingNotifyRequest; - /** @internal */ - constructor(incomingNotifyRequest: IncomingNotifyRequest); - /** Incoming NOTIFY request message. */ - readonly request: IncomingRequestMessage; - /** Accept the request. */ - accept(options?: ResponseOptions): Promise; - /** Reject the request. */ - reject(options?: ResponseOptions): Promise; -} -//# sourceMappingURL=notification.d.ts.map \ No newline at end of file diff --git a/lib/api/notification.d.ts.map b/lib/api/notification.d.ts.map deleted file mode 100644 index f76a7634d..000000000 --- a/lib/api/notification.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"notification.d.ts","sourceRoot":"","sources":["../../src/api/notification.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,qBAAqB,EACrB,sBAAsB,EACtB,eAAe,EAChB,MAAM,SAAS,CAAC;AAEjB;;;GAGG;AACH,qBAAa,YAAY;IAGX,OAAO,CAAC,qBAAqB;IADzC,gBAAgB;gBACI,qBAAqB,EAAE,qBAAqB;IAGhE,uCAAuC;aACnC,OAAO,EAAI,sBAAsB;IAIrC,0BAA0B;IACnB,MAAM,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC;IAKvD,0BAA0B;IACnB,MAAM,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC;CAIxD"} \ No newline at end of file diff --git a/lib/api/notification.js b/lib/api/notification.js deleted file mode 100644 index 010828463..000000000 --- a/lib/api/notification.js +++ /dev/null @@ -1,32 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * A notification of an event (incoming NOTIFY). - * @public - */ -var Notification = /** @class */ (function () { - /** @internal */ - function Notification(incomingNotifyRequest) { - this.incomingNotifyRequest = incomingNotifyRequest; - } - Object.defineProperty(Notification.prototype, "request", { - /** Incoming NOTIFY request message. */ - get: function () { - return this.incomingNotifyRequest.message; - }, - enumerable: true, - configurable: true - }); - /** Accept the request. */ - Notification.prototype.accept = function (options) { - this.incomingNotifyRequest.accept(options); - return Promise.resolve(); - }; - /** Reject the request. */ - Notification.prototype.reject = function (options) { - this.incomingNotifyRequest.reject(options); - return Promise.resolve(); - }; - return Notification; -}()); -exports.Notification = Notification; diff --git a/lib/api/notifier.d.ts b/lib/api/notifier.d.ts deleted file mode 100644 index feb606737..000000000 --- a/lib/api/notifier.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -/** - * TODO: This is currently just a placeholder. - * Notifier is the peer of a Subscriber. - * That is, a Notifier sends NOTIFY requests. - * @internal - */ -export declare class Notifier { -} -//# sourceMappingURL=notifier.d.ts.map \ No newline at end of file diff --git a/lib/api/notifier.d.ts.map b/lib/api/notifier.d.ts.map deleted file mode 100644 index 6835d9c85..000000000 --- a/lib/api/notifier.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"notifier.d.ts","sourceRoot":"","sources":["../../src/api/notifier.ts"],"names":[],"mappings":"AACA;;;;;GAKG;AACH,qBAAa,QAAQ;CACpB"} \ No newline at end of file diff --git a/lib/api/notifier.js b/lib/api/notifier.js deleted file mode 100644 index fb8f43077..000000000 --- a/lib/api/notifier.js +++ /dev/null @@ -1,14 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * TODO: This is currently just a placeholder. - * Notifier is the peer of a Subscriber. - * That is, a Notifier sends NOTIFY requests. - * @internal - */ -var Notifier = /** @class */ (function () { - function Notifier() { - } - return Notifier; -}()); -exports.Notifier = Notifier; diff --git a/lib/api/publisher-options.d.ts b/lib/api/publisher-options.d.ts deleted file mode 100644 index 137223835..000000000 --- a/lib/api/publisher-options.d.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { URI } from "../core"; -/** - * Options for {@link Publisher} constructor. - * @public - */ -export interface PublisherOptions { - /** @deprecated TODO: provide alternative. */ - body?: string; - /** @deprecated TODO: provide alternative. */ - contentType?: string; - /** - * Expire value for the published event. - * @defaultValue 3600 - */ - expires?: number; - /** - * Array of extra headers added to the PUBLISH request message. - */ - extraHeaders?: Array; - /** @deprecated TODO: provide alternative. */ - params?: { - fromDisplayName?: string; - fromTag?: string; - fromUri?: URI; - toDisplayName?: string; - toUri?: URI; - }; - /** - * If set true, UA will gracefully unpublish for the event on UA close. - * @defaultValue true - */ - unpublishOnClose?: boolean; -} -//# sourceMappingURL=publisher-options.d.ts.map \ No newline at end of file diff --git a/lib/api/publisher-options.d.ts.map b/lib/api/publisher-options.d.ts.map deleted file mode 100644 index 01fdfda1a..000000000 --- a/lib/api/publisher-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"publisher-options.d.ts","sourceRoot":"","sources":["../../src/api/publisher-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AAE9B;;;GAGG;AACH,MAAM,WAAW,gBAAgB;IAC/B,6CAA6C;IAC7C,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,6CAA6C;IAC7C,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;OAEG;IACH,YAAY,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAC7B,6CAA6C;IAC7C,MAAM,CAAC,EAAE;QACP,eAAe,CAAC,EAAE,MAAM,CAAC;QACzB,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,OAAO,CAAC,EAAE,GAAG,CAAC;QACd,aAAa,CAAC,EAAE,MAAM,CAAC;QACvB,KAAK,CAAC,EAAE,GAAG,CAAC;KACb,CAAC;IACF;;;OAGG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;CAC5B"} \ No newline at end of file diff --git a/lib/api/publisher-options.js b/lib/api/publisher-options.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/api/publisher-options.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/api/publisher-publish-options.d.ts b/lib/api/publisher-publish-options.d.ts deleted file mode 100644 index e849f0773..000000000 --- a/lib/api/publisher-publish-options.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -/** - * Options for {@link Publisher.publish}. - * @public - */ -export interface PublisherPublishOptions { -} -//# sourceMappingURL=publisher-publish-options.d.ts.map \ No newline at end of file diff --git a/lib/api/publisher-publish-options.d.ts.map b/lib/api/publisher-publish-options.d.ts.map deleted file mode 100644 index e59df0311..000000000 --- a/lib/api/publisher-publish-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"publisher-publish-options.d.ts","sourceRoot":"","sources":["../../src/api/publisher-publish-options.ts"],"names":[],"mappings":"AACA;;;GAGG;AACH,MAAM,WAAW,uBAAuB;CACvC"} \ No newline at end of file diff --git a/lib/api/publisher-publish-options.js b/lib/api/publisher-publish-options.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/api/publisher-publish-options.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/api/publisher-unpublish-options.d.ts b/lib/api/publisher-unpublish-options.d.ts deleted file mode 100644 index 09d3c157a..000000000 --- a/lib/api/publisher-unpublish-options.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -/** - * Options for {@link Publisher.unpublish}. - * @public - */ -export interface PublisherUnpublishOptions { -} -//# sourceMappingURL=publisher-unpublish-options.d.ts.map \ No newline at end of file diff --git a/lib/api/publisher-unpublish-options.d.ts.map b/lib/api/publisher-unpublish-options.d.ts.map deleted file mode 100644 index 86b1b9498..000000000 --- a/lib/api/publisher-unpublish-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"publisher-unpublish-options.d.ts","sourceRoot":"","sources":["../../src/api/publisher-unpublish-options.ts"],"names":[],"mappings":"AACA;;;GAGG;AACH,MAAM,WAAW,yBAAyB;CACzC"} \ No newline at end of file diff --git a/lib/api/publisher-unpublish-options.js b/lib/api/publisher-unpublish-options.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/api/publisher-unpublish-options.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/api/publisher.d.ts b/lib/api/publisher.d.ts deleted file mode 100644 index 9466a2c31..000000000 --- a/lib/api/publisher.d.ts +++ /dev/null @@ -1,52 +0,0 @@ -/// -import { EventEmitter } from "events"; -import { IncomingResponseMessage, URI } from "../core"; -import { PublisherOptions } from "./publisher-options"; -import { PublisherPublishOptions } from "./publisher-publish-options"; -import { PublisherUnpublishOptions } from "./publisher-unpublish-options"; -import { UserAgent } from "./user-agent"; -/** - * A publisher publishes a document (outgoing PUBLISH). - * @public - */ -export declare class Publisher extends EventEmitter { - private event; - private options; - private target; - private pubRequestBody; - private pubRequestExpires; - private pubRequestEtag; - private publishRefreshTimer; - private logger; - private request; - private userAgent; - /** - * Constructs a new instance of the `Publisher` class. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @param targetURI - Request URI identifying the target of the message. - * @param eventType - The event type identifying the published document. - * @param options - Options bucket. See {@link PublisherOptions} for details. - */ - constructor(userAgent: UserAgent, targetURI: URI, eventType: string, options?: PublisherOptions); - /** - * Close - * @internal - */ - close(): void; - /** - * Publish - * @param content - Body to publish - */ - publish(content: string, options?: PublisherPublishOptions): void; - /** - * Unpublish - */ - unpublish(options?: PublisherUnpublishOptions): void; - /** @internal */ - protected receiveResponse(response: IncomingResponseMessage): void; - /** @internal */ - protected send(): this; - private refreshRequest; - private sendPublishRequest; -} -//# sourceMappingURL=publisher.d.ts.map \ No newline at end of file diff --git a/lib/api/publisher.d.ts.map b/lib/api/publisher.d.ts.map deleted file mode 100644 index d8f17d510..000000000 --- a/lib/api/publisher.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"publisher.d.ts","sourceRoot":"","sources":["../../src/api/publisher.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAEtC,OAAO,EAGL,uBAAuB,EAGvB,GAAG,EACJ,MAAM,SAAS,CAAC;AAIjB,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,uBAAuB,EAAE,MAAM,6BAA6B,CAAC;AACtE,OAAO,EAAE,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAE1E,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC;;;GAGG;AACH,qBAAa,SAAU,SAAQ,YAAY;IACzC,OAAO,CAAC,KAAK,CAAS;IACtB,OAAO,CAAC,OAAO,CAAM;IACrB,OAAO,CAAC,MAAM,CAAM;IACpB,OAAO,CAAC,cAAc,CAAM;IAC5B,OAAO,CAAC,iBAAiB,CAAS;IAClC,OAAO,CAAC,cAAc,CAAqB;IAC3C,OAAO,CAAC,mBAAmB,CAAkB;IAE7C,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,OAAO,CAAyB;IACxC,OAAO,CAAC,SAAS,CAAY;IAE7B;;;;;;OAMG;gBACS,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,GAAG,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,GAAE,gBAAqB;IAqDnG;;;OAGG;IACI,KAAK,IAAI,IAAI;IAoBpB;;;OAGG;IACI,OAAO,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE,uBAA4B,GAAG,IAAI;IAwB5E;;OAEG;IACI,SAAS,CAAC,OAAO,GAAE,yBAA8B,GAAG,IAAI;IAe/D,gBAAgB;IAChB,SAAS,CAAC,eAAe,CAAC,QAAQ,EAAE,uBAAuB,GAAG,IAAI;IAqGlE,gBAAgB;IAChB,SAAS,CAAC,IAAI,IAAI,IAAI;IAWtB,OAAO,CAAC,cAAc;IAuBtB,OAAO,CAAC,kBAAkB;CAqC3B"} \ No newline at end of file diff --git a/lib/api/publisher.js b/lib/api/publisher.js deleted file mode 100644 index be6fc0865..000000000 --- a/lib/api/publisher.js +++ /dev/null @@ -1,273 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var events_1 = require("events"); -var core_1 = require("../core"); -var Exceptions_1 = require("../Exceptions"); -var Utils_1 = require("../Utils"); -/** - * A publisher publishes a document (outgoing PUBLISH). - * @public - */ -var Publisher = /** @class */ (function (_super) { - tslib_1.__extends(Publisher, _super); - /** - * Constructs a new instance of the `Publisher` class. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @param targetURI - Request URI identifying the target of the message. - * @param eventType - The event type identifying the published document. - * @param options - Options bucket. See {@link PublisherOptions} for details. - */ - function Publisher(userAgent, targetURI, eventType, options) { - if (options === void 0) { options = {}; } - var _this = _super.call(this) || this; - options.extraHeaders = (options.extraHeaders || []).slice(); - options.contentType = (options.contentType || "text/plain"); - if (typeof options.expires !== "number" || (options.expires % 1) !== 0) { - options.expires = 3600; - } - else { - options.expires = Number(options.expires); - } - if (typeof (options.unpublishOnClose) !== "boolean") { - options.unpublishOnClose = true; - } - _this.target = targetURI; - _this.event = eventType; - _this.options = options; - _this.pubRequestExpires = _this.options.expires; - _this.logger = userAgent.getLogger("sip.publisher"); - var params = options.params || {}; - var fromURI = params.fromUri ? params.fromUri : userAgent.userAgentCore.configuration.aor; - var toURI = params.toUri ? params.toUri : targetURI; - var body; - if (options.body && options.contentType) { - var contentDisposition = "render"; - var contentType = options.contentType; - var content = options.body; - body = { - contentDisposition: contentDisposition, - contentType: contentType, - content: content, - }; - } - var extraHeaders = (options.extraHeaders || []).slice(); - // Build the request - _this.request = userAgent.userAgentCore.makeOutgoingRequestMessage(core_1.C.PUBLISH, targetURI, fromURI, toURI, params, extraHeaders, body); - _this.userAgent = userAgent; - return _this; - } - /** - * Close - * @internal - */ - Publisher.prototype.close = function () { - // Send unpublish, if requested - if (this.options.unpublishOnClose) { - this.unpublish(); - } - else { - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - this.pubRequestBody = undefined; - this.pubRequestExpires = 0; - this.pubRequestEtag = undefined; - } - if (this.userAgent.publishers[this.target.toString() + ":" + this.event]) { - delete this.userAgent.publishers[this.target.toString() + ":" + this.event]; - } - }; - /** - * Publish - * @param content - Body to publish - */ - Publisher.prototype.publish = function (content, options) { - if (options === void 0) { options = {}; } - // Clean up before the run - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - // is Initial or Modify request - this.options.body = content; - this.pubRequestBody = this.options.body; - if (this.pubRequestExpires === 0) { - // This is Initial request after unpublish - this.pubRequestExpires = this.options.expires; - this.pubRequestEtag = undefined; - } - if (!(this.userAgent.publishers[this.target.toString() + ":" + this.event])) { - this.userAgent.publishers[this.target.toString() + ":" + this.event] = this; - } - this.sendPublishRequest(); - }; - /** - * Unpublish - */ - Publisher.prototype.unpublish = function (options) { - if (options === void 0) { options = {}; } - // Clean up before the run - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - this.pubRequestBody = undefined; - this.pubRequestExpires = 0; - if (this.pubRequestEtag !== undefined) { - this.sendPublishRequest(); - } - }; - /** @internal */ - Publisher.prototype.receiveResponse = function (response) { - var _this = this; - var statusCode = response.statusCode || 0; - var cause = Utils_1.Utils.getReasonPhrase(statusCode); - switch (true) { - case /^1[0-9]{2}$/.test(statusCode.toString()): - this.emit("progress", response, cause); - break; - case /^2[0-9]{2}$/.test(statusCode.toString()): - // Set SIP-Etag - if (response.hasHeader("SIP-ETag")) { - this.pubRequestEtag = response.getHeader("SIP-ETag"); - } - else { - this.logger.warn("SIP-ETag header missing in a 200-class response to PUBLISH"); - } - // Update Expire - if (response.hasHeader("Expires")) { - var expires = Number(response.getHeader("Expires")); - if (typeof expires === "number" && expires >= 0 && expires <= this.pubRequestExpires) { - this.pubRequestExpires = expires; - } - else { - this.logger.warn("Bad Expires header in a 200-class response to PUBLISH"); - } - } - else { - this.logger.warn("Expires header missing in a 200-class response to PUBLISH"); - } - if (this.pubRequestExpires !== 0) { - // Schedule refresh - this.publishRefreshTimer = setTimeout(function () { return _this.refreshRequest(); }, this.pubRequestExpires * 900); - this.emit("published", response, cause); - } - else { - this.emit("unpublished", response, cause); - } - break; - case /^412$/.test(statusCode.toString()): - // 412 code means no matching ETag - possibly the PUBLISH expired - // Resubmit as new request, if the current request is not a "remove" - if (this.pubRequestEtag !== undefined && this.pubRequestExpires !== 0) { - this.logger.warn("412 response to PUBLISH, recovering"); - this.pubRequestEtag = undefined; - this.emit("progress", response, cause); - this.publish(this.options.body); - } - else { - this.logger.warn("412 response to PUBLISH, recovery failed"); - this.pubRequestExpires = 0; - this.emit("failed", response, cause); - this.emit("unpublished", response, cause); - } - break; - case /^423$/.test(statusCode.toString()): - // 423 code means we need to adjust the Expires interval up - if (this.pubRequestExpires !== 0 && response.hasHeader("Min-Expires")) { - var minExpires = Number(response.getHeader("Min-Expires")); - if (typeof minExpires === "number" || minExpires > this.pubRequestExpires) { - this.logger.warn("423 code in response to PUBLISH, adjusting the Expires value and trying to recover"); - this.pubRequestExpires = minExpires; - this.emit("progress", response, cause); - this.publish(this.options.body); - } - else { - this.logger.warn("Bad 423 response Min-Expires header received for PUBLISH"); - this.pubRequestExpires = 0; - this.emit("failed", response, cause); - this.emit("unpublished", response, cause); - } - } - else { - this.logger.warn("423 response to PUBLISH, recovery failed"); - this.pubRequestExpires = 0; - this.emit("failed", response, cause); - this.emit("unpublished", response, cause); - } - break; - default: - this.pubRequestExpires = 0; - this.emit("failed", response, cause); - this.emit("unpublished", response, cause); - break; - } - // Do the cleanup - if (this.pubRequestExpires === 0) { - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - this.pubRequestBody = undefined; - this.pubRequestEtag = undefined; - } - }; - /** @internal */ - Publisher.prototype.send = function () { - var _this = this; - this.userAgent.userAgentCore.publish(this.request, { - onAccept: function (response) { return _this.receiveResponse(response.message); }, - onProgress: function (response) { return _this.receiveResponse(response.message); }, - onRedirect: function (response) { return _this.receiveResponse(response.message); }, - onReject: function (response) { return _this.receiveResponse(response.message); }, - onTrying: function (response) { return _this.receiveResponse(response.message); } - }); - return this; - }; - Publisher.prototype.refreshRequest = function () { - // Clean up before the run - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - // This is Refresh request - this.pubRequestBody = undefined; - if (this.pubRequestEtag === undefined) { - // Request not valid - throw new Exceptions_1.Exceptions.MethodParameterError("Publish", "Body", undefined); - } - if (this.pubRequestExpires === 0) { - // Request not valid - throw new Exceptions_1.Exceptions.MethodParameterError("Publish", "Expire", this.pubRequestExpires); - } - this.sendPublishRequest(); - }; - Publisher.prototype.sendPublishRequest = function () { - var reqOptions = Object.create(this.options || Object.prototype); - reqOptions.extraHeaders = (this.options.extraHeaders || []).slice(); - reqOptions.extraHeaders.push("Event: " + this.event); - reqOptions.extraHeaders.push("Expires: " + this.pubRequestExpires); - if (this.pubRequestEtag !== undefined) { - reqOptions.extraHeaders.push("SIP-If-Match: " + this.pubRequestEtag); - } - var ruri = this.target; - var params = this.options.params || {}; - var bodyAndContentType; - if (this.pubRequestBody !== undefined) { - bodyAndContentType = { - body: this.pubRequestBody, - contentType: this.options.contentType - }; - } - var body; - if (bodyAndContentType) { - body = Utils_1.Utils.fromBodyObj(bodyAndContentType); - } - this.request = this.userAgent.userAgentCore.makeOutgoingRequestMessage(core_1.C.PUBLISH, ruri, params.fromUri ? params.fromUri : this.userAgent.userAgentCore.configuration.aor, params.toUri ? params.toUri : this.target, params, reqOptions.extraHeaders, body); - this.send(); - }; - return Publisher; -}(events_1.EventEmitter)); -exports.Publisher = Publisher; diff --git a/lib/api/referral.d.ts b/lib/api/referral.d.ts deleted file mode 100644 index fb869304f..000000000 --- a/lib/api/referral.d.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { IncomingReferRequest, IncomingRequestMessage, NameAddrHeader, ResponseOptions } from "../core"; -import { Inviter } from "./inviter"; -import { InviterOptions } from "./inviter-options"; -import { Session } from "./session"; -/** - * A request to establish a {@link Session} elsewhere (incoming REFER). - * @public - */ -export declare class Referral { - private incomingReferRequest; - private session; - private inviter; - /** @internal */ - constructor(incomingReferRequest: IncomingReferRequest, session: Session); - readonly referTo: NameAddrHeader; - readonly referredBy: string | undefined; - readonly replaces: string | undefined; - /** Incoming REFER request message. */ - readonly request: IncomingRequestMessage; - /** Accept the request. */ - accept(options?: ResponseOptions): Promise; - /** Reject the request. */ - reject(options?: ResponseOptions): Promise; - /** - * Creates an inviter which may be used to send an out of dialog INVITE request. - * - * @remarks - * This a helper method to create an Inviter which will execute the referral - * of the `Session` which was referred. The appropriate headers are set and - * the referred `Session` is linked to the new `Session`. Note that only a - * single instance of the `Inviter` will be created and returned (if called - * more than once a reference to the same `Inviter` will be returned every time). - * - * @param options - Options bucket. - * @param modifiers - Session description handler modifiers. - */ - makeInviter(options?: InviterOptions): Inviter; -} -//# sourceMappingURL=referral.d.ts.map \ No newline at end of file diff --git a/lib/api/referral.d.ts.map b/lib/api/referral.d.ts.map deleted file mode 100644 index 7949e7830..000000000 --- a/lib/api/referral.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"referral.d.ts","sourceRoot":"","sources":["../../src/api/referral.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oBAAoB,EACpB,sBAAsB,EACtB,cAAc,EACd,eAAe,EAChB,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC;;;GAGG;AACH,qBAAa,QAAQ;IAKP,OAAO,CAAC,oBAAoB;IAAwB,OAAO,CAAC,OAAO;IAH/E,OAAO,CAAC,OAAO,CAAsB;IAErC,gBAAgB;gBACI,oBAAoB,EAAE,oBAAoB,EAAU,OAAO,EAAE,OAAO;aAGpF,OAAO,EAAI,cAAc;aAQzB,UAAU,EAAI,MAAM,GAAG,SAAS;aAIhC,QAAQ,EAAI,MAAM,GAAG,SAAS;IAIlC,sCAAsC;aAClC,OAAO,EAAI,sBAAsB;IAIrC,0BAA0B;IACnB,MAAM,CAAC,OAAO,GAAE,eAAqC,GAAG,OAAO,CAAC,IAAI,CAAC;IAK5E,0BAA0B;IACnB,MAAM,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC;IAKvD;;;;;;;;;;;;OAYG;IACI,WAAW,CAChB,OAAO,CAAC,EAAE,cAAc,GACvB,OAAO;CAuBX"} \ No newline at end of file diff --git a/lib/api/referral.js b/lib/api/referral.js deleted file mode 100644 index 4399770b0..000000000 --- a/lib/api/referral.js +++ /dev/null @@ -1,96 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var core_1 = require("../core"); -/** - * A request to establish a {@link Session} elsewhere (incoming REFER). - * @public - */ -var Referral = /** @class */ (function () { - /** @internal */ - function Referral(incomingReferRequest, session) { - this.incomingReferRequest = incomingReferRequest; - this.session = session; - } - Object.defineProperty(Referral.prototype, "referTo", { - get: function () { - var referTo = this.incomingReferRequest.message.parseHeader("refer-to"); - if (!(referTo instanceof core_1.NameAddrHeader)) { - throw new Error("Failed to parse Refer-To header."); - } - return referTo; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Referral.prototype, "referredBy", { - get: function () { - return this.incomingReferRequest.message.getHeader("referred-by"); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Referral.prototype, "replaces", { - get: function () { - return this.referTo.uri.getHeader("replaces"); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Referral.prototype, "request", { - /** Incoming REFER request message. */ - get: function () { - return this.incomingReferRequest.message; - }, - enumerable: true, - configurable: true - }); - /** Accept the request. */ - Referral.prototype.accept = function (options) { - if (options === void 0) { options = { statusCode: 202 }; } - this.incomingReferRequest.accept(options); - return Promise.resolve(); - }; - /** Reject the request. */ - Referral.prototype.reject = function (options) { - this.incomingReferRequest.reject(options); - return Promise.resolve(); - }; - /** - * Creates an inviter which may be used to send an out of dialog INVITE request. - * - * @remarks - * This a helper method to create an Inviter which will execute the referral - * of the `Session` which was referred. The appropriate headers are set and - * the referred `Session` is linked to the new `Session`. Note that only a - * single instance of the `Inviter` will be created and returned (if called - * more than once a reference to the same `Inviter` will be returned every time). - * - * @param options - Options bucket. - * @param modifiers - Session description handler modifiers. - */ - Referral.prototype.makeInviter = function (options) { - if (this.inviter) { - return this.inviter; - } - var targetURI = this.referTo.uri.clone(); - targetURI.clearHeaders(); - options = options || {}; - var extraHeaders = (options.extraHeaders || []).slice(); - var replaces = this.replaces; - if (replaces) { - // decodeURIComponent is a holdover from 2c086eb4. Not sure that it is actually necessary - extraHeaders.push("Replaces: " + decodeURIComponent(replaces)); - } - var referredBy = this.referredBy; - if (referredBy) { - extraHeaders.push("Referred-By: " + referredBy); - } - options.extraHeaders = extraHeaders; - this.inviter = this.session.userAgent.makeInviter(targetURI, options); - this.inviter.referred = this.session; - this.session.referral = this.inviter; - return this.inviter; - }; - return Referral; -}()); -exports.Referral = Referral; diff --git a/lib/api/referrer-delegate.d.ts b/lib/api/referrer-delegate.d.ts deleted file mode 100644 index d2e18f3b0..000000000 --- a/lib/api/referrer-delegate.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { OutgoingRequestDelegate } from "../core"; -import { Notification } from "./notification"; -/** - * Delegate for {@link Referrer}. - * @public - */ -export interface ReferrerDelegate extends OutgoingRequestDelegate { - onNotify(notification: Notification): void; -} -//# sourceMappingURL=referrer-delegate.d.ts.map \ No newline at end of file diff --git a/lib/api/referrer-delegate.d.ts.map b/lib/api/referrer-delegate.d.ts.map deleted file mode 100644 index 338239eed..000000000 --- a/lib/api/referrer-delegate.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"referrer-delegate.d.ts","sourceRoot":"","sources":["../../src/api/referrer-delegate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,SAAS,CAAC;AAClD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAE9C;;;GAGG;AACH,MAAM,WAAW,gBAAiB,SAAQ,uBAAuB;IAC/D,QAAQ,CAAC,YAAY,EAAE,YAAY,GAAG,IAAI,CAAC;CAC5C"} \ No newline at end of file diff --git a/lib/api/referrer-delegate.js b/lib/api/referrer-delegate.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/api/referrer-delegate.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/api/referrer-options.d.ts b/lib/api/referrer-options.d.ts deleted file mode 100644 index 7b6046df2..000000000 --- a/lib/api/referrer-options.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -/** - * Options for {@link Referrer} constructor. - * @public - */ -export interface ReferrerOptions { - extraHeaders?: Array; -} -//# sourceMappingURL=referrer-options.d.ts.map \ No newline at end of file diff --git a/lib/api/referrer-options.d.ts.map b/lib/api/referrer-options.d.ts.map deleted file mode 100644 index 7a8042418..000000000 --- a/lib/api/referrer-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"referrer-options.d.ts","sourceRoot":"","sources":["../../src/api/referrer-options.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,WAAW,eAAe;IAC9B,YAAY,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;CAC9B"} \ No newline at end of file diff --git a/lib/api/referrer-options.js b/lib/api/referrer-options.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/api/referrer-options.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/api/referrer-refer-options.d.ts b/lib/api/referrer-refer-options.d.ts deleted file mode 100644 index b302138ce..000000000 --- a/lib/api/referrer-refer-options.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { RequestOptions } from "../core"; -import { ReferrerDelegate } from "./referrer-delegate"; -/** - * Options for {@link Referrer.refer}. - * @public - */ -export interface ReferrerReferOptions { - /** See `core` API. */ - requestDelegate?: ReferrerDelegate; - /** See `core` API. */ - requestOptions?: RequestOptions; -} -//# sourceMappingURL=referrer-refer-options.d.ts.map \ No newline at end of file diff --git a/lib/api/referrer-refer-options.d.ts.map b/lib/api/referrer-refer-options.d.ts.map deleted file mode 100644 index 7546f6edf..000000000 --- a/lib/api/referrer-refer-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"referrer-refer-options.d.ts","sourceRoot":"","sources":["../../src/api/referrer-refer-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AACzC,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAEvD;;;GAGG;AACH,MAAM,WAAW,oBAAoB;IACnC,sBAAsB;IACtB,eAAe,CAAC,EAAE,gBAAgB,CAAC;IACnC,sBAAsB;IACtB,cAAc,CAAC,EAAE,cAAc,CAAC;CACjC"} \ No newline at end of file diff --git a/lib/api/referrer-refer-options.js b/lib/api/referrer-refer-options.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/api/referrer-refer-options.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/api/referrer.d.ts b/lib/api/referrer.d.ts deleted file mode 100644 index f89ea4122..000000000 --- a/lib/api/referrer.d.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { OutgoingReferRequest, URI } from "../core"; -import { ReferrerDelegate } from "./referrer-delegate"; -import { ReferrerOptions } from "./referrer-options"; -import { ReferrerReferOptions } from "./referrer-refer-options"; -import { Session } from "./session"; -/** - * A referrer sends a {@link Referral} (outgoing REFER). - * @remarks - * Sends an outgoing in dialog REFER request. - * @public - */ -export declare class Referrer { - /** The referrer delegate. */ - delegate: ReferrerDelegate | undefined; - /** The referTo. */ - private _referTo; - /** The referrer session. */ - private _session; - /** - * Constructs a new instance of the `Referrer` class. - * @param session - The session the REFER will be sent from. See {@link Session} for details. - * @param referTo - The referral target. If a `Session`, a REFER w/Replaces is sent. - * @param options - An options bucket. See {@link ReferrerOptions} for details. - */ - constructor(session: Session, referTo: URI | Session, options?: ReferrerOptions); - /** The referrer session. */ - readonly session: Session; - /** - * Sends the REFER request. - * @param options - An options bucket. - */ - refer(options?: ReferrerReferOptions): Promise; - private extraHeaders; - private referToString; -} -//# sourceMappingURL=referrer.d.ts.map \ No newline at end of file diff --git a/lib/api/referrer.d.ts.map b/lib/api/referrer.d.ts.map deleted file mode 100644 index 1589befe4..000000000 --- a/lib/api/referrer.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"referrer.d.ts","sourceRoot":"","sources":["../../src/api/referrer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AACpD,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAChE,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAGpC;;;;;GAKG;AACH,qBAAa,QAAQ;IACnB,6BAA6B;IACtB,QAAQ,EAAE,gBAAgB,GAAG,SAAS,CAAC;IAE9C,mBAAmB;IACnB,OAAO,CAAC,QAAQ,CAAgB;IAChC,4BAA4B;IAC5B,OAAO,CAAC,QAAQ,CAAU;IAE1B;;;;;OAKG;gBACS,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,GAAG,OAAO,EAAE,OAAO,CAAC,EAAE,eAAe;IAK/E,4BAA4B;aACxB,OAAO,EAAI,OAAO;IAItB;;;OAGG;IACK,KAAK,CAAC,OAAO,GAAE,oBAAyB,GAAG,OAAO,CAAC,oBAAoB,CAAC;IAkBhF,OAAO,CAAC,YAAY;IAmBpB,OAAO,CAAC,aAAa;CAoBtB"} \ No newline at end of file diff --git a/lib/api/referrer.js b/lib/api/referrer.js deleted file mode 100644 index 1029bf3e7..000000000 --- a/lib/api/referrer.js +++ /dev/null @@ -1,90 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var core_1 = require("../core"); -var session_state_1 = require("./session-state"); -/** - * A referrer sends a {@link Referral} (outgoing REFER). - * @remarks - * Sends an outgoing in dialog REFER request. - * @public - */ -var Referrer = /** @class */ (function () { - /** - * Constructs a new instance of the `Referrer` class. - * @param session - The session the REFER will be sent from. See {@link Session} for details. - * @param referTo - The referral target. If a `Session`, a REFER w/Replaces is sent. - * @param options - An options bucket. See {@link ReferrerOptions} for details. - */ - function Referrer(session, referTo, options) { - this._session = session; - this._referTo = referTo; - } - Object.defineProperty(Referrer.prototype, "session", { - /** The referrer session. */ - get: function () { - return this._session; - }, - enumerable: true, - configurable: true - }); - /** - * Sends the REFER request. - * @param options - An options bucket. - */ - Referrer.prototype.refer = function (options) { - if (options === void 0) { options = {}; } - // guard session state - if (this.session.state !== session_state_1.SessionState.Established) { - var message = "Referrer.refer() may only be called if established session."; - this.session.logger.error(message); - return Promise.reject(new Error("Invalid session state " + this.session.state)); - } - var requestDelegate = options.requestDelegate; - var requestOptions = options.requestOptions || {}; - var extraHeaders = this.extraHeaders(this.referToString(this._referTo)); - requestOptions.extraHeaders = requestOptions.extraHeaders || []; - requestOptions.extraHeaders = requestOptions.extraHeaders.concat(extraHeaders); - return this.session.refer(this, requestDelegate, requestOptions); - }; - Referrer.prototype.extraHeaders = function (referTo) { - var extraHeaders = []; - extraHeaders.push("Referred-By: <" + this._session.userAgent.configuration.uri + ">"); - extraHeaders.push("Contact: " + this._session.contact); - extraHeaders.push("Allow: " + [ - "ACK", - "CANCEL", - "INVITE", - "MESSAGE", - "BYE", - "OPTIONS", - "INFO", - "NOTIFY", - "REFER" - ].toString()); - extraHeaders.push("Refer-To: " + referTo); - return extraHeaders; - }; - Referrer.prototype.referToString = function (target) { - var referTo; - if (target instanceof core_1.URI) { - // REFER without Replaces (Blind Transfer) - referTo = target.toString(); - } - else { - // REFER with Replaces (Attended Transfer) - if (!target.dialog) { - throw new Error("Dialog undefined."); - } - var displayName = target.remoteIdentity.friendlyName; - var remoteTarget = target.dialog.remoteTarget.toString(); - var callId = target.dialog.callId; - var remoteTag = target.dialog.remoteTag; - var localTag = target.dialog.localTag; - var replaces = encodeURIComponent(callId + ";to-tag=" + remoteTag + ";from-tag=" + localTag); - referTo = "\"" + displayName + "\" <" + remoteTarget + "?Replaces=" + replaces + ">"; - } - return referTo; - }; - return Referrer; -}()); -exports.Referrer = Referrer; diff --git a/lib/api/registerer-options.d.ts b/lib/api/registerer-options.d.ts deleted file mode 100644 index c3e60dc88..000000000 --- a/lib/api/registerer-options.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -/** - * Options for {@link Registerer} constructor. - * @public - */ -export interface RegistererOptions { - expires?: number; - extraContactHeaderParams?: Array; - /** Array of extra headers added to the REGISTER. */ - extraHeaders?: Array; - instanceId?: string; - params?: any; - regId?: number; - registrar?: string; -} -//# sourceMappingURL=registerer-options.d.ts.map \ No newline at end of file diff --git a/lib/api/registerer-options.d.ts.map b/lib/api/registerer-options.d.ts.map deleted file mode 100644 index 6bb27e541..000000000 --- a/lib/api/registerer-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"registerer-options.d.ts","sourceRoot":"","sources":["../../src/api/registerer-options.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,WAAW,iBAAiB;IAChC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,wBAAwB,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IACzC,oDAAoD;IACpD,YAAY,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAC7B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,MAAM,CAAC,EAAE,GAAG,CAAC;IACb,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB"} \ No newline at end of file diff --git a/lib/api/registerer-options.js b/lib/api/registerer-options.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/api/registerer-options.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/api/registerer-register-options.d.ts b/lib/api/registerer-register-options.d.ts deleted file mode 100644 index 22140aa66..000000000 --- a/lib/api/registerer-register-options.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { OutgoingRequestDelegate, RequestOptions } from "../core"; -/** - * Options for {@link Registerer.register}. - * @public - */ -export interface RegistererRegisterOptions { - /** See `core` API. */ - requestDelegate?: OutgoingRequestDelegate; - /** See `core` API. */ - requestOptions?: RequestOptions; -} -//# sourceMappingURL=registerer-register-options.d.ts.map \ No newline at end of file diff --git a/lib/api/registerer-register-options.d.ts.map b/lib/api/registerer-register-options.d.ts.map deleted file mode 100644 index 5cb35bfa1..000000000 --- a/lib/api/registerer-register-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"registerer-register-options.d.ts","sourceRoot":"","sources":["../../src/api/registerer-register-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAGlE;;;GAGG;AACH,MAAM,WAAW,yBAAyB;IACxC,sBAAsB;IACtB,eAAe,CAAC,EAAE,uBAAuB,CAAC;IAC1C,sBAAsB;IACtB,cAAc,CAAC,EAAE,cAAc,CAAC;CACjC"} \ No newline at end of file diff --git a/lib/api/registerer-register-options.js b/lib/api/registerer-register-options.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/api/registerer-register-options.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/api/registerer-state.d.ts b/lib/api/registerer-state.d.ts deleted file mode 100644 index 05c6e5e9c..000000000 --- a/lib/api/registerer-state.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -/** - * {@link Registerer} state. - * @remarks - * Valid state transitions: - * ``` - * 1. "initial" --> "registered" - * 2. "initial" --> "unregistered" - * 3. "registered" --> "unregistered" - * 3. "unregistered" --> "registered" - * ``` - * @public - */ -export declare enum RegistererState { - Initial = "Initial", - Registered = "Registered", - Unregistered = "Unregistered" -} -//# sourceMappingURL=registerer-state.d.ts.map \ No newline at end of file diff --git a/lib/api/registerer-state.d.ts.map b/lib/api/registerer-state.d.ts.map deleted file mode 100644 index 09711df5a..000000000 --- a/lib/api/registerer-state.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"registerer-state.d.ts","sourceRoot":"","sources":["../../src/api/registerer-state.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,oBAAY,eAAe;IACzB,OAAO,YAAY;IACnB,UAAU,eAAgB;IAC1B,YAAY,iBAAiB;CAC9B"} \ No newline at end of file diff --git a/lib/api/registerer-state.js b/lib/api/registerer-state.js deleted file mode 100644 index 69e08e48f..000000000 --- a/lib/api/registerer-state.js +++ /dev/null @@ -1,20 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * {@link Registerer} state. - * @remarks - * Valid state transitions: - * ``` - * 1. "initial" --> "registered" - * 2. "initial" --> "unregistered" - * 3. "registered" --> "unregistered" - * 3. "unregistered" --> "registered" - * ``` - * @public - */ -var RegistererState; -(function (RegistererState) { - RegistererState["Initial"] = "Initial"; - RegistererState["Registered"] = "Registered"; - RegistererState["Unregistered"] = "Unregistered"; -})(RegistererState = exports.RegistererState || (exports.RegistererState = {})); diff --git a/lib/api/registerer-unregister-options.d.ts b/lib/api/registerer-unregister-options.d.ts deleted file mode 100644 index d2673f86d..000000000 --- a/lib/api/registerer-unregister-options.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { OutgoingRequestDelegate, RequestOptions } from "../core"; -/** - * Options for {@link Registerer.unregister}. - * @public - */ -export interface RegistererUnregisterOptions { - /** - * If true, unregister all contacts. - * @defaultValue false - */ - all?: boolean; - /** See `core` API. */ - requestDelegate?: OutgoingRequestDelegate; - /** See `core` API. */ - requestOptions?: RequestOptions; -} -//# sourceMappingURL=registerer-unregister-options.d.ts.map \ No newline at end of file diff --git a/lib/api/registerer-unregister-options.d.ts.map b/lib/api/registerer-unregister-options.d.ts.map deleted file mode 100644 index 3f30ee432..000000000 --- a/lib/api/registerer-unregister-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"registerer-unregister-options.d.ts","sourceRoot":"","sources":["../../src/api/registerer-unregister-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAElE;;;GAGG;AACH,MAAM,WAAW,2BAA2B;IAC1C;;;OAGG;IACH,GAAG,CAAC,EAAE,OAAO,CAAC;IACd,sBAAsB;IACtB,eAAe,CAAC,EAAE,uBAAuB,CAAC;IAC1C,sBAAsB;IACtB,cAAc,CAAC,EAAE,cAAc,CAAC;CACjC"} \ No newline at end of file diff --git a/lib/api/registerer-unregister-options.js b/lib/api/registerer-unregister-options.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/api/registerer-unregister-options.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/api/registerer.d.ts b/lib/api/registerer.d.ts deleted file mode 100644 index 62cdc13c6..000000000 --- a/lib/api/registerer.d.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { OutgoingRegisterRequest } from "../core"; -import { Emitter } from "./emitter"; -import { RegistererOptions } from "./registerer-options"; -import { RegistererRegisterOptions } from "./registerer-register-options"; -import { RegistererState } from "./registerer-state"; -import { RegistererUnregisterOptions } from "./registerer-unregister-options"; -import { UserAgent } from "./user-agent"; -/** - * A registerer registers a contact for an address of record (outgoing REGISTER). - * @public - */ -export declare class Registerer { - private id; - private contact; - private expires; - private logger; - private options; - private request; - private userAgent; - private registrationExpiredTimer; - private registrationTimer; - /** The contacts returned from the most recent accepted REGISTER request. */ - private _contacts; - /** The registration state. */ - private _state; - /** Emits when the registration state changes. */ - private _stateEventEmitter; - /** True is waiting for final response to outstanding REGISTER request. */ - private _waiting; - /** Emits when waiting changes. */ - private _waitingEventEmitter; - /** - * Constructs a new instance of the `Registerer` class. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @param options - Options bucket. See {@link RegistererOptions} for details. - */ - constructor(userAgent: UserAgent, options?: RegistererOptions); - /** The registered contacts. */ - readonly contacts: Array; - /** The registration state. */ - readonly state: RegistererState; - /** Emits when the registerer state changes. */ - readonly stateChange: Emitter; - /** Destructor. */ - dispose(): Promise; - /** - * Sends the REGISTER request. - * @remarks - * If successfull, sends re-REGISTER requests prior to registration expiration until `unsubscribe()` is called. - */ - register(options?: RegistererRegisterOptions): Promise; - /** - * Sends the REGISTER request with expires equal to zero. - */ - unregister(options?: RegistererUnregisterOptions): Promise; - /** @internal */ - private clearTimers; - /** - * Helper Function to generate Contact Header - * @internal - */ - private generateContactHeader; - /** @internal */ - private onTransportDisconnected; - /** @internal */ - private registered; - /** @internal */ - private unregistered; - /** - * Transition registration state. - * @internal - */ - private stateTransition; - /** True if waiting for final response to a REGISTER request. */ - private readonly waiting; - /** Emits when the registerer toggles waiting. */ - private readonly waitingChange; - /** - * Toggle waiting. - * @internal - */ - private waitingToggle; -} -//# sourceMappingURL=registerer.d.ts.map \ No newline at end of file diff --git a/lib/api/registerer.d.ts.map b/lib/api/registerer.d.ts.map deleted file mode 100644 index 17b48cce2..000000000 --- a/lib/api/registerer.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"registerer.d.ts","sourceRoot":"","sources":["../../src/api/registerer.ts"],"names":[],"mappings":"AAGA,OAAO,EAGL,uBAAuB,EAGxB,MAAM,SAAS,CAAC;AAIjB,OAAO,EAAE,OAAO,EAAe,MAAM,WAAW,CAAC;AACjD,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAC1E,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,EAAE,2BAA2B,EAAE,MAAM,iCAAiC,CAAC;AAC9E,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAoIzC;;;GAGG;AACH,qBAAa,UAAU;IACrB,OAAO,CAAC,EAAE,CAAS;IAEnB,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,OAAO,CAAoB;IACnC,OAAO,CAAC,OAAO,CAAyB;IACxC,OAAO,CAAC,SAAS,CAAY;IAE7B,OAAO,CAAC,wBAAwB,CAAkB;IAClD,OAAO,CAAC,iBAAiB,CAAkB;IAE3C,4EAA4E;IAC5E,OAAO,CAAC,SAAS,CAAqB;IAEtC,8BAA8B;IAC9B,OAAO,CAAC,MAAM,CAA4C;IAC1D,iDAAiD;IACjD,OAAO,CAAC,kBAAkB,CAAsB;IAEhD,0EAA0E;IAC1E,OAAO,CAAC,QAAQ,CAAS;IACzB,kCAAkC;IAClC,OAAO,CAAC,oBAAoB,CAAsB;IAElD;;;;OAIG;gBACS,SAAS,EAAE,SAAS,EAAE,OAAO,GAAE,iBAAsB;IAgEjE,+BAA+B;aAC3B,QAAQ,EAAI,KAAK,CAAC,MAAM,CAAC;IAI7B,8BAA8B;aAC1B,KAAK,EAAI,eAAe;IAI5B,+CAA+C;aAC3C,WAAW,EAAI,OAAO,CAAC,eAAe,CAAC;IAI3C,kBAAkB;IACL,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IA2BrC;;;;OAIG;IACU,QAAQ,CAAC,OAAO,GAAE,yBAA8B,GAAG,OAAO,CAAC,uBAAuB,CAAC;IAwKhG;;OAEG;IACU,UAAU,CAAC,OAAO,GAAE,2BAAgC,GAAG,OAAO,CAAC,uBAAuB,CAAC;IAmGpG,gBAAgB;IAChB,OAAO,CAAC,WAAW;IAYnB;;;OAGG;IACH,OAAO,CAAC,qBAAqB;IAkB7B,gBAAgB;IAChB,OAAO,CAAC,uBAAuB;IAI/B,gBAAgB;IAChB,OAAO,CAAC,UAAU;IAqBlB,gBAAgB;IAChB,OAAO,CAAC,YAAY;IAQpB;;;OAGG;IACH,OAAO,CAAC,eAAe;IAuCvB,gEAAgE;qBACpD,OAAO;IAInB,iDAAiD;qBACrC,aAAa;IAIzB;;;OAGG;IACH,OAAO,CAAC,aAAa;CAQtB"} \ No newline at end of file diff --git a/lib/api/registerer.js b/lib/api/registerer.js deleted file mode 100644 index cd7682180..000000000 --- a/lib/api/registerer.js +++ /dev/null @@ -1,647 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var events_1 = require("events"); -var Constants_1 = require("../Constants"); -var core_1 = require("../core"); -var Exceptions_1 = require("../Exceptions"); -var Utils_1 = require("../Utils"); -var emitter_1 = require("./emitter"); -var registerer_state_1 = require("./registerer-state"); -/** - * @internal - */ -function loadConfig(configuration) { - var settings = { - expires: 600, - extraContactHeaderParams: [], - instanceId: undefined, - params: {}, - regId: undefined, - registrar: undefined, - }; - var configCheck = getConfigurationCheck(); - // Check Mandatory parameters - for (var parameter in configCheck.mandatory) { - if (!configuration.hasOwnProperty(parameter)) { - throw new Exceptions_1.Exceptions.ConfigurationError(parameter); - } - else { - var value = configuration[parameter]; - var checkedValue = configCheck.mandatory[parameter](value); - if (checkedValue !== undefined) { - settings[parameter] = checkedValue; - } - else { - throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); - } - } - } - // Check Optional parameters - for (var parameter in configCheck.optional) { - if (configuration.hasOwnProperty(parameter)) { - var value = configuration[parameter]; - // If the parameter value is an empty array, but shouldn't be, apply its default value. - if (value instanceof Array && value.length === 0) { - continue; - } - // If the parameter value is null, empty string, or undefined then apply its default value. - // If it's a number with NaN value then also apply its default value. - // NOTE: JS does not allow "value === NaN", the following does the work: - if (value === null || value === "" || value === undefined || - (typeof (value) === "number" && isNaN(value))) { - continue; - } - var checkedValue = configCheck.optional[parameter](value); - if (checkedValue !== undefined) { - settings[parameter] = checkedValue; - } - else { - throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); - } - } - } - return settings; -} -/** - * @internal - */ -function getConfigurationCheck() { - return { - mandatory: {}, - optional: { - expires: function (expires) { - if (Utils_1.Utils.isDecimal(expires)) { - var value = Number(expires); - if (value >= 0) { - return value; - } - } - }, - extraContactHeaderParams: function (extraContactHeaderParams) { - if (extraContactHeaderParams instanceof Array) { - return extraContactHeaderParams.filter(function (contactHeaderParam) { return (typeof contactHeaderParam === "string"); }); - } - }, - instanceId: function (instanceId) { - if (typeof instanceId !== "string") { - return; - } - if ((/^uuid:/i.test(instanceId))) { - instanceId = instanceId.substr(5); - } - if (core_1.Grammar.parse(instanceId, "uuid") === -1) { - return; - } - else { - return instanceId; - } - }, - params: function (params) { - if (typeof params === "object") { - return params; - } - }, - regId: function (regId) { - if (Utils_1.Utils.isDecimal(regId)) { - var value = Number(regId); - if (value >= 0) { - return value; - } - } - }, - registrar: function (registrar) { - if (typeof registrar !== "string") { - return; - } - if (!/^sip:/i.test(registrar)) { - registrar = Constants_1.C.SIP + ":" + registrar; - } - var parsed = core_1.Grammar.URIParse(registrar); - if (!parsed) { - return; - } - else if (parsed.user) { - return; - } - else { - return parsed; - } - } - } - }; -} -/** - * A registerer registers a contact for an address of record (outgoing REGISTER). - * @public - */ -var Registerer = /** @class */ (function () { - /** - * Constructs a new instance of the `Registerer` class. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @param options - Options bucket. See {@link RegistererOptions} for details. - */ - function Registerer(userAgent, options) { - var _this = this; - if (options === void 0) { options = {}; } - /** The contacts returned from the most recent accepted REGISTER request. */ - this._contacts = []; - /** The registration state. */ - this._state = registerer_state_1.RegistererState.Initial; - /** Emits when the registration state changes. */ - this._stateEventEmitter = new events_1.EventEmitter(); - /** True is waiting for final response to outstanding REGISTER request. */ - this._waiting = false; - /** Emits when waiting changes. */ - this._waitingEventEmitter = new events_1.EventEmitter(); - var settings = loadConfig(options); - if (settings.regId && !settings.instanceId) { - settings.instanceId = Utils_1.Utils.newUUID(); - } - else if (!settings.regId && settings.instanceId) { - settings.regId = 1; - } - settings.params.toUri = settings.params.toUri || userAgent.configuration.uri; - settings.params.toDisplayName = settings.params.toDisplayName || userAgent.configuration.displayName; - settings.params.callId = settings.params.callId || Utils_1.Utils.createRandomToken(22); - settings.params.cseq = settings.params.cseq || Math.floor(Math.random() * 10000); - /* If no 'registrarServer' is set use the 'uri' value without user portion. */ - if (!settings.registrar) { - var registrarServer = {}; - if (typeof userAgent.configuration.uri === "object") { - registrarServer = userAgent.configuration.uri.clone(); - registrarServer.user = undefined; - } - else { - registrarServer = userAgent.configuration.uri; - } - settings.registrar = registrarServer; - } - this.userAgent = userAgent; - this.logger = userAgent.getLogger("sip.registerer"); - var extraHeaders = (options.extraHeaders || []).slice(); - // Build the request - this.request = userAgent.userAgentCore.makeOutgoingRequestMessage(Constants_1.C.REGISTER, settings.registrar, settings.params.fromUri ? settings.params.fromUri : userAgent.userAgentCore.configuration.aor, settings.params.toUri ? settings.params.toUri : settings.registrar, settings.params, extraHeaders, undefined); - this.options = settings; - this.logger.log("configuration parameters for RegisterContext after validation:"); - for (var parameter in settings) { - if (settings.hasOwnProperty(parameter)) { - this.logger.log("· " + parameter + ": " + JSON.stringify(settings[parameter])); - } - } - // Registration expires - this.expires = settings.expires; - // Contact header - this.contact = userAgent.contact.toString(); - userAgent.transport.on("disconnected", function () { return _this.onTransportDisconnected(); }); - // Add to UA's collection - this.id = this.request.callId + this.request.from.parameters.tag; - this.userAgent.registerers[this.id] = this; - } - Object.defineProperty(Registerer.prototype, "contacts", { - /** The registered contacts. */ - get: function () { - return this._contacts.slice(); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Registerer.prototype, "state", { - /** The registration state. */ - get: function () { - return this._state; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Registerer.prototype, "stateChange", { - /** Emits when the registerer state changes. */ - get: function () { - return emitter_1.makeEmitter(this._stateEventEmitter); - }, - enumerable: true, - configurable: true - }); - /** Destructor. */ - Registerer.prototype.dispose = function () { - return tslib_1.__awaiter(this, void 0, void 0, function () { - var _this = this; - return tslib_1.__generator(this, function (_a) { - // Remove from UA's collection - delete this.userAgent.registerers[this.id]; - // If registered, unregisters and resolves after final response received. - return [2 /*return*/, new Promise(function (resolve, reject) { - var doClose = function () { - // If we are registered, unregister and resolve after our state changes - if (!_this.waiting && _this._state === registerer_state_1.RegistererState.Registered) { - _this.stateChange.once(function () { return resolve(); }); - _this.unregister(); - return; - } - // Otherwise just resolve - resolve(); - }; - // If we are waiting for an outstanding request, wait for it to finish and then try closing. - // Otherwise just try closing. - if (_this.waiting) { - _this.waitingChange.once(function () { return doClose(); }); - } - else { - doClose(); - } - })]; - }); - }); - }; - /** - * Sends the REGISTER request. - * @remarks - * If successfull, sends re-REGISTER requests prior to registration expiration until `unsubscribe()` is called. - */ - Registerer.prototype.register = function (options) { - if (options === void 0) { options = {}; } - return tslib_1.__awaiter(this, void 0, void 0, function () { - var error, extraHeaders, outgoingRegisterRequest; - var _this = this; - return tslib_1.__generator(this, function (_a) { - // UAs MUST NOT send a new registration (that is, containing new Contact - // header field values, as opposed to a retransmission) until they have - // received a final response from the registrar for the previous one or - // the previous REGISTER request has timed out. - // https://tools.ietf.org/html/rfc3261#section-10.2 - if (this.waiting) { - error = new Error("REGISTER request already in progress, waiting for final response"); - return [2 /*return*/, Promise.reject(error)]; - } - // Options - if (options.requestOptions) { - this.options = tslib_1.__assign({}, this.options, options.requestOptions); - } - extraHeaders = (this.options.extraHeaders || []).slice(); - extraHeaders.push("Contact: " + this.generateContactHeader(this.expires)); - // this is UA.C.ALLOWED_METHODS, removed to get around circular dependency - extraHeaders.push("Allow: " + [ - "ACK", - "CANCEL", - "INVITE", - "MESSAGE", - "BYE", - "OPTIONS", - "INFO", - "NOTIFY", - "REFER" - ].toString()); - // Call-ID: All registrations from a UAC SHOULD use the same Call-ID - // header field value for registrations sent to a particular - // registrar. - // - // CSeq: The CSeq value guarantees proper ordering of REGISTER - // requests. A UA MUST increment the CSeq value by one for each - // REGISTER request with the same Call-ID. - // https://tools.ietf.org/html/rfc3261#section-10.2 - this.request.cseq++; - this.request.setHeader("cseq", this.request.cseq + " REGISTER"); - this.request.extraHeaders = extraHeaders; - this.waitingToggle(true); - outgoingRegisterRequest = this.userAgent.userAgentCore.register(this.request, { - onAccept: function (response) { - var expires; - // FIXME: This does NOT appear to be to spec and should be removed. - // I haven't found anywhere that an Expires header may be used in a response. - if (response.message.hasHeader("expires")) { - expires = Number(response.message.getHeader("expires")); - } - // 8. The registrar returns a 200 (OK) response. The response MUST - // contain Contact header field values enumerating all current - // bindings. Each Contact value MUST feature an "expires" - // parameter indicating its expiration interval chosen by the - // registrar. The response SHOULD include a Date header field. - // https://tools.ietf.org/html/rfc3261#section-10.3 - _this._contacts = response.message.getHeaders("contact"); - var contacts = _this._contacts.length; - if (!contacts) { - _this.logger.error("No Contact header in response to REGISTER, dropping response."); - _this.unregistered(); - return; - } - // The 200 (OK) response from the registrar contains a list of Contact - // fields enumerating all current bindings. The UA compares each - // contact address to see if it created the contact address, using - // comparison rules in Section 19.1.4. If so, it updates the expiration - // time interval according to the expires parameter or, if absent, the - // Expires field value. The UA then issues a REGISTER request for each - // of its bindings before the expiration interval has elapsed. - // https://tools.ietf.org/html/rfc3261#section-10.2.4 - var contact; - while (contacts--) { - contact = response.message.parseHeader("contact", contacts); - if (contact.uri.user === _this.userAgent.contact.uri.user) { - expires = contact.getParam("expires"); - break; - } - else { - contact = undefined; - } - } - // There must be a matching contact. - if (contact === undefined) { - _this.logger.error("No Contact header pointing to us, dropping response"); - _this.unregistered(); - _this.waitingToggle(false); - return; - } - // The contact must have an expires. - if (expires === undefined) { - _this.logger.error("Contact pointing to us is missing expires parameter, dropping response"); - _this.unregistered(); - _this.waitingToggle(false); - return; - } - // Save gruu values - if (contact.hasParam("temp-gruu")) { - _this.userAgent.contact.tempGruu = core_1.Grammar.URIParse(contact.getParam("temp-gruu").replace(/"/g, "")); - } - if (contact.hasParam("pub-gruu")) { - _this.userAgent.contact.pubGruu = core_1.Grammar.URIParse(contact.getParam("pub-gruu").replace(/"/g, "")); - } - _this.registered(expires); - _this.waitingToggle(false); - }, - onProgress: function (response) { - return; - }, - onRedirect: function (response) { - _this.logger.error("Redirect received. Not supported."); - _this.unregistered(); - _this.waitingToggle(false); - }, - onReject: function (response) { - if (response.message.statusCode === 423) { - // If a UA receives a 423 (Interval Too Brief) response, it MAY retry - // the registration after making the expiration interval of all contact - // addresses in the REGISTER request equal to or greater than the - // expiration interval within the Min-Expires header field of the 423 - // (Interval Too Brief) response. - // https://tools.ietf.org/html/rfc3261#section-10.2.8 - // - // The registrar MAY choose an expiration less than the requested - // expiration interval. If and only if the requested expiration - // interval is greater than zero AND smaller than one hour AND - // less than a registrar-configured minimum, the registrar MAY - // reject the registration with a response of 423 (Interval Too - // Brief). This response MUST contain a Min-Expires header field - // that states the minimum expiration interval the registrar is - // willing to honor. It then skips the remaining steps. - // https://tools.ietf.org/html/rfc3261#section-10.3 - if (!response.message.hasHeader("min-expires")) { - // This response MUST contain a Min-Expires header field - _this.logger.error("423 response received for REGISTER without Min-Expires"); - _this.unregistered(); - _this.waitingToggle(false); - return; - } - // Increase our registration interval to the suggested minimum - _this.expires = Number(response.message.getHeader("min-expires")); - // Attempt the registration again immediately - _this.waitingToggle(false); - _this.register(); - return; - } - _this.logger.warn("Failed to register, status code " + response.message.statusCode); - _this.unregistered(); - _this.waitingToggle(false); - }, - onTrying: function (response) { - return; - } - }); - return [2 /*return*/, Promise.resolve(outgoingRegisterRequest)]; - }); - }); - }; - /** - * Sends the REGISTER request with expires equal to zero. - */ - Registerer.prototype.unregister = function (options) { - if (options === void 0) { options = {}; } - return tslib_1.__awaiter(this, void 0, void 0, function () { - var error, extraHeaders, outgoingRegisterRequest; - var _this = this; - return tslib_1.__generator(this, function (_a) { - // UAs MUST NOT send a new registration (that is, containing new Contact - // header field values, as opposed to a retransmission) until they have - // received a final response from the registrar for the previous one or - // the previous REGISTER request has timed out. - // https://tools.ietf.org/html/rfc3261#section-10.2 - if (this.waiting) { - error = new Error("REGISTER request already in progress, waiting for final response"); - return [2 /*return*/, Promise.reject(error)]; - } - if (this._state !== registerer_state_1.RegistererState.Registered && !options.all) { - this.logger.warn("Not currently registered, but sending an unregister anyway."); - } - extraHeaders = (options.requestOptions && options.requestOptions.extraHeaders || []).slice(); - this.request.extraHeaders = extraHeaders; - // Registrations are soft state and expire unless refreshed, but can - // also be explicitly removed. A client can attempt to influence the - // expiration interval selected by the registrar as described in Section - // 10.2.1. A UA requests the immediate removal of a binding by - // specifying an expiration interval of "0" for that contact address in - // a REGISTER request. UAs SHOULD support this mechanism so that - // bindings can be removed before their expiration interval has passed. - // - // The REGISTER-specific Contact header field value of "*" applies to - // all registrations, but it MUST NOT be used unless the Expires header - // field is present with a value of "0". - // https://tools.ietf.org/html/rfc3261#section-10.2.2 - if (options.all) { - extraHeaders.push("Contact: *"); - extraHeaders.push("Expires: 0"); - } - else { - extraHeaders.push("Contact: " + this.generateContactHeader(0)); - } - // Call-ID: All registrations from a UAC SHOULD use the same Call-ID - // header field value for registrations sent to a particular - // registrar. - // - // CSeq: The CSeq value guarantees proper ordering of REGISTER - // requests. A UA MUST increment the CSeq value by one for each - // REGISTER request with the same Call-ID. - // https://tools.ietf.org/html/rfc3261#section-10.2 - this.request.cseq++; - this.request.setHeader("cseq", this.request.cseq + " REGISTER"); - // Pre-emptively clear the registration timer to avoid a race condition where - // this timer fires while waiting for a final response to the unsubscribe. - if (this.registrationTimer !== undefined) { - clearTimeout(this.registrationTimer); - this.registrationTimer = undefined; - } - this.waitingToggle(true); - outgoingRegisterRequest = this.userAgent.userAgentCore.register(this.request, { - onAccept: function (response) { - _this._contacts = response.message.getHeaders("contact"); // Update contacts - _this.unregistered(); - if (options.requestDelegate && options.requestDelegate.onAccept) { - options.requestDelegate.onAccept(response); - } - _this.waitingToggle(false); - }, - onProgress: function (response) { - if (options.requestDelegate && options.requestDelegate.onProgress) { - options.requestDelegate.onProgress(response); - } - }, - onRedirect: function (response) { - _this.logger.error("Unregister redirected. Not currently supported."); - _this.unregistered(); - if (options.requestDelegate && options.requestDelegate.onRedirect) { - options.requestDelegate.onRedirect(response); - } - _this.waitingToggle(false); - }, - onReject: function (response) { - _this.waitingToggle(false); - _this.logger.error("Unregister rejected with status code " + response.message.statusCode); - _this.unregistered(); - if (options.requestDelegate && options.requestDelegate.onReject) { - options.requestDelegate.onReject(response); - } - _this.waitingToggle(false); - }, - onTrying: function (response) { - if (options.requestDelegate && options.requestDelegate.onTrying) { - options.requestDelegate.onTrying(response); - } - } - }); - return [2 /*return*/, Promise.resolve(outgoingRegisterRequest)]; - }); - }); - }; - /** @internal */ - Registerer.prototype.clearTimers = function () { - if (this.registrationTimer !== undefined) { - clearTimeout(this.registrationTimer); - this.registrationTimer = undefined; - } - if (this.registrationExpiredTimer !== undefined) { - clearTimeout(this.registrationExpiredTimer); - this.registrationExpiredTimer = undefined; - } - }; - /** - * Helper Function to generate Contact Header - * @internal - */ - Registerer.prototype.generateContactHeader = function (expires) { - if (expires === void 0) { expires = 0; } - var contact = this.contact; - if (this.options.regId && this.options.instanceId) { - contact += ";reg-id=" + this.options.regId; - contact += ';+sip.instance=""'; - } - if (this.options.extraContactHeaderParams) { - this.options.extraContactHeaderParams.forEach(function (header) { - contact += ";" + header; - }); - } - contact += ";expires=" + expires; - return contact; - }; - /** @internal */ - Registerer.prototype.onTransportDisconnected = function () { - this.unregistered(); - }; - /** @internal */ - Registerer.prototype.registered = function (expires) { - var _this = this; - this.clearTimers(); - // Re-Register before the expiration interval has elapsed. - // For that, decrease the expires value. ie: 3 seconds - this.registrationTimer = setTimeout(function () { - _this.registrationTimer = undefined; - _this.register(); - }, (expires * 1000) - 3000); - // We are unregistered if the registration expires. - this.registrationExpiredTimer = setTimeout(function () { - _this.logger.warn("Registration expired"); - _this.unregistered(); - }, expires * 1000); - if (this._state !== registerer_state_1.RegistererState.Registered) { - this.stateTransition(registerer_state_1.RegistererState.Registered); - } - }; - /** @internal */ - Registerer.prototype.unregistered = function () { - this.clearTimers(); - if (this._state !== registerer_state_1.RegistererState.Unregistered) { - this.stateTransition(registerer_state_1.RegistererState.Unregistered); - } - }; - /** - * Transition registration state. - * @internal - */ - Registerer.prototype.stateTransition = function (newState) { - var _this = this; - var invalidTransition = function () { - throw new Error("Invalid state transition from " + _this._state + " to " + newState); - }; - // Validate transition - switch (this._state) { - case registerer_state_1.RegistererState.Initial: - if (newState !== registerer_state_1.RegistererState.Registered && - newState !== registerer_state_1.RegistererState.Unregistered) { - invalidTransition(); - } - break; - case registerer_state_1.RegistererState.Registered: - if (newState !== registerer_state_1.RegistererState.Unregistered) { - invalidTransition(); - } - break; - case registerer_state_1.RegistererState.Unregistered: - if (newState !== registerer_state_1.RegistererState.Registered) { - invalidTransition(); - } - break; - default: - throw new Error("Unrecognized state."); - } - // Transition - this._state = newState; - this.logger.log("Registration transitioned to state " + this._state); - this._stateEventEmitter.emit("event", this._state); - }; - Object.defineProperty(Registerer.prototype, "waiting", { - /** True if waiting for final response to a REGISTER request. */ - get: function () { - return this._waiting; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Registerer.prototype, "waitingChange", { - /** Emits when the registerer toggles waiting. */ - get: function () { - return emitter_1.makeEmitter(this._waitingEventEmitter); - }, - enumerable: true, - configurable: true - }); - /** - * Toggle waiting. - * @internal - */ - Registerer.prototype.waitingToggle = function (waiting) { - if (this._waiting === waiting) { - throw new Error("Invalid waiting transition from " + this._waiting + " to " + waiting); - } - this._waiting = waiting; - this.logger.log("Waiting toggled to " + this._waiting); - this._waitingEventEmitter.emit("event", this._waiting); - }; - return Registerer; -}()); -exports.Registerer = Registerer; diff --git a/lib/api/session-delegate.d.ts b/lib/api/session-delegate.d.ts deleted file mode 100644 index 524151dd5..000000000 --- a/lib/api/session-delegate.d.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { IncomingRequestMessage } from "../core"; -import { Info } from "./info"; -import { Notification } from "./notification"; -import { Referral } from "./referral"; -/** - * Delegate for {@link Session}. - * @public - */ -export interface SessionDelegate { - /** - * Called upon receiving an incoming in dialog INFO request. - * @param info - The info. - */ - onInfo?(info: Info): void; - /** - * Called upon receiving an incoming in dialog INVITE request. - * @param invite - The invite. - */ - onInvite?(request: IncomingRequestMessage, response: string, statusCode: number): void; - /** - * Called upon receiving an incoming in dialog NOTIFY request. - * - * @remarks - * If a refer is in progress notifications are delivered to the referrers delegate. - * - * @param notification - The notification. - */ - onNotify?(notification: Notification): void; - /** - * Called upon receiving an incoming in dialog REFER request. - * @param referral - The referral. - */ - onRefer?(referral: Referral): void; - /** - * Hook which is called upon receiving an incoming in dialog INVITE request. - * Used for generating and testing failure cases. - * @internal - */ - onReinviteTest?(): "acceptWithoutDescription" | "reject488"; -} -//# sourceMappingURL=session-delegate.d.ts.map \ No newline at end of file diff --git a/lib/api/session-delegate.d.ts.map b/lib/api/session-delegate.d.ts.map deleted file mode 100644 index 1a5d6e1bd..000000000 --- a/lib/api/session-delegate.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"session-delegate.d.ts","sourceRoot":"","sources":["../../src/api/session-delegate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,SAAS,CAAC;AACjD,OAAO,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AAC9B,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAEtC;;;GAGG;AACH,MAAM,WAAW,eAAe;IAC9B;;;OAGG;IACH,MAAM,CAAC,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,CAAC;IAE1B;;;OAGG;IACH,QAAQ,CAAC,CAAC,OAAO,EAAE,sBAAsB,EAAE,QAAQ,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAEvF;;;;;;;OAOG;IACH,QAAQ,CAAC,CAAC,YAAY,EAAE,YAAY,GAAG,IAAI,CAAC;IAE5C;;;OAGG;IACH,OAAO,CAAC,CAAC,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAAC;IAUnC;;;;OAIG;IACH,cAAc,CAAC,IAAI,0BAA0B,GAAG,WAAW,CAAC;CAC7D"} \ No newline at end of file diff --git a/lib/api/session-delegate.js b/lib/api/session-delegate.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/api/session-delegate.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/api/session-description-handler-factory.d.ts b/lib/api/session-description-handler-factory.d.ts deleted file mode 100644 index a85aa9ad7..000000000 --- a/lib/api/session-description-handler-factory.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Session } from "./session"; -import { SessionDescriptionHandler } from "./session-description-handler"; -/** - * Factory for {@link SessionDescriptionHandler}. - * @public - */ -export interface SessionDescriptionHandlerFactory { - /** - * SessionDescriptionHandler factory fucntion. - * @remarks - * The `options` are provided as part of the UserAgent configuration - * and passed through on every call to SessionDescriptionHandlerFactory's constructor. - */ - (session: Session, options?: object): SessionDescriptionHandler; -} -//# sourceMappingURL=session-description-handler-factory.d.ts.map \ No newline at end of file diff --git a/lib/api/session-description-handler-factory.d.ts.map b/lib/api/session-description-handler-factory.d.ts.map deleted file mode 100644 index 473caa0c8..000000000 --- a/lib/api/session-description-handler-factory.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"session-description-handler-factory.d.ts","sourceRoot":"","sources":["../../src/api/session-description-handler-factory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAI1E;;;GAGG;AACH,MAAM,WAAW,gCAAgC;IAC/C;;;;;OAKG;IACH,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,yBAAyB,CAAC;CACjE"} \ No newline at end of file diff --git a/lib/api/session-description-handler-factory.js b/lib/api/session-description-handler-factory.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/api/session-description-handler-factory.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/api/session-description-handler.d.ts b/lib/api/session-description-handler.d.ts deleted file mode 100644 index e2dbaebe5..000000000 --- a/lib/api/session-description-handler.d.ts +++ /dev/null @@ -1,83 +0,0 @@ -/** - * Delegate for {@link Session} offer/answer exchange. - * @public - */ -export interface SessionDescriptionHandler { - /** - * Destructor. - */ - close(): void; - /** - * Gets the local description from the underlying media implementation. - * @param options - Options object to be used by getDescription. - * @param modifiers - Array with one time use description modifiers. - * @returns Promise that resolves with the local description to be used for the session. - * Rejects with `ClosedSessionDescriptionHandlerError` when this method - * is called after close or when close occurs before complete. - */ - getDescription(options?: SessionDescriptionHandlerOptions, modifiers?: Array): Promise; - /** - * Returns true if the Session Description Handler can handle the Content-Type described by a SIP message. - * @param contentType - The content type that is in the SIP Message. - * @returns True if the content type is handled by this session description handler. False otherwise. - */ - hasDescription(contentType: string): boolean; - /** - * The modifier that should be used when the session would like to place the call on hold. - * @param sessionDescription - The description that will be modified. - * @returns Promise that resolves with modified SDP. - * Rejects with `ClosedSessionDescriptionHandlerError` when this method - * is called after close or when close occurs before complete. - */ - holdModifier(sessionDescription: RTCSessionDescriptionInit): Promise; - /** - * Rolls back the current local/remote offer to the prior stable state. - */ - rollbackDescription?(): Promise; - /** - * Sets the remote description to the underlying media implementation. - * @param sessionDescription - The description provided by a SIP message to be set on the media implementation. - * @param options - Options object to be used by setDescription. - * @param modifiers - Array with one time use description modifiers. - * @returns Promise that resolves once the description is set. - * Rejects with `ClosedSessionDescriptionHandlerError` when this method - * is called after close or when close occurs before complete. - */ - setDescription(sdp: string, options?: SessionDescriptionHandlerOptions, modifiers?: Array): Promise; - /** - * Send DTMF via RTP (RFC 4733). - * Returns true if DTMF send is successful, false otherwise. - * @param tones - A string containing DTMF digits. - * @param options - Options object to be used by sendDtmf. - * @returns True if DTMF send is successful, false otherwise. - */ - sendDtmf(tones: string, options?: any): boolean; -} -/** - * Modifier for {@link SessionDescriptionHandler} offer/answer. - * @public - */ -export interface SessionDescriptionHandlerModifier { - (sessionDescription: RTCSessionDescriptionInit): Promise; -} -/** - * Options for {@link SessionDescriptionHandler} methods. - * @remarks - * These options are provided to various UserAgent methods (invite() for example) - * and passed through on calls to getDescription() and setDescription(). - * @public - */ -export interface SessionDescriptionHandlerOptions { - constraints?: object; -} -/** - * Message body content and type. - * @public - */ -export interface BodyAndContentType { - /** Message body content. */ - body: string; - /** Message body content type. */ - contentType: string; -} -//# sourceMappingURL=session-description-handler.d.ts.map \ No newline at end of file diff --git a/lib/api/session-description-handler.d.ts.map b/lib/api/session-description-handler.d.ts.map deleted file mode 100644 index 65ae138fa..000000000 --- a/lib/api/session-description-handler.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"session-description-handler.d.ts","sourceRoot":"","sources":["../../src/api/session-description-handler.ts"],"names":[],"mappings":"AAEA;;;GAGG;AACH,MAAM,WAAW,yBAAyB;IACxC;;OAEG;IACH,KAAK,IAAI,IAAI,CAAC;IAEd;;;;;;;OAOG;IACH,cAAc,CACZ,OAAO,CAAC,EAAE,gCAAgC,EAC1C,SAAS,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,GACnD,OAAO,CAAC,kBAAkB,CAAC,CAAC;IAE/B;;;;OAIG;IACH,cAAc,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC;IAE7C;;;;;;OAMG;IACH,YAAY,CAAC,kBAAkB,EAAE,yBAAyB,GAAG,OAAO,CAAC,yBAAyB,CAAC,CAAC;IAEhG;;OAEG;IACH,mBAAmB,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAEtC;;;;;;;;OAQG;IACH,cAAc,CACZ,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,gCAAgC,EAC1C,SAAS,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,GACnD,OAAO,CAAC,IAAI,CAAC,CAAC;IAEjB;;;;;;OAMG;IACH,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,GAAG,GAAG,OAAO,CAAC;CACjD;AAED;;;GAGG;AACH,MAAM,WAAW,iCAAiC;IAChD,CAAC,kBAAkB,EAAE,yBAAyB,GAAG,OAAO,CAAC,yBAAyB,CAAC,CAAC;CACrF;AAED;;;;;;GAMG;AACH,MAAM,WAAW,gCAAgC;IAC/C,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED;;;GAGG;AACH,MAAM,WAAW,kBAAkB;IACjC,4BAA4B;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,iCAAiC;IACjC,WAAW,EAAE,MAAM,CAAC;CACrB"} \ No newline at end of file diff --git a/lib/api/session-description-handler.js b/lib/api/session-description-handler.js deleted file mode 100644 index 993644a62..000000000 --- a/lib/api/session-description-handler.js +++ /dev/null @@ -1,3 +0,0 @@ -"use strict"; -// tslint:disable:callable-types -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/api/session-invite-options.d.ts b/lib/api/session-invite-options.d.ts deleted file mode 100644 index 0f150b354..000000000 --- a/lib/api/session-invite-options.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { OutgoingRequestDelegate, RequestOptions } from "../core"; -import { SessionDescriptionHandlerModifier, SessionDescriptionHandlerOptions } from "./session-description-handler"; -/** - * Options for {@link Session.invite}. - * @public - */ -export interface SessionInviteOptions { - /** See `core` API. */ - requestDelegate?: OutgoingRequestDelegate; - /** See `core` API. */ - requestOptions?: RequestOptions; - sessionDescriptionHandlerModifiers?: Array; - sessionDescriptionHandlerOptions?: SessionDescriptionHandlerOptions; - /** If true, send INVITE without SDP. Default is false. */ - withoutSdp?: boolean; -} -//# sourceMappingURL=session-invite-options.d.ts.map \ No newline at end of file diff --git a/lib/api/session-invite-options.d.ts.map b/lib/api/session-invite-options.d.ts.map deleted file mode 100644 index 0551b50b7..000000000 --- a/lib/api/session-invite-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"session-invite-options.d.ts","sourceRoot":"","sources":["../../src/api/session-invite-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAClE,OAAO,EACL,iCAAiC,EACjC,gCAAgC,EACjC,MAAM,+BAA+B,CAAC;AAEvC;;;GAGG;AACH,MAAM,WAAW,oBAAoB;IACnC,sBAAsB;IACtB,eAAe,CAAC,EAAE,uBAAuB,CAAC;IAC1C,sBAAsB;IACtB,cAAc,CAAC,EAAE,cAAc,CAAC;IAChC,kCAAkC,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,CAAC;IAC9E,gCAAgC,CAAC,EAAE,gCAAgC,CAAC;IACpE,0DAA0D;IAC1D,UAAU,CAAC,EAAE,OAAO,CAAC;CACtB"} \ No newline at end of file diff --git a/lib/api/session-invite-options.js b/lib/api/session-invite-options.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/api/session-invite-options.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/api/session-options.d.ts b/lib/api/session-options.d.ts deleted file mode 100644 index ea5e9b0fc..000000000 --- a/lib/api/session-options.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { SessionDelegate } from "./session-delegate"; -/** - * Options for {@link Session} constructor. - * @public - */ -export interface SessionOptions { - delegate?: SessionDelegate; -} -//# sourceMappingURL=session-options.d.ts.map \ No newline at end of file diff --git a/lib/api/session-options.d.ts.map b/lib/api/session-options.d.ts.map deleted file mode 100644 index fd9033393..000000000 --- a/lib/api/session-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"session-options.d.ts","sourceRoot":"","sources":["../../src/api/session-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACrD;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,EAAE,eAAe,CAAC;CAC5B"} \ No newline at end of file diff --git a/lib/api/session-options.js b/lib/api/session-options.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/api/session-options.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/api/session-state.d.ts b/lib/api/session-state.d.ts deleted file mode 100644 index 290a3027d..000000000 --- a/lib/api/session-state.d.ts +++ /dev/null @@ -1,26 +0,0 @@ -/** - * {@link Session} state. - * @remarks - * Valid state transitions: - * ``` - * 1. "initial" --> "establishing" (before INVITE sent on outgoing, before OK sent on incoming) - * 2. "initial" --> "established" (after ACK is sent on outgoing, after OK sent on incoming) - * 4. "initial" --> "terminating" - * 4. "initial" --> "terminated" - * 5. "establishing" --> "established" - * 6. "establishing" --> "terminating" - * 7. "establishing" --> "terminated" - * 8. "established" --> "terminating" - * 9. "established" --> "terminated" - * 10. "terminating" --> "terminated" - * ``` - * @public - */ -export declare enum SessionState { - Initial = "Initial", - Establishing = "Establishing", - Established = "Established", - Terminating = "Terminating", - Terminated = "Terminated" -} -//# sourceMappingURL=session-state.d.ts.map \ No newline at end of file diff --git a/lib/api/session-state.d.ts.map b/lib/api/session-state.d.ts.map deleted file mode 100644 index 3ff6bff54..000000000 --- a/lib/api/session-state.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"session-state.d.ts","sourceRoot":"","sources":["../../src/api/session-state.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AACH,oBAAY,YAAY;IACtB,OAAO,YAAY;IACnB,YAAY,iBAAiB;IAC7B,WAAW,gBAAgB;IAC3B,WAAW,gBAAgB;IAC3B,UAAU,eAAe;CAC1B"} \ No newline at end of file diff --git a/lib/api/session-state.js b/lib/api/session-state.js deleted file mode 100644 index f9ea29a42..000000000 --- a/lib/api/session-state.js +++ /dev/null @@ -1,28 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * {@link Session} state. - * @remarks - * Valid state transitions: - * ``` - * 1. "initial" --> "establishing" (before INVITE sent on outgoing, before OK sent on incoming) - * 2. "initial" --> "established" (after ACK is sent on outgoing, after OK sent on incoming) - * 4. "initial" --> "terminating" - * 4. "initial" --> "terminated" - * 5. "establishing" --> "established" - * 6. "establishing" --> "terminating" - * 7. "establishing" --> "terminated" - * 8. "established" --> "terminating" - * 9. "established" --> "terminated" - * 10. "terminating" --> "terminated" - * ``` - * @public - */ -var SessionState; -(function (SessionState) { - SessionState["Initial"] = "Initial"; - SessionState["Establishing"] = "Establishing"; - SessionState["Established"] = "Established"; - SessionState["Terminating"] = "Terminating"; - SessionState["Terminated"] = "Terminated"; -})(SessionState = exports.SessionState || (exports.SessionState = {})); diff --git a/lib/api/session.d.ts b/lib/api/session.d.ts deleted file mode 100644 index 94674d15f..000000000 --- a/lib/api/session.d.ts +++ /dev/null @@ -1,430 +0,0 @@ -/// -import { EventEmitter } from "events"; -import { C } from "../Constants"; -import { AckableIncomingResponseWithSession, Body, IncomingAckRequest, IncomingByeRequest, IncomingInfoRequest, IncomingInviteRequest, IncomingNotifyRequest, IncomingPrackRequest, IncomingReferRequest, IncomingRequestMessage, IncomingResponseMessage, Logger, NameAddrHeader, OutgoingByeRequest, OutgoingInviteRequest, OutgoingRequestDelegate, OutgoingRequestMessage, RequestOptions, Session as SessionDialog } from "../core"; -import { SessionStatus, TypeStrings } from "../Enums"; -import { Emitter } from "./emitter"; -import { Inviter } from "./inviter"; -import { Referrer } from "./referrer"; -import { SessionDelegate } from "./session-delegate"; -import { BodyAndContentType, SessionDescriptionHandler, SessionDescriptionHandlerModifier, SessionDescriptionHandlerOptions } from "./session-description-handler"; -import { SessionDescriptionHandlerFactory } from "./session-description-handler-factory"; -import { SessionInviteOptions } from "./session-invite-options"; -import { SessionOptions } from "./session-options"; -import { SessionState } from "./session-state"; -import { UserAgent } from "./user-agent"; -/** - * A session provides real time communication between one or more participants. - * @public - */ -export declare abstract class Session extends EventEmitter { - /** @internal */ - static readonly C: typeof SessionStatus; - /** - * Property reserved for use by instance owner. - * @defaultValue `undefined` - */ - data: any | undefined; - /** - * The session delegate. - * @defaultValue `undefined` - */ - delegate: SessionDelegate | undefined; - /** - * The confirmed session dialog. - */ - dialog: SessionDialog | undefined; - /** @internal */ - type: TypeStrings; - /** @internal */ - userAgent: UserAgent; - /** @internal */ - logger: Logger; - /** @internal */ - method: string; - /** @internal */ - abstract body: BodyAndContentType | string | undefined; - /** @internal */ - abstract localIdentity: NameAddrHeader; - /** @internal */ - abstract remoteIdentity: NameAddrHeader; - /** @internal */ - assertedIdentity: NameAddrHeader | undefined; - /** @internal */ - contentType: string | undefined; - /** @internal */ - id: string | undefined; - /** @internal */ - contact: string | undefined; - /** Terminated time. */ - /** @internal */ - endTime: Date | undefined; - /** @internal */ - localHold: boolean; - /** @internal */ - referral: Inviter | undefined; - /** @internal */ - referrer: Referrer | undefined; - /** @internal */ - replacee: Session | undefined; - /** Accepted time. */ - /** @internal */ - startTime: Date | undefined; - /** DEPRECATED: Session status */ - /** @internal */ - status: SessionStatus; - /** True if an error caused session termination. */ - /** @internal */ - isFailed: boolean; - /** @internal */ - protected earlySdp: string | undefined; - /** @internal */ - protected errorListener: ((...args: Array) => void); - /** @internal */ - protected fromTag: string | undefined; - /** @internal */ - protected onInfo: ((request: IncomingRequestMessage) => void) | undefined; - /** @internal */ - protected passedOptions: any; - /** @internal */ - protected rel100: C.supported; - /** @internal */ - protected renderbody: string | undefined; - /** @internal */ - protected rendertype: string | undefined; - /** @internal */ - protected sessionDescriptionHandlerModifiers: Array | undefined; - /** @internal */ - protected sessionDescriptionHandlerOptions: SessionDescriptionHandlerOptions | undefined; - /** @internal */ - protected expiresTimer: any; - /** @internal */ - protected userNoAnswerTimer: any; - private _sessionDescriptionHandler; - private _state; - private _stateEventEmitter; - private pendingReinvite; - private tones; - /** - * Constructor. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @internal - */ - protected constructor(userAgent: UserAgent, options?: SessionOptions); - /** - * @deprecated Legacy state transition. - * @internal - */ - on(event: "SessionDescriptionHandler-created", listener: (sessionDescriptionHandler: SessionDescriptionHandler) => void): this; - /** - * @deprecated Legacy state transition. - * @internal - */ - on(event: "referInviteSent" | "referProgress" | "referAccepted" | "referRequestProgress" | "referRequestAccepted" | "referRequestRejected" | "reinviteAccepted" | "reinviteFailed", listener: (session: Session) => void): this; - /** - * @deprecated Legacy state transition. - * @internal - */ - on(event: "reinvite", listener: (session: Session, request: IncomingRequestMessage) => void): this; - /** - * @deprecated Legacy state transition. - * @internal - */ - on(event: "confirmed" | "notify", listener: (request: IncomingRequestMessage) => void): this; - /** - * @deprecated Legacy state transition. - * @internal - */ - on(event: "bye", listener: (request: IncomingRequestMessage | OutgoingRequestMessage) => void): this; - /** - * @deprecated Legacy state transition. - * @internal - */ - on(event: "connecting", listener: (request: { - request: IncomingRequestMessage; - }) => void): this; - /** - * @deprecated Legacy state transition. - * @internal - */ - on(event: "progress", listener: (response: IncomingResponseMessage | string, reasonPhrase?: any) => void): this; - /** - * @deprecated Legacy state transition. - * @internal - */ - on(event: "failed" | "rejected", listener: (response?: IncomingRequestMessage | IncomingResponseMessage | string, cause?: string) => void): this; - /** - * @deprecated Legacy state transition. - * @internal - */ - on(event: "terminated", listener: (response?: IncomingRequestMessage | IncomingResponseMessage, cause?: string) => void): this; - /** - * @deprecated Legacy state transition. - * @internal - */ - on(event: "renegotiationError", listener: (error: Error) => void): this; - /** - * @deprecated Legacy state transition. - * @internal - */ - on(event: "trackAdded" | "directionChanged" | "referRejected", listener: () => void): this; - /** - * @deprecated Legacy state transition. - * @internal - */ - emit(event: "SessionDescriptionHandler-created", sessionDescriptionHandler: SessionDescriptionHandler): boolean; - /** - * @deprecated Legacy state transition. - * @internal - */ - emit(event: "referInviteSent" | "referRejected" | "referRequestProgress" | "referRequestAccepted" | "referRequestRejected" | "reinviteAccepted" | "reinviteFailed", session: Session): boolean; - /** - * @deprecated Legacy state transition. - * @internal - */ - emit(event: "reinvite", session: Session, request: IncomingRequestMessage): boolean; - /** - * @deprecated Legacy state transition. - * @internal - */ - emit(event: "confirmed" | "notify", request: IncomingRequestMessage): boolean; - /** - * @deprecated Legacy state transition. - * @internal - */ - emit(event: "invite" | "refer" | "notify", request: OutgoingRequestMessage): boolean; - /** - * @deprecated Legacy state transition. - * @internal - */ - emit(event: "bye", request: IncomingRequestMessage | OutgoingRequestMessage): boolean; - /** - * @deprecated Legacy state transition. - * @internal - */ - emit(event: "connecting", request: { - request: IncomingRequestMessage; - }): boolean; - /** - * @deprecated Legacy state transition. - * @internal - */ - emit(event: "progress", response: IncomingResponseMessage | string, reasonPhrase?: any): boolean; - /** - * @deprecated Legacy state transition. - * @internal - */ - emit(event: "failed" | "rejected", response?: IncomingRequestMessage | IncomingResponseMessage | string, cause?: string): boolean; - /** - * @deprecated Legacy state transition. - * @internal - */ - emit(event: "terminated", response?: IncomingRequestMessage | IncomingResponseMessage, cause?: string): boolean; - /** - * @deprecated Legacy state transition. - * @internal - */ - emit(event: "renegotiationError", error: Error): boolean; - /** - * @deprecated Legacy state transition. - * @internal - */ - emit(event: "trackAdded" | "directionChanged" | "referRejected"): boolean; - /** - * Session description handler. - */ - readonly sessionDescriptionHandler: SessionDescriptionHandler | undefined; - /** - * Session description handler factory. - */ - readonly sessionDescriptionHandlerFactory: SessionDescriptionHandlerFactory; - /** - * Session state. - */ - readonly state: SessionState; - /** - * Session state change emitter. - */ - readonly stateChange: Emitter; - /** - * Renegotiate the session. Sends a re-INVITE. - * @param options - Options bucket. - */ - invite(options?: SessionInviteOptions): Promise; - /** - * TODO: This is awkward. - * Helper function - * @internal - */ - byePending(): void; - /** - * TODO: This is awkward. - * Helper function - * @internal - */ - byeSent(request: OutgoingByeRequest): void; - /** - * Send BYE. - * @param delegate - Request delegate. - * @param options - Request options bucket. - * @internal - */ - bye(delegate?: OutgoingRequestDelegate, options?: RequestOptions): Promise; - /** - * Send INFO. - * @param delegate - Request delegate. - * @param options - Request options bucket. - * @internal - */ - info(delegate?: OutgoingRequestDelegate, options?: RequestOptions): Promise; - /** - * Send REFER. - * @param delegate - Request delegate. - * @param options - Request options bucket. - * @internal - */ - refer(referrer: Referrer, delegate?: OutgoingRequestDelegate, options?: RequestOptions): Promise; - /** - * @internal - */ - close(): void; - /** - * @internal - */ - onRequestTimeout(): void; - /** - * @internal - */ - onTransportError(): void; - /** - * Send ACK and then BYE. There are unrecoverable errors which can occur - * while handling dialog forming and in-dialog INVITE responses and when - * they occur we ACK the response and terminate the session. - * @param inviteResponse - The response causing the error. - * @param statusCode - Status code for he reason phrase. - * @param reasonPhrase - Reason phrase for the BYE. - * @internal - */ - protected ackAndBye(response: AckableIncomingResponseWithSession, statusCode?: number, reasonPhrase?: string): void; - /** - * Handle in dialog ACK request. - * @internal - */ - protected onAckRequest(request: IncomingAckRequest): void; - /** - * Handle in dialog BYE request. - * @internal - */ - protected onByeRequest(request: IncomingByeRequest): void; - /** - * Handle in dialog INFO request. - * @internal - */ - protected onInfoRequest(request: IncomingInfoRequest): void; - /** - * Handle in dialog INVITE request. - * @internal - */ - protected onInviteRequest(request: IncomingInviteRequest): void; - /** - * Handle in dialog NOTIFY request. - * @internal - */ - protected onNotifyRequest(request: IncomingNotifyRequest): void; - /** - * Handle in dialog PRACK request. - * @internal - */ - protected onPrackRequest(request: IncomingPrackRequest): void; - /** - * Handle in dialog REFER request. - * @internal - */ - protected onReferRequest(request: IncomingReferRequest): void; - /** - * @deprecated Legacy state transition. - * @internal - */ - protected connecting(request: IncomingRequestMessage): void; - /** - * @deprecated Legacy state transition. - * @internal - */ - protected failed(response: IncomingResponseMessage | IncomingRequestMessage | undefined, cause: string): void; - /** - * @deprecated Legacy state transition. - * @internal - */ - protected rejected(response: IncomingResponseMessage | IncomingRequestMessage, cause: string): void; - /** - * @deprecated Legacy state transition. - * @internal - */ - protected terminated(message?: IncomingResponseMessage | IncomingRequestMessage, cause?: string): void; - /** - * Generate an offer or answer for a response to an INVITE request. - * If a remote offer was provided in the request, set the remote - * description and get a local answer. If a remote offer was not - * provided, generates a local offer. - * @internal - */ - protected generateResponseOfferAnswer(request: IncomingInviteRequest, options: { - sessionDescriptionHandlerOptions?: SessionDescriptionHandlerOptions; - sessionDescriptionHandlerModifiers?: Array; - }): Promise; - /** - * Generate an offer or answer for a response to an INVITE request - * when a dialog (early or otherwise) has already been established. - * This method may NOT be called if a dialog has yet to be established. - * @internal - */ - protected generateResponseOfferAnswerInDialog(options: { - sessionDescriptionHandlerOptions?: SessionDescriptionHandlerOptions; - sessionDescriptionHandlerModifiers?: Array; - }): Promise; - /** - * Get local offer. - * @internal - */ - protected getOffer(options: { - sessionDescriptionHandlerOptions?: SessionDescriptionHandlerOptions; - sessionDescriptionHandlerModifiers?: Array; - }): Promise; - /** - * Rollback local/remote offer. - * @internal - */ - protected rollbackOffer(): Promise; - /** - * Set remote answer. - * @internal - */ - protected setAnswer(answer: Body, options: { - sessionDescriptionHandlerOptions?: SessionDescriptionHandlerOptions; - sessionDescriptionHandlerModifiers?: Array; - }): Promise; - /** - * Set remote offer and get local answer. - * @internal - */ - protected setOfferAndGetAnswer(offer: Body, options: { - sessionDescriptionHandlerOptions?: SessionDescriptionHandlerOptions; - sessionDescriptionHandlerModifiers?: Array; - }): Promise; - /** - * SDH for confirmed dialog. - * @internal - */ - protected setSessionDescriptionHandler(sdh: SessionDescriptionHandler): void; - /** - * SDH for confirmed dialog. - * @internal - */ - protected setupSessionDescriptionHandler(): SessionDescriptionHandler; - /** - * Transition session state. - * @internal - */ - protected stateTransition(newState: SessionState): void; -} -//# sourceMappingURL=session.d.ts.map \ No newline at end of file diff --git a/lib/api/session.d.ts.map b/lib/api/session.d.ts.map deleted file mode 100644 index dd034e265..000000000 --- a/lib/api/session.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../../src/api/session.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAEtC,OAAO,EAAE,CAAC,EAAE,MAAM,cAAc,CAAC;AACjC,OAAO,EACL,kCAAkC,EAClC,IAAI,EAGJ,kBAAkB,EAClB,kBAAkB,EAClB,mBAAmB,EACnB,qBAAqB,EACrB,qBAAqB,EACrB,oBAAoB,EACpB,oBAAoB,EACpB,sBAAsB,EACtB,uBAAuB,EACvB,MAAM,EACN,cAAc,EACd,kBAAkB,EAClB,qBAAqB,EAErB,uBAAuB,EACvB,sBAAsB,EACtB,cAAc,EACd,OAAO,IAAI,aAAa,EAGzB,MAAM,SAAS,CAAC;AAEjB,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAItD,OAAO,EAAE,OAAO,EAAe,MAAM,WAAW,CAAC;AAEjD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAGpC,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AACtC,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,EACL,kBAAkB,EAClB,yBAAyB,EACzB,iCAAiC,EACjC,gCAAgC,EACjC,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,gCAAgC,EAAE,MAAM,uCAAuC,CAAC;AACzF,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAChE,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC;;;GAGG;AACH,8BAAsB,OAAQ,SAAQ,YAAY;IAEhD,gBAAgB;IAChB,gBAAuB,CAAC,uBAAiB;IAEzC;;;OAGG;IACI,IAAI,EAAE,GAAG,GAAG,SAAS,CAAC;IAE7B;;;OAGG;IACI,QAAQ,EAAE,eAAe,GAAG,SAAS,CAAC;IAE7C;;OAEG;IACI,MAAM,EAAE,aAAa,GAAG,SAAS,CAAC;IAGzC,gBAAgB;IACT,IAAI,cAAuB;IAClC,gBAAgB;IACT,SAAS,EAAE,SAAS,CAAC;IAC5B,gBAAgB;IACT,MAAM,EAAE,MAAM,CAAC;IACtB,gBAAgB;IACT,MAAM,SAAY;IACzB,gBAAgB;IAChB,SAAgB,IAAI,EAAE,kBAAkB,GAAG,MAAM,GAAG,SAAS,CAAC;IAC9D,gBAAgB;IAChB,SAAgB,aAAa,EAAE,cAAc,CAAC;IAC9C,gBAAgB;IAChB,SAAgB,cAAc,EAAE,cAAc,CAAC;IAK/C,gBAAgB;IACT,gBAAgB,EAAE,cAAc,GAAG,SAAS,CAAC;IACpD,gBAAgB;IACT,WAAW,EAAE,MAAM,GAAG,SAAS,CAAC;IAGvC,gBAAgB;IACT,EAAE,EAAE,MAAM,GAAG,SAAS,CAAC;IAC9B,gBAAgB;IACT,OAAO,EAAE,MAAM,GAAG,SAAS,CAAC;IACnC,uBAAuB;IACvB,gBAAgB;IACT,OAAO,EAAE,IAAI,GAAG,SAAS,CAAC;IACjC,gBAAgB;IACT,SAAS,UAAS;IACzB,gBAAgB;IACT,QAAQ,EAAE,OAAO,GAAG,SAAS,CAAC;IACrC,gBAAgB;IACT,QAAQ,EAAE,QAAQ,GAAG,SAAS,CAAC;IACtC,gBAAgB;IACT,QAAQ,EAAE,OAAO,GAAG,SAAS,CAAC;IACrC,qBAAqB;IACrB,gBAAgB;IACT,SAAS,EAAE,IAAI,GAAG,SAAS,CAAC;IACnC,iCAAiC;IACjC,gBAAgB;IACT,MAAM,EAAE,aAAa,CAA8B;IAE1D,mDAAmD;IACnD,gBAAgB;IACT,QAAQ,EAAE,OAAO,CAAS;IAEjC,gBAAgB;IAChB,SAAS,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IACvC,gBAAgB;IAChB,SAAS,CAAC,aAAa,EAAE,CAAC,CAAC,GAAG,IAAI,EAAE,KAAK,CAAC,GAAG,CAAC,KAAK,IAAI,CAAC,CAAC;IACzD,gBAAgB;IAChB,SAAS,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,CAAC;IACtC,gBAAgB;IAChB,SAAS,CAAC,MAAM,EAAE,CAAC,CAAC,OAAO,EAAE,sBAAsB,KAAK,IAAI,CAAC,GAAG,SAAS,CAAC;IAC1E,gBAAgB;IAChB,SAAS,CAAC,aAAa,EAAE,GAAG,CAAC;IAC7B,gBAAgB;IAChB,SAAS,CAAC,MAAM,cAA2B;IAC3C,gBAAgB;IAChB,SAAS,CAAC,UAAU,EAAE,MAAM,GAAG,SAAS,CAAC;IACzC,gBAAgB;IAChB,SAAS,CAAC,UAAU,EAAE,MAAM,GAAG,SAAS,CAAC;IACzC,gBAAgB;IAChB,SAAS,CAAC,kCAAkC,EAAE,KAAK,CAAC,iCAAiC,CAAC,GAAG,SAAS,CAAC;IACnG,gBAAgB;IAChB,SAAS,CAAC,gCAAgC,EAAE,gCAAgC,GAAG,SAAS,CAAC;IACzF,gBAAgB;IAChB,SAAS,CAAC,YAAY,EAAE,GAAG,CAAa;IACxC,gBAAgB;IAChB,SAAS,CAAC,iBAAiB,EAAE,GAAG,CAAa;IAE7C,OAAO,CAAC,0BAA0B,CAAwC;IAC1E,OAAO,CAAC,MAAM,CAAsC;IACpD,OAAO,CAAC,kBAAkB,CAAsB;IAEhD,OAAO,CAAC,eAAe,CAAkB;IACzC,OAAO,CAAC,KAAK,CAAkB;IAE/B;;;;OAIG;IACH,SAAS,aAAa,SAAS,EAAE,SAAS,EAAE,OAAO,GAAE,cAAmB;IAYxE;;;OAGG;IACI,EAAE,CACP,KAAK,EAAE,mCAAmC,EAAE,QAAQ,EAAE,CAAC,yBAAyB,EAAE,yBAAyB,KAAK,IAAI,GACnH,IAAI;IACP;;;OAGG;IACI,EAAE,CACP,KAAK,EACH,iBAAiB,GACjB,eAAe,GACf,eAAe,GACf,sBAAsB,GACtB,sBAAsB,GACtB,sBAAsB,GACtB,kBAAkB,GAClB,gBAAgB,EAClB,QAAQ,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,IAAI,GACnC,IAAI;IACP;;;OAGG;IACI,EAAE,CACP,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,sBAAsB,KAAK,IAAI,GACvF,IAAI;IACP;;;OAGG;IACI,EAAE,CACP,KAAK,EAAE,WAAW,GAAG,QAAQ,EAAI,QAAQ,EAAE,CAAC,OAAO,EAAE,sBAAsB,KAAK,IAAI,GACnF,IAAI;IACP;;;OAGG;IACI,EAAE,CACP,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,OAAO,EAAE,sBAAsB,GAAG,sBAAsB,KAAK,IAAI,GACzF,IAAI;IACP;;;OAGG;IACI,EAAE,CACP,KAAK,EAAE,YAAY,EAAE,QAAQ,EAAE,CAAC,OAAO,EAAE;QAAE,OAAO,EAAE,sBAAsB,CAAA;KAAE,KAAK,IAAI,GACpF,IAAI;IACP;;;OAGG;IACI,EAAE,CACP,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,CAAC,QAAQ,EAAE,uBAAuB,GAAG,MAAM,EAAE,YAAY,CAAC,EAAE,GAAG,KAAK,IAAI,GACpG,IAAI;IACP;;;OAGG;IACI,EAAE,CACP,KAAK,EAAE,QAAQ,GAAG,UAAU,EAC5B,QAAQ,EAAE,CAAC,QAAQ,CAAC,EAAE,sBAAsB,GAAG,uBAAuB,GAAG,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,KAAK,IAAI,GACvG,IAAI;IACP;;;OAGG;IACI,EAAE,CACP,KAAK,EAAE,YAAY,EAAE,QAAQ,EAAE,CAAC,QAAQ,CAAC,EAAE,sBAAsB,GAAG,uBAAuB,EAAE,KAAK,CAAC,EAAE,MAAM,KAAK,IAAI,GACnH,IAAI;IACP;;;OAGG;IACI,EAAE,CAAC,KAAK,EAAE,oBAAoB,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,GAAG,IAAI;IAC9E;;;OAGG;IACI,EAAE,CAAC,KAAK,EAAE,YAAY,GAAG,kBAAkB,GAAG,eAAe,EAAE,QAAQ,EAAE,MAAM,IAAI,GAAG,IAAI;IASjG;;;OAGG;IACI,IAAI,CACT,KAAK,EAAE,mCAAmC,EAAE,yBAAyB,EAAE,yBAAyB,GAC/F,OAAO;IACV;;;OAGG;IACI,IAAI,CACT,KAAK,EACH,iBAAiB,GACjB,eAAe,GACf,sBAAsB,GACtB,sBAAsB,GACtB,sBAAsB,GACtB,kBAAkB,GAClB,gBAAgB,EAClB,OAAO,EAAE,OAAO,GAAG,OAAO;IAC5B;;;OAGG;IACI,IAAI,CACT,KAAK,EAAE,UAAU,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,sBAAsB,GACnE,OAAO;IACV;;;OAGG;IACI,IAAI,CACT,KAAK,EAAE,WAAW,GAAG,QAAQ,EAAE,OAAO,EAAE,sBAAsB,GAC7D,OAAO;IACV;;;OAGG;IACI,IAAI,CACT,KAAK,EAAE,QAAQ,GAAG,OAAO,GAAG,QAAQ,EAAE,OAAO,EAAE,sBAAsB,GACpE,OAAO;IACV;;;OAGG;IACI,IAAI,CACT,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,sBAAsB,GAAG,sBAAsB,GACrE,OAAO;IACV;;;OAGG;IACI,IAAI,CACT,KAAK,EAAE,YAAY,EAAE,OAAO,EAAE;QAAE,OAAO,EAAE,sBAAsB,CAAA;KAAE,GAChE,OAAO;IACV;;;OAGG;IACI,IAAI,CACT,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,uBAAuB,GAAG,MAAM,EAAE,YAAY,CAAC,EAAE,GAAG,GAChF,OAAO;IACV;;;OAGG;IACI,IAAI,CACT,KAAK,EAAE,QAAQ,GAAG,UAAU,EAC5B,QAAQ,CAAC,EAAE,sBAAsB,GAAG,uBAAuB,GAAG,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,GACnF,OAAO;IACV;;;OAGG;IACI,IAAI,CACT,KAAK,EAAE,YAAY,EAAE,QAAQ,CAAC,EAAE,sBAAsB,GAAG,uBAAuB,EAAE,KAAK,CAAC,EAAE,MAAM,GAC/F,OAAO;IACV;;;OAGG;IACI,IAAI,CAAC,KAAK,EAAE,oBAAoB,EAAE,KAAK,EAAE,KAAK,GAAG,OAAO;IAC/D;;;OAGG;IACI,IAAI,CAAC,KAAK,EAAE,YAAY,GAAG,kBAAkB,GAAG,eAAe,GAAG,OAAO;IAShF;;OAEG;aACC,yBAAyB,EAAI,yBAAyB,GAAG,SAAS;IAItE;;OAEG;aACC,gCAAgC,EAAI,gCAAgC;IAIxE;;OAEG;aACC,KAAK,EAAI,YAAY;IAIzB;;OAEG;aACC,WAAW,EAAI,OAAO,CAAC,YAAY,CAAC;IAIxC;;;OAGG;IACI,MAAM,CAAC,OAAO,GAAE,oBAAyB,GAAG,OAAO,CAAC,qBAAqB,CAAC;IAyKjF;;;;OAIG;IACI,UAAU,IAAI,IAAI;IAKzB;;;;OAIG;IACI,OAAO,CAAC,OAAO,EAAE,kBAAkB,GAAG,IAAI;IAMjD;;;;;OAKG;IACI,GAAG,CAAC,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,kBAAkB,CAAC;IAiDrG;;;;;OAKG;IACI,IAAI,CAAC,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,kBAAkB,CAAC;IAQtG;;;;;OAKG;IACI,KAAK,CACV,QAAQ,EAAE,QAAQ,EAClB,QAAQ,CAAC,EAAE,uBAAuB,EAClC,OAAO,CAAC,EAAE,cAAc,GACvB,OAAO,CAAC,kBAAkB,CAAC;IAU9B;;OAEG;IACI,KAAK,IAAI,IAAI;IAmCpB;;OAEG;IACI,gBAAgB,IAAI,IAAI;IAS/B;;OAEG;IACI,gBAAgB,IAAI,IAAI;IAM/B;;;;;;;;OAQG;IACH,SAAS,CAAC,SAAS,CACjB,QAAQ,EAAE,kCAAkC,EAC5C,UAAU,CAAC,EAAE,MAAM,EACnB,YAAY,CAAC,EAAE,MAAM,GACpB,IAAI;IAUP;;;OAGG;IACH,SAAS,CAAC,YAAY,CAAC,OAAO,EAAE,kBAAkB,GAAG,IAAI;IAiFzD;;;OAGG;IACH,SAAS,CAAC,YAAY,CAAC,OAAO,EAAE,kBAAkB,GAAG,IAAI;IAczD;;;OAGG;IACH,SAAS,CAAC,aAAa,CAAC,OAAO,EAAE,mBAAmB,GAAG,IAAI;IAe3D;;;OAGG;IACH,SAAS,CAAC,eAAe,CAAC,OAAO,EAAE,qBAAqB,GAAG,IAAI;IAyF/D;;;OAGG;IACH,SAAS,CAAC,eAAe,CAAC,OAAO,EAAE,qBAAqB,GAAG,IAAI;IAsC/D;;;OAGG;IACH,SAAS,CAAC,cAAc,CAAC,OAAO,EAAE,oBAAoB,GAAG,IAAI;IAU7D;;;OAGG;IACH,SAAS,CAAC,cAAc,CAAC,OAAO,EAAE,oBAAoB,GAAG,IAAI;IA4C7D;;;OAGG;IACH,SAAS,CAAC,UAAU,CAAC,OAAO,EAAE,sBAAsB,GAAG,IAAI;IAI3D;;;OAGG;IACH,SAAS,CAAC,MAAM,CAAC,QAAQ,EAAE,uBAAuB,GAAG,sBAAsB,GAAG,SAAS,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI;IAO7G;;;OAGG;IACH,SAAS,CAAC,QAAQ,CAAC,QAAQ,EAAE,uBAAuB,GAAG,sBAAsB,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI;IAInG;;;OAGG;IACH,SAAS,CAAC,UAAU,CAAC,OAAO,CAAC,EAAE,uBAAuB,GAAG,sBAAsB,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI;IAWtG;;;;;;OAMG;IACH,SAAS,CAAC,2BAA2B,CACnC,OAAO,EAAE,qBAAqB,EAC9B,OAAO,EAAE;QACP,gCAAgC,CAAC,EAAE,gCAAgC,CAAC;QACpE,kCAAkC,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,CAAA;KAC9E,GACA,OAAO,CAAC,IAAI,GAAG,SAAS,CAAC;IAY5B;;;;;OAKG;IACH,SAAS,CAAC,mCAAmC,CAC3C,OAAO,EAAE;QACP,gCAAgC,CAAC,EAAE,gCAAgC,CAAC;QACpE,kCAAkC,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,CAAA;KAC9E,GACA,OAAO,CAAC,IAAI,GAAG,SAAS,CAAC;IAuC5B;;;OAGG;IACH,SAAS,CAAC,QAAQ,CAAC,OAAO,EAAE;QAC1B,gCAAgC,CAAC,EAAE,gCAAgC,CAAC;QACpE,kCAAkC,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,CAAA;KAC9E,GAAG,OAAO,CAAC,IAAI,CAAC;IAWjB;;;OAGG;IACH,SAAS,CAAC,aAAa,IAAI,OAAO,CAAC,IAAI,CAAC;IAWxC;;;OAGG;IACH,SAAS,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE;QACzC,gCAAgC,CAAC,EAAE,gCAAgC,CAAC;QACpE,kCAAkC,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,CAAA;KAC9E,GAAG,OAAO,CAAC,IAAI,CAAC;IAajB;;;OAGG;IACH,SAAS,CAAC,oBAAoB,CAAC,KAAK,EAAE,IAAI,EAAE,OAAO,EAAE;QACnD,gCAAgC,CAAC,EAAE,gCAAgC,CAAC;QACpE,kCAAkC,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,CAAA;KAC9E,GAAG,OAAO,CAAC,IAAI,CAAC;IAejB;;;OAGG;IACH,SAAS,CAAC,4BAA4B,CAAC,GAAG,EAAE,yBAAyB,GAAG,IAAI;IAO5E;;;OAGG;IACH,SAAS,CAAC,8BAA8B,IAAI,yBAAyB;IAUrE;;;OAGG;IACH,SAAS,CAAC,eAAe,CAAC,QAAQ,EAAE,YAAY,GAAG,IAAI;CA0DxD"} \ No newline at end of file diff --git a/lib/api/session.js b/lib/api/session.js deleted file mode 100644 index c50d826e7..000000000 --- a/lib/api/session.js +++ /dev/null @@ -1,996 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var events_1 = require("events"); -var Constants_1 = require("../Constants"); -var core_1 = require("../core"); -var allowed_methods_1 = require("../core/user-agent-core/allowed-methods"); -var Enums_1 = require("../Enums"); -var Exceptions_1 = require("../Exceptions"); -var Utils_1 = require("../Utils"); -var emitter_1 = require("./emitter"); -var info_1 = require("./info"); -var notification_1 = require("./notification"); -var referral_1 = require("./referral"); -var session_state_1 = require("./session-state"); -/** - * A session provides real time communication between one or more participants. - * @public - */ -var Session = /** @class */ (function (_super) { - tslib_1.__extends(Session, _super); - /** - * Constructor. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @internal - */ - function Session(userAgent, options) { - if (options === void 0) { options = {}; } - var _this = _super.call(this) || this; - // Property overlap with ClientContext & ServerContext Interfaces - /** @internal */ - _this.type = Enums_1.TypeStrings.Session; - /** @internal */ - _this.method = Constants_1.C.INVITE; - /** @internal */ - _this.localHold = false; - /** DEPRECATED: Session status */ - /** @internal */ - _this.status = Enums_1.SessionStatus.STATUS_NULL; - /** True if an error caused session termination. */ - /** @internal */ - _this.isFailed = false; - /** @internal */ - _this.rel100 = Constants_1.C.supported.UNSUPPORTED; - /** @internal */ - _this.expiresTimer = undefined; - /** @internal */ - _this.userNoAnswerTimer = undefined; - _this._state = session_state_1.SessionState.Initial; - _this._stateEventEmitter = new events_1.EventEmitter(); - _this.pendingReinvite = false; - _this.tones = undefined; - _this.userAgent = userAgent; - _this.delegate = options.delegate; - _this.logger = userAgent.getLogger("sip.session"); - _this.errorListener = _this.onTransportError.bind(_this); - if (userAgent.transport) { - userAgent.transport.on("transportError", _this.errorListener); - } - return _this; - } - /** - * @deprecated Legacy state transition. - * @internal - */ - Session.prototype.on = function (name, callback) { - return _super.prototype.on.call(this, name, callback); - }; - /** - * @deprecated Legacy state transition. - * @internal - */ - Session.prototype.emit = function (event) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - return _super.prototype.emit.apply(this, [event].concat(args)); - }; - Object.defineProperty(Session.prototype, "sessionDescriptionHandler", { - /** - * Session description handler. - */ - get: function () { - return this._sessionDescriptionHandler; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Session.prototype, "sessionDescriptionHandlerFactory", { - /** - * Session description handler factory. - */ - get: function () { - return this.userAgent.configuration.sessionDescriptionHandlerFactory; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Session.prototype, "state", { - /** - * Session state. - */ - get: function () { - return this._state; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Session.prototype, "stateChange", { - /** - * Session state change emitter. - */ - get: function () { - return emitter_1.makeEmitter(this._stateEventEmitter); - }, - enumerable: true, - configurable: true - }); - /** - * Renegotiate the session. Sends a re-INVITE. - * @param options - Options bucket. - */ - Session.prototype.invite = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - this.logger.log("Session.invite"); - if (this.state !== session_state_1.SessionState.Established) { - return Promise.reject(new Error("Invalid session state " + this.state)); - } - if (this.pendingReinvite) { - return Promise.reject(new Error("Reinvite in progress. Please wait until complete, then try again.")); - } - if (!this._sessionDescriptionHandler) { - throw new Error("Session description handler undefined."); - } - this.pendingReinvite = true; - var delegate = { - onAccept: function (response) { - // A re-INVITE transaction has an offer/answer [RFC3264] exchange - // associated with it. The UAC (User Agent Client) generating a given - // re-INVITE can act as the offerer or as the answerer. A UAC willing - // to act as the offerer includes an offer in the re-INVITE. The UAS - // (User Agent Server) then provides an answer in a response to the - // re-INVITE. A UAC willing to act as answerer does not include an - // offer in the re-INVITE. The UAS then provides an offer in a response - // to the re-INVITE becoming, thus, the offerer. - // https://tools.ietf.org/html/rfc6141#section-1 - var body = core_1.getBody(response.message); - if (!body) { - // No way to recover, so terminate session and mark as failed. - _this.logger.error("Received 2xx response to re-INVITE without a session description"); - _this.ackAndBye(response, 400, "Missing session description"); - _this.stateTransition(session_state_1.SessionState.Terminated); - _this.isFailed = true; - _this.pendingReinvite = false; - return; - } - if (options.withoutSdp) { - // INVITE without SDP - set remote offer and send an answer in the ACK - // FIXME: SDH options & SDH modifiers options are applied somewhat ambiguously - // This behavior was ported from legacy code and the issue punted down the road. - var answerOptions = { - sessionDescriptionHandlerOptions: options.sessionDescriptionHandlerOptions, - sessionDescriptionHandlerModifiers: options.sessionDescriptionHandlerModifiers - }; - _this.setOfferAndGetAnswer(body, answerOptions) - .then(function (answerBody) { - var request = response.ack({ body: answerBody }); - }) - .catch(function (error) { - // No way to recover, so terminate session and mark as failed. - _this.logger.error(error.message); - _this.logger.error("Failed to handle offer in 2xx response to re-INVITE"); - _this.ackAndBye(response, 488, "Bad Media Description"); - _this.stateTransition(session_state_1.SessionState.Terminated); - _this.isFailed = true; - }) - .then(function () { - _this.pendingReinvite = false; - if (options.requestDelegate && options.requestDelegate.onAccept) { - options.requestDelegate.onAccept(response); - } - }); - } - else { - // INVITE with SDP - set remote answer and send an ACK - // FIXME: SDH options & SDH modifiers options are applied somewhat ambiguously - // This behavior was ported from legacy code and the issue punted down the road. - var answerOptions = { - sessionDescriptionHandlerOptions: _this.sessionDescriptionHandlerOptions, - sessionDescriptionHandlerModifiers: _this.sessionDescriptionHandlerModifiers - }; - _this.setAnswer(body, answerOptions) - .then(function () { - var request = response.ack(); - }) - .catch(function (error) { - // No way to recover, so terminate session and mark as failed. - _this.logger.error(error.message); - _this.logger.error("Failed to handle answer in 2xx response to re-INVITE"); - _this.ackAndBye(response, 488, "Bad Media Description"); - _this.stateTransition(session_state_1.SessionState.Terminated); - _this.isFailed = true; - }) - .then(function () { - _this.pendingReinvite = false; - if (options.requestDelegate && options.requestDelegate.onAccept) { - options.requestDelegate.onAccept(response); - } - }); - } - }, - onProgress: function (response) { - return; - }, - onRedirect: function (response) { - return; - }, - onReject: function (response) { - _this.logger.warn("Received a non-2xx response to re-INVITE"); - _this.pendingReinvite = false; - if (options.withoutSdp) { - if (options.requestDelegate && options.requestDelegate.onReject) { - options.requestDelegate.onReject(response); - } - } - else { - _this.rollbackOffer() - .catch(function (error) { - // No way to recover, so terminate session and mark as failed. - _this.logger.error(error.message); - _this.logger.error("Failed to rollback offer on non-2xx response to re-INVITE"); - // Note that the ACK was already sent by the transaction, so just need to send BYE - if (!_this.dialog) { - throw new Error("Dialog undefined."); - } - var extraHeaders = []; - extraHeaders.push("Reason: " + Utils_1.Utils.getReasonHeaderValue(500, "Internal Server Error")); - var outgoingByeRequest = _this.dialog.bye(undefined, { extraHeaders: extraHeaders }); - _this.stateTransition(session_state_1.SessionState.Terminated); - _this.isFailed = true; - }) - .then(function () { - if (options.requestDelegate && options.requestDelegate.onReject) { - options.requestDelegate.onReject(response); - } - }); - } - }, - onTrying: function (response) { - return; - } - }; - var requestOptions = options.requestOptions || {}; - requestOptions.extraHeaders = (requestOptions.extraHeaders || []).slice(); - requestOptions.extraHeaders.push("Allow: " + allowed_methods_1.AllowedMethods.toString()); - requestOptions.extraHeaders.push("Contact: " + this.contact); - // Just send an INVITE with no sdp... - if (options.withoutSdp) { - if (!this.dialog) { - this.pendingReinvite = false; - return Promise.reject(new Error("Dialog undefined.")); - } - return Promise.resolve(this.dialog.invite(delegate, requestOptions)); - } - // Get an offer and send it in an INVITE - // FIXME: SDH options & SDH modifiers options are applied somewhat ambiguously - // This behavior was ported from legacy code and the issue punted down the road. - var offerOptions = { - sessionDescriptionHandlerOptions: options.sessionDescriptionHandlerOptions, - sessionDescriptionHandlerModifiers: options.sessionDescriptionHandlerModifiers - }; - return this.getOffer(offerOptions) - .then(function (offerBody) { - if (!_this.dialog) { - _this.pendingReinvite = false; - throw new Error("Dialog undefined."); - } - requestOptions.body = offerBody; - return _this.dialog.invite(delegate, requestOptions); - }) - .catch(function (error) { - _this.logger.error(error.message); - _this.logger.error("Failed to send re-INVITE"); - _this.pendingReinvite = false; - throw error; - }); - }; - /** - * TODO: This is awkward. - * Helper function - * @internal - */ - Session.prototype.byePending = function () { - this.stateTransition(session_state_1.SessionState.Terminating); - this.terminated(); - }; - /** - * TODO: This is awkward. - * Helper function - * @internal - */ - Session.prototype.byeSent = function (request) { - this.emit("bye", request.message); - this.stateTransition(session_state_1.SessionState.Terminated); - this.terminated(); - }; - /** - * Send BYE. - * @param delegate - Request delegate. - * @param options - Request options bucket. - * @internal - */ - Session.prototype.bye = function (delegate, options) { - var _this = this; - // Using core session dialog - if (!this.dialog) { - return Promise.reject(new Error("Session dialog undefined.")); - } - var dialog = this.dialog; - // The caller's UA MAY send a BYE for either confirmed or early dialogs, - // and the callee's UA MAY send a BYE on confirmed dialogs, but MUST NOT - // send a BYE on early dialogs. However, the callee's UA MUST NOT send a - // BYE on a confirmed dialog until it has received an ACK for its 2xx - // response or until the server transaction times out. - // https://tools.ietf.org/html/rfc3261#section-15 - switch (dialog.sessionState) { - case core_1.SessionState.Initial: - throw new Error("Invalid dialog state " + dialog.sessionState); - case core_1.SessionState.Early: // Implementation choice - not sending BYE for early dialogs. - throw new Error("Invalid dialog state " + dialog.sessionState); - case core_1.SessionState.AckWait: { // This state only occurs if we are the callee. - this.byePending(); - return new Promise(function (resolve, reject) { - dialog.delegate = { - // When ACK shows up, say BYE. - onAck: function () { - var request = dialog.bye(delegate, options); - _this.byeSent(request); - resolve(request); - }, - // Or the server transaction times out before the ACK arrives. - onAckTimeout: function () { - var request = dialog.bye(delegate, options); - _this.byeSent(request); - resolve(request); - } - }; - }); - } - case core_1.SessionState.Confirmed: { - var request = dialog.bye(delegate, options); - this.byeSent(request); - return Promise.resolve(request); - } - case core_1.SessionState.Terminated: - throw new Error("Invalid dialog state " + dialog.sessionState); - default: - throw new Error("Unrecognized state."); - } - }; - /** - * Send INFO. - * @param delegate - Request delegate. - * @param options - Request options bucket. - * @internal - */ - Session.prototype.info = function (delegate, options) { - // Using core session dialog - if (!this.dialog) { - return Promise.reject(new Error("Session dialog undefined.")); - } - return Promise.resolve(this.dialog.info(delegate, options)); - }; - /** - * Send REFER. - * @param delegate - Request delegate. - * @param options - Request options bucket. - * @internal - */ - Session.prototype.refer = function (referrer, delegate, options) { - // Using core session dialog - if (!this.dialog) { - return Promise.reject(new Error("Session dialog undefined.")); - } - // If the session has a referrer, it will receive any in-dialog NOTIFY requests. - this.referrer = referrer; - return Promise.resolve(this.dialog.refer(delegate, options)); - }; - /** - * @internal - */ - Session.prototype.close = function () { - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return; - } - this.logger.log("closing INVITE session " + this.id); - // 1st Step. Terminate media. - if (this._sessionDescriptionHandler) { - this._sessionDescriptionHandler.close(); - } - // 2nd Step. Terminate signaling. - // Clear session timers - if (this.expiresTimer) { - clearTimeout(this.expiresTimer); - } - if (this.userNoAnswerTimer) { - clearTimeout(this.userNoAnswerTimer); - } - this.status = Enums_1.SessionStatus.STATUS_TERMINATED; - if (this.userAgent.transport) { - this.userAgent.transport.removeListener("transportError", this.errorListener); - } - if (!this.id) { - throw new Error("Session id undefined."); - } - delete this.userAgent.sessions[this.id]; - return; - }; - /** - * @internal - */ - Session.prototype.onRequestTimeout = function () { - if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { - this.terminated(undefined, Constants_1.C.causes.REQUEST_TIMEOUT); - } - else if (this.status !== Enums_1.SessionStatus.STATUS_TERMINATED) { - this.failed(undefined, Constants_1.C.causes.REQUEST_TIMEOUT); - this.terminated(undefined, Constants_1.C.causes.REQUEST_TIMEOUT); - } - }; - /** - * @internal - */ - Session.prototype.onTransportError = function () { - if (this.status !== Enums_1.SessionStatus.STATUS_CONFIRMED && this.status !== Enums_1.SessionStatus.STATUS_TERMINATED) { - this.failed(undefined, Constants_1.C.causes.CONNECTION_ERROR); - } - }; - /** - * Send ACK and then BYE. There are unrecoverable errors which can occur - * while handling dialog forming and in-dialog INVITE responses and when - * they occur we ACK the response and terminate the session. - * @param inviteResponse - The response causing the error. - * @param statusCode - Status code for he reason phrase. - * @param reasonPhrase - Reason phrase for the BYE. - * @internal - */ - Session.prototype.ackAndBye = function (response, statusCode, reasonPhrase) { - var outgoingAckRequest = response.ack(); - var extraHeaders = []; - if (statusCode) { - extraHeaders.push("Reason: " + Utils_1.Utils.getReasonHeaderValue(statusCode, reasonPhrase)); - } - var outgoingByeRequest = response.session.bye(undefined, { extraHeaders: extraHeaders }); - this.emit("bye", outgoingByeRequest.message); - }; - /** - * Handle in dialog ACK request. - * @internal - */ - Session.prototype.onAckRequest = function (request) { - var _this = this; - this.logger.log("Session.onAckRequest"); - if (this.state !== session_state_1.SessionState.Initial && - this.state !== session_state_1.SessionState.Establishing && - this.state !== session_state_1.SessionState.Established && - this.state !== session_state_1.SessionState.Terminating) { - this.logger.error("ACK received while in state " + this.state + ", dropping request"); - return; - } - // FIXME: Review is this ever true? We're "Established" when dialog created in accept(). - if (this.state === session_state_1.SessionState.Initial || this.state === session_state_1.SessionState.Establishing) { - this.stateTransition(session_state_1.SessionState.Established); - } - var dialog = this.dialog; - if (!dialog) { - throw new Error("Dialog undefined."); - } - // Helper function. - var confirmSession = function () { - _this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; - _this.emit("confirmed", request.message); - }; - // If the ACK doesn't have an offer/answer, nothing to be done. - var body = core_1.getBody(request.message); - if (!body) { - confirmSession(); - return; - } - if (body.contentDisposition === "render") { - this.renderbody = body.content; - this.rendertype = body.contentType; - confirmSession(); - return; - } - if (body.contentDisposition !== "session") { - confirmSession(); - return; - } - var options = { - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers - }; - switch (dialog.signalingState) { - case core_1.SignalingState.Initial: - // State should never be reached as first reliable response must have answer/offer. - throw new Error("Invalid signaling state " + dialog.signalingState + "."); - case core_1.SignalingState.Stable: - // Receved answer. - this.setAnswer(body, options) - .then(function () { return confirmSession(); }) - .catch(function (error) { - // FIXME: TODO - need to do something to handle this error - _this.logger.error(error); - var extraHeaders = ["Reason: " + Utils_1.Utils.getReasonHeaderValue(488, "Bad Media Description")]; - _this.bye(undefined, { extraHeaders: extraHeaders }); - _this.failed(request.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - _this.terminated(request.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); - throw error; - }); - return; - case core_1.SignalingState.HaveLocalOffer: - // State should never be reached as local offer would be answered by this ACK - throw new Error("Invalid signaling state " + dialog.signalingState + "."); - case core_1.SignalingState.HaveRemoteOffer: - // State should never be reached as remote offer would be answered in first reliable response. - throw new Error("Invalid signaling state " + dialog.signalingState + "."); - case core_1.SignalingState.Closed: - throw new Error("Invalid signaling state " + dialog.signalingState + "."); - default: - throw new Error("Invalid signaling state " + dialog.signalingState + "."); - } - }; - /** - * Handle in dialog BYE request. - * @internal - */ - Session.prototype.onByeRequest = function (request) { - this.logger.log("Session.onByeRequest"); - if (this.state !== session_state_1.SessionState.Established) { - this.logger.error("BYE received while in state " + this.state + ", dropping request"); - return; - } - request.accept(); - this.stateTransition(session_state_1.SessionState.Terminated); - if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { - this.emit("bye", request.message); - this.terminated(request.message, Constants_1.C.BYE); - } - }; - /** - * Handle in dialog INFO request. - * @internal - */ - Session.prototype.onInfoRequest = function (request) { - this.logger.log("Session.onInfoRequest"); - if (this.state !== session_state_1.SessionState.Established) { - this.logger.error("INFO received while in state " + this.state + ", dropping request"); - return; - } - if (this.delegate && this.delegate.onInfo) { - var info = new info_1.Info(request); - this.delegate.onInfo(info); - } - else { - request.accept(); - } - }; - /** - * Handle in dialog INVITE request. - * @internal - */ - Session.prototype.onInviteRequest = function (request) { - var _this = this; - this.logger.log("Session.onInviteRequest"); - if (this.state !== session_state_1.SessionState.Established) { - this.logger.error("INVITE received while in state " + this.state + ", dropping request"); - return; - } - // TODO: would be nice to have core track and set the Contact header, - // but currently the session which is setting it is holding onto it. - var extraHeaders = ["Contact: " + this.contact]; - // Check testing hooks - if (this.delegate && this.delegate.onReinviteTest) { - var test = this.delegate.onReinviteTest(); - if (test === "acceptWithoutDescription") { - request.accept({ statusCode: 200, extraHeaders: extraHeaders }); - return; - } - if (test === "reject488") { - request.reject({ statusCode: 488 }); - return; - } - } - // Handle P-Asserted-Identity - if (request.message.hasHeader("P-Asserted-Identity")) { - var header = request.message.getHeader("P-Asserted-Identity"); - if (!header) { - throw new Error("Header undefined."); - } - this.assertedIdentity = core_1.Grammar.nameAddrHeaderParse(header); - } - // FIXME: SDH options & SDH modifiers options are applied somewhat ambiguously - // This behavior was ported from legacy code and the issue punted down the road. - var options = { - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers - }; - this.generateResponseOfferAnswerInDialog(options) - .then(function (body) { - var outgoingResponse = request.accept({ statusCode: 200, extraHeaders: extraHeaders, body: body }); - if (_this.delegate && _this.delegate.onInvite) { - _this.delegate.onInvite(request.message, outgoingResponse.message, 200); - } - }) - .catch(function (error) { - _this.logger.error(error.message); - _this.logger.error("Failed to handle to re-INVITE request"); - if (!_this.dialog) { - throw new Error("Dialog undefined."); - } - _this.logger.error(_this.dialog.signalingState); - // If we don't have a local/remote offer... - if (_this.dialog.signalingState === core_1.SignalingState.Stable) { - var outgoingResponse = request.reject({ statusCode: 488 }); // Not Acceptable Here - if (_this.delegate && _this.delegate.onInvite) { - _this.delegate.onInvite(request.message, outgoingResponse.message, 488); - } - return; - } - // Otherwise rollback - _this.rollbackOffer() - .then(function () { - var outgoingResponse = request.reject({ statusCode: 488 }); // Not Acceptable Here - if (_this.delegate && _this.delegate.onInvite) { - _this.delegate.onInvite(request.message, outgoingResponse.message, 488); - } - }) - .catch(function (errorRollback) { - // No way to recover, so terminate session and mark as failed. - _this.logger.error(errorRollback.message); - _this.logger.error("Failed to rollback offer on re-INVITE request"); - var outgoingResponse = request.reject({ statusCode: 488 }); // Not Acceptable Here - var extraHeadersBye = []; - extraHeadersBye.push("Reason: " + Utils_1.Utils.getReasonHeaderValue(500, "Internal Server Error")); - if (!_this.dialog) { - throw new Error("Dialog undefined."); - } - var outgoingByeRequest = _this.dialog.bye(undefined, { extraHeaders: extraHeaders }); - _this.stateTransition(session_state_1.SessionState.Terminated); - _this.isFailed = true; - if (_this.delegate && _this.delegate.onInvite) { - _this.delegate.onInvite(request.message, outgoingResponse.message, 488); - } - }); - }); - }; - /** - * Handle in dialog NOTIFY request. - * @internal - */ - Session.prototype.onNotifyRequest = function (request) { - this.logger.log("Session.onNotifyRequest"); - if (this.state !== session_state_1.SessionState.Established) { - this.logger.error("NOTIFY received while in state " + this.state + ", dropping request"); - return; - } - // DEPRECATED BEGIN - // ReferClientContext is deprecated - // if ( - // this.referContext && - // this.referContext.type === TypeStrings.ReferClientContext && - // incomingRequest.message.hasHeader("event") && - // /^refer(;.*)?$/.test(incomingRequest.message.getHeader("event") as string) - // ) { - // this.referContext.receiveNotify(incomingRequest); - // return; - // } - // DEPRECATED END - // If this a NOTIFY associated with the progress of a REFER, - // look to delegate handling to the associated Referrer. - if (this.referrer && this.referrer.delegate && this.referrer.delegate.onNotify) { - var notification = new notification_1.Notification(request); - this.referrer.delegate.onNotify(notification); - return; - } - // Otherwise accept the NOTIFY. - if (this.delegate && this.delegate.onNotify) { - var notification = new notification_1.Notification(request); - this.delegate.onNotify(notification); - } - else { - request.accept(); - } - this.emit("notify", request.message); - }; - /** - * Handle in dialog PRACK request. - * @internal - */ - Session.prototype.onPrackRequest = function (request) { - this.logger.log("Session.onPrackRequest"); - if (this.state !== session_state_1.SessionState.Established) { - this.logger.error("PRACK received while in state " + this.state + ", dropping request"); - return; - } - throw new Error("Unimplemented."); - }; - /** - * Handle in dialog REFER request. - * @internal - */ - Session.prototype.onReferRequest = function (request) { - var _this = this; - this.logger.log("Session.onReferRequest"); - if (this.state !== session_state_1.SessionState.Established) { - this.logger.error("REFER received while in state " + this.state + ", dropping request"); - return; - } - if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { - // RFC 3515 2.4.1 - if (!request.message.hasHeader("refer-to")) { - this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting."); - request.reject(); - return; - } - // DEPRECATED BEGIN - // // ReferServerContext is deprecated - // if (this.listeners("referRequested").length) { - // const referContext = new ReferServerContext(this.ua, incomingRequest, this.dialog); - // this.emit("referRequested", referContext); - // return; - // } - // DEPRECATED END - var referral_2 = new referral_1.Referral(request, this); - if (this.delegate && this.delegate.onRefer) { - this.delegate.onRefer(referral_2); - } - else { - this.logger.log("No delegate available to handle REFER, automatically accepting and following."); - referral_2 - .accept() - .then(function () { return referral_2 - .makeInviter(_this.passedOptions) - .invite(); }) - .catch(function (error) { - // FIXME: logging and eating error... - _this.logger.error(error.message); - }); - } - } - }; - /** - * @deprecated Legacy state transition. - * @internal - */ - Session.prototype.connecting = function (request) { - this.emit("connecting", { request: request }); - }; - /** - * @deprecated Legacy state transition. - * @internal - */ - Session.prototype.failed = function (response, cause) { - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return; - } - this.emit("failed", response, cause); - }; - /** - * @deprecated Legacy state transition. - * @internal - */ - Session.prototype.rejected = function (response, cause) { - this.emit("rejected", response, cause); - }; - /** - * @deprecated Legacy state transition. - * @internal - */ - Session.prototype.terminated = function (message, cause) { - if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { - return; - } - this.endTime = new Date(); - this.close(); - this.emit("terminated", message, cause); - }; - /** - * Generate an offer or answer for a response to an INVITE request. - * If a remote offer was provided in the request, set the remote - * description and get a local answer. If a remote offer was not - * provided, generates a local offer. - * @internal - */ - Session.prototype.generateResponseOfferAnswer = function (request, options) { - if (this.dialog) { - return this.generateResponseOfferAnswerInDialog(options); - } - var body = core_1.getBody(request.message); - if (!body || body.contentDisposition !== "session") { - return this.getOffer(options); - } - else { - return this.setOfferAndGetAnswer(body, options); - } - }; - /** - * Generate an offer or answer for a response to an INVITE request - * when a dialog (early or otherwise) has already been established. - * This method may NOT be called if a dialog has yet to be established. - * @internal - */ - Session.prototype.generateResponseOfferAnswerInDialog = function (options) { - if (!this.dialog) { - throw new Error("Dialog undefined."); - } - switch (this.dialog.signalingState) { - case core_1.SignalingState.Initial: - return this.getOffer(options); - case core_1.SignalingState.HaveLocalOffer: - // o Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - return Promise.resolve(undefined); - case core_1.SignalingState.HaveRemoteOffer: - if (!this.dialog.offer) { - throw new Error("Session offer undefined in signaling state " + this.dialog.signalingState + "."); - } - return this.setOfferAndGetAnswer(this.dialog.offer, options); - case core_1.SignalingState.Stable: - // o Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - if (this.state !== session_state_1.SessionState.Established) { - return Promise.resolve(undefined); - } - // In dialog INVITE without offer, get an offer for the response. - return this.getOffer(options); - case core_1.SignalingState.Closed: - throw new Error("Invalid signaling state " + this.dialog.signalingState + "."); - default: - throw new Error("Invalid signaling state " + this.dialog.signalingState + "."); - } - }; - /** - * Get local offer. - * @internal - */ - Session.prototype.getOffer = function (options) { - var sdh = this.setupSessionDescriptionHandler(); - var sdhOptions = options.sessionDescriptionHandlerOptions; - var sdhModifiers = options.sessionDescriptionHandlerModifiers; - return sdh.getDescription(sdhOptions, sdhModifiers) - .then(function (bodyAndContentType) { return Utils_1.Utils.fromBodyObj(bodyAndContentType); }) - .catch(function (error) { - throw (error instanceof Error ? error : new Error(error)); - }); - }; - /** - * Rollback local/remote offer. - * @internal - */ - Session.prototype.rollbackOffer = function () { - var sdh = this.setupSessionDescriptionHandler(); - if (!sdh.rollbackDescription) { - return Promise.resolve(); - } - return sdh.rollbackDescription() - .catch(function (error) { - throw (error instanceof Error ? error : new Error(error)); - }); - }; - /** - * Set remote answer. - * @internal - */ - Session.prototype.setAnswer = function (answer, options) { - var sdh = this.setupSessionDescriptionHandler(); - var sdhOptions = options.sessionDescriptionHandlerOptions; - var sdhModifiers = options.sessionDescriptionHandlerModifiers; - if (!sdh.hasDescription(answer.contentType)) { - return Promise.reject(new Exceptions_1.Exceptions.UnsupportedSessionDescriptionContentTypeError()); - } - return sdh.setDescription(answer.content, sdhOptions, sdhModifiers) - .catch(function (error) { - throw (error instanceof Error ? error : new Error(error)); - }); - }; - /** - * Set remote offer and get local answer. - * @internal - */ - Session.prototype.setOfferAndGetAnswer = function (offer, options) { - var sdh = this.setupSessionDescriptionHandler(); - var sdhOptions = options.sessionDescriptionHandlerOptions; - var sdhModifiers = options.sessionDescriptionHandlerModifiers; - if (!sdh.hasDescription(offer.contentType)) { - return Promise.reject(new Exceptions_1.Exceptions.UnsupportedSessionDescriptionContentTypeError()); - } - return sdh.setDescription(offer.content, sdhOptions, sdhModifiers) - .then(function () { return sdh.getDescription(sdhOptions, sdhModifiers); }) - .then(function (bodyAndContentType) { return Utils_1.Utils.fromBodyObj(bodyAndContentType); }) - .catch(function (error) { - throw (error instanceof Error ? error : new Error(error)); - }); - }; - /** - * SDH for confirmed dialog. - * @internal - */ - Session.prototype.setSessionDescriptionHandler = function (sdh) { - if (this._sessionDescriptionHandler) { - throw new Error("Sessionn description handler defined."); - } - this._sessionDescriptionHandler = sdh; - }; - /** - * SDH for confirmed dialog. - * @internal - */ - Session.prototype.setupSessionDescriptionHandler = function () { - if (this._sessionDescriptionHandler) { - return this._sessionDescriptionHandler; - } - this._sessionDescriptionHandler = - this.sessionDescriptionHandlerFactory(this, this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions); - this.emit("SessionDescriptionHandler-created", this._sessionDescriptionHandler); - return this._sessionDescriptionHandler; - }; - /** - * Transition session state. - * @internal - */ - Session.prototype.stateTransition = function (newState) { - var _this = this; - var invalidTransition = function () { - throw new Error("Invalid state transition from " + _this._state + " to " + newState); - }; - // Validate transition - switch (this._state) { - case session_state_1.SessionState.Initial: - if (newState !== session_state_1.SessionState.Establishing && - newState !== session_state_1.SessionState.Established && - newState !== session_state_1.SessionState.Terminating && - newState !== session_state_1.SessionState.Terminated) { - invalidTransition(); - } - break; - case session_state_1.SessionState.Establishing: - if (newState !== session_state_1.SessionState.Established && - newState !== session_state_1.SessionState.Terminating && - newState !== session_state_1.SessionState.Terminated) { - invalidTransition(); - } - break; - case session_state_1.SessionState.Established: - if (newState !== session_state_1.SessionState.Terminating && - newState !== session_state_1.SessionState.Terminated) { - invalidTransition(); - } - break; - case session_state_1.SessionState.Terminating: - if (newState !== session_state_1.SessionState.Terminated) { - invalidTransition(); - } - break; - case session_state_1.SessionState.Terminated: - invalidTransition(); - break; - default: - throw new Error("Unrecognized state."); - } - // Deprecated legacy ported behavior - if (newState === session_state_1.SessionState.Established) { - this.startTime = new Date(); - } - // Transition - this._state = newState; - this.logger.log("Session " + this.id + " transitioned to state " + this._state); - this._stateEventEmitter.emit("event", this._state); - }; - // DEPRECATED - /** @internal */ - Session.C = Enums_1.SessionStatus; - return Session; -}(events_1.EventEmitter)); -exports.Session = Session; diff --git a/lib/api/subscriber-options.d.ts b/lib/api/subscriber-options.d.ts deleted file mode 100644 index 61cfed12b..000000000 --- a/lib/api/subscriber-options.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { SubscriptionOptions } from "./subscription-options"; -/** - * Options for {@link Subscriber} constructor. - * @public - */ -export interface SubscriberOptions extends SubscriptionOptions { - expires?: number; - extraHeaders?: Array; - body?: string; - contentType?: string; -} -//# sourceMappingURL=subscriber-options.d.ts.map \ No newline at end of file diff --git a/lib/api/subscriber-options.d.ts.map b/lib/api/subscriber-options.d.ts.map deleted file mode 100644 index 0bebbff69..000000000 --- a/lib/api/subscriber-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"subscriber-options.d.ts","sourceRoot":"","sources":["../../src/api/subscriber-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAE7D;;;GAGG;AACH,MAAM,WAAW,iBAAkB,SAAQ,mBAAmB;IAC5D,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,YAAY,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAC7B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB"} \ No newline at end of file diff --git a/lib/api/subscriber-options.js b/lib/api/subscriber-options.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/api/subscriber-options.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/api/subscriber-subscribe-options.d.ts b/lib/api/subscriber-subscribe-options.d.ts deleted file mode 100644 index 53ffaa836..000000000 --- a/lib/api/subscriber-subscribe-options.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -/** - * Options for {@link Subscriber.subscribe}. - * @public - */ -export interface SubscriberSubscribeOptions { -} -//# sourceMappingURL=subscriber-subscribe-options.d.ts.map \ No newline at end of file diff --git a/lib/api/subscriber-subscribe-options.d.ts.map b/lib/api/subscriber-subscribe-options.d.ts.map deleted file mode 100644 index 52a1f2f32..000000000 --- a/lib/api/subscriber-subscribe-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"subscriber-subscribe-options.d.ts","sourceRoot":"","sources":["../../src/api/subscriber-subscribe-options.ts"],"names":[],"mappings":"AACA;;;GAGG;AACH,MAAM,WAAW,0BAA0B;CAC1C"} \ No newline at end of file diff --git a/lib/api/subscriber-subscribe-options.js b/lib/api/subscriber-subscribe-options.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/api/subscriber-subscribe-options.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/api/subscriber.d.ts b/lib/api/subscriber.d.ts deleted file mode 100644 index 98915f6a5..000000000 --- a/lib/api/subscriber.d.ts +++ /dev/null @@ -1,160 +0,0 @@ -import { IncomingNotifyRequest, IncomingRequestMessage, IncomingResponse, IncomingResponseMessage, OutgoingSubscribeRequest, URI } from "../core"; -import { SubscriberOptions } from "./subscriber-options"; -import { SubscriberSubscribeOptions } from "./subscriber-subscribe-options"; -import { Subscription } from "./subscription"; -import { SubscriptionUnsubscribeOptions } from "./subscription-unsubscribe-options"; -import { UserAgent } from "./user-agent"; -/** - * A subscriber establishes a {@link Subscription} (outgoing SUBSCRIBE). - * - * @remarks - * This is (more or less) an implementation of a "subscriber" as - * defined in RFC 6665 "SIP-Specific Event Notifications". - * https://tools.ietf.org/html/rfc6665 - * - * @example - * ```ts - * // Create a new subscriber. - * const targetURI = new URI("sip", "alice", "example.com"); - * const eventType = "example-name"; // https://www.iana.org/assignments/sip-events/sip-events.xhtml - * const subscriber = new Subscriber(userAgent, targetURI, eventType); - * - * // Add delegate to handle event notifications. - * subscriber.delegate = { - * onNotify: (notification: Notification) => { - * // handle notification here - * } - * }; - * - * // Monitor subscription state changes. - * subscriber.stateChange.on((newState: SubscriptionState) => { - * if (newState === SubscriptionState.Terminated) { - * // handle state change here - * } - * }); - * - * // Attempt to establish the subscription - * subscriber.subscribe(); - * - * // Sometime later when done with subscription - * subscriber.unsubscribe(); - * ``` - * - * @public - */ -export declare class Subscriber extends Subscription { - private id; - private body; - private context; - private event; - private expires; - private extraHeaders; - private logger; - private request; - private retryAfterTimer; - private targetURI; - /** - * Constructor. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @param targetURI - The request URI identifying the subscribed event. - * @param eventType - The event type identifying the subscribed event. - * @param options - Options bucket. See {@link SubscriberOptions} for details. - */ - constructor(userAgent: UserAgent, targetURI: URI, eventType: string, options?: SubscriberOptions); - /** - * Destructor. - * @internal - */ - dispose(): void; - /** - * Subscribe to event notifications. - * - * @remarks - * Send an initial SUBSCRIBE request if no subscription as been established. - * Sends a re-SUBSCRIBE request if the subscription is "active". - */ - subscribe(options?: SubscriberSubscribeOptions): Promise; - /** - * Unsubscribe. - * @internal - */ - unsubscribe(options?: SubscriptionUnsubscribeOptions): Promise; - /** - * Alias for `unsubscribe`. - * @deprecated Use `unsubscribe` instead. - * @internal - */ - close(): Promise; - /** - * Sends a re-SUBSCRIBE request if the subscription is "active". - * @deprecated Use `subscribe` instead. - * @internal - */ - refresh(): Promise; - /** - * Registration of event listeners. - * - * @remarks - * The following events are emitted... - * - "accepted" A 200-class final response to a SUBSCRIBE request was received. - * - "failed" A non-200-class final response to a SUBSCRIBE request was received. - * - "rejected" Emitted immediately after a "failed" event (yes, it's redundant). - * - "notify" A NOTIFY request was received. - * - SubscriptionState.Terminated The subscription is moving to or has moved to a terminated state. - * - * More than one SUBSCRIBE request may be sent, so "accepted", "failed" and "rejected" - * may be emitted multiple times. However these event will NOT be emitted for SUBSCRIBE - * requests with expires of zero (unsubscribe requests). - * - * Note that a "terminated" event does NOT indicate the subscription is in the "terminated" - * state as described in RFC 6665. Instead, a SubscriptionState.Terminated event indicates that this class - * is no longer usable and/or is in the process of becoming no longer usable. - * - * The order the events are emitted in is not deterministic. Some examples... - * - "accepted" may occur multiple times - * - "accepted" may follow "notify" and "notify" may follow "accepted" - * - SubscriptionState.Terminated may follow "accepted" and "accepted" may follow SubscriptionState.Terminated - * - SubscriptionState.Terminated may follow "notify" and "notify" may follow SubscriptionState.Terminated - * - * Hint: Experience suggests one workable approach to utilizing these events - * is to make use of "notify" and SubscriptionState.Terminated only. That is, call `subscribe()` - * and if a "notify" occurs then you have a subscription. If a SubscriptionState.Terminated - * event occurs then either a new subscription failed to be established or an - * established subscription has terminated or is in the process of terminating. - * Note that "notify" events may follow a SubscriptionState.Terminated event, but experience - * suggests it is reasonable to discontinue usage of this class after receipt - * of a SubscriptionState.Terminated event. The other events are informational, but as they do not - * arrive in a deterministic manner it is difficult to make use of them otherwise. - * - * @param name - Event name. - * @param callback - Callback. - * @internal - */ - on(name: "accepted" | "failed" | "rejected", callback: (message: IncomingResponseMessage, cause: string) => void): this; - /** @internal */ - on(name: "notify", callback: (notification: { - request: IncomingRequestMessage; - }) => void): this; - /** @internal */ - on(name: "terminated", callback: () => void): this; - /** @internal */ - emit(event: "accepted" | "failed" | "rejected", message: IncomingResponseMessage, cause: string): boolean; - /** @internal */ - emit(event: "notify", notification: { - request: IncomingRequestMessage; - }): boolean; - /** @internal */ - emit(event: "terminated"): boolean; - /** @internal */ - protected onAccepted(response: IncomingResponse): void; - /** @internal */ - protected onFailed(response?: IncomingResponse): void; - /** @internal */ - protected onNotify(request: IncomingNotifyRequest): void; - /** @internal */ - protected onRefresh(request: OutgoingSubscribeRequest): void; - /** @internal */ - protected onTerminated(): void; - private initContext; -} -//# sourceMappingURL=subscriber.d.ts.map \ No newline at end of file diff --git a/lib/api/subscriber.d.ts.map b/lib/api/subscriber.d.ts.map deleted file mode 100644 index 6e0e5c94b..000000000 --- a/lib/api/subscriber.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"subscriber.d.ts","sourceRoot":"","sources":["../../src/api/subscriber.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,qBAAqB,EACrB,sBAAsB,EAEtB,gBAAgB,EAChB,uBAAuB,EAGvB,wBAAwB,EAIxB,GAAG,EAEJ,MAAM,SAAS,CAAC;AAMjB,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,0BAA0B,EAAE,MAAM,gCAAgC,CAAC;AAC5E,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAE9C,OAAO,EAAE,8BAA8B,EAAE,MAAM,oCAAoC,CAAC;AACpF,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,qBAAa,UAAW,SAAQ,YAAY;IAG1C,OAAO,CAAC,EAAE,CAAS;IACnB,OAAO,CAAC,IAAI,CAA6C;IACzD,OAAO,CAAC,OAAO,CAAyB;IACxC,OAAO,CAAC,KAAK,CAAS;IACtB,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,YAAY,CAAgB;IACpC,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,OAAO,CAAyB;IACxC,OAAO,CAAC,eAAe,CAAkB;IACzC,OAAO,CAAC,SAAS,CAAM;IAEvB;;;;;;OAMG;gBACS,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,GAAG,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,GAAE,iBAAsB;IAwCpG;;;OAGG;IACI,OAAO,IAAI,IAAI;IAgBtB;;;;;;OAMG;IACI,SAAS,CAAC,OAAO,GAAE,0BAA+B,GAAG,OAAO,CAAC,IAAI,CAAC;IAgDzE;;;OAGG;IACI,WAAW,CAAC,OAAO,GAAE,8BAAmC,GAAG,OAAO,CAAC,IAAI,CAAC;IA+B/E;;;;OAIG;IACI,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAI7B;;;;OAIG;IACI,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAO/B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAsCG;IACI,EAAE,CACP,IAAI,EAAE,UAAU,GAAG,QAAQ,GAAG,UAAU,EACxC,QAAQ,EAAE,CAAC,OAAO,EAAE,uBAAuB,EAAE,KAAK,EAAE,MAAM,KAAK,IAAI,GAClE,IAAI;IACP,gBAAgB;IACT,EAAE,CAAC,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,CAAC,YAAY,EAAE;QAAE,OAAO,EAAE,sBAAsB,CAAA;KAAE,KAAK,IAAI,GAAG,IAAI;IACtG,gBAAgB;IACT,EAAE,CAAC,IAAI,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,IAAI,GAAG,IAAI;IAMzD,gBAAgB;IACT,IAAI,CACT,KAAK,EAAE,UAAU,GAAG,QAAQ,GAAG,UAAU,EACzC,OAAO,EAAE,uBAAuB,EAAE,KAAK,EAAE,MAAM,GAC9C,OAAO;IACV,gBAAgB;IACT,IAAI,CAAC,KAAK,EAAE,QAAQ,EAAE,YAAY,EAAE;QAAE,OAAO,EAAE,sBAAsB,CAAA;KAAE,GAAG,OAAO;IACxF,gBAAgB;IACT,IAAI,CAAC,KAAK,EAAE,YAAY,GAAG,OAAO;IAMzC,gBAAgB;IAChB,SAAS,CAAC,UAAU,CAAC,QAAQ,EAAE,gBAAgB,GAAG,IAAI;IAMtD,gBAAgB;IAChB,SAAS,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,gBAAgB,GAAG,IAAI;IAUrD,gBAAgB;IAChB,SAAS,CAAC,QAAQ,CAAC,OAAO,EAAE,qBAAqB,GAAG,IAAI;IA0ExD,gBAAgB;IAChB,SAAS,CAAC,SAAS,CAAC,OAAO,EAAE,wBAAwB,GAAG,IAAI;IAM5D,gBAAgB;IAChB,SAAS,CAAC,YAAY,IAAI,IAAI;IAI9B,OAAO,CAAC,WAAW;CAiBpB"} \ No newline at end of file diff --git a/lib/api/subscriber.js b/lib/api/subscriber.js deleted file mode 100644 index b6b618d6e..000000000 --- a/lib/api/subscriber.js +++ /dev/null @@ -1,455 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var core_1 = require("../core"); -var allowed_methods_1 = require("../core/user-agent-core/allowed-methods"); -var Utils_1 = require("../Utils"); -var notification_1 = require("./notification"); -var subscription_1 = require("./subscription"); -var subscription_state_1 = require("./subscription-state"); -/** - * A subscriber establishes a {@link Subscription} (outgoing SUBSCRIBE). - * - * @remarks - * This is (more or less) an implementation of a "subscriber" as - * defined in RFC 6665 "SIP-Specific Event Notifications". - * https://tools.ietf.org/html/rfc6665 - * - * @example - * ```ts - * // Create a new subscriber. - * const targetURI = new URI("sip", "alice", "example.com"); - * const eventType = "example-name"; // https://www.iana.org/assignments/sip-events/sip-events.xhtml - * const subscriber = new Subscriber(userAgent, targetURI, eventType); - * - * // Add delegate to handle event notifications. - * subscriber.delegate = { - * onNotify: (notification: Notification) => { - * // handle notification here - * } - * }; - * - * // Monitor subscription state changes. - * subscriber.stateChange.on((newState: SubscriptionState) => { - * if (newState === SubscriptionState.Terminated) { - * // handle state change here - * } - * }); - * - * // Attempt to establish the subscription - * subscriber.subscribe(); - * - * // Sometime later when done with subscription - * subscriber.unsubscribe(); - * ``` - * - * @public - */ -var Subscriber = /** @class */ (function (_super) { - tslib_1.__extends(Subscriber, _super); - /** - * Constructor. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @param targetURI - The request URI identifying the subscribed event. - * @param eventType - The event type identifying the subscribed event. - * @param options - Options bucket. See {@link SubscriberOptions} for details. - */ - function Subscriber(userAgent, targetURI, eventType, options) { - if (options === void 0) { options = {}; } - var _this = _super.call(this, userAgent, options) || this; - _this.body = undefined; - _this.logger = userAgent.getLogger("sip.subscription"); - if (options.body) { - _this.body = { - body: options.body, - contentType: options.contentType ? options.contentType : "application/sdp" - }; - } - _this.userAgent = userAgent; - _this.targetURI = targetURI; - // Subscription event - _this.event = eventType; - // Subscription expires - if (options.expires === undefined) { - _this.expires = 3600; - } - else if (typeof options.expires !== "number") { // pre-typescript type guard - _this.logger.warn("Option \"expires\" must be a number. Using default of 3600."); - _this.expires = 3600; - } - else { - _this.expires = options.expires; - } - // Subscription extra headers - _this.extraHeaders = (options.extraHeaders || []).slice(); - // Subscription context. - _this.context = _this.initContext(); - _this.request = _this.context.message; - // Add to UA's collection - _this.id = _this.request.callId + _this.request.from.parameters.tag + _this.event; - _this.userAgent.subscriptions[_this.id] = _this; - return _this; - } - /** - * Destructor. - * @internal - */ - Subscriber.prototype.dispose = function () { - if (this.disposed) { - return; - } - _super.prototype.dispose.call(this); - if (this.retryAfterTimer) { - clearTimeout(this.retryAfterTimer); - this.retryAfterTimer = undefined; - } - this.context.dispose(); - // Remove from userAgent's collection - delete this.userAgent.subscriptions[this.id]; - }; - /** - * Subscribe to event notifications. - * - * @remarks - * Send an initial SUBSCRIBE request if no subscription as been established. - * Sends a re-SUBSCRIBE request if the subscription is "active". - */ - Subscriber.prototype.subscribe = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - switch (this.context.state) { - case core_1.SubscriptionState.Initial: - // we can end up here when retrying so only state transition if in SubscriptionState.Initial state - if (this.state === subscription_state_1.SubscriptionState.Initial) { - this.stateTransition(subscription_state_1.SubscriptionState.NotifyWait); - } - this.context.subscribe().then(function (result) { - if (result.success) { - if (result.success.subscription) { - _this.dialog = result.success.subscription; - _this.dialog.delegate = { - onNotify: function (request) { return _this.onNotify(request); }, - onRefresh: function (request) { return _this.onRefresh(request); }, - onTerminated: function () { - _this.dispose(); - _this.onTerminated(); - } - }; - } - _this.onNotify(result.success.request); - } - else if (result.failure) { - _this.onFailed(result.failure.response); - } - }); - break; - case core_1.SubscriptionState.NotifyWait: - break; - case core_1.SubscriptionState.Pending: - break; - case core_1.SubscriptionState.Active: - if (this.dialog) { - var request = this.dialog.refresh(); - request.delegate = { - onAccept: (function (response) { return _this.onAccepted(response); }), - onRedirect: (function (response) { return _this.onFailed(response); }), - onReject: (function (response) { return _this.onFailed(response); }), - }; - } - break; - case core_1.SubscriptionState.Terminated: - break; - default: - break; - } - return Promise.resolve(); - }; - /** - * Unsubscribe. - * @internal - */ - Subscriber.prototype.unsubscribe = function (options) { - if (options === void 0) { options = {}; } - if (this.disposed) { - return Promise.resolve(); - } - switch (this.context.state) { - case core_1.SubscriptionState.Initial: - break; - case core_1.SubscriptionState.NotifyWait: - break; - case core_1.SubscriptionState.Pending: - if (this.dialog) { - this.dialog.unsubscribe(); - // responses intentionally ignored - } - break; - case core_1.SubscriptionState.Active: - if (this.dialog) { - this.dialog.unsubscribe(); - // responses intentionally ignored - } - break; - case core_1.SubscriptionState.Terminated: - break; - default: - break; - } - this.dispose(); - this.onTerminated(); - return Promise.resolve(); - }; - /** - * Alias for `unsubscribe`. - * @deprecated Use `unsubscribe` instead. - * @internal - */ - Subscriber.prototype.close = function () { - return this.unsubscribe(); - }; - /** - * Sends a re-SUBSCRIBE request if the subscription is "active". - * @deprecated Use `subscribe` instead. - * @internal - */ - Subscriber.prototype.refresh = function () { - if (this.context.state === core_1.SubscriptionState.Active) { - return this.subscribe(); - } - return Promise.resolve(); - }; - /** @internal */ - Subscriber.prototype.on = function (name, callback) { - return _super.prototype.on.call(this, name, callback); - }; - /** @internal */ - Subscriber.prototype.emit = function (event) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - return _super.prototype.emit.apply(this, [event].concat(args)); - }; - /** @internal */ - Subscriber.prototype.onAccepted = function (response) { - var statusCode = response.message.statusCode ? response.message.statusCode : 0; - var cause = Utils_1.Utils.getReasonPhrase(statusCode); - this.emit("accepted", response.message, cause); - }; - /** @internal */ - Subscriber.prototype.onFailed = function (response) { - this.close(); - if (response) { - var statusCode = response.message.statusCode ? response.message.statusCode : 0; - var cause = Utils_1.Utils.getReasonPhrase(statusCode); - this.emit("failed", response.message, cause); - this.emit("rejected", response.message, cause); - } - }; - /** @internal */ - Subscriber.prototype.onNotify = function (request) { - var _this = this; - // DEPRECATED BEGIN - // request.accept(); // Send 200 response. - this.emit("notify", { request: request.message }); - // DEPRECATED END - // If we've set state to done, no further processing should take place - // and we are only interested in cleaning up after the appropriate NOTIFY. - if (this.disposed) { - request.accept(); - return; - } - // State transition if needed. - if (this.state !== subscription_state_1.SubscriptionState.Subscribed) { - this.stateTransition(subscription_state_1.SubscriptionState.Subscribed); - } - // Delegate notification. - if (this.delegate && this.delegate.onNotify) { - var notification = new notification_1.Notification(request); - this.delegate.onNotify(notification); - } - else { - request.accept(); - } - // If the "Subscription-State" value is SubscriptionState.Terminated, the subscriber - // MUST consider the subscription terminated. The "expires" parameter - // has no semantics for SubscriptionState.Terminated -- notifiers SHOULD NOT include an - // "expires" parameter on a "Subscription-State" header field with a - // value of SubscriptionState.Terminated, and subscribers MUST ignore any such - // parameter, if present. If a reason code is present, the client - // should behave as described below. If no reason code or an unknown - // reason code is present, the client MAY attempt to re-subscribe at any - // time (unless a "retry-after" parameter is present, in which case the - // client SHOULD NOT attempt re-subscription until after the number of - // seconds specified by the "retry-after" parameter). The reason codes - // defined by this document are: - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - var subscriptionState = request.message.parseHeader("Subscription-State"); - if (subscriptionState && subscriptionState.state) { - switch (subscriptionState.state) { - case "terminated": - if (subscriptionState.reason) { - this.logger.log("Terminated subscription with reason " + subscriptionState.reason); - switch (subscriptionState.reason) { - case "deactivated": - case "timeout": - this.initContext(); - this.subscribe(); - return; - case "probation": - case "giveup": - this.initContext(); - if (subscriptionState.params && subscriptionState.params["retry-after"]) { - this.retryAfterTimer = setTimeout(function () { return _this.subscribe(); }, subscriptionState.params["retry-after"]); - } - else { - this.subscribe(); - } - return; - case "rejected": - case "noresource": - case "invariant": - break; - } - } - this.close(); - break; - default: - break; - } - } - }; - /** @internal */ - Subscriber.prototype.onRefresh = function (request) { - var _this = this; - request.delegate = { - onAccept: function (response) { return _this.onAccepted(response); } - }; - }; - /** @internal */ - Subscriber.prototype.onTerminated = function () { - this.emit("terminated"); - }; - Subscriber.prototype.initContext = function () { - var _this = this; - var options = { - extraHeaders: this.extraHeaders, - body: this.body ? Utils_1.Utils.fromBodyObj(this.body) : undefined - }; - this.context = new SubscribeClientContext(this.userAgent.userAgentCore, this.targetURI, this.event, this.expires, options); - this.context.delegate = { - onAccept: (function (response) { return _this.onAccepted(response); }) - }; - return this.context; - }; - return Subscriber; -}(subscription_1.Subscription)); -exports.Subscriber = Subscriber; -// tslint:disable-next-line:max-classes-per-file -var SubscribeClientContext = /** @class */ (function () { - function SubscribeClientContext(core, target, event, expires, options, delegate) { - this.core = core; - this.target = target; - this.event = event; - this.expires = expires; - this.subscribed = false; - this.logger = core.loggerFactory.getLogger("sip.subscription"); - this.delegate = delegate; - var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); - var extraHeaders = (options && options.extraHeaders || []).slice(); - extraHeaders.push(allowHeader); - extraHeaders.push("Event: " + this.event); - extraHeaders.push("Expires: " + this.expires); - extraHeaders.push("Contact: " + this.core.configuration.contact.toString()); - var body = options && options.body; - this.message = core.makeOutgoingRequestMessage(core_1.C.SUBSCRIBE, this.target, this.core.configuration.aor, this.target, {}, extraHeaders, body); - } - /** Destructor. */ - SubscribeClientContext.prototype.dispose = function () { - if (this.subscription) { - this.subscription.dispose(); - } - if (this.request) { - this.request.waitNotifyStop(); - this.request.dispose(); - } - }; - Object.defineProperty(SubscribeClientContext.prototype, "state", { - /** Subscription state. */ - get: function () { - if (this.subscription) { - return this.subscription.subscriptionState; - } - else if (this.subscribed) { - return core_1.SubscriptionState.NotifyWait; - } - else { - return core_1.SubscriptionState.Initial; - } - }, - enumerable: true, - configurable: true - }); - /** - * Establish subscription. - * @param options Options bucket. - */ - SubscribeClientContext.prototype.subscribe = function () { - var _this = this; - if (this.subscribed) { - return Promise.reject(new Error("Not in initial state. Did you call subscribe more than once?")); - } - this.subscribed = true; - return new Promise(function (resolve, reject) { - if (!_this.message) { - throw new Error("Message undefined."); - } - _this.request = _this.core.subscribe(_this.message, { - // This SUBSCRIBE request will be confirmed with a final response. - // 200-class responses indicate that the subscription has been accepted - // and that a NOTIFY request will be sent immediately. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - onAccept: function (response) { - if (_this.delegate && _this.delegate.onAccept) { - _this.delegate.onAccept(response); - } - }, - // Due to the potential for out-of-order messages, packet loss, and - // forking, the subscriber MUST be prepared to receive NOTIFY requests - // before the SUBSCRIBE transaction has completed. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.4 - onNotify: function (requestWithSubscription) { - _this.subscription = requestWithSubscription.subscription; - if (_this.subscription) { - _this.subscription.autoRefresh = true; - } - resolve({ success: requestWithSubscription }); - }, - // If this Timer N expires prior to the receipt of a NOTIFY request, - // the subscriber considers the subscription failed, and cleans up - // any state associated with the subscription attempt. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.4 - onNotifyTimeout: function () { - resolve({ failure: {} }); - }, - // This SUBSCRIBE request will be confirmed with a final response. - // Non-200-class final responses indicate that no subscription or new - // dialog usage has been created, and no subsequent NOTIFY request will - // be sent. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - onRedirect: function (response) { - resolve({ failure: { response: response } }); - }, - // This SUBSCRIBE request will be confirmed with a final response. - // Non-200-class final responses indicate that no subscription or new - // dialog usage has been created, and no subsequent NOTIFY request will - // be sent. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - onReject: function (response) { - resolve({ failure: { response: response } }); - } - }); - }); - }; - return SubscribeClientContext; -}()); diff --git a/lib/api/subscription-delegate.d.ts b/lib/api/subscription-delegate.d.ts deleted file mode 100644 index 4efb00ec1..000000000 --- a/lib/api/subscription-delegate.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { Notification } from "./notification"; -/** - * Delegate for {@link Subscription}. - * @public - */ -export interface SubscriptionDelegate { - /** - * Called upon receiving an incoming in dialog NOTIFY request. - * @param notification - A notification. See {@link Notification} for details. - */ - onNotify(notification: Notification): void; -} -//# sourceMappingURL=subscription-delegate.d.ts.map \ No newline at end of file diff --git a/lib/api/subscription-delegate.d.ts.map b/lib/api/subscription-delegate.d.ts.map deleted file mode 100644 index 7f5133b59..000000000 --- a/lib/api/subscription-delegate.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"subscription-delegate.d.ts","sourceRoot":"","sources":["../../src/api/subscription-delegate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAE9C;;;GAGG;AACH,MAAM,WAAW,oBAAoB;IACnC;;;OAGG;IACH,QAAQ,CAAC,YAAY,EAAE,YAAY,GAAG,IAAI,CAAC;CAC5C"} \ No newline at end of file diff --git a/lib/api/subscription-delegate.js b/lib/api/subscription-delegate.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/api/subscription-delegate.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/api/subscription-options.d.ts b/lib/api/subscription-options.d.ts deleted file mode 100644 index 70e65308d..000000000 --- a/lib/api/subscription-options.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { SubscriptionDelegate } from "./subscription-delegate"; -/** - * Options for {@link Subscription } constructor. - * @public - */ -export interface SubscriptionOptions { - delegate?: SubscriptionDelegate; -} -//# sourceMappingURL=subscription-options.d.ts.map \ No newline at end of file diff --git a/lib/api/subscription-options.d.ts.map b/lib/api/subscription-options.d.ts.map deleted file mode 100644 index abd24343b..000000000 --- a/lib/api/subscription-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"subscription-options.d.ts","sourceRoot":"","sources":["../../src/api/subscription-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAC/D;;;GAGG;AACH,MAAM,WAAW,mBAAmB;IAClC,QAAQ,CAAC,EAAE,oBAAoB,CAAC;CACjC"} \ No newline at end of file diff --git a/lib/api/subscription-options.js b/lib/api/subscription-options.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/api/subscription-options.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/api/subscription-state.d.ts b/lib/api/subscription-state.d.ts deleted file mode 100644 index 89bebc4e4..000000000 --- a/lib/api/subscription-state.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -/** - * {@link Subscription} state. - * @remarks - * Valid state transitions: - * ``` - * 1. "initial" --> "notify-wait" --> "subscribed" --> "terminated" - * 2. "initial" --> "notify-wait" --> "terminated" - * 3. "initial" --> "terminated" - * ``` - * @public - */ -export declare enum SubscriptionState { - Initial = "Initial", - NotifyWait = "NotifyWait", - Subscribed = "Subscribed", - Terminated = "Terminated" -} -//# sourceMappingURL=subscription-state.d.ts.map \ No newline at end of file diff --git a/lib/api/subscription-state.d.ts.map b/lib/api/subscription-state.d.ts.map deleted file mode 100644 index 091f79a51..000000000 --- a/lib/api/subscription-state.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"subscription-state.d.ts","sourceRoot":"","sources":["../../src/api/subscription-state.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,oBAAY,iBAAiB;IAC3B,OAAO,YAAY;IACnB,UAAU,eAAgB;IAC1B,UAAU,eAAe;IACzB,UAAU,eAAe;CAC1B"} \ No newline at end of file diff --git a/lib/api/subscription-state.js b/lib/api/subscription-state.js deleted file mode 100644 index 89d954085..000000000 --- a/lib/api/subscription-state.js +++ /dev/null @@ -1,20 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * {@link Subscription} state. - * @remarks - * Valid state transitions: - * ``` - * 1. "initial" --> "notify-wait" --> "subscribed" --> "terminated" - * 2. "initial" --> "notify-wait" --> "terminated" - * 3. "initial" --> "terminated" - * ``` - * @public - */ -var SubscriptionState; -(function (SubscriptionState) { - SubscriptionState["Initial"] = "Initial"; - SubscriptionState["NotifyWait"] = "NotifyWait"; - SubscriptionState["Subscribed"] = "Subscribed"; - SubscriptionState["Terminated"] = "Terminated"; -})(SubscriptionState = exports.SubscriptionState || (exports.SubscriptionState = {})); diff --git a/lib/api/subscription-subscribe-options.d.ts b/lib/api/subscription-subscribe-options.d.ts deleted file mode 100644 index 38fc11d53..000000000 --- a/lib/api/subscription-subscribe-options.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -/** - * Options for {@link Subscription.subscribe}. - * @public - */ -export interface SubscriptionSubscribeOptions { -} -//# sourceMappingURL=subscription-subscribe-options.d.ts.map \ No newline at end of file diff --git a/lib/api/subscription-subscribe-options.d.ts.map b/lib/api/subscription-subscribe-options.d.ts.map deleted file mode 100644 index 969140a1f..000000000 --- a/lib/api/subscription-subscribe-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"subscription-subscribe-options.d.ts","sourceRoot":"","sources":["../../src/api/subscription-subscribe-options.ts"],"names":[],"mappings":"AACA;;;GAGG;AACH,MAAM,WAAW,4BAA4B;CAC5C"} \ No newline at end of file diff --git a/lib/api/subscription-subscribe-options.js b/lib/api/subscription-subscribe-options.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/api/subscription-subscribe-options.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/api/subscription-unsubscribe-options.d.ts b/lib/api/subscription-unsubscribe-options.d.ts deleted file mode 100644 index 0130c59f3..000000000 --- a/lib/api/subscription-unsubscribe-options.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -/** - * Options for {@link Subscription.unsubscribe}. - * @public - */ -export interface SubscriptionUnsubscribeOptions { -} -//# sourceMappingURL=subscription-unsubscribe-options.d.ts.map \ No newline at end of file diff --git a/lib/api/subscription-unsubscribe-options.d.ts.map b/lib/api/subscription-unsubscribe-options.d.ts.map deleted file mode 100644 index b05991308..000000000 --- a/lib/api/subscription-unsubscribe-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"subscription-unsubscribe-options.d.ts","sourceRoot":"","sources":["../../src/api/subscription-unsubscribe-options.ts"],"names":[],"mappings":"AACA;;;GAGG;AACH,MAAM,WAAW,8BAA8B;CAC9C"} \ No newline at end of file diff --git a/lib/api/subscription-unsubscribe-options.js b/lib/api/subscription-unsubscribe-options.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/api/subscription-unsubscribe-options.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/api/subscription.d.ts b/lib/api/subscription.d.ts deleted file mode 100644 index 3eaa0d6f2..000000000 --- a/lib/api/subscription.d.ts +++ /dev/null @@ -1,81 +0,0 @@ -/// -import { EventEmitter } from "events"; -import { Subscription as SubscriptionDialog } from "../core"; -import { Emitter } from "./emitter"; -import { SubscriptionDelegate } from "./subscription-delegate"; -import { SubscriptionOptions } from "./subscription-options"; -import { SubscriptionState } from "./subscription-state"; -import { SubscriptionSubscribeOptions } from "./subscription-subscribe-options"; -import { SubscriptionUnsubscribeOptions } from "./subscription-unsubscribe-options"; -import { UserAgent } from "./user-agent"; -/** - * A subscription provides asynchronous {@link Notification} of events. - * - * @remarks - * See {@link Subscriber} for details on establishing a subscription. - * - * @public - */ -export declare abstract class Subscription extends EventEmitter { - /** - * Property reserved for use by instance owner. - * @defaultValue `undefined` - */ - data: any | undefined; - /** - * Subscription delegate. See {@link SubscriptionDelegate} for details. - * @defaultValue `undefined` - */ - delegate: SubscriptionDelegate | undefined; - /** - * If the subscription state is SubscriptionState.Subscribed, the associated subscription dialog. Otherwise undefined. - * @internal - */ - dialog: SubscriptionDialog | undefined; - /** @internal */ - protected userAgent: UserAgent; - private _disposed; - private _logger; - private _state; - private _stateEventEmitter; - /** - * Constructor. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @internal - */ - protected constructor(userAgent: UserAgent, options?: SubscriptionOptions); - /** - * Destructor. - * @internal - */ - dispose(): void; - /** - * True if disposed. - * @internal - */ - readonly disposed: boolean; - /** - * Subscription state. See {@link SubscriptionState} for details. - */ - readonly state: SubscriptionState; - /** - * Emits when the subscription `state` property changes. - */ - readonly stateChange: Emitter; - /** - * Sends a re-SUBSCRIBE request if the subscription is "active". - */ - abstract subscribe(options?: SubscriptionSubscribeOptions): Promise; - /** - * Unsubscribe from event notifications. - * - * @remarks - * If the subscription state is SubscriptionState.Subscribed, sends an in dialog SUBSCRIBE request - * with expires time of zero (an un-subscribe) and terminates the subscription. - * Otherwise a noop. - */ - abstract unsubscribe(options?: SubscriptionUnsubscribeOptions): Promise; - /** @internal */ - protected stateTransition(newState: SubscriptionState): void; -} -//# sourceMappingURL=subscription.d.ts.map \ No newline at end of file diff --git a/lib/api/subscription.d.ts.map b/lib/api/subscription.d.ts.map deleted file mode 100644 index caaf37cec..000000000 --- a/lib/api/subscription.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"subscription.d.ts","sourceRoot":"","sources":["../../src/api/subscription.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAEtC,OAAO,EAEL,YAAY,IAAI,kBAAkB,EACnC,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,OAAO,EAAe,MAAM,WAAW,CAAC;AACjD,OAAO,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAC/D,OAAO,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAC7D,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,4BAA4B,EAAE,MAAM,kCAAkC,CAAC;AAChF,OAAO,EAAE,8BAA8B,EAAE,MAAM,oCAAoC,CAAC;AACpF,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC;;;;;;;GAOG;AACH,8BAAsB,YAAa,SAAQ,YAAY;IAErD;;;OAGG;IACI,IAAI,EAAE,GAAG,GAAG,SAAS,CAAC;IAE7B;;;OAGG;IACI,QAAQ,EAAE,oBAAoB,GAAG,SAAS,CAAC;IAElD;;;OAGG;IACI,MAAM,EAAE,kBAAkB,GAAG,SAAS,CAAC;IAE9C,gBAAgB;IAChB,SAAS,CAAC,SAAS,EAAE,SAAS,CAAC;IAE/B,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,MAAM,CAAgD;IAC9D,OAAO,CAAC,kBAAkB,CAAsB;IAEhD;;;;OAIG;IACH,SAAS,aAAa,SAAS,EAAE,SAAS,EAAE,OAAO,GAAE,mBAAwB;IAO7E;;;OAGG;IACI,OAAO,IAAI,IAAI;IAStB;;;OAGG;aACC,QAAQ,EAAI,OAAO;IAIvB;;OAEG;aACC,KAAK,EAAI,iBAAiB;IAI9B;;OAEG;aACC,WAAW,EAAI,OAAO,CAAC,iBAAiB,CAAC;IAI7C;;OAEG;aACa,SAAS,CAAC,OAAO,CAAC,EAAE,4BAA4B,GAAG,OAAO,CAAC,IAAI,CAAC;IAEhF;;;;;;;OAOG;aACa,WAAW,CAAC,OAAO,CAAC,EAAE,8BAA8B,GAAG,OAAO,CAAC,IAAI,CAAC;IAEpF,gBAAgB;IAChB,SAAS,CAAC,eAAe,CAAC,QAAQ,EAAE,iBAAiB,GAAG,IAAI;CAuC7D"} \ No newline at end of file diff --git a/lib/api/subscription.js b/lib/api/subscription.js deleted file mode 100644 index 6d047bee9..000000000 --- a/lib/api/subscription.js +++ /dev/null @@ -1,116 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var events_1 = require("events"); -var emitter_1 = require("./emitter"); -var subscription_state_1 = require("./subscription-state"); -/** - * A subscription provides asynchronous {@link Notification} of events. - * - * @remarks - * See {@link Subscriber} for details on establishing a subscription. - * - * @public - */ -var Subscription = /** @class */ (function (_super) { - tslib_1.__extends(Subscription, _super); - /** - * Constructor. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @internal - */ - function Subscription(userAgent, options) { - if (options === void 0) { options = {}; } - var _this = _super.call(this) || this; - _this._disposed = false; - _this._state = subscription_state_1.SubscriptionState.Initial; - _this._stateEventEmitter = new events_1.EventEmitter(); - _this._logger = userAgent.getLogger("sip.subscription"); - _this.userAgent = userAgent; - _this.delegate = options.delegate; - return _this; - } - /** - * Destructor. - * @internal - */ - Subscription.prototype.dispose = function () { - if (this._disposed) { - return; - } - this._disposed = true; - this.stateTransition(subscription_state_1.SubscriptionState.Terminated); - this._stateEventEmitter.removeAllListeners(); - }; - Object.defineProperty(Subscription.prototype, "disposed", { - /** - * True if disposed. - * @internal - */ - get: function () { - return this._disposed; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Subscription.prototype, "state", { - /** - * Subscription state. See {@link SubscriptionState} for details. - */ - get: function () { - return this._state; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Subscription.prototype, "stateChange", { - /** - * Emits when the subscription `state` property changes. - */ - get: function () { - return emitter_1.makeEmitter(this._stateEventEmitter); - }, - enumerable: true, - configurable: true - }); - /** @internal */ - Subscription.prototype.stateTransition = function (newState) { - var _this = this; - var invalidTransition = function () { - throw new Error("Invalid state transition from " + _this._state + " to " + newState); - }; - // Validate transition - switch (this._state) { - case subscription_state_1.SubscriptionState.Initial: - if (newState !== subscription_state_1.SubscriptionState.NotifyWait && newState !== subscription_state_1.SubscriptionState.Terminated) { - invalidTransition(); - } - break; - case subscription_state_1.SubscriptionState.NotifyWait: - if (newState !== subscription_state_1.SubscriptionState.Subscribed && newState !== subscription_state_1.SubscriptionState.Terminated) { - invalidTransition(); - } - break; - case subscription_state_1.SubscriptionState.Subscribed: - if (newState !== subscription_state_1.SubscriptionState.Terminated) { - invalidTransition(); - } - break; - case subscription_state_1.SubscriptionState.Terminated: - invalidTransition(); - break; - default: - throw new Error("Unrecognized state."); - } - // Guard against duplicate transition - if (this._state === newState) { - return; - } - // Transition - this._state = newState; - this._logger.log("Subscription " + (this.dialog ? this.dialog.id : undefined) + " transitioned to " + this._state); - this._stateEventEmitter.emit("event", this._state); - }; - return Subscription; -}(events_1.EventEmitter)); -exports.Subscription = Subscription; diff --git a/lib/api/user-agent-delegate.d.ts b/lib/api/user-agent-delegate.d.ts deleted file mode 100644 index 0918951d6..000000000 --- a/lib/api/user-agent-delegate.d.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { IncomingRegisterRequest, IncomingSubscribeRequest } from "../core"; -import { Invitation } from "./invitation"; -import { Message } from "./message"; -import { Notification } from "./notification"; -import { Referral } from "./referral"; -import { Subscription } from "./subscription"; -/** - * Delegate for {@link UserAgent}. - * @public - */ -export interface UserAgentDelegate { - /** - * Called upon receipt of an invitation. - * @remarks - * Handler for incoming out of dialog INVITE requests. - * @param invitation - The invitation. - */ - onInvite?(invitation: Invitation): void; - /** - * Called upon receipt of a message. - * @remarks - * Handler for incoming out of dialog MESSAGE requests. - * @param message - The message. - */ - onMessage?(message: Message): void; - /** - * Called upon receipt of a notification. - * @remarks - * Handler for incoming out of dialog NOTIFY requests. - * @param notification - The notification. - */ - onNotify?(notification: Notification): void; - /** - * Called upon receipt of a referral. - * @remarks - * Handler for incoming out of dialog REFER requests. - * @param referral - The referral. - */ - onRefer?(referral: Referral): void; - /** - * Called upon receipt of a subscription. - * @remarks - * Handler for incoming out of dialog SUBSCRIBE requests. - * @param subscription - The subscription. - */ - onSubscribe?(subscription: Subscription): void; - /** - * @internal - * Called upon receipt of a registration request. Used by test suite. - * @param request - The request. - */ - onRegisterRequest?(request: IncomingRegisterRequest): void; - /** - * @internal - * Called upon receipt of a subscription request. Used by test suite. - * @param request - The request. - */ - onSubscribeRequest?(request: IncomingSubscribeRequest): void; -} -//# sourceMappingURL=user-agent-delegate.d.ts.map \ No newline at end of file diff --git a/lib/api/user-agent-delegate.d.ts.map b/lib/api/user-agent-delegate.d.ts.map deleted file mode 100644 index 6408ce468..000000000 --- a/lib/api/user-agent-delegate.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"user-agent-delegate.d.ts","sourceRoot":"","sources":["../../src/api/user-agent-delegate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,wBAAwB,EAAE,MAAM,SAAS,CAAC;AAC5E,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AACtC,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAE9C;;;GAGG;AACH,MAAM,WAAW,iBAAiB;IAChC;;;;;OAKG;IACH,QAAQ,CAAC,CAAC,UAAU,EAAE,UAAU,GAAG,IAAI,CAAC;IAExC;;;;;OAKG;IACH,SAAS,CAAC,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAAC;IAEnC;;;;;OAKG;IACH,QAAQ,CAAC,CAAC,YAAY,EAAE,YAAY,GAAG,IAAI,CAAC;IAE5C;;;;;OAKG;IACF,OAAO,CAAC,CAAC,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAAC;IAEpC;;;;;OAKG;IACH,WAAW,CAAC,CAAC,YAAY,EAAE,YAAY,GAAG,IAAI,CAAC;IAE/C;;;;OAIG;IACH,iBAAiB,CAAC,CAAC,OAAO,EAAE,uBAAuB,GAAG,IAAI,CAAC;IAE3D;;;;OAIG;IACH,kBAAkB,CAAC,CAAC,OAAO,EAAE,wBAAwB,GAAG,IAAI,CAAC;CAC9D"} \ No newline at end of file diff --git a/lib/api/user-agent-delegate.js b/lib/api/user-agent-delegate.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/api/user-agent-delegate.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/api/user-agent-options.d.ts b/lib/api/user-agent-options.d.ts deleted file mode 100644 index 5712cfe50..000000000 --- a/lib/api/user-agent-options.d.ts +++ /dev/null @@ -1,227 +0,0 @@ -import { Transport, URI } from "../core"; -import { SessionDescriptionHandlerFactory } from "./session-description-handler-factory"; -import { UserAgentDelegate } from "./user-agent-delegate"; -/** - * Log level. - * @public - */ -export declare type LogLevel = "debug" | "log" | "warn" | "error"; -/** - * Log connector function. - * @public - */ -export declare type LogConnector = (level: LogLevel, category: string, label: string | undefined, content: string) => void; -/** - * SIP extension support level. - * @public - */ -export declare enum SIPExtension { - Required = "Required", - Supported = "Supported", - Unsupported = "Unsupported" -} -/** - * Options for {@link UserAgent} constructor. - * @public - */ -export interface UserAgentOptions { - /** - * If `true`, the user agent will accept out of dialog NOTIFY. - * @remarks - * RFC 6665 obsoletes the use of out of dialog NOTIFY from RFC 3265. - * @defaultValue `false` - */ - allowLegacyNotifications?: boolean; - /** - * If `true`, the user agent will accept out of dialog REFER. - * @defaultValue `false` - */ - allowOutOfDialogRefers?: boolean; - /** - * Authorization password. - * @defaultValue `""` - */ - authorizationPassword?: string; - /** - * Authorization username. - * @defaultValue `""` - */ - authorizationUsername?: string; - /** - * @deprecated - * If `true`, the user agent calls the `start()` method in the constructor. - * @defaultValue `false` - * @remarks - * The call to start() resovles when the user agent connects, so if this - * option is set to `true` an alternative method of connection detection - * must be used. - */ - autoStart?: boolean; - /** - * If `true`, the user agent calls the `stop()` method on unload (if running in browser window). - * @defaultValue `true` - */ - autoStop?: boolean; - /** - * Delegate for {@link UserAgent}. - * @defaultValue `{}` - */ - delegate?: UserAgentDelegate; - /** - * The display name associated with the user agent. - * @remarks - * Descriptive name to be shown to the called party when calling or sending IM messages - * (the display name portion of the From header). - * It must NOT be enclosed between double quotes even if the given name contains multi-byte symbols - * (SIPjs will always enclose the `displayName` value between double quotes). - * @defaultValue `""` - */ - displayName?: string; - /** - * Force adding rport to Via header. - * @defaultValue `false` - */ - forceRport?: boolean; - /** - * Hack - * @deprecated TBD - */ - hackIpInContact?: boolean | string; - /** - * Hack - * @deprecated TBD - */ - hackAllowUnregisteredOptionTags?: boolean; - /** - * Hack - * @deprecated TBD - */ - hackViaTcp?: boolean; - /** - * Hack - * @deprecated TBD - */ - hackWssInTransport?: boolean; - /** - * Indicates whether log messages should be written to the browser console. - * @defaultValue `true` - */ - logBuiltinEnabled?: boolean; - /** - * If true, constructor logs the user agent configuration. - * @defaultValue `true` - */ - logConfiguration?: boolean; - /** - * A function which will be called everytime a log is generated. - * @defaultValue - * A noop if not defined. - */ - logConnector?: LogConnector; - /** - * Indicates the verbosity level of the log messages. - * @defaultValue `"log"` - */ - logLevel?: LogLevel; - /** - * Number of seconds after which an incoming call is rejected if not answered. - * @defaultValue 60 - */ - noAnswerTimeout?: number; - /** - * A factory for generating `SessionDescriptionHandler` instances. - * @remarks - * The factory will be passed a `Session` object for the current session - * and the `sessionDescriptionHandlerFactoryOptions` object. - * @defaultValue `Web.SessionDesecriptionHandler.defaultFactory` - */ - sessionDescriptionHandlerFactory?: SessionDescriptionHandlerFactory; - /** - * Options to passed to `sessionDescriptionHandlerFactory`. - * @remarks - * See `Web.SessionDesecriptionHandlerOptions` for details. - * @defaultValue `{}` - */ - sessionDescriptionHandlerFactoryOptions?: object; - /** - * Reliable provisional responses. - * https://tools.ietf.org/html/rfc3262 - * @defaultValue `SIPExtension.Unsupported` - */ - sipExtension100rel?: SIPExtension; - /** - * Replaces header. - * https://tools.ietf.org/html/rfc3891 - * @defaultValue `SIPExtension.Unsupported` - */ - sipExtensionReplaces?: SIPExtension; - /** - * Extra option tags to claim support for. - * @remarks - * Setting an extra option tag does not enable support for the associated extension - * it simply adds the tag to the list of supported options. - * See {@link UserAgentRegisteredOptionTags} for valid option tags. - * @defaultValue `[]` - */ - sipExtensionExtraSupported?: Array; - /** - * An id uniquely identify this user agent instance. - * @defaultValue - * A random id generated by default. - */ - sipjsId?: string; - /** - * A constructor function for the user agent's `Transport`. - * @remarks - * For more information about creating your own transport see `Transport`. - * @defaultValue `WebSocketTransport` - */ - transportConstructor?: new (logger: any, options: any) => Transport; - /** - * An options bucket object passed to `transportConstructor` when instantiated. - * @remarks - * See WebSocket Transport Configuration Parameters for the full list of options for the default transport. - * @defaultValue `{}` - */ - transportOptions?: any; - /** - * SIP Addresses-of-Record URI associated with the user agent. - * @remarks - * This is a SIP address given to you by your provider. - * If the user agent registers, it is the address-of-record which the user agent registers a contact for. - * An address-of-record represents an identity of the user, generally a long-term identity, - * and it does not have a dependency on any device; users can move between devices or even - * be associated with multiple devices at one time while retaining the same address-of-record. - * A simple URI, generally of the form `sip:egdar@example.com`, is used for an address-of-record. - * @defaultValue - * By default, URI is set to `sip:anonymous.X@anonymous.invalid`, where X is a random token generated for each UA. - */ - uri?: URI; - /** - * Adds a Route header to requests. - * @defaultValue `false` - */ - usePreloadedRoute?: boolean; - /** - * User agent string used in the UserAgent header. - * @defaultValue - * A reasonable value is utilized. - */ - userAgentString?: string; - /** - * Hostname to use in Via header. - * @defaultValue - * A random hostname in the .invalid domain. - */ - viaHost?: string; -} -/** - * SIP Option Tags - * @remarks - * http://www.iana.org/assignments/sip-parameters/sip-parameters.xhtml#sip-parameters-4 - * @public - */ -export declare const UserAgentRegisteredOptionTags: { - [option: string]: boolean; -}; -//# sourceMappingURL=user-agent-options.d.ts.map \ No newline at end of file diff --git a/lib/api/user-agent-options.d.ts.map b/lib/api/user-agent-options.d.ts.map deleted file mode 100644 index 612a612d8..000000000 --- a/lib/api/user-agent-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"user-agent-options.d.ts","sourceRoot":"","sources":["../../src/api/user-agent-options.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,GAAG,EACJ,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,gCAAgC,EAAE,MAAM,uCAAuC,CAAC;AACzF,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAE1D;;;GAGG;AACH,oBAAY,QAAQ,GAAI,OAAO,GAAG,KAAK,GAAG,MAAM,GAAG,OAAO,CAAC;AAE3D;;;GAGG;AACH,oBAAY,YAAY,GAAG,CACzB,KAAK,EAAE,QAAQ,EACf,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,GAAG,SAAS,EACzB,OAAO,EAAE,MAAM,KACZ,IAAI,CAAC;AAEV;;;GAGG;AACH,oBAAY,YAAY;IACtB,QAAQ,aAAa;IACrB,SAAS,cAAc;IACvB,WAAW,gBAAgB;CAC5B;AAED;;;GAGG;AACH,MAAM,WAAW,gBAAgB;IAC/B;;;;;OAKG;IACH,wBAAwB,CAAC,EAAE,OAAO,CAAC;IAEnC;;;OAGG;IACH,sBAAsB,CAAC,EAAE,OAAO,CAAC;IAEjC;;;OAGG;IACH,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAE/B;;;OAGG;IACH,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAE/B;;;;;;;;OAQG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC;IAEpB;;;OAGG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;IAEnB;;;OAGG;IACH,QAAQ,CAAC,EAAE,iBAAiB,CAAC;IAE7B;;;;;;;;OAQG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IAErB;;;OAGG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;IAErB;;;OAGG;IACH,eAAe,CAAC,EAAE,OAAO,GAAG,MAAM,CAAC;IAEnC;;;OAGG;IACH,+BAA+B,CAAC,EAAE,OAAO,CAAC;IAE1C;;;OAGG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;IAErB;;;OAGG;IACH,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAE7B;;;OAGG;IACH,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAE5B;;;OAGG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAE3B;;;;OAIG;IACH,YAAY,CAAC,EAAE,YAAY,CAAC;IAE5B;;;OAGG;IACH,QAAQ,CAAC,EAAE,QAAQ,CAAC;IAEpB;;;OAGG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IAEzB;;;;;;OAMG;IACH,gCAAgC,CAAC,EAAE,gCAAgC,CAAC;IAEpE;;;;;OAKG;IACH,uCAAuC,CAAC,EAAE,MAAM,CAAC;IAEjD;;;;OAIG;IACH,kBAAkB,CAAC,EAAE,YAAY,CAAC;IAElC;;;;OAIG;IACH,oBAAoB,CAAC,EAAE,YAAY,CAAC;IAEpC;;;;;;;OAOG;IACH,0BAA0B,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAE3C;;;;OAIG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IAEjB;;;;;OAKG;IACH,oBAAoB,CAAC,EAAE,KAAK,MAAM,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,KAAK,SAAS,CAAC;IAEpE;;;;;OAKG;IACH,gBAAgB,CAAC,EAAE,GAAG,CAAC;IAEvB;;;;;;;;;;;OAWG;IACH,GAAG,CAAC,EAAE,GAAG,CAAC;IAEV;;;OAGG;IACH,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAE5B;;;;OAIG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IAEzB;;;;OAIG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED;;;;;GAKG;AACH,eAAO,MAAM,6BAA6B,EAAE;IAAC,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAA;CAkCrE,CAAC"} \ No newline at end of file diff --git a/lib/api/user-agent-options.js b/lib/api/user-agent-options.js deleted file mode 100644 index 50e8f9ce6..000000000 --- a/lib/api/user-agent-options.js +++ /dev/null @@ -1,53 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * SIP extension support level. - * @public - */ -var SIPExtension; -(function (SIPExtension) { - SIPExtension["Required"] = "Required"; - SIPExtension["Supported"] = "Supported"; - SIPExtension["Unsupported"] = "Unsupported"; -})(SIPExtension = exports.SIPExtension || (exports.SIPExtension = {})); -/** - * SIP Option Tags - * @remarks - * http://www.iana.org/assignments/sip-parameters/sip-parameters.xhtml#sip-parameters-4 - * @public - */ -exports.UserAgentRegisteredOptionTags = { - "100rel": true, - "199": true, - "answermode": true, - "early-session": true, - "eventlist": true, - "explicitsub": true, - "from-change": true, - "geolocation-http": true, - "geolocation-sip": true, - "gin": true, - "gruu": true, - "histinfo": true, - "ice": true, - "join": true, - "multiple-refer": true, - "norefersub": true, - "nosub": true, - "outbound": true, - "path": true, - "policy": true, - "precondition": true, - "pref": true, - "privacy": true, - "recipient-list-invite": true, - "recipient-list-message": true, - "recipient-list-subscribe": true, - "replaces": true, - "resource-priority": true, - "sdp-anat": true, - "sec-agree": true, - "tdialog": true, - "timer": true, - "uui": true // RFC 7433 -}; diff --git a/lib/api/user-agent-state.d.ts b/lib/api/user-agent-state.d.ts deleted file mode 100644 index c1f5d8584..000000000 --- a/lib/api/user-agent-state.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -/** - * {@link UserAgent} state. - * @remarks - * Valid state transitions: - * ``` - * 1. "initial" --> "starting" - * 2. "starting" --> "started" - * 3. "starting" --> "stopped" - * 4. "started" --> "stopping" - * 5. "started" --> "stopped" - * 6. "stopped" --> "starting" - * ``` - * @public - */ -export declare enum UserAgentState { - Initial = "Initial", - Starting = "Starting", - Started = "Started", - Stopping = "Stopping", - Stopped = "Stopped" -} -//# sourceMappingURL=user-agent-state.d.ts.map \ No newline at end of file diff --git a/lib/api/user-agent-state.d.ts.map b/lib/api/user-agent-state.d.ts.map deleted file mode 100644 index 579c18415..000000000 --- a/lib/api/user-agent-state.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"user-agent-state.d.ts","sourceRoot":"","sources":["../../src/api/user-agent-state.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,oBAAY,cAAc;IACxB,OAAO,YAAY;IACnB,QAAQ,aAAa;IACrB,OAAO,YAAY;IACnB,QAAQ,aAAa;IACrB,OAAO,YAAY;CACpB"} \ No newline at end of file diff --git a/lib/api/user-agent-state.js b/lib/api/user-agent-state.js deleted file mode 100644 index 5cd534d04..000000000 --- a/lib/api/user-agent-state.js +++ /dev/null @@ -1,24 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * {@link UserAgent} state. - * @remarks - * Valid state transitions: - * ``` - * 1. "initial" --> "starting" - * 2. "starting" --> "started" - * 3. "starting" --> "stopped" - * 4. "started" --> "stopping" - * 5. "started" --> "stopped" - * 6. "stopped" --> "starting" - * ``` - * @public - */ -var UserAgentState; -(function (UserAgentState) { - UserAgentState["Initial"] = "Initial"; - UserAgentState["Starting"] = "Starting"; - UserAgentState["Started"] = "Started"; - UserAgentState["Stopping"] = "Stopping"; - UserAgentState["Stopped"] = "Stopped"; -})(UserAgentState = exports.UserAgentState || (exports.UserAgentState = {})); diff --git a/lib/api/user-agent.d.ts b/lib/api/user-agent.d.ts deleted file mode 100644 index 1105b1e50..000000000 --- a/lib/api/user-agent.d.ts +++ /dev/null @@ -1,127 +0,0 @@ -import { Contact, IncomingRequestMessage, Logger, LoggerFactory, Transport, URI, UserAgentCore } from "../core"; -import { UAStatus } from "../Enums"; -import { Inviter } from "./inviter"; -import { InviterOptions } from "./inviter-options"; -import { Publisher } from "./publisher"; -import { Registerer } from "./registerer"; -import { Session } from "./session"; -import { Subscription } from "./subscription"; -import { UserAgentDelegate } from "./user-agent-delegate"; -import { UserAgentOptions } from "./user-agent-options"; -/** - * A user agent sends and receives requests using a `Transport`. - * - * @remarks - * A user agent (UA) is associated with a user via the user's SIP address of record (AOR) - * and acts on behalf of that user to send and receive SIP requests. The user agent can - * register to receive incoming requests, as well as create and send outbound messages. - * The user agent also maintains the Transport over which its signaling travels. - * - * @public - */ -export declare class UserAgent { - /** - * Create a URI instance from a string. - * @param uri - The string to parse. - * - * @example - * ```ts - * const uri = UserAgent.makeURI("sip:edgar@example.com"); - * ``` - */ - static makeURI(uri: string): URI | undefined; - /** Default user agent options. */ - private static readonly defaultOptions; - /** Delegate. */ - delegate: UserAgentDelegate | undefined; - /** @internal */ - data: any; - /** @internal */ - applicants: { - [id: string]: Inviter; - }; - /** @internal */ - publishers: { - [id: string]: Publisher; - }; - /** @internal */ - registerers: { - [id: string]: Registerer; - }; - /** @internal */ - sessions: { - [id: string]: Session; - }; - /** @internal */ - subscriptions: { - [id: string]: Subscription; - }; - /** @internal */ - status: UAStatus; - /** @internal */ - transport: Transport; - /** @internal */ - contact: Contact; - /** @internal */ - userAgentCore: UserAgentCore; - /** Logger. */ - private logger; - /** LoggerFactory. */ - private loggerFactory; - /** Options. */ - private options; - private _state; - private _stateEventEmitter; - /** Unload listener. */ - private unloadListener; - /** - * Constructs a new instance of the `UserAgent` class. - * @param options - Options bucket. See {@link UserAgentOptions} for details. - */ - constructor(options?: UserAgentOptions); - /** - * User agent configuration. - */ - readonly configuration: Required; - /** - * Connect user agent to network transport. - * @remarks - * Connect to the WS server if status = STATUS_INIT. - * Resume UA after being closed. - */ - start(): Promise; - /** - * Gracefully close. - * Gracefully disconnect from network transport. - * @remarks - * Unregisters and terminates active sessions/subscriptions. - */ - stop(): Promise; - /** @internal */ - findSession(request: IncomingRequestMessage): Session | undefined; - /** @internal */ - getLogger(category: string, label?: string): Logger; - /** @internal */ - getLoggerFactory(): LoggerFactory; - /** @internal */ - getSupportedResponseOptions(): Array; - /** @internal */ - makeInviter(targetURI: URI, options?: InviterOptions): Inviter; - private onTransportError; - /** - * Helper function. Sets transport listeners - */ - private setTransportListeners; - /** - * Transport connection event. - */ - private onTransportConnected; - /** - * Handle SIP message received from the transport. - * @param messageString - The message. - */ - private onTransportReceiveMsg; - private initContact; - private initCore; -} -//# sourceMappingURL=user-agent.d.ts.map \ No newline at end of file diff --git a/lib/api/user-agent.d.ts.map b/lib/api/user-agent.d.ts.map deleted file mode 100644 index 1dfc37a6e..000000000 --- a/lib/api/user-agent.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"user-agent.d.ts","sourceRoot":"","sources":["../../src/api/user-agent.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,OAAO,EAQP,sBAAsB,EAItB,MAAM,EACN,aAAa,EACb,SAAS,EAET,GAAG,EACH,aAAa,EAGd,MAAM,SAAS,CAAC;AAKjB,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AASpC,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAGnD,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAC1D,OAAO,EAEL,gBAAgB,EAEjB,MAAM,sBAAsB,CAAC;AAK9B;;;;;;;;;;GAUG;AACH,qBAAa,SAAS;IAEpB;;;;;;;;OAQG;WACW,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,GAAG,SAAS;IAInD,kCAAkC;IAClC,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,cAAc,CA+BpC;IAEF,gBAAgB;IACT,QAAQ,EAAE,iBAAiB,GAAG,SAAS,CAAC;IAE/C,gBAAgB;IACT,IAAI,EAAE,GAAG,CAAM;IACtB,gBAAgB;IACT,UAAU,EAAE;QAAC,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAA;KAAC,CAAM;IAChD,gBAAgB;IACT,UAAU,EAAE;QAAC,CAAC,EAAE,EAAE,MAAM,GAAG,SAAS,CAAA;KAAC,CAAM;IAClD,gBAAgB;IACT,WAAW,EAAE;QAAC,CAAC,EAAE,EAAE,MAAM,GAAG,UAAU,CAAA;KAAE,CAAM;IACrD,gBAAgB;IACT,QAAQ,EAAE;QAAC,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAA;KAAE,CAAM;IAC/C,gBAAgB;IACT,aAAa,EAAE;QAAC,CAAC,EAAE,EAAE,MAAM,GAAG,YAAY,CAAA;KAAC,CAAM;IACxD,gBAAgB;IACT,MAAM,EAAE,QAAQ,CAAwB;IAC/C,gBAAgB;IACT,SAAS,EAAE,SAAS,CAAC;IAE5B,gBAAgB;IACT,OAAO,EAAE,OAAO,CAAC;IAExB,gBAAgB;IACT,aAAa,EAAE,aAAa,CAAC;IAEpC,cAAc;IACd,OAAO,CAAC,MAAM,CAAS;IACvB,qBAAqB;IACrB,OAAO,CAAC,aAAa,CAAsC;IAC3D,eAAe;IACf,OAAO,CAAC,OAAO,CAA6B;IAE5C,OAAO,CAAC,MAAM,CAA0C;IACxD,OAAO,CAAC,kBAAkB,CAAsB;IAEhD,uBAAuB;IACvB,OAAO,CAAC,cAAc,CAA4B;IAElD;;;OAGG;gBACS,OAAO,GAAE,gBAAqB;IA0F1C;;OAEG;aACQ,aAAa,EAAI,QAAQ,CAAC,gBAAgB,CAAC;IAItD;;;;;OAKG;IACI,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAiC7B;;;;;OAKG;IACU,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAoFlC,gBAAgB;IACT,WAAW,CAChB,OAAO,EAAE,sBAAsB,GAC9B,OAAO,GAAG,SAAS;IAMtB,gBAAgB;IACT,SAAS,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM;IAI1D,gBAAgB;IACT,gBAAgB,IAAI,aAAa;IAIxC,gBAAgB;IACT,2BAA2B,IAAI,KAAK,CAAC,MAAM,CAAC;IA6BnD,gBAAgB;IACT,WAAW,CAChB,SAAS,EAAE,GAAG,EACd,OAAO,CAAC,EAAE,cAAc,GACvB,OAAO;IAQV,OAAO,CAAC,gBAAgB;IAOxB;;OAEG;IACH,OAAO,CAAC,qBAAqB;IAM7B;;OAEG;IACH,OAAO,CAAC,oBAAoB;IAQ5B;;;OAGG;IACH,OAAO,CAAC,qBAAqB;IAwG7B,OAAO,CAAC,WAAW;IA2BnB,OAAO,CAAC,QAAQ;CAmNjB"} \ No newline at end of file diff --git a/lib/api/user-agent.js b/lib/api/user-agent.js deleted file mode 100644 index 8a15bf2ac..000000000 --- a/lib/api/user-agent.js +++ /dev/null @@ -1,711 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var events_1 = require("events"); -var core_1 = require("../core"); -var utils_1 = require("../core/messages/utils"); -var Enums_1 = require("../Enums"); -var Parser_1 = require("../Parser"); -var version_1 = require("../version"); -var SessionDescriptionHandler_1 = require("../Web/SessionDescriptionHandler"); -var Transport_1 = require("../Web/Transport"); -var invitation_1 = require("./invitation"); -var inviter_1 = require("./inviter"); -var message_1 = require("./message"); -var notification_1 = require("./notification"); -var session_state_1 = require("./session-state"); -var user_agent_options_1 = require("./user-agent-options"); -var user_agent_state_1 = require("./user-agent-state"); -/** - * A user agent sends and receives requests using a `Transport`. - * - * @remarks - * A user agent (UA) is associated with a user via the user's SIP address of record (AOR) - * and acts on behalf of that user to send and receive SIP requests. The user agent can - * register to receive incoming requests, as well as create and send outbound messages. - * The user agent also maintains the Transport over which its signaling travels. - * - * @public - */ -var UserAgent = /** @class */ (function () { - /** - * Constructs a new instance of the `UserAgent` class. - * @param options - Options bucket. See {@link UserAgentOptions} for details. - */ - function UserAgent(options) { - var _this = this; - if (options === void 0) { options = {}; } - /** @internal */ - this.data = {}; - /** @internal */ - this.applicants = {}; - /** @internal */ - this.publishers = {}; - /** @internal */ - this.registerers = {}; - /** @internal */ - this.sessions = {}; - /** @internal */ - this.subscriptions = {}; - /** @internal */ - this.status = Enums_1.UAStatus.STATUS_INIT; - /** LoggerFactory. */ - this.loggerFactory = new core_1.LoggerFactory(); - this._state = user_agent_state_1.UserAgentState.Initial; - this._stateEventEmitter = new events_1.EventEmitter(); - /** Unload listener. */ - this.unloadListener = (function () { _this.stop(); }); - // initialize delegate - this.delegate = options.delegate; - // initialize configuration - this.options = tslib_1.__assign({}, UserAgent.defaultOptions, { sipjsId: utils_1.createRandomToken(5) }, { uri: new core_1.URI("sip", "anonymous." + utils_1.createRandomToken(6), "anonymous.invalid") }, { viaHost: utils_1.createRandomToken(12) + ".invalid" }, options); - // viaHost is hack - if (this.options.hackIpInContact) { - if (typeof this.options.hackIpInContact === "boolean" && this.options.hackIpInContact) { - var from = 1; - var to = 254; - var octet = Math.floor(Math.random() * (to - from + 1) + from); - // random Test-Net IP (http://tools.ietf.org/html/rfc5735) - this.options.viaHost = "192.0.2." + octet; - } - else if (this.options.hackIpInContact) { - this.options.viaHost = this.options.hackIpInContact; - } - } - // initialize logger & logger factory - this.logger = this.loggerFactory.getLogger("sip.UserAgent"); - this.loggerFactory.builtinEnabled = this.options.logBuiltinEnabled; - this.loggerFactory.connector = this.options.logConnector; - switch (this.options.logLevel) { - case "error": - this.loggerFactory.level = core_1.Levels.error; - break; - case "warn": - this.loggerFactory.level = core_1.Levels.warn; - break; - case "log": - this.loggerFactory.level = core_1.Levels.log; - break; - case "debug": - this.loggerFactory.level = core_1.Levels.debug; - break; - default: - break; - } - if (this.options.logConfiguration) { - this.logger.log("Configuration:"); - for (var _i = 0, _a = Object.entries(this.options); _i < _a.length; _i++) { - var _b = _a[_i], key = _b[0], value = _b[1]; - switch (key) { - case "uri": - case "sessionDescriptionHandlerFactory": - this.logger.log("· " + key + ": " + value); - break; - case "authorizationPassword": - this.logger.log("· " + key + ": " + "NOT SHOWN"); - break; - case "transportConstructor": - this.logger.log("· " + key + ": " + value.name); - break; - default: - this.logger.log("· " + key + ": " + JSON.stringify(value)); - } - } - } - // initialize transport - this.transport = new this.options.transportConstructor(this.getLogger("sip.transport"), this.options.transportOptions); - // initialize contact - this.contact = this.initContact(); - // initialize core - this.userAgentCore = this.initCore(); - if (this.options.autoStart) { - this.start(); - } - } - /** - * Create a URI instance from a string. - * @param uri - The string to parse. - * - * @example - * ```ts - * const uri = UserAgent.makeURI("sip:edgar@example.com"); - * ``` - */ - UserAgent.makeURI = function (uri) { - return core_1.Grammar.URIParse(uri); - }; - Object.defineProperty(UserAgent.prototype, "configuration", { - /** - * User agent configuration. - */ - get: function () { - return this.options; - }, - enumerable: true, - configurable: true - }); - /** - * Connect user agent to network transport. - * @remarks - * Connect to the WS server if status = STATUS_INIT. - * Resume UA after being closed. - */ - UserAgent.prototype.start = function () { - this.logger.log("user requested startup..."); - if (this.status === Enums_1.UAStatus.STATUS_INIT) { - this.status = Enums_1.UAStatus.STATUS_STARTING; - this.setTransportListeners(); - return this.transport.connect(); - } - else if (this.status === Enums_1.UAStatus.STATUS_USER_CLOSED) { - this.logger.log("resuming"); - this.status = Enums_1.UAStatus.STATUS_READY; - return this.transport.connect(); - } - else if (this.status === Enums_1.UAStatus.STATUS_STARTING) { - this.logger.log("UA is in STARTING status, not opening new connection"); - } - else if (this.status === Enums_1.UAStatus.STATUS_READY) { - this.logger.log("UA is in READY status, not resuming"); - } - else { - this.logger.error("Connection is down. Auto-Recovery system is trying to connect"); - } - if (this.options.autoStop) { - // Google Chrome Packaged Apps don't allow 'unload' listeners: unload is not available in packaged apps - var googleChromePackagedApp = typeof chrome !== "undefined" && chrome.app && chrome.app.runtime ? true : false; - if (typeof window !== "undefined" && - typeof window.addEventListener === "function" && - !googleChromePackagedApp) { - window.addEventListener("unload", this.unloadListener); - } - } - return Promise.resolve(); - }; - /** - * Gracefully close. - * Gracefully disconnect from network transport. - * @remarks - * Unregisters and terminates active sessions/subscriptions. - */ - UserAgent.prototype.stop = function () { - return tslib_1.__awaiter(this, void 0, void 0, function () { - var _a, _b, _i, id, id, session, subscription, publisher, applicant, googleChromePackagedApp; - return tslib_1.__generator(this, function (_c) { - switch (_c.label) { - case 0: - this.logger.log("Stopping user agent " + this.configuration.uri + "..."); - if (this.status === Enums_1.UAStatus.STATUS_USER_CLOSED) { - this.logger.warn("UA already closed"); - } - _a = []; - for (_b in this.registerers) - _a.push(_b); - _i = 0; - _c.label = 1; - case 1: - if (!(_i < _a.length)) return [3 /*break*/, 4]; - id = _a[_i]; - if (!this.registerers[id]) return [3 /*break*/, 3]; - return [4 /*yield*/, this.registerers[id].dispose()]; - case 2: - _c.sent(); - _c.label = 3; - case 3: - _i++; - return [3 /*break*/, 1]; - case 4: - // End every Session - for (id in this.sessions) { - if (this.sessions[id]) { - this.logger.log("closing session " + id); - session = this.sessions[id]; - switch (session.state) { - case session_state_1.SessionState.Initial: - case session_state_1.SessionState.Establishing: - if (session instanceof invitation_1.Invitation) { - session.reject(); - } - if (session instanceof inviter_1.Inviter) { - session.cancel(); - } - break; - case session_state_1.SessionState.Established: - session.bye(); - break; - case session_state_1.SessionState.Terminating: - case session_state_1.SessionState.Terminated: - default: - break; - } - } - } - // Run unsubscribe on every Subscription - for (subscription in this.subscriptions) { - if (this.subscriptions[subscription]) { - this.logger.log("unsubscribe " + subscription); - this.subscriptions[subscription].unsubscribe(); - } - } - // Run close on every Publisher - for (publisher in this.publishers) { - if (this.publishers[publisher]) { - this.logger.log("unpublish " + publisher); - this.publishers[publisher].close(); - } - } - // Run close on every applicant - for (applicant in this.applicants) { - if (this.applicants[applicant]) { - this.applicants[applicant].close(); - } - } - this.status = Enums_1.UAStatus.STATUS_USER_CLOSED; - // Disconnect the transport and reset user agent core - this.transport.disconnect(); - this.userAgentCore.reset(); - if (this.options.autoStop) { - googleChromePackagedApp = typeof chrome !== "undefined" && chrome.app && chrome.app.runtime ? true : false; - if (typeof window !== "undefined" && - window.removeEventListener && - !googleChromePackagedApp) { - window.removeEventListener("unload", this.unloadListener); - } - } - return [2 /*return*/, Promise.resolve()]; - } - }); - }); - }; - /** @internal */ - UserAgent.prototype.findSession = function (request) { - return this.sessions[request.callId + request.fromTag] || - this.sessions[request.callId + request.toTag] || - undefined; - }; - /** @internal */ - UserAgent.prototype.getLogger = function (category, label) { - return this.loggerFactory.getLogger(category, label); - }; - /** @internal */ - UserAgent.prototype.getLoggerFactory = function () { - return this.loggerFactory; - }; - /** @internal */ - UserAgent.prototype.getSupportedResponseOptions = function () { - var optionTags = []; - if (this.contact.pubGruu || this.contact.tempGruu) { - optionTags.push("gruu"); - } - if (this.options.sipExtension100rel === user_agent_options_1.SIPExtension.Supported) { - optionTags.push("100rel"); - } - if (this.options.sipExtensionReplaces === user_agent_options_1.SIPExtension.Supported) { - optionTags.push("replaces"); - } - optionTags.push("outbound"); - optionTags = optionTags.concat(this.options.sipExtensionExtraSupported || []); - var allowUnregistered = this.options.hackAllowUnregisteredOptionTags || false; - var optionTagSet = {}; - optionTags = optionTags.filter(function (optionTag) { - var registered = user_agent_options_1.UserAgentRegisteredOptionTags[optionTag]; - var unique = !optionTagSet[optionTag]; - optionTagSet[optionTag] = true; - return (registered || allowUnregistered) && unique; - }); - return optionTags; - }; - /** @internal */ - UserAgent.prototype.makeInviter = function (targetURI, options) { - return new inviter_1.Inviter(this, targetURI, options); - }; - // ============================== - // Event Handlers - // ============================== - UserAgent.prototype.onTransportError = function () { - if (this.status === Enums_1.UAStatus.STATUS_USER_CLOSED) { - return; - } - this.status = Enums_1.UAStatus.STATUS_NOT_READY; - }; - /** - * Helper function. Sets transport listeners - */ - UserAgent.prototype.setTransportListeners = function () { - var _this = this; - this.transport.on("connected", function () { return _this.onTransportConnected(); }); - this.transport.on("message", function (message) { return _this.onTransportReceiveMsg(message); }); - this.transport.on("transportError", function () { return _this.onTransportError(); }); - }; - /** - * Transport connection event. - */ - UserAgent.prototype.onTransportConnected = function () { - // if (this.configuration.register) { - // // In an effor to maintain behavior from when we "initialized" an - // // authentication factory, this is in a Promise.then - // Promise.resolve().then(() => this.registerer.register()); - // } - }; - /** - * Handle SIP message received from the transport. - * @param messageString - The message. - */ - UserAgent.prototype.onTransportReceiveMsg = function (messageString) { - var _this = this; - var message = Parser_1.Parser.parseMessage(messageString, this.getLogger("sip.parser")); - if (!message) { - this.logger.warn("Failed to parse incoming message. Dropping."); - return; - } - if (this.status === Enums_1.UAStatus.STATUS_USER_CLOSED && message instanceof core_1.IncomingRequestMessage) { - this.logger.warn("Received " + message.method + " request in state USER_CLOSED. Dropping."); - return; - } - // A valid SIP request formulated by a UAC MUST, at a minimum, contain - // the following header fields: To, From, CSeq, Call-ID, Max-Forwards, - // and Via; all of these header fields are mandatory in all SIP - // requests. - // https://tools.ietf.org/html/rfc3261#section-8.1.1 - var hasMinimumHeaders = function () { - var mandatoryHeaders = ["from", "to", "call_id", "cseq", "via"]; - for (var _i = 0, mandatoryHeaders_1 = mandatoryHeaders; _i < mandatoryHeaders_1.length; _i++) { - var header = mandatoryHeaders_1[_i]; - if (!message.hasHeader(header)) { - _this.logger.warn("Missing mandatory header field : " + header + "."); - return false; - } - } - return true; - }; - // Request Checks - if (message instanceof core_1.IncomingRequestMessage) { - // This is port of SanityCheck.minimumHeaders(). - if (!hasMinimumHeaders()) { - this.logger.warn("Request missing mandatory header field. Dropping."); - return; - } - // FIXME: This is non-standard and should be a configruable behavior (desirable regardless). - // Custom SIP.js check to reject request from ourself (this instance of SIP.js). - // This is port of SanityCheck.rfc3261_16_3_4(). - if (!message.toTag && message.callId.substr(0, 5) === this.options.sipjsId) { - this.userAgentCore.replyStateless(message, { statusCode: 482 }); - return; - } - // FIXME: This should be Transport check before we get here (Section 18). - // Custom SIP.js check to reject requests if body length wrong. - // This is port of SanityCheck.rfc3261_18_3_request(). - var len = utils_1.str_utf8_length(message.body); - var contentLength = message.getHeader("content-length"); - if (contentLength && len < Number(contentLength)) { - this.userAgentCore.replyStateless(message, { statusCode: 400 }); - return; - } - } - // Reponse Checks - if (message instanceof core_1.IncomingResponseMessage) { - // This is port of SanityCheck.minimumHeaders(). - if (!hasMinimumHeaders()) { - this.logger.warn("Response missing mandatory header field. Dropping."); - return; - } - // Custom SIP.js check to drop responses if multiple Via headers. - // This is port of SanityCheck.rfc3261_8_1_3_3(). - if (message.getHeaders("via").length > 1) { - this.logger.warn("More than one Via header field present in the response. Dropping."); - return; - } - // FIXME: This should be Transport check before we get here (Section 18). - // Custom SIP.js check to drop responses if bad Via header. - // This is port of SanityCheck.rfc3261_18_1_2(). - if (message.via.host !== this.options.viaHost || message.via.port !== undefined) { - this.logger.warn("Via sent-by in the response does not match UA Via host value. Dropping."); - return; - } - // FIXME: This should be Transport check before we get here (Section 18). - // Custom SIP.js check to reject requests if body length wrong. - // This is port of SanityCheck.rfc3261_18_3_response(). - var len = utils_1.str_utf8_length(message.body); - var contentLength = message.getHeader("content-length"); - if (contentLength && len < Number(contentLength)) { - this.logger.warn("Message body length is lower than the value in Content-Length header field. Dropping."); - return; - } - } - // Handle Request - if (message instanceof core_1.IncomingRequestMessage) { - this.userAgentCore.receiveIncomingRequestFromTransport(message); - return; - } - // Handle Response - if (message instanceof core_1.IncomingResponseMessage) { - this.userAgentCore.receiveIncomingResponseFromTransport(message); - return; - } - throw new Error("Invalid message type."); - }; - UserAgent.prototype.initContact = function () { - var _this = this; - var contactName = utils_1.createRandomToken(8); // FIXME: should be configurable - var contactTransport = this.options.hackWssInTransport ? "wss" : "ws"; // FIXME: clearly broken for non ws transports - var contact = { - pubGruu: undefined, - tempGruu: undefined, - uri: new core_1.URI("sip", contactName, this.options.viaHost, undefined, { transport: contactTransport }), - toString: function (contactToStringOptions) { - if (contactToStringOptions === void 0) { contactToStringOptions = {}; } - var anonymous = contactToStringOptions.anonymous || false; - var outbound = contactToStringOptions.outbound || false; - var contactString = "<"; - if (anonymous) { - contactString += _this.contact.tempGruu || "sip:anonymous@anonymous.invalid;transport=" + contactTransport; - } - else { - contactString += _this.contact.pubGruu || _this.contact.uri; - } - if (outbound) { - contactString += ";ob"; - } - contactString += ">"; - return contactString; - } - }; - return contact; - }; - UserAgent.prototype.initCore = function () { - var _this = this; - // supported options - var supportedOptionTags = []; - supportedOptionTags.push("outbound"); // TODO: is this really supported? - if (this.options.sipExtension100rel === user_agent_options_1.SIPExtension.Supported) { - supportedOptionTags.push("100rel"); - } - if (this.options.sipExtensionReplaces === user_agent_options_1.SIPExtension.Supported) { - supportedOptionTags.push("replaces"); - } - if (this.options.sipExtensionExtraSupported) { - supportedOptionTags.push.apply(supportedOptionTags, this.options.sipExtensionExtraSupported); - } - if (!this.options.hackAllowUnregisteredOptionTags) { - supportedOptionTags = supportedOptionTags.filter(function (optionTag) { return user_agent_options_1.UserAgentRegisteredOptionTags[optionTag]; }); - } - supportedOptionTags = Array.from(new Set(supportedOptionTags)); // array of unique values - // FIXME: TODO: This was ported, but this is and was just plain broken. - var supportedOptionTagsResponse = supportedOptionTags.slice(); - if (this.contact.pubGruu || this.contact.tempGruu) { - supportedOptionTagsResponse.push("gruu"); - } - // core configuration - var userAgentCoreConfiguration = { - aor: this.options.uri, - contact: this.contact, - displayName: this.options.displayName, - loggerFactory: this.loggerFactory, - hackViaTcp: this.options.hackViaTcp, - routeSet: this.options.usePreloadedRoute && this.transport.server && this.transport.server.sipUri ? - [this.transport.server.sipUri] : - [], - supportedOptionTags: supportedOptionTags, - supportedOptionTagsResponse: supportedOptionTagsResponse, - sipjsId: this.options.sipjsId, - userAgentHeaderFieldValue: this.options.userAgentString, - viaForceRport: this.options.forceRport, - viaHost: this.options.viaHost, - authenticationFactory: function () { - var username = _this.options.authorizationUsername ? - _this.options.authorizationUsername : - _this.options.uri.user; // if authorization username not provided, use uri user as username - var password = _this.options.authorizationPassword ? - _this.options.authorizationPassword : - undefined; - return new core_1.DigestAuthentication(_this.getLoggerFactory(), username, password); - }, - transportAccessor: function () { return _this.transport; } - }; - var userAgentCoreDelegate = { - onInvite: function (incomingInviteRequest) { - var invitation = new invitation_1.Invitation(_this, incomingInviteRequest); - incomingInviteRequest.delegate = { - onCancel: function (cancel) { - invitation.onCancel(cancel); - }, - onTransportError: function (error) { - invitation.onTransportError(); - } - }; - // FIXME: Ported - 100 Trying send should be configurable. - // Only required if TU will not respond in 200ms. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - incomingInviteRequest.trying(); - // The Replaces header contains information used to match an existing - // SIP dialog (call-id, to-tag, and from-tag). Upon receiving an INVITE - // with a Replaces header, the User Agent (UA) attempts to match this - // information with a confirmed or early dialog. - // https://tools.ietf.org/html/rfc3891#section-3 - if (_this.options.sipExtensionReplaces !== user_agent_options_1.SIPExtension.Unsupported) { - var message = incomingInviteRequest.message; - var replaces = message.parseHeader("replaces"); - if (replaces) { - var callId = replaces.call_id; - if (typeof callId !== "string") { - throw new Error("Type of call id is not string"); - } - var toTag = replaces.replaces_to_tag; - if (typeof toTag !== "string") { - throw new Error("Type of to tag is not string"); - } - var fromTag = replaces.replaces_from_tag; - if (typeof fromTag !== "string") { - throw new Error("type of from tag is not string"); - } - var targetDialogId = callId + toTag + fromTag; - var targetDialog = _this.userAgentCore.dialogs.get(targetDialogId); - // If no match is found, the UAS rejects the INVITE and returns a 481 - // Call/Transaction Does Not Exist response. Likewise, if the Replaces - // header field matches a dialog which was not created with an INVITE, - // the UAS MUST reject the request with a 481 response. - // https://tools.ietf.org/html/rfc3891#section-3 - if (!targetDialog) { - invitation.reject({ statusCode: 481 }); - return; - } - // If the Replaces header field matches a confirmed dialog, it checks - // for the presence of the "early-only" flag in the Replaces header - // field. (This flag allows the UAC to prevent a potentially - // undesirable race condition described in Section 7.1.) If the flag is - // present, the UA rejects the request with a 486 Busy response. - // https://tools.ietf.org/html/rfc3891#section-3 - if (!targetDialog.early && replaces.early_only === true) { - invitation.reject({ statusCode: 486 }); - return; - } - // Provide a handle on the session being replaced. - var targetSession = _this.sessions[callId + fromTag] || _this.sessions[callId + toTag] || undefined; - if (!targetSession) { - throw new Error("Session does not exist."); - } - invitation.replacee = targetSession; - } - } - // A common scenario occurs when the callee is currently not willing or - // able to take additional calls at this end system. A 486 (Busy Here) - // SHOULD be returned in such a scenario. - // https://tools.ietf.org/html/rfc3261#section-13.3.1.3 - if (!_this.delegate || !_this.delegate.onInvite) { - invitation.reject({ statusCode: 486 }); - return; - } - // Delegate invitation handling. - if (!invitation.autoSendAnInitialProvisionalResponse) { - _this.delegate.onInvite(invitation); - } - else { - var onInvite_1 = _this.delegate.onInvite; - invitation.progress() - .then(function () { return onInvite_1(invitation); }); - } - }, - onMessage: function (incomingMessageRequest) { - if (_this.delegate && _this.delegate.onMessage) { - var message = new message_1.Message(incomingMessageRequest); - _this.delegate.onMessage(message); - } - else { - // Accept the MESSAGE request, but do nothing with it. - incomingMessageRequest.accept(); - } - }, - onNotify: function (incomingNotifyRequest) { - // NOTIFY requests are sent to inform subscribers of changes in state to - // which the subscriber has a subscription. Subscriptions are created - // using the SUBSCRIBE method. In legacy implementations, it is - // possible that other means of subscription creation have been used. - // However, this specification does not allow the creation of - // subscriptions except through SUBSCRIBE requests and (for backwards- - // compatibility) REFER requests [RFC3515]. - // https://tools.ietf.org/html/rfc6665#section-3.2 - if (_this.delegate && _this.delegate.onNotify) { - var notification = new notification_1.Notification(incomingNotifyRequest); - _this.delegate.onNotify(notification); - } - else { - // Per the above which sbsoletes https://tools.ietf.org/html/rfc3265, - // the use of out of dialog NOTIFY is obsolete, but... - if (_this.options.allowLegacyNotifications) { - incomingNotifyRequest.accept(); // Accept the NOTIFY request, but do nothing with it. - } - else { - incomingNotifyRequest.reject({ statusCode: 481 }); - } - } - }, - onRefer: function (incomingReferRequest) { - _this.logger.log("Received an out of dialog refer"); - if (!_this.options.allowOutOfDialogRefers) { - incomingReferRequest.reject({ statusCode: 405 }); - } - _this.logger.log("Allow out of dialog refers is enabled on the UA"); - // const referContext = new ReferServerContext(this, incomingReferRequest); - // if (this.listeners("outOfDialogReferRequested").length) { - // this.emit("outOfDialogReferRequested", referContext); - // } else { - // this.logger.log( - // "No outOfDialogReferRequest listeners, automatically accepting and following the out of dialog refer" - // ); - // referContext.accept({ followRefer: true }); - // } - // if (this.delegate && this.delegate.onRefer) { - // this.delegate.onRefer(incomingReferRequest); - // } - }, - onRegister: function (incomingRegisterRequest) { - // TOOD: this.delegate.onRegister(...) - if (_this.delegate && _this.delegate.onRegisterRequest) { - _this.delegate.onRegisterRequest(incomingRegisterRequest); - } - }, - onSubscribe: function (incomingSubscribeRequest) { - // TOOD: this.delegate.onSubscribe(...) - if (_this.delegate && _this.delegate.onSubscribeRequest) { - _this.delegate.onSubscribeRequest(incomingSubscribeRequest); - } - } - }; - return new core_1.UserAgentCore(userAgentCoreConfiguration, userAgentCoreDelegate); - }; - /** Default user agent options. */ - UserAgent.defaultOptions = { - allowLegacyNotifications: false, - allowOutOfDialogRefers: false, - authorizationPassword: "", - authorizationUsername: "", - autoStart: false, - autoStop: true, - delegate: {}, - displayName: "", - forceRport: false, - hackAllowUnregisteredOptionTags: false, - hackIpInContact: false, - hackViaTcp: false, - hackWssInTransport: false, - logBuiltinEnabled: true, - logConfiguration: true, - logConnector: function () { }, - logLevel: "log", - noAnswerTimeout: 60, - sessionDescriptionHandlerFactory: SessionDescriptionHandler_1.SessionDescriptionHandler.defaultFactory, - sessionDescriptionHandlerFactoryOptions: {}, - sipExtension100rel: user_agent_options_1.SIPExtension.Unsupported, - sipExtensionReplaces: user_agent_options_1.SIPExtension.Unsupported, - sipExtensionExtraSupported: [], - sipjsId: "", - transportConstructor: Transport_1.Transport, - transportOptions: {}, - uri: new core_1.URI("sip", "anonymous", "anonymous.invalid"), - usePreloadedRoute: false, - userAgentString: "SIP.js/" + version_1.LIBRARY_VERSION, - viaHost: "" - }; - return UserAgent; -}()); -exports.UserAgent = UserAgent; diff --git a/lib/core/dialogs/dialog-state.d.ts b/lib/core/dialogs/dialog-state.d.ts deleted file mode 100644 index 27fd3e391..000000000 --- a/lib/core/dialogs/dialog-state.d.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { URI } from "../messages/uri"; -/** - * Dialog state. - * @remarks - * A dialog contains certain pieces of state needed for further message - * transmissions within the dialog. This state consists of the dialog - * ID, a local sequence number (used to order requests from the UA to - * its peer), a remote sequence number (used to order requests from its - * peer to the UA), a local URI, a remote URI, remote target, a boolean - * flag called "secure", and a route set, which is an ordered list of - * URIs. The route set is the list of servers that need to be traversed - * to send a request to the peer. A dialog can also be in the "early" - * state, which occurs when it is created with a provisional response, - * and then transition to the "confirmed" state when a 2xx final - * response arrives. For other responses, or if no response arrives at - * all on that dialog, the early dialog terminates. - * - * https://tools.ietf.org/html/rfc3261#section-12 - * @public - */ -export interface DialogState { - id: string; - early: boolean; - callId: string; - localTag: string; - remoteTag: string; - localSequenceNumber: number | undefined; - remoteSequenceNumber: number | undefined; - localURI: URI; - remoteURI: URI; - remoteTarget: URI; - routeSet: Array; - secure: boolean; -} -//# sourceMappingURL=dialog-state.d.ts.map \ No newline at end of file diff --git a/lib/core/dialogs/dialog-state.d.ts.map b/lib/core/dialogs/dialog-state.d.ts.map deleted file mode 100644 index cd3d03543..000000000 --- a/lib/core/dialogs/dialog-state.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"dialog-state.d.ts","sourceRoot":"","sources":["../../../src/core/dialogs/dialog-state.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAEtC;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,WAAW,WAAW;IAC1B,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,OAAO,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,mBAAmB,EAAE,MAAM,GAAG,SAAS,CAAC;IACxC,oBAAoB,EAAE,MAAM,GAAG,SAAS,CAAC;IACzC,QAAQ,EAAE,GAAG,CAAC;IACd,SAAS,EAAE,GAAG,CAAC;IACf,YAAY,EAAE,GAAG,CAAC;IAClB,QAAQ,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IACxB,MAAM,EAAE,OAAO,CAAC;CACjB"} \ No newline at end of file diff --git a/lib/core/dialogs/dialog-state.js b/lib/core/dialogs/dialog-state.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/core/dialogs/dialog-state.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/core/dialogs/dialog.d.ts b/lib/core/dialogs/dialog.d.ts deleted file mode 100644 index 46454c4a0..000000000 --- a/lib/core/dialogs/dialog.d.ts +++ /dev/null @@ -1,155 +0,0 @@ -import { Body, IncomingRequestMessage, IncomingResponseMessage, OutgoingRequestMessage, URI } from "../messages"; -import { UserAgentCore } from "../user-agent-core"; -import { DialogState } from "./dialog-state"; -/** - * Dialog. - * @remarks - * A key concept for a user agent is that of a dialog. A dialog - * represents a peer-to-peer SIP relationship between two user agents - * that persists for some time. The dialog facilitates sequencing of - * messages between the user agents and proper routing of requests - * between both of them. The dialog represents a context in which to - * interpret SIP messages. - * https://tools.ietf.org/html/rfc3261#section-12 - * @public - */ -export declare class Dialog { - protected core: UserAgentCore; - protected dialogState: DialogState; - /** - * When a UAC receives a response that establishes a dialog, it - * constructs the state of the dialog. This state MUST be maintained - * for the duration of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.1.2 - * @param outgoingRequestMessage - Outgoing request message for dialog. - * @param incomingResponseMessage - Incoming response message creating dialog. - */ - static initialDialogStateForUserAgentClient(outgoingRequestMessage: OutgoingRequestMessage, incomingResponseMessage: IncomingResponseMessage): DialogState; - /** - * The UAS then constructs the state of the dialog. This state MUST be - * maintained for the duration of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.1.1 - * @param incomingRequestMessage - Incoming request message creating dialog. - * @param toTag - Tag in the To field in the response to the incoming request. - */ - static initialDialogStateForUserAgentServer(incomingRequestMessage: IncomingRequestMessage, toTag: string, early?: boolean): DialogState; - /** - * Dialog constructor. - * @param core - User agent core. - * @param dialogState - Initial dialog state. - */ - protected constructor(core: UserAgentCore, dialogState: DialogState); - /** Destructor. */ - dispose(): void; - /** - * A dialog is identified at each UA with a dialog ID, which consists of - * a Call-ID value, a local tag and a remote tag. The dialog ID at each - * UA involved in the dialog is not the same. Specifically, the local - * tag at one UA is identical to the remote tag at the peer UA. The - * tags are opaque tokens that facilitate the generation of unique - * dialog IDs. - * https://tools.ietf.org/html/rfc3261#section-12 - */ - readonly id: string; - /** - * A dialog can also be in the "early" state, which occurs when it is - * created with a provisional response, and then it transition to the - * "confirmed" state when a 2xx final response received or is sent. - * - * Note: RFC 3261 is concise on when a dialog is "confirmed", but it - * can be a point of confusion if an INVITE dialog is "confirmed" after - * a 2xx is sent or after receiving the ACK for the 2xx response. - * With careful reading it can be inferred a dialog is always is - * "confirmed" when the 2xx is sent (regardless of type of dialog). - * However a INVITE dialog does have additional considerations - * when it is confirmed but an ACK has not yet been received (in - * particular with regard to a callee sending BYE requests). - */ - readonly early: boolean; - /** Call identifier component of the dialog id. */ - readonly callId: string; - /** Local tag component of the dialog id. */ - readonly localTag: string; - /** Remote tag component of the dialog id. */ - readonly remoteTag: string; - /** Local sequence number (used to order requests from the UA to its peer). */ - readonly localSequenceNumber: number | undefined; - /** Remote sequence number (used to order requests from its peer to the UA). */ - readonly remoteSequenceNumber: number | undefined; - /** Local URI. */ - readonly localURI: URI; - /** Remote URI. */ - readonly remoteURI: URI; - /** Remote target. */ - readonly remoteTarget: URI; - /** - * Route set, which is an ordered list of URIs. The route set is the - * list of servers that need to be traversed to send a request to the peer. - */ - readonly routeSet: Array; - /** - * If the request was sent over TLS, and the Request-URI contained - * a SIPS URI, the "secure" flag is set to true. *NOT IMPLEMENTED* - */ - readonly secure: boolean; - /** The user agent core servicing this dialog. */ - readonly userAgentCore: UserAgentCore; - /** Confirm the dialog. Only matters if dialog is currently early. */ - confirm(): void; - /** - * Requests sent within a dialog, as any other requests, are atomic. If - * a particular request is accepted by the UAS, all the state changes - * associated with it are performed. If the request is rejected, none - * of the state changes are performed. - * - * Note that some requests, such as INVITEs, affect several pieces of - * state. - * - * https://tools.ietf.org/html/rfc3261#section-12.2.2 - * @param message - Incoming request message within this dialog. - */ - receiveRequest(message: IncomingRequestMessage): void; - /** - * If the dialog identifier in the 2xx response matches the dialog - * identifier of an existing dialog, the dialog MUST be transitioned to - * the "confirmed" state, and the route set for the dialog MUST be - * recomputed based on the 2xx response using the procedures of Section - * 12.2.1.2. Otherwise, a new dialog in the "confirmed" state MUST be - * constructed using the procedures of Section 12.1.2. - * - * Note that the only piece of state that is recomputed is the route - * set. Other pieces of state such as the highest sequence numbers - * (remote and local) sent within the dialog are not recomputed. The - * route set only is recomputed for backwards compatibility. RFC - * 2543 did not mandate mirroring of the Record-Route header field in - * a 1xx, only 2xx. However, we cannot update the entire state of - * the dialog, since mid-dialog requests may have been sent within - * the early dialog, modifying the sequence numbers, for example. - * - * https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - */ - recomputeRouteSet(message: IncomingResponseMessage): void; - /** - * A request within a dialog is constructed by using many of the - * components of the state stored as part of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - * @param method - Outgoing request method. - */ - createOutgoingRequestMessage(method: string, options?: { - cseq?: number; - extraHeaders?: Array; - body?: Body; - }): OutgoingRequestMessage; - /** - * If the remote sequence number was not empty, but the sequence number - * of the request is lower than the remote sequence number, the request - * is out of order and MUST be rejected with a 500 (Server Internal - * Error) response. - * https://tools.ietf.org/html/rfc3261#section-12.2.2 - * @param request - Incoming request to guard. - * @returns True if the program execution is to continue in the branch in question. - * Otherwise a 500 Server Internal Error was stateless sent and request processing must stop. - */ - protected sequenceGuard(message: IncomingRequestMessage): boolean; -} -//# sourceMappingURL=dialog.d.ts.map \ No newline at end of file diff --git a/lib/core/dialogs/dialog.d.ts.map b/lib/core/dialogs/dialog.d.ts.map deleted file mode 100644 index ce4d82d3a..000000000 --- a/lib/core/dialogs/dialog.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"dialog.d.ts","sourceRoot":"","sources":["../../../src/core/dialogs/dialog.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,IAAI,EAEJ,sBAAsB,EACtB,uBAAuB,EAEvB,sBAAsB,EACtB,GAAG,EACJ,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAE7C;;;;;;;;;;;GAWG;AACH,qBAAa,MAAM;IA8Lf,SAAS,CAAC,IAAI,EAAE,aAAa;IAC7B,SAAS,CAAC,WAAW,EAAE,WAAW;IA7LpC;;;;;;;OAOG;WACW,oCAAoC,CAChD,sBAAsB,EAAE,sBAAsB,EAC9C,uBAAuB,EAAE,uBAAuB,GAC/C,WAAW;IA4Fd;;;;;;OAMG;WACW,oCAAoC,CAChD,sBAAsB,EAAE,sBAAsB,EAC9C,KAAK,EAAE,MAAM,EACb,KAAK,GAAE,OAAe,GACrB,WAAW;IAoEd;;;;OAIG;IACH,SAAS,aACG,IAAI,EAAE,aAAa,EACnB,WAAW,EAAE,WAAW;IAKpC,kBAAkB;IACX,OAAO,IAAI,IAAI;IAItB;;;;;;;;OAQG;aACQ,EAAE,EAAI,MAAM;IAIvB;;;;;;;;;;;;;OAaG;aACQ,KAAK,EAAI,OAAO;IAI3B,kDAAkD;aACvC,MAAM,EAAI,MAAM;IAI3B,4CAA4C;aACjC,QAAQ,EAAI,MAAM;IAI7B,6CAA6C;aAClC,SAAS,EAAI,MAAM;IAI9B,8EAA8E;aACnE,mBAAmB,EAAI,MAAM,GAAG,SAAS;IAIpD,+EAA+E;aACpE,oBAAoB,EAAI,MAAM,GAAG,SAAS;IAIrD,iBAAiB;aACN,QAAQ,EAAI,GAAG;IAI1B,kBAAkB;aACP,SAAS,EAAI,GAAG;IAI3B,qBAAqB;aACV,YAAY,EAAI,GAAG;IAI9B;;;OAGG;aACQ,QAAQ,EAAI,KAAK,CAAC,MAAM,CAAC;IAIpC;;;OAGG;aACQ,MAAM,EAAI,OAAO;IAI5B,iDAAiD;aACtC,aAAa,EAAI,aAAa;IAIzC,qEAAqE;IAC9D,OAAO,IAAI,IAAI;IAItB;;;;;;;;;;;OAWG;IACI,cAAc,CAAC,OAAO,EAAE,sBAAsB,GAAG,IAAI;IAkD5D;;;;;;;;;;;;;;;;;;OAkBG;IACI,iBAAiB,CAAC,OAAO,EAAE,uBAAuB,GAAG,IAAI;IAIhE;;;;;OAKG;IACI,4BAA4B,CACjC,MAAM,EAAE,MAAM,EACd,OAAO,CAAC,EAAE;QACR,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,YAAY,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;QAC7B,IAAI,CAAC,EAAE,IAAI,CAAC;KACb,GACA,sBAAsB;IAkHzB;;;;;;;;;OASG;IACH,SAAS,CAAC,aAAa,CAAC,OAAO,EAAE,sBAAsB,GAAG,OAAO;CAmClE"} \ No newline at end of file diff --git a/lib/core/dialogs/dialog.js b/lib/core/dialogs/dialog.js deleted file mode 100644 index 0d7b390ef..000000000 --- a/lib/core/dialogs/dialog.js +++ /dev/null @@ -1,562 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var messages_1 = require("../messages"); -/** - * Dialog. - * @remarks - * A key concept for a user agent is that of a dialog. A dialog - * represents a peer-to-peer SIP relationship between two user agents - * that persists for some time. The dialog facilitates sequencing of - * messages between the user agents and proper routing of requests - * between both of them. The dialog represents a context in which to - * interpret SIP messages. - * https://tools.ietf.org/html/rfc3261#section-12 - * @public - */ -var Dialog = /** @class */ (function () { - /** - * Dialog constructor. - * @param core - User agent core. - * @param dialogState - Initial dialog state. - */ - function Dialog(core, dialogState) { - this.core = core; - this.dialogState = dialogState; - this.core.dialogs.set(this.id, this); - } - /** - * When a UAC receives a response that establishes a dialog, it - * constructs the state of the dialog. This state MUST be maintained - * for the duration of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.1.2 - * @param outgoingRequestMessage - Outgoing request message for dialog. - * @param incomingResponseMessage - Incoming response message creating dialog. - */ - Dialog.initialDialogStateForUserAgentClient = function (outgoingRequestMessage, incomingResponseMessage) { - // If the request was sent over TLS, and the Request-URI contained a - // SIPS URI, the "secure" flag is set to TRUE. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - var secure = false; // FIXME: Currently no support for TLS. - // The route set MUST be set to the list of URIs in the Record-Route - // header field from the response, taken in reverse order and preserving - // all URI parameters. If no Record-Route header field is present in - // the response, the route set MUST be set to the empty set. This route - // set, even if empty, overrides any pre-existing route set for future - // requests in this dialog. The remote target MUST be set to the URI - // from the Contact header field of the response. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - var routeSet = incomingResponseMessage.getHeaders("record-route").reverse(); - var contact = incomingResponseMessage.parseHeader("contact"); - if (!contact) { // TODO: Review to make sure this will never happen - throw new Error("Contact undefined."); - } - if (!(contact instanceof messages_1.NameAddrHeader)) { - throw new Error("Contact not instance of NameAddrHeader."); - } - var remoteTarget = contact.uri; - // The local sequence number MUST be set to the value of the sequence - // number in the CSeq header field of the request. The remote sequence - // number MUST be empty (it is established when the remote UA sends a - // request within the dialog). The call identifier component of the - // dialog ID MUST be set to the value of the Call-ID in the request. - // The local tag component of the dialog ID MUST be set to the tag in - // the From field in the request, and the remote tag component of the - // dialog ID MUST be set to the tag in the To field of the response. A - // UAC MUST be prepared to receive a response without a tag in the To - // field, in which case the tag is considered to have a value of null. - // - // This is to maintain backwards compatibility with RFC 2543, which - // did not mandate To tags. - // - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - var localSequenceNumber = outgoingRequestMessage.cseq; - var remoteSequenceNumber = undefined; - var callId = outgoingRequestMessage.callId; - var localTag = outgoingRequestMessage.fromTag; - var remoteTag = incomingResponseMessage.toTag; - if (!callId) { // TODO: Review to make sure this will never happen - throw new Error("Call id undefined."); - } - if (!localTag) { // TODO: Review to make sure this will never happen - throw new Error("From tag undefined."); - } - if (!remoteTag) { // TODO: Review to make sure this will never happen - throw new Error("To tag undefined."); // FIXME: No backwards compatibility with RFC 2543 - } - // The remote URI MUST be set to the URI in the To field, and the local - // URI MUST be set to the URI in the From field. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - if (!outgoingRequestMessage.from) { // TODO: Review to make sure this will never happen - throw new Error("From undefined."); - } - if (!outgoingRequestMessage.to) { // TODO: Review to make sure this will never happen - throw new Error("To undefined."); - } - var localURI = outgoingRequestMessage.from.uri; - var remoteURI = outgoingRequestMessage.to.uri; - // A dialog can also be in the "early" state, which occurs when it is - // created with a provisional response, and then transition to the - // "confirmed" state when a 2xx final response arrives. - // https://tools.ietf.org/html/rfc3261#section-12 - if (!incomingResponseMessage.statusCode) { - throw new Error("Incoming response status code undefined."); - } - var early = incomingResponseMessage.statusCode < 200 ? true : false; - var dialogState = { - id: callId + localTag + remoteTag, - early: early, - callId: callId, - localTag: localTag, - remoteTag: remoteTag, - localSequenceNumber: localSequenceNumber, - remoteSequenceNumber: remoteSequenceNumber, - localURI: localURI, - remoteURI: remoteURI, - remoteTarget: remoteTarget, - routeSet: routeSet, - secure: secure - }; - return dialogState; - }; - /** - * The UAS then constructs the state of the dialog. This state MUST be - * maintained for the duration of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.1.1 - * @param incomingRequestMessage - Incoming request message creating dialog. - * @param toTag - Tag in the To field in the response to the incoming request. - */ - Dialog.initialDialogStateForUserAgentServer = function (incomingRequestMessage, toTag, early) { - if (early === void 0) { early = false; } - // If the request arrived over TLS, and the Request-URI contained a SIPS - // URI, the "secure" flag is set to TRUE. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - var secure = false; // FIXME: Currently no support for TLS. - // The route set MUST be set to the list of URIs in the Record-Route - // header field from the request, taken in order and preserving all URI - // parameters. If no Record-Route header field is present in the - // request, the route set MUST be set to the empty set. This route set, - // even if empty, overrides any pre-existing route set for future - // requests in this dialog. The remote target MUST be set to the URI - // from the Contact header field of the request. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - var routeSet = incomingRequestMessage.getHeaders("record-route"); - var contact = incomingRequestMessage.parseHeader("contact"); - if (!contact) { // TODO: Review to make sure this will never happen - throw new Error("Contact undefined."); - } - if (!(contact instanceof messages_1.NameAddrHeader)) { - throw new Error("Contact not instance of NameAddrHeader."); - } - var remoteTarget = contact.uri; - // The remote sequence number MUST be set to the value of the sequence - // number in the CSeq header field of the request. The local sequence - // number MUST be empty. The call identifier component of the dialog ID - // MUST be set to the value of the Call-ID in the request. The local - // tag component of the dialog ID MUST be set to the tag in the To field - // in the response to the request (which always includes a tag), and the - // remote tag component of the dialog ID MUST be set to the tag from the - // From field in the request. A UAS MUST be prepared to receive a - // request without a tag in the From field, in which case the tag is - // considered to have a value of null. - // - // This is to maintain backwards compatibility with RFC 2543, which - // did not mandate From tags. - // - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - var remoteSequenceNumber = incomingRequestMessage.cseq; - var localSequenceNumber = undefined; - var callId = incomingRequestMessage.callId; - var localTag = toTag; - var remoteTag = incomingRequestMessage.fromTag; - // The remote URI MUST be set to the URI in the From field, and the - // local URI MUST be set to the URI in the To field. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - var remoteURI = incomingRequestMessage.from.uri; - var localURI = incomingRequestMessage.to.uri; - var dialogState = { - id: callId + localTag + remoteTag, - early: early, - callId: callId, - localTag: localTag, - remoteTag: remoteTag, - localSequenceNumber: localSequenceNumber, - remoteSequenceNumber: remoteSequenceNumber, - localURI: localURI, - remoteURI: remoteURI, - remoteTarget: remoteTarget, - routeSet: routeSet, - secure: secure - }; - return dialogState; - }; - /** Destructor. */ - Dialog.prototype.dispose = function () { - this.core.dialogs.delete(this.id); - }; - Object.defineProperty(Dialog.prototype, "id", { - /** - * A dialog is identified at each UA with a dialog ID, which consists of - * a Call-ID value, a local tag and a remote tag. The dialog ID at each - * UA involved in the dialog is not the same. Specifically, the local - * tag at one UA is identical to the remote tag at the peer UA. The - * tags are opaque tokens that facilitate the generation of unique - * dialog IDs. - * https://tools.ietf.org/html/rfc3261#section-12 - */ - get: function () { - return this.dialogState.id; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "early", { - /** - * A dialog can also be in the "early" state, which occurs when it is - * created with a provisional response, and then it transition to the - * "confirmed" state when a 2xx final response received or is sent. - * - * Note: RFC 3261 is concise on when a dialog is "confirmed", but it - * can be a point of confusion if an INVITE dialog is "confirmed" after - * a 2xx is sent or after receiving the ACK for the 2xx response. - * With careful reading it can be inferred a dialog is always is - * "confirmed" when the 2xx is sent (regardless of type of dialog). - * However a INVITE dialog does have additional considerations - * when it is confirmed but an ACK has not yet been received (in - * particular with regard to a callee sending BYE requests). - */ - get: function () { - return this.dialogState.early; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "callId", { - /** Call identifier component of the dialog id. */ - get: function () { - return this.dialogState.callId; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "localTag", { - /** Local tag component of the dialog id. */ - get: function () { - return this.dialogState.localTag; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "remoteTag", { - /** Remote tag component of the dialog id. */ - get: function () { - return this.dialogState.remoteTag; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "localSequenceNumber", { - /** Local sequence number (used to order requests from the UA to its peer). */ - get: function () { - return this.dialogState.localSequenceNumber; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "remoteSequenceNumber", { - /** Remote sequence number (used to order requests from its peer to the UA). */ - get: function () { - return this.dialogState.remoteSequenceNumber; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "localURI", { - /** Local URI. */ - get: function () { - return this.dialogState.localURI; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "remoteURI", { - /** Remote URI. */ - get: function () { - return this.dialogState.remoteURI; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "remoteTarget", { - /** Remote target. */ - get: function () { - return this.dialogState.remoteTarget; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "routeSet", { - /** - * Route set, which is an ordered list of URIs. The route set is the - * list of servers that need to be traversed to send a request to the peer. - */ - get: function () { - return this.dialogState.routeSet; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "secure", { - /** - * If the request was sent over TLS, and the Request-URI contained - * a SIPS URI, the "secure" flag is set to true. *NOT IMPLEMENTED* - */ - get: function () { - return this.dialogState.secure; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Dialog.prototype, "userAgentCore", { - /** The user agent core servicing this dialog. */ - get: function () { - return this.core; - }, - enumerable: true, - configurable: true - }); - /** Confirm the dialog. Only matters if dialog is currently early. */ - Dialog.prototype.confirm = function () { - this.dialogState.early = false; - }; - /** - * Requests sent within a dialog, as any other requests, are atomic. If - * a particular request is accepted by the UAS, all the state changes - * associated with it are performed. If the request is rejected, none - * of the state changes are performed. - * - * Note that some requests, such as INVITEs, affect several pieces of - * state. - * - * https://tools.ietf.org/html/rfc3261#section-12.2.2 - * @param message - Incoming request message within this dialog. - */ - Dialog.prototype.receiveRequest = function (message) { - // ACK guard. - // By convention, the handling of ACKs is the responsibility - // the particular dialog implementation. For example, see SessionDialog. - // Furthermore, ACKs have same sequence number as the associated INVITE. - if (message.method === messages_1.C.ACK) { - return; - } - // If the remote sequence number was not empty, but the sequence number - // of the request is lower than the remote sequence number, the request - // is out of order and MUST be rejected with a 500 (Server Internal - // Error) response. If the remote sequence number was not empty, and - // the sequence number of the request is greater than the remote - // sequence number, the request is in order. It is possible for the - // CSeq sequence number to be higher than the remote sequence number by - // more than one. This is not an error condition, and a UAS SHOULD be - // prepared to receive and process requests with CSeq values more than - // one higher than the previous received request. The UAS MUST then set - // the remote sequence number to the value of the sequence number in the - // CSeq header field value in the request. - // - // If a proxy challenges a request generated by the UAC, the UAC has - // to resubmit the request with credentials. The resubmitted request - // will have a new CSeq number. The UAS will never see the first - // request, and thus, it will notice a gap in the CSeq number space. - // Such a gap does not represent any error condition. - // - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (this.remoteSequenceNumber) { - if (message.cseq <= this.remoteSequenceNumber) { - throw new Error("Out of sequence in dialog request. Did you forget to call sequenceGuard()?"); - } - this.dialogState.remoteSequenceNumber = message.cseq; - } - // If the remote sequence number is empty, it MUST be set to the value - // of the sequence number in the CSeq header field value in the request. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (!this.remoteSequenceNumber) { - this.dialogState.remoteSequenceNumber = message.cseq; - } - // When a UAS receives a target refresh request, it MUST replace the - // dialog's remote target URI with the URI from the Contact header field - // in that request, if present. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - // Note: "target refresh request" processing delegated to sub-class. - }; - /** - * If the dialog identifier in the 2xx response matches the dialog - * identifier of an existing dialog, the dialog MUST be transitioned to - * the "confirmed" state, and the route set for the dialog MUST be - * recomputed based on the 2xx response using the procedures of Section - * 12.2.1.2. Otherwise, a new dialog in the "confirmed" state MUST be - * constructed using the procedures of Section 12.1.2. - * - * Note that the only piece of state that is recomputed is the route - * set. Other pieces of state such as the highest sequence numbers - * (remote and local) sent within the dialog are not recomputed. The - * route set only is recomputed for backwards compatibility. RFC - * 2543 did not mandate mirroring of the Record-Route header field in - * a 1xx, only 2xx. However, we cannot update the entire state of - * the dialog, since mid-dialog requests may have been sent within - * the early dialog, modifying the sequence numbers, for example. - * - * https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - */ - Dialog.prototype.recomputeRouteSet = function (message) { - this.dialogState.routeSet = message.getHeaders("record-route").reverse(); - }; - /** - * A request within a dialog is constructed by using many of the - * components of the state stored as part of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - * @param method - Outgoing request method. - */ - Dialog.prototype.createOutgoingRequestMessage = function (method, options) { - // The URI in the To field of the request MUST be set to the remote URI - // from the dialog state. The tag in the To header field of the request - // MUST be set to the remote tag of the dialog ID. The From URI of the - // request MUST be set to the local URI from the dialog state. The tag - // in the From header field of the request MUST be set to the local tag - // of the dialog ID. If the value of the remote or local tags is null, - // the tag parameter MUST be omitted from the To or From header fields, - // respectively. - // - // Usage of the URI from the To and From fields in the original - // request within subsequent requests is done for backwards - // compatibility with RFC 2543, which used the URI for dialog - // identification. In this specification, only the tags are used for - // dialog identification. It is expected that mandatory reflection - // of the original To and From URI in mid-dialog requests will be - // deprecated in a subsequent revision of this specification. - // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - var toUri = this.remoteURI; - var toTag = this.remoteTag; - var fromUri = this.localURI; - var fromTag = this.localTag; - // The Call-ID of the request MUST be set to the Call-ID of the dialog. - // Requests within a dialog MUST contain strictly monotonically - // increasing and contiguous CSeq sequence numbers (increasing-by-one) - // in each direction (excepting ACK and CANCEL of course, whose numbers - // equal the requests being acknowledged or cancelled). Therefore, if - // the local sequence number is not empty, the value of the local - // sequence number MUST be incremented by one, and this value MUST be - // placed into the CSeq header field. If the local sequence number is - // empty, an initial value MUST be chosen using the guidelines of - // Section 8.1.1.5. The method field in the CSeq header field value - // MUST match the method of the request. - // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - var callId = this.callId; - var cseq; - if (options && options.cseq) { - cseq = options.cseq; - } - else if (!this.dialogState.localSequenceNumber) { - cseq = this.dialogState.localSequenceNumber = 1; // https://tools.ietf.org/html/rfc3261#section-8.1.1.5 - } - else { - cseq = this.dialogState.localSequenceNumber += 1; - } - // The UAC uses the remote target and route set to build the Request-URI - // and Route header field of the request. - // - // If the route set is empty, the UAC MUST place the remote target URI - // into the Request-URI. The UAC MUST NOT add a Route header field to - // the request. - // - // If the route set is not empty, and the first URI in the route set - // contains the lr parameter (see Section 19.1.1), the UAC MUST place - // the remote target URI into the Request-URI and MUST include a Route - // header field containing the route set values in order, including all - // parameters. - // - // If the route set is not empty, and its first URI does not contain the - // lr parameter, the UAC MUST place the first URI from the route set - // into the Request-URI, stripping any parameters that are not allowed - // in a Request-URI. The UAC MUST add a Route header field containing - // the remainder of the route set values in order, including all - // parameters. The UAC MUST then place the remote target URI into the - // Route header field as the last value. - // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - // The lr parameter, when present, indicates that the element - // responsible for this resource implements the routing mechanisms - // specified in this document. This parameter will be used in the - // URIs proxies place into Record-Route header field values, and - // may appear in the URIs in a pre-existing route set. - // - // This parameter is used to achieve backwards compatibility with - // systems implementing the strict-routing mechanisms of RFC 2543 - // and the rfc2543bis drafts up to bis-05. An element preparing - // to send a request based on a URI not containing this parameter - // can assume the receiving element implements strict-routing and - // reformat the message to preserve the information in the - // Request-URI. - // https://tools.ietf.org/html/rfc3261#section-19.1.1 - // NOTE: Not backwards compatible with RFC 2543 (no support for strict-routing). - var ruri = this.remoteTarget; - var routeSet = this.routeSet; - var extraHeaders = options && options.extraHeaders; - var body = options && options.body; - // The relative order of header fields with different field names is not - // significant. However, it is RECOMMENDED that header fields which are - // needed for proxy processing (Via, Route, Record-Route, Proxy-Require, - // Max-Forwards, and Proxy-Authorization, for example) appear towards - // the top of the message to facilitate rapid parsing. - // https://tools.ietf.org/html/rfc3261#section-7.3.1 - var message = this.userAgentCore.makeOutgoingRequestMessage(method, ruri, fromUri, toUri, { - callId: callId, - cseq: cseq, - fromTag: fromTag, - toTag: toTag, - routeSet: routeSet - }, extraHeaders, body); - return message; - }; - /** - * If the remote sequence number was not empty, but the sequence number - * of the request is lower than the remote sequence number, the request - * is out of order and MUST be rejected with a 500 (Server Internal - * Error) response. - * https://tools.ietf.org/html/rfc3261#section-12.2.2 - * @param request - Incoming request to guard. - * @returns True if the program execution is to continue in the branch in question. - * Otherwise a 500 Server Internal Error was stateless sent and request processing must stop. - */ - Dialog.prototype.sequenceGuard = function (message) { - // ACK guard. - // By convention, handling of unexpected ACKs is responsibility - // the particular dialog implementation. For example, see SessionDialog. - // Furthermore, we cannot reply to an "out of sequence" ACK. - if (message.method === messages_1.C.ACK) { - return true; - } - // Note: We are rejecting on "less than or equal to" the remote - // sequence number (excepting ACK whose numbers equal the requests - // being acknowledged or cancelled), which is the correct thing to - // do in our case. The only time a request with the same sequence number - // will show up here if is a) it is a very late retransmission of a - // request we already handled or b) it is a different request with the - // same sequence number which would be violation of the standard. - // Request retransmissions are absorbed by the transaction layer, - // so any request with a duplicate sequence number getting here - // would have to be a retransmission after the transaction terminated - // or a broken request (with unique via branch value). - // Requests within a dialog MUST contain strictly monotonically - // increasing and contiguous CSeq sequence numbers (increasing-by-one) - // in each direction (excepting ACK and CANCEL of course, whose numbers - // equal the requests being acknowledged or cancelled). Therefore, if - // the local sequence number is not empty, the value of the local - // sequence number MUST be incremented by one, and this value MUST be - // placed into the CSeq header field. - // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - if (this.remoteSequenceNumber && message.cseq <= this.remoteSequenceNumber) { - this.core.replyStateless(message, { statusCode: 500 }); - return false; - } - return true; - }; - return Dialog; -}()); -exports.Dialog = Dialog; diff --git a/lib/core/dialogs/index.d.ts b/lib/core/dialogs/index.d.ts deleted file mode 100644 index c09e33400..000000000 --- a/lib/core/dialogs/index.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -export * from "./dialog"; -export * from "./dialog-state"; -export * from "./session-dialog"; -export * from "./subscription-dialog"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/core/dialogs/index.d.ts.map b/lib/core/dialogs/index.d.ts.map deleted file mode 100644 index 12c5dbfac..000000000 --- a/lib/core/dialogs/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/dialogs/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAC;AACzB,cAAc,gBAAgB,CAAC;AAC/B,cAAc,kBAAkB,CAAC;AACjC,cAAc,uBAAuB,CAAC"} \ No newline at end of file diff --git a/lib/core/dialogs/index.js b/lib/core/dialogs/index.js deleted file mode 100644 index 2e8adb3a6..000000000 --- a/lib/core/dialogs/index.js +++ /dev/null @@ -1,6 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -tslib_1.__exportStar(require("./dialog"), exports); -tslib_1.__exportStar(require("./session-dialog"), exports); -tslib_1.__exportStar(require("./subscription-dialog"), exports); diff --git a/lib/core/dialogs/session-dialog.d.ts b/lib/core/dialogs/session-dialog.d.ts deleted file mode 100644 index f597676e2..000000000 --- a/lib/core/dialogs/session-dialog.d.ts +++ /dev/null @@ -1,182 +0,0 @@ -import { Body, IncomingRequestMessage, IncomingResponseMessage, OutgoingAckRequest, OutgoingByeRequest, OutgoingInfoRequest, OutgoingInviteRequest, OutgoingInviteRequestDelegate, OutgoingNotifyRequest, OutgoingPrackRequest, OutgoingReferRequest, OutgoingRequestDelegate, OutgoingRequestMessage, RequestOptions } from "../messages"; -import { Session, SessionDelegate, SessionState, SignalingState } from "../session"; -import { InviteClientTransaction, InviteServerTransaction } from "../transactions"; -import { UserAgentCore } from "../user-agent-core"; -import { ReInviteUserAgentClient } from "../user-agents/re-invite-user-agent-client"; -import { ReInviteUserAgentServer } from "../user-agents/re-invite-user-agent-server"; -import { Dialog } from "./dialog"; -import { DialogState } from "./dialog-state"; -/** - * Session Dialog. - * @public - */ -export declare class SessionDialog extends Dialog implements Session { - private initialTransaction; - delegate: SessionDelegate | undefined; - reinviteUserAgentClient: ReInviteUserAgentClient | undefined; - reinviteUserAgentServer: ReInviteUserAgentServer | undefined; - /** The state of the offer/answer exchange. */ - private _signalingState; - /** The current offer. Undefined unless signaling state HaveLocalOffer, HaveRemoteOffer, or Stable. */ - private _offer; - /** The current answer. Undefined unless signaling state Stable. */ - private _answer; - /** The rollback offer. Undefined unless signaling state HaveLocalOffer or HaveRemoteOffer. */ - private _rollbackOffer; - /** The rollback answer. Undefined unless signaling state HaveLocalOffer or HaveRemoteOffer. */ - private _rollbackAnswer; - /** True if waiting for an ACK to the initial transaction 2xx (UAS only). */ - private ackWait; - /** Retransmission timer for 2xx response which confirmed the dialog. */ - private invite2xxTimer; - /** The rseq of the last reliable response. */ - private rseq; - private logger; - constructor(initialTransaction: InviteClientTransaction | InviteServerTransaction, core: UserAgentCore, state: DialogState, delegate?: SessionDelegate); - dispose(): void; - readonly sessionState: SessionState; - /** The state of the offer/answer exchange. */ - readonly signalingState: SignalingState; - /** The current offer. Undefined unless signaling state HaveLocalOffer, HaveRemoteOffer, of Stable. */ - readonly offer: Body | undefined; - /** The current answer. Undefined unless signaling state Stable. */ - readonly answer: Body | undefined; - /** Confirm the dialog. Only matters if dialog is currently early. */ - confirm(): void; - /** Re-confirm the dialog. Only matters if handling re-INVITE request. */ - reConfirm(): void; - /** - * The UAC core MUST generate an ACK request for each 2xx received from - * the transaction layer. The header fields of the ACK are constructed - * in the same way as for any request sent within a dialog (see Section - * 12) with the exception of the CSeq and the header fields related to - * authentication. The sequence number of the CSeq header field MUST be - * the same as the INVITE being acknowledged, but the CSeq method MUST - * be ACK. The ACK MUST contain the same credentials as the INVITE. If - * the 2xx contains an offer (based on the rules above), the ACK MUST - * carry an answer in its body. If the offer in the 2xx response is not - * acceptable, the UAC core MUST generate a valid answer in the ACK and - * then send a BYE immediately. - * https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - * @param options - ACK options bucket. - */ - ack(options?: RequestOptions): OutgoingAckRequest; - /** - * Terminating a Session - * - * This section describes the procedures for terminating a session - * established by SIP. The state of the session and the state of the - * dialog are very closely related. When a session is initiated with an - * INVITE, each 1xx or 2xx response from a distinct UAS creates a - * dialog, and if that response completes the offer/answer exchange, it - * also creates a session. As a result, each session is "associated" - * with a single dialog - the one which resulted in its creation. If an - * initial INVITE generates a non-2xx final response, that terminates - * all sessions (if any) and all dialogs (if any) that were created - * through responses to the request. By virtue of completing the - * transaction, a non-2xx final response also prevents further sessions - * from being created as a result of the INVITE. The BYE request is - * used to terminate a specific session or attempted session. In this - * case, the specific session is the one with the peer UA on the other - * side of the dialog. When a BYE is received on a dialog, any session - * associated with that dialog SHOULD terminate. A UA MUST NOT send a - * BYE outside of a dialog. The caller's UA MAY send a BYE for either - * confirmed or early dialogs, and the callee's UA MAY send a BYE on - * confirmed dialogs, but MUST NOT send a BYE on early dialogs. - * - * However, the callee's UA MUST NOT send a BYE on a confirmed dialog - * until it has received an ACK for its 2xx response or until the server - * transaction times out. If no SIP extensions have defined other - * application layer states associated with the dialog, the BYE also - * terminates the dialog. - * - * https://tools.ietf.org/html/rfc3261#section-15 - * FIXME: Make these proper Exceptions... - * @param options - BYE options bucket. - * @returns - * Throws `Error` if callee's UA attempts a BYE on an early dialog. - * Throws `Error` if callee's UA attempts a BYE on a confirmed dialog - * while it's waiting on the ACK for its 2xx response. - */ - bye(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingByeRequest; - /** - * An INFO request can be associated with an Info Package (see - * Section 5), or associated with a legacy INFO usage (see Section 2). - * - * The construction of the INFO request is the same as any other - * non-target refresh request within an existing invite dialog usage as - * described in Section 12.2 of RFC 3261. - * https://tools.ietf.org/html/rfc6086#section-4.2.1 - * @param options - Options bucket. - */ - info(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingInfoRequest; - /** - * Modifying an Existing Session - * - * A successful INVITE request (see Section 13) establishes both a - * dialog between two user agents and a session using the offer-answer - * model. Section 12 explains how to modify an existing dialog using a - * target refresh request (for example, changing the remote target URI - * of the dialog). This section describes how to modify the actual - * session. This modification can involve changing addresses or ports, - * adding a media stream, deleting a media stream, and so on. This is - * accomplished by sending a new INVITE request within the same dialog - * that established the session. An INVITE request sent within an - * existing dialog is known as a re-INVITE. - * - * Note that a single re-INVITE can modify the dialog and the - * parameters of the session at the same time. - * - * Either the caller or callee can modify an existing session. - * https://tools.ietf.org/html/rfc3261#section-14 - * @param options - Options bucket - */ - invite(delegate?: OutgoingInviteRequestDelegate, options?: RequestOptions): OutgoingInviteRequest; - /** - * The NOTIFY mechanism defined in [2] MUST be used to inform the agent - * sending the REFER of the status of the reference. - * https://tools.ietf.org/html/rfc3515#section-2.4.4 - * @param options - Options bucket. - */ - notify(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingNotifyRequest; - /** - * Assuming the response is to be transmitted reliably, the UAC MUST - * create a new request with method PRACK. This request is sent within - * the dialog associated with the provisional response (indeed, the - * provisional response may have created the dialog). PRACK requests - * MAY contain bodies, which are interpreted according to their type and - * disposition. - * https://tools.ietf.org/html/rfc3262#section-4 - * @param options - Options bucket. - */ - prack(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingPrackRequest; - /** - * REFER is a SIP request and is constructed as defined in [1]. A REFER - * request MUST contain exactly one Refer-To header field value. - * https://tools.ietf.org/html/rfc3515#section-2.4.1 - * @param options - Options bucket. - */ - refer(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingReferRequest; - /** - * Requests sent within a dialog, as any other requests, are atomic. If - * a particular request is accepted by the UAS, all the state changes - * associated with it are performed. If the request is rejected, none - * of the state changes are performed. - * https://tools.ietf.org/html/rfc3261#section-12.2.2 - * @param message - Incoming request message within this dialog. - */ - receiveRequest(message: IncomingRequestMessage): void; - reliableSequenceGuard(message: IncomingResponseMessage): boolean; - /** - * If not in a stable signaling state, rollback to prior stable signaling state. - */ - signalingStateRollback(): void; - /** - * Update the signaling state of the dialog. - * @param message - The message to base the update off of. - */ - signalingStateTransition(message: IncomingRequestMessage | IncomingResponseMessage | OutgoingRequestMessage | Body): void; - private start2xxRetransmissionTimer; - private startReInvite2xxRetransmissionTimer; -} -//# sourceMappingURL=session-dialog.d.ts.map \ No newline at end of file diff --git a/lib/core/dialogs/session-dialog.d.ts.map b/lib/core/dialogs/session-dialog.d.ts.map deleted file mode 100644 index 14c414dea..000000000 --- a/lib/core/dialogs/session-dialog.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"session-dialog.d.ts","sourceRoot":"","sources":["../../../src/core/dialogs/session-dialog.ts"],"names":[],"mappings":"AACA,OAAO,EACL,IAAI,EAGJ,sBAAsB,EACtB,uBAAuB,EAGvB,kBAAkB,EAClB,kBAAkB,EAClB,mBAAmB,EACnB,qBAAqB,EACrB,6BAA6B,EAC7B,qBAAqB,EACrB,oBAAoB,EACpB,oBAAoB,EACpB,uBAAuB,EACvB,sBAAsB,EACtB,cAAc,EACf,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,OAAO,EACP,eAAe,EACf,YAAY,EACZ,cAAc,EACf,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,uBAAuB,EACvB,uBAAuB,EAExB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AASnD,OAAO,EAAE,uBAAuB,EAAE,MAAM,4CAA4C,CAAC;AACrF,OAAO,EAAE,uBAAuB,EAAE,MAAM,4CAA4C,CAAC;AAGrF,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAClC,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAE7C;;;GAGG;AACH,qBAAa,aAAc,SAAQ,MAAO,YAAW,OAAO;IA2BxD,OAAO,CAAC,kBAAkB;IA1BrB,QAAQ,EAAE,eAAe,GAAG,SAAS,CAAC;IAEtC,uBAAuB,EAAE,uBAAuB,GAAG,SAAS,CAAC;IAC7D,uBAAuB,EAAE,uBAAuB,GAAG,SAAS,CAAC;IAEpE,8CAA8C;IAC9C,OAAO,CAAC,eAAe,CAA0C;IACjE,sGAAsG;IACtG,OAAO,CAAC,MAAM,CAAmB;IACjC,mEAAmE;IACnE,OAAO,CAAC,OAAO,CAAmB;IAClC,8FAA8F;IAC9F,OAAO,CAAC,cAAc,CAAmB;IACzC,+FAA+F;IAC/F,OAAO,CAAC,eAAe,CAAmB;IAE1C,4EAA4E;IAC5E,OAAO,CAAC,OAAO,CAAS;IACxB,wEAAwE;IACxE,OAAO,CAAC,cAAc,CAAM;IAC5B,8CAA8C;IAC9C,OAAO,CAAC,IAAI,CAAqB;IAEjC,OAAO,CAAC,MAAM,CAAS;gBAGb,kBAAkB,EAAE,uBAAuB,GAAG,uBAAuB,EAC7E,IAAI,EAAE,aAAa,EACnB,KAAK,EAAE,WAAW,EAClB,QAAQ,CAAC,EAAE,eAAe;IAmBrB,OAAO,IAAI,IAAI;aAsBlB,YAAY,EAAI,YAAY;IAYhC,8CAA8C;aAC1C,cAAc,EAAI,cAAc;IAIpC,sGAAsG;aAClG,KAAK,EAAI,IAAI,GAAG,SAAS;IAI7B,mEAAmE;aAC/D,MAAM,EAAI,IAAI,GAAG,SAAS;IAI9B,qEAAqE;IAC9D,OAAO,IAAI,IAAI;IAStB,yEAAyE;IAClE,SAAS,IAAI,IAAI;IAQxB;;;;;;;;;;;;;;OAcG;IACI,GAAG,CAAC,OAAO,GAAE,cAAmB,GAAG,kBAAkB;IAwB5D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAoCG;IACI,GAAG,CAAC,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,kBAAkB;IA0C5F;;;;;;;;;OASG;IACI,IAAI,CAAC,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,mBAAmB;IAS9F;;;;;;;;;;;;;;;;;;;;OAoBG;IACI,MAAM,CAAC,QAAQ,CAAC,EAAE,6BAA6B,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,qBAAqB;IAkCxG;;;;;OAKG;IACI,MAAM,CAAC,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,qBAAqB;IASlG;;;;;;;;;OASG;IACI,KAAK,CAAC,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,oBAAoB;IAKhG;;;;;OAKG;IACI,KAAK,CAAC,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,oBAAoB;IAUhG;;;;;;;OAOG;IACI,cAAc,CAAC,OAAO,EAAE,sBAAsB,GAAG,IAAI;IAoMrD,qBAAqB,CAAC,OAAO,EAAE,uBAAuB,GAAG,OAAO;IAkDvE;;OAEG;IACI,sBAAsB,IAAI,IAAI;IAYrC;;;OAGG;IACI,wBAAwB,CAC7B,OAAO,EAAE,sBAAsB,GAAG,uBAAuB,GAAG,sBAAsB,GAAG,IAAI,GACxF,IAAI;IAmHP,OAAO,CAAC,2BAA2B;IAqDnC,OAAO,CAAC,mCAAmC;CA+C5C"} \ No newline at end of file diff --git a/lib/core/dialogs/session-dialog.js b/lib/core/dialogs/session-dialog.js deleted file mode 100644 index 0fbe12b92..000000000 --- a/lib/core/dialogs/session-dialog.js +++ /dev/null @@ -1,823 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var messages_1 = require("../messages"); -var session_1 = require("../session"); -var timers_1 = require("../timers"); -var transactions_1 = require("../transactions"); -var bye_user_agent_client_1 = require("../user-agents/bye-user-agent-client"); -var bye_user_agent_server_1 = require("../user-agents/bye-user-agent-server"); -var info_user_agent_client_1 = require("../user-agents/info-user-agent-client"); -var info_user_agent_server_1 = require("../user-agents/info-user-agent-server"); -var notify_user_agent_client_1 = require("../user-agents/notify-user-agent-client"); -var notify_user_agent_server_1 = require("../user-agents/notify-user-agent-server"); -var prack_user_agent_client_1 = require("../user-agents/prack-user-agent-client"); -var prack_user_agent_server_1 = require("../user-agents/prack-user-agent-server"); -var re_invite_user_agent_client_1 = require("../user-agents/re-invite-user-agent-client"); -var re_invite_user_agent_server_1 = require("../user-agents/re-invite-user-agent-server"); -var refer_user_agent_client_1 = require("../user-agents/refer-user-agent-client"); -var refer_user_agent_server_1 = require("../user-agents/refer-user-agent-server"); -var dialog_1 = require("./dialog"); -/** - * Session Dialog. - * @public - */ -var SessionDialog = /** @class */ (function (_super) { - tslib_1.__extends(SessionDialog, _super); - function SessionDialog(initialTransaction, core, state, delegate) { - var _this = _super.call(this, core, state) || this; - _this.initialTransaction = initialTransaction; - /** The state of the offer/answer exchange. */ - _this._signalingState = session_1.SignalingState.Initial; - /** True if waiting for an ACK to the initial transaction 2xx (UAS only). */ - _this.ackWait = false; - _this.delegate = delegate; - if (initialTransaction instanceof transactions_1.InviteServerTransaction) { - // If we're created by an invite server transaction, we're - // going to be waiting for an ACK if are to be confirmed. - _this.ackWait = true; - } - // If we're confirmed upon creation start the retransmitting whatever - // the 2xx final response was that confirmed us into existence. - if (!_this.early) { - _this.start2xxRetransmissionTimer(); - } - _this.signalingStateTransition(initialTransaction.request); - _this.logger = core.loggerFactory.getLogger("sip.invite-dialog"); - _this.logger.log("INVITE dialog " + _this.id + " constructed"); - return _this; - } - SessionDialog.prototype.dispose = function () { - _super.prototype.dispose.call(this); - this._signalingState = session_1.SignalingState.Closed; - this._offer = undefined; - this._answer = undefined; - if (this.invite2xxTimer) { - clearTimeout(this.invite2xxTimer); - this.invite2xxTimer = undefined; - } - // The UAS MUST still respond to any pending requests received for that - // dialog. It is RECOMMENDED that a 487 (Request Terminated) response - // be generated to those pending requests. - // https://tools.ietf.org/html/rfc3261#section-15.1.2 - // TODO: - // this.userAgentServers.forEach((uas) => uas.reply(487)); - this.logger.log("INVITE dialog " + this.id + " destroyed"); - }; - Object.defineProperty(SessionDialog.prototype, "sessionState", { - // FIXME: Need real state machine - get: function () { - if (this.early) { - return session_1.SessionState.Early; - } - else if (this.ackWait) { - return session_1.SessionState.AckWait; - } - else if (this._signalingState === session_1.SignalingState.Closed) { - return session_1.SessionState.Terminated; - } - else { - return session_1.SessionState.Confirmed; - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SessionDialog.prototype, "signalingState", { - /** The state of the offer/answer exchange. */ - get: function () { - return this._signalingState; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SessionDialog.prototype, "offer", { - /** The current offer. Undefined unless signaling state HaveLocalOffer, HaveRemoteOffer, of Stable. */ - get: function () { - return this._offer; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SessionDialog.prototype, "answer", { - /** The current answer. Undefined unless signaling state Stable. */ - get: function () { - return this._answer; - }, - enumerable: true, - configurable: true - }); - /** Confirm the dialog. Only matters if dialog is currently early. */ - SessionDialog.prototype.confirm = function () { - // When we're confirmed start the retransmitting whatever - // the 2xx final response that may have confirmed us. - if (this.early) { - this.start2xxRetransmissionTimer(); - } - _super.prototype.confirm.call(this); - }; - /** Re-confirm the dialog. Only matters if handling re-INVITE request. */ - SessionDialog.prototype.reConfirm = function () { - // When we're confirmed start the retransmitting whatever - // the 2xx final response that may have confirmed us. - if (this.reinviteUserAgentServer) { - this.startReInvite2xxRetransmissionTimer(); - } - }; - /** - * The UAC core MUST generate an ACK request for each 2xx received from - * the transaction layer. The header fields of the ACK are constructed - * in the same way as for any request sent within a dialog (see Section - * 12) with the exception of the CSeq and the header fields related to - * authentication. The sequence number of the CSeq header field MUST be - * the same as the INVITE being acknowledged, but the CSeq method MUST - * be ACK. The ACK MUST contain the same credentials as the INVITE. If - * the 2xx contains an offer (based on the rules above), the ACK MUST - * carry an answer in its body. If the offer in the 2xx response is not - * acceptable, the UAC core MUST generate a valid answer in the ACK and - * then send a BYE immediately. - * https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - * @param options - ACK options bucket. - */ - SessionDialog.prototype.ack = function (options) { - if (options === void 0) { options = {}; } - this.logger.log("INVITE dialog " + this.id + " sending ACK request"); - var transaction; - if (this.reinviteUserAgentClient) { - // We're sending ACK for a re-INVITE - if (!(this.reinviteUserAgentClient.transaction instanceof transactions_1.InviteClientTransaction)) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - transaction = this.reinviteUserAgentClient.transaction; - this.reinviteUserAgentClient = undefined; - } - else { - // We're sending ACK for the initial INVITE - if (!(this.initialTransaction instanceof transactions_1.InviteClientTransaction)) { - throw new Error("Initial transaction not instance of InviteClientTransaction."); - } - transaction = this.initialTransaction; - } - options.cseq = transaction.request.cseq; // ACK cseq is INVITE cseq - var message = this.createOutgoingRequestMessage(messages_1.C.ACK, options); - transaction.ackResponse(message); // See InviteClientTransaction for details. - this.signalingStateTransition(message); - return { message: message }; - }; - /** - * Terminating a Session - * - * This section describes the procedures for terminating a session - * established by SIP. The state of the session and the state of the - * dialog are very closely related. When a session is initiated with an - * INVITE, each 1xx or 2xx response from a distinct UAS creates a - * dialog, and if that response completes the offer/answer exchange, it - * also creates a session. As a result, each session is "associated" - * with a single dialog - the one which resulted in its creation. If an - * initial INVITE generates a non-2xx final response, that terminates - * all sessions (if any) and all dialogs (if any) that were created - * through responses to the request. By virtue of completing the - * transaction, a non-2xx final response also prevents further sessions - * from being created as a result of the INVITE. The BYE request is - * used to terminate a specific session or attempted session. In this - * case, the specific session is the one with the peer UA on the other - * side of the dialog. When a BYE is received on a dialog, any session - * associated with that dialog SHOULD terminate. A UA MUST NOT send a - * BYE outside of a dialog. The caller's UA MAY send a BYE for either - * confirmed or early dialogs, and the callee's UA MAY send a BYE on - * confirmed dialogs, but MUST NOT send a BYE on early dialogs. - * - * However, the callee's UA MUST NOT send a BYE on a confirmed dialog - * until it has received an ACK for its 2xx response or until the server - * transaction times out. If no SIP extensions have defined other - * application layer states associated with the dialog, the BYE also - * terminates the dialog. - * - * https://tools.ietf.org/html/rfc3261#section-15 - * FIXME: Make these proper Exceptions... - * @param options - BYE options bucket. - * @returns - * Throws `Error` if callee's UA attempts a BYE on an early dialog. - * Throws `Error` if callee's UA attempts a BYE on a confirmed dialog - * while it's waiting on the ACK for its 2xx response. - */ - SessionDialog.prototype.bye = function (delegate, options) { - this.logger.log("INVITE dialog " + this.id + " sending BYE request"); - // The caller's UA MAY send a BYE for either - // confirmed or early dialogs, and the callee's UA MAY send a BYE on - // confirmed dialogs, but MUST NOT send a BYE on early dialogs. - // - // However, the callee's UA MUST NOT send a BYE on a confirmed dialog - // until it has received an ACK for its 2xx response or until the server - // transaction times out. - // https://tools.ietf.org/html/rfc3261#section-15 - if (this.initialTransaction instanceof transactions_1.InviteServerTransaction) { - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("UAS MUST NOT send a BYE on early dialogs."); - } - if (this.ackWait && this.initialTransaction.state !== transactions_1.TransactionState.Terminated) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("UAS MUST NOT send a BYE on a confirmed dialog " + - "until it has received an ACK for its 2xx response " + - "or until the server transaction times out."); - } - } - // A BYE request is constructed as would any other request within a - // dialog, as described in Section 12. - // - // Once the BYE is constructed, the UAC core creates a new non-INVITE - // client transaction, and passes it the BYE request. The UAC MUST - // consider the session terminated (and therefore stop sending or - // listening for media) as soon as the BYE request is passed to the - // client transaction. If the response for the BYE is a 481 - // (Call/Transaction Does Not Exist) or a 408 (Request Timeout) or no - // response at all is received for the BYE (that is, a timeout is - // returned by the client transaction), the UAC MUST consider the - // session and the dialog terminated. - // https://tools.ietf.org/html/rfc3261#section-15.1.1 - return new bye_user_agent_client_1.ByeUserAgentClient(this, delegate, options); - }; - /** - * An INFO request can be associated with an Info Package (see - * Section 5), or associated with a legacy INFO usage (see Section 2). - * - * The construction of the INFO request is the same as any other - * non-target refresh request within an existing invite dialog usage as - * described in Section 12.2 of RFC 3261. - * https://tools.ietf.org/html/rfc6086#section-4.2.1 - * @param options - Options bucket. - */ - SessionDialog.prototype.info = function (delegate, options) { - this.logger.log("INVITE dialog " + this.id + " sending INFO request"); - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("Dialog not confirmed."); - } - return new info_user_agent_client_1.InfoUserAgentClient(this, delegate, options); - }; - /** - * Modifying an Existing Session - * - * A successful INVITE request (see Section 13) establishes both a - * dialog between two user agents and a session using the offer-answer - * model. Section 12 explains how to modify an existing dialog using a - * target refresh request (for example, changing the remote target URI - * of the dialog). This section describes how to modify the actual - * session. This modification can involve changing addresses or ports, - * adding a media stream, deleting a media stream, and so on. This is - * accomplished by sending a new INVITE request within the same dialog - * that established the session. An INVITE request sent within an - * existing dialog is known as a re-INVITE. - * - * Note that a single re-INVITE can modify the dialog and the - * parameters of the session at the same time. - * - * Either the caller or callee can modify an existing session. - * https://tools.ietf.org/html/rfc3261#section-14 - * @param options - Options bucket - */ - SessionDialog.prototype.invite = function (delegate, options) { - this.logger.log("INVITE dialog " + this.id + " sending INVITE request"); - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("Dialog not confirmed."); - } - // Note that a UAC MUST NOT initiate a new INVITE transaction within a - // dialog while another INVITE transaction is in progress in either - // direction. - // - // 1. If there is an ongoing INVITE client transaction, the TU MUST - // wait until the transaction reaches the completed or terminated - // state before initiating the new INVITE. - // - // 2. If there is an ongoing INVITE server transaction, the TU MUST - // wait until the transaction reaches the confirmed or terminated - // state before initiating the new INVITE. - // - // However, a UA MAY initiate a regular transaction while an INVITE - // transaction is in progress. A UA MAY also initiate an INVITE - // transaction while a regular transaction is in progress. - // https://tools.ietf.org/html/rfc3261#section-14.1 - if (this.reinviteUserAgentClient) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("There is an ongoing re-INVITE client transaction."); - } - if (this.reinviteUserAgentServer) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("There is an ongoing re-INVITE server transaction."); - } - return new re_invite_user_agent_client_1.ReInviteUserAgentClient(this, delegate, options); - }; - /** - * The NOTIFY mechanism defined in [2] MUST be used to inform the agent - * sending the REFER of the status of the reference. - * https://tools.ietf.org/html/rfc3515#section-2.4.4 - * @param options - Options bucket. - */ - SessionDialog.prototype.notify = function (delegate, options) { - this.logger.log("INVITE dialog " + this.id + " sending NOTIFY request"); - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("Dialog not confirmed."); - } - return new notify_user_agent_client_1.NotifyUserAgentClient(this, delegate, options); - }; - /** - * Assuming the response is to be transmitted reliably, the UAC MUST - * create a new request with method PRACK. This request is sent within - * the dialog associated with the provisional response (indeed, the - * provisional response may have created the dialog). PRACK requests - * MAY contain bodies, which are interpreted according to their type and - * disposition. - * https://tools.ietf.org/html/rfc3262#section-4 - * @param options - Options bucket. - */ - SessionDialog.prototype.prack = function (delegate, options) { - this.logger.log("INVITE dialog " + this.id + " sending PRACK request"); - return new prack_user_agent_client_1.PrackUserAgentClient(this, delegate, options); - }; - /** - * REFER is a SIP request and is constructed as defined in [1]. A REFER - * request MUST contain exactly one Refer-To header field value. - * https://tools.ietf.org/html/rfc3515#section-2.4.1 - * @param options - Options bucket. - */ - SessionDialog.prototype.refer = function (delegate, options) { - this.logger.log("INVITE dialog " + this.id + " sending REFER request"); - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("Dialog not confirmed."); - } - // FIXME: TODO: Validate Refer-To header field value. - return new refer_user_agent_client_1.ReferUserAgentClient(this, delegate, options); - }; - /** - * Requests sent within a dialog, as any other requests, are atomic. If - * a particular request is accepted by the UAS, all the state changes - * associated with it are performed. If the request is rejected, none - * of the state changes are performed. - * https://tools.ietf.org/html/rfc3261#section-12.2.2 - * @param message - Incoming request message within this dialog. - */ - SessionDialog.prototype.receiveRequest = function (message) { - this.logger.log("INVITE dialog " + this.id + " received " + message.method + " request"); - // Response retransmissions cease when an ACK request for the - // response is received. This is independent of whatever transport - // protocols are used to send the response. - // https://tools.ietf.org/html/rfc6026#section-8.1 - if (message.method === messages_1.C.ACK) { - // If ackWait is true, then this is the ACK to the initial INVITE, - // otherwise this is an ACK to an in dialog INVITE. In either case, - // guard to make sure the sequence number of the ACK matches the INVITE. - if (this.ackWait) { - if (this.initialTransaction instanceof transactions_1.InviteClientTransaction) { - this.logger.warn("INVITE dialog " + this.id + " received unexpected " + message.method + " request, dropping."); - return; - } - if (this.initialTransaction.request.cseq !== message.cseq) { - this.logger.warn("INVITE dialog " + this.id + " received unexpected " + message.method + " request, dropping."); - return; - } - // Update before the delegate has a chance to handle the - // message as delegate may callback into this dialog. - this.ackWait = false; - } - else { - if (!this.reinviteUserAgentServer) { - this.logger.warn("INVITE dialog " + this.id + " received unexpected " + message.method + " request, dropping."); - return; - } - if (this.reinviteUserAgentServer.transaction.request.cseq !== message.cseq) { - this.logger.warn("INVITE dialog " + this.id + " received unexpected " + message.method + " request, dropping."); - return; - } - this.reinviteUserAgentServer = undefined; - } - this.signalingStateTransition(message); - if (this.delegate && this.delegate.onAck) { - this.delegate.onAck({ message: message }); - } - return; - } - // Request within a dialog out of sequence guard. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (!this.sequenceGuard(message)) { - this.logger.log("INVITE dialog " + this.id + " rejected out of order " + message.method + " request."); - return; - } - if (message.method === messages_1.C.INVITE) { - // A UAS that receives a second INVITE before it sends the final - // response to a first INVITE with a lower CSeq sequence number on the - // same dialog MUST return a 500 (Server Internal Error) response to the - // second INVITE and MUST include a Retry-After header field with a - // randomly chosen value of between 0 and 10 seconds. - // https://tools.ietf.org/html/rfc3261#section-14.2 - if (this.reinviteUserAgentServer) { - // https://tools.ietf.org/html/rfc3261#section-20.33 - var retryAfter = Math.floor((Math.random() * 10)) + 1; - var extraHeaders = ["Retry-After: " + retryAfter]; - this.core.replyStateless(message, { statusCode: 500, extraHeaders: extraHeaders }); - return; - } - // A UAS that receives an INVITE on a dialog while an INVITE it had sent - // on that dialog is in progress MUST return a 491 (Request Pending) - // response to the received INVITE. - // https://tools.ietf.org/html/rfc3261#section-14.2 - if (this.reinviteUserAgentClient) { - this.core.replyStateless(message, { statusCode: 491 }); - return; - } - } - // Request within a dialog common processing. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - _super.prototype.receiveRequest.call(this, message); - // Requests within a dialog MAY contain Record-Route and Contact header - // fields. However, these requests do not cause the dialog's route set - // to be modified, although they may modify the remote target URI. - // Specifically, requests that are not target refresh requests do not - // modify the dialog's remote target URI, and requests that are target - // refresh requests do. For dialogs that have been established with an - // INVITE, the only target refresh request defined is re-INVITE (see - // Section 14). Other extensions may define different target refresh - // requests for dialogs established in other ways. - // - // Note that an ACK is NOT a target refresh request. - // - // Target refresh requests only update the dialog's remote target URI, - // and not the route set formed from the Record-Route. Updating the - // latter would introduce severe backwards compatibility problems with - // RFC 2543-compliant systems. - // https://tools.ietf.org/html/rfc3261#section-15 - if (message.method === messages_1.C.INVITE) { - // FIXME: parser needs to be typed... - var contact = message.parseHeader("contact"); - if (!contact) { // TODO: Review to make sure this will never happen - throw new Error("Contact undefined."); - } - if (!(contact instanceof messages_1.NameAddrHeader)) { - throw new Error("Contact not instance of NameAddrHeader."); - } - this.dialogState.remoteTarget = contact.uri; - } - // Switch on method and then delegate. - switch (message.method) { - case messages_1.C.BYE: - // A UAS core receiving a BYE request for an existing dialog MUST follow - // the procedures of Section 12.2.2 to process the request. Once done, - // the UAS SHOULD terminate the session (and therefore stop sending and - // listening for media). The only case where it can elect not to are - // multicast sessions, where participation is possible even if the other - // participant in the dialog has terminated its involvement in the - // session. Whether or not it ends its participation on the session, - // the UAS core MUST generate a 2xx response to the BYE, and MUST pass - // that to the server transaction for transmission. - // - // The UAS MUST still respond to any pending requests received for that - // dialog. It is RECOMMENDED that a 487 (Request Terminated) response - // be generated to those pending requests. - // https://tools.ietf.org/html/rfc3261#section-15.1.2 - { - var uas = new bye_user_agent_server_1.ByeUserAgentServer(this, message); - this.delegate && this.delegate.onBye ? - this.delegate.onBye(uas) : - uas.accept(); - this.dispose(); - } - break; - case messages_1.C.INFO: - // If a UA receives an INFO request associated with an Info Package that - // the UA has not indicated willingness to receive, the UA MUST send a - // 469 (Bad Info Package) response (see Section 11.6), which contains a - // Recv-Info header field with Info Packages for which the UA is willing - // to receive INFO requests. - { - var uas = new info_user_agent_server_1.InfoUserAgentServer(this, message); - this.delegate && this.delegate.onInfo ? - this.delegate.onInfo(uas) : - uas.reject({ - statusCode: 469, - extraHeaders: ["Recv-Info :"] - }); - } - break; - case messages_1.C.INVITE: - // If the new session description is not acceptable, the UAS can reject - // it by returning a 488 (Not Acceptable Here) response for the re- - // INVITE. This response SHOULD include a Warning header field. - // https://tools.ietf.org/html/rfc3261#section-14.2 - { - var uas = new re_invite_user_agent_server_1.ReInviteUserAgentServer(this, message); - this.signalingStateTransition(message); - this.delegate && this.delegate.onInvite ? - this.delegate.onInvite(uas) : - uas.reject({ statusCode: 488 }); // TODO: Warning header field. - } - break; - case messages_1.C.NOTIFY: - // https://tools.ietf.org/html/rfc3515#section-2.4.4 - { - var uas = new notify_user_agent_server_1.NotifyUserAgentServer(this, message); - this.delegate && this.delegate.onNotify ? - this.delegate.onNotify(uas) : - uas.accept(); - } - break; - case messages_1.C.PRACK: - // https://tools.ietf.org/html/rfc3262#section-4 - { - var uas = new prack_user_agent_server_1.PrackUserAgentServer(this, message); - this.delegate && this.delegate.onPrack ? - this.delegate.onPrack(uas) : - uas.accept(); - } - break; - case messages_1.C.REFER: - // https://tools.ietf.org/html/rfc3515#section-2.4.2 - { - var uas = new refer_user_agent_server_1.ReferUserAgentServer(this, message); - this.delegate && this.delegate.onRefer ? - this.delegate.onRefer(uas) : - uas.reject(); - } - break; - default: - { - this.logger.log("INVITE dialog " + this.id + " received unimplemented " + message.method + " request"); - this.core.replyStateless(message, { statusCode: 501 }); - } - break; - } - }; - SessionDialog.prototype.reliableSequenceGuard = function (message) { - var statusCode = message.statusCode; - if (!statusCode) { - throw new Error("Status code undefined"); - } - if (statusCode > 100 && statusCode < 200) { - // If a provisional response is received for an initial request, and - // that response contains a Require header field containing the option - // tag 100rel, the response is to be sent reliably. If the response is - // a 100 (Trying) (as opposed to 101 to 199), this option tag MUST be - // ignored, and the procedures below MUST NOT be used. - // https://tools.ietf.org/html/rfc3262#section-4 - var requireHeader = message.getHeader("require"); - var rseqHeader = message.getHeader("rseq"); - var rseq = requireHeader && requireHeader.includes("100rel") && rseqHeader ? Number(rseqHeader) : undefined; - if (rseq) { - // Handling of subsequent reliable provisional responses for the same - // initial request follows the same rules as above, with the following - // difference: reliable provisional responses are guaranteed to be in - // order. As a result, if the UAC receives another reliable provisional - // response to the same request, and its RSeq value is not one higher - // than the value of the sequence number, that response MUST NOT be - // acknowledged with a PRACK, and MUST NOT be processed further by the - // UAC. An implementation MAY discard the response, or MAY cache the - // response in the hopes of receiving the missing responses. - // https://tools.ietf.org/html/rfc3262#section-4 - if (this.rseq && this.rseq + 1 !== rseq) { - return false; - } - // Once a reliable provisional response is received, retransmissions of - // that response MUST be discarded. A response is a retransmission when - // its dialog ID, CSeq, and RSeq match the original response. The UAC - // MUST maintain a sequence number that indicates the most recently - // received in-order reliable provisional response for the initial - // request. This sequence number MUST be maintained until a final - // response is received for the initial request. Its value MUST be - // initialized to the RSeq header field in the first reliable - // provisional response received for the initial request. - // https://tools.ietf.org/html/rfc3262#section-4 - if (!this.rseq) { - this.rseq = rseq; - } - } - } - return true; - }; - /** - * If not in a stable signaling state, rollback to prior stable signaling state. - */ - SessionDialog.prototype.signalingStateRollback = function () { - if (this._signalingState === session_1.SignalingState.HaveLocalOffer || - this.signalingState === session_1.SignalingState.HaveRemoteOffer) { - if (this._rollbackOffer && this._rollbackAnswer) { - this._signalingState = session_1.SignalingState.Stable; - this._offer = this._rollbackOffer; - this._answer = this._rollbackAnswer; - } - } - }; - /** - * Update the signaling state of the dialog. - * @param message - The message to base the update off of. - */ - SessionDialog.prototype.signalingStateTransition = function (message) { - var body = messages_1.getBody(message); - // No body, no session. No, woman, no cry. - if (!body || body.contentDisposition !== "session") { - return; - } - // We've got an existing offer and answer which we may wish to rollback to - if (this._signalingState === session_1.SignalingState.Stable) { - this._rollbackOffer = this._offer; - this._rollbackAnswer = this._answer; - } - // We're in UAS role, receiving incoming request with session description - if (message instanceof messages_1.IncomingRequestMessage) { - switch (this._signalingState) { - case session_1.SignalingState.Initial: - case session_1.SignalingState.Stable: - this._signalingState = session_1.SignalingState.HaveRemoteOffer; - this._offer = body; - this._answer = undefined; - break; - case session_1.SignalingState.HaveLocalOffer: - this._signalingState = session_1.SignalingState.Stable; - this._answer = body; - break; - case session_1.SignalingState.HaveRemoteOffer: - // You cannot make a new offer while one is in progress. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // FIXME: What to do here? - break; - case session_1.SignalingState.Closed: - break; - default: - throw new Error("Unexpected signaling state."); - } - } - // We're in UAC role, receiving incoming response with session description - if (message instanceof messages_1.IncomingResponseMessage) { - switch (this._signalingState) { - case session_1.SignalingState.Initial: - case session_1.SignalingState.Stable: - this._signalingState = session_1.SignalingState.HaveRemoteOffer; - this._offer = body; - this._answer = undefined; - break; - case session_1.SignalingState.HaveLocalOffer: - this._signalingState = session_1.SignalingState.Stable; - this._answer = body; - break; - case session_1.SignalingState.HaveRemoteOffer: - // You cannot make a new offer while one is in progress. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // FIXME: What to do here? - break; - case session_1.SignalingState.Closed: - break; - default: - throw new Error("Unexpected signaling state."); - } - } - // We're in UAC role, sending outgoing request with session description - if (message instanceof messages_1.OutgoingRequestMessage) { - switch (this._signalingState) { - case session_1.SignalingState.Initial: - case session_1.SignalingState.Stable: - this._signalingState = session_1.SignalingState.HaveLocalOffer; - this._offer = body; - this._answer = undefined; - break; - case session_1.SignalingState.HaveLocalOffer: - // You cannot make a new offer while one is in progress. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // FIXME: What to do here? - break; - case session_1.SignalingState.HaveRemoteOffer: - this._signalingState = session_1.SignalingState.Stable; - this._answer = body; - break; - case session_1.SignalingState.Closed: - break; - default: - throw new Error("Unexpected signaling state."); - } - } - // We're in UAS role, sending outgoing response with session description - if (messages_1.isBody(message)) { - switch (this._signalingState) { - case session_1.SignalingState.Initial: - case session_1.SignalingState.Stable: - this._signalingState = session_1.SignalingState.HaveLocalOffer; - this._offer = body; - this._answer = undefined; - break; - case session_1.SignalingState.HaveLocalOffer: - // You cannot make a new offer while one is in progress. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // FIXME: What to do here? - break; - case session_1.SignalingState.HaveRemoteOffer: - this._signalingState = session_1.SignalingState.Stable; - this._answer = body; - break; - case session_1.SignalingState.Closed: - break; - default: - throw new Error("Unexpected signaling state."); - } - } - }; - SessionDialog.prototype.start2xxRetransmissionTimer = function () { - var _this = this; - if (this.initialTransaction instanceof transactions_1.InviteServerTransaction) { - var transaction_1 = this.initialTransaction; - // Once the response has been constructed, it is passed to the INVITE - // server transaction. In order to ensure reliable end-to-end - // transport of the response, it is necessary to periodically pass - // the response directly to the transport until the ACK arrives. The - // 2xx response is passed to the transport with an interval that - // starts at T1 seconds and doubles for each retransmission until it - // reaches T2 seconds (T1 and T2 are defined in Section 17). - // Response retransmissions cease when an ACK request for the - // response is received. This is independent of whatever transport - // protocols are used to send the response. - // https://tools.ietf.org/html/rfc6026#section-8.1 - var timeout_1 = timers_1.Timers.T1; - var retransmission_1 = function () { - if (!_this.ackWait) { - _this.invite2xxTimer = undefined; - return; - } - _this.logger.log("No ACK for 2xx response received, attempting retransmission"); - transaction_1.retransmitAcceptedResponse(); - timeout_1 = Math.min(timeout_1 * 2, timers_1.Timers.T2); - _this.invite2xxTimer = setTimeout(retransmission_1, timeout_1); - }; - this.invite2xxTimer = setTimeout(retransmission_1, timeout_1); - // If the server retransmits the 2xx response for 64*T1 seconds without - // receiving an ACK, the dialog is confirmed, but the session SHOULD be - // terminated. This is accomplished with a BYE, as described in Section 15. - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - var stateChanged_1 = function () { - if (transaction_1.state === transactions_1.TransactionState.Terminated) { - transaction_1.removeListener("stateChanged", stateChanged_1); - if (_this.invite2xxTimer) { - clearTimeout(_this.invite2xxTimer); - _this.invite2xxTimer = undefined; - } - if (_this.ackWait) { - if (_this.delegate && _this.delegate.onAckTimeout) { - _this.delegate.onAckTimeout(); - } - else { - _this.bye(); - } - } - } - }; - transaction_1.addListener("stateChanged", stateChanged_1); - } - }; - // FIXME: Refactor - SessionDialog.prototype.startReInvite2xxRetransmissionTimer = function () { - var _this = this; - if (this.reinviteUserAgentServer && this.reinviteUserAgentServer.transaction instanceof transactions_1.InviteServerTransaction) { - var transaction_2 = this.reinviteUserAgentServer.transaction; - // Once the response has been constructed, it is passed to the INVITE - // server transaction. In order to ensure reliable end-to-end - // transport of the response, it is necessary to periodically pass - // the response directly to the transport until the ACK arrives. The - // 2xx response is passed to the transport with an interval that - // starts at T1 seconds and doubles for each retransmission until it - // reaches T2 seconds (T1 and T2 are defined in Section 17). - // Response retransmissions cease when an ACK request for the - // response is received. This is independent of whatever transport - // protocols are used to send the response. - // https://tools.ietf.org/html/rfc6026#section-8.1 - var timeout_2 = timers_1.Timers.T1; - var retransmission_2 = function () { - if (!_this.reinviteUserAgentServer) { - _this.invite2xxTimer = undefined; - return; - } - _this.logger.log("No ACK for 2xx response received, attempting retransmission"); - transaction_2.retransmitAcceptedResponse(); - timeout_2 = Math.min(timeout_2 * 2, timers_1.Timers.T2); - _this.invite2xxTimer = setTimeout(retransmission_2, timeout_2); - }; - this.invite2xxTimer = setTimeout(retransmission_2, timeout_2); - // If the server retransmits the 2xx response for 64*T1 seconds without - // receiving an ACK, the dialog is confirmed, but the session SHOULD be - // terminated. This is accomplished with a BYE, as described in Section 15. - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - var stateChanged_2 = function () { - if (transaction_2.state === transactions_1.TransactionState.Terminated) { - transaction_2.removeListener("stateChanged", stateChanged_2); - if (_this.invite2xxTimer) { - clearTimeout(_this.invite2xxTimer); - _this.invite2xxTimer = undefined; - } - if (_this.reinviteUserAgentServer) { - // FIXME: TODO: What to do here - } - } - }; - transaction_2.addListener("stateChanged", stateChanged_2); - } - }; - return SessionDialog; -}(dialog_1.Dialog)); -exports.SessionDialog = SessionDialog; diff --git a/lib/core/dialogs/subscription-dialog.d.ts b/lib/core/dialogs/subscription-dialog.d.ts deleted file mode 100644 index 94720fb5a..000000000 --- a/lib/core/dialogs/subscription-dialog.d.ts +++ /dev/null @@ -1,119 +0,0 @@ -import { IncomingRequestMessage, OutgoingRequestMessage, OutgoingSubscribeRequest, OutgoingSubscribeRequestDelegate, RequestOptions } from "../messages"; -import { Subscription, SubscriptionDelegate, SubscriptionState } from "../subscription"; -import { UserAgentCore } from "../user-agent-core/user-agent-core"; -import { Dialog } from "./dialog"; -import { DialogState } from "./dialog-state"; -/** - * Subscription Dialog. - * @remarks - * SIP-Specific Event Notification - * - * Abstract - * - * This document describes an extension to the Session Initiation - * Protocol (SIP) defined by RFC 3261. The purpose of this extension is - * to provide an extensible framework by which SIP nodes can request - * notification from remote nodes indicating that certain events have - * occurred. - * - * Note that the event notification mechanisms defined herein are NOT - * intended to be a general-purpose infrastructure for all classes of - * event subscription and notification. - * - * This document represents a backwards-compatible improvement on the - * original mechanism described by RFC 3265, taking into account several - * years of implementation experience. Accordingly, this document - * obsoletes RFC 3265. This document also updates RFC 4660 slightly to - * accommodate some small changes to the mechanism that were discussed - * in that document. - * - * https://tools.ietf.org/html/rfc6665 - * @public - */ -export declare class SubscriptionDialog extends Dialog implements Subscription { - /** - * When a UAC receives a response that establishes a dialog, it - * constructs the state of the dialog. This state MUST be maintained - * for the duration of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.1.2 - * @param outgoingRequestMessage - Outgoing request message for dialog. - * @param incomingResponseMessage - Incoming response message creating dialog. - */ - static initialDialogStateForSubscription(outgoingSubscribeRequestMessage: OutgoingRequestMessage, incomingNotifyRequestMessage: IncomingRequestMessage): DialogState; - delegate: SubscriptionDelegate | undefined; - private _autoRefresh; - private _subscriptionEvent; - private _subscriptionExpires; - private _subscriptionExpiresInitial; - private _subscriptionExpiresLastSet; - private _subscriptionRefresh; - private _subscriptionRefreshLastSet; - private _subscriptionState; - private logger; - private N; - private refreshTimer; - constructor(subscriptionEvent: string, subscriptionExpires: number, subscriptionState: SubscriptionState, core: UserAgentCore, state: DialogState, delegate?: SubscriptionDelegate); - dispose(): void; - autoRefresh: boolean; - readonly subscriptionEvent: string; - /** Number of seconds until subscription expires. */ - subscriptionExpires: number; - readonly subscriptionExpiresInitial: number; - /** Number of seconds until subscription auto refresh. */ - readonly subscriptionRefresh: number | undefined; - readonly subscriptionState: SubscriptionState; - /** - * Receive in dialog request message from transport. - * @param message - The incoming request message. - */ - receiveRequest(message: IncomingRequestMessage): void; - /** - * 4.1.2.2. Refreshing of Subscriptions - * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - */ - refresh(): OutgoingSubscribeRequest; - /** - * 4.1.2.2. Refreshing of Subscriptions - * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - * @param delegate - Delegate to handle responses. - * @param options - Options bucket. - */ - subscribe(delegate?: OutgoingSubscribeRequestDelegate, options?: RequestOptions): OutgoingSubscribeRequest; - /** - * 4.4.1. Dialog Creation and Termination - * A subscription is destroyed after a notifier sends a NOTIFY request - * with a "Subscription-State" of "terminated", or in certain error - * situations described elsewhere in this document. - * https://tools.ietf.org/html/rfc6665#section-4.4.1 - */ - terminate(): void; - /** - * 4.1.2.3. Unsubscribing - * https://tools.ietf.org/html/rfc6665#section-4.1.2.3 - */ - unsubscribe(): OutgoingSubscribeRequest; - /** - * Handle in dialog NOTIFY requests. - * This does not include the first NOTIFY which created the dialog. - * @param message - The incoming NOTIFY request message. - */ - private onNotify; - private onRefresh; - private onTerminated; - private refreshTimerClear; - private refreshTimerSet; - private stateTransition; - /** - * When refreshing a subscription, a subscriber starts Timer N, set to - * 64*T1, when it sends the SUBSCRIBE request. If this Timer N expires - * prior to the receipt of a NOTIFY request, the subscriber considers - * the subscription terminated. If the subscriber receives a success - * response to the SUBSCRIBE request that indicates that no NOTIFY - * request will be generated -- such as the 204 response defined for use - * with the optional extension described in [RFC5839] -- then it MUST - * cancel Timer N. - * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - */ - private timer_N; -} -//# sourceMappingURL=subscription-dialog.d.ts.map \ No newline at end of file diff --git a/lib/core/dialogs/subscription-dialog.d.ts.map b/lib/core/dialogs/subscription-dialog.d.ts.map deleted file mode 100644 index 6fff48ab9..000000000 --- a/lib/core/dialogs/subscription-dialog.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"subscription-dialog.d.ts","sourceRoot":"","sources":["../../../src/core/dialogs/subscription-dialog.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,sBAAsB,EAEtB,sBAAsB,EACtB,wBAAwB,EACxB,gCAAgC,EAChC,cAAc,EACf,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,YAAY,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAGxF,OAAO,EAAE,aAAa,EAAE,MAAM,oCAAoC,CAAC;AAGnE,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAClC,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAE7C;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,qBAAa,kBAAmB,SAAQ,MAAO,YAAW,YAAY;IAEpE;;;;;;;OAOG;WACW,iCAAiC,CAC7C,+BAA+B,EAAE,sBAAsB,EACvD,4BAA4B,EAAE,sBAAsB,GACnD,WAAW;IAyFP,QAAQ,EAAE,oBAAoB,GAAG,SAAS,CAAC;IAElD,OAAO,CAAC,YAAY,CAAU;IAC9B,OAAO,CAAC,kBAAkB,CAAS;IACnC,OAAO,CAAC,oBAAoB,CAAS;IACrC,OAAO,CAAC,2BAA2B,CAAS;IAC5C,OAAO,CAAC,2BAA2B,CAAS;IAC5C,OAAO,CAAC,oBAAoB,CAAqB;IACjD,OAAO,CAAC,2BAA2B,CAAqB;IACxD,OAAO,CAAC,kBAAkB,CAAoB;IAE9C,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,CAAC,CAAkB;IAC3B,OAAO,CAAC,YAAY,CAAkB;gBAGpC,iBAAiB,EAAE,MAAM,EACzB,mBAAmB,EAAE,MAAM,EAC3B,iBAAiB,EAAE,iBAAiB,EACpC,IAAI,EAAE,aAAa,EACnB,KAAK,EAAE,WAAW,EAClB,QAAQ,CAAC,EAAE,oBAAoB;IAgB1B,OAAO,IAAI,IAAI;IAUlB,WAAW,EAAI,OAAO;aAStB,iBAAiB,EAAI,MAAM;IAI/B,oDAAoD;IAChD,mBAAmB,EAAI,MAAM;aAoB7B,0BAA0B,EAAI,MAAM;IAIxC,yDAAyD;aACrD,mBAAmB,EAAI,MAAM,GAAG,SAAS;aASzC,iBAAiB,EAAI,iBAAiB;IAI1C;;;OAGG;IACI,cAAc,CAAC,OAAO,EAAE,sBAAsB,GAAG,IAAI;IA0B5D;;;OAGG;IACI,OAAO,IAAI,wBAAwB;IAW1C;;;;;OAKG;IACI,SAAS,CACd,QAAQ,CAAC,EAAE,gCAAgC,EAC3C,OAAO,GAAE,cAAmB,GAC3B,wBAAwB;IAgB3B;;;;;;OAMG;IACI,SAAS,IAAI,IAAI;IAKxB;;;OAGG;IACI,WAAW,IAAI,wBAAwB;IAW9C;;;;OAIG;IACH,OAAO,CAAC,QAAQ;IAyDhB,OAAO,CAAC,SAAS;IAMjB,OAAO,CAAC,YAAY;IAMpB,OAAO,CAAC,iBAAiB;IAOzB,OAAO,CAAC,eAAe;IAevB,OAAO,CAAC,eAAe;IAwFvB;;;;;;;;;;OAUG;IACH,OAAO,CAAC,OAAO;CAMhB"} \ No newline at end of file diff --git a/lib/core/dialogs/subscription-dialog.js b/lib/core/dialogs/subscription-dialog.js deleted file mode 100644 index f0a31dde8..000000000 --- a/lib/core/dialogs/subscription-dialog.js +++ /dev/null @@ -1,494 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var messages_1 = require("../messages"); -var subscription_1 = require("../subscription"); -var timers_1 = require("../timers"); -var allowed_methods_1 = require("../user-agent-core/allowed-methods"); -var notify_user_agent_server_1 = require("../user-agents/notify-user-agent-server"); -var re_subscribe_user_agent_client_1 = require("../user-agents/re-subscribe-user-agent-client"); -var dialog_1 = require("./dialog"); -/** - * Subscription Dialog. - * @remarks - * SIP-Specific Event Notification - * - * Abstract - * - * This document describes an extension to the Session Initiation - * Protocol (SIP) defined by RFC 3261. The purpose of this extension is - * to provide an extensible framework by which SIP nodes can request - * notification from remote nodes indicating that certain events have - * occurred. - * - * Note that the event notification mechanisms defined herein are NOT - * intended to be a general-purpose infrastructure for all classes of - * event subscription and notification. - * - * This document represents a backwards-compatible improvement on the - * original mechanism described by RFC 3265, taking into account several - * years of implementation experience. Accordingly, this document - * obsoletes RFC 3265. This document also updates RFC 4660 slightly to - * accommodate some small changes to the mechanism that were discussed - * in that document. - * - * https://tools.ietf.org/html/rfc6665 - * @public - */ -var SubscriptionDialog = /** @class */ (function (_super) { - tslib_1.__extends(SubscriptionDialog, _super); - function SubscriptionDialog(subscriptionEvent, subscriptionExpires, subscriptionState, core, state, delegate) { - var _this = _super.call(this, core, state) || this; - _this.delegate = delegate; - _this._autoRefresh = false; - _this._subscriptionEvent = subscriptionEvent; - _this._subscriptionExpires = subscriptionExpires; - _this._subscriptionExpiresInitial = subscriptionExpires; - _this._subscriptionExpiresLastSet = Math.floor(Date.now() / 1000); - _this._subscriptionRefresh = undefined; - _this._subscriptionRefreshLastSet = undefined; - _this._subscriptionState = subscriptionState; - _this.logger = core.loggerFactory.getLogger("sip.subscribe-dialog"); - _this.logger.log("SUBSCRIBE dialog " + _this.id + " constructed"); - return _this; - } - /** - * When a UAC receives a response that establishes a dialog, it - * constructs the state of the dialog. This state MUST be maintained - * for the duration of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.1.2 - * @param outgoingRequestMessage - Outgoing request message for dialog. - * @param incomingResponseMessage - Incoming response message creating dialog. - */ - SubscriptionDialog.initialDialogStateForSubscription = function (outgoingSubscribeRequestMessage, incomingNotifyRequestMessage) { - // If the request was sent over TLS, and the Request-URI contained a - // SIPS URI, the "secure" flag is set to TRUE. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - var secure = false; // FIXME: Currently no support for TLS. - // The route set MUST be set to the list of URIs in the Record-Route - // header field from the response, taken in reverse order and preserving - // all URI parameters. If no Record-Route header field is present in - // the response, the route set MUST be set to the empty set. This route - // set, even if empty, overrides any pre-existing route set for future - // requests in this dialog. The remote target MUST be set to the URI - // from the Contact header field of the response. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - var routeSet = incomingNotifyRequestMessage.getHeaders("record-route"); - var contact = incomingNotifyRequestMessage.parseHeader("contact"); - if (!contact) { // TODO: Review to make sure this will never happen - throw new Error("Contact undefined."); - } - if (!(contact instanceof messages_1.NameAddrHeader)) { - throw new Error("Contact not instance of NameAddrHeader."); - } - var remoteTarget = contact.uri; - // The local sequence number MUST be set to the value of the sequence - // number in the CSeq header field of the request. The remote sequence - // number MUST be empty (it is established when the remote UA sends a - // request within the dialog). The call identifier component of the - // dialog ID MUST be set to the value of the Call-ID in the request. - // The local tag component of the dialog ID MUST be set to the tag in - // the From field in the request, and the remote tag component of the - // dialog ID MUST be set to the tag in the To field of the response. A - // UAC MUST be prepared to receive a response without a tag in the To - // field, in which case the tag is considered to have a value of null. - // - // This is to maintain backwards compatibility with RFC 2543, which - // did not mandate To tags. - // - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - var localSequenceNumber = outgoingSubscribeRequestMessage.cseq; - var remoteSequenceNumber = undefined; - var callId = outgoingSubscribeRequestMessage.callId; - var localTag = outgoingSubscribeRequestMessage.fromTag; - var remoteTag = incomingNotifyRequestMessage.fromTag; - if (!callId) { // TODO: Review to make sure this will never happen - throw new Error("Call id undefined."); - } - if (!localTag) { // TODO: Review to make sure this will never happen - throw new Error("From tag undefined."); - } - if (!remoteTag) { // TODO: Review to make sure this will never happen - throw new Error("To tag undefined."); // FIXME: No backwards compatibility with RFC 2543 - } - // The remote URI MUST be set to the URI in the To field, and the local - // URI MUST be set to the URI in the From field. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - if (!outgoingSubscribeRequestMessage.from) { // TODO: Review to make sure this will never happen - throw new Error("From undefined."); - } - if (!outgoingSubscribeRequestMessage.to) { // TODO: Review to make sure this will never happen - throw new Error("To undefined."); - } - var localURI = outgoingSubscribeRequestMessage.from.uri; - var remoteURI = outgoingSubscribeRequestMessage.to.uri; - // A dialog can also be in the "early" state, which occurs when it is - // created with a provisional response, and then transition to the - // "confirmed" state when a 2xx final response arrives. - // https://tools.ietf.org/html/rfc3261#section-12 - var early = false; - var dialogState = { - id: callId + localTag + remoteTag, - early: early, - callId: callId, - localTag: localTag, - remoteTag: remoteTag, - localSequenceNumber: localSequenceNumber, - remoteSequenceNumber: remoteSequenceNumber, - localURI: localURI, - remoteURI: remoteURI, - remoteTarget: remoteTarget, - routeSet: routeSet, - secure: secure - }; - return dialogState; - }; - SubscriptionDialog.prototype.dispose = function () { - _super.prototype.dispose.call(this); - if (this.N) { - clearTimeout(this.N); - this.N = undefined; - } - this.refreshTimerClear(); - this.logger.log("SUBSCRIBE dialog " + this.id + " destroyed"); - }; - Object.defineProperty(SubscriptionDialog.prototype, "autoRefresh", { - get: function () { - return this._autoRefresh; - }, - set: function (autoRefresh) { - this._autoRefresh = true; - this.refreshTimerSet(); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SubscriptionDialog.prototype, "subscriptionEvent", { - get: function () { - return this._subscriptionEvent; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SubscriptionDialog.prototype, "subscriptionExpires", { - /** Number of seconds until subscription expires. */ - get: function () { - var secondsSinceLastSet = Math.floor(Date.now() / 1000) - this._subscriptionExpiresLastSet; - var secondsUntilExpires = this._subscriptionExpires - secondsSinceLastSet; - return Math.max(secondsUntilExpires, 0); - }, - set: function (expires) { - if (expires < 0) { - throw new Error("Expires must be greater than or equal to zero."); - } - this._subscriptionExpires = expires; - this._subscriptionExpiresLastSet = Math.floor(Date.now() / 1000); - if (this.autoRefresh) { - var refresh = this.subscriptionRefresh; - if (refresh === undefined || refresh >= expires) { - this.refreshTimerSet(); - } - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SubscriptionDialog.prototype, "subscriptionExpiresInitial", { - get: function () { - return this._subscriptionExpiresInitial; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SubscriptionDialog.prototype, "subscriptionRefresh", { - /** Number of seconds until subscription auto refresh. */ - get: function () { - if (this._subscriptionRefresh === undefined || this._subscriptionRefreshLastSet === undefined) { - return undefined; - } - var secondsSinceLastSet = Math.floor(Date.now() / 1000) - this._subscriptionRefreshLastSet; - var secondsUntilExpires = this._subscriptionRefresh - secondsSinceLastSet; - return Math.max(secondsUntilExpires, 0); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SubscriptionDialog.prototype, "subscriptionState", { - get: function () { - return this._subscriptionState; - }, - enumerable: true, - configurable: true - }); - /** - * Receive in dialog request message from transport. - * @param message - The incoming request message. - */ - SubscriptionDialog.prototype.receiveRequest = function (message) { - this.logger.log("SUBSCRIBE dialog " + this.id + " received " + message.method + " request"); - // Request within a dialog out of sequence guard. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (!this.sequenceGuard(message)) { - this.logger.log("SUBSCRIBE dialog " + this.id + " rejected out of order " + message.method + " request."); - return; - } - // Request within a dialog common processing. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - _super.prototype.receiveRequest.call(this, message); - // Switch on method and then delegate. - switch (message.method) { - case messages_1.C.NOTIFY: - this.onNotify(message); - break; - default: - this.logger.log("SUBSCRIBE dialog " + this.id + " received unimplemented " + message.method + " request"); - this.core.replyStateless(message, { statusCode: 501 }); - break; - } - }; - /** - * 4.1.2.2. Refreshing of Subscriptions - * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - */ - SubscriptionDialog.prototype.refresh = function () { - var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); - var options = {}; - options.extraHeaders = (options.extraHeaders || []).slice(); - options.extraHeaders.push(allowHeader); - options.extraHeaders.push("Event: " + this.subscriptionEvent); - options.extraHeaders.push("Expires: " + this.subscriptionExpiresInitial); - options.extraHeaders.push("Contact: " + this.core.configuration.contact.toString()); - return this.subscribe(undefined, options); - }; - /** - * 4.1.2.2. Refreshing of Subscriptions - * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - * @param delegate - Delegate to handle responses. - * @param options - Options bucket. - */ - SubscriptionDialog.prototype.subscribe = function (delegate, options) { - var _this = this; - if (options === void 0) { options = {}; } - if (this.subscriptionState !== subscription_1.SubscriptionState.Pending && this.subscriptionState !== subscription_1.SubscriptionState.Active) { - // FIXME: This needs to be a proper exception - throw new Error("Invalid state " + this.subscriptionState + ". May only re-subscribe while in state \"pending\" or \"active\"."); - } - this.logger.log("SUBSCRIBE dialog " + this.id + " sending SUBSCRIBE request"); - var uac = new re_subscribe_user_agent_client_1.ReSubscribeUserAgentClient(this, delegate, options); - // When refreshing a subscription, a subscriber starts Timer N, set to - // 64*T1, when it sends the SUBSCRIBE request. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - this.N = setTimeout(function () { return _this.timer_N(); }, timers_1.Timers.TIMER_N); - return uac; - }; - /** - * 4.4.1. Dialog Creation and Termination - * A subscription is destroyed after a notifier sends a NOTIFY request - * with a "Subscription-State" of "terminated", or in certain error - * situations described elsewhere in this document. - * https://tools.ietf.org/html/rfc6665#section-4.4.1 - */ - SubscriptionDialog.prototype.terminate = function () { - this.stateTransition(subscription_1.SubscriptionState.Terminated); - this.onTerminated(); - }; - /** - * 4.1.2.3. Unsubscribing - * https://tools.ietf.org/html/rfc6665#section-4.1.2.3 - */ - SubscriptionDialog.prototype.unsubscribe = function () { - var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); - var options = {}; - options.extraHeaders = (options.extraHeaders || []).slice(); - options.extraHeaders.push(allowHeader); - options.extraHeaders.push("Event: " + this.subscriptionEvent); - options.extraHeaders.push("Expires: 0"); - options.extraHeaders.push("Contact: " + this.core.configuration.contact.toString()); - return this.subscribe(undefined, options); - }; - /** - * Handle in dialog NOTIFY requests. - * This does not include the first NOTIFY which created the dialog. - * @param message - The incoming NOTIFY request message. - */ - SubscriptionDialog.prototype.onNotify = function (message) { - // If, for some reason, the event package designated in the "Event" - // header field of the NOTIFY request is not supported, the subscriber - // will respond with a 489 (Bad Event) response. - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - var event = message.parseHeader("Event").event; - if (!event || event !== this.subscriptionEvent) { - this.core.replyStateless(message, { statusCode: 489 }); - return; - } - // In the state diagram, "Re-subscription times out" means that an - // attempt to refresh or update the subscription using a new SUBSCRIBE - // request does not result in a NOTIFY request before the corresponding - // Timer N expires. - // https://tools.ietf.org/html/rfc6665#section-4.1.2 - if (this.N) { - clearTimeout(this.N); - this.N = undefined; - } - // NOTIFY requests MUST contain "Subscription-State" header fields that - // indicate the status of the subscription. - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - var subscriptionState = message.parseHeader("Subscription-State"); - if (!subscriptionState || !subscriptionState.state) { - this.core.replyStateless(message, { statusCode: 489 }); - return; - } - var state = subscriptionState.state; - var expires = subscriptionState.expires ? Math.max(subscriptionState.expires, 0) : undefined; - // Update our state and expiration. - switch (state) { - case "pending": - this.stateTransition(subscription_1.SubscriptionState.Pending, expires); - break; - case "active": - this.stateTransition(subscription_1.SubscriptionState.Active, expires); - break; - case "terminated": - this.stateTransition(subscription_1.SubscriptionState.Terminated, expires); - break; - default: - this.logger.warn("Unrecognized subscription state."); - break; - } - // Delegate remainder of NOTIFY handling. - var uas = new notify_user_agent_server_1.NotifyUserAgentServer(this, message); - if (this.delegate && this.delegate.onNotify) { - this.delegate.onNotify(uas); - } - else { - uas.accept(); - } - }; - SubscriptionDialog.prototype.onRefresh = function (request) { - if (this.delegate && this.delegate.onRefresh) { - this.delegate.onRefresh(request); - } - }; - SubscriptionDialog.prototype.onTerminated = function () { - if (this.delegate && this.delegate.onTerminated) { - this.delegate.onTerminated(); - } - }; - SubscriptionDialog.prototype.refreshTimerClear = function () { - if (this.refreshTimer) { - clearTimeout(this.refreshTimer); - this.refreshTimer = undefined; - } - }; - SubscriptionDialog.prototype.refreshTimerSet = function () { - var _this = this; - this.refreshTimerClear(); - if (this.autoRefresh && this.subscriptionExpires > 0) { - var refresh = this.subscriptionExpires * 900; - this._subscriptionRefresh = Math.floor(refresh / 1000); - this._subscriptionRefreshLastSet = Math.floor(Date.now() / 1000); - this.refreshTimer = setTimeout(function () { - _this.refreshTimer = undefined; - _this._subscriptionRefresh = undefined; - _this._subscriptionRefreshLastSet = undefined; - _this.onRefresh(_this.refresh()); - }, refresh); - } - }; - SubscriptionDialog.prototype.stateTransition = function (newState, newExpires) { - var _this = this; - // Assert valid state transitions. - var invalidStateTransition = function () { - _this.logger.warn("Invalid subscription state transition from " + _this.subscriptionState + " to " + newState); - }; - switch (newState) { - case subscription_1.SubscriptionState.Initial: - invalidStateTransition(); - return; - case subscription_1.SubscriptionState.NotifyWait: - invalidStateTransition(); - return; - case subscription_1.SubscriptionState.Pending: - if (this.subscriptionState !== subscription_1.SubscriptionState.NotifyWait && - this.subscriptionState !== subscription_1.SubscriptionState.Pending) { - invalidStateTransition(); - return; - } - break; - case subscription_1.SubscriptionState.Active: - if (this.subscriptionState !== subscription_1.SubscriptionState.NotifyWait && - this.subscriptionState !== subscription_1.SubscriptionState.Pending && - this.subscriptionState !== subscription_1.SubscriptionState.Active) { - invalidStateTransition(); - return; - } - break; - case subscription_1.SubscriptionState.Terminated: - if (this.subscriptionState !== subscription_1.SubscriptionState.NotifyWait && - this.subscriptionState !== subscription_1.SubscriptionState.Pending && - this.subscriptionState !== subscription_1.SubscriptionState.Active) { - invalidStateTransition(); - return; - } - break; - default: - invalidStateTransition(); - return; - } - // If the "Subscription-State" value is "pending", the subscription has - // been received by the notifier, but there is insufficient policy - // information to grant or deny the subscription yet. If the header - // field also contains an "expires" parameter, the subscriber SHOULD - // take it as the authoritative subscription duration and adjust - // accordingly. No further action is necessary on the part of the - // subscriber. The "retry-after" and "reason" parameters have no - // semantics for "pending". - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - if (newState === subscription_1.SubscriptionState.Pending) { - if (newExpires) { - this.subscriptionExpires = newExpires; - } - } - // If the "Subscription-State" header field value is "active", it means - // that the subscription has been accepted and (in general) has been - // authorized. If the header field also contains an "expires" - // parameter, the subscriber SHOULD take it as the authoritative - // subscription duration and adjust accordingly. The "retry-after" and - // "reason" parameters have no semantics for "active". - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - if (newState === subscription_1.SubscriptionState.Active) { - if (newExpires) { - this.subscriptionExpires = newExpires; - } - } - // If the "Subscription-State" value is "terminated", the subscriber - // MUST consider the subscription terminated. The "expires" parameter - // has no semantics for "terminated" -- notifiers SHOULD NOT include an - // "expires" parameter on a "Subscription-State" header field with a - // value of "terminated", and subscribers MUST ignore any such - // parameter, if present. - if (newState === subscription_1.SubscriptionState.Terminated) { - this.dispose(); - } - this._subscriptionState = newState; - }; - /** - * When refreshing a subscription, a subscriber starts Timer N, set to - * 64*T1, when it sends the SUBSCRIBE request. If this Timer N expires - * prior to the receipt of a NOTIFY request, the subscriber considers - * the subscription terminated. If the subscriber receives a success - * response to the SUBSCRIBE request that indicates that no NOTIFY - * request will be generated -- such as the 204 response defined for use - * with the optional extension described in [RFC5839] -- then it MUST - * cancel Timer N. - * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - */ - SubscriptionDialog.prototype.timer_N = function () { - if (this.subscriptionState !== subscription_1.SubscriptionState.Terminated) { - this.stateTransition(subscription_1.SubscriptionState.Terminated); - this.onTerminated(); - } - }; - return SubscriptionDialog; -}(dialog_1.Dialog)); -exports.SubscriptionDialog = SubscriptionDialog; diff --git a/lib/core/exceptions/exception.d.ts b/lib/core/exceptions/exception.d.ts deleted file mode 100644 index 476b4fad0..000000000 --- a/lib/core/exceptions/exception.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -/** - * An Exception is considered a condition that a reasonable application may wish to catch. - * An Error indicates serious problems that a reasonable application should not try to catch. - * @public - */ -export declare abstract class Exception extends Error { - protected constructor(message?: string); -} -//# sourceMappingURL=exception.d.ts.map \ No newline at end of file diff --git a/lib/core/exceptions/exception.d.ts.map b/lib/core/exceptions/exception.d.ts.map deleted file mode 100644 index d9b0b27c2..000000000 --- a/lib/core/exceptions/exception.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"exception.d.ts","sourceRoot":"","sources":["../../../src/core/exceptions/exception.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,8BAAsB,SAAU,SAAQ,KAAK;IAC3C,SAAS,aAAa,OAAO,CAAC,EAAE,MAAM;CAIvC"} \ No newline at end of file diff --git a/lib/core/exceptions/exception.js b/lib/core/exceptions/exception.js deleted file mode 100644 index 4e25fb887..000000000 --- a/lib/core/exceptions/exception.js +++ /dev/null @@ -1,19 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -/** - * An Exception is considered a condition that a reasonable application may wish to catch. - * An Error indicates serious problems that a reasonable application should not try to catch. - * @public - */ -var Exception = /** @class */ (function (_super) { - tslib_1.__extends(Exception, _super); - function Exception(message) { - var _newTarget = this.constructor; - var _this = _super.call(this, message) || this; - Object.setPrototypeOf(_this, _newTarget.prototype); // restore prototype chain - return _this; - } - return Exception; -}(Error)); -exports.Exception = Exception; diff --git a/lib/core/exceptions/index.d.ts b/lib/core/exceptions/index.d.ts deleted file mode 100644 index fad2dd3c9..000000000 --- a/lib/core/exceptions/index.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -export * from "./exception"; -export * from "./transaction-state-error"; -export * from "./transport-error"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/core/exceptions/index.d.ts.map b/lib/core/exceptions/index.d.ts.map deleted file mode 100644 index cb6188c01..000000000 --- a/lib/core/exceptions/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/exceptions/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,cAAc,2BAA2B,CAAC;AAC1C,cAAc,mBAAmB,CAAC"} \ No newline at end of file diff --git a/lib/core/exceptions/index.js b/lib/core/exceptions/index.js deleted file mode 100644 index 4b11b7ca6..000000000 --- a/lib/core/exceptions/index.js +++ /dev/null @@ -1,6 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -tslib_1.__exportStar(require("./exception"), exports); -tslib_1.__exportStar(require("./transaction-state-error"), exports); -tslib_1.__exportStar(require("./transport-error"), exports); diff --git a/lib/core/exceptions/transaction-state-error.d.ts b/lib/core/exceptions/transaction-state-error.d.ts deleted file mode 100644 index efac75de6..000000000 --- a/lib/core/exceptions/transaction-state-error.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { Exception } from "./exception"; -/** - * Indicates that the operation could not be completed given the current transaction state. - * @public - */ -export declare class TransactionStateError extends Exception { - constructor(message?: string); -} -//# sourceMappingURL=transaction-state-error.d.ts.map \ No newline at end of file diff --git a/lib/core/exceptions/transaction-state-error.d.ts.map b/lib/core/exceptions/transaction-state-error.d.ts.map deleted file mode 100644 index a9ee2adab..000000000 --- a/lib/core/exceptions/transaction-state-error.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"transaction-state-error.d.ts","sourceRoot":"","sources":["../../../src/core/exceptions/transaction-state-error.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC;;;GAGG;AACH,qBAAa,qBAAsB,SAAQ,SAAS;gBACtC,OAAO,CAAC,EAAE,MAAM;CAG7B"} \ No newline at end of file diff --git a/lib/core/exceptions/transaction-state-error.js b/lib/core/exceptions/transaction-state-error.js deleted file mode 100644 index 19b33884b..000000000 --- a/lib/core/exceptions/transaction-state-error.js +++ /dev/null @@ -1,16 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var exception_1 = require("./exception"); -/** - * Indicates that the operation could not be completed given the current transaction state. - * @public - */ -var TransactionStateError = /** @class */ (function (_super) { - tslib_1.__extends(TransactionStateError, _super); - function TransactionStateError(message) { - return _super.call(this, message ? message : "Transaction state error.") || this; - } - return TransactionStateError; -}(exception_1.Exception)); -exports.TransactionStateError = TransactionStateError; diff --git a/lib/core/exceptions/transport-error.d.ts b/lib/core/exceptions/transport-error.d.ts deleted file mode 100644 index 29db45f93..000000000 --- a/lib/core/exceptions/transport-error.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { Exception } from "./exception"; -/** - * Transport error. - * @public - */ -export declare class TransportError extends Exception { - constructor(message?: string); -} -//# sourceMappingURL=transport-error.d.ts.map \ No newline at end of file diff --git a/lib/core/exceptions/transport-error.d.ts.map b/lib/core/exceptions/transport-error.d.ts.map deleted file mode 100644 index 7f7e3f494..000000000 --- a/lib/core/exceptions/transport-error.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"transport-error.d.ts","sourceRoot":"","sources":["../../../src/core/exceptions/transport-error.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC;;;GAGG;AACH,qBAAa,cAAe,SAAQ,SAAS;gBAC/B,OAAO,CAAC,EAAE,MAAM;CAG7B"} \ No newline at end of file diff --git a/lib/core/exceptions/transport-error.js b/lib/core/exceptions/transport-error.js deleted file mode 100644 index c53d994ab..000000000 --- a/lib/core/exceptions/transport-error.js +++ /dev/null @@ -1,16 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var exception_1 = require("./exception"); -/** - * Transport error. - * @public - */ -var TransportError = /** @class */ (function (_super) { - tslib_1.__extends(TransportError, _super); - function TransportError(message) { - return _super.call(this, message ? message : "Unspecified transport error.") || this; - } - return TransportError; -}(exception_1.Exception)); -exports.TransportError = TransportError; diff --git a/lib/core/index.d.ts b/lib/core/index.d.ts deleted file mode 100644 index aeaad6230..000000000 --- a/lib/core/index.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -/** - * A core library implementing low level SIP protocol elements. - * @packageDocumentation - */ -export * from "./dialogs"; -export * from "./exceptions"; -export * from "./log"; -export * from "./messages"; -export * from "./session"; -export * from "./subscription"; -export * from "./transactions"; -export * from "./user-agent-core"; -export * from "./user-agents"; -export * from "./timers"; -export * from "./transport"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/core/index.d.ts.map b/lib/core/index.d.ts.map deleted file mode 100644 index d5d7687f4..000000000 --- a/lib/core/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/core/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,cAAc,WAAW,CAAC;AAC1B,cAAc,cAAc,CAAC;AAC7B,cAAc,OAAO,CAAC;AACtB,cAAc,YAAY,CAAC;AAC3B,cAAc,WAAW,CAAC;AAC1B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,mBAAmB,CAAC;AAClC,cAAc,eAAe,CAAC;AAG9B,cAAc,UAAU,CAAC;AACzB,cAAc,aAAa,CAAC"} \ No newline at end of file diff --git a/lib/core/index.js b/lib/core/index.js deleted file mode 100644 index 34a50e913..000000000 --- a/lib/core/index.js +++ /dev/null @@ -1,20 +0,0 @@ -"use strict"; -/** - * A core library implementing low level SIP protocol elements. - * @packageDocumentation - */ -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -// Directories -tslib_1.__exportStar(require("./dialogs"), exports); -tslib_1.__exportStar(require("./exceptions"), exports); -tslib_1.__exportStar(require("./log"), exports); -tslib_1.__exportStar(require("./messages"), exports); -tslib_1.__exportStar(require("./session"), exports); -tslib_1.__exportStar(require("./subscription"), exports); -tslib_1.__exportStar(require("./transactions"), exports); -tslib_1.__exportStar(require("./user-agent-core"), exports); -tslib_1.__exportStar(require("./user-agents"), exports); -// Files -tslib_1.__exportStar(require("./timers"), exports); -tslib_1.__exportStar(require("./transport"), exports); diff --git a/lib/core/log/index.d.ts b/lib/core/log/index.d.ts deleted file mode 100644 index 011860395..000000000 --- a/lib/core/log/index.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -export * from "./levels"; -export * from "./logger-factory"; -export * from "./logger"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/core/log/index.d.ts.map b/lib/core/log/index.d.ts.map deleted file mode 100644 index b9ae7b73a..000000000 --- a/lib/core/log/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/log/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAC;AACzB,cAAc,kBAAkB,CAAC;AACjC,cAAc,UAAU,CAAC"} \ No newline at end of file diff --git a/lib/core/log/index.js b/lib/core/log/index.js deleted file mode 100644 index 394ac7e28..000000000 --- a/lib/core/log/index.js +++ /dev/null @@ -1,6 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -tslib_1.__exportStar(require("./levels"), exports); -tslib_1.__exportStar(require("./logger-factory"), exports); -tslib_1.__exportStar(require("./logger"), exports); diff --git a/lib/core/log/levels.d.ts b/lib/core/log/levels.d.ts deleted file mode 100644 index 49a9b7296..000000000 --- a/lib/core/log/levels.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -/** - * Log levels. - * @public - */ -export declare enum Levels { - error = 0, - warn = 1, - log = 2, - debug = 3 -} -//# sourceMappingURL=levels.d.ts.map \ No newline at end of file diff --git a/lib/core/log/levels.d.ts.map b/lib/core/log/levels.d.ts.map deleted file mode 100644 index 494d285b6..000000000 --- a/lib/core/log/levels.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"levels.d.ts","sourceRoot":"","sources":["../../../src/core/log/levels.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,oBAAY,MAAM;IAChB,KAAK,IAAA;IACL,IAAI,IAAA;IACJ,GAAG,IAAA;IACH,KAAK,IAAA;CACN"} \ No newline at end of file diff --git a/lib/core/log/levels.js b/lib/core/log/levels.js deleted file mode 100644 index dfa4ef191..000000000 --- a/lib/core/log/levels.js +++ /dev/null @@ -1,13 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * Log levels. - * @public - */ -var Levels; -(function (Levels) { - Levels[Levels["error"] = 0] = "error"; - Levels[Levels["warn"] = 1] = "warn"; - Levels[Levels["log"] = 2] = "log"; - Levels[Levels["debug"] = 3] = "debug"; -})(Levels = exports.Levels || (exports.Levels = {})); diff --git a/lib/core/log/logger-factory.d.ts b/lib/core/log/logger-factory.d.ts deleted file mode 100644 index d0c22a2af..000000000 --- a/lib/core/log/logger-factory.d.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { Levels } from "./levels"; -import { Logger } from "./logger"; -/** - * Logger. - * @public - */ -export declare class LoggerFactory { - builtinEnabled: boolean; - private _level; - private _connector; - private loggers; - private logger; - constructor(); - level: Levels; - connector: ((level: string, category: string, label: string | undefined, content: any) => void) | undefined; - getLogger(category: string, label?: string): Logger; - genericLog(levelToLog: Levels, category: string, label: string | undefined, content: any): void; - private print; -} -//# sourceMappingURL=logger-factory.d.ts.map \ No newline at end of file diff --git a/lib/core/log/logger-factory.d.ts.map b/lib/core/log/logger-factory.d.ts.map deleted file mode 100644 index fc766d631..000000000 --- a/lib/core/log/logger-factory.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"logger-factory.d.ts","sourceRoot":"","sources":["../../../src/core/log/logger-factory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAClC,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAElC;;;GAGG;AACH,qBAAa,aAAa;IACjB,cAAc,EAAE,OAAO,CAAQ;IAEtC,OAAO,CAAC,MAAM,CAAsB;IACpC,OAAO,CAAC,UAAU,CAAmG;IAErH,OAAO,CAAC,OAAO,CAAW;IAC1B,OAAO,CAAC,MAAM,CAAS;;IAMnB,KAAK,EAAI,MAAM;IAaf,SAAS,EAAI,CAAC,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,SAAS,EAAE,OAAO,EAAE,GAAG,KAAK,IAAI,CAAC,GAAG,SAAS;IAe1G,SAAS,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM;IAYnD,UAAU,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,SAAS,EAAE,OAAO,EAAE,GAAG,GAAG,IAAI;IAYtG,OAAO,CAAC,KAAK;CA6Bd"} \ No newline at end of file diff --git a/lib/core/log/logger-factory.js b/lib/core/log/logger-factory.js deleted file mode 100644 index 47cc61303..000000000 --- a/lib/core/log/logger-factory.js +++ /dev/null @@ -1,107 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var levels_1 = require("./levels"); -var logger_1 = require("./logger"); -/** - * Logger. - * @public - */ -var LoggerFactory = /** @class */ (function () { - function LoggerFactory() { - this.builtinEnabled = true; - this._level = levels_1.Levels.log; - this.loggers = {}; - this.logger = this.getLogger("sip:loggerfactory"); - } - Object.defineProperty(LoggerFactory.prototype, "level", { - get: function () { return this._level; }, - set: function (newLevel) { - if (newLevel >= 0 && newLevel <= 3) { - this._level = newLevel; - } - else if (newLevel > 3) { - this._level = 3; - } - else if (levels_1.Levels.hasOwnProperty(newLevel)) { - this._level = newLevel; - } - else { - this.logger.error("invalid 'level' parameter value: " + JSON.stringify(newLevel)); - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(LoggerFactory.prototype, "connector", { - get: function () { - return this._connector; - }, - set: function (value) { - if (!value) { - this._connector = undefined; - } - else if (typeof value === "function") { - this._connector = value; - } - else { - this.logger.error("invalid 'connector' parameter value: " + JSON.stringify(value)); - } - }, - enumerable: true, - configurable: true - }); - LoggerFactory.prototype.getLogger = function (category, label) { - if (label && this.level === 3) { - return new logger_1.Logger(this, category, label); - } - else if (this.loggers[category]) { - return this.loggers[category]; - } - else { - var logger = new logger_1.Logger(this, category); - this.loggers[category] = logger; - return logger; - } - }; - LoggerFactory.prototype.genericLog = function (levelToLog, category, label, content) { - if (this.level >= levelToLog) { - if (this.builtinEnabled) { - this.print(levelToLog, category, label, content); - } - } - if (this.connector) { - this.connector(levels_1.Levels[levelToLog], category, label, content); - } - }; - LoggerFactory.prototype.print = function (levelToLog, category, label, content) { - if (typeof content === "string") { - var prefix = [new Date(), category]; - if (label) { - prefix.push(label); - } - content = prefix.concat(content).join(" | "); - } - switch (levelToLog) { - case levels_1.Levels.error: - // tslint:disable-next-line:no-console - console.error(content); - break; - case levels_1.Levels.warn: - // tslint:disable-next-line:no-console - console.warn(content); - break; - case levels_1.Levels.log: - // tslint:disable-next-line:no-console - console.log(content); - break; - case levels_1.Levels.debug: - // tslint:disable-next-line:no-console - console.debug(content); - break; - default: - break; - } - }; - return LoggerFactory; -}()); -exports.LoggerFactory = LoggerFactory; diff --git a/lib/core/log/logger.d.ts b/lib/core/log/logger.d.ts deleted file mode 100644 index b48b629cc..000000000 --- a/lib/core/log/logger.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { LoggerFactory } from "./logger-factory"; -/** - * Logger. - * @public - */ -export declare class Logger { - private logger; - private category; - private label; - constructor(logger: LoggerFactory, category: string, label?: string); - error(content: string): void; - warn(content: string): void; - log(content: string): void; - debug(content: string): void; - private genericLog; -} -//# sourceMappingURL=logger.d.ts.map \ No newline at end of file diff --git a/lib/core/log/logger.d.ts.map b/lib/core/log/logger.d.ts.map deleted file mode 100644 index 313f35dc6..000000000 --- a/lib/core/log/logger.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"logger.d.ts","sourceRoot":"","sources":["../../../src/core/log/logger.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAEjD;;;GAGG;AACH,qBAAa,MAAM;IACjB,OAAO,CAAC,MAAM,CAAgB;IAC9B,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,KAAK,CAAqB;gBAEtB,MAAM,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM;IAM5D,KAAK,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAC5B,IAAI,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAC3B,GAAG,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAC1B,KAAK,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAEnC,OAAO,CAAC,UAAU;CAGnB"} \ No newline at end of file diff --git a/lib/core/log/logger.js b/lib/core/log/logger.js deleted file mode 100644 index 959d93f9f..000000000 --- a/lib/core/log/logger.js +++ /dev/null @@ -1,23 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var levels_1 = require("./levels"); -/** - * Logger. - * @public - */ -var Logger = /** @class */ (function () { - function Logger(logger, category, label) { - this.logger = logger; - this.category = category; - this.label = label; - } - Logger.prototype.error = function (content) { this.genericLog(levels_1.Levels.error, content); }; - Logger.prototype.warn = function (content) { this.genericLog(levels_1.Levels.warn, content); }; - Logger.prototype.log = function (content) { this.genericLog(levels_1.Levels.log, content); }; - Logger.prototype.debug = function (content) { this.genericLog(levels_1.Levels.debug, content); }; - Logger.prototype.genericLog = function (level, content) { - this.logger.genericLog(level, this.category, this.label, content); - }; - return Logger; -}()); -exports.Logger = Logger; diff --git a/lib/core/messages/body.d.ts b/lib/core/messages/body.d.ts deleted file mode 100644 index 74cadcc17..000000000 --- a/lib/core/messages/body.d.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { IncomingRequestMessage } from "./incoming-request-message"; -import { IncomingResponseMessage } from "./incoming-response-message"; -import { OutgoingRequestMessage } from "./outgoing-request-message"; -/** - * Message body. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-7.4 - * @public - */ -export interface Body { - /** - * If the Content-Disposition header field is missing, bodies of - * Content-Type application/sdp imply the disposition "session", while - * other content types imply "render". - * https://tools.ietf.org/html/rfc3261#section-13.2.1 - * For backward-compatibility, if the Content-Disposition header field - * is missing, the server SHOULD assume bodies of Content-Type - * application/sdp are the disposition "session", while other content - * types are "render". - * https://tools.ietf.org/html/rfc3261#section-20.11 - */ - contentDisposition: string; - /** - * The Content-Type header field indicates the media type of the - * message-body sent to the recipient. The Content-Type header field - * MUST be present if the body is not empty. If the body is empty, - * and a Content-Type header field is present, it indicates that the body - * of the specific type has zero length (for example, an empty audio file). - * https://tools.ietf.org/html/rfc3261#section-20.15 - */ - contentType: string; - /** - * Requests, including new requests defined in extensions to this - * specification, MAY contain message bodies unless otherwise noted. - * The interpretation of the body depends on the request method. - * For response messages, the request method and the response status - * code determine the type and interpretation of any message body. All - * responses MAY include a body. - * https://tools.ietf.org/html/rfc3261#section-7.4 - */ - content: string; -} -/** - * Create a Body given a legacy body type. - * @param bodyLegacy - Body Object - * @internal - */ -export declare function fromBodyLegacy(bodyLegacy: string | { - body: string; - contentType: string; -}): Body; -/** - * Given a message, get a normalized body. - * The content disposition is inferred if not set. - * @param message - The message. - * @internal - */ -export declare function getBody(message: IncomingRequestMessage | IncomingResponseMessage | OutgoingRequestMessage | Body): Body | undefined; -/** - * User-Defined Type Guard for Body. - * @param body - Body to check. - * @internal - */ -export declare function isBody(body: any): body is Body; -//# sourceMappingURL=body.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/body.d.ts.map b/lib/core/messages/body.d.ts.map deleted file mode 100644 index ffc71e396..000000000 --- a/lib/core/messages/body.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"body.d.ts","sourceRoot":"","sources":["../../../src/core/messages/body.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AACpE,OAAO,EAAE,uBAAuB,EAAE,MAAM,6BAA6B,CAAC;AACtE,OAAO,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AAEpE;;;;;GAKG;AACH,MAAM,WAAW,IAAI;IACnB;;;;;;;;;;OAUG;IACH,kBAAkB,EAAE,MAAM,CAAC;IAE3B;;;;;;;OAOG;IACH,WAAW,EAAE,MAAM,CAAC;IAEpB;;;;;;;;OAQG;IACH,OAAO,EAAE,MAAM,CAAC;CACjB;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,UAAU,EAAE,MAAM,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAM/F;AAED;;;;;GAKG;AACH,wBAAgB,OAAO,CACrB,OAAO,EAAE,sBAAsB,GAAG,uBAAuB,GAAG,sBAAsB,GAAG,IAAI,GACxF,IAAI,GAAG,SAAS,CA4ElB;AAED;;;;GAIG;AACH,wBAAgB,MAAM,CAAC,IAAI,EAAE,GAAG,GAAG,IAAI,IAAI,IAAI,CAK9C"} \ No newline at end of file diff --git a/lib/core/messages/body.js b/lib/core/messages/body.js deleted file mode 100644 index 7d0208f71..000000000 --- a/lib/core/messages/body.js +++ /dev/null @@ -1,120 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var incoming_request_message_1 = require("./incoming-request-message"); -var incoming_response_message_1 = require("./incoming-response-message"); -var outgoing_request_message_1 = require("./outgoing-request-message"); -/** - * Create a Body given a legacy body type. - * @param bodyLegacy - Body Object - * @internal - */ -function fromBodyLegacy(bodyLegacy) { - var content = (typeof bodyLegacy === "string") ? bodyLegacy : bodyLegacy.body; - var contentType = (typeof bodyLegacy === "string") ? "application/sdp" : bodyLegacy.contentType; - var contentDisposition = contentTypeToContentDisposition(contentType); - var body = { contentDisposition: contentDisposition, contentType: contentType, content: content }; - return body; -} -exports.fromBodyLegacy = fromBodyLegacy; -/** - * Given a message, get a normalized body. - * The content disposition is inferred if not set. - * @param message - The message. - * @internal - */ -function getBody(message) { - var contentDisposition; - var contentType; - var content; - // We're in UAS role, receiving incoming request - if (message instanceof incoming_request_message_1.IncomingRequestMessage) { - if (message.body) { - // FIXME: Parsing needs typing - var parse = message.parseHeader("Content-Disposition"); - contentDisposition = parse ? parse.type : undefined; - contentType = message.parseHeader("Content-Type"); - content = message.body; - } - } - // We're in UAC role, receiving incoming response - if (message instanceof incoming_response_message_1.IncomingResponseMessage) { - if (message.body) { - // FIXME: Parsing needs typing - var parse = message.parseHeader("Content-Disposition"); - contentDisposition = parse ? parse.type : undefined; - contentType = message.parseHeader("Content-Type"); - content = message.body; - } - } - // We're in UAC role, sending outgoing request - if (message instanceof outgoing_request_message_1.OutgoingRequestMessage) { - if (message.body) { - contentDisposition = message.getHeader("Content-Disposition"); - contentType = message.getHeader("Content-Type"); - if (typeof message.body === "string") { - // FIXME: OutgoingRequest should not allow a "string" body without a "Content-Type" header. - if (!contentType) { - throw new Error("Header content type header does not equal body content type."); - } - content = message.body; - } - else { - // FIXME: OutgoingRequest should not allow the "Content-Type" header not to match th body content type - if (contentType && contentType !== message.body.contentType) { - throw new Error("Header content type header does not equal body content type."); - } - contentType = message.body.contentType; - content = message.body.body; - } - } - } - // We're in UAS role, sending outgoing response - if (isBody(message)) { - contentDisposition = message.contentDisposition; - contentType = message.contentType; - content = message.content; - } - // No content, no body. - if (!content) { - return undefined; - } - if (contentType && !contentDisposition) { - contentDisposition = contentTypeToContentDisposition(contentType); - } - if (!contentDisposition) { - throw new Error("Content disposition undefined."); - } - if (!contentType) { - throw new Error("Content type undefined."); - } - return { - contentDisposition: contentDisposition, - contentType: contentType, - content: content - }; -} -exports.getBody = getBody; -/** - * User-Defined Type Guard for Body. - * @param body - Body to check. - * @internal - */ -function isBody(body) { - return body && - typeof body.content === "string" && - typeof body.contentType === "string" && - body.contentDisposition === undefined ? true : typeof body.contentDisposition === "string"; -} -exports.isBody = isBody; -// If the Content-Disposition header field is missing, bodies of -// Content-Type application/sdp imply the disposition "session", while -// other content types imply "render". -// https://tools.ietf.org/html/rfc3261#section-13.2.1 -function contentTypeToContentDisposition(contentType) { - if (contentType === "application/sdp") { - return "session"; - } - else { - return "render"; - } -} diff --git a/lib/core/messages/digest-authentication.d.ts b/lib/core/messages/digest-authentication.d.ts deleted file mode 100644 index f787b0571..000000000 --- a/lib/core/messages/digest-authentication.d.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { LoggerFactory } from "../log"; -import { OutgoingRequestMessage } from "./outgoing-request-message"; -/** - * Digest Authentication. - * @internal - */ -export declare class DigestAuthentication { - stale: boolean | undefined; - private logger; - private username; - private password; - private cnonce; - private nc; - private ncHex; - private response; - private algorithm; - private realm; - private nonce; - private opaque; - private qop; - private method; - private uri; - /** - * Constructor. - * @param loggerFactory - LoggerFactory. - * @param username - Username. - * @param password - Password. - */ - constructor(loggerFactory: LoggerFactory, username: string | undefined, password: string | undefined); - /** - * Performs Digest authentication given a SIP request and the challenge - * received in a response to that request. - * @param request - - * @param challenge - - * @returns true if credentials were successfully generated, false otherwise. - */ - authenticate(request: OutgoingRequestMessage, challenge: any, body?: string): boolean; - /** - * Return the Proxy-Authorization or WWW-Authorization header value. - */ - toString(): string; - /** - * Generate the 'nc' value as required by Digest in this.ncHex by reading this.nc. - */ - private updateNcHex; - /** - * Generate Digest 'response' value. - */ - private calculateResponse; -} -//# sourceMappingURL=digest-authentication.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/digest-authentication.d.ts.map b/lib/core/messages/digest-authentication.d.ts.map deleted file mode 100644 index 62fe80c61..000000000 --- a/lib/core/messages/digest-authentication.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"digest-authentication.d.ts","sourceRoot":"","sources":["../../../src/core/messages/digest-authentication.ts"],"names":[],"mappings":"AAEA,OAAO,EAAU,aAAa,EAAE,MAAM,QAAQ,CAAC;AAC/C,OAAO,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AAIpE;;;GAGG;AACH,qBAAa,oBAAoB;IACxB,KAAK,EAAE,OAAO,GAAG,SAAS,CAAC;IAElC,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,QAAQ,CAAqB;IACrC,OAAO,CAAC,QAAQ,CAAqB;IACrC,OAAO,CAAC,MAAM,CAAqB;IACnC,OAAO,CAAC,EAAE,CAAS;IACnB,OAAO,CAAC,KAAK,CAAS;IACtB,OAAO,CAAC,QAAQ,CAAkB;IAClC,OAAO,CAAC,SAAS,CAAqB;IACtC,OAAO,CAAC,KAAK,CAAqB;IAClC,OAAO,CAAC,KAAK,CAAqB;IAClC,OAAO,CAAC,MAAM,CAAqB;IACnC,OAAO,CAAC,GAAG,CAAqB;IAChC,OAAO,CAAC,MAAM,CAAqB;IACnC,OAAO,CAAC,GAAG,CAA2B;IAEtC;;;;;OAKG;gBACS,aAAa,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,GAAG,SAAS,EAAE,QAAQ,EAAE,MAAM,GAAG,SAAS;IAQpG;;;;;;OAMG;IACI,YAAY,CAAC,OAAO,EAAE,sBAAsB,EAAE,SAAS,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,OAAO;IA+D5F;;OAEG;IACI,QAAQ,IAAI,MAAM;IAwBzB;;OAEG;IACH,OAAO,CAAC,WAAW;IAKnB;;OAEG;IACH,OAAO,CAAC,iBAAiB;CAyB1B"} \ No newline at end of file diff --git a/lib/core/messages/digest-authentication.js b/lib/core/messages/digest-authentication.js deleted file mode 100644 index 360f1d6d1..000000000 --- a/lib/core/messages/digest-authentication.js +++ /dev/null @@ -1,146 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var md5_1 = tslib_1.__importDefault(require("crypto-js/md5")); -var utils_1 = require("./utils"); -/** - * Digest Authentication. - * @internal - */ -var DigestAuthentication = /** @class */ (function () { - /** - * Constructor. - * @param loggerFactory - LoggerFactory. - * @param username - Username. - * @param password - Password. - */ - function DigestAuthentication(loggerFactory, username, password) { - this.logger = loggerFactory.getLogger("sipjs.digestauthentication"); - this.username = username; - this.password = password; - this.nc = 0; - this.ncHex = "00000000"; - } - /** - * Performs Digest authentication given a SIP request and the challenge - * received in a response to that request. - * @param request - - * @param challenge - - * @returns true if credentials were successfully generated, false otherwise. - */ - DigestAuthentication.prototype.authenticate = function (request, challenge, body) { - // Inspect and validate the challenge. - this.algorithm = challenge.algorithm; - this.realm = challenge.realm; - this.nonce = challenge.nonce; - this.opaque = challenge.opaque; - this.stale = challenge.stale; - if (this.algorithm) { - if (this.algorithm !== "MD5") { - this.logger.warn("challenge with Digest algorithm different than 'MD5', authentication aborted"); - return false; - } - } - else { - this.algorithm = "MD5"; - } - if (!this.realm) { - this.logger.warn("challenge without Digest realm, authentication aborted"); - return false; - } - if (!this.nonce) { - this.logger.warn("challenge without Digest nonce, authentication aborted"); - return false; - } - // 'qop' can contain a list of values (Array). Let's choose just one. - if (challenge.qop) { - if (challenge.qop.indexOf("auth") > -1) { - this.qop = "auth"; - } - else if (challenge.qop.indexOf("auth-int") > -1) { - this.qop = "auth-int"; - } - else { - // Otherwise 'qop' is present but does not contain 'auth' or 'auth-int', so abort here. - this.logger.warn("challenge without Digest qop different than 'auth' or 'auth-int', authentication aborted"); - return false; - } - } - else { - this.qop = undefined; - } - // Fill other attributes. - this.method = request.method; - this.uri = request.ruri; - this.cnonce = utils_1.createRandomToken(12); - this.nc += 1; - this.updateNcHex(); - // nc-value = 8LHEX. Max value = 'FFFFFFFF'. - if (this.nc === 4294967296) { - this.nc = 1; - this.ncHex = "00000001"; - } - // Calculate the Digest "response" value. - this.calculateResponse(body); - return true; - }; - /** - * Return the Proxy-Authorization or WWW-Authorization header value. - */ - DigestAuthentication.prototype.toString = function () { - var authParams = []; - if (!this.response) { - throw new Error("response field does not exist, cannot generate Authorization header"); - } - authParams.push("algorithm=" + this.algorithm); - authParams.push('username="' + this.username + '"'); - authParams.push('realm="' + this.realm + '"'); - authParams.push('nonce="' + this.nonce + '"'); - authParams.push('uri="' + this.uri + '"'); - authParams.push('response="' + this.response + '"'); - if (this.opaque) { - authParams.push('opaque="' + this.opaque + '"'); - } - if (this.qop) { - authParams.push("qop=" + this.qop); - authParams.push('cnonce="' + this.cnonce + '"'); - authParams.push("nc=" + this.ncHex); - } - return "Digest " + authParams.join(", "); - }; - /** - * Generate the 'nc' value as required by Digest in this.ncHex by reading this.nc. - */ - DigestAuthentication.prototype.updateNcHex = function () { - var hex = Number(this.nc).toString(16); - this.ncHex = "00000000".substr(0, 8 - hex.length) + hex; - }; - /** - * Generate Digest 'response' value. - */ - DigestAuthentication.prototype.calculateResponse = function (body) { - var ha2; - // HA1 = MD5(A1) = MD5(username:realm:password) - var ha1 = md5_1.default(this.username + ":" + this.realm + ":" + this.password); - if (this.qop === "auth") { - // HA2 = MD5(A2) = MD5(method:digestURI) - ha2 = md5_1.default(this.method + ":" + this.uri); - // response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2) - this.response = md5_1.default(ha1 + ":" + this.nonce + ":" + this.ncHex + ":" + this.cnonce + ":auth:" + ha2); - } - else if (this.qop === "auth-int") { - // HA2 = MD5(A2) = MD5(method:digestURI:MD5(entityBody)) - ha2 = md5_1.default(this.method + ":" + this.uri + ":" + md5_1.default(body ? body : "")); - // response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2) - this.response = md5_1.default(ha1 + ":" + this.nonce + ":" + this.ncHex + ":" + this.cnonce + ":auth-int:" + ha2); - } - else if (this.qop === undefined) { - // HA2 = MD5(A2) = MD5(method:digestURI) - ha2 = md5_1.default(this.method + ":" + this.uri); - // response = MD5(HA1:nonce:HA2) - this.response = md5_1.default(ha1 + ":" + this.nonce + ":" + ha2); - } - }; - return DigestAuthentication; -}()); -exports.DigestAuthentication = DigestAuthentication; diff --git a/lib/core/messages/grammar.d.ts b/lib/core/messages/grammar.d.ts deleted file mode 100644 index 656d32dfd..000000000 --- a/lib/core/messages/grammar.d.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { NameAddrHeader } from "./name-addr-header"; -import { URI } from "./uri"; -/** - * Grammar. - * @internal - */ -export declare namespace Grammar { - /** - * Parse. - * @param input - - * @param startRule - - */ - function parse(input: string, startRule: string): any; - /** - * Parse the given string and returns a SIP.NameAddrHeader instance or undefined if - * it is an invalid NameAddrHeader. - * @param name_addr_header - - */ - function nameAddrHeaderParse(nameAddrHeader: string): NameAddrHeader | undefined; - /** - * Parse the given string and returns a SIP.URI instance or undefined if - * it is an invalid URI. - * @param uri - - */ - function URIParse(uri: string): URI | undefined; -} -//# sourceMappingURL=grammar.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/grammar.d.ts.map b/lib/core/messages/grammar.d.ts.map deleted file mode 100644 index 1487c5f02..000000000 --- a/lib/core/messages/grammar.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"grammar.d.ts","sourceRoot":"","sources":["../../../src/core/messages/grammar.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAE,GAAG,EAAE,MAAM,OAAO,CAAC;AAE5B;;;GAGG;AACH,yBAAiB,OAAO,CAAC;IAEvB;;;;OAIG;IACH,SAAgB,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,GAAG,CAS3D;IAED;;;;OAIG;IACH,SAAgB,mBAAmB,CAAC,cAAc,EAAE,MAAM,GAAG,cAAc,GAAG,SAAS,CAItF;IAED;;;;OAIG;IACH,SAAgB,QAAQ,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,GAAG,SAAS,CAIrD;CACF"} \ No newline at end of file diff --git a/lib/core/messages/grammar.js b/lib/core/messages/grammar.js deleted file mode 100644 index fd944feb1..000000000 --- a/lib/core/messages/grammar.js +++ /dev/null @@ -1,47 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var pegGrammar = tslib_1.__importStar(require("../../grammar/dist/grammar")); -/** - * Grammar. - * @internal - */ -var Grammar; -(function (Grammar) { - /** - * Parse. - * @param input - - * @param startRule - - */ - function parse(input, startRule) { - var options = { startRule: startRule }; - try { - pegGrammar.parse(input, options); - } - catch (e) { - options.data = -1; - } - return options.data; - } - Grammar.parse = parse; - /** - * Parse the given string and returns a SIP.NameAddrHeader instance or undefined if - * it is an invalid NameAddrHeader. - * @param name_addr_header - - */ - function nameAddrHeaderParse(nameAddrHeader) { - var parsedNameAddrHeader = Grammar.parse(nameAddrHeader, "Name_Addr_Header"); - return parsedNameAddrHeader !== -1 ? parsedNameAddrHeader : undefined; - } - Grammar.nameAddrHeaderParse = nameAddrHeaderParse; - /** - * Parse the given string and returns a SIP.URI instance or undefined if - * it is an invalid URI. - * @param uri - - */ - function URIParse(uri) { - var parsedUri = Grammar.parse(uri, "SIP_URI"); - return parsedUri !== -1 ? parsedUri : undefined; - } - Grammar.URIParse = URIParse; -})(Grammar = exports.Grammar || (exports.Grammar = {})); diff --git a/lib/core/messages/incoming-message.d.ts b/lib/core/messages/incoming-message.d.ts deleted file mode 100644 index c6d218350..000000000 --- a/lib/core/messages/incoming-message.d.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { NameAddrHeader } from "./name-addr-header"; -/** - * Incoming message. - * @public - */ -export declare class IncomingMessage { - viaBranch: string; - method: string; - body: string; - toTag: string; - to: NameAddrHeader; - fromTag: string; - from: NameAddrHeader; - callId: string; - cseq: number; - via: { - host: string; - port: number; - }; - headers: { - [name: string]: Array<{ - parsed?: any; - raw: string; - }>; - }; - referTo: string | undefined; - data: string; - /** - * Insert a header of the given name and value into the last position of the - * header array. - * @param name - header name - * @param value - header value - */ - addHeader(name: string, value: string): void; - /** - * Get the value of the given header name at the given position. - * @param name - header name - * @returns Returns the specified header, undefined if header doesn't exist. - */ - getHeader(name: string): string | undefined; - /** - * Get the header/s of the given name. - * @param name - header name - * @returns Array - with all the headers of the specified name. - */ - getHeaders(name: string): Array; - /** - * Verify the existence of the given header. - * @param name - header name - * @returns true if header with given name exists, false otherwise - */ - hasHeader(name: string): boolean; - /** - * Parse the given header on the given index. - * @param name - header name - * @param idx - header index - * @returns Parsed header object, undefined if the - * header is not present or in case of a parsing error. - */ - parseHeader(name: string, idx?: number): any | undefined; - /** - * Message Header attribute selector. Alias of parseHeader. - * @param name - header name - * @param idx - header index - * @returns Parsed header object, undefined if the - * header is not present or in case of a parsing error. - * - * @example - * message.s('via',3).port - */ - s(name: string, idx?: number): any | undefined; - /** - * Replace the value of the given header by the value. - * @param name - header name - * @param value - header value - */ - setHeader(name: string, value: string): void; - toString(): string; -} -//# sourceMappingURL=incoming-message.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/incoming-message.d.ts.map b/lib/core/messages/incoming-message.d.ts.map deleted file mode 100644 index 17555f0c4..000000000 --- a/lib/core/messages/incoming-message.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"incoming-message.d.ts","sourceRoot":"","sources":["../../../src/core/messages/incoming-message.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAGpD;;;GAGG;AACH,qBAAa,eAAe;IACnB,SAAS,EAAG,MAAM,CAAC;IACnB,MAAM,EAAG,MAAM,CAAC;IAChB,IAAI,EAAG,MAAM,CAAC;IACd,KAAK,EAAG,MAAM,CAAC;IACf,EAAE,EAAG,cAAc,CAAC;IACpB,OAAO,EAAG,MAAM,CAAC;IACjB,IAAI,EAAG,cAAc,CAAC;IACtB,MAAM,EAAG,MAAM,CAAC;IAChB,IAAI,EAAG,MAAM,CAAC;IACd,GAAG,EAAG;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAC,CAAC;IACnC,OAAO,EAAE;QAAC,CAAC,IAAI,EAAE,MAAM,GAAG,KAAK,CAAC;YAAE,MAAM,CAAC,EAAE,GAAG,CAAC;YAAC,GAAG,EAAE,MAAM,CAAA;SAAE,CAAC,CAAA;KAAC,CAAM;IACrE,OAAO,EAAE,MAAM,GAAG,SAAS,CAAC;IAC5B,IAAI,EAAG,MAAM,CAAC;IAErB;;;;;OAKG;IACI,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI;IAWnD;;;;OAIG;IACI,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS;IAYlD;;;;OAIG;IACI,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC;IAa9C;;;;OAIG;IACI,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO;IAIvC;;;;;;OAMG;IACI,WAAW,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,GAAE,MAAU,GAAG,GAAG,GAAG,SAAS;IA+BlE;;;;;;;;;OASG;IACI,CAAC,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,GAAE,MAAU,GAAG,GAAG,GAAG,SAAS;IAIxD;;;;OAIG;IACI,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI;IAI5C,QAAQ,IAAI,MAAM;CAG1B"} \ No newline at end of file diff --git a/lib/core/messages/incoming-message.js b/lib/core/messages/incoming-message.js deleted file mode 100644 index d2e87cea2..000000000 --- a/lib/core/messages/incoming-message.js +++ /dev/null @@ -1,132 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var grammar_1 = require("./grammar"); -var utils_1 = require("./utils"); -/** - * Incoming message. - * @public - */ -var IncomingMessage = /** @class */ (function () { - function IncomingMessage() { - this.headers = {}; - } - /** - * Insert a header of the given name and value into the last position of the - * header array. - * @param name - header name - * @param value - header value - */ - IncomingMessage.prototype.addHeader = function (name, value) { - var header = { raw: value }; - name = utils_1.headerize(name); - if (this.headers[name]) { - this.headers[name].push(header); - } - else { - this.headers[name] = [header]; - } - }; - /** - * Get the value of the given header name at the given position. - * @param name - header name - * @returns Returns the specified header, undefined if header doesn't exist. - */ - IncomingMessage.prototype.getHeader = function (name) { - var header = this.headers[utils_1.headerize(name)]; - if (header) { - if (header[0]) { - return header[0].raw; - } - } - else { - return; - } - }; - /** - * Get the header/s of the given name. - * @param name - header name - * @returns Array - with all the headers of the specified name. - */ - IncomingMessage.prototype.getHeaders = function (name) { - var header = this.headers[utils_1.headerize(name)]; - var result = []; - if (!header) { - return []; - } - for (var _i = 0, header_1 = header; _i < header_1.length; _i++) { - var headerPart = header_1[_i]; - result.push(headerPart.raw); - } - return result; - }; - /** - * Verify the existence of the given header. - * @param name - header name - * @returns true if header with given name exists, false otherwise - */ - IncomingMessage.prototype.hasHeader = function (name) { - return !!this.headers[utils_1.headerize(name)]; - }; - /** - * Parse the given header on the given index. - * @param name - header name - * @param idx - header index - * @returns Parsed header object, undefined if the - * header is not present or in case of a parsing error. - */ - IncomingMessage.prototype.parseHeader = function (name, idx) { - if (idx === void 0) { idx = 0; } - name = utils_1.headerize(name); - if (!this.headers[name]) { - // this.logger.log("header '" + name + "' not present"); - return; - } - else if (idx >= this.headers[name].length) { - // this.logger.log("not so many '" + name + "' headers present"); - return; - } - var header = this.headers[name][idx]; - var value = header.raw; - if (header.parsed) { - return header.parsed; - } - // substitute '-' by '_' for grammar rule matching. - var parsed = grammar_1.Grammar.parse(value, name.replace(/-/g, "_")); - if (parsed === -1) { - this.headers[name].splice(idx, 1); // delete from headers - // this.logger.warn('error parsing "' + name + '" header field with value "' + value + '"'); - return; - } - else { - header.parsed = parsed; - return parsed; - } - }; - /** - * Message Header attribute selector. Alias of parseHeader. - * @param name - header name - * @param idx - header index - * @returns Parsed header object, undefined if the - * header is not present or in case of a parsing error. - * - * @example - * message.s('via',3).port - */ - IncomingMessage.prototype.s = function (name, idx) { - if (idx === void 0) { idx = 0; } - return this.parseHeader(name, idx); - }; - /** - * Replace the value of the given header by the value. - * @param name - header name - * @param value - header value - */ - IncomingMessage.prototype.setHeader = function (name, value) { - this.headers[utils_1.headerize(name)] = [{ raw: value }]; - }; - IncomingMessage.prototype.toString = function () { - return this.data; - }; - return IncomingMessage; -}()); -exports.IncomingMessage = IncomingMessage; diff --git a/lib/core/messages/incoming-request-message.d.ts b/lib/core/messages/incoming-request-message.d.ts deleted file mode 100644 index eb50bbc8e..000000000 --- a/lib/core/messages/incoming-request-message.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { URI } from "../messages"; -import { IncomingMessage } from "./incoming-message"; -/** - * Incoming request message. - * @public - */ -export declare class IncomingRequestMessage extends IncomingMessage { - ruri: URI | undefined; - constructor(); -} -//# sourceMappingURL=incoming-request-message.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/incoming-request-message.d.ts.map b/lib/core/messages/incoming-request-message.d.ts.map deleted file mode 100644 index 23beeffa3..000000000 --- a/lib/core/messages/incoming-request-message.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"incoming-request-message.d.ts","sourceRoot":"","sources":["../../../src/core/messages/incoming-request-message.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAClC,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAErD;;;GAGG;AACH,qBAAa,sBAAuB,SAAQ,eAAe;IAClD,IAAI,EAAE,GAAG,GAAG,SAAS,CAAC;;CAK9B"} \ No newline at end of file diff --git a/lib/core/messages/incoming-request-message.js b/lib/core/messages/incoming-request-message.js deleted file mode 100644 index 0bc951b84..000000000 --- a/lib/core/messages/incoming-request-message.js +++ /dev/null @@ -1,16 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var incoming_message_1 = require("./incoming-message"); -/** - * Incoming request message. - * @public - */ -var IncomingRequestMessage = /** @class */ (function (_super) { - tslib_1.__extends(IncomingRequestMessage, _super); - function IncomingRequestMessage() { - return _super.call(this) || this; - } - return IncomingRequestMessage; -}(incoming_message_1.IncomingMessage)); -exports.IncomingRequestMessage = IncomingRequestMessage; diff --git a/lib/core/messages/incoming-request.d.ts b/lib/core/messages/incoming-request.d.ts deleted file mode 100644 index 56da6209b..000000000 --- a/lib/core/messages/incoming-request.d.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { TransportError } from "../exceptions"; -import { URI } from "../messages"; -import { IncomingRequestMessage } from "./incoming-request-message"; -import { OutgoingResponse, ResponseOptions } from "./outgoing-response"; -/** - * A SIP message sent from a remote client to a local server. - * @remarks - * For the purpose of invoking a particular operation. - * https://tools.ietf.org/html/rfc3261#section-7.1 - * @public - */ -export interface IncomingRequest { - /** Delegate providing custom handling of this incoming request. */ - delegate?: IncomingRequestDelegate; - /** The incoming message. */ - readonly message: IncomingRequestMessage; - /** - * Send a 2xx positive final response to this request. Defaults to 200. - * @param options - Response options bucket. - */ - accept(options?: ResponseOptions): OutgoingResponse; - /** - * Send a 1xx provisional response to this request. Defaults to 180. Excludes 100. - * Note that per RFC 4320, this method may only be used to respond to INVITE requests. - * @param options - Response options bucket. - */ - progress(options?: ResponseOptions): OutgoingResponse; - /** - * Send a 3xx negative final response to this request. Defaults to 302. - * @param contacts - Contacts to redirect the UAC to. - * @param options - Response options bucket. - */ - redirect(contacts: Array, options?: ResponseOptions): OutgoingResponse; - /** - * Send a 4xx, 5xx, or 6xx negative final response to this request. Defaults to 480. - * @param options - Response options bucket. - */ - reject(options?: ResponseOptions): OutgoingResponse; - /** - * Send a 100 outgoing response to this request. - * @param options - Response options bucket. - */ - trying(options?: ResponseOptions): OutgoingResponse; -} -/** - * Delegate providing custom handling of incoming requests. - * @public - */ -export interface IncomingRequestDelegate { - /** - * Receive CANCEL request. - * https://tools.ietf.org/html/rfc3261#section-9.2 - * Note: Currently CANCEL is being handled as a special case. - * No UAS is created to handle the CANCEL and the response to - * it CANCEL is being handled statelessly by the user agent core. - * As such, there is currently no way to externally impact the - * response to the a CANCEL request and thus the method here is - * receiving a "message" (as apposed to a "uas"). - * @param message - Incoming CANCEL request message. - */ - onCancel?(message: IncomingRequestMessage): void; - /** - * A transport error occurred attempted to send a response. - * @param error - Transport error. - */ - onTransportError?(error: TransportError): void; -} -//# sourceMappingURL=incoming-request.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/incoming-request.d.ts.map b/lib/core/messages/incoming-request.d.ts.map deleted file mode 100644 index 5cde494a7..000000000 --- a/lib/core/messages/incoming-request.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"incoming-request.d.ts","sourceRoot":"","sources":["../../../src/core/messages/incoming-request.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAC/C,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAClC,OAAO,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AACpE,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAExE;;;;;;GAMG;AACH,MAAM,WAAW,eAAe;IAC9B,mEAAmE;IACnE,QAAQ,CAAC,EAAE,uBAAuB,CAAC;IACnC,4BAA4B;IAC5B,QAAQ,CAAC,OAAO,EAAE,sBAAsB,CAAC;IAEzC;;;OAGG;IACH,MAAM,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,gBAAgB,CAAC;IAEpD;;;;OAIG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,gBAAgB,CAAC;IAEtD;;;;OAIG;IACH,QAAQ,CAAC,QAAQ,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,gBAAgB,CAAC;IAE5E;;;OAGG;IACH,MAAM,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,gBAAgB,CAAC;IAEpD;;;OAGG;IACH,MAAM,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,gBAAgB,CAAC;CACrD;AAED;;;GAGG;AACH,MAAM,WAAW,uBAAuB;IACtC;;;;;;;;;;OAUG;IACH,QAAQ,CAAC,CAAC,OAAO,EAAE,sBAAsB,GAAG,IAAI,CAAC;IAEjD;;;OAGG;IACH,gBAAgB,CAAC,CAAC,KAAK,EAAE,cAAc,GAAG,IAAI,CAAC;CAChD"} \ No newline at end of file diff --git a/lib/core/messages/incoming-request.js b/lib/core/messages/incoming-request.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/core/messages/incoming-request.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/core/messages/incoming-response-message.d.ts b/lib/core/messages/incoming-response-message.d.ts deleted file mode 100644 index a04152af4..000000000 --- a/lib/core/messages/incoming-response-message.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { IncomingMessage } from "./incoming-message"; -/** - * Incoming response message. - * @public - */ -export declare class IncomingResponseMessage extends IncomingMessage { - statusCode: number | undefined; - reasonPhrase: string | undefined; - constructor(); -} -//# sourceMappingURL=incoming-response-message.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/incoming-response-message.d.ts.map b/lib/core/messages/incoming-response-message.d.ts.map deleted file mode 100644 index 7c9d9853b..000000000 --- a/lib/core/messages/incoming-response-message.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"incoming-response-message.d.ts","sourceRoot":"","sources":["../../../src/core/messages/incoming-response-message.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAErD;;;GAGG;AACH,qBAAa,uBAAwB,SAAQ,eAAe;IACnD,UAAU,EAAE,MAAM,GAAG,SAAS,CAAC;IAC/B,YAAY,EAAE,MAAM,GAAG,SAAS,CAAC;;CAKzC"} \ No newline at end of file diff --git a/lib/core/messages/incoming-response-message.js b/lib/core/messages/incoming-response-message.js deleted file mode 100644 index 86885a2df..000000000 --- a/lib/core/messages/incoming-response-message.js +++ /dev/null @@ -1,16 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var incoming_message_1 = require("./incoming-message"); -/** - * Incoming response message. - * @public - */ -var IncomingResponseMessage = /** @class */ (function (_super) { - tslib_1.__extends(IncomingResponseMessage, _super); - function IncomingResponseMessage() { - return _super.call(this) || this; - } - return IncomingResponseMessage; -}(incoming_message_1.IncomingMessage)); -exports.IncomingResponseMessage = IncomingResponseMessage; diff --git a/lib/core/messages/incoming-response.d.ts b/lib/core/messages/incoming-response.d.ts deleted file mode 100644 index f2a2daefa..000000000 --- a/lib/core/messages/incoming-response.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { IncomingResponseMessage } from "./incoming-response-message"; -/** - * A SIP message sent from a remote server to a local client. - * @remarks - * For indicating the status of a request sent from the client to the server. - * https://tools.ietf.org/html/rfc3261#section-7.2 - * @public - */ -export interface IncomingResponse { - /** The incoming message. */ - readonly message: IncomingResponseMessage; -} -//# sourceMappingURL=incoming-response.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/incoming-response.d.ts.map b/lib/core/messages/incoming-response.d.ts.map deleted file mode 100644 index f1c1bfa0a..000000000 --- a/lib/core/messages/incoming-response.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"incoming-response.d.ts","sourceRoot":"","sources":["../../../src/core/messages/incoming-response.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,uBAAuB,EAAE,MAAM,6BAA6B,CAAC;AAErE;;;;;;GAMG;AACH,MAAM,WAAW,gBAAgB;IAC/B,4BAA4B;IAC5B,QAAQ,CAAC,OAAO,EAAE,uBAAuB,CAAC;CAC3C"} \ No newline at end of file diff --git a/lib/core/messages/incoming-response.js b/lib/core/messages/incoming-response.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/core/messages/incoming-response.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/core/messages/index.d.ts b/lib/core/messages/index.d.ts deleted file mode 100644 index aa1d473b2..000000000 --- a/lib/core/messages/index.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -export * from "./methods"; -export * from "./body"; -export * from "./digest-authentication"; -export * from "./grammar"; -export * from "./incoming-message"; -export * from "./incoming-request-message"; -export * from "./incoming-request"; -export * from "./incoming-response-message"; -export * from "./incoming-response"; -export * from "./name-addr-header"; -export * from "./outgoing-request-message"; -export * from "./outgoing-request"; -export * from "./outgoing-response"; -export * from "./parameters"; -export * from "./uri"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/index.d.ts.map b/lib/core/messages/index.d.ts.map deleted file mode 100644 index a28cb7f03..000000000 --- a/lib/core/messages/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/messages/index.ts"],"names":[],"mappings":"AACA,cAAc,WAAW,CAAC;AAG1B,cAAc,QAAQ,CAAC;AACvB,cAAc,yBAAyB,CAAC;AACxC,cAAc,WAAW,CAAC;AAC1B,cAAc,oBAAoB,CAAC;AACnC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,oBAAoB,CAAC;AACnC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,qBAAqB,CAAC;AACpC,cAAc,oBAAoB,CAAC;AACnC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,oBAAoB,CAAC;AACnC,cAAc,qBAAqB,CAAC;AACpC,cAAc,cAAc,CAAC;AAC7B,cAAc,OAAO,CAAC"} \ No newline at end of file diff --git a/lib/core/messages/index.js b/lib/core/messages/index.js deleted file mode 100644 index 9fcd15f62..000000000 --- a/lib/core/messages/index.js +++ /dev/null @@ -1,17 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -// Directories -tslib_1.__exportStar(require("./methods"), exports); -// Files -tslib_1.__exportStar(require("./body"), exports); -tslib_1.__exportStar(require("./digest-authentication"), exports); -tslib_1.__exportStar(require("./grammar"), exports); -tslib_1.__exportStar(require("./incoming-message"), exports); -tslib_1.__exportStar(require("./incoming-request-message"), exports); -tslib_1.__exportStar(require("./incoming-response-message"), exports); -tslib_1.__exportStar(require("./name-addr-header"), exports); -tslib_1.__exportStar(require("./outgoing-request-message"), exports); -tslib_1.__exportStar(require("./outgoing-response"), exports); -tslib_1.__exportStar(require("./parameters"), exports); -tslib_1.__exportStar(require("./uri"), exports); diff --git a/lib/core/messages/methods/ack.d.ts b/lib/core/messages/methods/ack.d.ts deleted file mode 100644 index 864a450e2..000000000 --- a/lib/core/messages/methods/ack.d.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { IncomingRequestMessage } from "../incoming-request-message"; -import { OutgoingRequestMessage } from "../outgoing-request-message"; -/** - * Incoming ACK request. - * @public - */ -export interface IncomingAckRequest { - /** The incoming message. */ - readonly message: IncomingRequestMessage; -} -/** - * Outgoing ACK request. - * @public - */ -export interface OutgoingAckRequest { - /** The outgoing message. */ - readonly message: OutgoingRequestMessage; -} -//# sourceMappingURL=ack.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/methods/ack.d.ts.map b/lib/core/messages/methods/ack.d.ts.map deleted file mode 100644 index 28a6505ec..000000000 --- a/lib/core/messages/methods/ack.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"ack.d.ts","sourceRoot":"","sources":["../../../../src/core/messages/methods/ack.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AAIrE;;;GAGG;AACH,MAAM,WAAW,kBAAkB;IACjC,4BAA4B;IAC5B,QAAQ,CAAC,OAAO,EAAE,sBAAsB,CAAC;CAC1C;AAED;;;GAGG;AACH,MAAM,WAAW,kBAAkB;IACjC,4BAA4B;IAC5B,QAAQ,CAAC,OAAO,EAAE,sBAAsB,CAAC;CAC1C"} \ No newline at end of file diff --git a/lib/core/messages/methods/ack.js b/lib/core/messages/methods/ack.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/core/messages/methods/ack.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/core/messages/methods/bye.d.ts b/lib/core/messages/methods/bye.d.ts deleted file mode 100644 index b1252b205..000000000 --- a/lib/core/messages/methods/bye.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { IncomingRequest } from "../incoming-request"; -import { IncomingResponse } from "../incoming-response"; -import { OutgoingRequest } from "../outgoing-request"; -/** - * Incoming BYE request. - * @public - */ -export interface IncomingByeRequest extends IncomingRequest { -} -/** - * Incoming BYE response. - * @public - */ -export interface IncomingByeResponse extends IncomingResponse { -} -/** - * Outgoing BYE request. - * @public - */ -export interface OutgoingByeRequest extends OutgoingRequest { -} -//# sourceMappingURL=bye.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/methods/bye.d.ts.map b/lib/core/messages/methods/bye.d.ts.map deleted file mode 100644 index c0b105bee..000000000 --- a/lib/core/messages/methods/bye.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"bye.d.ts","sourceRoot":"","sources":["../../../../src/core/messages/methods/bye.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAItD;;;GAGG;AACH,MAAM,WAAW,kBAAmB,SAAQ,eAAe;CAC1D;AAED;;;GAGG;AACH,MAAM,WAAW,mBAAoB,SAAQ,gBAAgB;CAC5D;AAED;;;GAGG;AACH,MAAM,WAAW,kBAAmB,SAAQ,eAAe;CAC1D"} \ No newline at end of file diff --git a/lib/core/messages/methods/bye.js b/lib/core/messages/methods/bye.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/core/messages/methods/bye.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/core/messages/methods/cancel.d.ts b/lib/core/messages/methods/cancel.d.ts deleted file mode 100644 index 8046a0a5b..000000000 --- a/lib/core/messages/methods/cancel.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { IncomingRequest } from "../incoming-request"; -import { IncomingResponse } from "../incoming-response"; -import { OutgoingRequest } from "../outgoing-request"; -/** - * Incoming CANCEL request. - * @public - */ -export interface IncomingCancelRequest extends IncomingRequest { -} -/** - * Incoming CANCEL response. - * @public - */ -export interface IncomingCancelResponse extends IncomingResponse { -} -/** - * Outgoing CANCEL request. - * @public - */ -export interface OutgoingCancelRequest extends OutgoingRequest { -} -//# sourceMappingURL=cancel.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/methods/cancel.d.ts.map b/lib/core/messages/methods/cancel.d.ts.map deleted file mode 100644 index 576d4d0e0..000000000 --- a/lib/core/messages/methods/cancel.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"cancel.d.ts","sourceRoot":"","sources":["../../../../src/core/messages/methods/cancel.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAItD;;;GAGG;AACH,MAAM,WAAW,qBAAsB,SAAQ,eAAe;CAC7D;AAED;;;GAGG;AACH,MAAM,WAAW,sBAAuB,SAAQ,gBAAgB;CAC/D;AAED;;;GAGG;AACH,MAAM,WAAW,qBAAsB,SAAQ,eAAe;CAC7D"} \ No newline at end of file diff --git a/lib/core/messages/methods/cancel.js b/lib/core/messages/methods/cancel.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/core/messages/methods/cancel.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/core/messages/methods/constants.d.ts b/lib/core/messages/methods/constants.d.ts deleted file mode 100644 index 02e5a2fdb..000000000 --- a/lib/core/messages/methods/constants.d.ts +++ /dev/null @@ -1,21 +0,0 @@ -/** - * SIP Methods - * @internal - */ -export declare namespace C { - const ACK = "ACK"; - const BYE = "BYE"; - const CANCEL = "CANCEL"; - const INFO = "INFO"; - const INVITE = "INVITE"; - const MESSAGE = "MESSAGE"; - const NOTIFY = "NOTIFY"; - const OPTIONS = "OPTIONS"; - const REGISTER = "REGISTER"; - const UPDATE = "UPDATE"; - const SUBSCRIBE = "SUBSCRIBE"; - const PUBLISH = "PUBLISH"; - const REFER = "REFER"; - const PRACK = "PRACK"; -} -//# sourceMappingURL=constants.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/methods/constants.d.ts.map b/lib/core/messages/methods/constants.d.ts.map deleted file mode 100644 index 264841a9e..000000000 --- a/lib/core/messages/methods/constants.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../../../src/core/messages/methods/constants.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,yBAAiB,CAAC,CAAC;IACV,MAAM,GAAG,QAAQ,CAAC;IAClB,MAAM,GAAG,QAAQ,CAAC;IAClB,MAAM,MAAM,WAAW,CAAC;IACxB,MAAM,IAAI,SAAS,CAAC;IACpB,MAAM,MAAM,WAAW,CAAC;IACxB,MAAM,OAAO,YAAY,CAAC;IAC1B,MAAM,MAAM,WAAW,CAAC;IACxB,MAAM,OAAO,YAAY,CAAC;IAC1B,MAAM,QAAQ,aAAa,CAAC;IAC5B,MAAM,MAAM,WAAW,CAAC;IACxB,MAAM,SAAS,cAAc,CAAC;IAC9B,MAAM,OAAO,YAAY,CAAC;IAC1B,MAAM,KAAK,UAAU,CAAC;IACtB,MAAM,KAAK,UAAU,CAAC;CAC9B"} \ No newline at end of file diff --git a/lib/core/messages/methods/constants.js b/lib/core/messages/methods/constants.js deleted file mode 100644 index e71d0b379..000000000 --- a/lib/core/messages/methods/constants.js +++ /dev/null @@ -1,23 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * SIP Methods - * @internal - */ -var C; -(function (C) { - C.ACK = "ACK"; - C.BYE = "BYE"; - C.CANCEL = "CANCEL"; - C.INFO = "INFO"; - C.INVITE = "INVITE"; - C.MESSAGE = "MESSAGE"; - C.NOTIFY = "NOTIFY"; - C.OPTIONS = "OPTIONS"; - C.REGISTER = "REGISTER"; - C.UPDATE = "UPDATE"; - C.SUBSCRIBE = "SUBSCRIBE"; - C.PUBLISH = "PUBLISH"; - C.REFER = "REFER"; - C.PRACK = "PRACK"; -})(C = exports.C || (exports.C = {})); diff --git a/lib/core/messages/methods/index.d.ts b/lib/core/messages/methods/index.d.ts deleted file mode 100644 index 84e1892a3..000000000 --- a/lib/core/messages/methods/index.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -export * from "./constants"; -export * from "./ack"; -export * from "./bye"; -export * from "./cancel"; -export * from "./info"; -export * from "./invite"; -export * from "./message"; -export * from "./notify"; -export * from "./prack"; -export * from "./publish"; -export * from "./register"; -export * from "./refer"; -export * from "./subscribe"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/methods/index.d.ts.map b/lib/core/messages/methods/index.d.ts.map deleted file mode 100644 index 95b4d8d8b..000000000 --- a/lib/core/messages/methods/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/core/messages/methods/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,cAAc,OAAO,CAAC;AACtB,cAAc,OAAO,CAAC;AACtB,cAAc,UAAU,CAAC;AACzB,cAAc,QAAQ,CAAC;AACvB,cAAc,UAAU,CAAC;AACzB,cAAc,WAAW,CAAC;AAC1B,cAAc,UAAU,CAAC;AACzB,cAAc,SAAS,CAAC;AACxB,cAAc,WAAW,CAAC;AAC1B,cAAc,YAAY,CAAC;AAC3B,cAAc,SAAS,CAAC;AACxB,cAAc,aAAa,CAAC"} \ No newline at end of file diff --git a/lib/core/messages/methods/index.js b/lib/core/messages/methods/index.js deleted file mode 100644 index d5d39c544..000000000 --- a/lib/core/messages/methods/index.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -tslib_1.__exportStar(require("./constants"), exports); diff --git a/lib/core/messages/methods/info.d.ts b/lib/core/messages/methods/info.d.ts deleted file mode 100644 index c5c26d00c..000000000 --- a/lib/core/messages/methods/info.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { IncomingRequest } from "../incoming-request"; -import { IncomingResponse } from "../incoming-response"; -import { OutgoingRequest } from "../outgoing-request"; -/** - * Incoming INFO request. - * @public - */ -export interface IncomingInfoRequest extends IncomingRequest { -} -/** - * Incoming INFO response. - * @public - */ -export interface IncomingInfoResponse extends IncomingResponse { -} -/** - * Outgoing INFO request. - * @public - */ -export interface OutgoingInfoRequest extends OutgoingRequest { -} -//# sourceMappingURL=info.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/methods/info.d.ts.map b/lib/core/messages/methods/info.d.ts.map deleted file mode 100644 index ac59edd96..000000000 --- a/lib/core/messages/methods/info.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"info.d.ts","sourceRoot":"","sources":["../../../../src/core/messages/methods/info.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAItD;;;GAGG;AACH,MAAM,WAAW,mBAAoB,SAAQ,eAAe;CAC3D;AAED;;;GAGG;AACH,MAAM,WAAW,oBAAqB,SAAQ,gBAAgB;CAC7D;AAED;;;GAGG;AACH,MAAM,WAAW,mBAAoB,SAAQ,eAAe;CAC3D"} \ No newline at end of file diff --git a/lib/core/messages/methods/info.js b/lib/core/messages/methods/info.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/core/messages/methods/info.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/core/messages/methods/invite.d.ts b/lib/core/messages/methods/invite.d.ts deleted file mode 100644 index 8ee3ab809..000000000 --- a/lib/core/messages/methods/invite.d.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { Session } from "../../session"; -import { IncomingRequest } from "../incoming-request"; -import { IncomingResponse } from "../incoming-response"; -import { OutgoingRequest, OutgoingRequestDelegate, RequestOptions } from "../outgoing-request"; -import { OutgoingResponse, ResponseOptions } from "../outgoing-response"; -import { OutgoingAckRequest } from "./ack"; -import { OutgoingPrackRequest } from "./prack"; -/** - * Incoming INVITE request. - * @public - */ -export interface IncomingInviteRequest extends IncomingRequest { - /** - * Send a 2xx positive final response to this request. Defaults to 200. - * @param options - Response options bucket. - * @returns Outgoing response and a confirmed Session. - */ - accept(options?: ResponseOptions): OutgoingResponseWithSession; - /** - * Send a 1xx provisional response to this request. Defaults to 180. Excludes 100. - * @param options - Response options bucket. - * @returns Outgoing response and an early Session. - */ - progress(options?: ResponseOptions): OutgoingResponseWithSession; -} -/** - * Outgoing INVITE response with the associated {@link Session}. - * @public - */ -export interface OutgoingResponseWithSession extends OutgoingResponse { - /** - * Session associated with incoming request acceptance, or - * Session associated with incoming request progress (if an out of dialog request, an early dialog). - */ - readonly session: Session; -} -/** - * Outgoing INVITE request. - * @public - */ -export interface OutgoingInviteRequest extends OutgoingRequest { - /** Delegate providing custom handling of this outgoing INVITE request. */ - delegate?: OutgoingInviteRequestDelegate; -} -/** - * Delegate providing custom handling of outgoing INVITE requests. - * @public - */ -export interface OutgoingInviteRequestDelegate extends OutgoingRequestDelegate { - /** - * Received a 2xx positive final response to this request. - * @param response - Incoming response (including a confirmed Session). - */ - onAccept?(response: AckableIncomingResponseWithSession): void; - /** - * Received a 1xx provisional response to this request. Excluding 100 responses. - * @param response - Incoming response (including an early Session). - */ - onProgress?(response: PrackableIncomingResponseWithSession): void; -} -/** - * Incoming INVITE response received when request is accepted. - * @public - */ -export interface AckableIncomingResponseWithSession extends IncomingResponse { - /** Session associated with outgoing request acceptance. */ - readonly session: Session; - /** - * Send an ACK to acknowledge this response. - * @param options - Request options bucket. - */ - ack(options?: RequestOptions): OutgoingAckRequest; -} -/** - * Incoming INVITE response received when request is progressed. - * @public - */ -export interface PrackableIncomingResponseWithSession extends IncomingResponse { - /** Session associated with outgoing request progress. If out of dialog request, an early dialog. */ - readonly session: Session; - /** - * Send an PRACK to acknowledge this response. - * @param options - Request options bucket. - */ - prack(options?: RequestOptions): OutgoingPrackRequest; -} -//# sourceMappingURL=invite.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/methods/invite.d.ts.map b/lib/core/messages/methods/invite.d.ts.map deleted file mode 100644 index 44e0bb416..000000000 --- a/lib/core/messages/methods/invite.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"invite.d.ts","sourceRoot":"","sources":["../../../../src/core/messages/methods/invite.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AACxC,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,uBAAuB,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAC/F,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACzE,OAAO,EAAE,kBAAkB,EAAE,MAAM,OAAO,CAAC;AAC3C,OAAO,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAC;AAQ/C;;;GAGG;AACH,MAAM,WAAW,qBAAsB,SAAQ,eAAe;IAC5D;;;;OAIG;IACH,MAAM,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,2BAA2B,CAAC;IAE/D;;;;OAIG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,2BAA2B,CAAC;CAClE;AAED;;;GAGG;AACH,MAAM,WAAW,2BAA4B,SAAQ,gBAAgB;IACnE;;;OAGG;IACH,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;CAC3B;AAMD;;;GAGG;AACH,MAAM,WAAW,qBAAsB,SAAQ,eAAe;IAC5D,0EAA0E;IAC1E,QAAQ,CAAC,EAAE,6BAA6B,CAAC;CAC1C;AAED;;;GAGG;AACH,MAAM,WAAW,6BAA8B,SAAQ,uBAAuB;IAC5E;;;OAGG;IACH,QAAQ,CAAC,CAAC,QAAQ,EAAE,kCAAkC,GAAG,IAAI,CAAC;IAE9D;;;OAGG;IACH,UAAU,CAAC,CAAC,QAAQ,EAAE,oCAAoC,GAAG,IAAI,CAAC;CACnE;AAED;;;GAGG;AACH,MAAM,WAAW,kCAAmC,SAAQ,gBAAgB;IAC1E,2DAA2D;IAC3D,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAE1B;;;OAGG;IACH,GAAG,CAAC,OAAO,CAAC,EAAE,cAAc,GAAG,kBAAkB,CAAC;CACnD;AAED;;;GAGG;AACH,MAAM,WAAW,oCAAqC,SAAQ,gBAAgB;IAC5E,oGAAoG;IACpG,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAE1B;;;OAGG;IACH,KAAK,CAAC,OAAO,CAAC,EAAE,cAAc,GAAG,oBAAoB,CAAC;CACvD"} \ No newline at end of file diff --git a/lib/core/messages/methods/invite.js b/lib/core/messages/methods/invite.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/core/messages/methods/invite.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/core/messages/methods/message.d.ts b/lib/core/messages/methods/message.d.ts deleted file mode 100644 index b501e63ed..000000000 --- a/lib/core/messages/methods/message.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { IncomingRequest } from "../incoming-request"; -import { IncomingResponse } from "../incoming-response"; -import { OutgoingRequest } from "../outgoing-request"; -/** - * Incoming MESSAGE request. - * @public - */ -export interface IncomingMessageRequest extends IncomingRequest { -} -/** - * Incoming MESSAGE response. - * @public - */ -export interface IncomingMessageResponse extends IncomingResponse { -} -/** - * Outgoing MESSAGE request. - * @public - */ -export interface OutgoingMessageRequest extends OutgoingRequest { -} -//# sourceMappingURL=message.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/methods/message.d.ts.map b/lib/core/messages/methods/message.d.ts.map deleted file mode 100644 index 2e6e057ed..000000000 --- a/lib/core/messages/methods/message.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"message.d.ts","sourceRoot":"","sources":["../../../../src/core/messages/methods/message.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAItD;;;GAGG;AACH,MAAM,WAAW,sBAAuB,SAAQ,eAAe;CAC9D;AAED;;;GAGG;AACH,MAAM,WAAW,uBAAwB,SAAQ,gBAAgB;CAChE;AAED;;;GAGG;AACH,MAAM,WAAW,sBAAuB,SAAQ,eAAe;CAC9D"} \ No newline at end of file diff --git a/lib/core/messages/methods/message.js b/lib/core/messages/methods/message.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/core/messages/methods/message.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/core/messages/methods/notify.d.ts b/lib/core/messages/methods/notify.d.ts deleted file mode 100644 index a19936699..000000000 --- a/lib/core/messages/methods/notify.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { IncomingRequest } from "../incoming-request"; -import { IncomingResponse } from "../incoming-response"; -import { OutgoingRequest } from "../outgoing-request"; -/** - * Incoming NOTIFY request. - * @public - */ -export interface IncomingNotifyRequest extends IncomingRequest { -} -/** - * Incoming NOTIFY response. - * @public - */ -export interface IncomingNotifyResponse extends IncomingResponse { -} -/** - * Outgoing NOTIFY request. - * @public - */ -export interface OutgoingNotifyRequest extends OutgoingRequest { -} -//# sourceMappingURL=notify.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/methods/notify.d.ts.map b/lib/core/messages/methods/notify.d.ts.map deleted file mode 100644 index c250655be..000000000 --- a/lib/core/messages/methods/notify.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"notify.d.ts","sourceRoot":"","sources":["../../../../src/core/messages/methods/notify.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAItD;;;GAGG;AACH,MAAM,WAAW,qBAAsB,SAAQ,eAAe;CAC7D;AAED;;;GAGG;AACH,MAAM,WAAW,sBAAuB,SAAQ,gBAAgB;CAC/D;AAED;;;GAGG;AACH,MAAM,WAAW,qBAAsB,SAAQ,eAAe;CAC7D"} \ No newline at end of file diff --git a/lib/core/messages/methods/notify.js b/lib/core/messages/methods/notify.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/core/messages/methods/notify.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/core/messages/methods/prack.d.ts b/lib/core/messages/methods/prack.d.ts deleted file mode 100644 index 4b565334d..000000000 --- a/lib/core/messages/methods/prack.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { IncomingRequest } from "../incoming-request"; -import { IncomingResponse } from "../incoming-response"; -import { OutgoingRequest } from "../outgoing-request"; -/** - * Incoming PRACK request. - * @public - */ -export interface IncomingPrackRequest extends IncomingRequest { -} -/** - * Incoming PRACK response. - * @public - */ -export interface IncomingPrackResponse extends IncomingResponse { -} -/** - * Outgoing PRACK request. - * @public - */ -export interface OutgoingPrackRequest extends OutgoingRequest { -} -//# sourceMappingURL=prack.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/methods/prack.d.ts.map b/lib/core/messages/methods/prack.d.ts.map deleted file mode 100644 index 18adf5961..000000000 --- a/lib/core/messages/methods/prack.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"prack.d.ts","sourceRoot":"","sources":["../../../../src/core/messages/methods/prack.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAItD;;;GAGG;AACH,MAAM,WAAW,oBAAqB,SAAQ,eAAe;CAC5D;AAED;;;GAGG;AACH,MAAM,WAAW,qBAAsB,SAAQ,gBAAgB;CAC9D;AAED;;;GAGG;AACH,MAAM,WAAW,oBAAqB,SAAQ,eAAe;CAC5D"} \ No newline at end of file diff --git a/lib/core/messages/methods/prack.js b/lib/core/messages/methods/prack.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/core/messages/methods/prack.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/core/messages/methods/publish.d.ts b/lib/core/messages/methods/publish.d.ts deleted file mode 100644 index c0c25b526..000000000 --- a/lib/core/messages/methods/publish.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { IncomingRequest } from "../incoming-request"; -import { IncomingResponse } from "../incoming-response"; -import { OutgoingRequest } from "../outgoing-request"; -/** - * Incoming PUBLISH request. - * @public - */ -export interface IncomingPublishRequest extends IncomingRequest { -} -/** - * Incoming PUBLISH response. - * @public - */ -export interface IncomingPublishResponse extends IncomingResponse { -} -/** - * Outgoing PUBLISH request. - * @public - */ -export interface OutgoingPublishRequest extends OutgoingRequest { -} -//# sourceMappingURL=publish.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/methods/publish.d.ts.map b/lib/core/messages/methods/publish.d.ts.map deleted file mode 100644 index a7d90aa06..000000000 --- a/lib/core/messages/methods/publish.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"publish.d.ts","sourceRoot":"","sources":["../../../../src/core/messages/methods/publish.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAItD;;;GAGG;AACH,MAAM,WAAW,sBAAuB,SAAQ,eAAe;CAC9D;AAED;;;GAGG;AACH,MAAM,WAAW,uBAAwB,SAAQ,gBAAgB;CAChE;AAED;;;GAGG;AACH,MAAM,WAAW,sBAAuB,SAAQ,eAAe;CAC9D"} \ No newline at end of file diff --git a/lib/core/messages/methods/publish.js b/lib/core/messages/methods/publish.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/core/messages/methods/publish.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/core/messages/methods/refer.d.ts b/lib/core/messages/methods/refer.d.ts deleted file mode 100644 index cb11370f7..000000000 --- a/lib/core/messages/methods/refer.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { IncomingRequest } from "../incoming-request"; -import { IncomingResponse } from "../incoming-response"; -import { OutgoingRequest } from "../outgoing-request"; -/** - * Incoming REFER request. - * @public - */ -export interface IncomingReferRequest extends IncomingRequest { -} -/** - * Incoming REFER response. - * @public - */ -export interface IncomingReferResponse extends IncomingResponse { -} -/** - * Outgoing REFER request. - * @public - */ -export interface OutgoingReferRequest extends OutgoingRequest { -} -//# sourceMappingURL=refer.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/methods/refer.d.ts.map b/lib/core/messages/methods/refer.d.ts.map deleted file mode 100644 index da6376817..000000000 --- a/lib/core/messages/methods/refer.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"refer.d.ts","sourceRoot":"","sources":["../../../../src/core/messages/methods/refer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAItD;;;GAGG;AACH,MAAM,WAAW,oBAAqB,SAAQ,eAAe;CAC5D;AAED;;;GAGG;AACH,MAAM,WAAW,qBAAsB,SAAQ,gBAAgB;CAC9D;AAED;;;GAGG;AACH,MAAM,WAAW,oBAAqB,SAAQ,eAAe;CAC5D"} \ No newline at end of file diff --git a/lib/core/messages/methods/refer.js b/lib/core/messages/methods/refer.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/core/messages/methods/refer.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/core/messages/methods/register.d.ts b/lib/core/messages/methods/register.d.ts deleted file mode 100644 index f5fb52552..000000000 --- a/lib/core/messages/methods/register.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { IncomingRequest } from "../incoming-request"; -import { IncomingResponse } from "../incoming-response"; -import { OutgoingRequest } from "../outgoing-request"; -/** - * Incoming REGISTER request. - * @public - */ -export interface IncomingRegisterRequest extends IncomingRequest { -} -/** - * Incoming REGISTER response. - * @public - */ -export interface IncomingRegisterResponse extends IncomingResponse { -} -/** - * Outgoing REGISTER request. - * @public - */ -export interface OutgoingRegisterRequest extends OutgoingRequest { -} -//# sourceMappingURL=register.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/methods/register.d.ts.map b/lib/core/messages/methods/register.d.ts.map deleted file mode 100644 index 6d76e31c7..000000000 --- a/lib/core/messages/methods/register.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"register.d.ts","sourceRoot":"","sources":["../../../../src/core/messages/methods/register.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAItD;;;GAGG;AACH,MAAM,WAAW,uBAAwB,SAAQ,eAAe;CAC/D;AAED;;;GAGG;AACH,MAAM,WAAW,wBAAyB,SAAQ,gBAAgB;CACjE;AAED;;;GAGG;AACH,MAAM,WAAW,uBAAwB,SAAQ,eAAe;CAC/D"} \ No newline at end of file diff --git a/lib/core/messages/methods/register.js b/lib/core/messages/methods/register.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/core/messages/methods/register.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/core/messages/methods/subscribe.d.ts b/lib/core/messages/methods/subscribe.d.ts deleted file mode 100644 index 43b41c6dc..000000000 --- a/lib/core/messages/methods/subscribe.d.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { Subscription } from "../../subscription"; -import { IncomingRequest } from "../incoming-request"; -import { IncomingResponse } from "../incoming-response"; -import { OutgoingRequest, OutgoingRequestDelegate } from "../outgoing-request"; -import { IncomingNotifyRequest } from "./notify"; -/** - * Incoming SUBSCRIBE request. - * @public - */ -export interface IncomingSubscribeRequest extends IncomingRequest { -} -/** - * Incoming SUBSCRIBE response. - * @public - */ -export interface IncomingSubscribeResponse extends IncomingResponse { -} -/** - * Outgoing SUBSCRIBE request. - * @public - */ -export interface OutgoingSubscribeRequest extends OutgoingRequest { - /** Delegate providing custom handling of this outgoing SUBSCRIBE request. */ - delegate?: OutgoingSubscribeRequestDelegate; - /** Stop waiting for an inital subscription creating NOTIFY. */ - waitNotifyStop(): void; -} -/** - * Delegate providing custom handling of outgoing SUBSCRIBE requests. - * @public - */ -export interface OutgoingSubscribeRequestDelegate extends OutgoingRequestDelegate { - /** - * Received the initial subscription creating NOTIFY in response to this request. - * Called for out of dialog SUBSCRIBE requests only (not called for re-SUBSCRIBE requests). - * @param request - Incoming NOTIFY request (including a Subscription). - */ - onNotify?(request: IncomingRequestWithSubscription): void; - /** - * Timed out waiting to receive the initial subscription creating NOTIFY in response to this request. - * Called for out of dialog SUBSCRIBE requests only (not called for re-SUBSCRIBE requests). - */ - onNotifyTimeout?(): void; -} -/** - * Incoming NOTIFY request with associated {@link Subscription}. - * @public - */ -export interface IncomingRequestWithSubscription { - /** The NOTIFY request which established the subscription. */ - readonly request: IncomingNotifyRequest; - /** If subscription state is not "terminated", then the subscription. Otherwise undefined. */ - readonly subscription?: Subscription; -} -//# sourceMappingURL=subscribe.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/methods/subscribe.d.ts.map b/lib/core/messages/methods/subscribe.d.ts.map deleted file mode 100644 index 780b8969a..000000000 --- a/lib/core/messages/methods/subscribe.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"subscribe.d.ts","sourceRoot":"","sources":["../../../../src/core/messages/methods/subscribe.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAC/E,OAAO,EAAE,qBAAqB,EAAE,MAAM,UAAU,CAAC;AAIjD;;;GAGG;AACH,MAAM,WAAW,wBAAyB,SAAQ,eAAe;CAChE;AAED;;;GAGG;AACH,MAAM,WAAW,yBAA0B,SAAQ,gBAAgB;CAClE;AAED;;;GAGG;AACH,MAAM,WAAW,wBAAyB,SAAQ,eAAe;IAC/D,6EAA6E;IAC7E,QAAQ,CAAC,EAAE,gCAAgC,CAAC;IAC5C,+DAA+D;IAC/D,cAAc,IAAI,IAAI,CAAC;CACxB;AAED;;;GAGG;AACH,MAAM,WAAW,gCAAiC,SAAQ,uBAAuB;IAC/E;;;;OAIG;IACH,QAAQ,CAAC,CAAC,OAAO,EAAE,+BAA+B,GAAG,IAAI,CAAC;IAE1D;;;OAGG;IACH,eAAe,CAAC,IAAI,IAAI,CAAC;CAC1B;AAED;;;GAGG;AACH,MAAM,WAAW,+BAA+B;IAC9C,6DAA6D;IAC7D,QAAQ,CAAC,OAAO,EAAE,qBAAqB,CAAC;IACxC,6FAA6F;IAC7F,QAAQ,CAAC,YAAY,CAAC,EAAE,YAAY,CAAC;CACtC"} \ No newline at end of file diff --git a/lib/core/messages/methods/subscribe.js b/lib/core/messages/methods/subscribe.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/core/messages/methods/subscribe.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/core/messages/name-addr-header.d.ts b/lib/core/messages/name-addr-header.d.ts deleted file mode 100644 index 54b78e438..000000000 --- a/lib/core/messages/name-addr-header.d.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { Parameters } from "./parameters"; -import { URI } from "./uri"; -/** - * Name Address SIP header. - * @public - */ -export declare class NameAddrHeader extends Parameters { - uri: URI; - private _displayName; - /** - * Constructor - * @param uri - - * @param displayName - - * @param parameters - - */ - constructor(uri: URI, displayName: string, parameters: { - [name: string]: string; - }); - readonly friendlyName: string; - displayName: string; - clone(): NameAddrHeader; - toString(): string; -} -//# sourceMappingURL=name-addr-header.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/name-addr-header.d.ts.map b/lib/core/messages/name-addr-header.d.ts.map deleted file mode 100644 index a7c33354f..000000000 --- a/lib/core/messages/name-addr-header.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"name-addr-header.d.ts","sourceRoot":"","sources":["../../../src/core/messages/name-addr-header.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,GAAG,EAAE,MAAM,OAAO,CAAC;AAE5B;;;GAGG;AACH,qBAAa,cAAe,SAAQ,UAAU;IACrC,GAAG,EAAE,GAAG,CAAC;IAEhB,OAAO,CAAC,YAAY,CAAS;IAE7B;;;;;OAKG;gBACS,GAAG,EAAE,GAAG,EAAE,WAAW,EAAE,MAAM,EAAE,UAAU,EAAE;QAAE,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE;aAM7E,YAAY,EAAI,MAAM;IAItB,WAAW,EACQ,MAAM;IAItB,KAAK,IAAI,cAAc;IAOvB,QAAQ,IAAI,MAAM;CAgB1B"} \ No newline at end of file diff --git a/lib/core/messages/name-addr-header.js b/lib/core/messages/name-addr-header.js deleted file mode 100644 index 87b85625f..000000000 --- a/lib/core/messages/name-addr-header.js +++ /dev/null @@ -1,56 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var parameters_1 = require("./parameters"); -/** - * Name Address SIP header. - * @public - */ -var NameAddrHeader = /** @class */ (function (_super) { - tslib_1.__extends(NameAddrHeader, _super); - /** - * Constructor - * @param uri - - * @param displayName - - * @param parameters - - */ - function NameAddrHeader(uri, displayName, parameters) { - var _this = _super.call(this, parameters) || this; - _this.uri = uri; - _this._displayName = displayName; - return _this; - } - Object.defineProperty(NameAddrHeader.prototype, "friendlyName", { - get: function () { - return this.displayName || this.uri.aor; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(NameAddrHeader.prototype, "displayName", { - get: function () { return this._displayName; }, - set: function (value) { - this._displayName = value; - }, - enumerable: true, - configurable: true - }); - NameAddrHeader.prototype.clone = function () { - return new NameAddrHeader(this.uri.clone(), this._displayName, JSON.parse(JSON.stringify(this.parameters))); - }; - NameAddrHeader.prototype.toString = function () { - var body = (this.displayName || this.displayName === "0") ? '"' + this.displayName + '" ' : ""; - body += "<" + this.uri.toString() + ">"; - for (var parameter in this.parameters) { - if (this.parameters.hasOwnProperty(parameter)) { - body += ";" + parameter; - if (this.parameters[parameter] !== null) { - body += "=" + this.parameters[parameter]; - } - } - } - return body; - }; - return NameAddrHeader; -}(parameters_1.Parameters)); -exports.NameAddrHeader = NameAddrHeader; diff --git a/lib/core/messages/outgoing-request-message.d.ts b/lib/core/messages/outgoing-request-message.d.ts deleted file mode 100644 index f2b144e3f..000000000 --- a/lib/core/messages/outgoing-request-message.d.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { Body } from "./body"; -import { NameAddrHeader } from "./name-addr-header"; -import { URI } from "./uri"; -/** - * Outgoing request message options. - * @public - */ -export interface OutgoingRequestMessageOptions { - callId?: string; - callIdPrefix?: string; - cseq?: number; - toDisplayName?: string; - toTag?: string; - fromDisplayName?: string; - fromTag?: string; - forceRport?: boolean; - hackViaTcp?: boolean; - optionTags?: Array; - routeSet?: Array; - userAgentString?: string; - viaHost?: string; -} -/** - * Outgoing SIP request message. - * @public - */ -export declare class OutgoingRequestMessage { - /** Get a copy of the default options. */ - private static getDefaultOptions; - private static makeNameAddrHeader; - readonly headers: { - [name: string]: Array; - }; - readonly method: string; - readonly ruri: URI; - readonly from: NameAddrHeader; - readonly fromTag: string; - readonly fromURI: URI; - readonly to: NameAddrHeader; - readonly toTag: string | undefined; - readonly toURI: URI; - branch: string | undefined; - readonly callId: string; - cseq: number; - extraHeaders: Array; - body: { - body: string; - contentType: string; - } | undefined; - private options; - constructor(method: string, ruri: URI, fromURI: URI, toURI: URI, options?: OutgoingRequestMessageOptions, extraHeaders?: Array, body?: Body); - /** - * Get the value of the given header name at the given position. - * @param name - header name - * @returns Returns the specified header, undefined if header doesn't exist. - */ - getHeader(name: string): string | undefined; - /** - * Get the header/s of the given name. - * @param name - header name - * @returns Array with all the headers of the specified name. - */ - getHeaders(name: string): Array; - /** - * Verify the existence of the given header. - * @param name - header name - * @returns true if header with given name exists, false otherwise - */ - hasHeader(name: string): boolean; - /** - * Replace the the given header by the given value. - * @param name - header name - * @param value - header value - */ - setHeader(name: string, value: string | Array): void; - /** - * The Via header field indicates the transport used for the transaction - * and identifies the location where the response is to be sent. A Via - * header field value is added only after the transport that will be - * used to reach the next hop has been selected (which may involve the - * usage of the procedures in [4]). - * - * When the UAC creates a request, it MUST insert a Via into that - * request. The protocol name and protocol version in the header field - * MUST be SIP and 2.0, respectively. The Via header field value MUST - * contain a branch parameter. This parameter is used to identify the - * transaction created by that request. This parameter is used by both - * the client and the server. - * https://tools.ietf.org/html/rfc3261#section-8.1.1.7 - * @param branchParameter - The branch parameter. - * @param scheme - The scheme. - */ - setViaHeader(branch: string, scheme?: string): void; - toString(): string; -} -//# sourceMappingURL=outgoing-request-message.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/outgoing-request-message.d.ts.map b/lib/core/messages/outgoing-request-message.d.ts.map deleted file mode 100644 index 38e39b3f1..000000000 --- a/lib/core/messages/outgoing-request-message.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"outgoing-request-message.d.ts","sourceRoot":"","sources":["../../../src/core/messages/outgoing-request-message.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AAC9B,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAE,GAAG,EAAE,MAAM,OAAO,CAAC;AAQ5B;;;GAGG;AACH,MAAM,WAAW,6BAA6B;IAC5C,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,UAAU,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAC3B,QAAQ,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IACzB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED;;;GAGG;AACH,qBAAa,sBAAsB;IAEjC,yCAAyC;IACzC,OAAO,CAAC,MAAM,CAAC,iBAAiB;IAkBhC,OAAO,CAAC,MAAM,CAAC,kBAAkB;IAQjC,SAAgB,OAAO,EAAE;QAAC,CAAC,IAAI,EAAE,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,CAAA;KAAC,CAAM;IAE9D,SAAgB,MAAM,EAAE,MAAM,CAAC;IAC/B,SAAgB,IAAI,EAAE,GAAG,CAAC;IAC1B,SAAgB,IAAI,EAAE,cAAc,CAAC;IACrC,SAAgB,OAAO,EAAE,MAAM,CAAC;IAChC,SAAgB,OAAO,EAAE,GAAG,CAAC;IAC7B,SAAgB,EAAE,EAAE,cAAc,CAAC;IACnC,SAAgB,KAAK,EAAE,MAAM,GAAG,SAAS,CAAC;IAC1C,SAAgB,KAAK,EAAE,GAAG,CAAC;IACpB,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC;IAClC,SAAgB,MAAM,EAAE,MAAM,CAAC;IACxB,IAAI,EAAE,MAAM,CAAC;IACb,YAAY,EAAE,KAAK,CAAC,MAAM,CAAC,CAAM;IACjC,IAAI,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,WAAW,EAAE,MAAM,CAAA;KAAE,GAAG,SAAS,CAAC;IAE/D,OAAO,CAAC,OAAO,CAAuF;gBAGpG,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,GAAG,EACT,OAAO,EAAE,GAAG,EACZ,KAAK,EAAE,GAAG,EACV,OAAO,CAAC,EAAE,6BAA6B,EACvC,YAAY,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,EAC5B,IAAI,CAAC,EAAE,IAAI;IAoEb;;;;OAIG;IACI,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS;IAkBlD;;;;OAIG;IACI,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC;IAmB9C;;;;OAIG;IACI,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO;IAevC;;;;OAIG;IACI,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,GAAG,IAAI;IAInE;;;;;;;;;;;;;;;;OAgBG;IACI,YAAY,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,GAAE,MAAc,GAAG,IAAI;IAc1D,QAAQ,IAAI,MAAM;CAuC1B"} \ No newline at end of file diff --git a/lib/core/messages/outgoing-request-message.js b/lib/core/messages/outgoing-request-message.js deleted file mode 100644 index 5033ca908..000000000 --- a/lib/core/messages/outgoing-request-message.js +++ /dev/null @@ -1,240 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var name_addr_header_1 = require("./name-addr-header"); -var utils_1 = require("./utils"); -/** - * Outgoing SIP request message. - * @public - */ -var OutgoingRequestMessage = /** @class */ (function () { - function OutgoingRequestMessage(method, ruri, fromURI, toURI, options, extraHeaders, body) { - this.headers = {}; - this.extraHeaders = []; - this.options = OutgoingRequestMessage.getDefaultOptions(); - // Options - merge a deep copy - if (options) { - this.options = tslib_1.__assign({}, this.options, options); - if (this.options.optionTags && this.options.optionTags.length) { - this.options.optionTags = this.options.optionTags.slice(); - } - if (this.options.routeSet && this.options.routeSet.length) { - this.options.routeSet = this.options.routeSet.slice(); - } - } - // Extra headers - deep copy - if (extraHeaders && extraHeaders.length) { - this.extraHeaders = extraHeaders.slice(); - } - // Body - deep copy - if (body) { - // TODO: internal representation should be Body - // this.body = { ...body }; - this.body = { - body: body.content, - contentType: body.contentType - }; - } - // Method - this.method = method; - // RURI - this.ruri = ruri.clone(); - // From - this.fromURI = fromURI.clone(); - this.fromTag = this.options.fromTag ? this.options.fromTag : utils_1.newTag(); - this.from = OutgoingRequestMessage.makeNameAddrHeader(this.fromURI, this.options.fromDisplayName, this.fromTag); - // To - this.toURI = toURI.clone(); - this.toTag = this.options.toTag; - this.to = OutgoingRequestMessage.makeNameAddrHeader(this.toURI, this.options.toDisplayName, this.toTag); - // Call-ID - this.callId = this.options.callId ? this.options.callId : this.options.callIdPrefix + utils_1.createRandomToken(15); - // CSeq - this.cseq = this.options.cseq; - // The relative order of header fields with different field names is not - // significant. However, it is RECOMMENDED that header fields which are - // needed for proxy processing (Via, Route, Record-Route, Proxy-Require, - // Max-Forwards, and Proxy-Authorization, for example) appear towards - // the top of the message to facilitate rapid parsing. - // https://tools.ietf.org/html/rfc3261#section-7.3.1 - this.setHeader("route", this.options.routeSet); - this.setHeader("via", ""); - this.setHeader("to", this.to.toString()); - this.setHeader("from", this.from.toString()); - this.setHeader("cseq", this.cseq + " " + this.method); - this.setHeader("call-id", this.callId); - this.setHeader("max-forwards", "70"); - } - /** Get a copy of the default options. */ - OutgoingRequestMessage.getDefaultOptions = function () { - return { - callId: "", - callIdPrefix: "", - cseq: 1, - toDisplayName: "", - toTag: "", - fromDisplayName: "", - fromTag: "", - forceRport: false, - hackViaTcp: false, - optionTags: ["outbound"], - routeSet: [], - userAgentString: "sip.js", - viaHost: "" - }; - }; - OutgoingRequestMessage.makeNameAddrHeader = function (uri, displayName, tag) { - var parameters = {}; - if (tag) { - parameters.tag = tag; - } - return new name_addr_header_1.NameAddrHeader(uri, displayName, parameters); - }; - /** - * Get the value of the given header name at the given position. - * @param name - header name - * @returns Returns the specified header, undefined if header doesn't exist. - */ - OutgoingRequestMessage.prototype.getHeader = function (name) { - var header = this.headers[utils_1.headerize(name)]; - if (header) { - if (header[0]) { - return header[0]; - } - } - else { - var regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); - for (var _i = 0, _a = this.extraHeaders; _i < _a.length; _i++) { - var exHeader = _a[_i]; - if (regexp.test(exHeader)) { - return exHeader.substring(exHeader.indexOf(":") + 1).trim(); - } - } - } - return; - }; - /** - * Get the header/s of the given name. - * @param name - header name - * @returns Array with all the headers of the specified name. - */ - OutgoingRequestMessage.prototype.getHeaders = function (name) { - var result = []; - var headerArray = this.headers[utils_1.headerize(name)]; - if (headerArray) { - for (var _i = 0, headerArray_1 = headerArray; _i < headerArray_1.length; _i++) { - var headerPart = headerArray_1[_i]; - result.push(headerPart); - } - } - else { - var regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); - for (var _a = 0, _b = this.extraHeaders; _a < _b.length; _a++) { - var exHeader = _b[_a]; - if (regexp.test(exHeader)) { - result.push(exHeader.substring(exHeader.indexOf(":") + 1).trim()); - } - } - } - return result; - }; - /** - * Verify the existence of the given header. - * @param name - header name - * @returns true if header with given name exists, false otherwise - */ - OutgoingRequestMessage.prototype.hasHeader = function (name) { - if (this.headers[utils_1.headerize(name)]) { - return true; - } - else { - var regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); - for (var _i = 0, _a = this.extraHeaders; _i < _a.length; _i++) { - var extraHeader = _a[_i]; - if (regexp.test(extraHeader)) { - return true; - } - } - } - return false; - }; - /** - * Replace the the given header by the given value. - * @param name - header name - * @param value - header value - */ - OutgoingRequestMessage.prototype.setHeader = function (name, value) { - this.headers[utils_1.headerize(name)] = (value instanceof Array) ? value : [value]; - }; - /** - * The Via header field indicates the transport used for the transaction - * and identifies the location where the response is to be sent. A Via - * header field value is added only after the transport that will be - * used to reach the next hop has been selected (which may involve the - * usage of the procedures in [4]). - * - * When the UAC creates a request, it MUST insert a Via into that - * request. The protocol name and protocol version in the header field - * MUST be SIP and 2.0, respectively. The Via header field value MUST - * contain a branch parameter. This parameter is used to identify the - * transaction created by that request. This parameter is used by both - * the client and the server. - * https://tools.ietf.org/html/rfc3261#section-8.1.1.7 - * @param branchParameter - The branch parameter. - * @param scheme - The scheme. - */ - OutgoingRequestMessage.prototype.setViaHeader = function (branch, scheme) { - if (scheme === void 0) { scheme = "WSS"; } - // FIXME: Hack - if (this.options.hackViaTcp) { - scheme = "TCP"; - } - var via = "SIP/2.0/" + scheme; - via += " " + this.options.viaHost + ";branch=" + branch; - if (this.options.forceRport) { - via += ";rport"; - } - this.setHeader("via", via); - this.branch = branch; - }; - OutgoingRequestMessage.prototype.toString = function () { - var msg = ""; - msg += this.method + " " + this.ruri.toRaw() + " SIP/2.0\r\n"; - for (var header in this.headers) { - if (this.headers[header]) { - for (var _i = 0, _a = this.headers[header]; _i < _a.length; _i++) { - var headerPart = _a[_i]; - msg += header + ": " + headerPart + "\r\n"; - } - } - } - for (var _b = 0, _c = this.extraHeaders; _b < _c.length; _b++) { - var header = _c[_b]; - msg += header.trim() + "\r\n"; - } - msg += "Supported: " + this.options.optionTags.join(", ") + "\r\n"; - msg += "User-Agent: " + this.options.userAgentString + "\r\n"; - if (this.body) { - if (typeof this.body === "string") { - msg += "Content-Length: " + utils_1.str_utf8_length(this.body) + "\r\n\r\n"; - msg += this.body; - } - else { - if (this.body.body && this.body.contentType) { - msg += "Content-Type: " + this.body.contentType + "\r\n"; - msg += "Content-Length: " + utils_1.str_utf8_length(this.body.body) + "\r\n\r\n"; - msg += this.body.body; - } - else { - msg += "Content-Length: " + 0 + "\r\n\r\n"; - } - } - } - else { - msg += "Content-Length: " + 0 + "\r\n\r\n"; - } - return msg; - }; - return OutgoingRequestMessage; -}()); -exports.OutgoingRequestMessage = OutgoingRequestMessage; diff --git a/lib/core/messages/outgoing-request.d.ts b/lib/core/messages/outgoing-request.d.ts deleted file mode 100644 index c88155faa..000000000 --- a/lib/core/messages/outgoing-request.d.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { Body } from "./body"; -import { IncomingResponse } from "./incoming-response"; -import { OutgoingRequestMessage } from "./outgoing-request-message"; -/** - * A SIP message sent from a local client to a remote server. - * @remarks - * For the purpose of invoking a particular operation. - * https://tools.ietf.org/html/rfc3261#section-7.1 - * @public - */ -export interface OutgoingRequest { - /** Delegate providing custom handling of this outgoing request. */ - delegate?: OutgoingRequestDelegate; - /** The outgoing message. */ - readonly message: OutgoingRequestMessage; - /** - * Destroy request. - */ - dispose(): void; - /** - * Sends a CANCEL message targeting this request to the UAS. - * @param reason - Reason for canceling request. - * @param options - Request options bucket. - */ - cancel(reason?: string, options?: RequestOptions): void; -} -/** - * Delegate providing custom handling of outgoing requests. - * @public - */ -export interface OutgoingRequestDelegate { - /** - * Received a 2xx positive final response to this request. - * @param response - Incoming response. - */ - onAccept?(response: IncomingResponse): void; - /** - * Received a 1xx provisional response to this request. Excluding 100 responses. - * @param response - Incoming response. - */ - onProgress?(response: IncomingResponse): void; - /** - * Received a 3xx negative final response to this request. - * @param response - Incoming response. - */ - onRedirect?(response: IncomingResponse): void; - /** - * Received a 4xx, 5xx, or 6xx negative final response to this request. - * @param response - Incoming response. - */ - onReject?(response: IncomingResponse): void; - /** - * Received a 100 provisional response. - * @param response - Incoming response. - */ - onTrying?(response: IncomingResponse): void; -} -/** - * Request options bucket. - * @public - */ -export interface RequestOptions { - /** Extra headers to include in the message. */ - extraHeaders?: Array; - /** Body to include in the message. */ - body?: Body; -} -//# sourceMappingURL=outgoing-request.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/outgoing-request.d.ts.map b/lib/core/messages/outgoing-request.d.ts.map deleted file mode 100644 index 35d2e0d88..000000000 --- a/lib/core/messages/outgoing-request.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"outgoing-request.d.ts","sourceRoot":"","sources":["../../../src/core/messages/outgoing-request.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AAC9B,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AAEpE;;;;;;GAMG;AACH,MAAM,WAAW,eAAe;IAC9B,mEAAmE;IACnE,QAAQ,CAAC,EAAE,uBAAuB,CAAC;IAEnC,4BAA4B;IAC5B,QAAQ,CAAC,OAAO,EAAE,sBAAsB,CAAC;IAEzC;;OAEG;IACH,OAAO,IAAI,IAAI,CAAC;IAEhB;;;;OAIG;IACH,MAAM,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,IAAI,CAAC;CACzD;AAED;;;GAGG;AACH,MAAM,WAAW,uBAAuB;IACtC;;;OAGG;IACH,QAAQ,CAAC,CAAC,QAAQ,EAAE,gBAAgB,GAAG,IAAI,CAAC;IAE5C;;;OAGG;IACH,UAAU,CAAC,CAAC,QAAQ,EAAE,gBAAgB,GAAG,IAAI,CAAC;IAE9C;;;OAGG;IACH,UAAU,CAAC,CAAC,QAAQ,EAAE,gBAAgB,GAAG,IAAI,CAAC;IAE9C;;;OAGG;IACH,QAAQ,CAAC,CAAC,QAAQ,EAAE,gBAAgB,GAAG,IAAI,CAAC;IAE5C;;;OAGG;IACH,QAAQ,CAAC,CAAC,QAAQ,EAAE,gBAAgB,GAAG,IAAI,CAAC;CAC7C;AAED;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC7B,+CAA+C;IAC/C,YAAY,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAC7B,sCAAsC;IACtC,IAAI,CAAC,EAAE,IAAI,CAAC;CACb"} \ No newline at end of file diff --git a/lib/core/messages/outgoing-request.js b/lib/core/messages/outgoing-request.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/core/messages/outgoing-request.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/core/messages/outgoing-response.d.ts b/lib/core/messages/outgoing-response.d.ts deleted file mode 100644 index cae196ed8..000000000 --- a/lib/core/messages/outgoing-response.d.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { Body } from "./body"; -import { IncomingRequestMessage } from "./incoming-request-message"; -/** - * A SIP message sent from a local server to a remote client. - * @remarks - * For indicating the status of a request sent from the client to the server. - * https://tools.ietf.org/html/rfc3261#section-7.2 - * @public - */ -export interface OutgoingResponse { - /** The outgoing message. */ - readonly message: string; -} -/** - * Response options bucket. - * @public - */ -export interface ResponseOptions { - /** Status code of the response. */ - statusCode: number; - /** Reason phrase of the response. */ - reasonPhrase?: string; - /** To tag of the response. If not provided, one is generated. */ - toTag?: string; - /** User agent string for User-Agent header. */ - userAgent?: string; - /** Support options tags for Supported header. */ - supported?: Array; - /** Extra headers to include in the message. */ - extraHeaders?: Array; - /** Body to include in the message. */ - body?: Body; -} -/** - * When a UAS wishes to construct a response to a request, it follows - * the general procedures detailed in the following subsections. - * Additional behaviors specific to the response code in question, which - * are not detailed in this section, may also be required. - * https://tools.ietf.org/html/rfc3261#section-8.2.6 - * @internal - */ -export declare function constructOutgoingResponse(message: IncomingRequestMessage, options: ResponseOptions): OutgoingResponse; -//# sourceMappingURL=outgoing-response.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/outgoing-response.d.ts.map b/lib/core/messages/outgoing-response.d.ts.map deleted file mode 100644 index 20c6b4d42..000000000 --- a/lib/core/messages/outgoing-response.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"outgoing-response.d.ts","sourceRoot":"","sources":["../../../src/core/messages/outgoing-response.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AAC9B,OAAO,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AAGpE;;;;;;GAMG;AACH,MAAM,WAAW,gBAAgB;IAC/B,4BAA4B;IAC5B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;CAC1B;AAED;;;GAGG;AACH,MAAM,WAAW,eAAe;IAC9B,mCAAmC;IACnC,UAAU,EAAE,MAAM,CAAC;IACnB,qCAAqC;IACrC,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,iEAAiE;IACjE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,+CAA+C;IAC/C,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,iDAAiD;IACjD,SAAS,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAC1B,+CAA+C;IAC/C,YAAY,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAC7B,sCAAsC;IACtC,IAAI,CAAC,EAAE,IAAI,CAAC;CACb;AAED;;;;;;;GAOG;AACH,wBAAgB,yBAAyB,CACvC,OAAO,EAAE,sBAAsB,EAC/B,OAAO,EAAE,eAAe,GACvB,gBAAgB,CAgIlB"} \ No newline at end of file diff --git a/lib/core/messages/outgoing-response.js b/lib/core/messages/outgoing-response.js deleted file mode 100644 index 5c2f78197..000000000 --- a/lib/core/messages/outgoing-response.js +++ /dev/null @@ -1,129 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var utils_1 = require("./utils"); -/** - * When a UAS wishes to construct a response to a request, it follows - * the general procedures detailed in the following subsections. - * Additional behaviors specific to the response code in question, which - * are not detailed in this section, may also be required. - * https://tools.ietf.org/html/rfc3261#section-8.2.6 - * @internal - */ -function constructOutgoingResponse(message, options) { - var CRLF = "\r\n"; - if (options.statusCode < 100 || options.statusCode > 699) { - throw new TypeError("Invalid statusCode: " + options.statusCode); - } - var reasonPhrase = options.reasonPhrase ? options.reasonPhrase : utils_1.getReasonPhrase(options.statusCode); - // SIP responses are distinguished from requests by having a Status-Line - // as their start-line. A Status-Line consists of the protocol version - // followed by a numeric Status-Code and its associated textual phrase, - // with each element separated by a single SP character. - // https://tools.ietf.org/html/rfc3261#section-7.2 - var response = "SIP/2.0 " + options.statusCode + " " + reasonPhrase + CRLF; - // One largely non-method-specific guideline for the generation of - // responses is that UASs SHOULD NOT issue a provisional response for a - // non-INVITE request. Rather, UASs SHOULD generate a final response to - // a non-INVITE request as soon as possible. - // https://tools.ietf.org/html/rfc3261#section-8.2.6.1 - if (options.statusCode >= 100 && options.statusCode < 200) { - // TODO - } - // When a 100 (Trying) response is generated, any Timestamp header field - // present in the request MUST be copied into this 100 (Trying) - // response. If there is a delay in generating the response, the UAS - // SHOULD add a delay value into the Timestamp value in the response. - // This value MUST contain the difference between the time of sending of - // the response and receipt of the request, measured in seconds. - // https://tools.ietf.org/html/rfc3261#section-8.2.6.1 - if (options.statusCode === 100) { - // TODO - } - // The From field of the response MUST equal the From header field of - // the request. The Call-ID header field of the response MUST equal the - // Call-ID header field of the request. The CSeq header field of the - // response MUST equal the CSeq field of the request. The Via header - // field values in the response MUST equal the Via header field values - // in the request and MUST maintain the same ordering. - // https://tools.ietf.org/html/rfc3261#section-8.2.6.2 - var fromHeader = "From: " + message.getHeader("From") + CRLF; - var callIdHeader = "Call-ID: " + message.callId + CRLF; - var cSeqHeader = "CSeq: " + message.cseq + " " + message.method + CRLF; - var viaHeaders = message.getHeaders("via").reduce(function (previous, current) { - return previous + "Via: " + current + CRLF; - }, ""); - // If a request contained a To tag in the request, the To header field - // in the response MUST equal that of the request. However, if the To - // header field in the request did not contain a tag, the URI in the To - // header field in the response MUST equal the URI in the To header - // field; additionally, the UAS MUST add a tag to the To header field in - // the response (with the exception of the 100 (Trying) response, in - // which a tag MAY be present). This serves to identify the UAS that is - // responding, possibly resulting in a component of a dialog ID. The - // same tag MUST be used for all responses to that request, both final - // and provisional (again excepting the 100 (Trying)). - // https://tools.ietf.org/html/rfc3261#section-8.2.6.2 - var toHeader = "To: " + message.getHeader("to"); - if (options.statusCode > 100 && !message.parseHeader("to").hasParam("tag")) { - var toTag = options.toTag; - if (!toTag) { - // Stateless UAS Behavior... - // o To header tags MUST be generated for responses in a stateless - // manner - in a manner that will generate the same tag for the - // same request consistently. For information on tag construction - // see Section 19.3. - // https://tools.ietf.org/html/rfc3261#section-8.2.7 - toTag = utils_1.newTag(); // FIXME: newTag() currently generates random tags - } - toHeader += ";tag=" + toTag; - } - toHeader += CRLF; - // FIXME: TODO: needs review... moved to InviteUserAgentServer (as it is specific to that) - // let recordRouteHeaders = ""; - // if (request.method === C.INVITE && statusCode > 100 && statusCode <= 200) { - // recordRouteHeaders = request.getHeaders("record-route").reduce((previous, current) => { - // return previous + "Record-Route: " + current + CRLF; - // }, ""); - // } - // FIXME: TODO: needs review... - var supportedHeader = ""; - if (options.supported) { - supportedHeader = "Supported: " + options.supported.join(", ") + CRLF; - } - // FIXME: TODO: needs review... - var userAgentHeader = ""; - if (options.userAgent) { - userAgentHeader = "User-Agent: " + options.userAgent + CRLF; - } - var extensionHeaders = ""; - if (options.extraHeaders) { - extensionHeaders = options.extraHeaders.reduce(function (previous, current) { - return previous + current.trim() + CRLF; - }, ""); - } - // The relative order of header fields with different field names is not - // significant. However, it is RECOMMENDED that header fields which are - // needed for proxy processing (Via, Route, Record-Route, Proxy-Require, - // Max-Forwards, and Proxy-Authorization, for example) appear towards - // the top of the message to facilitate rapid parsing. - // https://tools.ietf.org/html/rfc3261#section-7.3.1 - // response += recordRouteHeaders; - response += viaHeaders; - response += fromHeader; - response += toHeader; - response += cSeqHeader; - response += callIdHeader; - response += supportedHeader; - response += userAgentHeader; - response += extensionHeaders; - if (options.body) { - response += "Content-Type: " + options.body.contentType + CRLF; - response += "Content-Length: " + utils_1.str_utf8_length(options.body.content) + CRLF + CRLF; - response += options.body.content; - } - else { - response += "Content-Length: " + 0 + CRLF + CRLF; - } - return { message: response }; -} -exports.constructOutgoingResponse = constructOutgoingResponse; diff --git a/lib/core/messages/parameters.d.ts b/lib/core/messages/parameters.d.ts deleted file mode 100644 index 299b598ba..000000000 --- a/lib/core/messages/parameters.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -/** - * @internal - */ -export declare class Parameters { - parameters: { - [name: string]: string; - }; - constructor(parameters: { - [name: string]: string; - }); - setParam(key: string, value: any): void; - getParam(key: string): string | undefined; - hasParam(key: string): boolean; - deleteParam(parameter: string): any; - clearParams(): void; -} -//# sourceMappingURL=parameters.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/parameters.d.ts.map b/lib/core/messages/parameters.d.ts.map deleted file mode 100644 index a5720b95d..000000000 --- a/lib/core/messages/parameters.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"parameters.d.ts","sourceRoot":"","sources":["../../../src/core/messages/parameters.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,qBAAa,UAAU;IACd,UAAU,EAAE;QAAC,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAA;KAAC,CAAM;gBAErC,UAAU,EAAE;QAAC,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAA;KAAC;IAQzC,QAAQ,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,GAAG,IAAI;IAMvC,QAAQ,CAAC,GAAG,EAAE,MAAM;IAMpB,QAAQ,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO;IAO9B,WAAW,CAAC,SAAS,EAAE,MAAM,GAAG,GAAG;IASnC,WAAW,IAAI,IAAI;CAG3B"} \ No newline at end of file diff --git a/lib/core/messages/parameters.js b/lib/core/messages/parameters.js deleted file mode 100644 index 9d627f274..000000000 --- a/lib/core/messages/parameters.js +++ /dev/null @@ -1,44 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * @internal - */ -var Parameters = /** @class */ (function () { - function Parameters(parameters) { - this.parameters = {}; - for (var param in parameters) { - if (parameters.hasOwnProperty(param)) { - this.setParam(param, parameters[param]); - } - } - } - Parameters.prototype.setParam = function (key, value) { - if (key) { - this.parameters[key.toLowerCase()] = (typeof value === "undefined" || value === null) ? null : value.toString(); - } - }; - Parameters.prototype.getParam = function (key) { - if (key) { - return this.parameters[key.toLowerCase()]; - } - }; - Parameters.prototype.hasParam = function (key) { - if (key) { - return !!this.parameters.hasOwnProperty(key.toLowerCase()); - } - return false; - }; - Parameters.prototype.deleteParam = function (parameter) { - parameter = parameter.toLowerCase(); - if (this.parameters.hasOwnProperty(parameter)) { - var value = this.parameters[parameter]; - delete this.parameters[parameter]; - return value; - } - }; - Parameters.prototype.clearParams = function () { - this.parameters = {}; - }; - return Parameters; -}()); -exports.Parameters = Parameters; diff --git a/lib/core/messages/uri.d.ts b/lib/core/messages/uri.d.ts deleted file mode 100644 index d422f6f36..000000000 --- a/lib/core/messages/uri.d.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { Parameters } from "./parameters"; -/** - * URI. - * @public - */ -export declare class URI extends Parameters { - private headers; - private normal; - private raw; - /** - * Constructor - * @param scheme - - * @param user - - * @param host - - * @param port - - * @param parameters - - * @param headers - - */ - constructor(scheme: string, user: string, host: string, port?: number, parameters?: any, headers?: any); - scheme: string; - user: string | undefined; - host: string; - readonly aor: string; - port: number | undefined; - setHeader(name: string, value: any): void; - getHeader(name: string): string | undefined; - hasHeader(name: string): boolean; - deleteHeader(header: string): any; - clearHeaders(): void; - clone(): URI; - toRaw(): string; - toString(): string; - private readonly _normal; - private readonly _raw; - private _toString; - private escapeUser; - private headerize; -} -//# sourceMappingURL=uri.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/uri.d.ts.map b/lib/core/messages/uri.d.ts.map deleted file mode 100644 index 6380fa7e4..000000000 --- a/lib/core/messages/uri.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"uri.d.ts","sourceRoot":"","sources":["../../../src/core/messages/uri.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAS1C;;;GAGG;AACH,qBAAa,GAAI,SAAQ,UAAU;IACjC,OAAO,CAAC,OAAO,CAA6B;IAC5C,OAAO,CAAC,MAAM,CAAY;IAC1B,OAAO,CAAC,GAAG,CAAY;IAEvB;;;;;;;;OAQG;gBAED,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,EACZ,IAAI,CAAC,EAAE,MAAM,EACb,UAAU,CAAC,EAAE,GAAG,EAChB,OAAO,CAAC,EAAE,GAAG;IAkCX,MAAM,EAAI,MAAM;IAMhB,IAAI,EAAI,MAAM,GAAG,SAAS;IAK1B,IAAI,EAAI,MAAM;aAMd,GAAG,EAAI,MAAM;IAEb,IAAI,EAAI,MAAM,GAAG,SAAS;IAKvB,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,GAAG,IAAI;IAIzC,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS;IAM3C,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO;IAIhC,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG,GAAG;IAUjC,YAAY,IAAI,IAAI;IAIpB,KAAK,IAAI,GAAG;IAUZ,KAAK,IAAI,MAAM;IAIf,QAAQ,IAAI,MAAM;qBAIb,OAAO;qBAEP,IAAI;IAEhB,OAAO,CAAC,SAAS;IA+CjB,OAAO,CAAC,UAAU;IAuBlB,OAAO,CAAC,SAAS;CAwBlB"} \ No newline at end of file diff --git a/lib/core/messages/uri.js b/lib/core/messages/uri.js deleted file mode 100644 index 18789fcaf..000000000 --- a/lib/core/messages/uri.js +++ /dev/null @@ -1,217 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var parameters_1 = require("./parameters"); -/** - * URI. - * @public - */ -var URI = /** @class */ (function (_super) { - tslib_1.__extends(URI, _super); - /** - * Constructor - * @param scheme - - * @param user - - * @param host - - * @param port - - * @param parameters - - * @param headers - - */ - function URI(scheme, user, host, port, parameters, headers) { - var _this = _super.call(this, parameters) || this; - _this.headers = {}; - // Checks - if (!host) { - throw new TypeError('missing or invalid "host" parameter'); - } - // Initialize parameters - scheme = scheme || "sip"; - for (var header in headers) { - if (headers.hasOwnProperty(header)) { - _this.setHeader(header, headers[header]); - } - } - // Raw URI - _this.raw = { - scheme: scheme, - user: user, - host: host, - port: port - }; - // Normalized URI - _this.normal = { - scheme: scheme.toLowerCase(), - user: user, - host: host.toLowerCase(), - port: port - }; - return _this; - } - Object.defineProperty(URI.prototype, "scheme", { - get: function () { return this.normal.scheme; }, - set: function (value) { - this.raw.scheme = value; - this.normal.scheme = value.toLowerCase(); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(URI.prototype, "user", { - get: function () { return this.normal.user; }, - set: function (value) { - this.normal.user = this.raw.user = value; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(URI.prototype, "host", { - get: function () { return this.normal.host; }, - set: function (value) { - this.raw.host = value; - this.normal.host = value.toLowerCase(); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(URI.prototype, "aor", { - get: function () { return this.normal.user + "@" + this.normal.host; }, - enumerable: true, - configurable: true - }); - Object.defineProperty(URI.prototype, "port", { - get: function () { return this.normal.port; }, - set: function (value) { - this.normal.port = this.raw.port = value === 0 ? value : value; - }, - enumerable: true, - configurable: true - }); - URI.prototype.setHeader = function (name, value) { - this.headers[this.headerize(name)] = (value instanceof Array) ? value : [value]; - }; - URI.prototype.getHeader = function (name) { - if (name) { - return this.headers[this.headerize(name)]; - } - }; - URI.prototype.hasHeader = function (name) { - return !!name && !!this.headers.hasOwnProperty(this.headerize(name)); - }; - URI.prototype.deleteHeader = function (header) { - header = this.headerize(header); - if (this.headers.hasOwnProperty(header)) { - var value = this.headers[header]; - delete this.headers[header]; - return value; - } - }; - URI.prototype.clearHeaders = function () { - this.headers = {}; - }; - URI.prototype.clone = function () { - return new URI(this._raw.scheme, this._raw.user || "", this._raw.host, this._raw.port, JSON.parse(JSON.stringify(this.parameters)), JSON.parse(JSON.stringify(this.headers))); - }; - URI.prototype.toRaw = function () { - return this._toString(this._raw); - }; - URI.prototype.toString = function () { - return this._toString(this._normal); - }; - Object.defineProperty(URI.prototype, "_normal", { - get: function () { return this.normal; }, - enumerable: true, - configurable: true - }); - Object.defineProperty(URI.prototype, "_raw", { - get: function () { return this.raw; }, - enumerable: true, - configurable: true - }); - URI.prototype._toString = function (uri) { - var uriString = uri.scheme + ":"; - // add slashes if it's not a sip(s) URI - if (!uri.scheme.toLowerCase().match("^sips?$")) { - uriString += "//"; - } - if (uri.user) { - uriString += this.escapeUser(uri.user) + "@"; - } - uriString += uri.host; - if (uri.port || uri.port === 0) { - uriString += ":" + uri.port; - } - for (var parameter in this.parameters) { - if (this.parameters.hasOwnProperty(parameter)) { - uriString += ";" + parameter; - if (this.parameters[parameter] !== null) { - uriString += "=" + this.parameters[parameter]; - } - } - } - var headers = []; - for (var header in this.headers) { - if (this.headers.hasOwnProperty(header)) { - for (var idx in this.headers[header]) { - if (this.headers[header].hasOwnProperty(idx)) { - headers.push(header + "=" + this.headers[header][idx]); - } - } - } - } - if (headers.length > 0) { - uriString += "?" + headers.join("&"); - } - return uriString; - }; - /* - * Hex-escape a SIP URI user. - * @private - * @param {String} user - */ - URI.prototype.escapeUser = function (user) { - var decodedUser; - // FIXME: This is called by toString above which should never throw, but - // decodeURIComponent can throw and I've seen one case in production where - // it did throw resulting in a cascading failure. This class should be - // fixed so that decodeURIComponent is not called at this point (in toString). - // The user should be decoded when the URI is constructor or some other - // place where we can catch the error before the URI is created or somesuch. - try { - decodedUser = decodeURIComponent(user); - } - catch (error) { - throw error; - } - // Don't hex-escape ':' (%3A), '+' (%2B), '?' (%3F"), '/' (%2F). - return encodeURIComponent(decodedUser) - .replace(/%3A/ig, ":") - .replace(/%2B/ig, "+") - .replace(/%3F/ig, "?") - .replace(/%2F/ig, "/"); - }; - URI.prototype.headerize = function (str) { - var exceptions = { - "Call-Id": "Call-ID", - "Cseq": "CSeq", - "Min-Se": "Min-SE", - "Rack": "RAck", - "Rseq": "RSeq", - "Www-Authenticate": "WWW-Authenticate", - }; - var name = str.toLowerCase().replace(/_/g, "-").split("-"); - var parts = name.length; - var hname = ""; - for (var part = 0; part < parts; part++) { - if (part !== 0) { - hname += "-"; - } - hname += name[part].charAt(0).toUpperCase() + name[part].substring(1); - } - if (exceptions[hname]) { - hname = exceptions[hname]; - } - return hname; - }; - return URI; -}(parameters_1.Parameters)); -exports.URI = URI; diff --git a/lib/core/messages/utils.d.ts b/lib/core/messages/utils.d.ts deleted file mode 100644 index a89770ceb..000000000 --- a/lib/core/messages/utils.d.ts +++ /dev/null @@ -1,25 +0,0 @@ -/** - * @param size - - * @param base - - * @internal - */ -export declare function createRandomToken(size: number, base?: number): string; -/** - * @internal - */ -export declare function getReasonPhrase(code: number): string; -/** - * @internal - */ -export declare function newTag(): string; -/** - * @param str - - * @internal - */ -export declare function headerize(str: string): string; -/** - * @param str - - * @internal - */ -export declare function str_utf8_length(str: string): number; -//# sourceMappingURL=utils.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/utils.d.ts.map b/lib/core/messages/utils.d.ts.map deleted file mode 100644 index c009f6ab1..000000000 --- a/lib/core/messages/utils.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../src/core/messages/utils.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,GAAE,MAAW,GAAG,MAAM,CAOzE;AAED;;GAEG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAEpD;AAED;;GAEG;AACH,wBAAgB,MAAM,IAAI,MAAM,CAE/B;AAED;;;GAGG;AACH,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAuB7C;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAEnD"} \ No newline at end of file diff --git a/lib/core/messages/utils.js b/lib/core/messages/utils.js deleted file mode 100644 index 7cf513f87..000000000 --- a/lib/core/messages/utils.js +++ /dev/null @@ -1,145 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * @param size - - * @param base - - * @internal - */ -function createRandomToken(size, base) { - if (base === void 0) { base = 32; } - var token = ""; - for (var i = 0; i < size; i++) { - var r = Math.floor(Math.random() * base); - token += r.toString(base); - } - return token; -} -exports.createRandomToken = createRandomToken; -/** - * @internal - */ -function getReasonPhrase(code) { - return REASON_PHRASE[code] || ""; -} -exports.getReasonPhrase = getReasonPhrase; -/** - * @internal - */ -function newTag() { - return createRandomToken(10); -} -exports.newTag = newTag; -/** - * @param str - - * @internal - */ -function headerize(str) { - var exceptions = { - "Call-Id": "Call-ID", - "Cseq": "CSeq", - "Min-Se": "Min-SE", - "Rack": "RAck", - "Rseq": "RSeq", - "Www-Authenticate": "WWW-Authenticate", - }; - var name = str.toLowerCase().replace(/_/g, "-").split("-"); - var parts = name.length; - var hname = ""; - for (var part = 0; part < parts; part++) { - if (part !== 0) { - hname += "-"; - } - hname += name[part].charAt(0).toUpperCase() + name[part].substring(1); - } - if (exceptions[hname]) { - hname = exceptions[hname]; - } - return hname; -} -exports.headerize = headerize; -/** - * @param str - - * @internal - */ -function str_utf8_length(str) { - return encodeURIComponent(str).replace(/%[A-F\d]{2}/g, "U").length; -} -exports.str_utf8_length = str_utf8_length; -/** - * SIP Response Reasons - * DOC: http://www.iana.org/assignments/sip-parameters - * @internal - */ -var REASON_PHRASE = { - 100: "Trying", - 180: "Ringing", - 181: "Call Is Being Forwarded", - 182: "Queued", - 183: "Session Progress", - 199: "Early Dialog Terminated", - 200: "OK", - 202: "Accepted", - 204: "No Notification", - 300: "Multiple Choices", - 301: "Moved Permanently", - 302: "Moved Temporarily", - 305: "Use Proxy", - 380: "Alternative Service", - 400: "Bad Request", - 401: "Unauthorized", - 402: "Payment Required", - 403: "Forbidden", - 404: "Not Found", - 405: "Method Not Allowed", - 406: "Not Acceptable", - 407: "Proxy Authentication Required", - 408: "Request Timeout", - 410: "Gone", - 412: "Conditional Request Failed", - 413: "Request Entity Too Large", - 414: "Request-URI Too Long", - 415: "Unsupported Media Type", - 416: "Unsupported URI Scheme", - 417: "Unknown Resource-Priority", - 420: "Bad Extension", - 421: "Extension Required", - 422: "Session Interval Too Small", - 423: "Interval Too Brief", - 428: "Use Identity Header", - 429: "Provide Referrer Identity", - 430: "Flow Failed", - 433: "Anonymity Disallowed", - 436: "Bad Identity-Info", - 437: "Unsupported Certificate", - 438: "Invalid Identity Header", - 439: "First Hop Lacks Outbound Support", - 440: "Max-Breadth Exceeded", - 469: "Bad Info Package", - 470: "Consent Needed", - 478: "Unresolvable Destination", - 480: "Temporarily Unavailable", - 481: "Call/Transaction Does Not Exist", - 482: "Loop Detected", - 483: "Too Many Hops", - 484: "Address Incomplete", - 485: "Ambiguous", - 486: "Busy Here", - 487: "Request Terminated", - 488: "Not Acceptable Here", - 489: "Bad Event", - 491: "Request Pending", - 493: "Undecipherable", - 494: "Security Agreement Required", - 500: "Internal Server Error", - 501: "Not Implemented", - 502: "Bad Gateway", - 503: "Service Unavailable", - 504: "Server Time-out", - 505: "Version Not Supported", - 513: "Message Too Large", - 580: "Precondition Failure", - 600: "Busy Everywhere", - 603: "Decline", - 604: "Does Not Exist Anywhere", - 606: "Not Acceptable" -}; diff --git a/lib/core/session/index.d.ts b/lib/core/session/index.d.ts deleted file mode 100644 index 27ebc6836..000000000 --- a/lib/core/session/index.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -export * from "./session"; -export * from "./session-delegate"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/core/session/index.d.ts.map b/lib/core/session/index.d.ts.map deleted file mode 100644 index e32c4cc66..000000000 --- a/lib/core/session/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/session/index.ts"],"names":[],"mappings":"AAAA,cAAc,WAAW,CAAC;AAC1B,cAAc,oBAAoB,CAAC"} \ No newline at end of file diff --git a/lib/core/session/index.js b/lib/core/session/index.js deleted file mode 100644 index 1ca6145d7..000000000 --- a/lib/core/session/index.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -tslib_1.__exportStar(require("./session"), exports); diff --git a/lib/core/session/session-delegate.d.ts b/lib/core/session/session-delegate.d.ts deleted file mode 100644 index c2a18248a..000000000 --- a/lib/core/session/session-delegate.d.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { IncomingAckRequest, IncomingByeRequest, IncomingInfoRequest, IncomingInviteRequest, IncomingNotifyRequest, IncomingPrackRequest, IncomingReferRequest } from "../messages"; -/** - * Session delegate. - * @public - */ -export interface SessionDelegate { - /** - * Receive ACK request. - * @param request - Incoming ACK request. - */ - onAck?(request: IncomingAckRequest): void; - /** - * Timeout waiting for ACK request. - * If no handler is provided the Session will terminated with a BYE. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - */ - onAckTimeout?(): void; - /** - * Receive BYE request. - * https://tools.ietf.org/html/rfc3261#section-15.1.2 - * @param request - Incoming BYE request. - */ - onBye?(request: IncomingByeRequest): void; - /** - * Receive INFO request. - * @param request - Incoming INFO request. - */ - onInfo?(request: IncomingInfoRequest): void; - /** - * Receive re-INVITE request. - * https://tools.ietf.org/html/rfc3261#section-14.2 - * @param request - Incoming INVITE request. - */ - onInvite?(request: IncomingInviteRequest): void; - /** - * Receive NOTIFY request. - * https://tools.ietf.org/html/rfc6665#section-4.1.3 - * @param request - Incoming NOTIFY request. - */ - onNotify?(request: IncomingNotifyRequest): void; - /** - * Receive PRACK request. - * https://tools.ietf.org/html/rfc3262#section-3 - * @param request - Incoming PRACK request. - */ - onPrack?(request: IncomingPrackRequest): void; - /** - * Receive REFER request. - * https://tools.ietf.org/html/rfc3515#section-2.4.2 - * @param request - Incoming REFER request. - */ - onRefer?(request: IncomingReferRequest): void; -} -//# sourceMappingURL=session-delegate.d.ts.map \ No newline at end of file diff --git a/lib/core/session/session-delegate.d.ts.map b/lib/core/session/session-delegate.d.ts.map deleted file mode 100644 index 78de85e7c..000000000 --- a/lib/core/session/session-delegate.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"session-delegate.d.ts","sourceRoot":"","sources":["../../../src/core/session/session-delegate.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,kBAAkB,EAClB,mBAAmB,EACnB,qBAAqB,EACrB,qBAAqB,EACrB,oBAAoB,EACpB,oBAAoB,EACrB,MAAM,aAAa,CAAC;AAErB;;;GAGG;AACH,MAAM,WAAW,eAAe;IAC9B;;;OAGG;IACH,KAAK,CAAC,CAAC,OAAO,EAAE,kBAAkB,GAAG,IAAI,CAAC;IAE1C;;;;OAIG;IACH,YAAY,CAAC,IAAI,IAAI,CAAC;IAEtB;;;;OAIG;IACH,KAAK,CAAC,CAAC,OAAO,EAAE,kBAAkB,GAAG,IAAI,CAAC;IAE1C;;;OAGG;IACH,MAAM,CAAC,CAAC,OAAO,EAAE,mBAAmB,GAAG,IAAI,CAAC;IAE5C;;;;OAIG;IACH,QAAQ,CAAC,CAAC,OAAO,EAAE,qBAAqB,GAAG,IAAI,CAAC;IAEhD;;;;OAIG;IACH,QAAQ,CAAC,CAAC,OAAO,EAAE,qBAAqB,GAAG,IAAI,CAAC;IAEhD;;;;OAIG;IACH,OAAO,CAAC,CAAC,OAAO,EAAE,oBAAoB,GAAG,IAAI,CAAC;IAE9C;;;;OAIG;IACH,OAAO,CAAC,CAAC,OAAO,EAAE,oBAAoB,GAAG,IAAI,CAAC;CAC/C"} \ No newline at end of file diff --git a/lib/core/session/session-delegate.js b/lib/core/session/session-delegate.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/core/session/session-delegate.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/core/session/session.d.ts b/lib/core/session/session.d.ts deleted file mode 100644 index 61d23e7e6..000000000 --- a/lib/core/session/session.d.ts +++ /dev/null @@ -1,127 +0,0 @@ -import { Body, OutgoingByeRequest, OutgoingInfoRequest, OutgoingInviteRequest, OutgoingInviteRequestDelegate, OutgoingNotifyRequest, OutgoingPrackRequest, OutgoingReferRequest, OutgoingRequestDelegate, RequestOptions, URI } from "../messages"; -import { SessionDelegate } from "./session-delegate"; -/** - * Session. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-13 - * @public - */ -export interface Session { - /** Session delegate. */ - delegate: SessionDelegate | undefined; - /** The session id. Equal to callId + localTag + remoteTag. */ - readonly id: string; - /** Call Id. */ - readonly callId: string; - /** Local Tag. */ - readonly localTag: string; - /** Local URI. */ - readonly localURI: URI; - /** Remote Tag. */ - readonly remoteTag: string; - /** Remote Target. */ - readonly remoteTarget: URI; - /** Remote URI. */ - readonly remoteURI: URI; - /** Session state. */ - readonly sessionState: SessionState; - /** Current state of the offer/answer exchange. */ - readonly signalingState: SignalingState; - /** The current answer if signalingState is stable. Otherwise undefined. */ - readonly answer: Body | undefined; - /** The current offer if signalingState is not initial or closed. Otherwise undefined. */ - readonly offer: Body | undefined; - /** - * Destroy session. - */ - dispose(): void; - /** - * Send a BYE request. - * Terminating a session. - * https://tools.ietf.org/html/rfc3261#section-15 - * @param delegate - Request delegate. - * @param options - Options bucket. - */ - bye(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingByeRequest; - /** - * Send an INFO request. - * Exchange information during a session. - * https://tools.ietf.org/html/rfc6086#section-4.2.1 - * @param delegate - Request delegate. - * @param options - Options bucket. - */ - info(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingInfoRequest; - /** - * Send re-INVITE request. - * Modifying a session. - * https://tools.ietf.org/html/rfc3261#section-14.1 - * @param delegate - Request delegate. - * @param options - Options bucket. - */ - invite(delegate?: OutgoingInviteRequestDelegate, options?: RequestOptions): OutgoingInviteRequest; - /** - * Send NOTIFY request. - * Inform referrer of transfer progress. - * The use of this is limited to the implicit creation of subscription by REFER (historical). - * Otherwise, notifiers MUST NOT create subscriptions except upon receipt of a SUBSCRIBE request. - * https://tools.ietf.org/html/rfc3515#section-3.7 - * @param delegate - Request delegate. - * @param options - Options bucket. - */ - notify(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingNotifyRequest; - /** - * Send PRACK request. - * Acknowledge a reliable provisional response. - * https://tools.ietf.org/html/rfc3262#section-4 - * @param delegate - Request delegate. - * @param options - Options bucket. - */ - prack(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingPrackRequest; - /** - * Send REFER request (in dialog). - * Transfer a session. - * https://tools.ietf.org/html/rfc3515#section-2.4.1 - * @param delegate - Request delegate. - * @param options - Options bucket. - */ - refer(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingReferRequest; -} -/** - * Session state. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-13 - * @public - */ -export declare enum SessionState { - Initial = "Initial", - Early = "Early", - AckWait = "AckWait", - Confirmed = "Confirmed", - Terminated = "Terminated" -} -/** - * Offer/Answer state. - * @remarks - * ```txt - * Offer Answer RFC Ini Est Early - * ------------------------------------------------------------------- - * 1. INVITE Req. 2xx INVITE Resp. RFC 3261 Y Y N - * 2. 2xx INVITE Resp. ACK Req. RFC 3261 Y Y N - * 3. INVITE Req. 1xx-rel INVITE Resp. RFC 3262 Y Y N - * 4. 1xx-rel INVITE Resp. PRACK Req. RFC 3262 Y Y N - * 5. PRACK Req. 200 PRACK Resp. RFC 3262 N Y Y - * 6. UPDATE Req. 2xx UPDATE Resp. RFC 3311 N Y Y - * - * Table 1: Summary of SIP Usage of the Offer/Answer Model - * ``` - * https://tools.ietf.org/html/rfc6337#section-2.2 - * @public - */ -export declare enum SignalingState { - Initial = "Initial", - HaveLocalOffer = "HaveLocalOffer", - HaveRemoteOffer = "HaveRemoteOffer", - Stable = "Stable", - Closed = "Closed" -} -//# sourceMappingURL=session.d.ts.map \ No newline at end of file diff --git a/lib/core/session/session.d.ts.map b/lib/core/session/session.d.ts.map deleted file mode 100644 index fc1c74f75..000000000 --- a/lib/core/session/session.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../../../src/core/session/session.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,IAAI,EACJ,kBAAkB,EAClB,mBAAmB,EACnB,qBAAqB,EACrB,6BAA6B,EAC7B,qBAAqB,EACrB,oBAAoB,EACpB,oBAAoB,EACpB,uBAAuB,EACvB,cAAc,EACd,GAAG,EACJ,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAErD;;;;;GAKG;AACH,MAAM,WAAW,OAAO;IACtB,wBAAwB;IACxB,QAAQ,EAAE,eAAe,GAAG,SAAS,CAAC;IACtC,8DAA8D;IAC9D,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,eAAe;IACf,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,iBAAiB;IACjB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,iBAAiB;IACjB,QAAQ,CAAC,QAAQ,EAAE,GAAG,CAAC;IACvB,kBAAkB;IAClB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,qBAAqB;IACrB,QAAQ,CAAC,YAAY,EAAE,GAAG,CAAC;IAC3B,kBAAkB;IAClB,QAAQ,CAAC,SAAS,EAAE,GAAG,CAAC;IACxB,qBAAqB;IACrB,QAAQ,CAAC,YAAY,EAAE,YAAY,CAAC;IACpC,kDAAkD;IAClD,QAAQ,CAAC,cAAc,EAAE,cAAc,CAAC;IACxC,2EAA2E;IAC3E,QAAQ,CAAC,MAAM,EAAE,IAAI,GAAG,SAAS,CAAC;IAClC,yFAAyF;IACzF,QAAQ,CAAC,KAAK,EAAE,IAAI,GAAG,SAAS,CAAC;IAEjC;;OAEG;IACH,OAAO,IAAI,IAAI,CAAC;IAEhB;;;;;;OAMG;IACH,GAAG,CAAC,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,kBAAkB,CAAC;IAEtF;;;;;;OAMG;IACH,IAAI,CAAC,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,mBAAmB,CAAC;IAExF;;;;;;OAMG;IACH,MAAM,CAAC,QAAQ,CAAC,EAAE,6BAA6B,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,qBAAqB,CAAC;IAElG;;;;;;;;OAQG;IACH,MAAM,CAAC,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,qBAAqB,CAAC;IAE5F;;;;;;OAMG;IACH,KAAK,CAAC,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,oBAAoB,CAAC;IAE1F;;;;;;OAMG;IACH,KAAK,CAAC,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,oBAAoB,CAAC;CAC3F;AAED;;;;;GAKG;AACH,oBAAY,YAAY;IACtB,OAAO,YAAY;IACnB,KAAK,UAAU;IACf,OAAO,YAAY;IACnB,SAAS,cAAc;IACvB,UAAU,eAAe;CAC1B;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,oBAAY,cAAc;IACxB,OAAO,YAAY;IACnB,cAAc,mBAAmB;IACjC,eAAe,oBAAoB;IACnC,MAAM,WAAW;IACjB,MAAM,WAAW;CAClB"} \ No newline at end of file diff --git a/lib/core/session/session.js b/lib/core/session/session.js deleted file mode 100644 index cd729f13e..000000000 --- a/lib/core/session/session.js +++ /dev/null @@ -1,42 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * Session state. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-13 - * @public - */ -var SessionState; -(function (SessionState) { - SessionState["Initial"] = "Initial"; - SessionState["Early"] = "Early"; - SessionState["AckWait"] = "AckWait"; - SessionState["Confirmed"] = "Confirmed"; - SessionState["Terminated"] = "Terminated"; -})(SessionState = exports.SessionState || (exports.SessionState = {})); -/** - * Offer/Answer state. - * @remarks - * ```txt - * Offer Answer RFC Ini Est Early - * ------------------------------------------------------------------- - * 1. INVITE Req. 2xx INVITE Resp. RFC 3261 Y Y N - * 2. 2xx INVITE Resp. ACK Req. RFC 3261 Y Y N - * 3. INVITE Req. 1xx-rel INVITE Resp. RFC 3262 Y Y N - * 4. 1xx-rel INVITE Resp. PRACK Req. RFC 3262 Y Y N - * 5. PRACK Req. 200 PRACK Resp. RFC 3262 N Y Y - * 6. UPDATE Req. 2xx UPDATE Resp. RFC 3311 N Y Y - * - * Table 1: Summary of SIP Usage of the Offer/Answer Model - * ``` - * https://tools.ietf.org/html/rfc6337#section-2.2 - * @public - */ -var SignalingState; -(function (SignalingState) { - SignalingState["Initial"] = "Initial"; - SignalingState["HaveLocalOffer"] = "HaveLocalOffer"; - SignalingState["HaveRemoteOffer"] = "HaveRemoteOffer"; - SignalingState["Stable"] = "Stable"; - SignalingState["Closed"] = "Closed"; -})(SignalingState = exports.SignalingState || (exports.SignalingState = {})); diff --git a/lib/core/subscription/index.d.ts b/lib/core/subscription/index.d.ts deleted file mode 100644 index 1c22343d6..000000000 --- a/lib/core/subscription/index.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -export * from "./subscription"; -export * from "./subscription-delegate"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/core/subscription/index.d.ts.map b/lib/core/subscription/index.d.ts.map deleted file mode 100644 index 8ddb57378..000000000 --- a/lib/core/subscription/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/subscription/index.ts"],"names":[],"mappings":"AAAA,cAAc,gBAAgB,CAAC;AAC/B,cAAc,yBAAyB,CAAC"} \ No newline at end of file diff --git a/lib/core/subscription/index.js b/lib/core/subscription/index.js deleted file mode 100644 index b436e81e4..000000000 --- a/lib/core/subscription/index.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -tslib_1.__exportStar(require("./subscription"), exports); diff --git a/lib/core/subscription/subscription-delegate.d.ts b/lib/core/subscription/subscription-delegate.d.ts deleted file mode 100644 index 33bd060f2..000000000 --- a/lib/core/subscription/subscription-delegate.d.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { IncomingNotifyRequest, OutgoingSubscribeRequest } from "../messages"; -/** - * Subscription delegate. - * @public - */ -export interface SubscriptionDelegate { - /** - * Receive NOTIFY request. This includes in dialog NOTIFY requests only. - * Thus the first NOTIFY (the subscription creating NOTIFY) will not be provided. - * https://tools.ietf.org/html/rfc6665#section-4.1.3 - * @param request - Incoming NOTIFY request. - */ - onNotify?(request: IncomingNotifyRequest): void; - /** - * Sent a SUBSCRIBE request. This includes "auto refresh" in dialog SUBSCRIBE requests only. - * Thus SUBSCRIBE requests triggered by calls to `refresh()` or `subscribe()` will not be provided. - * Thus the first SUBSCRIBE (the subscription creating SUBSCRIBE) will not be provided. - * @param request - Outgoing SUBSCRIBE request. - */ - onRefresh?(request: OutgoingSubscribeRequest): void; - /** - * Subscription termination. This includes non-NOTIFY termination causes only. - * Thus this will not be called if a NOTIFY is the cause of termination. - * https://tools.ietf.org/html/rfc6665#section-4.4.1 - */ - onTerminated?(): void; -} -//# sourceMappingURL=subscription-delegate.d.ts.map \ No newline at end of file diff --git a/lib/core/subscription/subscription-delegate.d.ts.map b/lib/core/subscription/subscription-delegate.d.ts.map deleted file mode 100644 index 7dae89514..000000000 --- a/lib/core/subscription/subscription-delegate.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"subscription-delegate.d.ts","sourceRoot":"","sources":["../../../src/core/subscription/subscription-delegate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AAE9E;;;GAGG;AACH,MAAM,WAAW,oBAAoB;IACnC;;;;;OAKG;IACH,QAAQ,CAAC,CAAC,OAAO,EAAE,qBAAqB,GAAG,IAAI,CAAC;IAEhD;;;;;OAKG;IACH,SAAS,CAAC,CAAC,OAAO,EAAE,wBAAwB,GAAG,IAAI,CAAC;IAEpD;;;;OAIG;IACH,YAAY,CAAC,IAAI,IAAI,CAAC;CACvB"} \ No newline at end of file diff --git a/lib/core/subscription/subscription-delegate.js b/lib/core/subscription/subscription-delegate.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/core/subscription/subscription-delegate.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/core/subscription/subscription.d.ts b/lib/core/subscription/subscription.d.ts deleted file mode 100644 index e05f64883..000000000 --- a/lib/core/subscription/subscription.d.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { OutgoingSubscribeRequest, OutgoingSubscribeRequestDelegate, RequestOptions } from "../messages"; -import { SubscriptionDelegate } from "./subscription-delegate"; -/** - * Subscription. - * @remarks - * https://tools.ietf.org/html/rfc6665 - * @public - */ -export interface Subscription { - /** Subscription delegate. */ - delegate: SubscriptionDelegate | undefined; - /** The subscription id. */ - readonly id: string; - /** Subscription expires. Number of seconds until the subscription expires. */ - readonly subscriptionExpires: number; - /** Subscription state. */ - readonly subscriptionState: SubscriptionState; - /** If true, refresh subscription prior to expiration. Default is false. */ - autoRefresh: boolean; - /** - * Destroy subscription. - */ - dispose(): void; - /** - * Send re-SUBSCRIBE request. - * Refreshing a subscription and unsubscribing. - * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - * @param delegate - Request delegate. - * @param options - Options bucket - */ - subscribe(delegate?: OutgoingSubscribeRequestDelegate, options?: RequestOptions): OutgoingSubscribeRequest; - /** - * 4.1.2.2. Refreshing of Subscriptions - * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - */ - refresh(): OutgoingSubscribeRequest; - /** - * 4.1.2.3. Unsubscribing - * https://tools.ietf.org/html/rfc6665#section-4.1.2.3 - */ - unsubscribe(): OutgoingSubscribeRequest; -} -/** - * Subscription state. - * @remarks - * https://tools.ietf.org/html/rfc6665#section-4.1.2 - * @public - */ -export declare enum SubscriptionState { - Initial = "Initial", - NotifyWait = "NotifyWait", - Pending = "Pending", - Active = "Active", - Terminated = "Terminated" -} -//# sourceMappingURL=subscription.d.ts.map \ No newline at end of file diff --git a/lib/core/subscription/subscription.d.ts.map b/lib/core/subscription/subscription.d.ts.map deleted file mode 100644 index f37e62d05..000000000 --- a/lib/core/subscription/subscription.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"subscription.d.ts","sourceRoot":"","sources":["../../../src/core/subscription/subscription.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,wBAAwB,EACxB,gCAAgC,EAChC,cAAc,EACf,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAE/D;;;;;GAKG;AACH,MAAM,WAAW,YAAY;IAC3B,6BAA6B;IAC7B,QAAQ,EAAE,oBAAoB,GAAG,SAAS,CAAC;IAC3C,2BAA2B;IAC3B,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,8EAA8E;IAC9E,QAAQ,CAAC,mBAAmB,EAAE,MAAM,CAAC;IACrC,0BAA0B;IAC1B,QAAQ,CAAC,iBAAiB,EAAE,iBAAiB,CAAC;IAC9C,2EAA2E;IAC3E,WAAW,EAAE,OAAO,CAAC;IAErB;;OAEG;IACH,OAAO,IAAI,IAAI,CAAC;IAEhB;;;;;;OAMG;IACH,SAAS,CAAC,QAAQ,CAAC,EAAE,gCAAgC,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,wBAAwB,CAAC;IAE3G;;;OAGG;IACH,OAAO,IAAI,wBAAwB,CAAC;IAEpC;;;OAGG;IACH,WAAW,IAAI,wBAAwB,CAAC;CACzC;AAED;;;;;GAKG;AACH,oBAAY,iBAAiB;IAC3B,OAAO,YAAY;IACnB,UAAU,eAAe;IACzB,OAAO,YAAY;IACnB,MAAM,WAAW;IACjB,UAAU,eAAe;CAC1B"} \ No newline at end of file diff --git a/lib/core/subscription/subscription.js b/lib/core/subscription/subscription.js deleted file mode 100644 index 7dee5bd29..000000000 --- a/lib/core/subscription/subscription.js +++ /dev/null @@ -1,16 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * Subscription state. - * @remarks - * https://tools.ietf.org/html/rfc6665#section-4.1.2 - * @public - */ -var SubscriptionState; -(function (SubscriptionState) { - SubscriptionState["Initial"] = "Initial"; - SubscriptionState["NotifyWait"] = "NotifyWait"; - SubscriptionState["Pending"] = "Pending"; - SubscriptionState["Active"] = "Active"; - SubscriptionState["Terminated"] = "Terminated"; -})(SubscriptionState = exports.SubscriptionState || (exports.SubscriptionState = {})); diff --git a/lib/core/timers.d.ts b/lib/core/timers.d.ts deleted file mode 100644 index 70dda6301..000000000 --- a/lib/core/timers.d.ts +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Timers. - * @public - */ -export declare const Timers: { - T1: number; - T2: number; - T4: number; - TIMER_B: number; - TIMER_D: number; - TIMER_F: number; - TIMER_H: number; - TIMER_I: number; - TIMER_J: number; - TIMER_K: number; - TIMER_L: number; - TIMER_M: number; - TIMER_N: number; - PROVISIONAL_RESPONSE_INTERVAL: number; -}; -//# sourceMappingURL=timers.d.ts.map \ No newline at end of file diff --git a/lib/core/timers.d.ts.map b/lib/core/timers.d.ts.map deleted file mode 100644 index a1d612df2..000000000 --- a/lib/core/timers.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"timers.d.ts","sourceRoot":"","sources":["../../src/core/timers.ts"],"names":[],"mappings":"AAIA;;;GAGG;AACH,eAAO,MAAM,MAAM;;;;;;;;;;;;;;;CAelB,CAAC"} \ No newline at end of file diff --git a/lib/core/timers.js b/lib/core/timers.js deleted file mode 100644 index 4d795c3fc..000000000 --- a/lib/core/timers.js +++ /dev/null @@ -1,25 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var T1 = 500; -var T2 = 4000; -var T4 = 5000; -/** - * Timers. - * @public - */ -exports.Timers = { - T1: T1, - T2: T2, - T4: T4, - TIMER_B: 64 * T1, - TIMER_D: 0 * T1, - TIMER_F: 64 * T1, - TIMER_H: 64 * T1, - TIMER_I: 0 * T4, - TIMER_J: 0 * T1, - TIMER_K: 0 * T4, - TIMER_L: 64 * T1, - TIMER_M: 64 * T1, - TIMER_N: 64 * T1, - PROVISIONAL_RESPONSE_INTERVAL: 60000 // See RFC 3261 Section 13.3.1.1 -}; diff --git a/lib/core/transactions/client-transaction.d.ts b/lib/core/transactions/client-transaction.d.ts deleted file mode 100644 index d97866df9..000000000 --- a/lib/core/transactions/client-transaction.d.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { IncomingResponseMessage, OutgoingRequestMessage } from "../messages"; -import { Transport } from "../transport"; -import { Transaction } from "./transaction"; -import { TransactionState } from "./transaction-state"; -import { ClientTransactionUser } from "./transaction-user"; -/** - * Client Transaction. - * @remarks - * The client transaction provides its functionality through the - * maintenance of a state machine. - * - * The TU communicates with the client transaction through a simple - * interface. When the TU wishes to initiate a new transaction, it - * creates a client transaction and passes it the SIP request to send - * and an IP address, port, and transport to which to send it. The - * client transaction begins execution of its state machine. Valid - * responses are passed up to the TU from the client transaction. - * https://tools.ietf.org/html/rfc3261#section-17.1 - * @public - */ -export declare abstract class ClientTransaction extends Transaction { - private _request; - protected user: ClientTransactionUser; - private static makeId; - protected constructor(_request: OutgoingRequestMessage, transport: Transport, user: ClientTransactionUser, state: TransactionState, loggerCategory: string); - /** The outgoing request the transaction handling. */ - readonly request: OutgoingRequestMessage; - /** - * Receive incoming responses from the transport which match this transaction. - * Responses will be delivered to the transaction user as necessary. - * @param response - The incoming response. - */ - abstract receiveResponse(response: IncomingResponseMessage): void; - /** - * A 408 to non-INVITE will always arrive too late to be useful ([3]), - * The client already has full knowledge of the timeout. The only - * information this message would convey is whether or not the server - * believed the transaction timed out. However, with the current design - * of the NIT, a client cannot do anything with this knowledge. Thus, - * the 408 is simply wasting network resources and contributes to the - * response bombardment illustrated in [3]. - * https://tools.ietf.org/html/rfc4320#section-4.1 - */ - protected onRequestTimeout(): void; -} -//# sourceMappingURL=client-transaction.d.ts.map \ No newline at end of file diff --git a/lib/core/transactions/client-transaction.d.ts.map b/lib/core/transactions/client-transaction.d.ts.map deleted file mode 100644 index 78bc7d8b6..000000000 --- a/lib/core/transactions/client-transaction.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"client-transaction.d.ts","sourceRoot":"","sources":["../../../src/core/transactions/client-transaction.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAC9E,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAE3D;;;;;;;;;;;;;;GAcG;AACH,8BAAsB,iBAAkB,SAAQ,WAAW;IAavD,OAAO,CAAC,QAAQ;IAEhB,SAAS,CAAC,IAAI,EAAE,qBAAqB;IAdvC,OAAO,CAAC,MAAM,CAAC,MAAM;IAWrB,SAAS,aACC,QAAQ,EAAE,sBAAsB,EACxC,SAAS,EAAE,SAAS,EACV,IAAI,EAAE,qBAAqB,EACrC,KAAK,EAAE,gBAAgB,EACvB,cAAc,EAAE,MAAM;IAoBxB,qDAAqD;aACjD,OAAO,EAAI,sBAAsB;IAIrC;;;;OAIG;aACa,eAAe,CAAC,QAAQ,EAAE,uBAAuB,GAAG,IAAI;IAExE;;;;;;;;;OASG;IACH,SAAS,CAAC,gBAAgB,IAAI,IAAI;CAKnC"} \ No newline at end of file diff --git a/lib/core/transactions/client-transaction.js b/lib/core/transactions/client-transaction.js deleted file mode 100644 index 546840a38..000000000 --- a/lib/core/transactions/client-transaction.js +++ /dev/null @@ -1,73 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var transaction_1 = require("./transaction"); -/** - * Client Transaction. - * @remarks - * The client transaction provides its functionality through the - * maintenance of a state machine. - * - * The TU communicates with the client transaction through a simple - * interface. When the TU wishes to initiate a new transaction, it - * creates a client transaction and passes it the SIP request to send - * and an IP address, port, and transport to which to send it. The - * client transaction begins execution of its state machine. Valid - * responses are passed up to the TU from the client transaction. - * https://tools.ietf.org/html/rfc3261#section-17.1 - * @public - */ -var ClientTransaction = /** @class */ (function (_super) { - tslib_1.__extends(ClientTransaction, _super); - function ClientTransaction(_request, transport, user, state, loggerCategory) { - var _this = _super.call(this, transport, user, ClientTransaction.makeId(_request), state, loggerCategory) || this; - _this._request = _request; - _this.user = user; - // The Via header field indicates the transport used for the transaction - // and identifies the location where the response is to be sent. A Via - // header field value is added only after the transport that will be - // used to reach the next hop has been selected (which may involve the - // usage of the procedures in [4]). - // https://tools.ietf.org/html/rfc3261#section-8.1.1.7 - // FIXME: Transport's server property is not typed (as of writing this). - var scheme = transport.server && transport.server.scheme ? transport.server.scheme : undefined; - _request.setViaHeader(_this.id, scheme); - return _this; - } - ClientTransaction.makeId = function (request) { - if (request.method === "CANCEL") { - if (!request.branch) { - throw new Error("Outgoing CANCEL request without a branch."); - } - return request.branch; - } - else { - return "z9hG4bK" + Math.floor(Math.random() * 10000000); - } - }; - Object.defineProperty(ClientTransaction.prototype, "request", { - /** The outgoing request the transaction handling. */ - get: function () { - return this._request; - }, - enumerable: true, - configurable: true - }); - /** - * A 408 to non-INVITE will always arrive too late to be useful ([3]), - * The client already has full knowledge of the timeout. The only - * information this message would convey is whether or not the server - * believed the transaction timed out. However, with the current design - * of the NIT, a client cannot do anything with this knowledge. Thus, - * the 408 is simply wasting network resources and contributes to the - * response bombardment illustrated in [3]. - * https://tools.ietf.org/html/rfc4320#section-4.1 - */ - ClientTransaction.prototype.onRequestTimeout = function () { - if (this.user.onRequestTimeout) { - this.user.onRequestTimeout(); - } - }; - return ClientTransaction; -}(transaction_1.Transaction)); -exports.ClientTransaction = ClientTransaction; diff --git a/lib/core/transactions/index.d.ts b/lib/core/transactions/index.d.ts deleted file mode 100644 index 96371a98d..000000000 --- a/lib/core/transactions/index.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -export * from "./client-transaction"; -export * from "./invite-client-transaction"; -export * from "./invite-server-transaction"; -export * from "./non-invite-client-transaction"; -export * from "./non-invite-server-transaction"; -export * from "./invite-client-transaction"; -export * from "./server-transaction"; -export * from "./transaction-state"; -export * from "./transaction-user"; -export * from "./transaction"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/core/transactions/index.d.ts.map b/lib/core/transactions/index.d.ts.map deleted file mode 100644 index 5df90caf9..000000000 --- a/lib/core/transactions/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/transactions/index.ts"],"names":[],"mappings":"AAAA,cAAc,sBAAsB,CAAC;AACrC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,6BAA6B,CAAC;AAC5C,cAAc,iCAAiC,CAAC;AAChD,cAAc,iCAAiC,CAAC;AAChD,cAAc,6BAA6B,CAAC;AAC5C,cAAc,sBAAsB,CAAC;AACrC,cAAc,qBAAqB,CAAC;AACpC,cAAc,oBAAoB,CAAC;AACnC,cAAc,eAAe,CAAC"} \ No newline at end of file diff --git a/lib/core/transactions/index.js b/lib/core/transactions/index.js deleted file mode 100644 index db74c52eb..000000000 --- a/lib/core/transactions/index.js +++ /dev/null @@ -1,12 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -tslib_1.__exportStar(require("./client-transaction"), exports); -tslib_1.__exportStar(require("./invite-client-transaction"), exports); -tslib_1.__exportStar(require("./invite-server-transaction"), exports); -tslib_1.__exportStar(require("./non-invite-client-transaction"), exports); -tslib_1.__exportStar(require("./non-invite-server-transaction"), exports); -tslib_1.__exportStar(require("./invite-client-transaction"), exports); -tslib_1.__exportStar(require("./server-transaction"), exports); -tslib_1.__exportStar(require("./transaction-state"), exports); -tslib_1.__exportStar(require("./transaction"), exports); diff --git a/lib/core/transactions/invite-client-transaction.d.ts b/lib/core/transactions/invite-client-transaction.d.ts deleted file mode 100644 index c71af7147..000000000 --- a/lib/core/transactions/invite-client-transaction.d.ts +++ /dev/null @@ -1,117 +0,0 @@ -import { TransportError } from "../exceptions"; -import { IncomingResponseMessage, OutgoingRequestMessage } from "../messages"; -import { Transport } from "../transport"; -import { ClientTransaction } from "./client-transaction"; -import { ClientTransactionUser } from "./transaction-user"; -/** - * INVITE Client Transaction. - * @remarks - * The INVITE transaction consists of a three-way handshake. The client - * transaction sends an INVITE, the server transaction sends responses, - * and the client transaction sends an ACK. - * https://tools.ietf.org/html/rfc3261#section-17.1.1 - * @public - */ -export declare class InviteClientTransaction extends ClientTransaction { - private B; - private D; - private M; - /** - * Map of 2xx to-tag to ACK. - * If value is not undefined, value is the ACK which was sent. - * If key exists but value is undefined, a 2xx was received but the ACK not yet sent. - * Otherwise, a 2xx was not (yet) received for this transaction. - */ - private ackRetransmissionCache; - /** - * Constructor. - * Upon construction, the outgoing request's Via header is updated by calling `setViaHeader`. - * Then `toString` is called on the outgoing request and the message is sent via the transport. - * After construction the transaction will be in the "calling" state and the transaction id - * will equal the branch parameter set in the Via header of the outgoing request. - * https://tools.ietf.org/html/rfc3261#section-17.1.1 - * @param request - The outgoing INVITE request. - * @param transport - The transport. - * @param user - The transaction user. - */ - constructor(request: OutgoingRequestMessage, transport: Transport, user: ClientTransactionUser); - /** - * Destructor. - */ - dispose(): void; - /** Transaction kind. Deprecated. */ - readonly kind: string; - /** - * ACK a 2xx final response. - * - * The transaction includes the ACK only if the final response was not a 2xx response (the - * transaction will generate and send the ACK to the transport automagically). If the - * final response was a 2xx, the ACK is not considered part of the transaction (the - * transaction user needs to generate and send the ACK). - * - * This library is not strictly RFC compliant with regard to ACK handling for 2xx final - * responses. Specifically, retransmissions of ACKs to a 2xx final responses is handled - * by the transaction layer (instead of the UAC core). The "standard" approach is for - * the UAC core to receive all 2xx responses and manage sending ACK retransmissions to - * the transport directly. Herein the transaction layer manages sending ACKs to 2xx responses - * and any retransmissions of those ACKs as needed. - * - * @param ack - The outgoing ACK request. - */ - ackResponse(ack: OutgoingRequestMessage): void; - /** - * Handler for incoming responses from the transport which match this transaction. - * @param response - The incoming response. - */ - receiveResponse(response: IncomingResponseMessage): void; - /** - * The client transaction SHOULD inform the TU that a transport failure - * has occurred, and the client transaction SHOULD transition directly - * to the "Terminated" state. The TU will handle the failover - * mechanisms described in [4]. - * https://tools.ietf.org/html/rfc3261#section-17.1.4 - * @param error - The error. - */ - protected onTransportError(error: TransportError): void; - /** For logging. */ - protected typeToString(): string; - private ack; - /** - * Execute a state transition. - * @param newState - New state. - */ - private stateTransition; - /** - * When timer A fires, the client transaction MUST retransmit the - * request by passing it to the transport layer, and MUST reset the - * timer with a value of 2*T1. - * When timer A fires 2*T1 seconds later, the request MUST be - * retransmitted again (assuming the client transaction is still in this - * state). This process MUST continue so that the request is - * retransmitted with intervals that double after each transmission. - * These retransmissions SHOULD only be done while the client - * transaction is in the "Calling" state. - * https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - */ - private timer_A; - /** - * If the client transaction is still in the "Calling" state when timer - * B fires, the client transaction SHOULD inform the TU that a timeout - * has occurred. The client transaction MUST NOT generate an ACK. - * https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - */ - private timer_B; - /** - * If Timer D fires while the client transaction is in the "Completed" state, - * the client transaction MUST move to the "Terminated" state. - * https://tools.ietf.org/html/rfc6026#section-8.4 - */ - private timer_D; - /** - * If Timer M fires while the client transaction is in the "Accepted" - * state, the client transaction MUST move to the "Terminated" state. - * https://tools.ietf.org/html/rfc6026#section-8.4 - */ - private timer_M; -} -//# sourceMappingURL=invite-client-transaction.d.ts.map \ No newline at end of file diff --git a/lib/core/transactions/invite-client-transaction.d.ts.map b/lib/core/transactions/invite-client-transaction.d.ts.map deleted file mode 100644 index 445a1fe07..000000000 --- a/lib/core/transactions/invite-client-transaction.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"invite-client-transaction.d.ts","sourceRoot":"","sources":["../../../src/core/transactions/invite-client-transaction.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAE/C,OAAO,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAE9E,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAEzD,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAE3D;;;;;;;;GAQG;AACH,qBAAa,uBAAwB,SAAQ,iBAAiB;IAC5D,OAAO,CAAC,CAAC,CAAkB;IAC3B,OAAO,CAAC,CAAC,CAAkB;IAC3B,OAAO,CAAC,CAAC,CAAkB;IAE3B;;;;;OAKG;IACH,OAAO,CAAC,sBAAsB,CAA8D;IAE5F;;;;;;;;;;OAUG;gBACS,OAAO,EAAE,sBAAsB,EAAE,SAAS,EAAE,SAAS,EAAE,IAAI,EAAE,qBAAqB;IA0B9F;;OAEG;IACI,OAAO,IAAI,IAAI;IAgBtB,oCAAoC;aAChC,IAAI,EAAI,MAAM;IAIlB;;;;;;;;;;;;;;;;OAgBG;IACI,WAAW,CAAC,GAAG,EAAE,sBAAsB,GAAG,IAAI;IAerD;;;OAGG;IACI,eAAe,CAAC,QAAQ,EAAE,uBAAuB,GAAG,IAAI;IA8K/D;;;;;;;OAOG;IACH,SAAS,CAAC,gBAAgB,CAAC,KAAK,EAAE,cAAc,GAAG,IAAI;IAOvD,mBAAmB;IACnB,SAAS,CAAC,YAAY,IAAI,MAAM;IAIhC,OAAO,CAAC,GAAG;IAwDX;;;OAGG;IACH,OAAO,CAAC,eAAe;IA+EvB;;;;;;;;;;;OAWG;IACH,OAAO,CAAC,OAAO;IAIf;;;;;OAKG;IACH,OAAO,CAAC,OAAO;IAQf;;;;OAIG;IACH,OAAO,CAAC,OAAO;IAOf;;;;OAIG;IACH,OAAO,CAAC,OAAO;CAMhB"} \ No newline at end of file diff --git a/lib/core/transactions/invite-client-transaction.js b/lib/core/transactions/invite-client-transaction.js deleted file mode 100644 index 85a316380..000000000 --- a/lib/core/transactions/invite-client-transaction.js +++ /dev/null @@ -1,486 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var timers_1 = require("../timers"); -var client_transaction_1 = require("./client-transaction"); -var transaction_state_1 = require("./transaction-state"); -/** - * INVITE Client Transaction. - * @remarks - * The INVITE transaction consists of a three-way handshake. The client - * transaction sends an INVITE, the server transaction sends responses, - * and the client transaction sends an ACK. - * https://tools.ietf.org/html/rfc3261#section-17.1.1 - * @public - */ -var InviteClientTransaction = /** @class */ (function (_super) { - tslib_1.__extends(InviteClientTransaction, _super); - /** - * Constructor. - * Upon construction, the outgoing request's Via header is updated by calling `setViaHeader`. - * Then `toString` is called on the outgoing request and the message is sent via the transport. - * After construction the transaction will be in the "calling" state and the transaction id - * will equal the branch parameter set in the Via header of the outgoing request. - * https://tools.ietf.org/html/rfc3261#section-17.1.1 - * @param request - The outgoing INVITE request. - * @param transport - The transport. - * @param user - The transaction user. - */ - function InviteClientTransaction(request, transport, user) { - var _this = _super.call(this, request, transport, user, transaction_state_1.TransactionState.Calling, "sip.transaction.ict") || this; - /** - * Map of 2xx to-tag to ACK. - * If value is not undefined, value is the ACK which was sent. - * If key exists but value is undefined, a 2xx was received but the ACK not yet sent. - * Otherwise, a 2xx was not (yet) received for this transaction. - */ - _this.ackRetransmissionCache = new Map(); - // FIXME: Timer A for unreliable transport not implemented - // - // If an unreliable transport is being used, the client transaction - // MUST start timer A with a value of T1. If a reliable transport is being used, - // the client transaction SHOULD NOT start timer A (Timer A controls request retransmissions). - // For any transport, the client transaction MUST start timer B with a value - // of 64*T1 seconds (Timer B controls transaction timeouts). - // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - // - // While not spelled out in the RFC, Timer B is the maximum amount of time that a sender - // will wait for an INVITE message to be acknowledged (a SIP response message is received). - // So Timer B should be cleared when the transaction state proceeds from "Calling". - _this.B = setTimeout(function () { return _this.timer_B(); }, timers_1.Timers.TIMER_B); - _this.send(request.toString()).catch(function (error) { - _this.logTransportError(error, "Failed to send initial outgoing request."); - }); - return _this; - } - /** - * Destructor. - */ - InviteClientTransaction.prototype.dispose = function () { - if (this.B) { - clearTimeout(this.B); - this.B = undefined; - } - if (this.D) { - clearTimeout(this.D); - this.D = undefined; - } - if (this.M) { - clearTimeout(this.M); - this.M = undefined; - } - _super.prototype.dispose.call(this); - }; - Object.defineProperty(InviteClientTransaction.prototype, "kind", { - /** Transaction kind. Deprecated. */ - get: function () { - return "ict"; - }, - enumerable: true, - configurable: true - }); - /** - * ACK a 2xx final response. - * - * The transaction includes the ACK only if the final response was not a 2xx response (the - * transaction will generate and send the ACK to the transport automagically). If the - * final response was a 2xx, the ACK is not considered part of the transaction (the - * transaction user needs to generate and send the ACK). - * - * This library is not strictly RFC compliant with regard to ACK handling for 2xx final - * responses. Specifically, retransmissions of ACKs to a 2xx final responses is handled - * by the transaction layer (instead of the UAC core). The "standard" approach is for - * the UAC core to receive all 2xx responses and manage sending ACK retransmissions to - * the transport directly. Herein the transaction layer manages sending ACKs to 2xx responses - * and any retransmissions of those ACKs as needed. - * - * @param ack - The outgoing ACK request. - */ - InviteClientTransaction.prototype.ackResponse = function (ack) { - var _this = this; - var toTag = ack.toTag; - if (!toTag) { - throw new Error("To tag undefined."); - } - var id = "z9hG4bK" + Math.floor(Math.random() * 10000000); - // FIXME: Transport's server property is not typed (as of writing this). - var scheme = this.transport.server && this.transport.server.scheme ? this.transport.server.scheme : undefined; - ack.setViaHeader(id, scheme); - this.ackRetransmissionCache.set(toTag, ack); // Add to ACK retransmission cache - this.send(ack.toString()).catch(function (error) { - _this.logTransportError(error, "Failed to send ACK to 2xx response."); - }); - }; - /** - * Handler for incoming responses from the transport which match this transaction. - * @param response - The incoming response. - */ - InviteClientTransaction.prototype.receiveResponse = function (response) { - var _this = this; - var statusCode = response.statusCode; - if (!statusCode || statusCode < 100 || statusCode > 699) { - throw new Error("Invalid status code " + statusCode); - } - switch (this.state) { - case transaction_state_1.TransactionState.Calling: - // If the client transaction receives a provisional response while in - // the "Calling" state, it transitions to the "Proceeding" state. In the - // "Proceeding" state, the client transaction SHOULD NOT retransmit the - // request any longer. Furthermore, the provisional response MUST be - // passed to the TU. Any further provisional responses MUST be passed - // up to the TU while in the "Proceeding" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - if (statusCode >= 100 && statusCode <= 199) { - this.stateTransition(transaction_state_1.TransactionState.Proceeding); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // When a 2xx response is received while in either the "Calling" or - // "Proceeding" states, the client transaction MUST transition to - // the "Accepted" state... The 2xx response MUST be passed up to the TU. - // The client transaction MUST NOT generate an ACK to the 2xx response -- its - // handling is delegated to the TU. A UAC core will send an ACK to - // the 2xx response using a new transaction. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 200 && statusCode <= 299) { - this.ackRetransmissionCache.set(response.toTag, undefined); // Prime the ACK cache - this.stateTransition(transaction_state_1.TransactionState.Accepted); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // When in either the "Calling" or "Proceeding" states, reception of - // a response with status code from 300-699 MUST cause the client - // transaction to transition to "Completed". The client transaction - // MUST pass the received response up to the TU, and the client - // transaction MUST generate an ACK request, even if the transport is - // reliable (guidelines for constructing the ACK from the response - // are given in Section 17.1.1.3), and then pass the ACK to the - // transport layer for transmission. The ACK MUST be sent to the - // same address, port, and transport to which the original request was sent. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 300 && statusCode <= 699) { - this.stateTransition(transaction_state_1.TransactionState.Completed); - this.ack(response); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - break; - case transaction_state_1.TransactionState.Proceeding: - // In the "Proceeding" state, the client transaction SHOULD NOT retransmit the - // request any longer. Furthermore, the provisional response MUST be - // passed to the TU. Any further provisional responses MUST be passed - // up to the TU while in the "Proceeding" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - if (statusCode >= 100 && statusCode <= 199) { - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // When a 2xx response is received while in either the "Calling" or "Proceeding" states, - // the client transaction MUST transition to the "Accepted" state... - // The 2xx response MUST be passed up to the TU. The client - // transaction MUST NOT generate an ACK to the 2xx response -- its - // handling is delegated to the TU. A UAC core will send an ACK to - // the 2xx response using a new transaction. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 200 && statusCode <= 299) { - this.ackRetransmissionCache.set(response.toTag, undefined); // Prime the ACK cache - this.stateTransition(transaction_state_1.TransactionState.Accepted); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // When in either the "Calling" or "Proceeding" states, reception of - // a response with status code from 300-699 MUST cause the client - // transaction to transition to "Completed". The client transaction - // MUST pass the received response up to the TU, and the client - // transaction MUST generate an ACK request, even if the transport is - // reliable (guidelines for constructing the ACK from the response - // are given in Section 17.1.1.3), and then pass the ACK to the - // transport layer for transmission. The ACK MUST be sent to the - // same address, port, and transport to which the original request was sent. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 300 && statusCode <= 699) { - this.stateTransition(transaction_state_1.TransactionState.Completed); - this.ack(response); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - break; - case transaction_state_1.TransactionState.Accepted: - // The purpose of the "Accepted" state is to allow the client - // transaction to continue to exist to receive, and pass to the TU, - // any retransmissions of the 2xx response and any additional 2xx - // responses from other branches of the INVITE if it forked - // downstream. Timer M reflects the amount of time that the - // transaction user will wait for such messages. - // - // Any 2xx responses that match this client transaction and that are - // received while in the "Accepted" state MUST be passed up to the - // TU. The client transaction MUST NOT generate an ACK to the 2xx - // response. The client transaction takes no further action. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 200 && statusCode <= 299) { - // NOTE: This implementation herein is intentionally not RFC compliant. - // While the first 2xx response for a given branch is passed up to the TU, - // retransmissions of 2xx responses are absorbed and the ACK associated - // with the original response is resent. This approach is taken because - // our current transaction users are not currently in a good position to - // deal with 2xx retransmission. This SHOULD NOT cause any compliance issues - ;) - // - // If we don't have a cache hit, pass the response to the TU. - if (!this.ackRetransmissionCache.has(response.toTag)) { - this.ackRetransmissionCache.set(response.toTag, undefined); // Prime the ACK cache - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // If we have a cache hit, try pulling the ACK from cache and retransmitting it. - var ack = this.ackRetransmissionCache.get(response.toTag); - if (ack) { - this.send(ack.toString()).catch(function (error) { - _this.logTransportError(error, "Failed to send retransmission of ACK to 2xx response."); - }); - return; - } - // If an ACK was not found in cache then we have received a retransmitted 2xx - // response before the TU responded to the original response (we don't have an ACK yet). - // So discard this response under the assumption that the TU will eventually - // get us a ACK for the original response. - return; - } - break; - case transaction_state_1.TransactionState.Completed: - // Any retransmissions of a response with status code 300-699 that - // are received while in the "Completed" state MUST cause the ACK to - // be re-passed to the transport layer for retransmission, but the - // newly received response MUST NOT be passed up to the TU. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 300 && statusCode <= 699) { - this.ack(response); - return; - } - break; - case transaction_state_1.TransactionState.Terminated: - break; - default: - throw new Error("Invalid state " + this.state); - } - // Any response received that does not match an existing client - // transaction state machine is simply dropped. (Implementations are, - // of course, free to log or do other implementation-specific things - // with such responses, but the implementer should be sure to consider - // the impact of large numbers of malicious stray responses.) - // https://tools.ietf.org/html/rfc6026#section-7.2 - var message = "Received unexpected " + statusCode + " response while in state " + this.state + "."; - this.logger.warn(message); - return; - }; - /** - * The client transaction SHOULD inform the TU that a transport failure - * has occurred, and the client transaction SHOULD transition directly - * to the "Terminated" state. The TU will handle the failover - * mechanisms described in [4]. - * https://tools.ietf.org/html/rfc3261#section-17.1.4 - * @param error - The error. - */ - InviteClientTransaction.prototype.onTransportError = function (error) { - if (this.user.onTransportError) { - this.user.onTransportError(error); - } - this.stateTransition(transaction_state_1.TransactionState.Terminated, true); - }; - /** For logging. */ - InviteClientTransaction.prototype.typeToString = function () { - return "INVITE client transaction"; - }; - InviteClientTransaction.prototype.ack = function (response) { - var _this = this; - // The ACK request constructed by the client transaction MUST contain - // values for the Call-ID, From, and Request-URI that are equal to the - // values of those header fields in the request passed to the transport - // by the client transaction (call this the "original request"). The To - // header field in the ACK MUST equal the To header field in the - // response being acknowledged, and therefore will usually differ from - // the To header field in the original request by the addition of the - // tag parameter. The ACK MUST contain a single Via header field, and - // this MUST be equal to the top Via header field of the original - // request. The CSeq header field in the ACK MUST contain the same - // value for the sequence number as was present in the original request, - // but the method parameter MUST be equal to "ACK". - // - // If the INVITE request whose response is being acknowledged had Route - // header fields, those header fields MUST appear in the ACK. This is - // to ensure that the ACK can be routed properly through any downstream - // stateless proxies. - // https://tools.ietf.org/html/rfc3261#section-17.1.1.3 - var ruri = this.request.ruri; - var callId = this.request.callId; - var cseq = this.request.cseq; - var from = this.request.getHeader("from"); - var to = response.getHeader("to"); - var via = this.request.getHeader("via"); - var route = this.request.getHeader("route"); - if (!from) { - throw new Error("From undefined."); - } - if (!to) { - throw new Error("To undefined."); - } - if (!via) { - throw new Error("Via undefined."); - } - var ack = "ACK " + ruri + " SIP/2.0\r\n"; - if (route) { - ack += "Route: " + route + "\r\n"; - } - ack += "Via: " + via + "\r\n"; - ack += "To: " + to + "\r\n"; - ack += "From: " + from + "\r\n"; - ack += "Call-ID: " + callId + "\r\n"; - ack += "CSeq: " + cseq + " ACK\r\n"; - ack += "Max-Forwards: 70\r\n"; - ack += "Content-Length: 0\r\n\r\n"; - // TOOO: "User-Agent" header - this.send(ack).catch(function (error) { - _this.logTransportError(error, "Failed to send ACK to non-2xx response."); - }); - return; - }; - /** - * Execute a state transition. - * @param newState - New state. - */ - InviteClientTransaction.prototype.stateTransition = function (newState, dueToTransportError) { - var _this = this; - if (dueToTransportError === void 0) { dueToTransportError = false; } - // Assert valid state transitions. - var invalidStateTransition = function () { - throw new Error("Invalid state transition from " + _this.state + " to " + newState); - }; - switch (newState) { - case transaction_state_1.TransactionState.Calling: - invalidStateTransition(); - break; - case transaction_state_1.TransactionState.Proceeding: - if (this.state !== transaction_state_1.TransactionState.Calling) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Accepted: - case transaction_state_1.TransactionState.Completed: - if (this.state !== transaction_state_1.TransactionState.Calling && - this.state !== transaction_state_1.TransactionState.Proceeding) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Terminated: - if (this.state !== transaction_state_1.TransactionState.Calling && - this.state !== transaction_state_1.TransactionState.Accepted && - this.state !== transaction_state_1.TransactionState.Completed) { - if (!dueToTransportError) { - invalidStateTransition(); - } - } - break; - default: - invalidStateTransition(); - } - // While not spelled out in the RFC, Timer B is the maximum amount of time that a sender - // will wait for an INVITE message to be acknowledged (a SIP response message is received). - // So Timer B should be cleared when the transaction state proceeds from "Calling". - if (this.B) { - clearTimeout(this.B); - this.B = undefined; - } - if (newState === transaction_state_1.TransactionState.Proceeding) { - // Timers have no effect on "Proceeding" state. - // In the "Proceeding" state, the client transaction - // SHOULD NOT retransmit the request any longer. - // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - } - // The client transaction MUST start Timer D when it enters the "Completed" state - // for any reason, with a value of at least 32 seconds for unreliable transports, - // and a value of zero seconds for reliable transports. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (newState === transaction_state_1.TransactionState.Completed) { - this.D = setTimeout(function () { return _this.timer_D(); }, timers_1.Timers.TIMER_D); - } - // The client transaction MUST transition to the "Accepted" state, - // and Timer M MUST be started with a value of 64*T1. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (newState === transaction_state_1.TransactionState.Accepted) { - this.M = setTimeout(function () { return _this.timer_M(); }, timers_1.Timers.TIMER_M); - } - // Once the transaction is in the "Terminated" state, it MUST be destroyed immediately. - // https://tools.ietf.org/html/rfc6026#section-8.7 - if (newState === transaction_state_1.TransactionState.Terminated) { - this.dispose(); - } - // Update state. - this.setState(newState); - }; - /** - * When timer A fires, the client transaction MUST retransmit the - * request by passing it to the transport layer, and MUST reset the - * timer with a value of 2*T1. - * When timer A fires 2*T1 seconds later, the request MUST be - * retransmitted again (assuming the client transaction is still in this - * state). This process MUST continue so that the request is - * retransmitted with intervals that double after each transmission. - * These retransmissions SHOULD only be done while the client - * transaction is in the "Calling" state. - * https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - */ - InviteClientTransaction.prototype.timer_A = function () { - // TODO - }; - /** - * If the client transaction is still in the "Calling" state when timer - * B fires, the client transaction SHOULD inform the TU that a timeout - * has occurred. The client transaction MUST NOT generate an ACK. - * https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - */ - InviteClientTransaction.prototype.timer_B = function () { - this.logger.debug("Timer B expired for INVITE client transaction " + this.id + "."); - if (this.state === transaction_state_1.TransactionState.Calling) { - this.onRequestTimeout(); - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - /** - * If Timer D fires while the client transaction is in the "Completed" state, - * the client transaction MUST move to the "Terminated" state. - * https://tools.ietf.org/html/rfc6026#section-8.4 - */ - InviteClientTransaction.prototype.timer_D = function () { - this.logger.debug("Timer D expired for INVITE client transaction " + this.id + "."); - if (this.state === transaction_state_1.TransactionState.Completed) { - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - /** - * If Timer M fires while the client transaction is in the "Accepted" - * state, the client transaction MUST move to the "Terminated" state. - * https://tools.ietf.org/html/rfc6026#section-8.4 - */ - InviteClientTransaction.prototype.timer_M = function () { - this.logger.debug("Timer M expired for INVITE client transaction " + this.id + "."); - if (this.state === transaction_state_1.TransactionState.Accepted) { - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - return InviteClientTransaction; -}(client_transaction_1.ClientTransaction)); -exports.InviteClientTransaction = InviteClientTransaction; diff --git a/lib/core/transactions/invite-server-transaction.d.ts b/lib/core/transactions/invite-server-transaction.d.ts deleted file mode 100644 index 1a94b62b4..000000000 --- a/lib/core/transactions/invite-server-transaction.d.ts +++ /dev/null @@ -1,128 +0,0 @@ -import { IncomingRequestMessage } from "../messages"; -import { Transport } from "../transport"; -import { ServerTransaction } from "./server-transaction"; -import { ServerTransactionUser } from "./transaction-user"; -/** - * INVITE Server Transaction. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - * @public - */ -export declare class InviteServerTransaction extends ServerTransaction { - private lastFinalResponse; - private lastProvisionalResponse; - private H; - private I; - private L; - /** - * FIXME: This should not be here. It should be in the UAS. - * - * If the UAS desires an extended period of time to answer the INVITE, - * it will need to ask for an "extension" in order to prevent proxies - * from canceling the transaction. A proxy has the option of canceling - * a transaction when there is a gap of 3 minutes between responses in a - * transaction. To prevent cancellation, the UAS MUST send a non-100 - * provisional response at every minute, to handle the possibility of - * lost provisional responses. - * - * An INVITE transaction can go on for extended durations when the - * user is placed on hold, or when interworking with PSTN systems - * which allow communications to take place without answering the - * call. The latter is common in Interactive Voice Response (IVR) - * systems. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.1 - */ - private progressExtensionTimer; - /** - * Constructor. - * Upon construction, a "100 Trying" reply will be immediately sent. - * After construction the transaction will be in the "proceeding" state and the transaction - * `id` will equal the branch parameter set in the Via header of the incoming request. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - * @param request - Incoming INVITE request from the transport. - * @param transport - The transport. - * @param user - The transaction user. - */ - constructor(request: IncomingRequestMessage, transport: Transport, user: ServerTransactionUser); - /** - * Destructor. - */ - dispose(): void; - /** Transaction kind. Deprecated. */ - readonly kind: string; - /** - * Receive requests from transport matching this transaction. - * @param request - Request matching this transaction. - */ - receiveRequest(request: IncomingRequestMessage): void; - /** - * Receive responses from TU for this transaction. - * @param statusCode - Status code of response. - * @param response - Response. - */ - receiveResponse(statusCode: number, response: string): void; - /** - * Retransmit the last 2xx response. This is a noop if not in the "accepted" state. - */ - retransmitAcceptedResponse(): void; - /** - * First, the procedures in [4] are followed, which attempt to deliver the response to a backup. - * If those should all fail, based on the definition of failure in [4], the server transaction SHOULD - * inform the TU that a failure has occurred, and MUST remain in the current state. - * https://tools.ietf.org/html/rfc6026#section-8.8 - */ - protected onTransportError(error: Error): void; - /** For logging. */ - protected typeToString(): string; - /** - * Execute a state transition. - * @param newState - New state. - */ - private stateTransition; - /** - * FIXME: UAS Provisional Retransmission Timer. See RFC 3261 Section 13.3.1.1 - * This is in the wrong place. This is not a transaction level thing. It's a UAS level thing. - */ - private startProgressExtensionTimer; - /** - * FIXME: UAS Provisional Retransmission Timer id. See RFC 3261 Section 13.3.1.1 - * This is in the wrong place. This is not a transaction level thing. It's a UAS level thing. - */ - private stopProgressExtensionTimer; - /** - * While in the "Proceeding" state, if the TU passes a response with status code - * from 300 to 699 to the server transaction, the response MUST be passed to the - * transport layer for transmission, and the state machine MUST enter the "Completed" state. - * For unreliable transports, timer G is set to fire in T1 seconds, and is not set to fire for - * reliable transports. If timer G fires, the response is passed to the transport layer once - * more for retransmission, and timer G is set to fire in MIN(2*T1, T2) seconds. From then on, - * when timer G fires, the response is passed to the transport again for transmission, and - * timer G is reset with a value that doubles, unless that value exceeds T2, in which case - * it is reset with the value of T2. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - */ - private timer_G; - /** - * If timer H fires while in the "Completed" state, it implies that the ACK was never received. - * In this case, the server transaction MUST transition to the "Terminated" state, and MUST - * indicate to the TU that a transaction failure has occurred. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - */ - private timer_H; - /** - * Once timer I fires, the server MUST transition to the "Terminated" state. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - */ - private timer_I; - /** - * When Timer L fires and the state machine is in the "Accepted" state, the machine MUST - * transition to the "Terminated" state. Once the transaction is in the "Terminated" state, - * it MUST be destroyed immediately. Timer L reflects the amount of time the server - * transaction could receive 2xx responses for retransmission from the - * TU while it is waiting to receive an ACK. - * https://tools.ietf.org/html/rfc6026#section-7.1 - * https://tools.ietf.org/html/rfc6026#section-8.7 - */ - private timer_L; -} -//# sourceMappingURL=invite-server-transaction.d.ts.map \ No newline at end of file diff --git a/lib/core/transactions/invite-server-transaction.d.ts.map b/lib/core/transactions/invite-server-transaction.d.ts.map deleted file mode 100644 index 3c5947906..000000000 --- a/lib/core/transactions/invite-server-transaction.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"invite-server-transaction.d.ts","sourceRoot":"","sources":["../../../src/core/transactions/invite-server-transaction.ts"],"names":[],"mappings":"AACA,OAAO,EAAK,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAExD,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAEzD,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAE3D;;;;;GAKG;AACH,qBAAa,uBAAwB,SAAQ,iBAAiB;IAC5D,OAAO,CAAC,iBAAiB,CAAqB;IAC9C,OAAO,CAAC,uBAAuB,CAAqB;IACpD,OAAO,CAAC,CAAC,CAAkB;IAC3B,OAAO,CAAC,CAAC,CAAkB;IAC3B,OAAO,CAAC,CAAC,CAAkB;IAE3B;;;;;;;;;;;;;;;;;OAiBG;IACH,OAAO,CAAC,sBAAsB,CAAkB;IAEhD;;;;;;;;;OASG;gBACS,OAAO,EAAE,sBAAsB,EAAE,SAAS,EAAE,SAAS,EAAE,IAAI,EAAE,qBAAqB;IAU9F;;OAEG;IACI,OAAO,IAAI,IAAI;IAiBtB,oCAAoC;aAChC,IAAI,EAAI,MAAM;IAIlB;;;OAGG;IACI,cAAc,CAAC,OAAO,EAAE,sBAAsB,GAAG,IAAI;IAuE5D;;;;OAIG;IACI,eAAe,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI;IAiFlE;;OAEG;IACI,0BAA0B,IAAI,IAAI;IAQzC;;;;;OAKG;IACH,SAAS,CAAC,gBAAgB,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI;IAM9C,mBAAmB;IACnB,SAAS,CAAC,YAAY,IAAI,MAAM;IAIhC;;;OAGG;IACH,OAAO,CAAC,eAAe;IA4EvB;;;OAGG;IACH,OAAO,CAAC,2BAA2B;IAenC;;;OAGG;IACH,OAAO,CAAC,0BAA0B;IAOlC;;;;;;;;;;;OAWG;IACH,OAAO,CAAC,OAAO;IAIf;;;;;OAKG;IACH,OAAO,CAAC,OAAO;IAQf;;;OAGG;IACH,OAAO,CAAC,OAAO;IAKf;;;;;;;;OAQG;IACH,OAAO,CAAC,OAAO;CAMhB"} \ No newline at end of file diff --git a/lib/core/transactions/invite-server-transaction.js b/lib/core/transactions/invite-server-transaction.js deleted file mode 100644 index 46bdfd64d..000000000 --- a/lib/core/transactions/invite-server-transaction.js +++ /dev/null @@ -1,391 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var messages_1 = require("../messages"); -var timers_1 = require("../timers"); -var server_transaction_1 = require("./server-transaction"); -var transaction_state_1 = require("./transaction-state"); -/** - * INVITE Server Transaction. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - * @public - */ -var InviteServerTransaction = /** @class */ (function (_super) { - tslib_1.__extends(InviteServerTransaction, _super); - /** - * Constructor. - * Upon construction, a "100 Trying" reply will be immediately sent. - * After construction the transaction will be in the "proceeding" state and the transaction - * `id` will equal the branch parameter set in the Via header of the incoming request. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - * @param request - Incoming INVITE request from the transport. - * @param transport - The transport. - * @param user - The transaction user. - */ - function InviteServerTransaction(request, transport, user) { - return _super.call(this, request, transport, user, transaction_state_1.TransactionState.Proceeding, "sip.transaction.ist") || this; - } - /** - * Destructor. - */ - InviteServerTransaction.prototype.dispose = function () { - this.stopProgressExtensionTimer(); - if (this.H) { - clearTimeout(this.H); - this.H = undefined; - } - if (this.I) { - clearTimeout(this.I); - this.I = undefined; - } - if (this.L) { - clearTimeout(this.L); - this.L = undefined; - } - _super.prototype.dispose.call(this); - }; - Object.defineProperty(InviteServerTransaction.prototype, "kind", { - /** Transaction kind. Deprecated. */ - get: function () { - return "ist"; - }, - enumerable: true, - configurable: true - }); - /** - * Receive requests from transport matching this transaction. - * @param request - Request matching this transaction. - */ - InviteServerTransaction.prototype.receiveRequest = function (request) { - var _this = this; - switch (this.state) { - case transaction_state_1.TransactionState.Proceeding: - // If a request retransmission is received while in the "Proceeding" state, the most - // recent provisional response that was received from the TU MUST be passed to the - // transport layer for retransmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (request.method === messages_1.C.INVITE) { - if (this.lastProvisionalResponse) { - this.send(this.lastProvisionalResponse).catch(function (error) { - _this.logTransportError(error, "Failed to send retransmission of provisional response."); - }); - } - return; - } - break; - case transaction_state_1.TransactionState.Accepted: - // While in the "Accepted" state, any retransmissions of the INVITE - // received will match this transaction state machine and will be - // absorbed by the machine without changing its state. These - // retransmissions are not passed onto the TU. - // https://tools.ietf.org/html/rfc6026#section-7.1 - if (request.method === messages_1.C.INVITE) { - return; - } - break; - case transaction_state_1.TransactionState.Completed: - // Furthermore, while in the "Completed" state, if a request retransmission is - // received, the server SHOULD pass the response to the transport for retransmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (request.method === messages_1.C.INVITE) { - if (!this.lastFinalResponse) { - throw new Error("Last final response undefined."); - } - this.send(this.lastFinalResponse).catch(function (error) { - _this.logTransportError(error, "Failed to send retransmission of final response."); - }); - return; - } - // If an ACK is received while the server transaction is in the "Completed" state, - // the server transaction MUST transition to the "Confirmed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (request.method === messages_1.C.ACK) { - this.stateTransition(transaction_state_1.TransactionState.Confirmed); - return; - } - break; - case transaction_state_1.TransactionState.Confirmed: - // The purpose of the "Confirmed" state is to absorb any additional ACK messages that arrive, - // triggered from retransmissions of the final response. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (request.method === messages_1.C.INVITE || request.method === messages_1.C.ACK) { - return; - } - break; - case transaction_state_1.TransactionState.Terminated: - // For good measure absorb any additional messages that arrive (should not happen). - if (request.method === messages_1.C.INVITE || request.method === messages_1.C.ACK) { - return; - } - break; - default: - throw new Error("Invalid state " + this.state); - } - var message = "INVITE server transaction received unexpected " + request.method + " request while in state " + this.state + "."; - this.logger.warn(message); - return; - }; - /** - * Receive responses from TU for this transaction. - * @param statusCode - Status code of response. - * @param response - Response. - */ - InviteServerTransaction.prototype.receiveResponse = function (statusCode, response) { - var _this = this; - if (statusCode < 100 || statusCode > 699) { - throw new Error("Invalid status code " + statusCode); - } - switch (this.state) { - case transaction_state_1.TransactionState.Proceeding: - // The TU passes any number of provisional responses to the server - // transaction. So long as the server transaction is in the - // "Proceeding" state, each of these MUST be passed to the transport - // layer for transmission. They are not sent reliably by the - // transaction layer (they are not retransmitted by it) and do not cause - // a change in the state of the server transaction. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (statusCode >= 100 && statusCode <= 199) { - this.lastProvisionalResponse = response; - // Start the progress extension timer only for a non-100 provisional response. - if (statusCode > 100) { - this.startProgressExtensionTimer(); // FIXME: remove - } - this.send(response).catch(function (error) { - _this.logTransportError(error, "Failed to send 1xx response."); - }); - return; - } - // If, while in the "Proceeding" state, the TU passes a 2xx response - // to the server transaction, the server transaction MUST pass this - // response to the transport layer for transmission. It is not - // retransmitted by the server transaction; retransmissions of 2xx - // responses are handled by the TU. The server transaction MUST then - // transition to the "Accepted" state. - // https://tools.ietf.org/html/rfc6026#section-8.5 - if (statusCode >= 200 && statusCode <= 299) { - this.lastFinalResponse = response; - this.stateTransition(transaction_state_1.TransactionState.Accepted); - this.send(response).catch(function (error) { - _this.logTransportError(error, "Failed to send 2xx response."); - }); - return; - } - // While in the "Proceeding" state, if the TU passes a response with - // status code from 300 to 699 to the server transaction, the response - // MUST be passed to the transport layer for transmission, and the state - // machine MUST enter the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (statusCode >= 300 && statusCode <= 699) { - this.lastFinalResponse = response; - this.stateTransition(transaction_state_1.TransactionState.Completed); - this.send(response).catch(function (error) { - _this.logTransportError(error, "Failed to send non-2xx final response."); - }); - return; - } - break; - case transaction_state_1.TransactionState.Accepted: - // While in the "Accepted" state, if the TU passes a 2xx response, - // the server transaction MUST pass the response to the transport layer for transmission. - // https://tools.ietf.org/html/rfc6026#section-8.7 - if (statusCode >= 200 && statusCode <= 299) { - this.send(response).catch(function (error) { - _this.logTransportError(error, "Failed to send 2xx response."); - }); - return; - } - break; - case transaction_state_1.TransactionState.Completed: - break; - case transaction_state_1.TransactionState.Confirmed: - break; - case transaction_state_1.TransactionState.Terminated: - break; - default: - throw new Error("Invalid state " + this.state); - } - var message = "INVITE server transaction received unexpected " + statusCode + " response from TU while in state " + this.state + "."; - this.logger.error(message); - throw new Error(message); - }; - /** - * Retransmit the last 2xx response. This is a noop if not in the "accepted" state. - */ - InviteServerTransaction.prototype.retransmitAcceptedResponse = function () { - var _this = this; - if (this.state === transaction_state_1.TransactionState.Accepted && this.lastFinalResponse) { - this.send(this.lastFinalResponse).catch(function (error) { - _this.logTransportError(error, "Failed to send 2xx response."); - }); - } - }; - /** - * First, the procedures in [4] are followed, which attempt to deliver the response to a backup. - * If those should all fail, based on the definition of failure in [4], the server transaction SHOULD - * inform the TU that a failure has occurred, and MUST remain in the current state. - * https://tools.ietf.org/html/rfc6026#section-8.8 - */ - InviteServerTransaction.prototype.onTransportError = function (error) { - if (this.user.onTransportError) { - this.user.onTransportError(error); - } - }; - /** For logging. */ - InviteServerTransaction.prototype.typeToString = function () { - return "INVITE server transaction"; - }; - /** - * Execute a state transition. - * @param newState - New state. - */ - InviteServerTransaction.prototype.stateTransition = function (newState) { - var _this = this; - // Assert valid state transitions. - var invalidStateTransition = function () { - throw new Error("Invalid state transition from " + _this.state + " to " + newState); - }; - switch (newState) { - case transaction_state_1.TransactionState.Proceeding: - invalidStateTransition(); - break; - case transaction_state_1.TransactionState.Accepted: - case transaction_state_1.TransactionState.Completed: - if (this.state !== transaction_state_1.TransactionState.Proceeding) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Confirmed: - if (this.state !== transaction_state_1.TransactionState.Completed) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Terminated: - if (this.state !== transaction_state_1.TransactionState.Accepted && - this.state !== transaction_state_1.TransactionState.Completed && - this.state !== transaction_state_1.TransactionState.Confirmed) { - invalidStateTransition(); - } - break; - default: - invalidStateTransition(); - } - // On any state transition, stop resending provisonal responses - this.stopProgressExtensionTimer(); - // The purpose of the "Accepted" state is to absorb retransmissions of an accepted INVITE request. - // Any such retransmissions are absorbed entirely within the server transaction. - // They are not passed up to the TU since any downstream UAS cores that accepted the request have - // taken responsibility for reliability and will already retransmit their 2xx responses if necessary. - // https://tools.ietf.org/html/rfc6026#section-8.7 - if (newState === transaction_state_1.TransactionState.Accepted) { - this.L = setTimeout(function () { return _this.timer_L(); }, timers_1.Timers.TIMER_L); - } - // When the "Completed" state is entered, timer H MUST be set to fire in 64*T1 seconds for all transports. - // Timer H determines when the server transaction abandons retransmitting the response. - // If an ACK is received while the server transaction is in the "Completed" state, - // the server transaction MUST transition to the "Confirmed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (newState === transaction_state_1.TransactionState.Completed) { - // FIXME: Missing timer G for unreliable transports. - this.H = setTimeout(function () { return _this.timer_H(); }, timers_1.Timers.TIMER_H); - } - // The purpose of the "Confirmed" state is to absorb any additional ACK messages that arrive, - // triggered from retransmissions of the final response. When this state is entered, timer I - // is set to fire in T4 seconds for unreliable transports, and zero seconds for reliable - // transports. Once timer I fires, the server MUST transition to the "Terminated" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (newState === transaction_state_1.TransactionState.Confirmed) { - // FIXME: This timer is not getting set correctly for unreliable transports. - this.I = setTimeout(function () { return _this.timer_I(); }, timers_1.Timers.TIMER_I); - } - // Once the transaction is in the "Terminated" state, it MUST be destroyed immediately. - // https://tools.ietf.org/html/rfc6026#section-8.7 - if (newState === transaction_state_1.TransactionState.Terminated) { - this.dispose(); - } - // Update state. - this.setState(newState); - }; - /** - * FIXME: UAS Provisional Retransmission Timer. See RFC 3261 Section 13.3.1.1 - * This is in the wrong place. This is not a transaction level thing. It's a UAS level thing. - */ - InviteServerTransaction.prototype.startProgressExtensionTimer = function () { - var _this = this; - // Start the progress extension timer only for the first non-100 provisional response. - if (this.progressExtensionTimer === undefined) { - this.progressExtensionTimer = setInterval(function () { - _this.logger.debug("Progress extension timer expired for INVITE server transaction " + _this.id + "."); - if (!_this.lastProvisionalResponse) { - throw new Error("Last provisional response undefined."); - } - _this.send(_this.lastProvisionalResponse).catch(function (error) { - _this.logTransportError(error, "Failed to send retransmission of provisional response."); - }); - }, timers_1.Timers.PROVISIONAL_RESPONSE_INTERVAL); - } - }; - /** - * FIXME: UAS Provisional Retransmission Timer id. See RFC 3261 Section 13.3.1.1 - * This is in the wrong place. This is not a transaction level thing. It's a UAS level thing. - */ - InviteServerTransaction.prototype.stopProgressExtensionTimer = function () { - if (this.progressExtensionTimer !== undefined) { - clearInterval(this.progressExtensionTimer); - this.progressExtensionTimer = undefined; - } - }; - /** - * While in the "Proceeding" state, if the TU passes a response with status code - * from 300 to 699 to the server transaction, the response MUST be passed to the - * transport layer for transmission, and the state machine MUST enter the "Completed" state. - * For unreliable transports, timer G is set to fire in T1 seconds, and is not set to fire for - * reliable transports. If timer G fires, the response is passed to the transport layer once - * more for retransmission, and timer G is set to fire in MIN(2*T1, T2) seconds. From then on, - * when timer G fires, the response is passed to the transport again for transmission, and - * timer G is reset with a value that doubles, unless that value exceeds T2, in which case - * it is reset with the value of T2. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - */ - InviteServerTransaction.prototype.timer_G = function () { - // TODO - }; - /** - * If timer H fires while in the "Completed" state, it implies that the ACK was never received. - * In this case, the server transaction MUST transition to the "Terminated" state, and MUST - * indicate to the TU that a transaction failure has occurred. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - */ - InviteServerTransaction.prototype.timer_H = function () { - this.logger.debug("Timer H expired for INVITE server transaction " + this.id + "."); - if (this.state === transaction_state_1.TransactionState.Completed) { - this.logger.warn("ACK to negative final response was never received, terminating transaction."); - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - /** - * Once timer I fires, the server MUST transition to the "Terminated" state. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - */ - InviteServerTransaction.prototype.timer_I = function () { - this.logger.debug("Timer I expired for INVITE server transaction " + this.id + "."); - this.stateTransition(transaction_state_1.TransactionState.Terminated); - }; - /** - * When Timer L fires and the state machine is in the "Accepted" state, the machine MUST - * transition to the "Terminated" state. Once the transaction is in the "Terminated" state, - * it MUST be destroyed immediately. Timer L reflects the amount of time the server - * transaction could receive 2xx responses for retransmission from the - * TU while it is waiting to receive an ACK. - * https://tools.ietf.org/html/rfc6026#section-7.1 - * https://tools.ietf.org/html/rfc6026#section-8.7 - */ - InviteServerTransaction.prototype.timer_L = function () { - this.logger.debug("Timer L expired for INVITE server transaction " + this.id + "."); - if (this.state === transaction_state_1.TransactionState.Accepted) { - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - return InviteServerTransaction; -}(server_transaction_1.ServerTransaction)); -exports.InviteServerTransaction = InviteServerTransaction; diff --git a/lib/core/transactions/non-invite-client-transaction.d.ts b/lib/core/transactions/non-invite-client-transaction.d.ts deleted file mode 100644 index c395e8635..000000000 --- a/lib/core/transactions/non-invite-client-transaction.d.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { IncomingResponseMessage, OutgoingRequestMessage } from "../messages"; -import { Transport } from "../transport"; -import { ClientTransaction } from "./client-transaction"; -import { ClientTransactionUser } from "./transaction-user"; -/** - * Non-INVITE Client Transaction. - * @remarks - * Non-INVITE transactions do not make use of ACK. - * They are simple request-response interactions. - * https://tools.ietf.org/html/rfc3261#section-17.1.2 - * @public - */ -export declare class NonInviteClientTransaction extends ClientTransaction { - private F; - private K; - /** - * Constructor - * Upon construction, the outgoing request's Via header is updated by calling `setViaHeader`. - * Then `toString` is called on the outgoing request and the message is sent via the transport. - * After construction the transaction will be in the "calling" state and the transaction id - * will equal the branch parameter set in the Via header of the outgoing request. - * https://tools.ietf.org/html/rfc3261#section-17.1.2 - * @param request - The outgoing Non-INVITE request. - * @param transport - The transport. - * @param user - The transaction user. - */ - constructor(request: OutgoingRequestMessage, transport: Transport, user: ClientTransactionUser); - /** - * Destructor. - */ - dispose(): void; - /** Transaction kind. Deprecated. */ - readonly kind: string; - /** - * Handler for incoming responses from the transport which match this transaction. - * @param response - The incoming response. - */ - receiveResponse(response: IncomingResponseMessage): void; - /** - * The client transaction SHOULD inform the TU that a transport failure has occurred, - * and the client transaction SHOULD transition directly to the "Terminated" state. - * The TU will handle the failover mechanisms described in [4]. - * https://tools.ietf.org/html/rfc3261#section-17.1.4 - * @param error - Trasnsport error - */ - protected onTransportError(error: Error): void; - /** For logging. */ - protected typeToString(): string; - /** - * Execute a state transition. - * @param newState - New state. - */ - private stateTransition; - /** - * If Timer F fires while the client transaction is still in the - * "Trying" state, the client transaction SHOULD inform the TU about the - * timeout, and then it SHOULD enter the "Terminated" state. - * If timer F fires while in the "Proceeding" state, the TU MUST be informed of - * a timeout, and the client transaction MUST transition to the terminated state. - * https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - */ - private timer_F; - /** - * If Timer K fires while in this (COMPLETED) state, the client transaction - * MUST transition to the "Terminated" state. - * https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - */ - private timer_K; -} -//# sourceMappingURL=non-invite-client-transaction.d.ts.map \ No newline at end of file diff --git a/lib/core/transactions/non-invite-client-transaction.d.ts.map b/lib/core/transactions/non-invite-client-transaction.d.ts.map deleted file mode 100644 index dffd24cb6..000000000 --- a/lib/core/transactions/non-invite-client-transaction.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"non-invite-client-transaction.d.ts","sourceRoot":"","sources":["../../../src/core/transactions/non-invite-client-transaction.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAE9E,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAEzD,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAE3D;;;;;;;GAOG;AACH,qBAAa,0BAA2B,SAAQ,iBAAiB;IAC/D,OAAO,CAAC,CAAC,CAAkB;IAC3B,OAAO,CAAC,CAAC,CAAkB;IAE3B;;;;;;;;;;OAUG;gBACS,OAAO,EAAE,sBAAsB,EAAE,SAAS,EAAE,SAAS,EAAE,IAAI,EAAE,qBAAqB;IAqB9F;;OAEG;IACI,OAAO,IAAI,IAAI;IAYtB,oCAAoC;aAChC,IAAI,EAAI,MAAM;IAIlB;;;OAGG;IACI,eAAe,CAAC,QAAQ,EAAE,uBAAuB,GAAG,IAAI;IA8E/D;;;;;;OAMG;IACH,SAAS,CAAC,gBAAgB,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI;IAO9C,mBAAmB;IACnB,SAAS,CAAC,YAAY,IAAI,MAAM;IAIhC;;;OAGG;IACH,OAAO,CAAC,eAAe;IA8DvB;;;;;;;OAOG;IACH,OAAO,CAAC,OAAO;IAQf;;;;OAIG;IACH,OAAO,CAAC,OAAO;CAKhB"} \ No newline at end of file diff --git a/lib/core/transactions/non-invite-client-transaction.js b/lib/core/transactions/non-invite-client-transaction.js deleted file mode 100644 index 767dffbfe..000000000 --- a/lib/core/transactions/non-invite-client-transaction.js +++ /dev/null @@ -1,246 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var timers_1 = require("../timers"); -var client_transaction_1 = require("./client-transaction"); -var transaction_state_1 = require("./transaction-state"); -/** - * Non-INVITE Client Transaction. - * @remarks - * Non-INVITE transactions do not make use of ACK. - * They are simple request-response interactions. - * https://tools.ietf.org/html/rfc3261#section-17.1.2 - * @public - */ -var NonInviteClientTransaction = /** @class */ (function (_super) { - tslib_1.__extends(NonInviteClientTransaction, _super); - /** - * Constructor - * Upon construction, the outgoing request's Via header is updated by calling `setViaHeader`. - * Then `toString` is called on the outgoing request and the message is sent via the transport. - * After construction the transaction will be in the "calling" state and the transaction id - * will equal the branch parameter set in the Via header of the outgoing request. - * https://tools.ietf.org/html/rfc3261#section-17.1.2 - * @param request - The outgoing Non-INVITE request. - * @param transport - The transport. - * @param user - The transaction user. - */ - function NonInviteClientTransaction(request, transport, user) { - var _this = _super.call(this, request, transport, user, transaction_state_1.TransactionState.Trying, "sip.transaction.nict") || this; - // FIXME: Timer E for unreliable transports not implemented. - // - // The "Trying" state is entered when the TU initiates a new client - // transaction with a request. When entering this state, the client - // transaction SHOULD set timer F to fire in 64*T1 seconds. The request - // MUST be passed to the transport layer for transmission. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - _this.F = setTimeout(function () { return _this.timer_F(); }, timers_1.Timers.TIMER_F); - _this.send(request.toString()).catch(function (error) { - _this.logTransportError(error, "Failed to send initial outgoing request."); - }); - return _this; - } - /** - * Destructor. - */ - NonInviteClientTransaction.prototype.dispose = function () { - if (this.F) { - clearTimeout(this.F); - this.F = undefined; - } - if (this.K) { - clearTimeout(this.K); - this.K = undefined; - } - _super.prototype.dispose.call(this); - }; - Object.defineProperty(NonInviteClientTransaction.prototype, "kind", { - /** Transaction kind. Deprecated. */ - get: function () { - return "nict"; - }, - enumerable: true, - configurable: true - }); - /** - * Handler for incoming responses from the transport which match this transaction. - * @param response - The incoming response. - */ - NonInviteClientTransaction.prototype.receiveResponse = function (response) { - var statusCode = response.statusCode; - if (!statusCode || statusCode < 100 || statusCode > 699) { - throw new Error("Invalid status code " + statusCode); - } - switch (this.state) { - case transaction_state_1.TransactionState.Trying: - // If a provisional response is received while in the "Trying" state, the - // response MUST be passed to the TU, and then the client transaction - // SHOULD move to the "Proceeding" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (statusCode >= 100 && statusCode <= 199) { - this.stateTransition(transaction_state_1.TransactionState.Proceeding); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // If a final response (status codes 200-699) is received while in the - // "Trying" state, the response MUST be passed to the TU, and the - // client transaction MUST transition to the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (statusCode >= 200 && statusCode <= 699) { - this.stateTransition(transaction_state_1.TransactionState.Completed); - if (statusCode === 408) { - this.onRequestTimeout(); - return; - } - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - break; - case transaction_state_1.TransactionState.Proceeding: - // If a provisional response is received while in the "Proceeding" state, - // the response MUST be passed to the TU. (From Figure 6) - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (statusCode >= 100 && statusCode <= 199) { - if (this.user.receiveResponse) { - return this.user.receiveResponse(response); - } - } - // If a final response (status codes 200-699) is received while in the - // "Proceeding" state, the response MUST be passed to the TU, and the - // client transaction MUST transition to the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (statusCode >= 200 && statusCode <= 699) { - this.stateTransition(transaction_state_1.TransactionState.Completed); - if (statusCode === 408) { - this.onRequestTimeout(); - return; - } - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - case transaction_state_1.TransactionState.Completed: - // The "Completed" state exists to buffer any additional response - // retransmissions that may be received (which is why the client - // transaction remains there only for unreliable transports). - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - return; - case transaction_state_1.TransactionState.Terminated: - // For good measure just absorb additional response retransmissions. - return; - default: - throw new Error("Invalid state " + this.state); - } - var message = "Non-INVITE client transaction received unexpected " + statusCode + " response while in state " + this.state + "."; - this.logger.warn(message); - return; - }; - /** - * The client transaction SHOULD inform the TU that a transport failure has occurred, - * and the client transaction SHOULD transition directly to the "Terminated" state. - * The TU will handle the failover mechanisms described in [4]. - * https://tools.ietf.org/html/rfc3261#section-17.1.4 - * @param error - Trasnsport error - */ - NonInviteClientTransaction.prototype.onTransportError = function (error) { - if (this.user.onTransportError) { - this.user.onTransportError(error); - } - this.stateTransition(transaction_state_1.TransactionState.Terminated, true); - }; - /** For logging. */ - NonInviteClientTransaction.prototype.typeToString = function () { - return "non-INVITE client transaction"; - }; - /** - * Execute a state transition. - * @param newState - New state. - */ - NonInviteClientTransaction.prototype.stateTransition = function (newState, dueToTransportError) { - var _this = this; - if (dueToTransportError === void 0) { dueToTransportError = false; } - // Assert valid state transitions. - var invalidStateTransition = function () { - throw new Error("Invalid state transition from " + _this.state + " to " + newState); - }; - switch (newState) { - case transaction_state_1.TransactionState.Trying: - invalidStateTransition(); - break; - case transaction_state_1.TransactionState.Proceeding: - if (this.state !== transaction_state_1.TransactionState.Trying) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Completed: - if (this.state !== transaction_state_1.TransactionState.Trying && - this.state !== transaction_state_1.TransactionState.Proceeding) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Terminated: - if (this.state !== transaction_state_1.TransactionState.Trying && - this.state !== transaction_state_1.TransactionState.Proceeding && - this.state !== transaction_state_1.TransactionState.Completed) { - if (!dueToTransportError) { - invalidStateTransition(); - } - } - break; - default: - invalidStateTransition(); - } - // Once the client transaction enters the "Completed" state, it MUST set - // Timer K to fire in T4 seconds for unreliable transports, and zero - // seconds for reliable transports The "Completed" state exists to - // buffer any additional response retransmissions that may be received - // (which is why the client transaction remains there only for unreliable transports). - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (newState === transaction_state_1.TransactionState.Completed) { - if (this.F) { - clearTimeout(this.F); - this.F = undefined; - } - this.K = setTimeout(function () { return _this.timer_K(); }, timers_1.Timers.TIMER_K); - } - // Once the transaction is in the terminated state, it MUST be destroyed immediately. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (newState === transaction_state_1.TransactionState.Terminated) { - this.dispose(); - } - // Update state. - this.setState(newState); - }; - /** - * If Timer F fires while the client transaction is still in the - * "Trying" state, the client transaction SHOULD inform the TU about the - * timeout, and then it SHOULD enter the "Terminated" state. - * If timer F fires while in the "Proceeding" state, the TU MUST be informed of - * a timeout, and the client transaction MUST transition to the terminated state. - * https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - */ - NonInviteClientTransaction.prototype.timer_F = function () { - this.logger.debug("Timer F expired for non-INVITE client transaction " + this.id + "."); - if (this.state === transaction_state_1.TransactionState.Trying || this.state === transaction_state_1.TransactionState.Proceeding) { - this.onRequestTimeout(); - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - /** - * If Timer K fires while in this (COMPLETED) state, the client transaction - * MUST transition to the "Terminated" state. - * https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - */ - NonInviteClientTransaction.prototype.timer_K = function () { - if (this.state === transaction_state_1.TransactionState.Completed) { - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - return NonInviteClientTransaction; -}(client_transaction_1.ClientTransaction)); -exports.NonInviteClientTransaction = NonInviteClientTransaction; diff --git a/lib/core/transactions/non-invite-server-transaction.d.ts b/lib/core/transactions/non-invite-server-transaction.d.ts deleted file mode 100644 index 8044edd7a..000000000 --- a/lib/core/transactions/non-invite-server-transaction.d.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { IncomingRequestMessage } from "../messages"; -import { Transport } from "../transport"; -import { ServerTransaction } from "./server-transaction"; -import { ServerTransactionUser } from "./transaction-user"; -/** - * Non-INVITE Server Transaction. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-17.2.2 - * @public - */ -export declare class NonInviteServerTransaction extends ServerTransaction { - private lastResponse; - private J; - /** - * Constructor. - * After construction the transaction will be in the "trying": state and the transaction - * `id` will equal the branch parameter set in the Via header of the incoming request. - * https://tools.ietf.org/html/rfc3261#section-17.2.2 - * @param request - Incoming Non-INVITE request from the transport. - * @param transport - The transport. - * @param user - The transaction user. - */ - constructor(request: IncomingRequestMessage, transport: Transport, user: ServerTransactionUser); - /** - * Destructor. - */ - dispose(): void; - /** Transaction kind. Deprecated. */ - readonly kind: string; - /** - * Receive requests from transport matching this transaction. - * @param request - Request matching this transaction. - */ - receiveRequest(request: IncomingRequestMessage): void; - /** - * Receive responses from TU for this transaction. - * @param statusCode - Status code of repsonse. 101-199 not allowed per RFC 4320. - * @param response - Response to send. - */ - receiveResponse(statusCode: number, response: string): void; - /** - * First, the procedures in [4] are followed, which attempt to deliver the response to a backup. - * If those should all fail, based on the definition of failure in [4], the server transaction SHOULD - * inform the TU that a failure has occurred, and SHOULD transition to the terminated state. - * https://tools.ietf.org/html/rfc3261#section-17.2.4 - */ - protected onTransportError(error: Error): void; - /** For logging. */ - protected typeToString(): string; - private stateTransition; - /** - * The server transaction remains in this state until Timer J fires, - * at which point it MUST transition to the "Terminated" state. - * https://tools.ietf.org/html/rfc3261#section-17.2.2 - */ - private timer_J; -} -//# sourceMappingURL=non-invite-server-transaction.d.ts.map \ No newline at end of file diff --git a/lib/core/transactions/non-invite-server-transaction.d.ts.map b/lib/core/transactions/non-invite-server-transaction.d.ts.map deleted file mode 100644 index 65a78a3d5..000000000 --- a/lib/core/transactions/non-invite-server-transaction.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"non-invite-server-transaction.d.ts","sourceRoot":"","sources":["../../../src/core/transactions/non-invite-server-transaction.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAErD,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAEzD,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAE3D;;;;;GAKG;AACH,qBAAa,0BAA2B,SAAQ,iBAAiB;IAC/D,OAAO,CAAC,YAAY,CAAqB;IACzC,OAAO,CAAC,CAAC,CAAkB;IAE3B;;;;;;;;OAQG;gBACS,OAAO,EAAE,sBAAsB,EAAE,SAAS,EAAE,SAAS,EAAE,IAAI,EAAE,qBAAqB;IAU9F;;OAEG;IACI,OAAO,IAAI,IAAI;IAQtB,oCAAoC;aAChC,IAAI,EAAI,MAAM;IAIlB;;;OAGG;IACI,cAAc,CAAC,OAAO,EAAE,sBAAsB,GAAG,IAAI;IAoC5D;;;;OAIG;IACI,eAAe,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI;IAwElE;;;;;OAKG;IACH,SAAS,CAAC,gBAAgB,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI;IAO9C,mBAAmB;IACnB,SAAS,CAAC,YAAY,IAAI,MAAM;IAIhC,OAAO,CAAC,eAAe;IA+CvB;;;;OAIG;IACH,OAAO,CAAC,OAAO;CAMhB"} \ No newline at end of file diff --git a/lib/core/transactions/non-invite-server-transaction.js b/lib/core/transactions/non-invite-server-transaction.js deleted file mode 100644 index 4e2ee31ff..000000000 --- a/lib/core/transactions/non-invite-server-transaction.js +++ /dev/null @@ -1,231 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var timers_1 = require("../timers"); -var server_transaction_1 = require("./server-transaction"); -var transaction_state_1 = require("./transaction-state"); -/** - * Non-INVITE Server Transaction. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-17.2.2 - * @public - */ -var NonInviteServerTransaction = /** @class */ (function (_super) { - tslib_1.__extends(NonInviteServerTransaction, _super); - /** - * Constructor. - * After construction the transaction will be in the "trying": state and the transaction - * `id` will equal the branch parameter set in the Via header of the incoming request. - * https://tools.ietf.org/html/rfc3261#section-17.2.2 - * @param request - Incoming Non-INVITE request from the transport. - * @param transport - The transport. - * @param user - The transaction user. - */ - function NonInviteServerTransaction(request, transport, user) { - return _super.call(this, request, transport, user, transaction_state_1.TransactionState.Trying, "sip.transaction.nist") || this; - } - /** - * Destructor. - */ - NonInviteServerTransaction.prototype.dispose = function () { - if (this.J) { - clearTimeout(this.J); - this.J = undefined; - } - _super.prototype.dispose.call(this); - }; - Object.defineProperty(NonInviteServerTransaction.prototype, "kind", { - /** Transaction kind. Deprecated. */ - get: function () { - return "nist"; - }, - enumerable: true, - configurable: true - }); - /** - * Receive requests from transport matching this transaction. - * @param request - Request matching this transaction. - */ - NonInviteServerTransaction.prototype.receiveRequest = function (request) { - var _this = this; - switch (this.state) { - case transaction_state_1.TransactionState.Trying: - // Once in the "Trying" state, any further request retransmissions are discarded. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - break; - case transaction_state_1.TransactionState.Proceeding: - // If a retransmission of the request is received while in the "Proceeding" state, - // the most recently sent provisional response MUST be passed to the transport layer for retransmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - if (!this.lastResponse) { - throw new Error("Last response undefined."); - } - this.send(this.lastResponse).catch(function (error) { - _this.logTransportError(error, "Failed to send retransmission of provisional response."); - }); - break; - case transaction_state_1.TransactionState.Completed: - // While in the "Completed" state, the server transaction MUST pass the final response to the transport - // layer for retransmission whenever a retransmission of the request is received. Any other final responses - // passed by the TU to the server transaction MUST be discarded while in the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - if (!this.lastResponse) { - throw new Error("Last response undefined."); - } - this.send(this.lastResponse).catch(function (error) { - _this.logTransportError(error, "Failed to send retransmission of final response."); - }); - break; - case transaction_state_1.TransactionState.Terminated: - break; - default: - throw new Error("Invalid state " + this.state); - } - }; - /** - * Receive responses from TU for this transaction. - * @param statusCode - Status code of repsonse. 101-199 not allowed per RFC 4320. - * @param response - Response to send. - */ - NonInviteServerTransaction.prototype.receiveResponse = function (statusCode, response) { - var _this = this; - if (statusCode < 100 || statusCode > 699) { - throw new Error("Invalid status code " + statusCode); - } - // An SIP element MUST NOT send any provisional response with a - // Status-Code other than 100 to a non-INVITE request. - // An SIP element MUST NOT respond to a non-INVITE request with a - // Status-Code of 100 over any unreliable transport, such as UDP, - // before the amount of time it takes a client transaction's Timer E to be reset to T2. - // An SIP element MAY respond to a non-INVITE request with a - // Status-Code of 100 over a reliable transport at any time. - // https://tools.ietf.org/html/rfc4320#section-4.1 - if (statusCode > 100 && statusCode <= 199) { - throw new Error("Provisional response other than 100 not allowed."); - } - switch (this.state) { - case transaction_state_1.TransactionState.Trying: - // While in the "Trying" state, if the TU passes a provisional response - // to the server transaction, the server transaction MUST enter the "Proceeding" state. - // The response MUST be passed to the transport layer for transmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - this.lastResponse = response; - if (statusCode >= 100 && statusCode < 200) { - this.stateTransition(transaction_state_1.TransactionState.Proceeding); - this.send(response).catch(function (error) { - _this.logTransportError(error, "Failed to send provisional response."); - }); - return; - } - if (statusCode >= 200 && statusCode <= 699) { - this.stateTransition(transaction_state_1.TransactionState.Completed); - this.send(response).catch(function (error) { - _this.logTransportError(error, "Failed to send final response."); - }); - return; - } - break; - case transaction_state_1.TransactionState.Proceeding: - // Any further provisional responses that are received from the TU while - // in the "Proceeding" state MUST be passed to the transport layer for transmission. - // If the TU passes a final response (status codes 200-699) to the server while in - // the "Proceeding" state, the transaction MUST enter the "Completed" state, and - // the response MUST be passed to the transport layer for transmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - this.lastResponse = response; - if (statusCode >= 200 && statusCode <= 699) { - this.stateTransition(transaction_state_1.TransactionState.Completed); - this.send(response).catch(function (error) { - _this.logTransportError(error, "Failed to send final response."); - }); - return; - } - break; - case transaction_state_1.TransactionState.Completed: - // Any other final responses passed by the TU to the server - // transaction MUST be discarded while in the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - return; - case transaction_state_1.TransactionState.Terminated: - break; - default: - throw new Error("Invalid state " + this.state); - } - var message = "Non-INVITE server transaction received unexpected " + statusCode + " response from TU while in state " + this.state + "."; - this.logger.error(message); - throw new Error(message); - }; - /** - * First, the procedures in [4] are followed, which attempt to deliver the response to a backup. - * If those should all fail, based on the definition of failure in [4], the server transaction SHOULD - * inform the TU that a failure has occurred, and SHOULD transition to the terminated state. - * https://tools.ietf.org/html/rfc3261#section-17.2.4 - */ - NonInviteServerTransaction.prototype.onTransportError = function (error) { - if (this.user.onTransportError) { - this.user.onTransportError(error); - } - this.stateTransition(transaction_state_1.TransactionState.Terminated, true); - }; - /** For logging. */ - NonInviteServerTransaction.prototype.typeToString = function () { - return "non-INVITE server transaction"; - }; - NonInviteServerTransaction.prototype.stateTransition = function (newState, dueToTransportError) { - var _this = this; - if (dueToTransportError === void 0) { dueToTransportError = false; } - // Assert valid state transitions. - var invalidStateTransition = function () { - throw new Error("Invalid state transition from " + _this.state + " to " + newState); - }; - switch (newState) { - case transaction_state_1.TransactionState.Trying: - invalidStateTransition(); - break; - case transaction_state_1.TransactionState.Proceeding: - if (this.state !== transaction_state_1.TransactionState.Trying) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Completed: - if (this.state !== transaction_state_1.TransactionState.Trying && this.state !== transaction_state_1.TransactionState.Proceeding) { - invalidStateTransition(); - } - break; - case transaction_state_1.TransactionState.Terminated: - if (this.state !== transaction_state_1.TransactionState.Proceeding && this.state !== transaction_state_1.TransactionState.Completed) { - if (!dueToTransportError) { - invalidStateTransition(); - } - } - break; - default: - invalidStateTransition(); - } - // When the server transaction enters the "Completed" state, it MUST set Timer J to fire - // in 64*T1 seconds for unreliable transports, and zero seconds for reliable transports. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - if (newState === transaction_state_1.TransactionState.Completed) { - this.J = setTimeout(function () { return _this.timer_J(); }, timers_1.Timers.TIMER_J); - } - // The server transaction MUST be destroyed the instant it enters the "Terminated" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - if (newState === transaction_state_1.TransactionState.Terminated) { - this.dispose(); - } - this.setState(newState); - }; - /** - * The server transaction remains in this state until Timer J fires, - * at which point it MUST transition to the "Terminated" state. - * https://tools.ietf.org/html/rfc3261#section-17.2.2 - */ - NonInviteServerTransaction.prototype.timer_J = function () { - this.logger.debug("Timer J expired for NON-INVITE server transaction " + this.id + "."); - if (this.state === transaction_state_1.TransactionState.Completed) { - this.stateTransition(transaction_state_1.TransactionState.Terminated); - } - }; - return NonInviteServerTransaction; -}(server_transaction_1.ServerTransaction)); -exports.NonInviteServerTransaction = NonInviteServerTransaction; diff --git a/lib/core/transactions/server-transaction.d.ts b/lib/core/transactions/server-transaction.d.ts deleted file mode 100644 index 00601b22f..000000000 --- a/lib/core/transactions/server-transaction.d.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { IncomingRequestMessage } from "../messages"; -import { Transport } from "../transport"; -import { Transaction } from "./transaction"; -import { TransactionState } from "./transaction-state"; -import { ServerTransactionUser } from "./transaction-user"; -/** - * Server Transaction. - * @remarks - * The server transaction is responsible for the delivery of requests to - * the TU and the reliable transmission of responses. It accomplishes - * this through a state machine. Server transactions are created by the - * core when a request is received, and transaction handling is desired - * for that request (this is not always the case). - * https://tools.ietf.org/html/rfc3261#section-17.2 - * @public - */ -export declare abstract class ServerTransaction extends Transaction { - private _request; - protected user: ServerTransactionUser; - protected constructor(_request: IncomingRequestMessage, transport: Transport, user: ServerTransactionUser, state: TransactionState, loggerCategory: string); - /** The incoming request the transaction handling. */ - readonly request: IncomingRequestMessage; - /** - * Receive incoming requests from the transport which match this transaction. - * @param request - The incoming request. - */ - abstract receiveRequest(request: IncomingRequestMessage): void; - /** - * Receive outgoing responses to this request from the transaction user. - * Responses will be delivered to the transport as necessary. - * @param statusCode - Response status code. - * @param response - Response. - */ - abstract receiveResponse(statusCode: number, response: string): void; -} -//# sourceMappingURL=server-transaction.d.ts.map \ No newline at end of file diff --git a/lib/core/transactions/server-transaction.d.ts.map b/lib/core/transactions/server-transaction.d.ts.map deleted file mode 100644 index 57bac9de4..000000000 --- a/lib/core/transactions/server-transaction.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"server-transaction.d.ts","sourceRoot":"","sources":["../../../src/core/transactions/server-transaction.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAE3D;;;;;;;;;;GAUG;AACH,8BAAsB,iBAAkB,SAAQ,WAAW;IAEvD,OAAO,CAAC,QAAQ;IAEhB,SAAS,CAAC,IAAI,EAAE,qBAAqB;IAHvC,SAAS,aACC,QAAQ,EAAE,sBAAsB,EACxC,SAAS,EAAE,SAAS,EACV,IAAI,EAAE,qBAAqB,EACrC,KAAK,EAAE,gBAAgB,EACvB,cAAc,EAAE,MAAM;IAWxB,qDAAqD;aACjD,OAAO,EAAI,sBAAsB;IAIrC;;;OAGG;aACa,cAAc,CAAC,OAAO,EAAE,sBAAsB,GAAG,IAAI;IAErE;;;;;OAKG;aACa,eAAe,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI;CAC5E"} \ No newline at end of file diff --git a/lib/core/transactions/server-transaction.js b/lib/core/transactions/server-transaction.js deleted file mode 100644 index 5aeb25887..000000000 --- a/lib/core/transactions/server-transaction.js +++ /dev/null @@ -1,34 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var transaction_1 = require("./transaction"); -/** - * Server Transaction. - * @remarks - * The server transaction is responsible for the delivery of requests to - * the TU and the reliable transmission of responses. It accomplishes - * this through a state machine. Server transactions are created by the - * core when a request is received, and transaction handling is desired - * for that request (this is not always the case). - * https://tools.ietf.org/html/rfc3261#section-17.2 - * @public - */ -var ServerTransaction = /** @class */ (function (_super) { - tslib_1.__extends(ServerTransaction, _super); - function ServerTransaction(_request, transport, user, state, loggerCategory) { - var _this = _super.call(this, transport, user, _request.viaBranch, state, loggerCategory) || this; - _this._request = _request; - _this.user = user; - return _this; - } - Object.defineProperty(ServerTransaction.prototype, "request", { - /** The incoming request the transaction handling. */ - get: function () { - return this._request; - }, - enumerable: true, - configurable: true - }); - return ServerTransaction; -}(transaction_1.Transaction)); -exports.ServerTransaction = ServerTransaction; diff --git a/lib/core/transactions/transaction-state.d.ts b/lib/core/transactions/transaction-state.d.ts deleted file mode 100644 index 7b8e5165b..000000000 --- a/lib/core/transactions/transaction-state.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -/** - * Transaction state. - * @public - */ -export declare enum TransactionState { - Accepted = "Accepted", - Calling = "Calling", - Completed = "Completed", - Confirmed = "Confirmed", - Proceeding = "Proceeding", - Terminated = "Terminated", - Trying = "Trying" -} -//# sourceMappingURL=transaction-state.d.ts.map \ No newline at end of file diff --git a/lib/core/transactions/transaction-state.d.ts.map b/lib/core/transactions/transaction-state.d.ts.map deleted file mode 100644 index 6cb37738a..000000000 --- a/lib/core/transactions/transaction-state.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"transaction-state.d.ts","sourceRoot":"","sources":["../../../src/core/transactions/transaction-state.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,oBAAY,gBAAgB;IAC1B,QAAQ,aAAa;IACrB,OAAO,YAAY;IACnB,SAAS,cAAc;IACvB,SAAS,cAAc;IACvB,UAAU,eAAe;IACzB,UAAU,eAAe;IACzB,MAAM,WAAW;CAClB"} \ No newline at end of file diff --git a/lib/core/transactions/transaction-state.js b/lib/core/transactions/transaction-state.js deleted file mode 100644 index 0fa2c6a78..000000000 --- a/lib/core/transactions/transaction-state.js +++ /dev/null @@ -1,16 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * Transaction state. - * @public - */ -var TransactionState; -(function (TransactionState) { - TransactionState["Accepted"] = "Accepted"; - TransactionState["Calling"] = "Calling"; - TransactionState["Completed"] = "Completed"; - TransactionState["Confirmed"] = "Confirmed"; - TransactionState["Proceeding"] = "Proceeding"; - TransactionState["Terminated"] = "Terminated"; - TransactionState["Trying"] = "Trying"; -})(TransactionState = exports.TransactionState || (exports.TransactionState = {})); diff --git a/lib/core/transactions/transaction-user.d.ts b/lib/core/transactions/transaction-user.d.ts deleted file mode 100644 index 4cfcb99d6..000000000 --- a/lib/core/transactions/transaction-user.d.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { TransportError } from "../exceptions"; -import { LoggerFactory } from "../log"; -import { IncomingResponseMessage } from "../messages"; -import { TransactionState } from "./transaction-state"; -/** - * Transaction User (TU). - * @remarks - * The layer of protocol processing that resides above the transaction layer. - * Transaction users include the UAC core, UAS core, and proxy core. - * https://tools.ietf.org/html/rfc3261#section-5 - * https://tools.ietf.org/html/rfc3261#section-6 - * @public - */ -export interface TransactionUser { - /** - * Logger factory. - */ - loggerFactory: LoggerFactory; - /** - * Callback for notification of transaction state changes. - * - * Not called when transaction is constructed, so there is - * no notification of entering the initial transaction state. - * Otherwise, called once for each transaction state change. - * State changes adhere to the following RFCs. - * https://tools.ietf.org/html/rfc3261#section-17 - * https://tools.ietf.org/html/rfc6026 - */ - onStateChange?: (newState: TransactionState) => void; - /** - * Callback for notification of a transport error. - * - * If a fatal transport error is reported by the transport layer - * (generally, due to fatal ICMP errors in UDP or connection failures in - * TCP), the condition MUST be treated as a 503 (Service Unavailable) - * status code. - * https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - * https://tools.ietf.org/html/rfc3261#section-17.1.4 - * https://tools.ietf.org/html/rfc3261#section-17.2.4 - * https://tools.ietf.org/html/rfc6026 - */ - onTransportError?: (error: TransportError) => void; -} -/** - * UAC Core Transaction User. - * @public - */ -export interface ClientTransactionUser extends TransactionUser { - /** - * Callback for request timeout error. - * - * When a timeout error is received from the transaction layer, it MUST be - * treated as if a 408 (Request Timeout) status code has been received. - * https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - * TU MUST be informed of a timeout. - * https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - */ - onRequestTimeout?: () => void; - /** - * Callback for delegation of valid response handling. - * - * Valid responses are passed up to the TU from the client transaction. - * https://tools.ietf.org/html/rfc3261#section-17.1 - */ - receiveResponse?: (response: IncomingResponseMessage) => void; -} -/** - * UAS Core Transaction User. - * @public - */ -export interface ServerTransactionUser extends TransactionUser { -} -//# sourceMappingURL=transaction-user.d.ts.map \ No newline at end of file diff --git a/lib/core/transactions/transaction-user.d.ts.map b/lib/core/transactions/transaction-user.d.ts.map deleted file mode 100644 index 5be62db34..000000000 --- a/lib/core/transactions/transaction-user.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"transaction-user.d.ts","sourceRoot":"","sources":["../../../src/core/transactions/transaction-user.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAC/C,OAAO,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AACvC,OAAO,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAIvD;;;;;;;;GAQG;AACH,MAAM,WAAW,eAAe;IAC9B;;OAEG;IACH,aAAa,EAAE,aAAa,CAAC;IAE7B;;;;;;;;;OASG;IACH,aAAa,CAAC,EAAE,CAAC,QAAQ,EAAE,gBAAgB,KAAK,IAAI,CAAC;IAErD;;;;;;;;;;;OAWG;IACH,gBAAgB,CAAC,EAAE,CAAC,KAAK,EAAE,cAAc,KAAK,IAAI,CAAC;CACpD;AAED;;;GAGG;AACH,MAAM,WAAW,qBAAsB,SAAQ,eAAe;IAC5D;;;;;;;;OAQG;IACH,gBAAgB,CAAC,EAAE,MAAM,IAAI,CAAC;IAE9B;;;;;OAKG;IACH,eAAe,CAAC,EAAE,CAAC,QAAQ,EAAE,uBAAuB,KAAK,IAAI,CAAC;CAC/D;AAED;;;GAGG;AACH,MAAM,WAAW,qBAAsB,SAAQ,eAAe;CAI7D"} \ No newline at end of file diff --git a/lib/core/transactions/transaction-user.js b/lib/core/transactions/transaction-user.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/core/transactions/transaction-user.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/core/transactions/transaction.d.ts b/lib/core/transactions/transaction.d.ts deleted file mode 100644 index 112be8c2c..000000000 --- a/lib/core/transactions/transaction.d.ts +++ /dev/null @@ -1,63 +0,0 @@ -/// -import { EventEmitter } from "events"; -import { TransportError } from "../exceptions"; -import { Logger } from "../log"; -import { Transport } from "../transport"; -import { TransactionState } from "./transaction-state"; -import { TransactionUser } from "./transaction-user"; -/** - * Transaction. - * @remarks - * SIP is a transactional protocol: interactions between components take - * place in a series of independent message exchanges. Specifically, a - * SIP transaction consists of a single request and any responses to - * that request, which include zero or more provisional responses and - * one or more final responses. In the case of a transaction where the - * request was an INVITE (known as an INVITE transaction), the - * transaction also includes the ACK only if the final response was not - * a 2xx response. If the response was a 2xx, the ACK is not considered - * part of the transaction. - * https://tools.ietf.org/html/rfc3261#section-17 - * @public - */ -export declare abstract class Transaction extends EventEmitter { - private _transport; - private _user; - private _id; - private _state; - protected logger: Logger; - protected constructor(_transport: Transport, _user: TransactionUser, _id: string, _state: TransactionState, loggerCategory: string); - /** - * Destructor. - * Once the transaction is in the "terminated" state, it is destroyed - * immediately and there is no need to call `dispose`. However, if a - * transaction needs to be ended prematurely, the transaction user may - * do so by calling this method (for example, perhaps the UA is shutting down). - * No state transition will occur upon calling this method, all outstanding - * transmission timers will be cancelled, and use of the transaction after - * calling `dispose` is undefined. - */ - dispose(): void; - /** Transaction id. */ - readonly id: string; - /** Transaction kind. Deprecated. */ - readonly kind: string; - /** Transaction state. */ - readonly state: TransactionState; - /** Transaction transport. */ - readonly transport: Transport; - /** Subscribe to 'stateChanged' event. */ - on(name: "stateChanged", callback: () => void): this; - protected logTransportError(error: TransportError, message: string): void; - protected abstract onTransportError(error: TransportError): void; - /** - * Pass message to transport for transmission. If transport fails, - * the transaction user is notified by callback to onTransportError(). - * @returns - * Rejects with `TransportError` if transport fails. - */ - protected send(message: string): Promise; - protected setState(state: TransactionState): void; - protected typeToString(): string; -} -//# sourceMappingURL=transaction.d.ts.map \ No newline at end of file diff --git a/lib/core/transactions/transaction.d.ts.map b/lib/core/transactions/transaction.d.ts.map deleted file mode 100644 index 00bdcb718..000000000 --- a/lib/core/transactions/transaction.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"transaction.d.ts","sourceRoot":"","sources":["../../../src/core/transactions/transaction.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAEtC,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAC/C,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAErD;;;;;;;;;;;;;;GAcG;AACH,8BAAsB,WAAY,SAAQ,YAAY;IAIlD,OAAO,CAAC,UAAU;IAClB,OAAO,CAAC,KAAK;IACb,OAAO,CAAC,GAAG;IACX,OAAO,CAAC,MAAM;IANhB,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC;IAEzB,SAAS,aACC,UAAU,EAAE,SAAS,EACrB,KAAK,EAAE,eAAe,EACtB,GAAG,EAAE,MAAM,EACX,MAAM,EAAE,gBAAgB,EAChC,cAAc,EAAE,MAAM;IAOxB;;;;;;;;;OASG;IACI,OAAO,IAAI,IAAI;IAItB,sBAAsB;aAClB,EAAE,EAAI,MAAM;IAIhB,oCAAoC;aAChC,IAAI,EAAI,MAAM;IAIlB,yBAAyB;aACrB,KAAK,EAAI,gBAAgB;IAI7B,6BAA6B;aACzB,SAAS,EAAI,SAAS;IAI1B,yCAAyC;IAClC,EAAE,CAAC,IAAI,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,IAAI,GAAG,IAAI;IAG3D,SAAS,CAAC,iBAAiB,CAAC,KAAK,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI;IAMzE,SAAS,CAAC,QAAQ,CAAC,gBAAgB,CAAC,KAAK,EAAE,cAAc,GAAG,IAAI;IAEhE;;;;;OAKG;IACH,SAAS,CAAC,IAAI,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAoB9C,SAAS,CAAC,QAAQ,CAAC,KAAK,EAAE,gBAAgB,GAAG,IAAI;IASjD,SAAS,CAAC,YAAY,IAAI,MAAM;CAGjC"} \ No newline at end of file diff --git a/lib/core/transactions/transaction.js b/lib/core/transactions/transaction.js deleted file mode 100644 index f0d86f0c4..000000000 --- a/lib/core/transactions/transaction.js +++ /dev/null @@ -1,124 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var events_1 = require("events"); -var exceptions_1 = require("../exceptions"); -/** - * Transaction. - * @remarks - * SIP is a transactional protocol: interactions between components take - * place in a series of independent message exchanges. Specifically, a - * SIP transaction consists of a single request and any responses to - * that request, which include zero or more provisional responses and - * one or more final responses. In the case of a transaction where the - * request was an INVITE (known as an INVITE transaction), the - * transaction also includes the ACK only if the final response was not - * a 2xx response. If the response was a 2xx, the ACK is not considered - * part of the transaction. - * https://tools.ietf.org/html/rfc3261#section-17 - * @public - */ -var Transaction = /** @class */ (function (_super) { - tslib_1.__extends(Transaction, _super); - function Transaction(_transport, _user, _id, _state, loggerCategory) { - var _this = _super.call(this) || this; - _this._transport = _transport; - _this._user = _user; - _this._id = _id; - _this._state = _state; - _this.logger = _user.loggerFactory.getLogger(loggerCategory, _id); - _this.logger.debug("Constructing " + _this.typeToString() + " with id " + _this.id + "."); - return _this; - } - /** - * Destructor. - * Once the transaction is in the "terminated" state, it is destroyed - * immediately and there is no need to call `dispose`. However, if a - * transaction needs to be ended prematurely, the transaction user may - * do so by calling this method (for example, perhaps the UA is shutting down). - * No state transition will occur upon calling this method, all outstanding - * transmission timers will be cancelled, and use of the transaction after - * calling `dispose` is undefined. - */ - Transaction.prototype.dispose = function () { - this.logger.debug("Destroyed " + this.typeToString() + " with id " + this.id + "."); - }; - Object.defineProperty(Transaction.prototype, "id", { - /** Transaction id. */ - get: function () { - return this._id; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Transaction.prototype, "kind", { - /** Transaction kind. Deprecated. */ - get: function () { - throw new Error("Invalid kind."); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Transaction.prototype, "state", { - /** Transaction state. */ - get: function () { - return this._state; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Transaction.prototype, "transport", { - /** Transaction transport. */ - get: function () { - return this._transport; - }, - enumerable: true, - configurable: true - }); - Transaction.prototype.on = function (name, callback) { return _super.prototype.on.call(this, name, callback); }; - Transaction.prototype.logTransportError = function (error, message) { - this.logger.error(error.message); - this.logger.error("Transport error occurred in " + this.typeToString() + " with id " + this.id + "."); - this.logger.error(message); - }; - /** - * Pass message to transport for transmission. If transport fails, - * the transaction user is notified by callback to onTransportError(). - * @returns - * Rejects with `TransportError` if transport fails. - */ - Transaction.prototype.send = function (message) { - var _this = this; - return this.transport.send(message).catch(function (error) { - // FIXME: Transport is not, yet, typed and it is not clear - // yet what send() may or may not send our way. So for now, - // make sure we convert it to a TransportError if need be. - if (error instanceof exceptions_1.TransportError) { - _this.onTransportError(error); - return; - } - var transportError; - if (error && typeof error.message === "string") { - transportError = new exceptions_1.TransportError(error.message); - } - else { - transportError = new exceptions_1.TransportError(); - } - _this.onTransportError(transportError); - throw transportError; - }); - }; - Transaction.prototype.setState = function (state) { - this.logger.debug("State change to \"" + state + "\" on " + this.typeToString() + " with id " + this.id + "."); - this._state = state; - if (this._user.onStateChange) { - this._user.onStateChange(state); - } - this.emit("stateChanged"); - }; - Transaction.prototype.typeToString = function () { - return "UnknownType"; - }; - return Transaction; -}(events_1.EventEmitter)); -exports.Transaction = Transaction; diff --git a/lib/core/transport.d.ts b/lib/core/transport.d.ts deleted file mode 100644 index cb5f51bd6..000000000 --- a/lib/core/transport.d.ts +++ /dev/null @@ -1,77 +0,0 @@ -/// -import { EventEmitter } from "events"; -import { Logger } from "./log"; -/** - * Transport. - * @remarks - * Abstract transport layer base class. - * @public - */ -export declare abstract class Transport extends EventEmitter { - server: any; - protected logger: Logger; - /** - * Constructor - * @param logger - Logger. - * @param options - Options bucket. - */ - constructor(logger: Logger, options: any); - /** - * Returns the promise designated by the child layer then emits a connected event. - * Automatically emits an event upon resolution, unless overrideEvent is set. If you - * override the event in this fashion, you should emit it in your implementation of connectPromise - * @param options - Options bucket. - */ - connect(options?: any): Promise; - /** - * Returns true if the transport is connected - */ - abstract isConnected(): boolean; - /** - * Sends a message then emits a 'messageSent' event. Automatically emits an - * event upon resolution, unless data.overrideEvent is set. If you override - * the event in this fashion, you should emit it in your implementation of sendPromise - * @param msg - Message. - * @param options - Options bucket. - */ - send(msg: string, options?: any): Promise; - /** - * Returns the promise designated by the child layer then emits a - * disconnected event. Automatically emits an event upon resolution, - * unless overrideEvent is set. If you override the event in this fashion, - * you should emit it in your implementation of disconnectPromise - * @param options - Options bucket - */ - disconnect(options?: any): Promise; - afterConnected(callback: () => void): void; - /** - * Returns a promise which resolves once the UA is connected. DEPRECATION WARNING: just use afterConnected() - */ - waitForConnected(): Promise; - /** - * Called by connect, must return a promise - * promise must resolve to an object. object supports 1 parameter: overrideEvent - Boolean - * @param options - Options bucket. - */ - protected abstract connectPromise(options: any): Promise; - /** - * Called by send, must return a promise - * promise must resolve to an object. object supports 2 parameters: msg - string (mandatory) - * and overrideEvent - Boolean (optional) - * @param msg - Message. - * @param options - Options bucket. - */ - protected abstract sendPromise(msg: string, options?: any): Promise; - /** - * Called by disconnect, must return a promise - * promise must resolve to an object. object supports 1 parameter: overrideEvent - Boolean - * @param options - Options bucket. - */ - protected abstract disconnectPromise(options: any): Promise; - /** - * To be called when a message is received - * @param e - Event - */ - protected abstract onMessage(e: any): void; -} -//# sourceMappingURL=transport.d.ts.map \ No newline at end of file diff --git a/lib/core/transport.d.ts.map b/lib/core/transport.d.ts.map deleted file mode 100644 index 09e8f1ed6..000000000 --- a/lib/core/transport.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"transport.d.ts","sourceRoot":"","sources":["../../src/core/transport.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAEtC,OAAO,EAAE,MAAM,EAAE,MAAM,OAAO,CAAC;AAE/B;;;;;GAKG;AACH,8BAAsB,SAAU,SAAQ,YAAY;IAC3C,MAAM,EAAE,GAAG,CAAC;IACnB,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC;IAEzB;;;;OAIG;gBACS,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG;IAKxC;;;;;OAKG;IACI,OAAO,CAAC,OAAO,GAAE,GAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;IAQhD;;OAEG;aACa,WAAW,IAAI,OAAO;IAEtC;;;;;;OAMG;IACI,IAAI,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,GAAE,GAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;IAQ1D;;;;;;OAMG;IACI,UAAU,CAAC,OAAO,GAAE,GAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;IAQ5C,cAAc,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,IAAI;IAQjD;;OAEG;IACI,gBAAgB,IAAI,OAAO,CAAC,IAAI,CAAC;IAOxC;;;;OAIG;IACH,SAAS,CAAC,QAAQ,CAAC,cAAc,CAAC,OAAO,EAAE,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC;IAE7D;;;;;;OAMG;IACH,SAAS,CAAC,QAAQ,CAAC,WAAW,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC;IAExE;;;;OAIG;IACH,SAAS,CAAC,QAAQ,CAAC,iBAAiB,CAAC,OAAO,EAAE,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC;IAEhE;;;OAGG;IACH,SAAS,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC,EAAE,GAAG,GAAG,IAAI;CAC3C"} \ No newline at end of file diff --git a/lib/core/transport.js b/lib/core/transport.js deleted file mode 100644 index c62d62adc..000000000 --- a/lib/core/transport.js +++ /dev/null @@ -1,91 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var events_1 = require("events"); -/** - * Transport. - * @remarks - * Abstract transport layer base class. - * @public - */ -var Transport = /** @class */ (function (_super) { - tslib_1.__extends(Transport, _super); - /** - * Constructor - * @param logger - Logger. - * @param options - Options bucket. - */ - function Transport(logger, options) { - var _this = _super.call(this) || this; - _this.logger = logger; - return _this; - } - /** - * Returns the promise designated by the child layer then emits a connected event. - * Automatically emits an event upon resolution, unless overrideEvent is set. If you - * override the event in this fashion, you should emit it in your implementation of connectPromise - * @param options - Options bucket. - */ - Transport.prototype.connect = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - return this.connectPromise(options).then(function (data) { - if (!data.overrideEvent) { - _this.emit("connected"); - } - }); - }; - /** - * Sends a message then emits a 'messageSent' event. Automatically emits an - * event upon resolution, unless data.overrideEvent is set. If you override - * the event in this fashion, you should emit it in your implementation of sendPromise - * @param msg - Message. - * @param options - Options bucket. - */ - Transport.prototype.send = function (msg, options) { - var _this = this; - if (options === void 0) { options = {}; } - return this.sendPromise(msg).then(function (data) { - if (!data.overrideEvent) { - _this.emit("messageSent", data.msg); - } - }); - }; - /** - * Returns the promise designated by the child layer then emits a - * disconnected event. Automatically emits an event upon resolution, - * unless overrideEvent is set. If you override the event in this fashion, - * you should emit it in your implementation of disconnectPromise - * @param options - Options bucket - */ - Transport.prototype.disconnect = function (options) { - var _this = this; - if (options === void 0) { options = {}; } - return this.disconnectPromise(options).then(function (data) { - if (!data.overrideEvent) { - _this.emit("disconnected"); - } - }); - }; - Transport.prototype.afterConnected = function (callback) { - if (this.isConnected()) { - callback(); - } - else { - this.once("connected", callback); - } - }; - /** - * Returns a promise which resolves once the UA is connected. DEPRECATION WARNING: just use afterConnected() - */ - Transport.prototype.waitForConnected = function () { - var _this = this; - // tslint:disable-next-line:no-console - console.warn("DEPRECATION WARNING Transport.waitForConnected(): use afterConnected() instead"); - return new Promise(function (resolve) { - _this.afterConnected(resolve); - }); - }; - return Transport; -}(events_1.EventEmitter)); -exports.Transport = Transport; diff --git a/lib/core/user-agent-core/allowed-methods.d.ts b/lib/core/user-agent-core/allowed-methods.d.ts deleted file mode 100644 index 25b377a6d..000000000 --- a/lib/core/user-agent-core/allowed-methods.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -/** - * FIXME: TODO: Should be configurable/variable. - */ -export declare const AllowedMethods: string[]; -//# sourceMappingURL=allowed-methods.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agent-core/allowed-methods.d.ts.map b/lib/core/user-agent-core/allowed-methods.d.ts.map deleted file mode 100644 index 236310557..000000000 --- a/lib/core/user-agent-core/allowed-methods.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"allowed-methods.d.ts","sourceRoot":"","sources":["../../../src/core/user-agent-core/allowed-methods.ts"],"names":[],"mappings":"AAEA;;GAEG;AACH,eAAO,MAAM,cAAc,UAa1B,CAAC"} \ No newline at end of file diff --git a/lib/core/user-agent-core/allowed-methods.js b/lib/core/user-agent-core/allowed-methods.js deleted file mode 100644 index 4a8037ebd..000000000 --- a/lib/core/user-agent-core/allowed-methods.js +++ /dev/null @@ -1,20 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var messages_1 = require("../messages"); -/** - * FIXME: TODO: Should be configurable/variable. - */ -exports.AllowedMethods = [ - messages_1.C.ACK, - messages_1.C.BYE, - messages_1.C.CANCEL, - messages_1.C.INFO, - messages_1.C.INVITE, - messages_1.C.MESSAGE, - messages_1.C.NOTIFY, - messages_1.C.OPTIONS, - messages_1.C.PRACK, - messages_1.C.REFER, - messages_1.C.REGISTER, - messages_1.C.SUBSCRIBE -]; diff --git a/lib/core/user-agent-core/index.d.ts b/lib/core/user-agent-core/index.d.ts deleted file mode 100644 index 1dd187fa5..000000000 --- a/lib/core/user-agent-core/index.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -export * from "./user-agent-core"; -export * from "./user-agent-core-configuration"; -export * from "./user-agent-core-delegate"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agent-core/index.d.ts.map b/lib/core/user-agent-core/index.d.ts.map deleted file mode 100644 index 3251b93f2..000000000 --- a/lib/core/user-agent-core/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/user-agent-core/index.ts"],"names":[],"mappings":"AAAA,cAAc,mBAAmB,CAAC;AAClC,cAAc,iCAAiC,CAAC;AAChD,cAAc,4BAA4B,CAAC"} \ No newline at end of file diff --git a/lib/core/user-agent-core/index.js b/lib/core/user-agent-core/index.js deleted file mode 100644 index e87aff642..000000000 --- a/lib/core/user-agent-core/index.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -tslib_1.__exportStar(require("./user-agent-core"), exports); diff --git a/lib/core/user-agent-core/user-agent-core-configuration.d.ts b/lib/core/user-agent-core/user-agent-core-configuration.d.ts deleted file mode 100644 index 0a00f30c8..000000000 --- a/lib/core/user-agent-core/user-agent-core-configuration.d.ts +++ /dev/null @@ -1,97 +0,0 @@ -import { LoggerFactory } from "../log"; -import { DigestAuthentication, URI } from "../messages"; -import { Transport } from "../transport"; -/** - * Contact. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-8.1.1.8 - * This is ported from UA.contact. - * FIXME: TODO: This is not a great rep for Contact - * and is used in a kinda hacky way herein. - * @public - */ -export interface Contact { - pubGruu: URI | undefined; - tempGruu: URI | undefined; - uri: URI; - toString: (options?: any) => string; -} -/** - * User Agent Core configuration. - * @public - */ -export interface UserAgentCoreConfiguration { - /** - * Address-of-Record (AOR). - * @remarks - * https://tools.ietf.org/html/rfc3261#section-6 - */ - aor: URI; - /** - * Contact. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-8.1.1.8 - */ - contact: Contact; - /** - * From header display name. - */ - displayName: string; - /** - * Logger factory. - */ - loggerFactory: LoggerFactory; - /** - * Force Via header field transport to TCP. - */ - hackViaTcp: boolean; - /** - * Preloaded route set. - */ - routeSet: Array; - /** - * Unique instance id. - */ - sipjsId: string; - /** - * Option tags of supported SIP extenstions. - */ - supportedOptionTags: Array; - /** - * Option tags of supported SIP extenstions. - * Used in resposnes. - * @remarks - * FIXME: Make this go away. - */ - supportedOptionTagsResponse: Array; - /** - * User-Agent header field value. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-20.41 - */ - userAgentHeaderFieldValue: string | undefined; - /** - * Force use of "rport" Via header field parameter. - * @remarks - * https://www.ietf.org/rfc/rfc3581.txt - */ - viaForceRport: boolean; - /** - * Via header field host name or network address. - * @remarks - * The Via header field indicates the path taken by the request so far - * and indicates the path that should be followed in routing responses. - */ - viaHost: string; - /** - * DEPRECATED - * Authentication factory function. - */ - authenticationFactory(): DigestAuthentication | undefined; - /** - * DEPRECATED: This is a hack to get around `Transport` - * requiring the `UA` to start for construction. - */ - transportAccessor(): Transport | undefined; -} -//# sourceMappingURL=user-agent-core-configuration.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agent-core/user-agent-core-configuration.d.ts.map b/lib/core/user-agent-core/user-agent-core-configuration.d.ts.map deleted file mode 100644 index 0119e1d1c..000000000 --- a/lib/core/user-agent-core/user-agent-core-configuration.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"user-agent-core-configuration.d.ts","sourceRoot":"","sources":["../../../src/core/user-agent-core/user-agent-core-configuration.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AACvC,OAAO,EAAE,oBAAoB,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AACxD,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC;;;;;;;;GAQG;AACH,MAAM,WAAW,OAAO;IACtB,OAAO,EAAE,GAAG,GAAG,SAAS,CAAC;IACzB,QAAQ,EAAE,GAAG,GAAG,SAAS,CAAC;IAC1B,GAAG,EAAE,GAAG,CAAC;IACT,QAAQ,EAAE,CAAC,OAAO,CAAC,EAAE,GAAG,KAAK,MAAM,CAAC;CACrC;AAED;;;GAGG;AACH,MAAM,WAAW,0BAA0B;IACzC;;;;OAIG;IACH,GAAG,EAAE,GAAG,CAAC;IAET;;;;OAIG;IACH,OAAO,EAAE,OAAO,CAAC;IAEjB;;OAEG;IACH,WAAW,EAAE,MAAM,CAAC;IAEpB;;OAEG;IACH,aAAa,EAAE,aAAa,CAAC;IAE7B;;OAEG;IACH,UAAU,EAAE,OAAO,CAAC;IAEpB;;OAEG;IACH,QAAQ,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAExB;;OAEG;IACH,OAAO,EAAE,MAAM,CAAC;IAEhB;;OAEG;IACH,mBAAmB,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAEnC;;;;;OAKG;IACH,2BAA2B,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAE3C;;;;OAIG;IACH,yBAAyB,EAAE,MAAM,GAAG,SAAS,CAAC;IAE9C;;;;OAIG;IACH,aAAa,EAAE,OAAO,CAAC;IAEvB;;;;;OAKG;IACH,OAAO,EAAE,MAAM,CAAC;IAEhB;;;OAGG;IACH,qBAAqB,IAAI,oBAAoB,GAAG,SAAS,CAAC;IAE1D;;;OAGG;IACH,iBAAiB,IAAI,SAAS,GAAG,SAAS,CAAC;CAC5C"} \ No newline at end of file diff --git a/lib/core/user-agent-core/user-agent-core-configuration.js b/lib/core/user-agent-core/user-agent-core-configuration.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/core/user-agent-core/user-agent-core-configuration.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/core/user-agent-core/user-agent-core-delegate.d.ts b/lib/core/user-agent-core/user-agent-core-delegate.d.ts deleted file mode 100644 index 598f7776f..000000000 --- a/lib/core/user-agent-core/user-agent-core-delegate.d.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { IncomingInviteRequest, IncomingMessageRequest, IncomingNotifyRequest, IncomingReferRequest, IncomingRegisterRequest, IncomingSubscribeRequest } from "../messages"; -/** - * User Agent Core delegate. - * @public - */ -export interface UserAgentCoreDelegate { - /** - * Receive INVITE request. - * @param request - Incoming INVITE request. - */ - onInvite?(request: IncomingInviteRequest): void; - /** - * Receive MESSAGE request. - * @param request - Incoming MESSAGE request. - */ - onMessage?(request: IncomingMessageRequest): void; - /** - * DEPRECATED. Receive NOTIFY request. - * @param message - Incoming NOTIFY request. - */ - onNotify?(request: IncomingNotifyRequest): void; - /** - * Receive REFER request. - * @param request - Incoming REFER request. - */ - onRefer?(request: IncomingReferRequest): void; - /** - * Receive REGISTER request. - * @param request - Incoming REGISTER request. - */ - onRegister?(request: IncomingRegisterRequest): void; - /** - * Receive SUBSCRIBE request. - * @param request - Incoming SUBSCRIBE request. - */ - onSubscribe?(request: IncomingSubscribeRequest): void; -} -//# sourceMappingURL=user-agent-core-delegate.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agent-core/user-agent-core-delegate.d.ts.map b/lib/core/user-agent-core/user-agent-core-delegate.d.ts.map deleted file mode 100644 index e7d8950bd..000000000 --- a/lib/core/user-agent-core/user-agent-core-delegate.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"user-agent-core-delegate.d.ts","sourceRoot":"","sources":["../../../src/core/user-agent-core/user-agent-core-delegate.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,qBAAqB,EACrB,sBAAsB,EACtB,qBAAqB,EACrB,oBAAoB,EACpB,uBAAuB,EACvB,wBAAwB,EACzB,MAAM,aAAa,CAAC;AAErB;;;GAGG;AACH,MAAM,WAAW,qBAAqB;IACpC;;;OAGG;IACH,QAAQ,CAAC,CAAC,OAAO,EAAE,qBAAqB,GAAG,IAAI,CAAC;IAEhD;;;OAGG;IACH,SAAS,CAAC,CAAC,OAAO,EAAE,sBAAsB,GAAG,IAAI,CAAC;IAElD;;;OAGG;IACH,QAAQ,CAAC,CAAC,OAAO,EAAE,qBAAqB,GAAG,IAAI,CAAC;IAEhD;;;OAGG;IACH,OAAO,CAAC,CAAC,OAAO,EAAE,oBAAoB,GAAG,IAAI,CAAC;IAE9C;;;OAGG;IACH,UAAU,CAAC,CAAC,OAAO,EAAE,uBAAuB,GAAG,IAAI,CAAC;IAEpD;;;OAGG;IACH,WAAW,CAAC,CAAC,OAAO,EAAE,wBAAwB,GAAG,IAAI,CAAC;CACvD"} \ No newline at end of file diff --git a/lib/core/user-agent-core/user-agent-core-delegate.js b/lib/core/user-agent-core/user-agent-core-delegate.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/core/user-agent-core/user-agent-core-delegate.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/core/user-agent-core/user-agent-core.d.ts b/lib/core/user-agent-core/user-agent-core.d.ts deleted file mode 100644 index 8475541a9..000000000 --- a/lib/core/user-agent-core/user-agent-core.d.ts +++ /dev/null @@ -1,180 +0,0 @@ -import { Dialog } from "../dialogs"; -import { LoggerFactory } from "../log"; -import { Body, IncomingRequestMessage, IncomingResponseMessage, OutgoingInviteRequest, OutgoingInviteRequestDelegate, OutgoingMessageRequest, OutgoingPublishRequest, OutgoingRegisterRequest, OutgoingRequest, OutgoingRequestDelegate, OutgoingRequestMessage, OutgoingRequestMessageOptions, OutgoingResponse, OutgoingSubscribeRequest, OutgoingSubscribeRequestDelegate, ResponseOptions, URI } from "../messages"; -import { Transport } from "../transport"; -import { SubscribeUserAgentClient, UserAgentClient, UserAgentServer } from "../user-agents"; -import { UserAgentCoreConfiguration } from "./user-agent-core-configuration"; -import { UserAgentCoreDelegate } from "./user-agent-core-delegate"; -/** - * User Agent Core. - * @remarks - * Core designates the functions specific to a particular type - * of SIP entity, i.e., specific to either a stateful or stateless - * proxy, a user agent or registrar. All cores, except those for - * the stateless proxy, are transaction users. - * https://tools.ietf.org/html/rfc3261#section-6 - * - * UAC Core: The set of processing functions required of a UAC that - * reside above the transaction and transport layers. - * https://tools.ietf.org/html/rfc3261#section-6 - * - * UAS Core: The set of processing functions required at a UAS that - * resides above the transaction and transport layers. - * https://tools.ietf.org/html/rfc3261#section-6 - * @public - */ -export declare class UserAgentCore { - /** Configuration. */ - configuration: UserAgentCoreConfiguration; - /** Delegate. */ - delegate: UserAgentCoreDelegate; - /** Dialogs. */ - dialogs: Map; - /** Subscribers. */ - subscribers: Map; - /** UACs. */ - userAgentClients: Map; - /** UASs. */ - userAgentServers: Map; - private logger; - /** - * Constructor. - * @param configuration - Configuration. - * @param delegate - Delegate. - */ - constructor(configuration: UserAgentCoreConfiguration, delegate?: UserAgentCoreDelegate); - /** Destructor. */ - dispose(): void; - /** Reset. */ - reset(): void; - /** Logger factory. */ - readonly loggerFactory: LoggerFactory; - /** Transport. */ - readonly transport: Transport; - /** - * Send INVITE. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - invite(request: OutgoingRequestMessage, delegate?: OutgoingInviteRequestDelegate): OutgoingInviteRequest; - /** - * Send MESSAGE. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - message(request: OutgoingRequestMessage, delegate?: OutgoingRequestDelegate): OutgoingMessageRequest; - /** - * Send PUBLISH. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - publish(request: OutgoingRequestMessage, delegate?: OutgoingRequestDelegate): OutgoingPublishRequest; - /** - * Send REGISTER. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - register(request: OutgoingRequestMessage, delegate?: OutgoingRequestDelegate): OutgoingRegisterRequest; - /** - * Send SUBSCRIBE. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - subscribe(request: OutgoingRequestMessage, delegate?: OutgoingSubscribeRequestDelegate): OutgoingSubscribeRequest; - /** - * Send a request. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - request(request: OutgoingRequestMessage, delegate?: OutgoingRequestDelegate): OutgoingRequest; - /** - * Outgoing request message factory function. - * @param method - Method. - * @param requestURI - Request-URI. - * @param fromURI - From URI. - * @param toURI - To URI. - * @param options - Request options. - * @param extraHeaders - Extra headers to add. - * @param body - Message body. - */ - makeOutgoingRequestMessage(method: string, requestURI: URI, fromURI: URI, toURI: URI, options: OutgoingRequestMessageOptions, extraHeaders?: Array, body?: Body): OutgoingRequestMessage; - /** - * Handle an incoming request message from the transport. - * @param message - Incoming request message from transport layer. - */ - receiveIncomingRequestFromTransport(message: IncomingRequestMessage): void; - /** - * Handle an incoming response message from the transport. - * @param message - Incoming response message from transport layer. - */ - receiveIncomingResponseFromTransport(message: IncomingResponseMessage): void; - /** - * A stateless UAS is a UAS that does not maintain transaction state. - * It replies to requests normally, but discards any state that would - * ordinarily be retained by a UAS after a response has been sent. If a - * stateless UAS receives a retransmission of a request, it regenerates - * the response and re-sends it, just as if it were replying to the first - * instance of the request. A UAS cannot be stateless unless the request - * processing for that method would always result in the same response - * if the requests are identical. This rules out stateless registrars, - * for example. Stateless UASs do not use a transaction layer; they - * receive requests directly from the transport layer and send responses - * directly to the transport layer. - * https://tools.ietf.org/html/rfc3261#section-8.2.7 - * @param message - Incoming request message to reply to. - * @param statusCode - Status code to reply with. - */ - replyStateless(message: IncomingRequestMessage, options: ResponseOptions): OutgoingResponse; - /** - * In Section 18.2.1, replace the last paragraph with: - * - * Next, the server transport attempts to match the request to a - * server transaction. It does so using the matching rules described - * in Section 17.2.3. If a matching server transaction is found, the - * request is passed to that transaction for processing. If no match - * is found, the request is passed to the core, which may decide to - * construct a new server transaction for that request. - * https://tools.ietf.org/html/rfc6026#section-8.10 - * @param message - Incoming request message from transport layer. - */ - private receiveRequestFromTransport; - /** - * UAC and UAS procedures depend strongly on two factors. First, based - * on whether the request or response is inside or outside of a dialog, - * and second, based on the method of a request. Dialogs are discussed - * thoroughly in Section 12; they represent a peer-to-peer relationship - * between user agents and are established by specific SIP methods, such - * as INVITE. - * @param message - Incoming request message. - */ - private receiveRequest; - /** - * Once a dialog has been established between two UAs, either of them - * MAY initiate new transactions as needed within the dialog. The UA - * sending the request will take the UAC role for the transaction. The - * UA receiving the request will take the UAS role. Note that these may - * be different roles than the UAs held during the transaction that - * established the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.2 - * @param message - Incoming request message. - */ - private receiveInsideDialogRequest; - /** - * Assuming all of the checks in the previous subsections are passed, - * the UAS processing becomes method-specific. - * https://tools.ietf.org/html/rfc3261#section-8.2.5 - * @param message - Incoming request message. - */ - private receiveOutsideDialogRequest; - /** - * Responses are first processed by the transport layer and then passed - * up to the transaction layer. The transaction layer performs its - * processing and then passes the response up to the TU. The majority - * of response processing in the TU is method specific. However, there - * are some general behaviors independent of the method. - * https://tools.ietf.org/html/rfc3261#section-8.1.3 - * @param message - Incoming response message from transport layer. - */ - private receiveResponseFromTransport; -} -//# sourceMappingURL=user-agent-core.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agent-core/user-agent-core.d.ts.map b/lib/core/user-agent-core/user-agent-core.d.ts.map deleted file mode 100644 index f6d897b7c..000000000 --- a/lib/core/user-agent-core/user-agent-core.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"user-agent-core.d.ts","sourceRoot":"","sources":["../../../src/core/user-agent-core/user-agent-core.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AACpC,OAAO,EAAU,aAAa,EAAE,MAAM,QAAQ,CAAC;AAC/C,OAAO,EACL,IAAI,EAGJ,sBAAsB,EACtB,uBAAuB,EACvB,qBAAqB,EACrB,6BAA6B,EAC7B,sBAAsB,EACtB,sBAAsB,EACtB,uBAAuB,EACvB,eAAe,EACf,uBAAuB,EACvB,sBAAsB,EACtB,6BAA6B,EAC7B,gBAAgB,EAChB,wBAAwB,EACxB,gCAAgC,EAChC,eAAe,EACf,GAAG,EACJ,MAAM,aAAa,CAAC;AAMrB,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAUL,wBAAwB,EAExB,eAAe,EACf,eAAe,EAChB,MAAM,gBAAgB,CAAC;AAExB,OAAO,EAAE,0BAA0B,EAAE,MAAM,iCAAiC,CAAC;AAC7E,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AAUnE;;;;;;;;;;;;;;;;;GAiBG;AACH,qBAAa,aAAa;IACxB,qBAAqB;IACd,aAAa,EAAE,0BAA0B,CAAC;IACjD,gBAAgB;IACT,QAAQ,EAAE,qBAAqB,CAAC;IACvC,eAAe;IACR,OAAO,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACpC,mBAAmB;IACZ,WAAW,EAAE,GAAG,CAAC,MAAM,EAAE,wBAAwB,CAAC,CAAC;IAC1D,YAAY;IACL,gBAAgB,+BAAsC;IAC7D,YAAY;IACL,gBAAgB,+BAAsC;IAE7D,OAAO,CAAC,MAAM,CAAS;IAEvB;;;;OAIG;gBAED,aAAa,EAAE,0BAA0B,EACzC,QAAQ,GAAE,qBAA0B;IAStC,kBAAkB;IACX,OAAO,IAAI,IAAI;IAItB,aAAa;IACN,KAAK,IAAI,IAAI;IAWpB,sBAAsB;aAClB,aAAa,EAAI,aAAa;IAIlC,iBAAiB;aACb,SAAS,EAAI,SAAS;IAQ1B;;;;OAIG;IACI,MAAM,CACX,OAAO,EAAE,sBAAsB,EAC/B,QAAQ,CAAC,EAAE,6BAA6B,GACvC,qBAAqB;IAIxB;;;;OAIG;IACI,OAAO,CACZ,OAAO,EAAE,sBAAsB,EAC/B,QAAQ,CAAC,EAAE,uBAAuB,GACjC,sBAAsB;IAIzB;;;;OAIG;IACI,OAAO,CACZ,OAAO,EAAE,sBAAsB,EAC/B,QAAQ,CAAC,EAAE,uBAAuB,GACjC,sBAAsB;IAIzB;;;;OAIG;IACI,QAAQ,CACb,OAAO,EAAE,sBAAsB,EAC/B,QAAQ,CAAC,EAAE,uBAAuB,GACjC,uBAAuB;IAI1B;;;;OAIG;IACI,SAAS,CACd,OAAO,EAAE,sBAAsB,EAC/B,QAAQ,CAAC,EAAE,gCAAgC,GAC1C,wBAAwB;IAI3B;;;;OAIG;IACI,OAAO,CACZ,OAAO,EAAE,sBAAsB,EAC/B,QAAQ,CAAC,EAAE,uBAAuB,GACjC,eAAe;IAIlB;;;;;;;;;OASG;IACI,0BAA0B,CAC/B,MAAM,EAAE,MAAM,EACd,UAAU,EAAE,GAAG,EACf,OAAO,EAAE,GAAG,EACZ,KAAK,EAAE,GAAG,EACV,OAAO,EAAE,6BAA6B,EACtC,YAAY,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,EAC5B,IAAI,CAAC,EAAE,IAAI,GACV,sBAAsB;IA6CzB;;;OAGG;IACI,mCAAmC,CAAC,OAAO,EAAE,sBAAsB,GAAG,IAAI;IAIjF;;;OAGG;IACI,oCAAoC,CAAC,OAAO,EAAE,uBAAuB,GAAG,IAAI;IAInF;;;;;;;;;;;;;;;OAeG;IACI,cAAc,CACnB,OAAO,EAAE,sBAAsB,EAC/B,OAAO,EAAE,eAAe,GACvB,gBAAgB;IASnB;;;;;;;;;;;OAWG;IACH,OAAO,CAAC,2BAA2B;IA8HnC;;;;;;;;OAQG;IACH,OAAO,CAAC,cAAc;IAgJtB;;;;;;;;;OASG;IACH,OAAO,CAAC,0BAA0B;IAsIlC;;;;;OAKG;IACH,OAAO,CAAC,2BAA2B;IA0HnC;;;;;;;;OAQG;IACH,OAAO,CAAC,4BAA4B;CA2DrC"} \ No newline at end of file diff --git a/lib/core/user-agent-core/user-agent-core.js b/lib/core/user-agent-core/user-agent-core.js deleted file mode 100644 index d4dbf8030..000000000 --- a/lib/core/user-agent-core/user-agent-core.js +++ /dev/null @@ -1,803 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var messages_1 = require("../messages"); -var transactions_1 = require("../transactions"); -var user_agents_1 = require("../user-agents"); -var allowed_methods_1 = require("./allowed-methods"); -/** - * This is ported from UA.C.ACCEPTED_BODY_TYPES. - * FIXME: TODO: Should be configurable/variable. - */ -var acceptedBodyTypes = [ - "application/sdp", - "application/dtmf-relay" -]; -/** - * User Agent Core. - * @remarks - * Core designates the functions specific to a particular type - * of SIP entity, i.e., specific to either a stateful or stateless - * proxy, a user agent or registrar. All cores, except those for - * the stateless proxy, are transaction users. - * https://tools.ietf.org/html/rfc3261#section-6 - * - * UAC Core: The set of processing functions required of a UAC that - * reside above the transaction and transport layers. - * https://tools.ietf.org/html/rfc3261#section-6 - * - * UAS Core: The set of processing functions required at a UAS that - * resides above the transaction and transport layers. - * https://tools.ietf.org/html/rfc3261#section-6 - * @public - */ -var UserAgentCore = /** @class */ (function () { - /** - * Constructor. - * @param configuration - Configuration. - * @param delegate - Delegate. - */ - function UserAgentCore(configuration, delegate) { - if (delegate === void 0) { delegate = {}; } - /** UACs. */ - this.userAgentClients = new Map(); - /** UASs. */ - this.userAgentServers = new Map(); - this.configuration = configuration; - this.delegate = delegate; - this.dialogs = new Map(); - this.subscribers = new Map(); - this.logger = configuration.loggerFactory.getLogger("sip.user-agent-core"); - } - /** Destructor. */ - UserAgentCore.prototype.dispose = function () { - this.reset(); - }; - /** Reset. */ - UserAgentCore.prototype.reset = function () { - this.dialogs.forEach(function (dialog) { return dialog.dispose(); }); - this.dialogs.clear(); - this.subscribers.forEach(function (subscriber) { return subscriber.dispose(); }); - this.subscribers.clear(); - this.userAgentClients.forEach(function (uac) { return uac.dispose(); }); - this.userAgentClients.clear(); - this.userAgentServers.forEach(function (uac) { return uac.dispose(); }); - this.userAgentServers.clear(); - }; - Object.defineProperty(UserAgentCore.prototype, "loggerFactory", { - /** Logger factory. */ - get: function () { - return this.configuration.loggerFactory; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(UserAgentCore.prototype, "transport", { - /** Transport. */ - get: function () { - var transport = this.configuration.transportAccessor(); - if (!transport) { - throw new Error("Transport undefined."); - } - return transport; - }, - enumerable: true, - configurable: true - }); - /** - * Send INVITE. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - UserAgentCore.prototype.invite = function (request, delegate) { - return new user_agents_1.InviteUserAgentClient(this, request, delegate); - }; - /** - * Send MESSAGE. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - UserAgentCore.prototype.message = function (request, delegate) { - return new user_agents_1.MessageUserAgentClient(this, request, delegate); - }; - /** - * Send PUBLISH. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - UserAgentCore.prototype.publish = function (request, delegate) { - return new user_agents_1.PublishUserAgentClient(this, request, delegate); - }; - /** - * Send REGISTER. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - UserAgentCore.prototype.register = function (request, delegate) { - return new user_agents_1.RegisterUserAgentClient(this, request, delegate); - }; - /** - * Send SUBSCRIBE. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - UserAgentCore.prototype.subscribe = function (request, delegate) { - return new user_agents_1.SubscribeUserAgentClient(this, request, delegate); - }; - /** - * Send a request. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - UserAgentCore.prototype.request = function (request, delegate) { - return new user_agents_1.UserAgentClient(transactions_1.NonInviteClientTransaction, this, request, delegate); - }; - /** - * Outgoing request message factory function. - * @param method - Method. - * @param requestURI - Request-URI. - * @param fromURI - From URI. - * @param toURI - To URI. - * @param options - Request options. - * @param extraHeaders - Extra headers to add. - * @param body - Message body. - */ - UserAgentCore.prototype.makeOutgoingRequestMessage = function (method, requestURI, fromURI, toURI, options, extraHeaders, body) { - // default values from user agent configuration - var callIdPrefix = this.configuration.sipjsId; - var fromDisplayName = this.configuration.displayName; - var forceRport = this.configuration.viaForceRport; - var hackViaTcp = this.configuration.hackViaTcp; - var optionTags = this.configuration.supportedOptionTags.slice(); - if (method === messages_1.C.REGISTER) { - optionTags.push("path", "gruu"); - } - if (method === messages_1.C.INVITE && (this.configuration.contact.pubGruu || this.configuration.contact.tempGruu)) { - optionTags.push("gruu"); - } - var routeSet = this.configuration.routeSet; - var userAgentString = this.configuration.userAgentHeaderFieldValue; - var viaHost = this.configuration.viaHost; - var defaultOptions = { - callIdPrefix: callIdPrefix, - forceRport: forceRport, - fromDisplayName: fromDisplayName, - hackViaTcp: hackViaTcp, - optionTags: optionTags, - routeSet: routeSet, - userAgentString: userAgentString, - viaHost: viaHost, - }; - // merge provided options with default options - var requestOptions = tslib_1.__assign({}, defaultOptions, options); - return new messages_1.OutgoingRequestMessage(method, requestURI, fromURI, toURI, requestOptions, extraHeaders, body); - }; - /** - * Handle an incoming request message from the transport. - * @param message - Incoming request message from transport layer. - */ - UserAgentCore.prototype.receiveIncomingRequestFromTransport = function (message) { - this.receiveRequestFromTransport(message); - }; - /** - * Handle an incoming response message from the transport. - * @param message - Incoming response message from transport layer. - */ - UserAgentCore.prototype.receiveIncomingResponseFromTransport = function (message) { - this.receiveResponseFromTransport(message); - }; - /** - * A stateless UAS is a UAS that does not maintain transaction state. - * It replies to requests normally, but discards any state that would - * ordinarily be retained by a UAS after a response has been sent. If a - * stateless UAS receives a retransmission of a request, it regenerates - * the response and re-sends it, just as if it were replying to the first - * instance of the request. A UAS cannot be stateless unless the request - * processing for that method would always result in the same response - * if the requests are identical. This rules out stateless registrars, - * for example. Stateless UASs do not use a transaction layer; they - * receive requests directly from the transport layer and send responses - * directly to the transport layer. - * https://tools.ietf.org/html/rfc3261#section-8.2.7 - * @param message - Incoming request message to reply to. - * @param statusCode - Status code to reply with. - */ - UserAgentCore.prototype.replyStateless = function (message, options) { - var userAgent = this.configuration.userAgentHeaderFieldValue; - var supported = this.configuration.supportedOptionTagsResponse; - options = tslib_1.__assign({}, options, { userAgent: userAgent, supported: supported }); - var response = messages_1.constructOutgoingResponse(message, options); - this.transport.send(response.message); - return response; - }; - /** - * In Section 18.2.1, replace the last paragraph with: - * - * Next, the server transport attempts to match the request to a - * server transaction. It does so using the matching rules described - * in Section 17.2.3. If a matching server transaction is found, the - * request is passed to that transaction for processing. If no match - * is found, the request is passed to the core, which may decide to - * construct a new server transaction for that request. - * https://tools.ietf.org/html/rfc6026#section-8.10 - * @param message - Incoming request message from transport layer. - */ - UserAgentCore.prototype.receiveRequestFromTransport = function (message) { - // When a request is received from the network by the server, it has to - // be matched to an existing transaction. This is accomplished in the - // following manner. - // - // The branch parameter in the topmost Via header field of the request - // is examined. If it is present and begins with the magic cookie - // "z9hG4bK", the request was generated by a client transaction - // compliant to this specification. Therefore, the branch parameter - // will be unique across all transactions sent by that client. The - // request matches a transaction if: - // - // 1. the branch parameter in the request is equal to the one in the - // top Via header field of the request that created the - // transaction, and - // - // 2. the sent-by value in the top Via of the request is equal to the - // one in the request that created the transaction, and - // - // 3. the method of the request matches the one that created the - // transaction, except for ACK, where the method of the request - // that created the transaction is INVITE. - // - // This matching rule applies to both INVITE and non-INVITE transactions - // alike. - // - // The sent-by value is used as part of the matching process because - // there could be accidental or malicious duplication of branch - // parameters from different clients. - // https://tools.ietf.org/html/rfc3261#section-17.2.3 - var transactionId = message.viaBranch; // FIXME: Currently only using rule 1... - var uas = this.userAgentServers.get(transactionId); - // When receiving an ACK that matches an existing INVITE server - // transaction and that does not contain a branch parameter containing - // the magic cookie defined in RFC 3261, the matching transaction MUST - // be checked to see if it is in the "Accepted" state. If it is, then - // the ACK must be passed directly to the transaction user instead of - // being absorbed by the transaction state machine. This is necessary - // as requests from RFC 2543 clients will not include a unique branch - // parameter, and the mechanisms for calculating the transaction ID from - // such a request will be the same for both INVITE and ACKs. - // https://tools.ietf.org/html/rfc6026#section-6 - // Any ACKs received from the network while in the "Accepted" state MUST be - // passed directly to the TU and not absorbed. - // https://tools.ietf.org/html/rfc6026#section-7.1 - if (message.method === messages_1.C.ACK) { - if (uas && uas.transaction.state === transactions_1.TransactionState.Accepted) { - if (uas instanceof user_agents_1.InviteUserAgentServer) { - // These are ACKs matching an INVITE server transaction. - // These should never happen with RFC 3261 compliant user agents - // (would be a broken ACK to negative final response or something) - // but is apparently how RFC 2543 user agents do things. - // We are not currently supporting this case. - // NOTE: Not backwards compatible with RFC 2543 (no support for strict-routing). - this.logger.warn("Discarding out of dialog ACK after 2xx response sent on transaction " + transactionId + "."); - return; - } - } - } - // The CANCEL method requests that the TU at the server side cancel a - // pending transaction. The TU determines the transaction to be - // cancelled by taking the CANCEL request, and then assuming that the - // request method is anything but CANCEL or ACK and applying the - // transaction matching procedures of Section 17.2.3. The matching - // transaction is the one to be cancelled. - // https://tools.ietf.org/html/rfc3261#section-9.2 - if (message.method === messages_1.C.CANCEL) { - if (uas) { - // Regardless of the method of the original request, as long as the - // CANCEL matched an existing transaction, the UAS answers the CANCEL - // request itself with a 200 (OK) response. - // https://tools.ietf.org/html/rfc3261#section-9.2 - this.replyStateless(message, { statusCode: 200 }); - // If the transaction for the original request still exists, the behavior - // of the UAS on receiving a CANCEL request depends on whether it has already - // sent a final response for the original request. If it has, the CANCEL - // request has no effect on the processing of the original request, no - // effect on any session state, and no effect on the responses generated - // for the original request. If the UAS has not issued a final response - // for the original request, its behavior depends on the method of the - // original request. If the original request was an INVITE, the UAS - // SHOULD immediately respond to the INVITE with a 487 (Request - // Terminated). - // https://tools.ietf.org/html/rfc3261#section-9.2 - if (uas.transaction instanceof transactions_1.InviteServerTransaction && - uas.transaction.state === transactions_1.TransactionState.Proceeding) { - if (uas instanceof user_agents_1.InviteUserAgentServer) { - uas.receiveCancel(message); - } - // A CANCEL request has no impact on the processing of - // transactions with any other method defined in this specification. - // https://tools.ietf.org/html/rfc3261#section-9.2 - } - } - else { - // If the UAS did not find a matching transaction for the CANCEL - // according to the procedure above, it SHOULD respond to the CANCEL - // with a 481 (Call Leg/Transaction Does Not Exist). - // https://tools.ietf.org/html/rfc3261#section-9.2 - this.replyStateless(message, { statusCode: 481 }); - } - return; - } - // If a matching server transaction is found, the request is passed to that - // transaction for processing. - // https://tools.ietf.org/html/rfc6026#section-8.10 - if (uas) { - uas.transaction.receiveRequest(message); - return; - } - // If no match is found, the request is passed to the core, which may decide to - // construct a new server transaction for that request. - // https://tools.ietf.org/html/rfc6026#section-8.10 - this.receiveRequest(message); - return; - }; - /** - * UAC and UAS procedures depend strongly on two factors. First, based - * on whether the request or response is inside or outside of a dialog, - * and second, based on the method of a request. Dialogs are discussed - * thoroughly in Section 12; they represent a peer-to-peer relationship - * between user agents and are established by specific SIP methods, such - * as INVITE. - * @param message - Incoming request message. - */ - UserAgentCore.prototype.receiveRequest = function (message) { - // 8.2 UAS Behavior - // UASs SHOULD process the requests in the order of the steps that - // follow in this section (that is, starting with authentication, then - // inspecting the method, the header fields, and so on throughout the - // remainder of this section). - // https://tools.ietf.org/html/rfc3261#section-8.2 - // 8.2.1 Method Inspection - // Once a request is authenticated (or authentication is skipped), the - // UAS MUST inspect the method of the request. If the UAS recognizes - // but does not support the method of a request, it MUST generate a 405 - // (Method Not Allowed) response. Procedures for generating responses - // are described in Section 8.2.6. The UAS MUST also add an Allow - // header field to the 405 (Method Not Allowed) response. The Allow - // header field MUST list the set of methods supported by the UAS - // generating the message. - // https://tools.ietf.org/html/rfc3261#section-8.2.1 - if (!allowed_methods_1.AllowedMethods.includes(message.method)) { - var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); - this.replyStateless(message, { - statusCode: 405, - extraHeaders: [allowHeader] - }); - return; - } - // 8.2.2 Header Inspection - // https://tools.ietf.org/html/rfc3261#section-8.2.2 - if (!message.ruri) { // FIXME: A request message should always have an ruri - throw new Error("Request-URI undefined."); - } - // 8.2.2.1 To and Request-URI - // If the Request-URI uses a scheme not supported by the UAS, it SHOULD - // reject the request with a 416 (Unsupported URI Scheme) response. - // https://tools.ietf.org/html/rfc3261#section-8.2.2.1 - if (message.ruri.scheme !== "sip") { - this.replyStateless(message, { statusCode: 416 }); - return; - } - // 8.2.2.1 To and Request-URI - // If the Request-URI does not identify an address that the - // UAS is willing to accept requests for, it SHOULD reject - // the request with a 404 (Not Found) response. - // https://tools.ietf.org/html/rfc3261#section-8.2.2.1 - var ruri = message.ruri; - var ruriMatches = function (uri) { - return !!uri && uri.user === ruri.user; - }; - if (!ruriMatches(this.configuration.aor) && - !(ruriMatches(this.configuration.contact.uri) || - ruriMatches(this.configuration.contact.pubGruu) || - ruriMatches(this.configuration.contact.tempGruu))) { - this.logger.warn("Request-URI does not point to us."); - if (message.method !== messages_1.C.ACK) { - this.replyStateless(message, { statusCode: 404 }); - } - return; - } - // 8.2.2.1 To and Request-URI - // Other potential sources of received Request-URIs include - // the Contact header fields of requests and responses sent by the UA - // that establish or refresh dialogs. - // https://tools.ietf.org/html/rfc3261#section-8.2.2.1 - if (message.method === messages_1.C.INVITE) { - if (!message.hasHeader("Contact")) { - this.replyStateless(message, { - statusCode: 400, - reasonPhrase: "Missing Contact Header" - }); - return; - } - } - // 8.2.2.2 Merged Requests - // If the request has no tag in the To header field, the UAS core MUST - // check the request against ongoing transactions. If the From tag, - // Call-ID, and CSeq exactly match those associated with an ongoing - // transaction, but the request does not match that transaction (based - // on the matching rules in Section 17.2.3), the UAS core SHOULD - // generate a 482 (Loop Detected) response and pass it to the server - // transaction. - // - // The same request has arrived at the UAS more than once, following - // different paths, most likely due to forking. The UAS processes - // the first such request received and responds with a 482 (Loop - // Detected) to the rest of them. - // https://tools.ietf.org/html/rfc3261#section-8.2.2.2 - if (!message.toTag) { - var transactionId = message.viaBranch; - if (!this.userAgentServers.has(transactionId)) { - var mergedRequest = Array.from(this.userAgentServers.values()) - .some(function (uas) { - return uas.transaction.request.fromTag === message.fromTag && - uas.transaction.request.callId === message.callId && - uas.transaction.request.cseq === message.cseq; - }); - if (mergedRequest) { - this.replyStateless(message, { statusCode: 482 }); - return; - } - } - } - // 8.2.2.3 Require - // https://tools.ietf.org/html/rfc3261#section-8.2.2.3 - // TODO - // 8.2.3 Content Processing - // https://tools.ietf.org/html/rfc3261#section-8.2.3 - // TODO - // 8.2.4 Applying Extensions - // https://tools.ietf.org/html/rfc3261#section-8.2.4 - // TODO - // 8.2.5 Processing the Request - // Assuming all of the checks in the previous subsections are passed, - // the UAS processing becomes method-specific. - // https://tools.ietf.org/html/rfc3261#section-8.2.5 - // The UAS will receive the request from the transaction layer. If the - // request has a tag in the To header field, the UAS core computes the - // dialog identifier corresponding to the request and compares it with - // existing dialogs. If there is a match, this is a mid-dialog request. - // In that case, the UAS first applies the same processing rules for - // requests outside of a dialog, discussed in Section 8.2. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (message.toTag) { - this.receiveInsideDialogRequest(message); - } - else { - this.receiveOutsideDialogRequest(message); - } - return; - }; - /** - * Once a dialog has been established between two UAs, either of them - * MAY initiate new transactions as needed within the dialog. The UA - * sending the request will take the UAC role for the transaction. The - * UA receiving the request will take the UAS role. Note that these may - * be different roles than the UAs held during the transaction that - * established the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.2 - * @param message - Incoming request message. - */ - UserAgentCore.prototype.receiveInsideDialogRequest = function (message) { - // NOTIFY requests are matched to such SUBSCRIBE requests if they - // contain the same "Call-ID", a "To" header field "tag" parameter that - // matches the "From" header field "tag" parameter of the SUBSCRIBE - // request, and the same "Event" header field. Rules for comparisons of - // the "Event" header fields are described in Section 8.2.1. - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - if (message.method === messages_1.C.NOTIFY) { - var event_1 = message.parseHeader("Event"); - if (!event_1 || !event_1.event) { - this.replyStateless(message, { statusCode: 489 }); - return; - } - // FIXME: Subscriber id should also matching on event id. - var subscriberId = message.callId + message.toTag + event_1.event; - var subscriber = this.subscribers.get(subscriberId); - if (subscriber) { - var uas = new user_agents_1.NotifyUserAgentServer(this, message); - subscriber.onNotify(uas); - return; - } - } - // Requests sent within a dialog, as any other requests, are atomic. If - // a particular request is accepted by the UAS, all the state changes - // associated with it are performed. If the request is rejected, none - // of the state changes are performed. - // - // Note that some requests, such as INVITEs, affect several pieces of - // state. - // - // The UAS will receive the request from the transaction layer. If the - // request has a tag in the To header field, the UAS core computes the - // dialog identifier corresponding to the request and compares it with - // existing dialogs. If there is a match, this is a mid-dialog request. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - var dialogId = message.callId + message.toTag + message.fromTag; - var dialog = this.dialogs.get(dialogId); - if (dialog) { - // [Sip-implementors] Reg. SIP reinvite, UPDATE and OPTIONS - // You got the question right. - // - // And you got the right answer too. :-) - // - // Thanks, - // Paul - // - // Robert Sparks wrote: - // > So I've lost track of the question during the musing. - // > - // > I _think_ the fundamental question being asked is this: - // > - // > Is an endpoint required to reject (with a 481) an OPTIONS request that - // > arrives with at to-tag but does not match any existing dialog state. - // > (Assuming some earlier requirement hasn't forced another error code). Or - // > is it OK if it just sends - // > a 200 OK anyhow. - // > - // > My take on the collection of specs is that its _not_ ok for it to send - // > the 200 OK anyhow and that it is required to send - // > the 481. I base this primarily on these sentences from 11.2 in 3261: - // > - // > The response to an OPTIONS is constructed using the standard rules - // > for a SIP response as discussed in Section 8.2.6. The response code - // > chosen MUST be the same that would have been chosen had the request - // > been an INVITE. - // > - // > Did I miss the point of the question? - // > - // > On May 15, 2008, at 12:48 PM, Paul Kyzivat wrote: - // > - // >> [Including Robert in hopes of getting his insight on this.] - // https://lists.cs.columbia.edu/pipermail/sip-implementors/2008-May/019178.html - // - // Requests that do not change in any way the state of a dialog may be - // received within a dialog (for example, an OPTIONS request). They are - // processed as if they had been received outside the dialog. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (message.method === messages_1.C.OPTIONS) { - var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); - var acceptHeader = "Accept: " + acceptedBodyTypes.toString(); - this.replyStateless(message, { - statusCode: 200, - extraHeaders: [allowHeader, acceptHeader] - }); - return; - } - // Pass the incoming request to the dialog for further handling. - dialog.receiveRequest(message); - return; - } - // The most important behaviors of a stateless UAS are the following: - // ... - // o A stateless UAS MUST ignore ACK requests. - // ... - // https://tools.ietf.org/html/rfc3261#section-8.2.7 - if (message.method === messages_1.C.ACK) { - // If a final response to an INVITE was sent statelessly, - // the corresponding ACK: - // - will not match an existing transaction - // - may have tag in the To header field - // - not not match any existing dialogs - // Absorb unmatched ACKs. - return; - } - // If the request has a tag in the To header field, but the dialog - // identifier does not match any existing dialogs, the UAS may have - // crashed and restarted, or it may have received a request for a - // different (possibly failed) UAS (the UASs can construct the To tags - // so that a UAS can identify that the tag was for a UAS for which it is - // providing recovery). Another possibility is that the incoming - // request has been simply mis-routed. Based on the To tag, the UAS MAY - // either accept or reject the request. Accepting the request for - // acceptable To tags provides robustness, so that dialogs can persist - // even through crashes. UAs wishing to support this capability must - // take into consideration some issues such as choosing monotonically - // increasing CSeq sequence numbers even across reboots, reconstructing - // the route set, and accepting out-of-range RTP timestamps and sequence - // numbers. - // - // If the UAS wishes to reject the request because it does not wish to - // recreate the dialog, it MUST respond to the request with a 481 - // (Call/Transaction Does Not Exist) status code and pass that to the - // server transaction. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - this.replyStateless(message, { statusCode: 481 }); - return; - }; - /** - * Assuming all of the checks in the previous subsections are passed, - * the UAS processing becomes method-specific. - * https://tools.ietf.org/html/rfc3261#section-8.2.5 - * @param message - Incoming request message. - */ - UserAgentCore.prototype.receiveOutsideDialogRequest = function (message) { - switch (message.method) { - case messages_1.C.ACK: - // Absorb stray out of dialog ACKs - break; - case messages_1.C.BYE: - // If the BYE does not match an existing dialog, the UAS core SHOULD - // generate a 481 (Call/Transaction Does Not Exist) response and pass - // that to the server transaction. This rule means that a BYE sent - // without tags by a UAC will be rejected. - // https://tools.ietf.org/html/rfc3261#section-15.1.2 - this.replyStateless(message, { statusCode: 481 }); - break; - case messages_1.C.CANCEL: - throw new Error("Unexpected out of dialog request method " + message.method + "."); - break; - case messages_1.C.INFO: - // Use of the INFO method does not constitute a separate dialog usage. - // INFO messages are always part of, and share the fate of, an invite - // dialog usage [RFC5057]. INFO messages cannot be sent as part of - // other dialog usages, or outside an existing dialog. - // https://tools.ietf.org/html/rfc6086#section-1 - this.replyStateless(message, { statusCode: 405 }); // Should never happen - break; - case messages_1.C.INVITE: - // https://tools.ietf.org/html/rfc3261#section-13.3.1 - { - var uas = new user_agents_1.InviteUserAgentServer(this, message); - this.delegate.onInvite ? - this.delegate.onInvite(uas) : - uas.reject(); - } - break; - case messages_1.C.MESSAGE: - // MESSAGE requests are discouraged inside a dialog. Implementations - // are restricted from creating a usage for the purpose of carrying a - // sequence of MESSAGE requests (though some implementations use it that - // way, against the standard recommendation). - // https://tools.ietf.org/html/rfc5057#section-5.3 - { - var uas = new user_agents_1.MessageUserAgentServer(this, message); - this.delegate.onMessage ? - this.delegate.onMessage(uas) : - uas.accept(); - } - break; - case messages_1.C.NOTIFY: - // Obsoleted by: RFC 6665 - // If any non-SUBSCRIBE mechanisms are defined to create subscriptions, - // it is the responsibility of the parties defining those mechanisms to - // ensure that correlation of a NOTIFY message to the corresponding - // subscription is possible. Designers of such mechanisms are also - // warned to make a distinction between sending a NOTIFY message to a - // subscriber who is aware of the subscription, and sending a NOTIFY - // message to an unsuspecting node. The latter behavior is invalid, and - // MUST receive a "481 Subscription does not exist" response (unless - // some other 400- or 500-class error code is more applicable), as - // described in section 3.2.4. In other words, knowledge of a - // subscription must exist in both the subscriber and the notifier to be - // valid, even if installed via a non-SUBSCRIBE mechanism. - // https://tools.ietf.org/html/rfc3265#section-3.2 - // - // NOTIFY requests are sent to inform subscribers of changes in state to - // which the subscriber has a subscription. Subscriptions are created - // using the SUBSCRIBE method. In legacy implementations, it is - // possible that other means of subscription creation have been used. - // However, this specification does not allow the creation of - // subscriptions except through SUBSCRIBE requests and (for backwards- - // compatibility) REFER requests [RFC3515]. - // https://tools.ietf.org/html/rfc6665#section-3.2 - { - var uas = new user_agents_1.NotifyUserAgentServer(this, message); - this.delegate.onNotify ? - this.delegate.onNotify(uas) : - uas.reject({ statusCode: 405 }); - } - break; - case messages_1.C.OPTIONS: - // https://tools.ietf.org/html/rfc3261#section-11.2 - { - var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); - var acceptHeader = "Accept: " + acceptedBodyTypes.toString(); - this.replyStateless(message, { - statusCode: 200, - extraHeaders: [allowHeader, acceptHeader] - }); - } - break; - case messages_1.C.REFER: - // https://tools.ietf.org/html/rfc3515#section-2.4.2 - { - var uas = new user_agents_1.ReferUserAgentServer(this, message); - this.delegate.onRefer ? - this.delegate.onRefer(uas) : - uas.reject({ statusCode: 405 }); - } - break; - case messages_1.C.REGISTER: - // https://tools.ietf.org/html/rfc3261#section-10.3 - { - var uas = new user_agents_1.RegisterUserAgentServer(this, message); - this.delegate.onRegister ? - this.delegate.onRegister(uas) : - uas.reject({ statusCode: 405 }); - } - break; - case messages_1.C.SUBSCRIBE: - // https://tools.ietf.org/html/rfc6665#section-4.2 - { - var uas = new user_agents_1.SubscribeUserAgentServer(this, message); - this.delegate.onSubscribe ? - this.delegate.onSubscribe(uas) : - uas.reject({ statusCode: 480 }); - } - break; - default: - throw new Error("Unexpected out of dialog request method " + message.method + "."); - } - return; - }; - /** - * Responses are first processed by the transport layer and then passed - * up to the transaction layer. The transaction layer performs its - * processing and then passes the response up to the TU. The majority - * of response processing in the TU is method specific. However, there - * are some general behaviors independent of the method. - * https://tools.ietf.org/html/rfc3261#section-8.1.3 - * @param message - Incoming response message from transport layer. - */ - UserAgentCore.prototype.receiveResponseFromTransport = function (message) { - // 8.1.3.1 Transaction Layer Errors - // https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - // Handled by transaction layer callbacks. - // 8.1.3.2 Unrecognized Responses - // https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - // TODO - // 8.1.3.3 Vias - // https://tools.ietf.org/html/rfc3261#section-8.1.3.3 - if (message.getHeaders("via").length > 1) { - this.logger.warn("More than one Via header field present in the response, dropping"); - return; - } - // 8.1.3.4 Processing 3xx Responses - // https://tools.ietf.org/html/rfc3261#section-8.1.3.4 - // TODO - // 8.1.3.5 Processing 4xx Responses - // https://tools.ietf.org/html/rfc3261#section-8.1.3.5 - // TODO - // When the transport layer in the client receives a response, it has to - // determine which client transaction will handle the response, so that - // the processing of Sections 17.1.1 and 17.1.2 can take place. The - // branch parameter in the top Via header field is used for this - // purpose. A response matches a client transaction under two - // conditions: - // - // 1. If the response has the same value of the branch parameter in - // the top Via header field as the branch parameter in the top - // Via header field of the request that created the transaction. - // - // 2. If the method parameter in the CSeq header field matches the - // method of the request that created the transaction. The - // method is needed since a CANCEL request constitutes a - // different transaction, but shares the same value of the branch - // parameter. - // https://tools.ietf.org/html/rfc3261#section-17.1.3 - var userAgentClientId = message.viaBranch + message.method; - var userAgentClient = this.userAgentClients.get(userAgentClientId); - // The client transport uses the matching procedures of Section - // 17.1.3 to attempt to match the response to an existing - // transaction. If there is a match, the response MUST be passed to - // that transaction. Otherwise, any element other than a stateless - // proxy MUST silently discard the response. - // https://tools.ietf.org/html/rfc6026#section-8.9 - if (userAgentClient) { - userAgentClient.transaction.receiveResponse(message); - } - else { - this.logger.warn("Discarding unmatched " + message.statusCode + " response to " + message.method + " " + userAgentClientId + "."); - } - }; - return UserAgentCore; -}()); -exports.UserAgentCore = UserAgentCore; diff --git a/lib/core/user-agents/bye-user-agent-client.d.ts b/lib/core/user-agents/bye-user-agent-client.d.ts deleted file mode 100644 index c0f22aa95..000000000 --- a/lib/core/user-agents/bye-user-agent-client.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { SessionDialog } from "../dialogs"; -import { OutgoingByeRequest, OutgoingRequestDelegate, RequestOptions } from "../messages"; -import { UserAgentClient } from "./user-agent-client"; -/** - * BYE UAC. - * @public - */ -export declare class ByeUserAgentClient extends UserAgentClient implements OutgoingByeRequest { - constructor(dialog: SessionDialog, delegate?: OutgoingRequestDelegate, options?: RequestOptions); -} -//# sourceMappingURL=bye-user-agent-client.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/bye-user-agent-client.d.ts.map b/lib/core/user-agents/bye-user-agent-client.d.ts.map deleted file mode 100644 index 8e562263d..000000000 --- a/lib/core/user-agents/bye-user-agent-client.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"bye-user-agent-client.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/bye-user-agent-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,EAAK,kBAAkB,EAAE,uBAAuB,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAE7F,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,qBAAa,kBAAmB,SAAQ,eAAgB,YAAW,kBAAkB;gBAEjF,MAAM,EAAE,aAAa,EACrB,QAAQ,CAAC,EAAE,uBAAuB,EAClC,OAAO,CAAC,EAAE,cAAc;CAM3B"} \ No newline at end of file diff --git a/lib/core/user-agents/bye-user-agent-client.js b/lib/core/user-agents/bye-user-agent-client.js deleted file mode 100644 index 23f64b3c1..000000000 --- a/lib/core/user-agents/bye-user-agent-client.js +++ /dev/null @@ -1,22 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var messages_1 = require("../messages"); -var transactions_1 = require("../transactions"); -var user_agent_client_1 = require("./user-agent-client"); -/** - * BYE UAC. - * @public - */ -var ByeUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(ByeUserAgentClient, _super); - function ByeUserAgentClient(dialog, delegate, options) { - var _this = this; - var message = dialog.createOutgoingRequestMessage(messages_1.C.BYE, options); - _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; - dialog.dispose(); - return _this; - } - return ByeUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.ByeUserAgentClient = ByeUserAgentClient; diff --git a/lib/core/user-agents/bye-user-agent-server.d.ts b/lib/core/user-agents/bye-user-agent-server.d.ts deleted file mode 100644 index 85a98258e..000000000 --- a/lib/core/user-agents/bye-user-agent-server.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { SessionDialog } from "../dialogs"; -import { IncomingByeRequest, IncomingRequestDelegate, IncomingRequestMessage } from "../messages"; -import { UserAgentServer } from "./user-agent-server"; -/** - * BYE UAS. - * @public - */ -export declare class ByeUserAgentServer extends UserAgentServer implements IncomingByeRequest { - constructor(dialog: SessionDialog, message: IncomingRequestMessage, delegate?: IncomingRequestDelegate); -} -//# sourceMappingURL=bye-user-agent-server.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/bye-user-agent-server.d.ts.map b/lib/core/user-agents/bye-user-agent-server.d.ts.map deleted file mode 100644 index fb724f31e..000000000 --- a/lib/core/user-agents/bye-user-agent-server.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"bye-user-agent-server.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/bye-user-agent-server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,EAAE,kBAAkB,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAElG,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,qBAAa,kBAAmB,SAAQ,eAAgB,YAAW,kBAAkB;gBAEjF,MAAM,EAAE,aAAa,EACrB,OAAO,EAAE,sBAAsB,EAC/B,QAAQ,CAAC,EAAE,uBAAuB;CAIrC"} \ No newline at end of file diff --git a/lib/core/user-agents/bye-user-agent-server.js b/lib/core/user-agents/bye-user-agent-server.js deleted file mode 100644 index 53e00dbd5..000000000 --- a/lib/core/user-agents/bye-user-agent-server.js +++ /dev/null @@ -1,17 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var transactions_1 = require("../transactions"); -var user_agent_server_1 = require("./user-agent-server"); -/** - * BYE UAS. - * @public - */ -var ByeUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(ByeUserAgentServer, _super); - function ByeUserAgentServer(dialog, message, delegate) { - return _super.call(this, transactions_1.NonInviteServerTransaction, dialog.userAgentCore, message, delegate) || this; - } - return ByeUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.ByeUserAgentServer = ByeUserAgentServer; diff --git a/lib/core/user-agents/cancel-user-agent-client.d.ts b/lib/core/user-agents/cancel-user-agent-client.d.ts deleted file mode 100644 index e83c423f2..000000000 --- a/lib/core/user-agents/cancel-user-agent-client.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { OutgoingCancelRequest, OutgoingRequestDelegate, OutgoingRequestMessage } from "../messages"; -import { UserAgentCore } from "../user-agent-core"; -import { UserAgentClient } from "./user-agent-client"; -/** - * CANCEL UAC. - * @public - */ -export declare class CancelUserAgentClient extends UserAgentClient implements OutgoingCancelRequest { - constructor(core: UserAgentCore, message: OutgoingRequestMessage, delegate?: OutgoingRequestDelegate); -} -//# sourceMappingURL=cancel-user-agent-client.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/cancel-user-agent-client.d.ts.map b/lib/core/user-agents/cancel-user-agent-client.d.ts.map deleted file mode 100644 index b8caae069..000000000 --- a/lib/core/user-agents/cancel-user-agent-client.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"cancel-user-agent-client.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/cancel-user-agent-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAErG,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,qBAAa,qBAAsB,SAAQ,eAAgB,YAAW,qBAAqB;gBAEvF,IAAI,EAAE,aAAa,EACnB,OAAO,EAAE,sBAAsB,EAC/B,QAAQ,CAAC,EAAE,uBAAuB;CAIrC"} \ No newline at end of file diff --git a/lib/core/user-agents/cancel-user-agent-client.js b/lib/core/user-agents/cancel-user-agent-client.js deleted file mode 100644 index c1a28a545..000000000 --- a/lib/core/user-agents/cancel-user-agent-client.js +++ /dev/null @@ -1,17 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var transactions_1 = require("../transactions"); -var user_agent_client_1 = require("./user-agent-client"); -/** - * CANCEL UAC. - * @public - */ -var CancelUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(CancelUserAgentClient, _super); - function CancelUserAgentClient(core, message, delegate) { - return _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; - } - return CancelUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.CancelUserAgentClient = CancelUserAgentClient; diff --git a/lib/core/user-agents/index.d.ts b/lib/core/user-agents/index.d.ts deleted file mode 100644 index ac74c459b..000000000 --- a/lib/core/user-agents/index.d.ts +++ /dev/null @@ -1,27 +0,0 @@ -export * from "./bye-user-agent-client"; -export * from "./bye-user-agent-server"; -export * from "./cancel-user-agent-client"; -export * from "./info-user-agent-client"; -export * from "./info-user-agent-server"; -export * from "./invite-user-agent-client"; -export * from "./invite-user-agent-server"; -export * from "./message-user-agent-client"; -export * from "./message-user-agent-server"; -export * from "./notify-user-agent-client"; -export * from "./notify-user-agent-server"; -export * from "./publish-user-agent-client"; -export * from "./prack-user-agent-client"; -export * from "./prack-user-agent-server"; -export * from "./re-invite-user-agent-client"; -export * from "./re-invite-user-agent-server"; -export * from "./re-subscribe-user-agent-client"; -export * from "./re-subscribe-user-agent-server"; -export * from "./refer-user-agent-client"; -export * from "./refer-user-agent-server"; -export * from "./register-user-agent-client"; -export * from "./register-user-agent-server"; -export * from "./subscribe-user-agent-client"; -export * from "./subscribe-user-agent-server"; -export * from "./user-agent-client"; -export * from "./user-agent-server"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/index.d.ts.map b/lib/core/user-agents/index.d.ts.map deleted file mode 100644 index 816b4d781..000000000 --- a/lib/core/user-agents/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/index.ts"],"names":[],"mappings":"AAAA,cAAc,yBAAyB,CAAC;AACxC,cAAc,yBAAyB,CAAC;AACxC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,0BAA0B,CAAC;AACzC,cAAc,0BAA0B,CAAC;AACzC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,4BAA4B,CAAC;AAC3C,cAAc,6BAA6B,CAAC;AAC5C,cAAc,6BAA6B,CAAC;AAC5C,cAAc,4BAA4B,CAAC;AAC3C,cAAc,4BAA4B,CAAC;AAC3C,cAAc,6BAA6B,CAAC;AAC5C,cAAc,2BAA2B,CAAC;AAC1C,cAAc,2BAA2B,CAAC;AAC1C,cAAc,+BAA+B,CAAC;AAC9C,cAAc,+BAA+B,CAAC;AAC9C,cAAc,kCAAkC,CAAC;AACjD,cAAc,kCAAkC,CAAC;AACjD,cAAc,2BAA2B,CAAC;AAC1C,cAAc,2BAA2B,CAAC;AAC1C,cAAc,8BAA8B,CAAC;AAC7C,cAAc,8BAA8B,CAAC;AAC7C,cAAc,+BAA+B,CAAC;AAC9C,cAAc,+BAA+B,CAAC;AAC9C,cAAc,qBAAqB,CAAC;AACpC,cAAc,qBAAqB,CAAC"} \ No newline at end of file diff --git a/lib/core/user-agents/index.js b/lib/core/user-agents/index.js deleted file mode 100644 index 9ce88096b..000000000 --- a/lib/core/user-agents/index.js +++ /dev/null @@ -1,29 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -tslib_1.__exportStar(require("./bye-user-agent-client"), exports); -tslib_1.__exportStar(require("./bye-user-agent-server"), exports); -tslib_1.__exportStar(require("./cancel-user-agent-client"), exports); -tslib_1.__exportStar(require("./info-user-agent-client"), exports); -tslib_1.__exportStar(require("./info-user-agent-server"), exports); -tslib_1.__exportStar(require("./invite-user-agent-client"), exports); -tslib_1.__exportStar(require("./invite-user-agent-server"), exports); -tslib_1.__exportStar(require("./message-user-agent-client"), exports); -tslib_1.__exportStar(require("./message-user-agent-server"), exports); -tslib_1.__exportStar(require("./notify-user-agent-client"), exports); -tslib_1.__exportStar(require("./notify-user-agent-server"), exports); -tslib_1.__exportStar(require("./publish-user-agent-client"), exports); -tslib_1.__exportStar(require("./prack-user-agent-client"), exports); -tslib_1.__exportStar(require("./prack-user-agent-server"), exports); -tslib_1.__exportStar(require("./re-invite-user-agent-client"), exports); -tslib_1.__exportStar(require("./re-invite-user-agent-server"), exports); -tslib_1.__exportStar(require("./re-subscribe-user-agent-client"), exports); -tslib_1.__exportStar(require("./re-subscribe-user-agent-server"), exports); -tslib_1.__exportStar(require("./refer-user-agent-client"), exports); -tslib_1.__exportStar(require("./refer-user-agent-server"), exports); -tslib_1.__exportStar(require("./register-user-agent-client"), exports); -tslib_1.__exportStar(require("./register-user-agent-server"), exports); -tslib_1.__exportStar(require("./subscribe-user-agent-client"), exports); -tslib_1.__exportStar(require("./subscribe-user-agent-server"), exports); -tslib_1.__exportStar(require("./user-agent-client"), exports); -tslib_1.__exportStar(require("./user-agent-server"), exports); diff --git a/lib/core/user-agents/info-user-agent-client.d.ts b/lib/core/user-agents/info-user-agent-client.d.ts deleted file mode 100644 index 48bcafb3d..000000000 --- a/lib/core/user-agents/info-user-agent-client.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { SessionDialog } from "../dialogs"; -import { OutgoingInfoRequest, OutgoingRequestDelegate, RequestOptions } from "../messages"; -import { UserAgentClient } from "./user-agent-client"; -/** - * INFO UAC. - * @public - */ -export declare class InfoUserAgentClient extends UserAgentClient implements OutgoingInfoRequest { - constructor(dialog: SessionDialog, delegate?: OutgoingRequestDelegate, options?: RequestOptions); -} -//# sourceMappingURL=info-user-agent-client.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/info-user-agent-client.d.ts.map b/lib/core/user-agents/info-user-agent-client.d.ts.map deleted file mode 100644 index 7337314bd..000000000 --- a/lib/core/user-agents/info-user-agent-client.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"info-user-agent-client.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/info-user-agent-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,EAAK,mBAAmB,EAAE,uBAAuB,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAE9F,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,qBAAa,mBAAoB,SAAQ,eAAgB,YAAW,mBAAmB;gBAEnF,MAAM,EAAE,aAAa,EACrB,QAAQ,CAAC,EAAE,uBAAuB,EAClC,OAAO,CAAC,EAAE,cAAc;CAK3B"} \ No newline at end of file diff --git a/lib/core/user-agents/info-user-agent-client.js b/lib/core/user-agents/info-user-agent-client.js deleted file mode 100644 index d3d27d0df..000000000 --- a/lib/core/user-agents/info-user-agent-client.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var messages_1 = require("../messages"); -var transactions_1 = require("../transactions"); -var user_agent_client_1 = require("./user-agent-client"); -/** - * INFO UAC. - * @public - */ -var InfoUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(InfoUserAgentClient, _super); - function InfoUserAgentClient(dialog, delegate, options) { - var _this = this; - var message = dialog.createOutgoingRequestMessage(messages_1.C.INFO, options); - _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; - return _this; - } - return InfoUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.InfoUserAgentClient = InfoUserAgentClient; diff --git a/lib/core/user-agents/info-user-agent-server.d.ts b/lib/core/user-agents/info-user-agent-server.d.ts deleted file mode 100644 index 1a15097b1..000000000 --- a/lib/core/user-agents/info-user-agent-server.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { SessionDialog } from "../dialogs"; -import { IncomingInfoRequest, IncomingRequestDelegate, IncomingRequestMessage } from "../messages"; -import { UserAgentServer } from "./user-agent-server"; -/** - * INFO UAS. - * @public - */ -export declare class InfoUserAgentServer extends UserAgentServer implements IncomingInfoRequest { - constructor(dialog: SessionDialog, message: IncomingRequestMessage, delegate?: IncomingRequestDelegate); -} -//# sourceMappingURL=info-user-agent-server.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/info-user-agent-server.d.ts.map b/lib/core/user-agents/info-user-agent-server.d.ts.map deleted file mode 100644 index 378407a26..000000000 --- a/lib/core/user-agents/info-user-agent-server.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"info-user-agent-server.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/info-user-agent-server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,EAAE,mBAAmB,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAEnG,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,qBAAa,mBAAoB,SAAQ,eAAgB,YAAW,mBAAmB;gBAEnF,MAAM,EAAE,aAAa,EACrB,OAAO,EAAE,sBAAsB,EAC/B,QAAQ,CAAC,EAAE,uBAAuB;CAIrC"} \ No newline at end of file diff --git a/lib/core/user-agents/info-user-agent-server.js b/lib/core/user-agents/info-user-agent-server.js deleted file mode 100644 index eadeaea2f..000000000 --- a/lib/core/user-agents/info-user-agent-server.js +++ /dev/null @@ -1,17 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var transactions_1 = require("../transactions"); -var user_agent_server_1 = require("./user-agent-server"); -/** - * INFO UAS. - * @public - */ -var InfoUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(InfoUserAgentServer, _super); - function InfoUserAgentServer(dialog, message, delegate) { - return _super.call(this, transactions_1.NonInviteServerTransaction, dialog.userAgentCore, message, delegate) || this; - } - return InfoUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.InfoUserAgentServer = InfoUserAgentServer; diff --git a/lib/core/user-agents/invite-user-agent-client.d.ts b/lib/core/user-agents/invite-user-agent-client.d.ts deleted file mode 100644 index cc0471868..000000000 --- a/lib/core/user-agents/invite-user-agent-client.d.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { IncomingResponseMessage, OutgoingInviteRequest, OutgoingInviteRequestDelegate, OutgoingRequestMessage } from "../messages"; -import { UserAgentCore } from "../user-agent-core"; -import { UserAgentClient } from "./user-agent-client"; -/** - * INVITE UAC. - * @remarks - * 13 Initiating a Session - * https://tools.ietf.org/html/rfc3261#section-13 - * 13.1 Overview - * https://tools.ietf.org/html/rfc3261#section-13.1 - * 13.2 UAC Processing - * https://tools.ietf.org/html/rfc3261#section-13.2 - * @public - */ -export declare class InviteUserAgentClient extends UserAgentClient implements OutgoingInviteRequest { - delegate: OutgoingInviteRequestDelegate | undefined; - private confirmedDialogAcks; - private confirmedDialogs; - private earlyDialogs; - constructor(core: UserAgentCore, message: OutgoingRequestMessage, delegate?: OutgoingInviteRequestDelegate); - dispose(): void; - /** - * Once the INVITE has been passed to the INVITE client transaction, the - * UAC waits for responses for the INVITE. - * https://tools.ietf.org/html/rfc3261#section-13.2.2 - * @param incomingResponse - Incoming response to INVITE request. - */ - protected receiveResponse(message: IncomingResponseMessage): void; -} -//# sourceMappingURL=invite-user-agent-client.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/invite-user-agent-client.d.ts.map b/lib/core/user-agents/invite-user-agent-client.d.ts.map deleted file mode 100644 index 2e492f020..000000000 --- a/lib/core/user-agents/invite-user-agent-client.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"invite-user-agent-client.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/invite-user-agent-client.ts"],"names":[],"mappings":"AACA,OAAO,EACL,uBAAuB,EAEvB,qBAAqB,EACrB,6BAA6B,EAE7B,sBAAsB,EAEvB,MAAM,aAAa,CAAC;AAGrB,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;;;;;;;;GAUG;AACH,qBAAa,qBAAsB,SAAQ,eAAgB,YAAW,qBAAqB;IAClF,QAAQ,EAAE,6BAA6B,GAAG,SAAS,CAAC;IAE3D,OAAO,CAAC,mBAAmB,CAAyC;IACpE,OAAO,CAAC,gBAAgB,CAAoC;IAC5D,OAAO,CAAC,YAAY,CAAoC;gBAGtD,IAAI,EAAE,aAAa,EACnB,OAAO,EAAE,sBAAsB,EAC/B,QAAQ,CAAC,EAAE,6BAA6B;IAMnC,OAAO,IAAI,IAAI;IAgBtB;;;;;OAKG;IACH,SAAS,CAAC,eAAe,CAAC,OAAO,EAAE,uBAAuB,GAAG,IAAI;CAoRlE"} \ No newline at end of file diff --git a/lib/core/user-agents/invite-user-agent-client.js b/lib/core/user-agents/invite-user-agent-client.js deleted file mode 100644 index d6357281e..000000000 --- a/lib/core/user-agents/invite-user-agent-client.js +++ /dev/null @@ -1,311 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var dialogs_1 = require("../dialogs"); -var session_1 = require("../session"); -var transactions_1 = require("../transactions"); -var user_agent_client_1 = require("./user-agent-client"); -/** - * INVITE UAC. - * @remarks - * 13 Initiating a Session - * https://tools.ietf.org/html/rfc3261#section-13 - * 13.1 Overview - * https://tools.ietf.org/html/rfc3261#section-13.1 - * 13.2 UAC Processing - * https://tools.ietf.org/html/rfc3261#section-13.2 - * @public - */ -var InviteUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(InviteUserAgentClient, _super); - function InviteUserAgentClient(core, message, delegate) { - var _this = _super.call(this, transactions_1.InviteClientTransaction, core, message, delegate) || this; - _this.confirmedDialogAcks = new Map(); - _this.confirmedDialogs = new Map(); - _this.earlyDialogs = new Map(); - _this.delegate = delegate; - return _this; - } - InviteUserAgentClient.prototype.dispose = function () { - // The UAC core considers the INVITE transaction completed 64*T1 seconds - // after the reception of the first 2xx response. At this point all the - // early dialogs that have not transitioned to established dialogs are - // terminated. Once the INVITE transaction is considered completed by - // the UAC core, no more new 2xx responses are expected to arrive. - // - // If, after acknowledging any 2xx response to an INVITE, the UAC does - // not want to continue with that dialog, then the UAC MUST terminate - // the dialog by sending a BYE request as described in Section 15. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - this.earlyDialogs.forEach(function (earlyDialog) { return earlyDialog.dispose(); }); - this.earlyDialogs.clear(); - _super.prototype.dispose.call(this); - }; - /** - * Once the INVITE has been passed to the INVITE client transaction, the - * UAC waits for responses for the INVITE. - * https://tools.ietf.org/html/rfc3261#section-13.2.2 - * @param incomingResponse - Incoming response to INVITE request. - */ - InviteUserAgentClient.prototype.receiveResponse = function (message) { - var _this = this; - if (!this.authenticationGuard(message)) { - return; - } - var statusCode = message.statusCode ? message.statusCode.toString() : ""; - if (!statusCode) { - throw new Error("Response status code undefined."); - } - switch (true) { - case /^100$/.test(statusCode): - if (this.delegate && this.delegate.onTrying) { - this.delegate.onTrying({ message: message }); - } - return; - case /^1[0-9]{2}$/.test(statusCode): - // Zero, one or multiple provisional responses may arrive before one or - // more final responses are received. Provisional responses for an - // INVITE request can create "early dialogs". If a provisional response - // has a tag in the To field, and if the dialog ID of the response does - // not match an existing dialog, one is constructed using the procedures - // defined in Section 12.1.2. - // - // The early dialog will only be needed if the UAC needs to send a - // request to its peer within the dialog before the initial INVITE - // transaction completes. Header fields present in a provisional - // response are applicable as long as the dialog is in the early state - // (for example, an Allow header field in a provisional response - // contains the methods that can be used in the dialog while this is in - // the early state). - // https://tools.ietf.org/html/rfc3261#section-13.2.2.1 - { - // Provisional without to tag, no dialog to create. - if (!message.toTag) { - this.logger.warn("Non-100 1xx INVITE response received without a to tag, dropping."); - return; - } - // Compute dialog state. - var dialogState = dialogs_1.Dialog.initialDialogStateForUserAgentClient(this.message, message); - // Have existing early dialog or create a new one. - var earlyDialog = this.earlyDialogs.get(dialogState.id); - if (!earlyDialog) { - var transaction = this.transaction; - if (!(transaction instanceof transactions_1.InviteClientTransaction)) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - earlyDialog = new dialogs_1.SessionDialog(transaction, this.core, dialogState); - this.earlyDialogs.set(earlyDialog.id, earlyDialog); - } - // Guard against out of order reliable provisional responses. - // Note that this is where the rseq tracking is done. - if (!earlyDialog.reliableSequenceGuard(message)) { - this.logger.warn("1xx INVITE reliable response received out of order, dropping."); - return; - } - // If the initial offer is in an INVITE, the answer MUST be in a - // reliable non-failure message from UAS back to UAC which is - // correlated to that INVITE. For this specification, that is - // only the final 2xx response to that INVITE. That same exact - // answer MAY also be placed in any provisional responses sent - // prior to the answer. The UAC MUST treat the first session - // description it receives as the answer, and MUST ignore any - // session descriptions in subsequent responses to the initial - // INVITE. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - if (earlyDialog.signalingState === session_1.SignalingState.Initial || - earlyDialog.signalingState === session_1.SignalingState.HaveLocalOffer) { - earlyDialog.signalingStateTransition(message); - } - // Pass response to delegate. - var session_2 = earlyDialog; - if (this.delegate && this.delegate.onProgress) { - this.delegate.onProgress({ - message: message, - session: session_2, - prack: function (options) { - var outgoingPrackRequest = session_2.prack(undefined, options); - return outgoingPrackRequest; - } - }); - } - } - return; - case /^2[0-9]{2}$/.test(statusCode): - // Multiple 2xx responses may arrive at the UAC for a single INVITE - // request due to a forking proxy. Each response is distinguished by - // the tag parameter in the To header field, and each represents a - // distinct dialog, with a distinct dialog identifier. - // - // If the dialog identifier in the 2xx response matches the dialog - // identifier of an existing dialog, the dialog MUST be transitioned to - // the "confirmed" state, and the route set for the dialog MUST be - // recomputed based on the 2xx response using the procedures of Section - // 12.2.1.2. Otherwise, a new dialog in the "confirmed" state MUST be - // constructed using the procedures of Section 12.1.2. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - { - // Compute dialog state. - var dialogState = dialogs_1.Dialog.initialDialogStateForUserAgentClient(this.message, message); - // NOTE: Currently our transaction layer is caching the 2xx ACKs and - // handling retransmissions of the ACK which is an approach which is - // not to spec. In any event, this block is intended to provide a to - // spec implementation of ACK retransmissions, but it should not be - // hit currently. - var dialog = this.confirmedDialogs.get(dialogState.id); - if (dialog) { - // Once the ACK has been constructed, the procedures of [4] are used to - // determine the destination address, port and transport. However, the - // request is passed to the transport layer directly for transmission, - // rather than a client transaction. This is because the UAC core - // handles retransmissions of the ACK, not the transaction layer. The - // ACK MUST be passed to the client transport every time a - // retransmission of the 2xx final response that triggered the ACK - // arrives. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - var outgoingAckRequest = this.confirmedDialogAcks.get(dialogState.id); - if (outgoingAckRequest) { - var transaction = this.transaction; - if (!(transaction instanceof transactions_1.InviteClientTransaction)) { - throw new Error("Client transaction not instance of InviteClientTransaction."); - } - transaction.ackResponse(outgoingAckRequest.message); - } - else { - // If still waiting for an ACK, drop the retransmission of the 2xx final response. - } - return; - } - // If the dialog identifier in the 2xx response matches the dialog - // identifier of an existing dialog, the dialog MUST be transitioned to - // the "confirmed" state, and the route set for the dialog MUST be - // recomputed based on the 2xx response using the procedures of Section - // 12.2.1.2. Otherwise, a new dialog in the "confirmed" state MUST be - // constructed using the procedures of Section 12.1.2. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - dialog = this.earlyDialogs.get(dialogState.id); - if (dialog) { - dialog.confirm(); - dialog.recomputeRouteSet(message); - this.earlyDialogs.delete(dialog.id); - this.confirmedDialogs.set(dialog.id, dialog); - } - else { - var transaction = this.transaction; - if (!(transaction instanceof transactions_1.InviteClientTransaction)) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - dialog = new dialogs_1.SessionDialog(transaction, this.core, dialogState); - this.confirmedDialogs.set(dialog.id, dialog); - } - // If the initial offer is in an INVITE, the answer MUST be in a - // reliable non-failure message from UAS back to UAC which is - // correlated to that INVITE. For this specification, that is - // only the final 2xx response to that INVITE. That same exact - // answer MAY also be placed in any provisional responses sent - // prior to the answer. The UAC MUST treat the first session - // description it receives as the answer, and MUST ignore any - // session descriptions in subsequent responses to the initial - // INVITE. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - if (dialog.signalingState === session_1.SignalingState.Initial || - dialog.signalingState === session_1.SignalingState.HaveLocalOffer) { - dialog.signalingStateTransition(message); - } - // Session Initiated! :) - var session_3 = dialog; - // The UAC core MUST generate an ACK request for each 2xx received from - // the transaction layer. The header fields of the ACK are constructed - // in the same way as for any request sent within a dialog (see Section - // 12) with the exception of the CSeq and the header fields related to - // authentication. The sequence number of the CSeq header field MUST be - // the same as the INVITE being acknowledged, but the CSeq method MUST - // be ACK. The ACK MUST contain the same credentials as the INVITE. If - // the 2xx contains an offer (based on the rules above), the ACK MUST - // carry an answer in its body. If the offer in the 2xx response is not - // acceptable, the UAC core MUST generate a valid answer in the ACK and - // then send a BYE immediately. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - if (this.delegate && this.delegate.onAccept) { - this.delegate.onAccept({ - message: message, - session: session_3, - ack: function (options) { - var outgoingAckRequest = session_3.ack(options); - _this.confirmedDialogAcks.set(session_3.id, outgoingAckRequest); - return outgoingAckRequest; - } - }); - } - else { - var outgoingAckRequest = session_3.ack(); - this.confirmedDialogAcks.set(session_3.id, outgoingAckRequest); - } - } - return; - case /^3[0-9]{2}$/.test(statusCode): - // 12.3 Termination of a Dialog - // - // Independent of the method, if a request outside of a dialog generates - // a non-2xx final response, any early dialogs created through - // provisional responses to that request are terminated. The mechanism - // for terminating confirmed dialogs is method specific. In this - // specification, the BYE method terminates a session and the dialog - // associated with it. See Section 15 for details. - // https://tools.ietf.org/html/rfc3261#section-12.3 - // All early dialogs are considered terminated upon reception of the - // non-2xx final response. - // - // After having received the non-2xx final response the UAC core - // considers the INVITE transaction completed. The INVITE client - // transaction handles the generation of ACKs for the response (see - // Section 17). - // https://tools.ietf.org/html/rfc3261#section-13.2.2.3 - this.earlyDialogs.forEach(function (earlyDialog) { return earlyDialog.dispose(); }); - this.earlyDialogs.clear(); - // A 3xx response may contain one or more Contact header field values - // providing new addresses where the callee might be reachable. - // Depending on the status code of the 3xx response (see Section 21.3), - // the UAC MAY choose to try those new addresses. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.2 - if (this.delegate && this.delegate.onRedirect) { - this.delegate.onRedirect({ message: message }); - } - return; - case /^[4-6][0-9]{2}$/.test(statusCode): - // 12.3 Termination of a Dialog - // - // Independent of the method, if a request outside of a dialog generates - // a non-2xx final response, any early dialogs created through - // provisional responses to that request are terminated. The mechanism - // for terminating confirmed dialogs is method specific. In this - // specification, the BYE method terminates a session and the dialog - // associated with it. See Section 15 for details. - // https://tools.ietf.org/html/rfc3261#section-12.3 - // All early dialogs are considered terminated upon reception of the - // non-2xx final response. - // - // After having received the non-2xx final response the UAC core - // considers the INVITE transaction completed. The INVITE client - // transaction handles the generation of ACKs for the response (see - // Section 17). - // https://tools.ietf.org/html/rfc3261#section-13.2.2.3 - this.earlyDialogs.forEach(function (earlyDialog) { return earlyDialog.dispose(); }); - this.earlyDialogs.clear(); - // A single non-2xx final response may be received for the INVITE. 4xx, - // 5xx and 6xx responses may contain a Contact header field value - // indicating the location where additional information about the error - // can be found. Subsequent final responses (which would only arrive - // under error conditions) MUST be ignored. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.3 - if (this.delegate && this.delegate.onReject) { - this.delegate.onReject({ message: message }); - } - return; - default: - throw new Error("Invalid status code " + statusCode); - } - throw new Error("Executing what should be an unreachable code path receiving " + statusCode + " response."); - }; - return InviteUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.InviteUserAgentClient = InviteUserAgentClient; diff --git a/lib/core/user-agents/invite-user-agent-server.d.ts b/lib/core/user-agents/invite-user-agent-server.d.ts deleted file mode 100644 index 54968462a..000000000 --- a/lib/core/user-agents/invite-user-agent-server.d.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { IncomingInviteRequest, IncomingRequestDelegate, IncomingRequestMessage, OutgoingResponse, OutgoingResponseWithSession, ResponseOptions, URI } from "../messages"; -import { UserAgentCore } from "../user-agent-core"; -import { UserAgentServer } from "./user-agent-server"; -/** - * INVITE UAS. - * @remarks - * 13 Initiating a Session - * https://tools.ietf.org/html/rfc3261#section-13 - * 13.1 Overview - * https://tools.ietf.org/html/rfc3261#section-13.1 - * 13.3 UAS Processing - * https://tools.ietf.org/html/rfc3261#section-13.3 - * @public - */ -export declare class InviteUserAgentServer extends UserAgentServer implements IncomingInviteRequest { - protected core: UserAgentCore; - /** The confirmed dialog, if any. */ - private confirmedDialog; - /** The early dialog, if any. */ - private earlyDialog; - constructor(core: UserAgentCore, message: IncomingRequestMessage, delegate?: IncomingRequestDelegate); - dispose(): void; - /** - * 13.3.1.4 The INVITE is Accepted - * The UAS core generates a 2xx response. This response establishes a - * dialog, and therefore follows the procedures of Section 12.1.1 in - * addition to those of Section 8.2.6. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - * @param options - Accept options bucket. - */ - accept(options?: ResponseOptions): OutgoingResponseWithSession; - /** - * 13.3.1.1 Progress - * If the UAS is not able to answer the invitation immediately, it can - * choose to indicate some kind of progress to the UAC (for example, an - * indication that a phone is ringing). This is accomplished with a - * provisional response between 101 and 199. These provisional - * responses establish early dialogs and therefore follow the procedures - * of Section 12.1.1 in addition to those of Section 8.2.6. A UAS MAY - * send as many provisional responses as it likes. Each of these MUST - * indicate the same dialog ID. However, these will not be delivered - * reliably. - * - * If the UAS desires an extended period of time to answer the INVITE, - * it will need to ask for an "extension" in order to prevent proxies - * from canceling the transaction. A proxy has the option of canceling - * a transaction when there is a gap of 3 minutes between responses in a - * transaction. To prevent cancellation, the UAS MUST send a non-100 - * provisional response at every minute, to handle the possibility of - * lost provisional responses. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.1 - * @param options - Progress options bucket. - */ - progress(options?: ResponseOptions): OutgoingResponseWithSession; - /** - * 13.3.1.2 The INVITE is Redirected - * If the UAS decides to redirect the call, a 3xx response is sent. A - * 300 (Multiple Choices), 301 (Moved Permanently) or 302 (Moved - * Temporarily) response SHOULD contain a Contact header field - * containing one or more URIs of new addresses to be tried. The - * response is passed to the INVITE server transaction, which will deal - * with its retransmissions. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.2 - * @param contacts - Contacts to redirect to. - * @param options - Redirect options bucket. - */ - redirect(contacts: Array, options?: ResponseOptions): OutgoingResponse; - /** - * 13.3.1.3 The INVITE is Rejected - * A common scenario occurs when the callee is currently not willing or - * able to take additional calls at this end system. A 486 (Busy Here) - * SHOULD be returned in such a scenario. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.3 - * @param options - Reject options bucket. - */ - reject(options?: ResponseOptions): OutgoingResponse; -} -//# sourceMappingURL=invite-user-agent-server.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/invite-user-agent-server.d.ts.map b/lib/core/user-agents/invite-user-agent-server.d.ts.map deleted file mode 100644 index 6fc4ddb18..000000000 --- a/lib/core/user-agents/invite-user-agent-server.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"invite-user-agent-server.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/invite-user-agent-server.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,qBAAqB,EACrB,uBAAuB,EACvB,sBAAsB,EACtB,gBAAgB,EAChB,2BAA2B,EAC3B,eAAe,EACf,GAAG,EACJ,MAAM,aAAa,CAAC;AAGrB,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAEnD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;;;;;;;;GAUG;AACH,qBAAa,qBAAsB,SAAQ,eAAgB,YAAW,qBAAqB;IAQvF,SAAS,CAAC,IAAI,EAAE,aAAa;IAN/B,oCAAoC;IACpC,OAAO,CAAC,eAAe,CAA4B;IACnD,gCAAgC;IAChC,OAAO,CAAC,WAAW,CAA4B;gBAGnC,IAAI,EAAE,aAAa,EAC7B,OAAO,EAAE,sBAAsB,EAC/B,QAAQ,CAAC,EAAE,uBAAuB;IAK7B,OAAO,IAAI,IAAI;IAOtB;;;;;;;OAOG;IACI,MAAM,CAAC,OAAO,GAAE,eAAqC,GAAG,2BAA2B;IA0G1F;;;;;;;;;;;;;;;;;;;;;OAqBG;IACI,QAAQ,CAAC,OAAO,GAAE,eAAqC,GAAG,2BAA2B;IAoE5F;;;;;;;;;;;OAWG;IACI,QAAQ,CAAC,QAAQ,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,OAAO,GAAE,eAAqC,GAAG,gBAAgB;IAIvG;;;;;;;OAOG;IACI,MAAM,CAAC,OAAO,GAAE,eAAqC,GAAG,gBAAgB;CAGhF"} \ No newline at end of file diff --git a/lib/core/user-agents/invite-user-agent-server.js b/lib/core/user-agents/invite-user-agent-server.js deleted file mode 100644 index 7d825e727..000000000 --- a/lib/core/user-agents/invite-user-agent-server.js +++ /dev/null @@ -1,247 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var dialogs_1 = require("../dialogs"); -var exceptions_1 = require("../exceptions"); -var session_1 = require("../session"); -var transactions_1 = require("../transactions"); -var allowed_methods_1 = require("../user-agent-core/allowed-methods"); -var user_agent_server_1 = require("./user-agent-server"); -/** - * INVITE UAS. - * @remarks - * 13 Initiating a Session - * https://tools.ietf.org/html/rfc3261#section-13 - * 13.1 Overview - * https://tools.ietf.org/html/rfc3261#section-13.1 - * 13.3 UAS Processing - * https://tools.ietf.org/html/rfc3261#section-13.3 - * @public - */ -var InviteUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(InviteUserAgentServer, _super); - function InviteUserAgentServer(core, message, delegate) { - var _this = _super.call(this, transactions_1.InviteServerTransaction, core, message, delegate) || this; - _this.core = core; - return _this; - } - InviteUserAgentServer.prototype.dispose = function () { - if (this.earlyDialog) { - this.earlyDialog.dispose(); - } - _super.prototype.dispose.call(this); - }; - /** - * 13.3.1.4 The INVITE is Accepted - * The UAS core generates a 2xx response. This response establishes a - * dialog, and therefore follows the procedures of Section 12.1.1 in - * addition to those of Section 8.2.6. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - * @param options - Accept options bucket. - */ - InviteUserAgentServer.prototype.accept = function (options) { - if (options === void 0) { options = { statusCode: 200 }; } - if (!this.acceptable) { - throw new exceptions_1.TransactionStateError(this.message.method + " not acceptable in state " + this.transaction.state + "."); - } - // This response establishes a dialog... - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - if (!this.confirmedDialog) { - if (this.earlyDialog) { - this.earlyDialog.confirm(); - this.confirmedDialog = this.earlyDialog; - this.earlyDialog = undefined; - } - else { - var transaction = this.transaction; - if (!(transaction instanceof transactions_1.InviteServerTransaction)) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - var state = dialogs_1.Dialog.initialDialogStateForUserAgentServer(this.message, this.toTag); - this.confirmedDialog = new dialogs_1.SessionDialog(transaction, this.core, state); - } - } - // When a UAS responds to a request with a response that establishes a - // dialog (such as a 2xx to INVITE), the UAS MUST copy all Record-Route - // header field values from the request into the response (including the - // URIs, URI parameters, and any Record-Route header field parameters, - // whether they are known or unknown to the UAS) and MUST maintain the - // order of those values. The UAS MUST add a Contact header field to - // the response. The Contact header field contains an address where the - // UAS would like to be contacted for subsequent requests in the dialog - // (which includes the ACK for a 2xx response in the case of an INVITE). - // Generally, the host portion of this URI is the IP address or FQDN of - // the host. The URI provided in the Contact header field MUST be a SIP - // or SIPS URI. If the request that initiated the dialog contained a - // SIPS URI in the Request-URI or in the top Record-Route header field - // value, if there was any, or the Contact header field if there was no - // Record-Route header field, the Contact header field in the response - // MUST be a SIPS URI. The URI SHOULD have global scope (that is, the - // same URI can be used in messages outside this dialog). The same way, - // the scope of the URI in the Contact header field of the INVITE is not - // limited to this dialog either. It can therefore be used in messages - // to the UAC even outside this dialog. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - var recordRouteHeader = this.message - .getHeaders("record-route") - .map(function (header) { return "Record-Route: " + header; }); - var contactHeader = "Contact: " + this.core.configuration.contact.toString(); - // A 2xx response to an INVITE SHOULD contain the Allow header field and - // the Supported header field, and MAY contain the Accept header field. - // Including these header fields allows the UAC to determine the - // features and extensions supported by the UAS for the duration of the - // call, without probing. - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - // FIXME: TODO: This should not be hard coded. - var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); - // FIXME: TODO: Supported header (see reply()) - // FIXME: TODO: Accept header - // If the INVITE request contained an offer, and the UAS had not yet - // sent an answer, the 2xx MUST contain an answer. If the INVITE did - // not contain an offer, the 2xx MUST contain an offer if the UAS had - // not yet sent an offer. - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - if (!options.body) { - if (this.confirmedDialog.signalingState === session_1.SignalingState.Stable) { - options.body = this.confirmedDialog.answer; // resend the answer sent in provisional response - } - else if (this.confirmedDialog.signalingState === session_1.SignalingState.Initial || - this.confirmedDialog.signalingState === session_1.SignalingState.HaveRemoteOffer) { - throw new Error("Response must have a body."); - } - } - options.statusCode = options.statusCode || 200; - options.extraHeaders = options.extraHeaders || []; - options.extraHeaders = options.extraHeaders.concat(recordRouteHeader); - options.extraHeaders.push(allowHeader); - options.extraHeaders.push(contactHeader); - var response = _super.prototype.accept.call(this, options); - var session = this.confirmedDialog; - var result = tslib_1.__assign({}, response, { session: session }); - // Update dialog signaling state - if (options.body) { - // Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - if (this.confirmedDialog.signalingState !== session_1.SignalingState.Stable) { - this.confirmedDialog.signalingStateTransition(options.body); - } - } - return result; - }; - /** - * 13.3.1.1 Progress - * If the UAS is not able to answer the invitation immediately, it can - * choose to indicate some kind of progress to the UAC (for example, an - * indication that a phone is ringing). This is accomplished with a - * provisional response between 101 and 199. These provisional - * responses establish early dialogs and therefore follow the procedures - * of Section 12.1.1 in addition to those of Section 8.2.6. A UAS MAY - * send as many provisional responses as it likes. Each of these MUST - * indicate the same dialog ID. However, these will not be delivered - * reliably. - * - * If the UAS desires an extended period of time to answer the INVITE, - * it will need to ask for an "extension" in order to prevent proxies - * from canceling the transaction. A proxy has the option of canceling - * a transaction when there is a gap of 3 minutes between responses in a - * transaction. To prevent cancellation, the UAS MUST send a non-100 - * provisional response at every minute, to handle the possibility of - * lost provisional responses. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.1 - * @param options - Progress options bucket. - */ - InviteUserAgentServer.prototype.progress = function (options) { - if (options === void 0) { options = { statusCode: 180 }; } - if (!this.progressable) { - throw new exceptions_1.TransactionStateError(this.message.method + " not progressable in state " + this.transaction.state + "."); - } - // This response establishes a dialog... - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - if (!this.earlyDialog) { - var transaction = this.transaction; - if (!(transaction instanceof transactions_1.InviteServerTransaction)) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - var state = dialogs_1.Dialog.initialDialogStateForUserAgentServer(this.message, this.toTag, true); - this.earlyDialog = new dialogs_1.SessionDialog(transaction, this.core, state); - } - // When a UAS responds to a request with a response that establishes a - // dialog (such as a 2xx to INVITE), the UAS MUST copy all Record-Route - // header field values from the request into the response (including the - // URIs, URI parameters, and any Record-Route header field parameters, - // whether they are known or unknown to the UAS) and MUST maintain the - // order of those values. The UAS MUST add a Contact header field to - // the response. The Contact header field contains an address where the - // UAS would like to be contacted for subsequent requests in the dialog - // (which includes the ACK for a 2xx response in the case of an INVITE). - // Generally, the host portion of this URI is the IP address or FQDN of - // the host. The URI provided in the Contact header field MUST be a SIP - // or SIPS URI. If the request that initiated the dialog contained a - // SIPS URI in the Request-URI or in the top Record-Route header field - // value, if there was any, or the Contact header field if there was no - // Record-Route header field, the Contact header field in the response - // MUST be a SIPS URI. The URI SHOULD have global scope (that is, the - // same URI can be used in messages outside this dialog). The same way, - // the scope of the URI in the Contact header field of the INVITE is not - // limited to this dialog either. It can therefore be used in messages - // to the UAC even outside this dialog. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - var recordRouteHeader = this.message - .getHeaders("record-route") - .map(function (header) { return "Record-Route: " + header; }); - var contactHeader = "Contact: " + this.core.configuration.contact; - options.extraHeaders = options.extraHeaders || []; - options.extraHeaders = options.extraHeaders.concat(recordRouteHeader); - options.extraHeaders.push(contactHeader); - var response = _super.prototype.progress.call(this, options); - var session = this.earlyDialog; - var result = tslib_1.__assign({}, response, { session: session }); - // Update dialog signaling state - if (options.body) { - // Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - if (this.earlyDialog.signalingState !== session_1.SignalingState.Stable) { - this.earlyDialog.signalingStateTransition(options.body); - } - } - return result; - }; - /** - * 13.3.1.2 The INVITE is Redirected - * If the UAS decides to redirect the call, a 3xx response is sent. A - * 300 (Multiple Choices), 301 (Moved Permanently) or 302 (Moved - * Temporarily) response SHOULD contain a Contact header field - * containing one or more URIs of new addresses to be tried. The - * response is passed to the INVITE server transaction, which will deal - * with its retransmissions. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.2 - * @param contacts - Contacts to redirect to. - * @param options - Redirect options bucket. - */ - InviteUserAgentServer.prototype.redirect = function (contacts, options) { - if (options === void 0) { options = { statusCode: 302 }; } - return _super.prototype.redirect.call(this, contacts, options); - }; - /** - * 13.3.1.3 The INVITE is Rejected - * A common scenario occurs when the callee is currently not willing or - * able to take additional calls at this end system. A 486 (Busy Here) - * SHOULD be returned in such a scenario. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.3 - * @param options - Reject options bucket. - */ - InviteUserAgentServer.prototype.reject = function (options) { - if (options === void 0) { options = { statusCode: 486 }; } - return _super.prototype.reject.call(this, options); - }; - return InviteUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.InviteUserAgentServer = InviteUserAgentServer; diff --git a/lib/core/user-agents/message-user-agent-client.d.ts b/lib/core/user-agents/message-user-agent-client.d.ts deleted file mode 100644 index 90490517b..000000000 --- a/lib/core/user-agents/message-user-agent-client.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { OutgoingMessageRequest, OutgoingRequestDelegate, OutgoingRequestMessage } from "../messages"; -import { UserAgentCore } from "../user-agent-core"; -import { UserAgentClient } from "./user-agent-client"; -/** - * MESSAGE UAS. - * @public - */ -export declare class MessageUserAgentClient extends UserAgentClient implements OutgoingMessageRequest { - constructor(core: UserAgentCore, message: OutgoingRequestMessage, delegate?: OutgoingRequestDelegate); -} -//# sourceMappingURL=message-user-agent-client.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/message-user-agent-client.d.ts.map b/lib/core/user-agents/message-user-agent-client.d.ts.map deleted file mode 100644 index 53f25f5ff..000000000 --- a/lib/core/user-agents/message-user-agent-client.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"message-user-agent-client.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/message-user-agent-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAEtG,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,qBAAa,sBAAuB,SAAQ,eAAgB,YAAW,sBAAsB;gBAEzF,IAAI,EAAE,aAAa,EACnB,OAAO,EAAE,sBAAsB,EAC/B,QAAQ,CAAC,EAAE,uBAAuB;CAIrC"} \ No newline at end of file diff --git a/lib/core/user-agents/message-user-agent-client.js b/lib/core/user-agents/message-user-agent-client.js deleted file mode 100644 index c457a3ab6..000000000 --- a/lib/core/user-agents/message-user-agent-client.js +++ /dev/null @@ -1,17 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var transactions_1 = require("../transactions"); -var user_agent_client_1 = require("./user-agent-client"); -/** - * MESSAGE UAS. - * @public - */ -var MessageUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(MessageUserAgentClient, _super); - function MessageUserAgentClient(core, message, delegate) { - return _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; - } - return MessageUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.MessageUserAgentClient = MessageUserAgentClient; diff --git a/lib/core/user-agents/message-user-agent-server.d.ts b/lib/core/user-agents/message-user-agent-server.d.ts deleted file mode 100644 index 390ac7dbb..000000000 --- a/lib/core/user-agents/message-user-agent-server.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { IncomingMessageRequest, IncomingRequestDelegate, IncomingRequestMessage } from "../messages"; -import { UserAgentCore } from "../user-agent-core"; -import { UserAgentServer } from "./user-agent-server"; -/** - * MESSAGE UAS. - * @public - */ -export declare class MessageUserAgentServer extends UserAgentServer implements IncomingMessageRequest { - protected core: UserAgentCore; - constructor(core: UserAgentCore, message: IncomingRequestMessage, delegate?: IncomingRequestDelegate); -} -//# sourceMappingURL=message-user-agent-server.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/message-user-agent-server.d.ts.map b/lib/core/user-agents/message-user-agent-server.d.ts.map deleted file mode 100644 index 871353742..000000000 --- a/lib/core/user-agents/message-user-agent-server.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"message-user-agent-server.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/message-user-agent-server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAEtG,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,qBAAa,sBAAuB,SAAQ,eAAgB,YAAW,sBAAsB;IAEzF,SAAS,CAAC,IAAI,EAAE,aAAa;gBAAnB,IAAI,EAAE,aAAa,EAC7B,OAAO,EAAE,sBAAsB,EAC/B,QAAQ,CAAC,EAAE,uBAAuB;CAIrC"} \ No newline at end of file diff --git a/lib/core/user-agents/message-user-agent-server.js b/lib/core/user-agents/message-user-agent-server.js deleted file mode 100644 index 94b3284c5..000000000 --- a/lib/core/user-agents/message-user-agent-server.js +++ /dev/null @@ -1,19 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var transactions_1 = require("../transactions"); -var user_agent_server_1 = require("./user-agent-server"); -/** - * MESSAGE UAS. - * @public - */ -var MessageUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(MessageUserAgentServer, _super); - function MessageUserAgentServer(core, message, delegate) { - var _this = _super.call(this, transactions_1.NonInviteServerTransaction, core, message, delegate) || this; - _this.core = core; - return _this; - } - return MessageUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.MessageUserAgentServer = MessageUserAgentServer; diff --git a/lib/core/user-agents/notify-user-agent-client.d.ts b/lib/core/user-agents/notify-user-agent-client.d.ts deleted file mode 100644 index 2bbd23eac..000000000 --- a/lib/core/user-agents/notify-user-agent-client.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { SessionDialog } from "../dialogs"; -import { OutgoingNotifyRequest, OutgoingRequestDelegate, RequestOptions } from "../messages"; -import { UserAgentClient } from "./user-agent-client"; -/** - * NOTIFY UAS. - * @public - */ -export declare class NotifyUserAgentClient extends UserAgentClient implements OutgoingNotifyRequest { - constructor(dialog: SessionDialog, delegate?: OutgoingRequestDelegate, options?: RequestOptions); -} -//# sourceMappingURL=notify-user-agent-client.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/notify-user-agent-client.d.ts.map b/lib/core/user-agents/notify-user-agent-client.d.ts.map deleted file mode 100644 index 36e47bc8c..000000000 --- a/lib/core/user-agents/notify-user-agent-client.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"notify-user-agent-client.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/notify-user-agent-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,EAAK,qBAAqB,EAAE,uBAAuB,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAEhG,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,qBAAa,qBAAsB,SAAQ,eAAgB,YAAW,qBAAqB;gBAEvF,MAAM,EAAE,aAAa,EACrB,QAAQ,CAAC,EAAE,uBAAuB,EAClC,OAAO,CAAC,EAAE,cAAc;CAK3B"} \ No newline at end of file diff --git a/lib/core/user-agents/notify-user-agent-client.js b/lib/core/user-agents/notify-user-agent-client.js deleted file mode 100644 index 9601f1ffe..000000000 --- a/lib/core/user-agents/notify-user-agent-client.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var messages_1 = require("../messages"); -var transactions_1 = require("../transactions"); -var user_agent_client_1 = require("./user-agent-client"); -/** - * NOTIFY UAS. - * @public - */ -var NotifyUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(NotifyUserAgentClient, _super); - function NotifyUserAgentClient(dialog, delegate, options) { - var _this = this; - var message = dialog.createOutgoingRequestMessage(messages_1.C.NOTIFY, options); - _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; - return _this; - } - return NotifyUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.NotifyUserAgentClient = NotifyUserAgentClient; diff --git a/lib/core/user-agents/notify-user-agent-server.d.ts b/lib/core/user-agents/notify-user-agent-server.d.ts deleted file mode 100644 index 9a22df7ca..000000000 --- a/lib/core/user-agents/notify-user-agent-server.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { Dialog } from "../dialogs"; -import { IncomingNotifyRequest, IncomingRequestDelegate, IncomingRequestMessage } from "../messages"; -import { UserAgentCore } from "../user-agent-core"; -import { UserAgentServer } from "./user-agent-server"; -/** - * NOTIFY UAS. - * @public - */ -export declare class NotifyUserAgentServer extends UserAgentServer implements IncomingNotifyRequest { - /** - * NOTIFY UAS constructor. - * @param dialogOrCore - Dialog for in dialog NOTIFY, UserAgentCore for out of dialog NOTIFY (deprecated). - * @param message - Incoming NOTIFY request message. - */ - constructor(dialogOrCore: Dialog | UserAgentCore, message: IncomingRequestMessage, delegate?: IncomingRequestDelegate); -} -//# sourceMappingURL=notify-user-agent-server.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/notify-user-agent-server.d.ts.map b/lib/core/user-agents/notify-user-agent-server.d.ts.map deleted file mode 100644 index ece29d35c..000000000 --- a/lib/core/user-agents/notify-user-agent-server.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"notify-user-agent-server.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/notify-user-agent-server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AACpC,OAAO,EAAE,qBAAqB,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAErG,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,qBAAa,qBAAsB,SAAQ,eAAgB,YAAW,qBAAqB;IACzF;;;;OAIG;gBAED,YAAY,EAAE,MAAM,GAAG,aAAa,EACpC,OAAO,EAAE,sBAAsB,EAC/B,QAAQ,CAAC,EAAE,uBAAuB;CAQrC"} \ No newline at end of file diff --git a/lib/core/user-agents/notify-user-agent-server.js b/lib/core/user-agents/notify-user-agent-server.js deleted file mode 100644 index c1e10da4a..000000000 --- a/lib/core/user-agents/notify-user-agent-server.js +++ /dev/null @@ -1,30 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var transactions_1 = require("../transactions"); -var user_agent_server_1 = require("./user-agent-server"); -/** - * NOTIFY UAS. - * @public - */ -var NotifyUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(NotifyUserAgentServer, _super); - /** - * NOTIFY UAS constructor. - * @param dialogOrCore - Dialog for in dialog NOTIFY, UserAgentCore for out of dialog NOTIFY (deprecated). - * @param message - Incoming NOTIFY request message. - */ - function NotifyUserAgentServer(dialogOrCore, message, delegate) { - var _this = this; - var userAgentCore = instanceOfDialog(dialogOrCore) ? - dialogOrCore.userAgentCore : - dialogOrCore; - _this = _super.call(this, transactions_1.NonInviteServerTransaction, userAgentCore, message, delegate) || this; - return _this; - } - return NotifyUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.NotifyUserAgentServer = NotifyUserAgentServer; -function instanceOfDialog(object) { - return object.userAgentCore !== undefined; -} diff --git a/lib/core/user-agents/prack-user-agent-client.d.ts b/lib/core/user-agents/prack-user-agent-client.d.ts deleted file mode 100644 index b7dea252a..000000000 --- a/lib/core/user-agents/prack-user-agent-client.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { SessionDialog } from "../dialogs"; -import { OutgoingPrackRequest, OutgoingRequestDelegate, RequestOptions } from "../messages"; -import { UserAgentClient } from "./user-agent-client"; -/** - * PRACK UAC. - * @public - */ -export declare class PrackUserAgentClient extends UserAgentClient implements OutgoingPrackRequest { - constructor(dialog: SessionDialog, delegate?: OutgoingRequestDelegate, options?: RequestOptions); -} -//# sourceMappingURL=prack-user-agent-client.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/prack-user-agent-client.d.ts.map b/lib/core/user-agents/prack-user-agent-client.d.ts.map deleted file mode 100644 index 012f8f4f9..000000000 --- a/lib/core/user-agents/prack-user-agent-client.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"prack-user-agent-client.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/prack-user-agent-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,EAAK,oBAAoB,EAAE,uBAAuB,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAE/F,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,qBAAa,oBAAqB,SAAQ,eAAgB,YAAW,oBAAoB;gBAErF,MAAM,EAAE,aAAa,EACrB,QAAQ,CAAC,EAAE,uBAAuB,EAClC,OAAO,CAAC,EAAE,cAAc;CAM3B"} \ No newline at end of file diff --git a/lib/core/user-agents/prack-user-agent-client.js b/lib/core/user-agents/prack-user-agent-client.js deleted file mode 100644 index 633324f58..000000000 --- a/lib/core/user-agents/prack-user-agent-client.js +++ /dev/null @@ -1,22 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var messages_1 = require("../messages"); -var transactions_1 = require("../transactions"); -var user_agent_client_1 = require("./user-agent-client"); -/** - * PRACK UAC. - * @public - */ -var PrackUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(PrackUserAgentClient, _super); - function PrackUserAgentClient(dialog, delegate, options) { - var _this = this; - var message = dialog.createOutgoingRequestMessage(messages_1.C.PRACK, options); - _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; - dialog.signalingStateTransition(message); - return _this; - } - return PrackUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.PrackUserAgentClient = PrackUserAgentClient; diff --git a/lib/core/user-agents/prack-user-agent-server.d.ts b/lib/core/user-agents/prack-user-agent-server.d.ts deleted file mode 100644 index ecc1fc075..000000000 --- a/lib/core/user-agents/prack-user-agent-server.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { SessionDialog } from "../dialogs"; -import { IncomingPrackRequest, IncomingRequestDelegate, IncomingRequestMessage, OutgoingResponse, ResponseOptions } from "../messages"; -import { UserAgentServer } from "./user-agent-server"; -/** - * PRACK UAS. - * @public - */ -export declare class PrackUserAgentServer extends UserAgentServer implements IncomingPrackRequest { - private dialog; - constructor(dialog: SessionDialog, message: IncomingRequestMessage, delegate?: IncomingRequestDelegate); - /** - * Update the dialog signaling state on a 2xx response. - * @param options - Options bucket. - */ - accept(options?: ResponseOptions): OutgoingResponse; -} -//# sourceMappingURL=prack-user-agent-server.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/prack-user-agent-server.d.ts.map b/lib/core/user-agents/prack-user-agent-server.d.ts.map deleted file mode 100644 index 85f7c74e1..000000000 --- a/lib/core/user-agents/prack-user-agent-server.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"prack-user-agent-server.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/prack-user-agent-server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,EACL,oBAAoB,EACpB,uBAAuB,EACvB,sBAAsB,EACtB,gBAAgB,EAChB,eAAe,EAChB,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,qBAAa,oBAAqB,SAAQ,eAAgB,YAAW,oBAAoB;IACvF,OAAO,CAAC,MAAM,CAAgB;gBAG5B,MAAM,EAAE,aAAa,EACrB,OAAO,EAAE,sBAAsB,EAC/B,QAAQ,CAAC,EAAE,uBAAuB;IAQpC;;;OAGG;IACI,MAAM,CAAC,OAAO,GAAE,eAAqC,GAAG,gBAAgB;CAOhF"} \ No newline at end of file diff --git a/lib/core/user-agents/prack-user-agent-server.js b/lib/core/user-agents/prack-user-agent-server.js deleted file mode 100644 index 2e17ec3b4..000000000 --- a/lib/core/user-agents/prack-user-agent-server.js +++ /dev/null @@ -1,33 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var transactions_1 = require("../transactions"); -var user_agent_server_1 = require("./user-agent-server"); -/** - * PRACK UAS. - * @public - */ -var PrackUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(PrackUserAgentServer, _super); - function PrackUserAgentServer(dialog, message, delegate) { - var _this = _super.call(this, transactions_1.NonInviteServerTransaction, dialog.userAgentCore, message, delegate) || this; - // Update dialog signaling state with offer/answer in body - dialog.signalingStateTransition(message); - _this.dialog = dialog; - return _this; - } - /** - * Update the dialog signaling state on a 2xx response. - * @param options - Options bucket. - */ - PrackUserAgentServer.prototype.accept = function (options) { - if (options === void 0) { options = { statusCode: 200 }; } - if (options.body) { - // Update dialog signaling state with offer/answer in body - this.dialog.signalingStateTransition(options.body); - } - return _super.prototype.accept.call(this, options); - }; - return PrackUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.PrackUserAgentServer = PrackUserAgentServer; diff --git a/lib/core/user-agents/publish-user-agent-client.d.ts b/lib/core/user-agents/publish-user-agent-client.d.ts deleted file mode 100644 index d63bc4e8d..000000000 --- a/lib/core/user-agents/publish-user-agent-client.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { OutgoingPublishRequest, OutgoingRequestDelegate, OutgoingRequestMessage } from "../messages"; -import { UserAgentCore } from "../user-agent-core"; -import { UserAgentClient } from "./user-agent-client"; -/** - * PUBLISH UAC. - * @public - */ -export declare class PublishUserAgentClient extends UserAgentClient implements OutgoingPublishRequest { - constructor(core: UserAgentCore, message: OutgoingRequestMessage, delegate?: OutgoingRequestDelegate); -} -//# sourceMappingURL=publish-user-agent-client.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/publish-user-agent-client.d.ts.map b/lib/core/user-agents/publish-user-agent-client.d.ts.map deleted file mode 100644 index bbd04271f..000000000 --- a/lib/core/user-agents/publish-user-agent-client.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"publish-user-agent-client.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/publish-user-agent-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAEtG,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,qBAAa,sBAAuB,SAAQ,eAAgB,YAAW,sBAAsB;gBAEzF,IAAI,EAAE,aAAa,EACnB,OAAO,EAAE,sBAAsB,EAC/B,QAAQ,CAAC,EAAE,uBAAuB;CAIrC"} \ No newline at end of file diff --git a/lib/core/user-agents/publish-user-agent-client.js b/lib/core/user-agents/publish-user-agent-client.js deleted file mode 100644 index 599c6e479..000000000 --- a/lib/core/user-agents/publish-user-agent-client.js +++ /dev/null @@ -1,17 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var transactions_1 = require("../transactions"); -var user_agent_client_1 = require("./user-agent-client"); -/** - * PUBLISH UAC. - * @public - */ -var PublishUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(PublishUserAgentClient, _super); - function PublishUserAgentClient(core, message, delegate) { - return _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; - } - return PublishUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.PublishUserAgentClient = PublishUserAgentClient; diff --git a/lib/core/user-agents/re-invite-user-agent-client.d.ts b/lib/core/user-agents/re-invite-user-agent-client.d.ts deleted file mode 100644 index bdb157024..000000000 --- a/lib/core/user-agents/re-invite-user-agent-client.d.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { SessionDialog } from "../dialogs"; -import { IncomingResponseMessage, OutgoingInviteRequest, OutgoingInviteRequestDelegate, RequestOptions } from "../messages"; -import { UserAgentClient } from "./user-agent-client"; -/** - * Re-INVITE UAC. - * @remarks - * 14 Modifying an Existing Session - * https://tools.ietf.org/html/rfc3261#section-14 - * 14.1 UAC Behavior - * https://tools.ietf.org/html/rfc3261#section-14.1 - * @public - */ -export declare class ReInviteUserAgentClient extends UserAgentClient implements OutgoingInviteRequest { - delegate: OutgoingInviteRequestDelegate | undefined; - private dialog; - constructor(dialog: SessionDialog, delegate?: OutgoingInviteRequestDelegate, options?: RequestOptions); - protected receiveResponse(message: IncomingResponseMessage): void; -} -//# sourceMappingURL=re-invite-user-agent-client.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/re-invite-user-agent-client.d.ts.map b/lib/core/user-agents/re-invite-user-agent-client.d.ts.map deleted file mode 100644 index b8a078afa..000000000 --- a/lib/core/user-agents/re-invite-user-agent-client.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"re-invite-user-agent-client.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/re-invite-user-agent-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,EAEL,uBAAuB,EAEvB,qBAAqB,EACrB,6BAA6B,EAE7B,cAAc,EACf,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;;;;;;GAQG;AACH,qBAAa,uBAAwB,SAAQ,eAAgB,YAAW,qBAAqB;IACpF,QAAQ,EAAE,6BAA6B,GAAG,SAAS,CAAC;IAE3D,OAAO,CAAC,MAAM,CAAgB;gBAG5B,MAAM,EAAE,aAAa,EACrB,QAAQ,CAAC,EAAE,6BAA6B,EACxC,OAAO,CAAC,EAAE,cAAc;IAW1B,SAAS,CAAC,eAAe,CAAC,OAAO,EAAE,uBAAuB,GAAG,IAAI;CAqFlE"} \ No newline at end of file diff --git a/lib/core/user-agents/re-invite-user-agent-client.js b/lib/core/user-agents/re-invite-user-agent-client.js deleted file mode 100644 index b4114b657..000000000 --- a/lib/core/user-agents/re-invite-user-agent-client.js +++ /dev/null @@ -1,113 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var messages_1 = require("../messages"); -var transactions_1 = require("../transactions"); -var user_agent_client_1 = require("./user-agent-client"); -/** - * Re-INVITE UAC. - * @remarks - * 14 Modifying an Existing Session - * https://tools.ietf.org/html/rfc3261#section-14 - * 14.1 UAC Behavior - * https://tools.ietf.org/html/rfc3261#section-14.1 - * @public - */ -var ReInviteUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(ReInviteUserAgentClient, _super); - function ReInviteUserAgentClient(dialog, delegate, options) { - var _this = this; - var message = dialog.createOutgoingRequestMessage(messages_1.C.INVITE, options); - _this = _super.call(this, transactions_1.InviteClientTransaction, dialog.userAgentCore, message, delegate) || this; - _this.delegate = delegate; - dialog.signalingStateTransition(message); - // FIXME: TODO: next line obviously needs to be improved... - dialog.reinviteUserAgentClient = _this; // let the dialog know re-invite request sent - _this.dialog = dialog; - return _this; - } - ReInviteUserAgentClient.prototype.receiveResponse = function (message) { - var _this = this; - var statusCode = message.statusCode ? message.statusCode.toString() : ""; - if (!statusCode) { - throw new Error("Response status code undefined."); - } - switch (true) { - case /^100$/.test(statusCode): - if (this.delegate && this.delegate.onTrying) { - this.delegate.onTrying({ message: message }); - } - break; - case /^1[0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onProgress) { - this.delegate.onProgress({ - message: message, - session: this.dialog, - prack: function (options) { - throw new Error("Unimplemented."); - } - }); - } - break; - case /^2[0-9]{2}$/.test(statusCode): - // Update dialog signaling state with offer/answer in body - this.dialog.signalingStateTransition(message); - if (this.delegate && this.delegate.onAccept) { - this.delegate.onAccept({ - message: message, - session: this.dialog, - ack: function (options) { - var outgoingAckRequest = _this.dialog.ack(options); - return outgoingAckRequest; - } - }); - } - break; - case /^3[0-9]{2}$/.test(statusCode): - this.dialog.signalingStateRollback(); - this.dialog.reinviteUserAgentClient = undefined; // ACK was handled by transaction - if (this.delegate && this.delegate.onRedirect) { - this.delegate.onRedirect({ message: message }); - } - break; - case /^[4-6][0-9]{2}$/.test(statusCode): - this.dialog.signalingStateRollback(); - this.dialog.reinviteUserAgentClient = undefined; // ACK was handled by transaction - if (this.delegate && this.delegate.onReject) { - this.delegate.onReject({ message: message }); - } - else { - // If a UA receives a non-2xx final response to a re-INVITE, the session - // parameters MUST remain unchanged, as if no re-INVITE had been issued. - // Note that, as stated in Section 12.2.1.2, if the non-2xx final - // response is a 481 (Call/Transaction Does Not Exist), or a 408 - // (Request Timeout), or no response at all is received for the re- - // INVITE (that is, a timeout is returned by the INVITE client - // transaction), the UAC will terminate the dialog. - // - // If a UAC receives a 491 response to a re-INVITE, it SHOULD start a - // timer with a value T chosen as follows: - // - // 1. If the UAC is the owner of the Call-ID of the dialog ID - // (meaning it generated the value), T has a randomly chosen value - // between 2.1 and 4 seconds in units of 10 ms. - // - // 2. If the UAC is not the owner of the Call-ID of the dialog ID, T - // has a randomly chosen value of between 0 and 2 seconds in units - // of 10 ms. - // - // When the timer fires, the UAC SHOULD attempt the re-INVITE once more, - // if it still desires for that session modification to take place. For - // example, if the call was already hung up with a BYE, the re-INVITE - // would not take place. - // https://tools.ietf.org/html/rfc3261#section-14.1 - // FIXME: TODO: The above. - } - break; - default: - throw new Error("Invalid status code " + statusCode); - } - }; - return ReInviteUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.ReInviteUserAgentClient = ReInviteUserAgentClient; diff --git a/lib/core/user-agents/re-invite-user-agent-server.d.ts b/lib/core/user-agents/re-invite-user-agent-server.d.ts deleted file mode 100644 index 8083bb671..000000000 --- a/lib/core/user-agents/re-invite-user-agent-server.d.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { SessionDialog } from "../dialogs"; -import { IncomingInviteRequest, IncomingRequestDelegate, IncomingRequestMessage, OutgoingResponse, OutgoingResponseWithSession, ResponseOptions, URI } from "../messages"; -import { UserAgentServer } from "./user-agent-server"; -/** - * Re-INVITE UAS. - * @remarks - * 14 Modifying an Existing Session - * https://tools.ietf.org/html/rfc3261#section-14 - * 14.2 UAS Behavior - * https://tools.ietf.org/html/rfc3261#section-14.2 - * @public - */ -export declare class ReInviteUserAgentServer extends UserAgentServer implements IncomingInviteRequest { - private dialog; - constructor(dialog: SessionDialog, message: IncomingRequestMessage, delegate?: IncomingRequestDelegate); - /** - * Update the dialog signaling state on a 2xx response. - * @param options - Options bucket. - */ - accept(options?: ResponseOptions): OutgoingResponseWithSession; - /** - * Update the dialog signaling state on a 1xx response. - * @param options - Progress options bucket. - */ - progress(options?: ResponseOptions): OutgoingResponseWithSession; - /** - * TODO: Not Yet Supported - * @param contacts - Contacts to redirect to. - * @param options - Redirect options bucket. - */ - redirect(contacts: Array, options?: ResponseOptions): OutgoingResponse; - /** - * 3.1 Background on Re-INVITE Handling by UASs - * An error response to a re-INVITE has the following semantics. As - * specified in Section 12.2.2 of RFC 3261 [RFC3261], if a re-INVITE is - * rejected, no state changes are performed. - * https://tools.ietf.org/html/rfc6141#section-3.1 - * @param options - Reject options bucket. - */ - reject(options?: ResponseOptions): OutgoingResponse; -} -//# sourceMappingURL=re-invite-user-agent-server.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/re-invite-user-agent-server.d.ts.map b/lib/core/user-agents/re-invite-user-agent-server.d.ts.map deleted file mode 100644 index 946f3f568..000000000 --- a/lib/core/user-agents/re-invite-user-agent-server.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"re-invite-user-agent-server.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/re-invite-user-agent-server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,EACL,qBAAqB,EACrB,uBAAuB,EACvB,sBAAsB,EACtB,gBAAgB,EAChB,2BAA2B,EAC3B,eAAe,EACf,GAAG,EACJ,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;;;;;;GAQG;AACH,qBAAa,uBAAwB,SAAQ,eAAgB,YAAW,qBAAqB;IAC3F,OAAO,CAAC,MAAM,CAAgB;gBAG5B,MAAM,EAAE,aAAa,EACrB,OAAO,EAAE,sBAAsB,EAC/B,QAAQ,CAAC,EAAE,uBAAuB;IAOpC;;;OAGG;IACI,MAAM,CAAC,OAAO,GAAE,eAAqC,GAAG,2BAA2B;IA+B1F;;;OAGG;IACI,QAAQ,CAAC,OAAO,GAAE,eAAqC,GAAG,2BAA2B;IAc5F;;;;OAIG;IACI,QAAQ,CAAC,QAAQ,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,OAAO,GAAE,eAAqC,GAAG,gBAAgB;IAMvG;;;;;;;OAOG;IACI,MAAM,CAAC,OAAO,GAAE,eAAqC,GAAG,gBAAgB;CAKhF"} \ No newline at end of file diff --git a/lib/core/user-agents/re-invite-user-agent-server.js b/lib/core/user-agents/re-invite-user-agent-server.js deleted file mode 100644 index e55e74cd7..000000000 --- a/lib/core/user-agents/re-invite-user-agent-server.js +++ /dev/null @@ -1,96 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var transactions_1 = require("../transactions"); -var user_agent_server_1 = require("./user-agent-server"); -/** - * Re-INVITE UAS. - * @remarks - * 14 Modifying an Existing Session - * https://tools.ietf.org/html/rfc3261#section-14 - * 14.2 UAS Behavior - * https://tools.ietf.org/html/rfc3261#section-14.2 - * @public - */ -var ReInviteUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(ReInviteUserAgentServer, _super); - function ReInviteUserAgentServer(dialog, message, delegate) { - var _this = _super.call(this, transactions_1.InviteServerTransaction, dialog.userAgentCore, message, delegate) || this; - dialog.reinviteUserAgentServer = _this; - _this.dialog = dialog; - return _this; - } - /** - * Update the dialog signaling state on a 2xx response. - * @param options - Options bucket. - */ - ReInviteUserAgentServer.prototype.accept = function (options) { - if (options === void 0) { options = { statusCode: 200 }; } - // FIXME: The next two lines SHOULD go away, but I suppose it's technically harmless... - // These are here because some versions of SIP.js prior to 0.13.8 set the route set - // of all in dialog ACKs based on the Record-Route headers in the associated 2xx - // response. While this worked for dialog forming 2xx responses, it was technically - // broken for re-INVITE ACKS as it only worked if the UAS populated the Record-Route - // headers in the re-INVITE 2xx response (which is not required and a waste of bandwidth - // as the should be ignored if present in re-INVITE ACKS) and the UAS populated - // the Record-Route headers with the correct values (would be weird not too, but...). - // Anyway, for now the technically useless Record-Route headers are being added - // to maintain "backwards compatibility" with the older broken versions of SIP.js. - options.extraHeaders = options.extraHeaders || []; - options.extraHeaders = options.extraHeaders.concat(this.dialog.routeSet.map(function (route) { return "Record-Route: " + route; })); - // Send and return the response - var response = _super.prototype.accept.call(this, options); - var session = this.dialog; - var result = tslib_1.__assign({}, response, { session: session }); - if (options.body) { - // Update dialog signaling state with offer/answer in body - this.dialog.signalingStateTransition(options.body); - } - // Update dialog - this.dialog.reConfirm(); - return result; - }; - /** - * Update the dialog signaling state on a 1xx response. - * @param options - Progress options bucket. - */ - ReInviteUserAgentServer.prototype.progress = function (options) { - if (options === void 0) { options = { statusCode: 180 }; } - // Send and return the response - var response = _super.prototype.progress.call(this, options); - var session = this.dialog; - var result = tslib_1.__assign({}, response, { session: session }); - // Update dialog signaling state - if (options.body) { - this.dialog.signalingStateTransition(options.body); - } - return result; - }; - /** - * TODO: Not Yet Supported - * @param contacts - Contacts to redirect to. - * @param options - Redirect options bucket. - */ - ReInviteUserAgentServer.prototype.redirect = function (contacts, options) { - if (options === void 0) { options = { statusCode: 302 }; } - this.dialog.signalingStateRollback(); - this.dialog.reinviteUserAgentServer = undefined; // ACK will be handled by transaction - throw new Error("Unimplemented."); - }; - /** - * 3.1 Background on Re-INVITE Handling by UASs - * An error response to a re-INVITE has the following semantics. As - * specified in Section 12.2.2 of RFC 3261 [RFC3261], if a re-INVITE is - * rejected, no state changes are performed. - * https://tools.ietf.org/html/rfc6141#section-3.1 - * @param options - Reject options bucket. - */ - ReInviteUserAgentServer.prototype.reject = function (options) { - if (options === void 0) { options = { statusCode: 488 }; } - this.dialog.signalingStateRollback(); - this.dialog.reinviteUserAgentServer = undefined; // ACK will be handled by transaction - return _super.prototype.reject.call(this, options); - }; - return ReInviteUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.ReInviteUserAgentServer = ReInviteUserAgentServer; diff --git a/lib/core/user-agents/re-subscribe-user-agent-client.d.ts b/lib/core/user-agents/re-subscribe-user-agent-client.d.ts deleted file mode 100644 index 75183c74c..000000000 --- a/lib/core/user-agents/re-subscribe-user-agent-client.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { SubscriptionDialog } from "../dialogs"; -import { IncomingResponseMessage, OutgoingRequestDelegate, OutgoingSubscribeRequest, RequestOptions } from "../messages"; -import { UserAgentClient } from "./user-agent-client"; -/** - * Re-SUBSCRIBE UAC. - * @public - */ -export declare class ReSubscribeUserAgentClient extends UserAgentClient implements OutgoingSubscribeRequest { - private dialog; - constructor(dialog: SubscriptionDialog, delegate?: OutgoingRequestDelegate, options?: RequestOptions); - waitNotifyStop(): void; - /** - * Receive a response from the transaction layer. - * @param message - Incoming response message. - */ - protected receiveResponse(message: IncomingResponseMessage): void; -} -//# sourceMappingURL=re-subscribe-user-agent-client.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/re-subscribe-user-agent-client.d.ts.map b/lib/core/user-agents/re-subscribe-user-agent-client.d.ts.map deleted file mode 100644 index 62ef495b7..000000000 --- a/lib/core/user-agents/re-subscribe-user-agent-client.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"re-subscribe-user-agent-client.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/re-subscribe-user-agent-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAChD,OAAO,EAEL,uBAAuB,EACvB,uBAAuB,EACvB,wBAAwB,EACxB,cAAc,EACf,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,qBAAa,0BAA2B,SAAQ,eAAgB,YAAW,wBAAwB;IACjG,OAAO,CAAC,MAAM,CAAqB;gBAGjC,MAAM,EAAE,kBAAkB,EAC1B,QAAQ,CAAC,EAAE,uBAAuB,EAClC,OAAO,CAAC,EAAE,cAAc;IAOnB,cAAc,IAAI,IAAI;IAK7B;;;OAGG;IACH,SAAS,CAAC,eAAe,CAAC,OAAO,EAAE,uBAAuB,GAAG,IAAI;CA4ClE"} \ No newline at end of file diff --git a/lib/core/user-agents/re-subscribe-user-agent-client.js b/lib/core/user-agents/re-subscribe-user-agent-client.js deleted file mode 100644 index 5e21a21fe..000000000 --- a/lib/core/user-agents/re-subscribe-user-agent-client.js +++ /dev/null @@ -1,73 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var messages_1 = require("../messages"); -var transactions_1 = require("../transactions"); -var user_agent_client_1 = require("./user-agent-client"); -/** - * Re-SUBSCRIBE UAC. - * @public - */ -var ReSubscribeUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(ReSubscribeUserAgentClient, _super); - function ReSubscribeUserAgentClient(dialog, delegate, options) { - var _this = this; - var message = dialog.createOutgoingRequestMessage(messages_1.C.SUBSCRIBE, options); - _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; - _this.dialog = dialog; - return _this; - } - ReSubscribeUserAgentClient.prototype.waitNotifyStop = function () { - // TODO: Placeholder. Not utilized currently. - return; - }; - /** - * Receive a response from the transaction layer. - * @param message - Incoming response message. - */ - ReSubscribeUserAgentClient.prototype.receiveResponse = function (message) { - if (message.statusCode && message.statusCode >= 200 && message.statusCode < 300) { - // The "Expires" header field in a 200-class response to SUBSCRIBE - // request indicates the actual duration for which the subscription will - // remain active (unless refreshed). The received value might be - // smaller than the value indicated in the SUBSCRIBE request but cannot - // be larger; see Section 4.2.1 for details. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - var expires = message.getHeader("Expires"); - if (!expires) { - this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE"); - } - else { - var subscriptionExpiresReceived = Number(expires); - if (this.dialog.subscriptionExpires > subscriptionExpiresReceived) { - this.dialog.subscriptionExpires = subscriptionExpiresReceived; - } - } - } - if (message.statusCode && message.statusCode >= 400 && message.statusCode < 700) { - // If a SUBSCRIBE request to refresh a subscription receives a 404, 405, - // 410, 416, 480-485, 489, 501, or 604 response, the subscriber MUST - // consider the subscription terminated. (See [RFC5057] for further - // details and notes about the effect of error codes on dialogs and - // usages within dialog, such as subscriptions). If the subscriber - // wishes to re-subscribe to the state, he does so by composing an - // unrelated initial SUBSCRIBE request with a freshly generated Call-ID - // and a new, unique "From" tag (see Section 4.1.2.1). - // https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - var errorCodes = [404, 405, 410, 416, 480, 481, 482, 483, 484, 485, 489, 501, 604]; - if (errorCodes.includes(message.statusCode)) { - this.dialog.terminate(); - } - // If a SUBSCRIBE request to refresh a subscription fails with any error - // code other than those listed above, the original subscription is - // still considered valid for the duration of the most recently known - // "Expires" value as negotiated by the most recent successful SUBSCRIBE - // transaction, or as communicated by a NOTIFY request in its - // "Subscription-State" header field "expires" parameter. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - } - _super.prototype.receiveResponse.call(this, message); - }; - return ReSubscribeUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.ReSubscribeUserAgentClient = ReSubscribeUserAgentClient; diff --git a/lib/core/user-agents/re-subscribe-user-agent-server.d.ts b/lib/core/user-agents/re-subscribe-user-agent-server.d.ts deleted file mode 100644 index 0a11912a4..000000000 --- a/lib/core/user-agents/re-subscribe-user-agent-server.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { Dialog } from "../dialogs"; -import { IncomingRequestDelegate, IncomingRequestMessage, IncomingSubscribeRequest } from "../messages"; -import { UserAgentServer } from "./user-agent-server"; -/** - * Re-SUBSCRIBE UAS. - * @public - */ -export declare class ReSubscribeUserAgentServer extends UserAgentServer implements IncomingSubscribeRequest { - constructor(dialog: Dialog, message: IncomingRequestMessage, delegate?: IncomingRequestDelegate); -} -//# sourceMappingURL=re-subscribe-user-agent-server.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/re-subscribe-user-agent-server.d.ts.map b/lib/core/user-agents/re-subscribe-user-agent-server.d.ts.map deleted file mode 100644 index 3d5165c88..000000000 --- a/lib/core/user-agents/re-subscribe-user-agent-server.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"re-subscribe-user-agent-server.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/re-subscribe-user-agent-server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AACpC,OAAO,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AAExG,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,qBAAa,0BAA2B,SAAQ,eAAgB,YAAW,wBAAwB;gBAE/F,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,sBAAsB,EAC/B,QAAQ,CAAC,EAAE,uBAAuB;CAIrC"} \ No newline at end of file diff --git a/lib/core/user-agents/re-subscribe-user-agent-server.js b/lib/core/user-agents/re-subscribe-user-agent-server.js deleted file mode 100644 index 1f24314b8..000000000 --- a/lib/core/user-agents/re-subscribe-user-agent-server.js +++ /dev/null @@ -1,17 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var transactions_1 = require("../transactions"); -var user_agent_server_1 = require("./user-agent-server"); -/** - * Re-SUBSCRIBE UAS. - * @public - */ -var ReSubscribeUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(ReSubscribeUserAgentServer, _super); - function ReSubscribeUserAgentServer(dialog, message, delegate) { - return _super.call(this, transactions_1.NonInviteServerTransaction, dialog.userAgentCore, message, delegate) || this; - } - return ReSubscribeUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.ReSubscribeUserAgentServer = ReSubscribeUserAgentServer; diff --git a/lib/core/user-agents/refer-user-agent-client.d.ts b/lib/core/user-agents/refer-user-agent-client.d.ts deleted file mode 100644 index 92e14d6f7..000000000 --- a/lib/core/user-agents/refer-user-agent-client.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { SessionDialog } from "../dialogs"; -import { OutgoingReferRequest, OutgoingRequestDelegate, RequestOptions } from "../messages"; -import { UserAgentClient } from "./user-agent-client"; -/** - * REFER UAC. - * @public - */ -export declare class ReferUserAgentClient extends UserAgentClient implements OutgoingReferRequest { - constructor(dialog: SessionDialog, delegate?: OutgoingRequestDelegate, options?: RequestOptions); -} -//# sourceMappingURL=refer-user-agent-client.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/refer-user-agent-client.d.ts.map b/lib/core/user-agents/refer-user-agent-client.d.ts.map deleted file mode 100644 index e958a20db..000000000 --- a/lib/core/user-agents/refer-user-agent-client.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"refer-user-agent-client.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/refer-user-agent-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,EAAK,oBAAoB,EAAE,uBAAuB,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAE/F,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,qBAAa,oBAAqB,SAAQ,eAAgB,YAAW,oBAAoB;gBAErF,MAAM,EAAE,aAAa,EACrB,QAAQ,CAAC,EAAE,uBAAuB,EAClC,OAAO,CAAC,EAAE,cAAc;CAK3B"} \ No newline at end of file diff --git a/lib/core/user-agents/refer-user-agent-client.js b/lib/core/user-agents/refer-user-agent-client.js deleted file mode 100644 index 44ce21691..000000000 --- a/lib/core/user-agents/refer-user-agent-client.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var messages_1 = require("../messages"); -var transactions_1 = require("../transactions"); -var user_agent_client_1 = require("./user-agent-client"); -/** - * REFER UAC. - * @public - */ -var ReferUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(ReferUserAgentClient, _super); - function ReferUserAgentClient(dialog, delegate, options) { - var _this = this; - var message = dialog.createOutgoingRequestMessage(messages_1.C.REFER, options); - _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; - return _this; - } - return ReferUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.ReferUserAgentClient = ReferUserAgentClient; diff --git a/lib/core/user-agents/refer-user-agent-server.d.ts b/lib/core/user-agents/refer-user-agent-server.d.ts deleted file mode 100644 index 8203a6445..000000000 --- a/lib/core/user-agents/refer-user-agent-server.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { SessionDialog } from "../dialogs"; -import { IncomingReferRequest, IncomingRequestDelegate, IncomingRequestMessage } from "../messages"; -import { UserAgentCore } from "../user-agent-core"; -import { UserAgentServer } from "./user-agent-server"; -/** - * REFER UAS. - * @public - */ -export declare class ReferUserAgentServer extends UserAgentServer implements IncomingReferRequest { - /** - * REFER UAS constructor. - * @param dialogOrCore - Dialog for in dialog REFER, UserAgentCore for out of dialog REFER. - * @param message - Incoming REFER request message. - */ - constructor(dialogOrCore: SessionDialog | UserAgentCore, message: IncomingRequestMessage, delegate?: IncomingRequestDelegate); -} -//# sourceMappingURL=refer-user-agent-server.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/refer-user-agent-server.d.ts.map b/lib/core/user-agents/refer-user-agent-server.d.ts.map deleted file mode 100644 index 86accdd65..000000000 --- a/lib/core/user-agents/refer-user-agent-server.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"refer-user-agent-server.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/refer-user-agent-server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,EAAE,oBAAoB,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAEpG,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,qBAAa,oBAAqB,SAAQ,eAAgB,YAAW,oBAAoB;IACvF;;;;OAIG;gBAED,YAAY,EAAE,aAAa,GAAG,aAAa,EAC3C,OAAO,EAAE,sBAAsB,EAC/B,QAAQ,CAAC,EAAE,uBAAuB;CAQrC"} \ No newline at end of file diff --git a/lib/core/user-agents/refer-user-agent-server.js b/lib/core/user-agents/refer-user-agent-server.js deleted file mode 100644 index 1500a929b..000000000 --- a/lib/core/user-agents/refer-user-agent-server.js +++ /dev/null @@ -1,30 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var transactions_1 = require("../transactions"); -var user_agent_server_1 = require("./user-agent-server"); -/** - * REFER UAS. - * @public - */ -var ReferUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(ReferUserAgentServer, _super); - /** - * REFER UAS constructor. - * @param dialogOrCore - Dialog for in dialog REFER, UserAgentCore for out of dialog REFER. - * @param message - Incoming REFER request message. - */ - function ReferUserAgentServer(dialogOrCore, message, delegate) { - var _this = this; - var userAgentCore = instanceOfSessionDialog(dialogOrCore) ? - dialogOrCore.userAgentCore : - dialogOrCore; - _this = _super.call(this, transactions_1.NonInviteServerTransaction, userAgentCore, message, delegate) || this; - return _this; - } - return ReferUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.ReferUserAgentServer = ReferUserAgentServer; -function instanceOfSessionDialog(object) { - return object.userAgentCore !== undefined; -} diff --git a/lib/core/user-agents/register-user-agent-client.d.ts b/lib/core/user-agents/register-user-agent-client.d.ts deleted file mode 100644 index 71e4150be..000000000 --- a/lib/core/user-agents/register-user-agent-client.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { OutgoingRegisterRequest, OutgoingRequestDelegate, OutgoingRequestMessage } from "../messages"; -import { UserAgentCore } from "../user-agent-core"; -import { UserAgentClient } from "./user-agent-client"; -/** - * REGISTER UAC. - * @public - */ -export declare class RegisterUserAgentClient extends UserAgentClient implements OutgoingRegisterRequest { - constructor(core: UserAgentCore, message: OutgoingRequestMessage, delegate?: OutgoingRequestDelegate); -} -//# sourceMappingURL=register-user-agent-client.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/register-user-agent-client.d.ts.map b/lib/core/user-agents/register-user-agent-client.d.ts.map deleted file mode 100644 index 0be5962e1..000000000 --- a/lib/core/user-agents/register-user-agent-client.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"register-user-agent-client.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/register-user-agent-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAEvG,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,qBAAa,uBAAwB,SAAQ,eAAgB,YAAW,uBAAuB;gBAE3F,IAAI,EAAE,aAAa,EACnB,OAAO,EAAE,sBAAsB,EAC/B,QAAQ,CAAC,EAAE,uBAAuB;CAIrC"} \ No newline at end of file diff --git a/lib/core/user-agents/register-user-agent-client.js b/lib/core/user-agents/register-user-agent-client.js deleted file mode 100644 index 6f5750064..000000000 --- a/lib/core/user-agents/register-user-agent-client.js +++ /dev/null @@ -1,17 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var transactions_1 = require("../transactions"); -var user_agent_client_1 = require("./user-agent-client"); -/** - * REGISTER UAC. - * @public - */ -var RegisterUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(RegisterUserAgentClient, _super); - function RegisterUserAgentClient(core, message, delegate) { - return _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; - } - return RegisterUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.RegisterUserAgentClient = RegisterUserAgentClient; diff --git a/lib/core/user-agents/register-user-agent-server.d.ts b/lib/core/user-agents/register-user-agent-server.d.ts deleted file mode 100644 index b9f6ce296..000000000 --- a/lib/core/user-agents/register-user-agent-server.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { IncomingRegisterRequest, IncomingRequestDelegate, IncomingRequestMessage } from "../messages"; -import { UserAgentCore } from "../user-agent-core"; -import { UserAgentServer } from "./user-agent-server"; -/** - * REGISTER UAS. - * @public - */ -export declare class RegisterUserAgentServer extends UserAgentServer implements IncomingRegisterRequest { - protected core: UserAgentCore; - constructor(core: UserAgentCore, message: IncomingRequestMessage, delegate?: IncomingRequestDelegate); -} -//# sourceMappingURL=register-user-agent-server.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/register-user-agent-server.d.ts.map b/lib/core/user-agents/register-user-agent-server.d.ts.map deleted file mode 100644 index ea01489bd..000000000 --- a/lib/core/user-agents/register-user-agent-server.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"register-user-agent-server.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/register-user-agent-server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAEvG,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,qBAAa,uBAAwB,SAAQ,eAAgB,YAAW,uBAAuB;IAE3F,SAAS,CAAC,IAAI,EAAE,aAAa;gBAAnB,IAAI,EAAE,aAAa,EAC7B,OAAO,EAAE,sBAAsB,EAC/B,QAAQ,CAAC,EAAE,uBAAuB;CAIrC"} \ No newline at end of file diff --git a/lib/core/user-agents/register-user-agent-server.js b/lib/core/user-agents/register-user-agent-server.js deleted file mode 100644 index 2b6754316..000000000 --- a/lib/core/user-agents/register-user-agent-server.js +++ /dev/null @@ -1,19 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var transactions_1 = require("../transactions"); -var user_agent_server_1 = require("./user-agent-server"); -/** - * REGISTER UAS. - * @public - */ -var RegisterUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(RegisterUserAgentServer, _super); - function RegisterUserAgentServer(core, message, delegate) { - var _this = _super.call(this, transactions_1.NonInviteServerTransaction, core, message, delegate) || this; - _this.core = core; - return _this; - } - return RegisterUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.RegisterUserAgentServer = RegisterUserAgentServer; diff --git a/lib/core/user-agents/subscribe-user-agent-client.d.ts b/lib/core/user-agents/subscribe-user-agent-client.d.ts deleted file mode 100644 index 6061982c0..000000000 --- a/lib/core/user-agents/subscribe-user-agent-client.d.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { IncomingResponseMessage, OutgoingRequestMessage, OutgoingSubscribeRequest, OutgoingSubscribeRequestDelegate } from "../messages"; -import { UserAgentCore } from "../user-agent-core"; -import { NotifyUserAgentServer } from "./notify-user-agent-server"; -import { UserAgentClient } from "./user-agent-client"; -/** - * SUBSCRIBE UAC. - * @remarks - * 4.1. Subscriber Behavior - * https://tools.ietf.org/html/rfc6665#section-4.1 - * - * User agent client for installation of a single subscription per SUBSCRIBE request. - * TODO: Support for installation of multiple subscriptions on forked SUBSCRIBE reqeuests. - * @public - */ -export declare class SubscribeUserAgentClient extends UserAgentClient implements OutgoingSubscribeRequest { - delegate: OutgoingSubscribeRequestDelegate | undefined; - /** Dialog created upon receiving the first NOTIFY. */ - private dialog; - /** Identifier of this user agent client. */ - private subscriberId; - /** When the subscription expires. Starts as requested expires and updated on 200 and NOTIFY. */ - private subscriptionExpires; - /** The requested expires for the subscription. */ - private subscriptionExpiresRequested; - /** Subscription event being targeted. */ - private subscriptionEvent; - /** Subscription state. */ - private subscriptionState; - /** Timer N Id. */ - private N; - constructor(core: UserAgentCore, message: OutgoingRequestMessage, delegate?: OutgoingSubscribeRequestDelegate); - /** - * Destructor. - * Note that Timer N may live on waiting for an initial NOTIFY and - * the delegate may still receive that NOTIFY. If you don't want - * that behavior then either clear the delegate so the delegate - * doesn't get called (a 200 will be sent in response to the NOTIFY) - * or call `waitNotifyStop` which will clear Timer N and remove this - * UAC from the core (a 481 will be sent in response to the NOTIFY). - */ - dispose(): void; - /** - * Handle out of dialog NOTIFY assoicated with SUBSCRIBE request. - * This is the first NOTIFY received after the SUBSCRIBE request. - * @param uas - User agent server handling the subscription creating NOTIFY. - */ - onNotify(uas: NotifyUserAgentServer): void; - waitNotifyStart(): void; - waitNotifyStop(): void; - /** - * Receive a response from the transaction layer. - * @param message - Incoming response message. - */ - protected receiveResponse(message: IncomingResponseMessage): void; - /** - * To ensure that subscribers do not wait indefinitely for a - * subscription to be established, a subscriber starts a Timer N, set to - * 64*T1, when it sends a SUBSCRIBE request. If this Timer N expires - * prior to the receipt of a NOTIFY request, the subscriber considers - * the subscription failed, and cleans up any state associated with the - * subscription attempt. - * https://tools.ietf.org/html/rfc6665#section-4.1.2.4 - */ - private timer_N; -} -//# sourceMappingURL=subscribe-user-agent-client.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/subscribe-user-agent-client.d.ts.map b/lib/core/user-agents/subscribe-user-agent-client.d.ts.map deleted file mode 100644 index 4f4500a0b..000000000 --- a/lib/core/user-agents/subscribe-user-agent-client.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"subscribe-user-agent-client.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/subscribe-user-agent-client.ts"],"names":[],"mappings":"AACA,OAAO,EACL,uBAAuB,EACvB,sBAAsB,EACtB,wBAAwB,EACxB,gCAAgC,EACjC,MAAM,aAAa,CAAC;AAIrB,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AACnE,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;;;;;;;GASG;AACH,qBAAa,wBAAyB,SAAQ,eAAgB,YAAW,wBAAwB;IACxF,QAAQ,EAAE,gCAAgC,GAAG,SAAS,CAAC;IAE9D,sDAAsD;IACtD,OAAO,CAAC,MAAM,CAAiC;IAC/C,4CAA4C;IAC5C,OAAO,CAAC,YAAY,CAAS;IAC7B,gGAAgG;IAChG,OAAO,CAAC,mBAAmB,CAAS;IACpC,kDAAkD;IAClD,OAAO,CAAC,4BAA4B,CAAS;IAC7C,yCAAyC;IACzC,OAAO,CAAC,iBAAiB,CAAS;IAClC,0BAA0B;IAC1B,OAAO,CAAC,iBAAiB,CAAoB;IAC7C,kBAAkB;IAClB,OAAO,CAAC,CAAC,CAAkB;gBAGzB,IAAI,EAAE,aAAa,EACnB,OAAO,EAAE,sBAAsB,EAC/B,QAAQ,CAAC,EAAE,gCAAgC;IAyB7C;;;;;;;;OAQG;IACI,OAAO,IAAI,IAAI;IAItB;;;;OAIG;IACI,QAAQ,CAAC,GAAG,EAAE,qBAAqB,GAAG,IAAI;IAiK1C,eAAe,IAAI,IAAI;IASvB,cAAc,IAAI,IAAI;IAU7B;;;OAGG;IACH,SAAS,CAAC,eAAe,CAAC,OAAO,EAAE,uBAAuB,GAAG,IAAI;IAyDjE;;;;;;;;OAQG;IACH,OAAO,CAAC,OAAO;CAOhB"} \ No newline at end of file diff --git a/lib/core/user-agents/subscribe-user-agent-client.js b/lib/core/user-agents/subscribe-user-agent-client.js deleted file mode 100644 index b3fd19914..000000000 --- a/lib/core/user-agents/subscribe-user-agent-client.js +++ /dev/null @@ -1,297 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var subscription_dialog_1 = require("../dialogs/subscription-dialog"); -var subscription_1 = require("../subscription"); -var timers_1 = require("../timers"); -var transactions_1 = require("../transactions"); -var user_agent_client_1 = require("./user-agent-client"); -/** - * SUBSCRIBE UAC. - * @remarks - * 4.1. Subscriber Behavior - * https://tools.ietf.org/html/rfc6665#section-4.1 - * - * User agent client for installation of a single subscription per SUBSCRIBE request. - * TODO: Support for installation of multiple subscriptions on forked SUBSCRIBE reqeuests. - * @public - */ -var SubscribeUserAgentClient = /** @class */ (function (_super) { - tslib_1.__extends(SubscribeUserAgentClient, _super); - function SubscribeUserAgentClient(core, message, delegate) { - var _this = this; - // Get event from request message. - var event = message.getHeader("Event"); - if (!event) { - throw new Error("Event undefined"); - } - // Get expires from reqeust message. - var expires = message.getHeader("Expires"); - if (!expires) { - throw new Error("Expires undefined"); - } - _this = _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; - _this.delegate = delegate; - // FIXME: Subscriber id should also be matching on event id. - _this.subscriberId = message.callId + message.fromTag + event; - _this.subscriptionExpiresRequested = _this.subscriptionExpires = Number(expires); - _this.subscriptionEvent = event; - _this.subscriptionState = subscription_1.SubscriptionState.NotifyWait; - // Start waiting for a NOTIFY we can use to create a subscription. - _this.waitNotifyStart(); - return _this; - } - /** - * Destructor. - * Note that Timer N may live on waiting for an initial NOTIFY and - * the delegate may still receive that NOTIFY. If you don't want - * that behavior then either clear the delegate so the delegate - * doesn't get called (a 200 will be sent in response to the NOTIFY) - * or call `waitNotifyStop` which will clear Timer N and remove this - * UAC from the core (a 481 will be sent in response to the NOTIFY). - */ - SubscribeUserAgentClient.prototype.dispose = function () { - _super.prototype.dispose.call(this); - }; - /** - * Handle out of dialog NOTIFY assoicated with SUBSCRIBE request. - * This is the first NOTIFY received after the SUBSCRIBE request. - * @param uas - User agent server handling the subscription creating NOTIFY. - */ - SubscribeUserAgentClient.prototype.onNotify = function (uas) { - // NOTIFY requests are matched to such SUBSCRIBE requests if they - // contain the same "Call-ID", a "To" header field "tag" parameter that - // matches the "From" header field "tag" parameter of the SUBSCRIBE - // request, and the same "Event" header field. Rules for comparisons of - // the "Event" header fields are described in Section 8.2.1. - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - var event = uas.message.parseHeader("Event").event; - if (!event || event !== this.subscriptionEvent) { - this.logger.warn("Failed to parse event."); - uas.reject({ statusCode: 489 }); - return; - } - // NOTIFY requests MUST contain "Subscription-State" header fields that - // indicate the status of the subscription. - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - var subscriptionState = uas.message.parseHeader("Subscription-State"); - if (!subscriptionState || !subscriptionState.state) { - this.logger.warn("Failed to parse subscription state."); - uas.reject({ statusCode: 489 }); - return; - } - // Validate subscription state. - var state = subscriptionState.state; - switch (state) { - case "pending": - break; - case "active": - break; - case "terminated": - break; - default: - this.logger.warn("Invalid subscription state " + state); - uas.reject({ statusCode: 489 }); - return; - } - // Dialogs usages are created upon completion of a NOTIFY transaction - // for a new subscription, unless the NOTIFY request contains a - // "Subscription-State" of "terminated." - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - if (state !== "terminated") { - // The Contact header field MUST be present and contain exactly one SIP - // or SIPS URI in any request that can result in the establishment of a - // dialog. - // https://tools.ietf.org/html/rfc3261#section-8.1.1.8 - var contact = uas.message.parseHeader("contact"); - if (!contact) { - this.logger.warn("Failed to parse contact."); - uas.reject({ statusCode: 489 }); - return; - } - } - // In accordance with the rules for proxying non-INVITE requests as - // defined in [RFC3261], successful SUBSCRIBE requests will receive only - // one 200-class response; however, due to forking, the subscription may - // have been accepted by multiple nodes. The subscriber MUST therefore - // be prepared to receive NOTIFY requests with "From:" tags that differ - // from the "To:" tag received in the SUBSCRIBE 200-class response. - // - // If multiple NOTIFY requests are received in different dialogs in - // response to a single SUBSCRIBE request, each dialog represents a - // different destination to which the SUBSCRIBE request was forked. - // Subscriber handling in such situations varies by event package; see - // Section 5.4.9 for details. - // https://tools.ietf.org/html/rfc6665#section-4.1.4 - // Each event package MUST specify whether forked SUBSCRIBE requests are - // allowed to install multiple subscriptions. - // - // If such behavior is not allowed, the first potential dialog- - // establishing message will create a dialog. All subsequent NOTIFY - // requests that correspond to the SUBSCRIBE request (i.e., have - // matching "To", "From", "Call-ID", and "Event" header fields, as well - // as "From" header field "tag" parameter and "Event" header field "id" - // parameter) but that do not match the dialog would be rejected with a - // 481 response. Note that the 200-class response to the SUBSCRIBE - // request can arrive after a matching NOTIFY request has been received; - // such responses might not correlate to the same dialog established by - // the NOTIFY request. Except as required to complete the SUBSCRIBE - // transaction, such non-matching 200-class responses are ignored. - // - // If installing of multiple subscriptions by way of a single forked - // SUBSCRIBE request is allowed, the subscriber establishes a new dialog - // towards each notifier by returning a 200-class response to each - // NOTIFY request. Each dialog is then handled as its own entity and is - // refreshed independently of the other dialogs. - // - // In the case that multiple subscriptions are allowed, the event - // package MUST specify whether merging of the notifications to form a - // single state is required, and how such merging is to be performed. - // Note that it is possible that some event packages may be defined in - // such a way that each dialog is tied to a mutually exclusive state - // that is unaffected by the other dialogs; this MUST be clearly stated - // if it is the case. - // https://tools.ietf.org/html/rfc6665#section-5.4.9 - // *** NOTE: This implementation is only for event packages which - // do not allow forked requests to install muliple subscriptions. - // As such and in accordance with the specificaiton, we stop waiting - // and any future NOTIFY requests will be rejected with a 481. - if (this.dialog) { - throw new Error("Dialog already created. This implementation only supports install of single subscriptions."); - } - this.waitNotifyStop(); - // Update expires. - this.subscriptionExpires = - subscriptionState.expires ? - Math.min(this.subscriptionExpires, Math.max(subscriptionState.expires, 0)) : - this.subscriptionExpires; - // Update subscriptoin state. - switch (state) { - case "pending": - this.subscriptionState = subscription_1.SubscriptionState.Pending; - break; - case "active": - this.subscriptionState = subscription_1.SubscriptionState.Active; - break; - case "terminated": - this.subscriptionState = subscription_1.SubscriptionState.Terminated; - break; - default: - throw new Error("Unrecognized state " + state + "."); - } - // Dialogs usages are created upon completion of a NOTIFY transaction - // for a new subscription, unless the NOTIFY request contains a - // "Subscription-State" of "terminated." - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - if (this.subscriptionState !== subscription_1.SubscriptionState.Terminated) { - // Because the dialog usage is established by the NOTIFY request, the - // route set at the subscriber is taken from the NOTIFY request itself, - // as opposed to the route set present in the 200-class response to the - // SUBSCRIBE request. - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - var dialogState = subscription_dialog_1.SubscriptionDialog.initialDialogStateForSubscription(this.message, uas.message); - // Subscription Initiated! :) - this.dialog = new subscription_dialog_1.SubscriptionDialog(this.subscriptionEvent, this.subscriptionExpires, this.subscriptionState, this.core, dialogState); - } - // Delegate. - if (this.delegate && this.delegate.onNotify) { - var request = uas; - var subscription = this.dialog; - this.delegate.onNotify({ request: request, subscription: subscription }); - } - else { - uas.accept(); - } - }; - SubscribeUserAgentClient.prototype.waitNotifyStart = function () { - var _this = this; - if (!this.N) { - // Add ourselves to the core's subscriber map. - // This allows the core to route out of dialog NOTIFY messages to us. - this.core.subscribers.set(this.subscriberId, this); - this.N = setTimeout(function () { return _this.timer_N(); }, timers_1.Timers.TIMER_N); - } - }; - SubscribeUserAgentClient.prototype.waitNotifyStop = function () { - if (this.N) { - // Remove ourselves to the core's subscriber map. - // Any future out of dialog NOTIFY messages will be rejected with a 481. - this.core.subscribers.delete(this.subscriberId); - clearTimeout(this.N); - this.N = undefined; - } - }; - /** - * Receive a response from the transaction layer. - * @param message - Incoming response message. - */ - SubscribeUserAgentClient.prototype.receiveResponse = function (message) { - if (!this.authenticationGuard(message)) { - return; - } - if (message.statusCode && message.statusCode >= 200 && message.statusCode < 300) { - // The "Expires" header field in a 200-class response to SUBSCRIBE - // request indicates the actual duration for which the subscription will - // remain active (unless refreshed). The received value might be - // smaller than the value indicated in the SUBSCRIBE request but cannot - // be larger; see Section 4.2.1 for details. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - // The "Expires" values present in SUBSCRIBE 200-class responses behave - // in the same way as they do in REGISTER responses: the server MAY - // shorten the interval but MUST NOT lengthen it. - // - // If the duration specified in a SUBSCRIBE request is unacceptably - // short, the notifier may be able to send a 423 response, as - // described earlier in this section. - // - // 200-class responses to SUBSCRIBE requests will not generally contain - // any useful information beyond subscription duration; their primary - // purpose is to serve as a reliability mechanism. State information - // will be communicated via a subsequent NOTIFY request from the - // notifier. - // https://tools.ietf.org/html/rfc6665#section-4.2.1.1 - var expires = message.getHeader("Expires"); - if (!expires) { - this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE"); - } - else { - var subscriptionExpiresReceived = Number(expires); - if (subscriptionExpiresReceived > this.subscriptionExpiresRequested) { - this.logger.warn("Expires header in a 200-class response to SUBSCRIBE with a higher value than the one in the request"); - } - if (subscriptionExpiresReceived < this.subscriptionExpires) { - this.subscriptionExpires = subscriptionExpiresReceived; - } - } - // If a NOTIFY arrived before 200-class response a dialog may have been created. - // Updated the dialogs expiration only if this indicates earlier expiration. - if (this.dialog) { - if (this.dialog.subscriptionExpires > this.subscriptionExpires) { - this.dialog.subscriptionExpires = this.subscriptionExpires; - } - } - } - if (message.statusCode && message.statusCode >= 300 && message.statusCode < 700) { - this.waitNotifyStop(); // No NOTIFY will be sent after a negative final response. - } - _super.prototype.receiveResponse.call(this, message); - }; - /** - * To ensure that subscribers do not wait indefinitely for a - * subscription to be established, a subscriber starts a Timer N, set to - * 64*T1, when it sends a SUBSCRIBE request. If this Timer N expires - * prior to the receipt of a NOTIFY request, the subscriber considers - * the subscription failed, and cleans up any state associated with the - * subscription attempt. - * https://tools.ietf.org/html/rfc6665#section-4.1.2.4 - */ - SubscribeUserAgentClient.prototype.timer_N = function () { - this.logger.warn("Timer N expired for SUBSCRIBE user agent client. Timed out waiting for NOTIFY."); - this.waitNotifyStop(); - if (this.delegate && this.delegate.onNotifyTimeout) { - this.delegate.onNotifyTimeout(); - } - }; - return SubscribeUserAgentClient; -}(user_agent_client_1.UserAgentClient)); -exports.SubscribeUserAgentClient = SubscribeUserAgentClient; diff --git a/lib/core/user-agents/subscribe-user-agent-server.d.ts b/lib/core/user-agents/subscribe-user-agent-server.d.ts deleted file mode 100644 index ad65a8261..000000000 --- a/lib/core/user-agents/subscribe-user-agent-server.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { IncomingRequestDelegate, IncomingRequestMessage, IncomingSubscribeRequest } from "../messages"; -import { UserAgentCore } from "../user-agent-core"; -import { UserAgentServer } from "./user-agent-server"; -/** - * SUBSCRIBE UAS. - * @public - */ -export declare class SubscribeUserAgentServer extends UserAgentServer implements IncomingSubscribeRequest { - protected core: UserAgentCore; - constructor(core: UserAgentCore, message: IncomingRequestMessage, delegate?: IncomingRequestDelegate); -} -//# sourceMappingURL=subscribe-user-agent-server.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/subscribe-user-agent-server.d.ts.map b/lib/core/user-agents/subscribe-user-agent-server.d.ts.map deleted file mode 100644 index 5df1bc2ab..000000000 --- a/lib/core/user-agents/subscribe-user-agent-server.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"subscribe-user-agent-server.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/subscribe-user-agent-server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AAExG,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,qBAAa,wBAAyB,SAAQ,eAAgB,YAAW,wBAAwB;IAE7F,SAAS,CAAC,IAAI,EAAE,aAAa;gBAAnB,IAAI,EAAE,aAAa,EAC7B,OAAO,EAAE,sBAAsB,EAC/B,QAAQ,CAAC,EAAE,uBAAuB;CAIrC"} \ No newline at end of file diff --git a/lib/core/user-agents/subscribe-user-agent-server.js b/lib/core/user-agents/subscribe-user-agent-server.js deleted file mode 100644 index 4ba2c1013..000000000 --- a/lib/core/user-agents/subscribe-user-agent-server.js +++ /dev/null @@ -1,19 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var transactions_1 = require("../transactions"); -var user_agent_server_1 = require("./user-agent-server"); -/** - * SUBSCRIBE UAS. - * @public - */ -var SubscribeUserAgentServer = /** @class */ (function (_super) { - tslib_1.__extends(SubscribeUserAgentServer, _super); - function SubscribeUserAgentServer(core, message, delegate) { - var _this = _super.call(this, transactions_1.NonInviteServerTransaction, core, message, delegate) || this; - _this.core = core; - return _this; - } - return SubscribeUserAgentServer; -}(user_agent_server_1.UserAgentServer)); -exports.SubscribeUserAgentServer = SubscribeUserAgentServer; diff --git a/lib/core/user-agents/user-agent-client.d.ts b/lib/core/user-agents/user-agent-client.d.ts deleted file mode 100644 index 6b68f9146..000000000 --- a/lib/core/user-agents/user-agent-client.d.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { Logger, LoggerFactory } from "../log"; -import { IncomingResponseMessage, OutgoingRequest, OutgoingRequestDelegate, OutgoingRequestMessage, RequestOptions } from "../messages"; -import { ClientTransaction, ClientTransactionUser } from "../transactions"; -import { Transport } from "../transport"; -import { UserAgentCore } from "../user-agent-core"; -declare type ClientTransactionConstructor = new (message: OutgoingRequestMessage, transport: Transport, user: ClientTransactionUser) => ClientTransaction; -/** - * User Agent Client (UAC). - * @remarks - * A user agent client is a logical entity - * that creates a new request, and then uses the client - * transaction state machinery to send it. The role of UAC lasts - * only for the duration of that transaction. In other words, if - * a piece of software initiates a request, it acts as a UAC for - * the duration of that transaction. If it receives a request - * later, it assumes the role of a user agent server for the - * processing of that transaction. - * https://tools.ietf.org/html/rfc3261#section-6 - * @public - */ -export declare class UserAgentClient implements OutgoingRequest { - private transactionConstructor; - protected core: UserAgentCore; - message: OutgoingRequestMessage; - delegate?: OutgoingRequestDelegate | undefined; - protected logger: Logger; - private _transaction; - private credentials; - private challenged; - private stale; - constructor(transactionConstructor: ClientTransactionConstructor, core: UserAgentCore, message: OutgoingRequestMessage, delegate?: OutgoingRequestDelegate | undefined); - dispose(): void; - readonly loggerFactory: LoggerFactory; - /** The transaction associated with this request. */ - readonly transaction: ClientTransaction; - /** - * Since requests other than INVITE are responded to immediately, sending a - * CANCEL for a non-INVITE request would always create a race condition. - * A CANCEL request SHOULD NOT be sent to cancel a request other than INVITE. - * https://tools.ietf.org/html/rfc3261#section-9.1 - * @param options - Cancel options bucket. - */ - cancel(reason?: string, options?: RequestOptions): OutgoingRequestMessage; - /** - * If a 401 (Unauthorized) or 407 (Proxy Authentication Required) - * response is received, the UAC SHOULD follow the authorization - * procedures of Section 22.2 and Section 22.3 to retry the request with - * credentials. - * https://tools.ietf.org/html/rfc3261#section-8.1.3.5 - * 22 Usage of HTTP Authentication - * https://tools.ietf.org/html/rfc3261#section-22 - * 22.1 Framework - * https://tools.ietf.org/html/rfc3261#section-22.1 - * 22.2 User-to-User Authentication - * https://tools.ietf.org/html/rfc3261#section-22.2 - * 22.3 Proxy-to-User Authentication - * https://tools.ietf.org/html/rfc3261#section-22.3 - * - * FIXME: This "guard for and retry the request with credentials" - * implementation is not complete and at best minimally passable. - * @param response - The incoming response to guard. - * @returns True if the program execution is to continue in the branch in question. - * Otherwise the request is retried with credentials and current request processing must stop. - */ - protected authenticationGuard(message: IncomingResponseMessage): boolean; - /** - * Receive a response from the transaction layer. - * @param message - Incoming response message. - */ - protected receiveResponse(message: IncomingResponseMessage): void; - private init; - /** - * 8.1.3.1 Transaction Layer Errors - * In some cases, the response returned by the transaction layer will - * not be a SIP message, but rather a transaction layer error. When a - * timeout error is received from the transaction layer, it MUST be - * treated as if a 408 (Request Timeout) status code has been received. - * If a fatal transport error is reported by the transport layer - * (generally, due to fatal ICMP errors in UDP or connection failures in - * TCP), the condition MUST be treated as a 503 (Service Unavailable) - * status code. - * https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - */ - private onRequestTimeout; - /** - * 8.1.3.1 Transaction Layer Errors - * In some cases, the response returned by the transaction layer will - * not be a SIP message, but rather a transaction layer error. When a - * timeout error is received from the transaction layer, it MUST be - * treated as if a 408 (Request Timeout) status code has been received. - * If a fatal transport error is reported by the transport layer - * (generally, due to fatal ICMP errors in UDP or connection failures in - * TCP), the condition MUST be treated as a 503 (Service Unavailable) - * status code. - * https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - */ - private onTransportError; -} -export {}; -//# sourceMappingURL=user-agent-client.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/user-agent-client.d.ts.map b/lib/core/user-agents/user-agent-client.d.ts.map deleted file mode 100644 index 7bcb93f7d..000000000 --- a/lib/core/user-agents/user-agent-client.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"user-agent-client.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/user-agent-client.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AAC/C,OAAO,EAEL,uBAAuB,EACvB,eAAe,EACf,uBAAuB,EACvB,sBAAsB,EACtB,cAAc,EACf,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,iBAAiB,EACjB,qBAAqB,EAGtB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAEnD,aAAK,4BAA4B,GAAG,KAClC,OAAO,EAAE,sBAAsB,EAC/B,SAAS,EAAE,SAAS,EACpB,IAAI,EAAE,qBAAqB,KACxB,iBAAiB,CAAC;AAEvB;;;;;;;;;;;;;GAaG;AACH,qBAAa,eAAgB,YAAW,eAAe;IAUnD,OAAO,CAAC,sBAAsB;IAC9B,SAAS,CAAC,IAAI,EAAE,aAAa;IACtB,OAAO,EAAE,sBAAsB;IAC/B,QAAQ,CAAC;IAZlB,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC;IAEzB,OAAO,CAAC,YAAY,CAAgC;IAEpD,OAAO,CAAC,WAAW,CAAM;IACzB,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,KAAK,CAAS;gBAGZ,sBAAsB,EAAE,4BAA4B,EAClD,IAAI,EAAE,aAAa,EACtB,OAAO,EAAE,sBAAsB,EAC/B,QAAQ,CAAC,qCAAyB;IAMpC,OAAO,IAAI,IAAI;aAIlB,aAAa,EAAI,aAAa;IAIlC,oDAAoD;aAChD,WAAW,EAAI,iBAAiB;IAOpC;;;;;;OAMG;IACI,MAAM,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,OAAO,GAAE,cAAmB,GAAG,sBAAsB;IAyEpF;;;;;;;;;;;;;;;;;;;;OAoBG;IACH,SAAS,CAAC,mBAAmB,CAAC,OAAO,EAAE,uBAAuB,GAAG,OAAO;IAsExE;;;OAGG;IACH,SAAS,CAAC,eAAe,CAAC,OAAO,EAAE,uBAAuB,GAAG,IAAI;IAyCjE,OAAO,CAAC,IAAI;IA4BZ;;;;;;;;;;;OAWG;IACH,OAAO,CAAC,gBAAgB;IASxB;;;;;;;;;;;OAWG;IACH,OAAO,CAAC,gBAAgB;CAQzB"} \ No newline at end of file diff --git a/lib/core/user-agents/user-agent-client.js b/lib/core/user-agents/user-agent-client.js deleted file mode 100644 index 302f61bd0..000000000 --- a/lib/core/user-agents/user-agent-client.js +++ /dev/null @@ -1,313 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var messages_1 = require("../messages"); -var transactions_1 = require("../transactions"); -/** - * User Agent Client (UAC). - * @remarks - * A user agent client is a logical entity - * that creates a new request, and then uses the client - * transaction state machinery to send it. The role of UAC lasts - * only for the duration of that transaction. In other words, if - * a piece of software initiates a request, it acts as a UAC for - * the duration of that transaction. If it receives a request - * later, it assumes the role of a user agent server for the - * processing of that transaction. - * https://tools.ietf.org/html/rfc3261#section-6 - * @public - */ -var UserAgentClient = /** @class */ (function () { - function UserAgentClient(transactionConstructor, core, message, delegate) { - this.transactionConstructor = transactionConstructor; - this.core = core; - this.message = message; - this.delegate = delegate; - this.challenged = false; - this.stale = false; - this.logger = this.loggerFactory.getLogger("sip.user-agent-client"); - this.init(); - } - UserAgentClient.prototype.dispose = function () { - this.transaction.dispose(); - }; - Object.defineProperty(UserAgentClient.prototype, "loggerFactory", { - get: function () { - return this.core.loggerFactory; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(UserAgentClient.prototype, "transaction", { - /** The transaction associated with this request. */ - get: function () { - if (!this._transaction) { - throw new Error("Transaction undefined."); - } - return this._transaction; - }, - enumerable: true, - configurable: true - }); - /** - * Since requests other than INVITE are responded to immediately, sending a - * CANCEL for a non-INVITE request would always create a race condition. - * A CANCEL request SHOULD NOT be sent to cancel a request other than INVITE. - * https://tools.ietf.org/html/rfc3261#section-9.1 - * @param options - Cancel options bucket. - */ - UserAgentClient.prototype.cancel = function (reason, options) { - var _this = this; - if (options === void 0) { options = {}; } - if (!this.transaction) { - throw new Error("Transaction undefined."); - } - if (!this.message.to) { - throw new Error("To undefined."); - } - if (!this.message.from) { - throw new Error("From undefined."); - } - // The following procedures are used to construct a CANCEL request. The - // Request-URI, Call-ID, To, the numeric part of CSeq, and From header - // fields in the CANCEL request MUST be identical to those in the - // request being cancelled, including tags. A CANCEL constructed by a - // client MUST have only a single Via header field value matching the - // top Via value in the request being cancelled. Using the same values - // for these header fields allows the CANCEL to be matched with the - // request it cancels (Section 9.2 indicates how such matching occurs). - // However, the method part of the CSeq header field MUST have a value - // of CANCEL. This allows it to be identified and processed as a - // transaction in its own right (See Section 17). - // https://tools.ietf.org/html/rfc3261#section-9.1 - var message = this.core.makeOutgoingRequestMessage(messages_1.C.CANCEL, this.message.ruri, this.message.from.uri, this.message.to.uri, { - toTag: this.message.toTag, - fromTag: this.message.fromTag, - callId: this.message.callId, - cseq: this.message.cseq - }, options.extraHeaders); - // TODO: Revisit this. - // The CANCEL needs to use the same branch parameter so that - // it matches the INVITE transaction, but this is a hacky way to do this. - // Or at the very least not well documented. If the the branch parameter - // is set on the outgoing request, the transaction will use it. - // Otherwise the transaction will make a new one. - message.branch = this.message.branch; - if (this.message.headers.Route) { - message.headers.Route = this.message.headers.Route; - } - if (reason) { - message.setHeader("Reason", reason); - } - // If no provisional response has been received, the CANCEL request MUST - // NOT be sent; rather, the client MUST wait for the arrival of a - // provisional response before sending the request. If the original - // request has generated a final response, the CANCEL SHOULD NOT be - // sent, as it is an effective no-op, since CANCEL has no effect on - // requests that have already generated a final response. - // https://tools.ietf.org/html/rfc3261#section-9.1 - if (this.transaction.state === transactions_1.TransactionState.Proceeding) { - var uac = new UserAgentClient(transactions_1.NonInviteClientTransaction, this.core, message); - } - else { - this.transaction.once("stateChanged", function () { - if (_this.transaction && _this.transaction.state === transactions_1.TransactionState.Proceeding) { - var uac = new UserAgentClient(transactions_1.NonInviteClientTransaction, _this.core, message); - } - }); - } - return message; - }; - /** - * If a 401 (Unauthorized) or 407 (Proxy Authentication Required) - * response is received, the UAC SHOULD follow the authorization - * procedures of Section 22.2 and Section 22.3 to retry the request with - * credentials. - * https://tools.ietf.org/html/rfc3261#section-8.1.3.5 - * 22 Usage of HTTP Authentication - * https://tools.ietf.org/html/rfc3261#section-22 - * 22.1 Framework - * https://tools.ietf.org/html/rfc3261#section-22.1 - * 22.2 User-to-User Authentication - * https://tools.ietf.org/html/rfc3261#section-22.2 - * 22.3 Proxy-to-User Authentication - * https://tools.ietf.org/html/rfc3261#section-22.3 - * - * FIXME: This "guard for and retry the request with credentials" - * implementation is not complete and at best minimally passable. - * @param response - The incoming response to guard. - * @returns True if the program execution is to continue in the branch in question. - * Otherwise the request is retried with credentials and current request processing must stop. - */ - UserAgentClient.prototype.authenticationGuard = function (message) { - var statusCode = message.statusCode; - if (!statusCode) { - throw new Error("Response status code undefined."); - } - // If a 401 (Unauthorized) or 407 (Proxy Authentication Required) - // response is received, the UAC SHOULD follow the authorization - // procedures of Section 22.2 and Section 22.3 to retry the request with - // credentials. - // https://tools.ietf.org/html/rfc3261#section-8.1.3.5 - if (statusCode !== 401 && statusCode !== 407) { - return true; - } - // Get and parse the appropriate WWW-Authenticate or Proxy-Authenticate header. - var challenge; - var authorizationHeaderName; - if (statusCode === 401) { - challenge = message.parseHeader("www-authenticate"); - authorizationHeaderName = "authorization"; - } - else { - challenge = message.parseHeader("proxy-authenticate"); - authorizationHeaderName = "proxy-authorization"; - } - // Verify it seems a valid challenge. - if (!challenge) { - this.logger.warn(statusCode + " with wrong or missing challenge, cannot authenticate"); - return true; - } - // Avoid infinite authentications. - if (this.challenged && (this.stale || challenge.stale !== true)) { - this.logger.warn(statusCode + " apparently in authentication loop, cannot authenticate"); - return true; - } - // Get credentials. - if (!this.credentials) { - this.credentials = this.core.configuration.authenticationFactory(); - if (!this.credentials) { - this.logger.warn("Unable to obtain credentials, cannot authenticate"); - return true; - } - } - // Verify that the challenge is really valid. - if (!this.credentials.authenticate(this.message, challenge)) { - return true; - } - this.challenged = true; - if (challenge.stale) { - this.stale = true; - } - var cseq = this.message.cseq += 1; - this.message.setHeader("cseq", cseq + " " + this.message.method); - this.message.setHeader(authorizationHeaderName, this.credentials.toString()); - // Calling init (again) will swap out our existing client transaction with a new one. - // FIXME: HACK: An assumption is being made here that there is nothing that needs to - // be cleaned up beyond the client transaction which is being replaced. For example, - // it is assumed that no early dialogs have been created. - this.init(); - return false; - }; - /** - * Receive a response from the transaction layer. - * @param message - Incoming response message. - */ - UserAgentClient.prototype.receiveResponse = function (message) { - if (!this.authenticationGuard(message)) { - return; - } - var statusCode = message.statusCode ? message.statusCode.toString() : ""; - if (!statusCode) { - throw new Error("Response status code undefined."); - } - switch (true) { - case /^100$/.test(statusCode): - if (this.delegate && this.delegate.onTrying) { - this.delegate.onTrying({ message: message }); - } - break; - case /^1[0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onProgress) { - this.delegate.onProgress({ message: message }); - } - break; - case /^2[0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onAccept) { - this.delegate.onAccept({ message: message }); - } - break; - case /^3[0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onRedirect) { - this.delegate.onRedirect({ message: message }); - } - break; - case /^[4-6][0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onReject) { - this.delegate.onReject({ message: message }); - } - break; - default: - throw new Error("Invalid status code " + statusCode); - } - }; - UserAgentClient.prototype.init = function () { - var _this = this; - // We are the transaction user. - var user = { - loggerFactory: this.loggerFactory, - onRequestTimeout: function () { return _this.onRequestTimeout(); }, - onStateChange: function (newState) { - if (newState === transactions_1.TransactionState.Terminated) { - // Remove the terminated transaction from the core. - _this.core.userAgentClients.delete(userAgentClientId); - // FIXME: HACK: Our transaction may have been swapped out with a new one - // post authentication (see above), so make sure to only to dispose of - // ourselves if this terminating transaction is our current transaction. - if (transaction === _this._transaction) { - _this.dispose(); - } - } - }, - onTransportError: function (error) { return _this.onTransportError(error); }, - receiveResponse: function (message) { return _this.receiveResponse(message); } - }; - // Create a new transaction with us as the user. - var transaction = new this.transactionConstructor(this.message, this.core.transport, user); - this._transaction = transaction; - // Add the new transaction to the core. - var userAgentClientId = transaction.id + transaction.request.method; - this.core.userAgentClients.set(userAgentClientId, this); - }; - /** - * 8.1.3.1 Transaction Layer Errors - * In some cases, the response returned by the transaction layer will - * not be a SIP message, but rather a transaction layer error. When a - * timeout error is received from the transaction layer, it MUST be - * treated as if a 408 (Request Timeout) status code has been received. - * If a fatal transport error is reported by the transport layer - * (generally, due to fatal ICMP errors in UDP or connection failures in - * TCP), the condition MUST be treated as a 503 (Service Unavailable) - * status code. - * https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - */ - UserAgentClient.prototype.onRequestTimeout = function () { - this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout."); - var message = new messages_1.IncomingResponseMessage(); - message.statusCode = 408; - message.reasonPhrase = "Request Timeout"; - this.receiveResponse(message); - return; - }; - /** - * 8.1.3.1 Transaction Layer Errors - * In some cases, the response returned by the transaction layer will - * not be a SIP message, but rather a transaction layer error. When a - * timeout error is received from the transaction layer, it MUST be - * treated as if a 408 (Request Timeout) status code has been received. - * If a fatal transport error is reported by the transport layer - * (generally, due to fatal ICMP errors in UDP or connection failures in - * TCP), the condition MUST be treated as a 503 (Service Unavailable) - * status code. - * https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - */ - UserAgentClient.prototype.onTransportError = function (error) { - this.logger.error(error.message); - this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable."); - var message = new messages_1.IncomingResponseMessage(); - message.statusCode = 503; - message.reasonPhrase = "Service Unavailable"; - this.receiveResponse(message); - }; - return UserAgentClient; -}()); -exports.UserAgentClient = UserAgentClient; diff --git a/lib/core/user-agents/user-agent-server.d.ts b/lib/core/user-agents/user-agent-server.d.ts deleted file mode 100644 index 0635f466e..000000000 --- a/lib/core/user-agents/user-agent-server.d.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { Logger, LoggerFactory } from "../log"; -import { IncomingRequest, IncomingRequestDelegate, IncomingRequestMessage, OutgoingResponse, ResponseOptions, URI } from "../messages"; -import { ServerTransaction, ServerTransactionUser } from "../transactions"; -import { Transport } from "../transport"; -import { UserAgentCore } from "../user-agent-core"; -declare type ServerTransactionConstructor = new (message: IncomingRequestMessage, transport: Transport, user: ServerTransactionUser) => ServerTransaction; -/** - * User Agent Server (UAS). - * @remarks - * A user agent server is a logical entity - * that generates a response to a SIP request. The response - * accepts, rejects, or redirects the request. This role lasts - * only for the duration of that transaction. In other words, if - * a piece of software responds to a request, it acts as a UAS for - * the duration of that transaction. If it generates a request - * later, it assumes the role of a user agent client for the - * processing of that transaction. - * https://tools.ietf.org/html/rfc3261#section-6 - * @public - */ -export declare class UserAgentServer implements IncomingRequest { - private transactionConstructor; - protected core: UserAgentCore; - message: IncomingRequestMessage; - delegate?: IncomingRequestDelegate | undefined; - protected logger: Logger; - protected toTag: string; - private _transaction; - constructor(transactionConstructor: ServerTransactionConstructor, core: UserAgentCore, message: IncomingRequestMessage, delegate?: IncomingRequestDelegate | undefined); - dispose(): void; - readonly loggerFactory: LoggerFactory; - /** The transaction associated with this request. */ - readonly transaction: ServerTransaction; - accept(options?: ResponseOptions): OutgoingResponse; - progress(options?: ResponseOptions): OutgoingResponse; - redirect(contacts: Array, options?: ResponseOptions): OutgoingResponse; - reject(options?: ResponseOptions): OutgoingResponse; - trying(options?: ResponseOptions): OutgoingResponse; - /** - * If the UAS did not find a matching transaction for the CANCEL - * according to the procedure above, it SHOULD respond to the CANCEL - * with a 481 (Call Leg/Transaction Does Not Exist). If the transaction - * for the original request still exists, the behavior of the UAS on - * receiving a CANCEL request depends on whether it has already sent a - * final response for the original request. If it has, the CANCEL - * request has no effect on the processing of the original request, no - * effect on any session state, and no effect on the responses generated - * for the original request. If the UAS has not issued a final response - * for the original request, its behavior depends on the method of the - * original request. If the original request was an INVITE, the UAS - * SHOULD immediately respond to the INVITE with a 487 (Request - * Terminated). A CANCEL request has no impact on the processing of - * transactions with any other method defined in this specification. - * https://tools.ietf.org/html/rfc3261#section-9.2 - * @param request - Incoming CANCEL request. - */ - receiveCancel(message: IncomingRequestMessage): void; - protected readonly acceptable: boolean; - protected readonly progressable: boolean; - protected readonly redirectable: boolean; - protected readonly rejectable: boolean; - protected readonly tryingable: boolean; - /** - * When a UAS wishes to construct a response to a request, it follows - * the general procedures detailed in the following subsections. - * Additional behaviors specific to the response code in question, which - * are not detailed in this section, may also be required. - * - * Once all procedures associated with the creation of a response have - * been completed, the UAS hands the response back to the server - * transaction from which it received the request. - * https://tools.ietf.org/html/rfc3261#section-8.2.6 - * @param statusCode - Status code to reply with. - * @param options - Reply options bucket. - */ - private reply; - private init; -} -export {}; -//# sourceMappingURL=user-agent-server.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/user-agent-server.d.ts.map b/lib/core/user-agents/user-agent-server.d.ts.map deleted file mode 100644 index 92afb9f70..000000000 --- a/lib/core/user-agents/user-agent-server.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"user-agent-server.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/user-agent-server.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AAC/C,OAAO,EAEL,eAAe,EACf,uBAAuB,EACvB,sBAAsB,EACtB,gBAAgB,EAChB,eAAe,EACf,GAAG,EACJ,MAAM,aAAa,CAAC;AAGrB,OAAO,EAGL,iBAAiB,EACjB,qBAAqB,EAEtB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAEnD,aAAK,4BAA4B,GAAG,KAClC,OAAO,EAAE,sBAAsB,EAC/B,SAAS,EAAE,SAAS,EACpB,IAAI,EAAE,qBAAqB,KACxB,iBAAiB,CAAC;AAEvB;;;;;;;;;;;;;GAaG;AACH,qBAAa,eAAgB,YAAW,eAAe;IAOnD,OAAO,CAAC,sBAAsB;IAC9B,SAAS,CAAC,IAAI,EAAE,aAAa;IACtB,OAAO,EAAE,sBAAsB;IAC/B,QAAQ,CAAC;IATlB,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC;IACzB,SAAS,CAAC,KAAK,EAAE,MAAM,CAAC;IAExB,OAAO,CAAC,YAAY,CAAgC;gBAG1C,sBAAsB,EAAE,4BAA4B,EAClD,IAAI,EAAE,aAAa,EACtB,OAAO,EAAE,sBAAsB,EAC/B,QAAQ,CAAC,qCAAyB;IAOpC,OAAO,IAAI,IAAI;aAIlB,aAAa,EAAI,aAAa;IAIlC,oDAAoD;aAChD,WAAW,EAAI,iBAAiB;IAO7B,MAAM,CAAC,OAAO,GAAE,eAAqC,GAAG,gBAAgB;IAcxE,QAAQ,CAAC,OAAO,GAAE,eAAqC,GAAG,gBAAgB;IAc1E,QAAQ,CAAC,QAAQ,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,OAAO,GAAE,eAAqC,GAAG,gBAAgB;IAiBhG,MAAM,CAAC,OAAO,GAAE,eAAqC,GAAG,gBAAgB;IAcxE,MAAM,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,gBAAgB;IAU1D;;;;;;;;;;;;;;;;;OAiBG;IACI,aAAa,CAAC,OAAO,EAAE,sBAAsB,GAAG,IAAI;uBAW7C,UAAU,EAAI,OAAO;uBAgBrB,YAAY,EAAI,OAAO;uBAUvB,YAAY,EAAI,OAAO;uBAavB,UAAU,EAAI,OAAO;uBAarB,UAAU,EAAI,OAAO;IAUnC;;;;;;;;;;;;OAYG;IACH,OAAO,CAAC,KAAK;IAWb,OAAO,CAAC,IAAI;CA2Bb"} \ No newline at end of file diff --git a/lib/core/user-agents/user-agent-server.js b/lib/core/user-agents/user-agent-server.js deleted file mode 100644 index 08fe9ec6b..000000000 --- a/lib/core/user-agents/user-agent-server.js +++ /dev/null @@ -1,261 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var exceptions_1 = require("../exceptions"); -var messages_1 = require("../messages"); -var utils_1 = require("../messages/utils"); -var transactions_1 = require("../transactions"); -/** - * User Agent Server (UAS). - * @remarks - * A user agent server is a logical entity - * that generates a response to a SIP request. The response - * accepts, rejects, or redirects the request. This role lasts - * only for the duration of that transaction. In other words, if - * a piece of software responds to a request, it acts as a UAS for - * the duration of that transaction. If it generates a request - * later, it assumes the role of a user agent client for the - * processing of that transaction. - * https://tools.ietf.org/html/rfc3261#section-6 - * @public - */ -var UserAgentServer = /** @class */ (function () { - function UserAgentServer(transactionConstructor, core, message, delegate) { - this.transactionConstructor = transactionConstructor; - this.core = core; - this.message = message; - this.delegate = delegate; - this.logger = this.loggerFactory.getLogger("sip.user-agent-server"); - this.toTag = message.toTag ? message.toTag : utils_1.newTag(); - this.init(); - } - UserAgentServer.prototype.dispose = function () { - this.transaction.dispose(); - }; - Object.defineProperty(UserAgentServer.prototype, "loggerFactory", { - get: function () { - return this.core.loggerFactory; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(UserAgentServer.prototype, "transaction", { - /** The transaction associated with this request. */ - get: function () { - if (!this._transaction) { - throw new Error("Transaction undefined."); - } - return this._transaction; - }, - enumerable: true, - configurable: true - }); - UserAgentServer.prototype.accept = function (options) { - if (options === void 0) { options = { statusCode: 200 }; } - if (!this.acceptable) { - throw new exceptions_1.TransactionStateError(this.message.method + " not acceptable in state " + this.transaction.state + "."); - } - var statusCode = options.statusCode; - if (statusCode < 200 || statusCode > 299) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - var response = this.reply(options); - return response; - }; - UserAgentServer.prototype.progress = function (options) { - if (options === void 0) { options = { statusCode: 180 }; } - if (!this.progressable) { - throw new exceptions_1.TransactionStateError(this.message.method + " not progressable in state " + this.transaction.state + "."); - } - var statusCode = options.statusCode; - if (statusCode < 101 || statusCode > 199) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - var response = this.reply(options); - return response; - }; - UserAgentServer.prototype.redirect = function (contacts, options) { - if (options === void 0) { options = { statusCode: 302 }; } - if (!this.redirectable) { - throw new exceptions_1.TransactionStateError(this.message.method + " not redirectable in state " + this.transaction.state + "."); - } - var statusCode = options.statusCode; - if (statusCode < 300 || statusCode > 399) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - var contactHeaders = new Array(); - contacts.forEach(function (contact) { return contactHeaders.push("Contact: " + contact.toString()); }); - options.extraHeaders = (options.extraHeaders || []).concat(contactHeaders); - var response = this.reply(options); - return response; - }; - UserAgentServer.prototype.reject = function (options) { - if (options === void 0) { options = { statusCode: 480 }; } - if (!this.rejectable) { - throw new exceptions_1.TransactionStateError(this.message.method + " not rejectable in state " + this.transaction.state + "."); - } - var statusCode = options.statusCode; - if (statusCode < 400 || statusCode > 699) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - var response = this.reply(options); - return response; - }; - UserAgentServer.prototype.trying = function (options) { - if (!this.tryingable) { - throw new exceptions_1.TransactionStateError(this.message.method + " not tryingable in state " + this.transaction.state + "."); - } - var response = this.reply({ statusCode: 100 }); - return response; - }; - /** - * If the UAS did not find a matching transaction for the CANCEL - * according to the procedure above, it SHOULD respond to the CANCEL - * with a 481 (Call Leg/Transaction Does Not Exist). If the transaction - * for the original request still exists, the behavior of the UAS on - * receiving a CANCEL request depends on whether it has already sent a - * final response for the original request. If it has, the CANCEL - * request has no effect on the processing of the original request, no - * effect on any session state, and no effect on the responses generated - * for the original request. If the UAS has not issued a final response - * for the original request, its behavior depends on the method of the - * original request. If the original request was an INVITE, the UAS - * SHOULD immediately respond to the INVITE with a 487 (Request - * Terminated). A CANCEL request has no impact on the processing of - * transactions with any other method defined in this specification. - * https://tools.ietf.org/html/rfc3261#section-9.2 - * @param request - Incoming CANCEL request. - */ - UserAgentServer.prototype.receiveCancel = function (message) { - // Note: Currently CANCEL is being handled as a special case. - // No UAS is created to handle the CANCEL and the response to - // it CANCEL is being handled statelessly by the user agent core. - // As such, there is currently no way to externally impact the - // response to the a CANCEL request. - if (this.delegate && this.delegate.onCancel) { - this.delegate.onCancel(message); - } - }; - Object.defineProperty(UserAgentServer.prototype, "acceptable", { - get: function () { - if (this.transaction instanceof transactions_1.InviteServerTransaction) { - return (this.transaction.state === transactions_1.TransactionState.Proceeding || - this.transaction.state === transactions_1.TransactionState.Accepted); - } - if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { - return (this.transaction.state === transactions_1.TransactionState.Trying || - this.transaction.state === transactions_1.TransactionState.Proceeding); - } - throw new Error("Unknown transaction type."); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(UserAgentServer.prototype, "progressable", { - get: function () { - if (this.transaction instanceof transactions_1.InviteServerTransaction) { - return this.transaction.state === transactions_1.TransactionState.Proceeding; - } - if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { - return false; // https://tools.ietf.org/html/rfc4320#section-4.1 - } - throw new Error("Unknown transaction type."); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(UserAgentServer.prototype, "redirectable", { - get: function () { - if (this.transaction instanceof transactions_1.InviteServerTransaction) { - return this.transaction.state === transactions_1.TransactionState.Proceeding; - } - if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { - return (this.transaction.state === transactions_1.TransactionState.Trying || - this.transaction.state === transactions_1.TransactionState.Proceeding); - } - throw new Error("Unknown transaction type."); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(UserAgentServer.prototype, "rejectable", { - get: function () { - if (this.transaction instanceof transactions_1.InviteServerTransaction) { - return this.transaction.state === transactions_1.TransactionState.Proceeding; - } - if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { - return (this.transaction.state === transactions_1.TransactionState.Trying || - this.transaction.state === transactions_1.TransactionState.Proceeding); - } - throw new Error("Unknown transaction type."); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(UserAgentServer.prototype, "tryingable", { - get: function () { - if (this.transaction instanceof transactions_1.InviteServerTransaction) { - return this.transaction.state === transactions_1.TransactionState.Proceeding; - } - if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { - return this.transaction.state === transactions_1.TransactionState.Trying; - } - throw new Error("Unknown transaction type."); - }, - enumerable: true, - configurable: true - }); - /** - * When a UAS wishes to construct a response to a request, it follows - * the general procedures detailed in the following subsections. - * Additional behaviors specific to the response code in question, which - * are not detailed in this section, may also be required. - * - * Once all procedures associated with the creation of a response have - * been completed, the UAS hands the response back to the server - * transaction from which it received the request. - * https://tools.ietf.org/html/rfc3261#section-8.2.6 - * @param statusCode - Status code to reply with. - * @param options - Reply options bucket. - */ - UserAgentServer.prototype.reply = function (options) { - if (!options.toTag && options.statusCode !== 100) { - options.toTag = this.toTag; - } - options.userAgent = options.userAgent || this.core.configuration.userAgentHeaderFieldValue; - options.supported = options.supported || this.core.configuration.supportedOptionTagsResponse; - var response = messages_1.constructOutgoingResponse(this.message, options); - this.transaction.receiveResponse(options.statusCode, response.message); - return response; - }; - UserAgentServer.prototype.init = function () { - var _this = this; - // We are the transaction user. - var user = { - loggerFactory: this.loggerFactory, - onStateChange: function (newState) { - if (newState === transactions_1.TransactionState.Terminated) { - // Remove the terminated transaction from the core. - _this.core.userAgentServers.delete(userAgentServerId); - _this.dispose(); - } - }, - onTransportError: function (error) { - _this.logger.error(error.message); - if (_this.delegate && _this.delegate.onTransportError) { - _this.delegate.onTransportError(error); - } - else { - _this.logger.error("User agent server response transport error."); - } - } - }; - // Create a new transaction with us as the user. - var transaction = new this.transactionConstructor(this.message, this.core.transport, user); - this._transaction = transaction; - // Add the new transaction to the core. - var userAgentServerId = transaction.id; - this.core.userAgentServers.set(transaction.id, this); - }; - return UserAgentServer; -}()); -exports.UserAgentServer = UserAgentServer; diff --git a/lib/grammar/dist/grammar.d.ts b/lib/grammar/dist/grammar.d.ts deleted file mode 100644 index 5dff5415d..000000000 --- a/lib/grammar/dist/grammar.d.ts +++ /dev/null @@ -1,51 +0,0 @@ -export interface IFilePosition { - offset: number; - line: number; - column: number; -} -export interface IFileRange { - start: IFilePosition; - end: IFilePosition; -} -export interface ILiteralExpectation { - type: "literal"; - text: string; - ignoreCase: boolean; -} -export interface IClassParts extends Array { -} -export interface IClassExpectation { - type: "class"; - parts: IClassParts; - inverted: boolean; - ignoreCase: boolean; -} -export interface IAnyExpectation { - type: "any"; -} -export interface IEndExpectation { - type: "end"; -} -export interface IOtherExpectation { - type: "other"; - description: string; -} -export declare type Expectation = ILiteralExpectation | IClassExpectation | IAnyExpectation | IEndExpectation | IOtherExpectation; -export declare class SyntaxError extends Error { - static buildMessage(expected: Expectation[], found: string | null): string; - message: string; - expected: Expectation[]; - found: string | null; - location: IFileRange; - name: string; - constructor(message: string, expected: Expectation[], found: string | null, location: IFileRange); -} -export interface IParseOptions { - filename?: string; - startRule?: string; - tracer?: any; - [key: string]: any; -} -export declare type ParseFunction = (input: string, options?: IParseOptions) => any; -export declare const parse: ParseFunction; -//# sourceMappingURL=grammar.d.ts.map \ No newline at end of file diff --git a/lib/grammar/dist/grammar.d.ts.map b/lib/grammar/dist/grammar.d.ts.map deleted file mode 100644 index ce64e944e..000000000 --- a/lib/grammar/dist/grammar.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"grammar.d.ts","sourceRoot":"","sources":["../../../src/grammar/dist/grammar.ts"],"names":[],"mappings":"AA8BA,MAAM,WAAW,aAAa;IAC5B,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,UAAU;IACzB,KAAK,EAAE,aAAa,CAAC;IACrB,GAAG,EAAE,aAAa,CAAC;CACpB;AAED,MAAM,WAAW,mBAAmB;IAClC,IAAI,EAAE,SAAS,CAAC;IAChB,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,EAAE,OAAO,CAAC;CACrB;AAED,MAAM,WAAW,WAAY,SAAQ,KAAK,CAAC,MAAM,GAAG,WAAW,CAAC;CAAG;AAEnE,MAAM,WAAW,iBAAiB;IAChC,IAAI,EAAE,OAAO,CAAC;IACd,KAAK,EAAE,WAAW,CAAC;IACnB,QAAQ,EAAE,OAAO,CAAC;IAClB,UAAU,EAAE,OAAO,CAAC;CACrB;AAED,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,KAAK,CAAC;CACb;AAED,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,KAAK,CAAC;CACb;AAED,MAAM,WAAW,iBAAiB;IAChC,IAAI,EAAE,OAAO,CAAC;IACd,WAAW,EAAE,MAAM,CAAC;CACrB;AAED,oBAAY,WAAW,GAAG,mBAAmB,GAAG,iBAAiB,GAAG,eAAe,GAAG,eAAe,GAAG,iBAAiB,CAAC;AAE1H,qBAAa,WAAY,SAAQ,KAAK;WACtB,YAAY,CAAC,QAAQ,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI;IA0FjE,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,WAAW,EAAE,CAAC;IACxB,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,QAAQ,EAAE,UAAU,CAAC;IACrB,IAAI,EAAE,MAAM,CAAC;gBAER,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,EAAE,QAAQ,EAAE,UAAU;CAYjG;AAg3CD,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,CAAC,EAAE,GAAG,CAAC;IACb,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC;CACpB;AACD,oBAAY,aAAa,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,aAAa,KAAK,GAAG,CAAC;AAC5E,eAAO,MAAM,KAAK,EAAE,aAAyB,CAAC"} \ No newline at end of file diff --git a/lib/grammar/dist/grammar.js b/lib/grammar/dist/grammar.js deleted file mode 100644 index 35f6c5bd2..000000000 --- a/lib/grammar/dist/grammar.js +++ /dev/null @@ -1,1508 +0,0 @@ -"use strict"; -// tslint:disable:interface-name -// tslint:disable: trailing-comma -// tslint:disable: object-literal-sort-keys -// tslint:disable: max-line-length -// tslint:disable: only-arrow-functions -// tslint:disable: one-variable-per-declaration -// tslint:disable: no-consecutive-blank-lines -// tslint:disable: align -// tslint:disable: radix -// tslint:disable: quotemark -// tslint:disable: semicolon -// tslint:disable: object-literal-shorthand -// tslint:disable: variable-name -// tslint:disable: no-var-keyword -// tslint:disable: whitespace -// tslint:disable: curly -// tslint:disable: prefer-const -// tslint:disable: object-literal-key-quotes -// tslint:disable: no-string-literal -// tslint:disable: one-line -// tslint:disable: no-unused-expression -// tslint:disable: space-before-function-paren -// tslint:disable: arrow-return-shorthand -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -// Generated by PEG.js v. 0.10.0 (ts-pegjs plugin v. 0.2.6 ) -// -// https://pegjs.org/ https://github.com/metadevpro/ts-pegjs -var name_addr_header_1 = require("../../core/messages/name-addr-header"); -var uri_1 = require("../../core/messages/uri"); -var SyntaxError = /** @class */ (function (_super) { - tslib_1.__extends(SyntaxError, _super); - function SyntaxError(message, expected, found, location) { - var _this = _super.call(this) || this; - _this.message = message; - _this.expected = expected; - _this.found = found; - _this.location = location; - _this.name = "SyntaxError"; - if (typeof Error.captureStackTrace === "function") { - Error.captureStackTrace(_this, SyntaxError); - } - return _this; - } - SyntaxError.buildMessage = function (expected, found) { - function hex(ch) { - return ch.charCodeAt(0).toString(16).toUpperCase(); - } - function literalEscape(s) { - return s - .replace(/\\/g, "\\\\") - .replace(/"/g, "\\\"") - .replace(/\0/g, "\\0") - .replace(/\t/g, "\\t") - .replace(/\n/g, "\\n") - .replace(/\r/g, "\\r") - .replace(/[\x00-\x0F]/g, function (ch) { return "\\x0" + hex(ch); }) - .replace(/[\x10-\x1F\x7F-\x9F]/g, function (ch) { return "\\x" + hex(ch); }); - } - function classEscape(s) { - return s - .replace(/\\/g, "\\\\") - .replace(/\]/g, "\\]") - .replace(/\^/g, "\\^") - .replace(/-/g, "\\-") - .replace(/\0/g, "\\0") - .replace(/\t/g, "\\t") - .replace(/\n/g, "\\n") - .replace(/\r/g, "\\r") - .replace(/[\x00-\x0F]/g, function (ch) { return "\\x0" + hex(ch); }) - .replace(/[\x10-\x1F\x7F-\x9F]/g, function (ch) { return "\\x" + hex(ch); }); - } - function describeExpectation(expectation) { - switch (expectation.type) { - case "literal": - return "\"" + literalEscape(expectation.text) + "\""; - case "class": - var escapedParts = expectation.parts.map(function (part) { - return Array.isArray(part) - ? classEscape(part[0]) + "-" + classEscape(part[1]) - : classEscape(part); - }); - return "[" + (expectation.inverted ? "^" : "") + escapedParts + "]"; - case "any": - return "any character"; - case "end": - return "end of input"; - case "other": - return expectation.description; - } - } - function describeExpected(expected1) { - var descriptions = expected1.map(describeExpectation); - var i; - var j; - descriptions.sort(); - if (descriptions.length > 0) { - for (i = 1, j = 1; i < descriptions.length; i++) { - if (descriptions[i - 1] !== descriptions[i]) { - descriptions[j] = descriptions[i]; - j++; - } - } - descriptions.length = j; - } - switch (descriptions.length) { - case 1: - return descriptions[0]; - case 2: - return descriptions[0] + " or " + descriptions[1]; - default: - return descriptions.slice(0, -1).join(", ") - + ", or " - + descriptions[descriptions.length - 1]; - } - } - function describeFound(found1) { - return found1 ? "\"" + literalEscape(found1) + "\"" : "end of input"; - } - return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found."; - }; - return SyntaxError; -}(Error)); -exports.SyntaxError = SyntaxError; -function peg$parse(input, options) { - options = options !== undefined ? options : {}; - var peg$FAILED = {}; - var peg$startRuleIndices = { Contact: 119, Name_Addr_Header: 156, Record_Route: 176, Request_Response: 81, SIP_URI: 45, Subscription_State: 186, Supported: 191, Require: 182, Via: 194, absoluteURI: 84, Call_ID: 118, Content_Disposition: 130, Content_Length: 135, Content_Type: 136, CSeq: 146, displayName: 122, Event: 149, From: 151, host: 52, Max_Forwards: 154, Min_SE: 213, Proxy_Authenticate: 157, quoted_string: 40, Refer_To: 178, Replaces: 179, Session_Expires: 210, stun_URI: 217, To: 192, turn_URI: 223, uuid: 226, WWW_Authenticate: 209, challenge: 158, sipfrag: 230, Referred_By: 231 }; - var peg$startRuleIndex = 119; - var peg$consts = [ - "\r\n", - peg$literalExpectation("\r\n", false), - /^[0-9]/, - peg$classExpectation([["0", "9"]], false, false), - /^[a-zA-Z]/, - peg$classExpectation([["a", "z"], ["A", "Z"]], false, false), - /^[0-9a-fA-F]/, - peg$classExpectation([["0", "9"], ["a", "f"], ["A", "F"]], false, false), - /^[\0-\xFF]/, - peg$classExpectation([["\0", "\xFF"]], false, false), - /^["]/, - peg$classExpectation(["\""], false, false), - " ", - peg$literalExpectation(" ", false), - "\t", - peg$literalExpectation("\t", false), - /^[a-zA-Z0-9]/, - peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"]], false, false), - ";", - peg$literalExpectation(";", false), - "/", - peg$literalExpectation("/", false), - "?", - peg$literalExpectation("?", false), - ":", - peg$literalExpectation(":", false), - "@", - peg$literalExpectation("@", false), - "&", - peg$literalExpectation("&", false), - "=", - peg$literalExpectation("=", false), - "+", - peg$literalExpectation("+", false), - "$", - peg$literalExpectation("$", false), - ",", - peg$literalExpectation(",", false), - "-", - peg$literalExpectation("-", false), - "_", - peg$literalExpectation("_", false), - ".", - peg$literalExpectation(".", false), - "!", - peg$literalExpectation("!", false), - "~", - peg$literalExpectation("~", false), - "*", - peg$literalExpectation("*", false), - "'", - peg$literalExpectation("'", false), - "(", - peg$literalExpectation("(", false), - ")", - peg$literalExpectation(")", false), - "%", - peg$literalExpectation("%", false), - function () { return " "; }, - function () { return ':'; }, - /^[!-~]/, - peg$classExpectation([["!", "~"]], false, false), - /^[\x80-\uFFFF]/, - peg$classExpectation([["\x80", "\uFFFF"]], false, false), - /^[\x80-\xBF]/, - peg$classExpectation([["\x80", "\xBF"]], false, false), - /^[a-f]/, - peg$classExpectation([["a", "f"]], false, false), - "`", - peg$literalExpectation("`", false), - "<", - peg$literalExpectation("<", false), - ">", - peg$literalExpectation(">", false), - "\\", - peg$literalExpectation("\\", false), - "[", - peg$literalExpectation("[", false), - "]", - peg$literalExpectation("]", false), - "{", - peg$literalExpectation("{", false), - "}", - peg$literalExpectation("}", false), - function () { return "*"; }, - function () { return "/"; }, - function () { return "="; }, - function () { return "("; }, - function () { return ")"; }, - function () { return ">"; }, - function () { return "<"; }, - function () { return ","; }, - function () { return ";"; }, - function () { return ":"; }, - function () { return "\""; }, - /^[!-']/, - peg$classExpectation([["!", "'"]], false, false), - /^[*-[]/, - peg$classExpectation([["*", "["]], false, false), - /^[\]-~]/, - peg$classExpectation([["]", "~"]], false, false), - function (contents) { - return contents; - }, - /^[#-[]/, - peg$classExpectation([["#", "["]], false, false), - /^[\0-\t]/, - peg$classExpectation([["\0", "\t"]], false, false), - /^[\x0B-\f]/, - peg$classExpectation([["\x0B", "\f"]], false, false), - /^[\x0E-\x7F]/, - peg$classExpectation([["\x0E", "\x7F"]], false, false), - function () { - options = options || { data: {} }; - options.data.uri = new uri_1.URI(options.data.scheme, options.data.user, options.data.host, options.data.port); - delete options.data.scheme; - delete options.data.user; - delete options.data.host; - delete options.data.host_type; - delete options.data.port; - }, - function () { - options = options || { data: {} }; - options.data.uri = new uri_1.URI(options.data.scheme, options.data.user, options.data.host, options.data.port, options.data.uri_params, options.data.uri_headers); - delete options.data.scheme; - delete options.data.user; - delete options.data.host; - delete options.data.host_type; - delete options.data.port; - delete options.data.uri_params; - if (options.startRule === 'SIP_URI') { - options.data = options.data.uri; - } - }, - "sips", - peg$literalExpectation("sips", true), - "sip", - peg$literalExpectation("sip", true), - function (uri_scheme) { - options = options || { data: {} }; - options.data.scheme = uri_scheme; - }, - function () { - options = options || { data: {} }; - options.data.user = decodeURIComponent(text().slice(0, -1)); - }, - function () { - options = options || { data: {} }; - options.data.password = text(); - }, - function () { - options = options || { data: {} }; - options.data.host = text(); - return options.data.host; - }, - function () { - options = options || { data: {} }; - options.data.host_type = 'domain'; - return text(); - }, - /^[a-zA-Z0-9_\-]/, - peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"], "_", "-"], false, false), - /^[a-zA-Z0-9\-]/, - peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"], "-"], false, false), - function () { - options = options || { data: {} }; - options.data.host_type = 'IPv6'; - return text(); - }, - "::", - peg$literalExpectation("::", false), - function () { - options = options || { data: {} }; - options.data.host_type = 'IPv6'; - return text(); - }, - function () { - options = options || { data: {} }; - options.data.host_type = 'IPv4'; - return text(); - }, - "25", - peg$literalExpectation("25", false), - /^[0-5]/, - peg$classExpectation([["0", "5"]], false, false), - "2", - peg$literalExpectation("2", false), - /^[0-4]/, - peg$classExpectation([["0", "4"]], false, false), - "1", - peg$literalExpectation("1", false), - /^[1-9]/, - peg$classExpectation([["1", "9"]], false, false), - function (port) { - options = options || { data: {} }; - port = parseInt(port.join('')); - options.data.port = port; - return port; - }, - "transport=", - peg$literalExpectation("transport=", true), - "udp", - peg$literalExpectation("udp", true), - "tcp", - peg$literalExpectation("tcp", true), - "sctp", - peg$literalExpectation("sctp", true), - "tls", - peg$literalExpectation("tls", true), - function (transport) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['transport'] = transport.toLowerCase(); - }, - "user=", - peg$literalExpectation("user=", true), - "phone", - peg$literalExpectation("phone", true), - "ip", - peg$literalExpectation("ip", true), - function (user) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['user'] = user.toLowerCase(); - }, - "method=", - peg$literalExpectation("method=", true), - function (method) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['method'] = method; - }, - "ttl=", - peg$literalExpectation("ttl=", true), - function (ttl) { - options = options || { data: {} }; - if (!options.data.params) - options.data.params = {}; - options.data.params['ttl'] = ttl; - }, - "maddr=", - peg$literalExpectation("maddr=", true), - function (maddr) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['maddr'] = maddr; - }, - "lr", - peg$literalExpectation("lr", true), - function () { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['lr'] = undefined; - }, - function (param, value) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - if (value === null) { - value = undefined; - } - else { - value = value[1]; - } - options.data.uri_params[param.toLowerCase()] = value; - }, - function (hname, hvalue) { - hname = hname.join('').toLowerCase(); - hvalue = hvalue.join(''); - options = options || { data: {} }; - if (!options.data.uri_headers) - options.data.uri_headers = {}; - if (!options.data.uri_headers[hname]) { - options.data.uri_headers[hname] = [hvalue]; - } - else { - options.data.uri_headers[hname].push(hvalue); - } - }, - function () { - options = options || { data: {} }; - // lots of tests fail if this isn't guarded... - if (options.startRule === 'Refer_To') { - options.data.uri = new uri_1.URI(options.data.scheme, options.data.user, options.data.host, options.data.port, options.data.uri_params, options.data.uri_headers); - delete options.data.scheme; - delete options.data.user; - delete options.data.host; - delete options.data.host_type; - delete options.data.port; - delete options.data.uri_params; - } - }, - "//", - peg$literalExpectation("//", false), - function () { - options = options || { data: {} }; - options.data.scheme = text(); - }, - peg$literalExpectation("SIP", true), - function () { - options = options || { data: {} }; - options.data.sip_version = text(); - }, - "INVITE", - peg$literalExpectation("INVITE", false), - "ACK", - peg$literalExpectation("ACK", false), - "VXACH", - peg$literalExpectation("VXACH", false), - "OPTIONS", - peg$literalExpectation("OPTIONS", false), - "BYE", - peg$literalExpectation("BYE", false), - "CANCEL", - peg$literalExpectation("CANCEL", false), - "REGISTER", - peg$literalExpectation("REGISTER", false), - "SUBSCRIBE", - peg$literalExpectation("SUBSCRIBE", false), - "NOTIFY", - peg$literalExpectation("NOTIFY", false), - "REFER", - peg$literalExpectation("REFER", false), - "PUBLISH", - peg$literalExpectation("PUBLISH", false), - function () { - options = options || { data: {} }; - options.data.method = text(); - return options.data.method; - }, - function (status_code) { - options = options || { data: {} }; - options.data.status_code = parseInt(status_code.join('')); - }, - function () { - options = options || { data: {} }; - options.data.reason_phrase = text(); - }, - function () { - options = options || { data: {} }; - options.data = text(); - }, - function () { - var idx, length; - options = options || { data: {} }; - length = options.data.multi_header.length; - for (idx = 0; idx < length; idx++) { - if (options.data.multi_header[idx].parsed === null) { - options.data = null; - break; - } - } - if (options.data !== null) { - options.data = options.data.multi_header; - } - else { - options.data = -1; - } - }, - function () { - var header; - options = options || { data: {} }; - if (!options.data.multi_header) - options.data.multi_header = []; - try { - header = new name_addr_header_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); - delete options.data.uri; - delete options.data.displayName; - delete options.data.params; - } - catch (e) { - header = null; - } - options.data.multi_header.push({ 'position': peg$currPos, - 'offset': location().start.offset, - 'parsed': header - }); - }, - function (displayName) { - displayName = text().trim(); - if (displayName[0] === '\"') { - displayName = displayName.substring(1, displayName.length - 1); - } - options = options || { data: {} }; - options.data.displayName = displayName; - }, - "q", - peg$literalExpectation("q", true), - function (q) { - options = options || { data: {} }; - if (!options.data.params) - options.data.params = {}; - options.data.params['q'] = q; - }, - "expires", - peg$literalExpectation("expires", true), - function (expires) { - options = options || { data: {} }; - if (!options.data.params) - options.data.params = {}; - options.data.params['expires'] = expires; - }, - function (delta_seconds) { - return parseInt(delta_seconds.join('')); - }, - "0", - peg$literalExpectation("0", false), - function () { - return parseFloat(text()); - }, - function (param, value) { - options = options || { data: {} }; - if (!options.data.params) - options.data.params = {}; - if (value === null) { - value = undefined; - } - else { - value = value[1]; - } - options.data.params[param.toLowerCase()] = value; - }, - "render", - peg$literalExpectation("render", true), - "session", - peg$literalExpectation("session", true), - "icon", - peg$literalExpectation("icon", true), - "alert", - peg$literalExpectation("alert", true), - function () { - options = options || { data: {} }; - if (options.startRule === 'Content_Disposition') { - options.data.type = text().toLowerCase(); - } - }, - "handling", - peg$literalExpectation("handling", true), - "optional", - peg$literalExpectation("optional", true), - "required", - peg$literalExpectation("required", true), - function (length) { - options = options || { data: {} }; - options.data = parseInt(length.join('')); - }, - function () { - options = options || { data: {} }; - options.data = text(); - }, - "text", - peg$literalExpectation("text", true), - "image", - peg$literalExpectation("image", true), - "audio", - peg$literalExpectation("audio", true), - "video", - peg$literalExpectation("video", true), - "application", - peg$literalExpectation("application", true), - "message", - peg$literalExpectation("message", true), - "multipart", - peg$literalExpectation("multipart", true), - "x-", - peg$literalExpectation("x-", true), - function (cseq_value) { - options = options || { data: {} }; - options.data.value = parseInt(cseq_value.join('')); - }, - function (expires) { options = options || { data: {} }; options.data = expires; }, - function (event_type) { - options = options || { data: {} }; - options.data.event = event_type.toLowerCase(); - }, - function () { - options = options || { data: {} }; - var tag = options.data.tag; - options.data = new name_addr_header_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); - if (tag) { - options.data.setParam('tag', tag); - } - }, - "tag", - peg$literalExpectation("tag", true), - function (tag) { options = options || { data: {} }; options.data.tag = tag; }, - function (forwards) { - options = options || { data: {} }; - options.data = parseInt(forwards.join('')); - }, - function (min_expires) { options = options || { data: {} }; options.data = min_expires; }, - function () { - options = options || { data: {} }; - options.data = new name_addr_header_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); - }, - "digest", - peg$literalExpectation("Digest", true), - "realm", - peg$literalExpectation("realm", true), - function (realm) { options = options || { data: {} }; options.data.realm = realm; }, - "domain", - peg$literalExpectation("domain", true), - "nonce", - peg$literalExpectation("nonce", true), - function (nonce) { options = options || { data: {} }; options.data.nonce = nonce; }, - "opaque", - peg$literalExpectation("opaque", true), - function (opaque) { options = options || { data: {} }; options.data.opaque = opaque; }, - "stale", - peg$literalExpectation("stale", true), - "true", - peg$literalExpectation("true", true), - function () { options = options || { data: {} }; options.data.stale = true; }, - "false", - peg$literalExpectation("false", true), - function () { options = options || { data: {} }; options.data.stale = false; }, - "algorithm", - peg$literalExpectation("algorithm", true), - "md5", - peg$literalExpectation("MD5", true), - "md5-sess", - peg$literalExpectation("MD5-sess", true), - function (algorithm) { - options = options || { data: {} }; - options.data.algorithm = algorithm.toUpperCase(); - }, - "qop", - peg$literalExpectation("qop", true), - "auth-int", - peg$literalExpectation("auth-int", true), - "auth", - peg$literalExpectation("auth", true), - function (qop_value) { - options = options || { data: {} }; - options.data.qop || (options.data.qop = []); - options.data.qop.push(qop_value.toLowerCase()); - }, - function (rack_value) { - options = options || { data: {} }; - options.data.value = parseInt(rack_value.join('')); - }, - function () { - var idx, length; - options = options || { data: {} }; - length = options.data.multi_header.length; - for (idx = 0; idx < length; idx++) { - if (options.data.multi_header[idx].parsed === null) { - options.data = null; - break; - } - } - if (options.data !== null) { - options.data = options.data.multi_header; - } - else { - options.data = -1; - } - }, - function () { - var header; - options = options || { data: {} }; - if (!options.data.multi_header) - options.data.multi_header = []; - try { - header = new name_addr_header_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); - delete options.data.uri; - delete options.data.displayName; - delete options.data.params; - } - catch (e) { - header = null; - } - options.data.multi_header.push({ 'position': peg$currPos, - 'offset': location().start.offset, - 'parsed': header - }); - }, - function () { - options = options || { data: {} }; - options.data = new name_addr_header_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); - }, - function () { - options = options || { data: {} }; - if (!(options.data.replaces_from_tag && options.data.replaces_to_tag)) { - options.data = -1; - } - }, - function () { - options = options || { data: {} }; - options.data = { - call_id: options.data - }; - }, - "from-tag", - peg$literalExpectation("from-tag", true), - function (from_tag) { - options = options || { data: {} }; - options.data.replaces_from_tag = from_tag; - }, - "to-tag", - peg$literalExpectation("to-tag", true), - function (to_tag) { - options = options || { data: {} }; - options.data.replaces_to_tag = to_tag; - }, - "early-only", - peg$literalExpectation("early-only", true), - function () { - options = options || { data: {} }; - options.data.early_only = true; - }, - function (head, r) { return r; }, - function (head, tail) { return list(head, tail); }, - function (value) { - options = options || { data: {} }; - if (options.startRule === 'Require') { - options.data = value || []; - } - }, - function (rseq_value) { - options = options || { data: {} }; - options.data.value = parseInt(rseq_value.join('')); - }, - "active", - peg$literalExpectation("active", true), - "pending", - peg$literalExpectation("pending", true), - "terminated", - peg$literalExpectation("terminated", true), - function () { - options = options || { data: {} }; - options.data.state = text(); - }, - "reason", - peg$literalExpectation("reason", true), - function (reason) { - options = options || { data: {} }; - if (typeof reason !== 'undefined') - options.data.reason = reason; - }, - function (expires) { - options = options || { data: {} }; - if (typeof expires !== 'undefined') - options.data.expires = expires; - }, - "retry_after", - peg$literalExpectation("retry_after", true), - function (retry_after) { - options = options || { data: {} }; - if (typeof retry_after !== 'undefined') - options.data.retry_after = retry_after; - }, - "deactivated", - peg$literalExpectation("deactivated", true), - "probation", - peg$literalExpectation("probation", true), - "rejected", - peg$literalExpectation("rejected", true), - "timeout", - peg$literalExpectation("timeout", true), - "giveup", - peg$literalExpectation("giveup", true), - "noresource", - peg$literalExpectation("noresource", true), - "invariant", - peg$literalExpectation("invariant", true), - function (value) { - options = options || { data: {} }; - if (options.startRule === 'Supported') { - options.data = value || []; - } - }, - function () { - options = options || { data: {} }; - var tag = options.data.tag; - options.data = new name_addr_header_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); - if (tag) { - options.data.setParam('tag', tag); - } - }, - "ttl", - peg$literalExpectation("ttl", true), - function (via_ttl_value) { - options = options || { data: {} }; - options.data.ttl = via_ttl_value; - }, - "maddr", - peg$literalExpectation("maddr", true), - function (via_maddr) { - options = options || { data: {} }; - options.data.maddr = via_maddr; - }, - "received", - peg$literalExpectation("received", true), - function (via_received) { - options = options || { data: {} }; - options.data.received = via_received; - }, - "branch", - peg$literalExpectation("branch", true), - function (via_branch) { - options = options || { data: {} }; - options.data.branch = via_branch; - }, - "rport", - peg$literalExpectation("rport", true), - function (response_port) { - options = options || { data: {} }; - if (typeof response_port !== 'undefined') - options.data.rport = response_port.join(''); - }, - function (via_protocol) { - options = options || { data: {} }; - options.data.protocol = via_protocol; - }, - peg$literalExpectation("UDP", true), - peg$literalExpectation("TCP", true), - peg$literalExpectation("TLS", true), - peg$literalExpectation("SCTP", true), - function (via_transport) { - options = options || { data: {} }; - options.data.transport = via_transport; - }, - function () { - options = options || { data: {} }; - options.data.host = text(); - }, - function (via_sent_by_port) { - options = options || { data: {} }; - options.data.port = parseInt(via_sent_by_port.join('')); - }, - function (ttl) { - return parseInt(ttl.join('')); - }, - function (deltaSeconds) { - options = options || { data: {} }; - if (options.startRule === 'Session_Expires') { - options.data.deltaSeconds = deltaSeconds; - } - }, - "refresher", - peg$literalExpectation("refresher", false), - "uas", - peg$literalExpectation("uas", false), - "uac", - peg$literalExpectation("uac", false), - function (endpoint) { - options = options || { data: {} }; - if (options.startRule === 'Session_Expires') { - options.data.refresher = endpoint; - } - }, - function (deltaSeconds) { - options = options || { data: {} }; - if (options.startRule === 'Min_SE') { - options.data = deltaSeconds; - } - }, - "stuns", - peg$literalExpectation("stuns", true), - "stun", - peg$literalExpectation("stun", true), - function (scheme) { - options = options || { data: {} }; - options.data.scheme = scheme; - }, - function (host) { - options = options || { data: {} }; - options.data.host = host; - }, - "?transport=", - peg$literalExpectation("?transport=", false), - "turns", - peg$literalExpectation("turns", true), - "turn", - peg$literalExpectation("turn", true), - function (transport) { - options = options || { data: {} }; - options.data.transport = transport; - }, - function () { - options = options || { data: {} }; - options.data = text(); - }, - "Referred-By", - peg$literalExpectation("Referred-By", false), - "b", - peg$literalExpectation("b", false), - "cid", - peg$literalExpectation("cid", false) - ]; - var peg$bytecode = [ - peg$decode("2 \"\"6 7!"), - peg$decode("4\"\"\"5!7#"), - peg$decode("4$\"\"5!7%"), - peg$decode("4&\"\"5!7'"), - peg$decode(";'.# &;("), - peg$decode("4(\"\"5!7)"), - peg$decode("4*\"\"5!7+"), - peg$decode("2,\"\"6,7-"), - peg$decode("2.\"\"6.7/"), - peg$decode("40\"\"5!71"), - peg$decode("22\"\"6273.\x89 &24\"\"6475.} &26\"\"6677.q &28\"\"6879.e &2:\"\"6:7;.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E"), - peg$decode(";).# &;,"), - peg$decode("2F\"\"6F7G.} &2H\"\"6H7I.q &2J\"\"6J7K.e &2L\"\"6L7M.Y &2N\"\"6N7O.M &2P\"\"6P7Q.A &2R\"\"6R7S.5 &2T\"\"6T7U.) &2V\"\"6V7W"), - peg$decode("%%2X\"\"6X7Y/5#;#/,$;#/#$+#)(#'#(\"'#&'#/\"!&,)"), - peg$decode("%%$;$0#*;$&/,#; /#$+\")(\"'#&'#.\" &\"/=#$;$/�#*;$&&&#/'$8\":Z\" )(\"'#&'#"), - peg$decode(";..\" &\""), - peg$decode("%$;'.# &;(0)*;'.# &;(&/?#28\"\"6879/0$;//'$8#:[# )(#'#(\"'#&'#"), - peg$decode("%%$;2/�#*;2&&&#/g#$%$;.0#*;.&/,#;2/#$+\")(\"'#&'#0=*%$;.0#*;.&/,#;2/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/\"!&,)"), - peg$decode("4\\\"\"5!7].# &;3"), - peg$decode("4^\"\"5!7_"), - peg$decode("4`\"\"5!7a"), - peg$decode(";!.) &4b\"\"5!7c"), - peg$decode("%$;).\x95 &2F\"\"6F7G.\x89 &2J\"\"6J7K.} &2L\"\"6L7M.q &2X\"\"6X7Y.e &2P\"\"6P7Q.Y &2H\"\"6H7I.M &2@\"\"6@7A.A &2d\"\"6d7e.5 &2R\"\"6R7S.) &2N\"\"6N7O/\x9E#0\x9B*;).\x95 &2F\"\"6F7G.\x89 &2J\"\"6J7K.} &2L\"\"6L7M.q &2X\"\"6X7Y.e &2P\"\"6P7Q.Y &2H\"\"6H7I.M &2@\"\"6@7A.A &2d\"\"6d7e.5 &2R\"\"6R7S.) &2N\"\"6N7O&&&#/\"!&,)"), - peg$decode("%$;).\x89 &2F\"\"6F7G.} &2L\"\"6L7M.q &2X\"\"6X7Y.e &2P\"\"6P7Q.Y &2H\"\"6H7I.M &2@\"\"6@7A.A &2d\"\"6d7e.5 &2R\"\"6R7S.) &2N\"\"6N7O/\x92#0\x8F*;).\x89 &2F\"\"6F7G.} &2L\"\"6L7M.q &2X\"\"6X7Y.e &2P\"\"6P7Q.Y &2H\"\"6H7I.M &2@\"\"6@7A.A &2d\"\"6d7e.5 &2R\"\"6R7S.) &2N\"\"6N7O&&&#/\"!&,)"), - peg$decode("2T\"\"6T7U.\xE3 &2V\"\"6V7W.\xD7 &2f\"\"6f7g.\xCB &2h\"\"6h7i.\xBF &2:\"\"6:7;.\xB3 &2D\"\"6D7E.\xA7 &22\"\"6273.\x9B &28\"\"6879.\x8F &2j\"\"6j7k.\x83 &;&.} &24\"\"6475.q &2l\"\"6l7m.e &2n\"\"6n7o.Y &26\"\"6677.M &2>\"\"6>7?.A &2p\"\"6p7q.5 &2r\"\"6r7s.) &;'.# &;("), - peg$decode("%$;).\u012B &2F\"\"6F7G.\u011F &2J\"\"6J7K.\u0113 &2L\"\"6L7M.\u0107 &2X\"\"6X7Y.\xFB &2P\"\"6P7Q.\xEF &2H\"\"6H7I.\xE3 &2@\"\"6@7A.\xD7 &2d\"\"6d7e.\xCB &2R\"\"6R7S.\xBF &2N\"\"6N7O.\xB3 &2T\"\"6T7U.\xA7 &2V\"\"6V7W.\x9B &2f\"\"6f7g.\x8F &2h\"\"6h7i.\x83 &28\"\"6879.w &2j\"\"6j7k.k &;&.e &24\"\"6475.Y &2l\"\"6l7m.M &2n\"\"6n7o.A &26\"\"6677.5 &2p\"\"6p7q.) &2r\"\"6r7s/\u0134#0\u0131*;).\u012B &2F\"\"6F7G.\u011F &2J\"\"6J7K.\u0113 &2L\"\"6L7M.\u0107 &2X\"\"6X7Y.\xFB &2P\"\"6P7Q.\xEF &2H\"\"6H7I.\xE3 &2@\"\"6@7A.\xD7 &2d\"\"6d7e.\xCB &2R\"\"6R7S.\xBF &2N\"\"6N7O.\xB3 &2T\"\"6T7U.\xA7 &2V\"\"6V7W.\x9B &2f\"\"6f7g.\x8F &2h\"\"6h7i.\x83 &28\"\"6879.w &2j\"\"6j7k.k &;&.e &24\"\"6475.Y &2l\"\"6l7m.M &2n\"\"6n7o.A &26\"\"6677.5 &2p\"\"6p7q.) &2r\"\"6r7s&&&#/\"!&,)"), - peg$decode("%;//?#2P\"\"6P7Q/0$;//'$8#:t# )(#'#(\"'#&'#"), - peg$decode("%;//?#24\"\"6475/0$;//'$8#:u# )(#'#(\"'#&'#"), - peg$decode("%;//?#2>\"\"6>7?/0$;//'$8#:v# )(#'#(\"'#&'#"), - peg$decode("%;//?#2T\"\"6T7U/0$;//'$8#:w# )(#'#(\"'#&'#"), - peg$decode("%;//?#2V\"\"6V7W/0$;//'$8#:x# )(#'#(\"'#&'#"), - peg$decode("%2h\"\"6h7i/0#;//'$8\":y\" )(\"'#&'#"), - peg$decode("%;//6#2f\"\"6f7g/'$8\":z\" )(\"'#&'#"), - peg$decode("%;//?#2D\"\"6D7E/0$;//'$8#:{# )(#'#(\"'#&'#"), - peg$decode("%;//?#22\"\"6273/0$;//'$8#:|# )(#'#(\"'#&'#"), - peg$decode("%;//?#28\"\"6879/0$;//'$8#:}# )(#'#(\"'#&'#"), - peg$decode("%;//0#;&/'$8\":~\" )(\"'#&'#"), - peg$decode("%;&/0#;//'$8\":~\" )(\"'#&'#"), - peg$decode("%;=/T#$;G.) &;K.# &;F0/*;G.) &;K.# &;F&/,$;>/#$+#)(#'#(\"'#&'#"), - peg$decode("4\x7F\"\"5!7\x80.A &4\x81\"\"5!7\x82.5 &4\x83\"\"5!7\x84.) &;3.# &;."), - peg$decode("%%;//Q#;&/H$$;J.# &;K0)*;J.# &;K&/,$;&/#$+$)($'#(#'#(\"'#&'#/\"!&,)"), - peg$decode("%;//]#;&/T$%$;J.# &;K0)*;J.# &;K&/\"!&,)/1$;&/($8$:\x85$!!)($'#(#'#(\"'#&'#"), - peg$decode(";..G &2L\"\"6L7M.; &4\x86\"\"5!7\x87./ &4\x83\"\"5!7\x84.# &;3"), - peg$decode("%2j\"\"6j7k/J#4\x88\"\"5!7\x89.5 &4\x8A\"\"5!7\x8B.) &4\x8C\"\"5!7\x8D/#$+\")(\"'#&'#"), - peg$decode("%;N/M#28\"\"6879/>$;O.\" &\"/0$;S/'$8$:\x8E$ )($'#(#'#(\"'#&'#"), - peg$decode("%;N/d#28\"\"6879/U$;O.\" &\"/G$;S/>$;_/5$;l.\" &\"/'$8&:\x8F& )(&'#(%'#($'#(#'#(\"'#&'#"), - peg$decode("%3\x90\"\"5$7\x91.) &3\x92\"\"5#7\x93/' 8!:\x94!! )"), - peg$decode("%;P/]#%28\"\"6879/,#;R/#$+\")(\"'#&'#.\" &\"/6$2:\"\"6:7;/'$8#:\x95# )(#'#(\"'#&'#"), - peg$decode("$;+.) &;-.# &;Q/2#0/*;+.) &;-.# &;Q&&&#"), - peg$decode("2<\"\"6<7=.q &2>\"\"6>7?.e &2@\"\"6@7A.Y &2B\"\"6B7C.M &2D\"\"6D7E.A &22\"\"6273.5 &26\"\"6677.) &24\"\"6475"), - peg$decode("%$;+._ &;-.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E0e*;+._ &;-.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E&/& 8!:\x96! )"), - peg$decode("%;T/J#%28\"\"6879/,#;^/#$+\")(\"'#&'#.\" &\"/#$+\")(\"'#&'#"), - peg$decode("%;U.) &;\\.# &;X/& 8!:\x97! )"), - peg$decode("%$%;V/2#2J\"\"6J7K/#$+\")(\"'#&'#0<*%;V/2#2J\"\"6J7K/#$+\")(\"'#&'#&/D#;W/;$2J\"\"6J7K.\" &\"/'$8#:\x98# )(#'#(\"'#&'#"), - peg$decode("$4\x99\"\"5!7\x9A/,#0)*4\x99\"\"5!7\x9A&&&#"), - peg$decode("%4$\"\"5!7%/?#$4\x9B\"\"5!7\x9C0)*4\x9B\"\"5!7\x9C&/#$+\")(\"'#&'#"), - peg$decode("%2l\"\"6l7m/?#;Y/6$2n\"\"6n7o/'$8#:\x9D# )(#'#(\"'#&'#"), - peg$decode("%%;Z/\xB3#28\"\"6879/\xA4$;Z/\x9B$28\"\"6879/\x8C$;Z/\x83$28\"\"6879/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+-)(-'#(,'#(+'#(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0790 &%2\x9E\"\"6\x9E7\x9F/\xA4#;Z/\x9B$28\"\"6879/\x8C$;Z/\x83$28\"\"6879/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+,)(,'#(+'#(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u06F9 &%2\x9E\"\"6\x9E7\x9F/\x8C#;Z/\x83$28\"\"6879/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+*)(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u067A &%2\x9E\"\"6\x9E7\x9F/t#;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+()(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0613 &%2\x9E\"\"6\x9E7\x9F/\\#;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+&)(&'#(%'#($'#(#'#(\"'#&'#.\u05C4 &%2\x9E\"\"6\x9E7\x9F/D#;Z/;$28\"\"6879/,$;[/#$+$)($'#(#'#(\"'#&'#.\u058D &%2\x9E\"\"6\x9E7\x9F/,#;[/#$+\")(\"'#&'#.\u056E &%2\x9E\"\"6\x9E7\x9F/,#;Z/#$+\")(\"'#&'#.\u054F &%;Z/\x9B#2\x9E\"\"6\x9E7\x9F/\x8C$;Z/\x83$28\"\"6879/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$++)(+'#(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u04C7 &%;Z/\xAA#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x83$2\x9E\"\"6\x9E7\x9F/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+*)(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0430 &%;Z/\xB9#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x92$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/k$2\x9E\"\"6\x9E7\x9F/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+))()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u038A &%;Z/\xC8#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xA1$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/z$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/S$2\x9E\"\"6\x9E7\x9F/D$;Z/;$28\"\"6879/,$;[/#$+()(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u02D5 &%;Z/\xD7#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xB0$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x89$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/b$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/;$2\x9E\"\"6\x9E7\x9F/,$;[/#$+')(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0211 &%;Z/\xFE#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xD7$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xB0$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x89$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/b$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/;$2\x9E\"\"6\x9E7\x9F/,$;Z/#$+()(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0126 &%;Z/\u011C#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xF5$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xCE$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xA7$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x80$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/Y$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/2$2\x9E\"\"6\x9E7\x9F/#$+()(('#(''#(&'#(%'#($'#(#'#(\"'#&'#/& 8!:\xA0! )"), - peg$decode("%;#/M#;#.\" &\"/?$;#.\" &\"/1$;#.\" &\"/#$+$)($'#(#'#(\"'#&'#"), - peg$decode("%;Z/;#28\"\"6879/,$;Z/#$+#)(#'#(\"'#&'#.# &;\\"), - peg$decode("%;]/o#2J\"\"6J7K/`$;]/W$2J\"\"6J7K/H$;]/?$2J\"\"6J7K/0$;]/'$8':\xA1' )(''#(&'#(%'#($'#(#'#(\"'#&'#"), - peg$decode("%2\xA2\"\"6\xA27\xA3/2#4\xA4\"\"5!7\xA5/#$+\")(\"'#&'#.\x98 &%2\xA6\"\"6\xA67\xA7/;#4\xA8\"\"5!7\xA9/,$;!/#$+#)(#'#(\"'#&'#.j &%2\xAA\"\"6\xAA7\xAB/5#;!/,$;!/#$+#)(#'#(\"'#&'#.B &%4\xAC\"\"5!7\xAD/,#;!/#$+\")(\"'#&'#.# &;!"), - peg$decode("%%;!.\" &\"/[#;!.\" &\"/M$;!.\" &\"/?$;!.\" &\"/1$;!.\" &\"/#$+%)(%'#($'#(#'#(\"'#&'#/' 8!:\xAE!! )"), - peg$decode("$%22\"\"6273/,#;`/#$+\")(\"'#&'#0<*%22\"\"6273/,#;`/#$+\")(\"'#&'#&"), - peg$decode(";a.A &;b.; &;c.5 &;d./ &;e.) &;f.# &;g"), - peg$decode("%3\xAF\"\"5*7\xB0/a#3\xB1\"\"5#7\xB2.G &3\xB3\"\"5#7\xB4.; &3\xB5\"\"5$7\xB6./ &3\xB7\"\"5#7\xB8.# &;6/($8\":\xB9\"! )(\"'#&'#"), - peg$decode("%3\xBA\"\"5%7\xBB/I#3\xBC\"\"5%7\xBD./ &3\xBE\"\"5\"7\xBF.# &;6/($8\":\xC0\"! )(\"'#&'#"), - peg$decode("%3\xC1\"\"5'7\xC2/1#;\x90/($8\":\xC3\"! )(\"'#&'#"), - peg$decode("%3\xC4\"\"5$7\xC5/1#;\xF0/($8\":\xC6\"! )(\"'#&'#"), - peg$decode("%3\xC7\"\"5&7\xC8/1#;T/($8\":\xC9\"! )(\"'#&'#"), - peg$decode("%3\xCA\"\"5\"7\xCB/N#%2>\"\"6>7?/,#;6/#$+\")(\"'#&'#.\" &\"/'$8\":\xCC\" )(\"'#&'#"), - peg$decode("%;h/P#%2>\"\"6>7?/,#;i/#$+\")(\"'#&'#.\" &\"/)$8\":\xCD\"\"! )(\"'#&'#"), - peg$decode("%$;j/�#*;j&&&#/\"!&,)"), - peg$decode("%$;j/�#*;j&&&#/\"!&,)"), - peg$decode(";k.) &;+.# &;-"), - peg$decode("2l\"\"6l7m.e &2n\"\"6n7o.Y &24\"\"6475.M &28\"\"6879.A &2<\"\"6<7=.5 &2@\"\"6@7A.) &2B\"\"6B7C"), - peg$decode("%26\"\"6677/n#;m/e$$%2<\"\"6<7=/,#;m/#$+\")(\"'#&'#0<*%2<\"\"6<7=/,#;m/#$+\")(\"'#&'#&/#$+#)(#'#(\"'#&'#"), - peg$decode("%;n/A#2>\"\"6>7?/2$;o/)$8#:\xCE#\"\" )(#'#(\"'#&'#"), - peg$decode("$;p.) &;+.# &;-/2#0/*;p.) &;+.# &;-&&&#"), - peg$decode("$;p.) &;+.# &;-0/*;p.) &;+.# &;-&"), - peg$decode("2l\"\"6l7m.e &2n\"\"6n7o.Y &24\"\"6475.M &26\"\"6677.A &28\"\"6879.5 &2@\"\"6@7A.) &2B\"\"6B7C"), - peg$decode(";\x91.# &;r"), - peg$decode("%;\x90/G#;'/>$;s/5$;'/,$;\x84/#$+%)(%'#($'#(#'#(\"'#&'#"), - peg$decode(";M.# &;t"), - peg$decode("%;\x7F/E#28\"\"6879/6$;u.# &;x/'$8#:\xCF# )(#'#(\"'#&'#"), - peg$decode("%;v.# &;w/J#%26\"\"6677/,#;\x83/#$+\")(\"'#&'#.\" &\"/#$+\")(\"'#&'#"), - peg$decode("%2\xD0\"\"6\xD07\xD1/:#;\x80/1$;w.\" &\"/#$+#)(#'#(\"'#&'#"), - peg$decode("%24\"\"6475/,#;{/#$+\")(\"'#&'#"), - peg$decode("%;z/3#$;y0#*;y&/#$+\")(\"'#&'#"), - peg$decode(";*.) &;+.# &;-"), - peg$decode(";+.\x8F &;-.\x89 &22\"\"6273.} &26\"\"6677.q &28\"\"6879.e &2:\"\"6:7;.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E"), - peg$decode("%;|/e#$%24\"\"6475/,#;|/#$+\")(\"'#&'#0<*%24\"\"6475/,#;|/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"), - peg$decode("%$;~0#*;~&/e#$%22\"\"6273/,#;}/#$+\")(\"'#&'#0<*%22\"\"6273/,#;}/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"), - peg$decode("$;~0#*;~&"), - peg$decode(";+.w &;-.q &28\"\"6879.e &2:\"\"6:7;.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E"), - peg$decode("%%;\"/\x87#$;\".G &;!.A &2@\"\"6@7A.5 &2F\"\"6F7G.) &2J\"\"6J7K0M*;\".G &;!.A &2@\"\"6@7A.5 &2F\"\"6F7G.) &2J\"\"6J7K&/#$+\")(\"'#&'#/& 8!:\xD2! )"), - peg$decode(";\x81.# &;\x82"), - peg$decode("%%;O/2#2:\"\"6:7;/#$+\")(\"'#&'#.\" &\"/,#;S/#$+\")(\"'#&'#.\" &\""), - peg$decode("$;+.\x83 &;-.} &2B\"\"6B7C.q &2D\"\"6D7E.e &22\"\"6273.Y &28\"\"6879.M &2:\"\"6:7;.A &2<\"\"6<7=.5 &2>\"\"6>7?.) &2@\"\"6@7A/\x8C#0\x89*;+.\x83 &;-.} &2B\"\"6B7C.q &2D\"\"6D7E.e &22\"\"6273.Y &28\"\"6879.M &2:\"\"6:7;.A &2<\"\"6<7=.5 &2>\"\"6>7?.) &2@\"\"6@7A&&&#"), - peg$decode("$;y0#*;y&"), - peg$decode("%3\x92\"\"5#7\xD3/q#24\"\"6475/b$$;!/�#*;!&&&#/L$2J\"\"6J7K/=$$;!/�#*;!&&&#/'$8%:\xD4% )(%'#($'#(#'#(\"'#&'#"), - peg$decode("2\xD5\"\"6\xD57\xD6"), - peg$decode("2\xD7\"\"6\xD77\xD8"), - peg$decode("2\xD9\"\"6\xD97\xDA"), - peg$decode("2\xDB\"\"6\xDB7\xDC"), - peg$decode("2\xDD\"\"6\xDD7\xDE"), - peg$decode("2\xDF\"\"6\xDF7\xE0"), - peg$decode("2\xE1\"\"6\xE17\xE2"), - peg$decode("2\xE3\"\"6\xE37\xE4"), - peg$decode("2\xE5\"\"6\xE57\xE6"), - peg$decode("2\xE7\"\"6\xE77\xE8"), - peg$decode("2\xE9\"\"6\xE97\xEA"), - peg$decode("%;\x85.Y &;\x86.S &;\x88.M &;\x89.G &;\x8A.A &;\x8B.; &;\x8C.5 &;\x8F./ &;\x8D.) &;\x8E.# &;6/& 8!:\xEB! )"), - peg$decode("%;\x84/G#;'/>$;\x92/5$;'/,$;\x94/#$+%)(%'#($'#(#'#(\"'#&'#"), - peg$decode("%;\x93/' 8!:\xEC!! )"), - peg$decode("%;!/5#;!/,$;!/#$+#)(#'#(\"'#&'#"), - peg$decode("%$;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(0G*;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(&/& 8!:\xED! )"), - peg$decode("%;\xB6/Y#$%;A/,#;\xB6/#$+\")(\"'#&'#06*%;A/,#;\xB6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"), - peg$decode("%;9/N#%2:\"\"6:7;/,#;9/#$+\")(\"'#&'#.\" &\"/'$8\":\xEE\" )(\"'#&'#"), - peg$decode("%;:.c &%;\x98/Y#$%;A/,#;\x98/#$+\")(\"'#&'#06*%;A/,#;\x98/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/& 8!:\xEF! )"), - peg$decode("%;L.# &;\x99/]#$%;B/,#;\x9B/#$+\")(\"'#&'#06*%;B/,#;\x9B/#$+\")(\"'#&'#&/'$8\":\xF0\" )(\"'#&'#"), - peg$decode("%;\x9A.\" &\"/>#;@/5$;M/,$;?/#$+$)($'#(#'#(\"'#&'#"), - peg$decode("%%;6/Y#$%;./,#;6/#$+\")(\"'#&'#06*%;./,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#.# &;H/' 8!:\xF1!! )"), - peg$decode(";\x9C.) &;\x9D.# &;\xA0"), - peg$decode("%3\xF2\"\"5!7\xF3/:#;$;\xCF/5$;./,$;\x90/#$+%)(%'#($'#(#'#(\"'#&'#"), - peg$decode("%$;!/�#*;!&&&#/' 8!:\u014B!! )"), - peg$decode("%;\xD1/]#$%;A/,#;\xD1/#$+\")(\"'#&'#06*%;A/,#;\xD1/#$+\")(\"'#&'#&/'$8\":\u014C\" )(\"'#&'#"), - peg$decode("%;\x99/]#$%;B/,#;\xA0/#$+\")(\"'#&'#06*%;B/,#;\xA0/#$+\")(\"'#&'#&/'$8\":\u014D\" )(\"'#&'#"), - peg$decode("%;L.O &;\x99.I &%;@.\" &\"/:#;t/1$;?.\" &\"/#$+#)(#'#(\"'#&'#/]#$%;B/,#;\xA0/#$+\")(\"'#&'#06*%;B/,#;\xA0/#$+\")(\"'#&'#&/'$8\":\u014E\" )(\"'#&'#"), - peg$decode("%;\xD4/]#$%;B/,#;\xD5/#$+\")(\"'#&'#06*%;B/,#;\xD5/#$+\")(\"'#&'#&/'$8\":\u014F\" )(\"'#&'#"), - peg$decode("%;\x96/& 8!:\u0150! )"), - peg$decode("%3\u0151\"\"5(7\u0152/:#;$;6/5$;;/,$;\xEC/#$+%)(%'#($'#(#'#(\"'#&'#"), - peg$decode("%3\x92\"\"5#7\xD3.# &;6/' 8!:\u018B!! )"), - peg$decode("%3\xB1\"\"5#7\u018C.G &3\xB3\"\"5#7\u018D.; &3\xB7\"\"5#7\u018E./ &3\xB5\"\"5$7\u018F.# &;6/' 8!:\u0190!! )"), - peg$decode("%;\xEE/D#%;C/,#;\xEF/#$+\")(\"'#&'#.\" &\"/#$+\")(\"'#&'#"), - peg$decode("%;U.) &;\\.# &;X/& 8!:\u0191! )"), - peg$decode("%%;!.\" &\"/[#;!.\" &\"/M$;!.\" &\"/?$;!.\" &\"/1$;!.\" &\"/#$+%)(%'#($'#(#'#(\"'#&'#/' 8!:\u0192!! )"), - peg$decode("%%;!/?#;!.\" &\"/1$;!.\" &\"/#$+#)(#'#(\"'#&'#/' 8!:\u0193!! )"), - peg$decode(";\xBE"), - peg$decode("%;\x9E/^#$%;B/,#;\xF3/#$+\")(\"'#&'#06*%;B/,#;\xF3/#$+\")(\"'#&'#&/($8\":\u0194\"!!)(\"'#&'#"), - peg$decode(";\xF4.# &;\xA0"), - peg$decode("%2\u0195\"\"6\u01957\u0196/L#;\"\"6>7?"), - peg$decode("%;\u0100/b#28\"\"6879/S$;\xFB/J$%2\u01A3\"\"6\u01A37\u01A4/,#;\xEC/#$+\")(\"'#&'#.\" &\"/#$+$)($'#(#'#(\"'#&'#"), - peg$decode("%3\u01A5\"\"5%7\u01A6.) &3\u01A7\"\"5$7\u01A8/' 8!:\u01A1!! )"), - peg$decode("%3\xB1\"\"5#7\xB2.6 &3\xB3\"\"5#7\xB4.* &$;+0#*;+&/' 8!:\u01A9!! )"), - peg$decode("%;\u0104/\x87#2F\"\"6F7G/x$;\u0103/o$2F\"\"6F7G/`$;\u0103/W$2F\"\"6F7G/H$;\u0103/?$2F\"\"6F7G/0$;\u0105/'$8):\u01AA) )()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#"), - peg$decode("%;#/>#;#/5$;#/,$;#/#$+$)($'#(#'#(\"'#&'#"), - peg$decode("%;\u0103/,#;\u0103/#$+\")(\"'#&'#"), - peg$decode("%;\u0103/5#;\u0103/,$;\u0103/#$+#)(#'#(\"'#&'#"), - peg$decode("%;q/T#$;m0#*;m&/D$%; /,#;\xF8/#$+\")(\"'#&'#.\" &\"/#$+#)(#'#(\"'#&'#"), - peg$decode("%2\u01AB\"\"6\u01AB7\u01AC.) &2\u01AD\"\"6\u01AD7\u01AE/w#;0/n$;\u0108/e$$%;B/2#;\u0109.# &;\xA0/#$+\")(\"'#&'#0<*%;B/2#;\u0109.# &;\xA0/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"), - peg$decode(";\x99.# &;L"), - peg$decode("%2\u01AF\"\"6\u01AF7\u01B0/5#; peg$maxFailPos) { - peg$maxFailPos = peg$currPos; - peg$maxFailExpected = []; - } - peg$maxFailExpected.push(expected1); - } - function peg$buildSimpleError(message, location1) { - return new SyntaxError(message, [], "", location1); - } - function peg$buildStructuredError(expected1, found, location1) { - return new SyntaxError(SyntaxError.buildMessage(expected1, found), expected1, found, location1); - } - function peg$decode(s) { - return s.split("").map(function (ch) { return ch.charCodeAt(0) - 32; }); - } - function peg$parseRule(index) { - var bc = peg$bytecode[index]; - var ip = 0; - var ips = []; - var end = bc.length; - var ends = []; - var stack = []; - var params; - while (true) { - while (ip < end) { - switch (bc[ip]) { - case 0: - stack.push(peg$consts[bc[ip + 1]]); - ip += 2; - break; - case 1: - stack.push(undefined); - ip++; - break; - case 2: - stack.push(null); - ip++; - break; - case 3: - stack.push(peg$FAILED); - ip++; - break; - case 4: - stack.push([]); - ip++; - break; - case 5: - stack.push(peg$currPos); - ip++; - break; - case 6: - stack.pop(); - ip++; - break; - case 7: - peg$currPos = stack.pop(); - ip++; - break; - case 8: - stack.length -= bc[ip + 1]; - ip += 2; - break; - case 9: - stack.splice(-2, 1); - ip++; - break; - case 10: - stack[stack.length - 2].push(stack.pop()); - ip++; - break; - case 11: - stack.push(stack.splice(stack.length - bc[ip + 1], bc[ip + 1])); - ip += 2; - break; - case 12: - stack.push(input.substring(stack.pop(), peg$currPos)); - ip++; - break; - case 13: - ends.push(end); - ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); - if (stack[stack.length - 1]) { - end = ip + 3 + bc[ip + 1]; - ip += 3; - } - else { - end = ip + 3 + bc[ip + 1] + bc[ip + 2]; - ip += 3 + bc[ip + 1]; - } - break; - case 14: - ends.push(end); - ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); - if (stack[stack.length - 1] === peg$FAILED) { - end = ip + 3 + bc[ip + 1]; - ip += 3; - } - else { - end = ip + 3 + bc[ip + 1] + bc[ip + 2]; - ip += 3 + bc[ip + 1]; - } - break; - case 15: - ends.push(end); - ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); - if (stack[stack.length - 1] !== peg$FAILED) { - end = ip + 3 + bc[ip + 1]; - ip += 3; - } - else { - end = ip + 3 + bc[ip + 1] + bc[ip + 2]; - ip += 3 + bc[ip + 1]; - } - break; - case 16: - if (stack[stack.length - 1] !== peg$FAILED) { - ends.push(end); - ips.push(ip); - end = ip + 2 + bc[ip + 1]; - ip += 2; - } - else { - ip += 2 + bc[ip + 1]; - } - break; - case 17: - ends.push(end); - ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); - if (input.length > peg$currPos) { - end = ip + 3 + bc[ip + 1]; - ip += 3; - } - else { - end = ip + 3 + bc[ip + 1] + bc[ip + 2]; - ip += 3 + bc[ip + 1]; - } - break; - case 18: - ends.push(end); - ips.push(ip + 4 + bc[ip + 2] + bc[ip + 3]); - if (input.substr(peg$currPos, peg$consts[bc[ip + 1]].length) === peg$consts[bc[ip + 1]]) { - end = ip + 4 + bc[ip + 2]; - ip += 4; - } - else { - end = ip + 4 + bc[ip + 2] + bc[ip + 3]; - ip += 4 + bc[ip + 2]; - } - break; - case 19: - ends.push(end); - ips.push(ip + 4 + bc[ip + 2] + bc[ip + 3]); - if (input.substr(peg$currPos, peg$consts[bc[ip + 1]].length).toLowerCase() === peg$consts[bc[ip + 1]]) { - end = ip + 4 + bc[ip + 2]; - ip += 4; - } - else { - end = ip + 4 + bc[ip + 2] + bc[ip + 3]; - ip += 4 + bc[ip + 2]; - } - break; - case 20: - ends.push(end); - ips.push(ip + 4 + bc[ip + 2] + bc[ip + 3]); - if (peg$consts[bc[ip + 1]].test(input.charAt(peg$currPos))) { - end = ip + 4 + bc[ip + 2]; - ip += 4; - } - else { - end = ip + 4 + bc[ip + 2] + bc[ip + 3]; - ip += 4 + bc[ip + 2]; - } - break; - case 21: - stack.push(input.substr(peg$currPos, bc[ip + 1])); - peg$currPos += bc[ip + 1]; - ip += 2; - break; - case 22: - stack.push(peg$consts[bc[ip + 1]]); - peg$currPos += peg$consts[bc[ip + 1]].length; - ip += 2; - break; - case 23: - stack.push(peg$FAILED); - if (peg$silentFails === 0) { - peg$fail(peg$consts[bc[ip + 1]]); - } - ip += 2; - break; - case 24: - peg$savedPos = stack[stack.length - 1 - bc[ip + 1]]; - ip += 2; - break; - case 25: - peg$savedPos = peg$currPos; - ip++; - break; - case 26: - params = bc.slice(ip + 4, ip + 4 + bc[ip + 3]) - .map(function (p) { return stack[stack.length - 1 - p]; }); - stack.splice(stack.length - bc[ip + 2], bc[ip + 2], peg$consts[bc[ip + 1]].apply(null, params)); - ip += 4 + bc[ip + 3]; - break; - case 27: - stack.push(peg$parseRule(bc[ip + 1])); - ip += 2; - break; - case 28: - peg$silentFails++; - ip++; - break; - case 29: - peg$silentFails--; - ip++; - break; - default: - throw new Error("Invalid opcode: " + bc[ip] + "."); - } - } - if (ends.length > 0) { - end = ends.pop(); - ip = ips.pop(); - } - else { - break; - } - } - return stack[0]; - } - options.data = {}; // Object to which header attributes will be assigned during parsing - function list(head, tail) { - return [head].concat(tail); - } - peg$result = peg$parseRule(peg$startRuleIndex); - if (peg$result !== peg$FAILED && peg$currPos === input.length) { - return peg$result; - } - else { - if (peg$result !== peg$FAILED && peg$currPos < input.length) { - peg$fail(peg$endExpectation()); - } - throw peg$buildStructuredError(peg$maxFailExpected, peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, peg$maxFailPos < input.length - ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) - : peg$computeLocation(peg$maxFailPos, peg$maxFailPos)); - } -} -exports.parse = peg$parse; diff --git a/lib/index.d.ts b/lib/index.d.ts deleted file mode 100644 index 9401ac319..000000000 --- a/lib/index.d.ts +++ /dev/null @@ -1,33 +0,0 @@ -export { DigestAuthentication, Grammar, IncomingRequestMessage as IncomingRequest, IncomingResponseMessage as IncomingResponse, LoggerFactory, NameAddrHeader, OutgoingRequestMessage as OutgoingRequest, Timers, Transport, URI } from "./core"; -export { ClientContext } from "./ClientContext"; -import { C } from "./Constants"; -export { C }; -export { DialogStatus, SessionStatus, TypeStrings, UAStatus } from "./Enums"; -export { Exceptions } from "./Exceptions"; -export { Parser } from "./Parser"; -export { PublishContext } from "./PublishContext"; -export { ReferClientContext, ReferServerContext } from "./ReferContext"; -export { RegisterContext } from "./RegisterContext"; -export { ServerContext } from "./ServerContext"; -export { InviteClientContext, InviteServerContext, Session } from "./Session"; -export { SessionDescriptionHandlerFactory, SessionDescriptionHandlerFactoryOptions } from "./session-description-handler-factory"; -export { SessionDescriptionHandler, SessionDescriptionHandlerModifier, SessionDescriptionHandlerModifiers, SessionDescriptionHandlerOptions } from "./session-description-handler"; -export { Subscription } from "./Subscription"; -import { InviteClientTransaction, InviteServerTransaction, NonInviteClientTransaction, NonInviteServerTransaction } from "./core/transactions"; -declare const Transactions: { - InviteClientTransaction: typeof InviteClientTransaction; - InviteServerTransaction: typeof InviteServerTransaction; - NonInviteClientTransaction: typeof NonInviteClientTransaction; - NonInviteServerTransaction: typeof NonInviteServerTransaction; -}; -export { Transactions }; -export { makeUserAgentCoreConfigurationFromUA, UA } from "./UA"; -export { Utils } from "./Utils"; -import * as Web from "./Web/index"; -export { Web }; -declare const version = "0.15.5"; -declare const name = "sip.js"; -export { name, version }; -import * as Core from "./core/index"; -export { Core }; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/index.d.ts.map b/lib/index.d.ts.map deleted file mode 100644 index a6beb9813..000000000 --- a/lib/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oBAAoB,EACpB,OAAO,EACP,sBAAsB,IAAI,eAAe,EACzC,uBAAuB,IAAI,gBAAgB,EAC3C,aAAa,EACb,cAAc,EACd,sBAAsB,IAAI,eAAe,EACzC,MAAM,EACN,SAAS,EACT,GAAG,EACJ,MAAM,QAAQ,CAAC;AAEhB,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,CAAC,EAAE,MAAM,aAAa,CAAC;AAChC,OAAO,EAAE,CAAC,EAAE,CAAC;AACb,OAAO,EACL,YAAY,EACZ,aAAa,EACb,WAAW,EACX,QAAQ,EACT,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAClC,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EACL,kBAAkB,EAClB,kBAAkB,EACnB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EACL,mBAAmB,EACnB,mBAAmB,EACnB,OAAO,EACR,MAAM,WAAW,CAAC;AACnB,OAAO,EACL,gCAAgC,EAChC,uCAAuC,EACxC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EACL,yBAAyB,EACzB,iCAAiC,EACjC,kCAAkC,EAClC,gCAAgC,EACjC,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAE9C,OAAO,EACL,uBAAuB,EACvB,uBAAuB,EACvB,0BAA0B,EAC1B,0BAA0B,EAC3B,MAAM,qBAAqB,CAAC;AAC7B,QAAA,MAAM,YAAY;;;;;CAKjB,CAAC;AACF,OAAO,EAAE,YAAY,EAAE,CAAC;AAExB,OAAO,EAAE,oCAAoC,EAAE,EAAE,EAAE,MAAM,MAAM,CAAC;AAChE,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAEhC,OAAO,KAAK,GAAG,MAAM,aAAa,CAAC;AACnC,OAAO,EAAE,GAAG,EAAE,CAAC;AAEf,QAAA,MAAM,OAAO,WAAY,CAAC;AAC1B,QAAA,MAAM,IAAI,WAAW,CAAC;AACtB,OAAO,EACL,IAAI,EACJ,OAAO,EACR,CAAC;AAEF,OAAO,KAAK,IAAI,MAAM,cAAc,CAAC;AACrC,OAAO,EAAE,IAAI,EAAE,CAAC"} \ No newline at end of file diff --git a/lib/index.js b/lib/index.js deleted file mode 100644 index 7f1214d6e..000000000 --- a/lib/index.js +++ /dev/null @@ -1,63 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -var core_1 = require("./core"); -exports.DigestAuthentication = core_1.DigestAuthentication; -exports.Grammar = core_1.Grammar; -exports.IncomingRequest = core_1.IncomingRequestMessage; -exports.IncomingResponse = core_1.IncomingResponseMessage; -exports.LoggerFactory = core_1.LoggerFactory; -exports.NameAddrHeader = core_1.NameAddrHeader; -exports.OutgoingRequest = core_1.OutgoingRequestMessage; -exports.Timers = core_1.Timers; -exports.Transport = core_1.Transport; -exports.URI = core_1.URI; -var ClientContext_1 = require("./ClientContext"); -exports.ClientContext = ClientContext_1.ClientContext; -var Constants_1 = require("./Constants"); -exports.C = Constants_1.C; -var Enums_1 = require("./Enums"); -exports.DialogStatus = Enums_1.DialogStatus; -exports.SessionStatus = Enums_1.SessionStatus; -exports.TypeStrings = Enums_1.TypeStrings; -exports.UAStatus = Enums_1.UAStatus; -var Exceptions_1 = require("./Exceptions"); -exports.Exceptions = Exceptions_1.Exceptions; -var Parser_1 = require("./Parser"); -exports.Parser = Parser_1.Parser; -var PublishContext_1 = require("./PublishContext"); -exports.PublishContext = PublishContext_1.PublishContext; -var ReferContext_1 = require("./ReferContext"); -exports.ReferClientContext = ReferContext_1.ReferClientContext; -exports.ReferServerContext = ReferContext_1.ReferServerContext; -var RegisterContext_1 = require("./RegisterContext"); -exports.RegisterContext = RegisterContext_1.RegisterContext; -var ServerContext_1 = require("./ServerContext"); -exports.ServerContext = ServerContext_1.ServerContext; -var Session_1 = require("./Session"); -exports.InviteClientContext = Session_1.InviteClientContext; -exports.InviteServerContext = Session_1.InviteServerContext; -exports.Session = Session_1.Session; -var Subscription_1 = require("./Subscription"); -exports.Subscription = Subscription_1.Subscription; -var transactions_1 = require("./core/transactions"); -var Transactions = { - InviteClientTransaction: transactions_1.InviteClientTransaction, - InviteServerTransaction: transactions_1.InviteServerTransaction, - NonInviteClientTransaction: transactions_1.NonInviteClientTransaction, - NonInviteServerTransaction: transactions_1.NonInviteServerTransaction -}; -exports.Transactions = Transactions; -var UA_1 = require("./UA"); -exports.makeUserAgentCoreConfigurationFromUA = UA_1.makeUserAgentCoreConfigurationFromUA; -exports.UA = UA_1.UA; -var Utils_1 = require("./Utils"); -exports.Utils = Utils_1.Utils; -var Web = tslib_1.__importStar(require("./Web/index")); -exports.Web = Web; -var version = Constants_1.C.version; -exports.version = version; -var name = "sip.js"; -exports.name = name; -var Core = tslib_1.__importStar(require("./core/index")); -exports.Core = Core; diff --git a/lib/session-description-handler-factory.d.ts b/lib/session-description-handler-factory.d.ts deleted file mode 100644 index 898fadbce..000000000 --- a/lib/session-description-handler-factory.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { InviteClientContext, InviteServerContext } from "./Session"; -import { SessionDescriptionHandler } from "./session-description-handler"; -/** - * The SessionDescriptionHandlerFactory interface SIP.js is expecting. - */ -export interface SessionDescriptionHandlerFactory { - (session: InviteClientContext | InviteServerContext, options?: SessionDescriptionHandlerFactoryOptions): SessionDescriptionHandler; -} -/** - * SessionDescriptionHandlerFactory options. - * These options are provided as part of the UserAgent configuration - * and passed through on every call to SessionDescriptionHandlerFactory's constructor. - */ -export declare type SessionDescriptionHandlerFactoryOptions = object; -//# sourceMappingURL=session-description-handler-factory.d.ts.map \ No newline at end of file diff --git a/lib/session-description-handler-factory.d.ts.map b/lib/session-description-handler-factory.d.ts.map deleted file mode 100644 index 1c11c0674..000000000 --- a/lib/session-description-handler-factory.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"session-description-handler-factory.d.ts","sourceRoot":"","sources":["../src/session-description-handler-factory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AACrE,OAAO,EAAE,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAI1E;;GAEG;AACH,MAAM,WAAW,gCAAgC;IAC/C,CACE,OAAO,EAAE,mBAAmB,GAAG,mBAAmB,EAClD,OAAO,CAAC,EAAE,uCAAuC,GAChD,yBAAyB,CAAC;CAC9B;AAED;;;;GAIG;AACH,oBAAY,uCAAuC,GAAG,MAAM,CAAC"} \ No newline at end of file diff --git a/lib/session-description-handler-factory.js b/lib/session-description-handler-factory.js deleted file mode 100644 index c8ad2e549..000000000 --- a/lib/session-description-handler-factory.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/session-description-handler.d.ts b/lib/session-description-handler.d.ts deleted file mode 100644 index b78cc6bbb..000000000 --- a/lib/session-description-handler.d.ts +++ /dev/null @@ -1,71 +0,0 @@ -/** - * The SessionDescriptionHandler interface SIP.js is expecting. - */ -export interface SessionDescriptionHandler { - /** - * Destructor. - */ - close(): void; - /** - * Gets the local description from the underlying media implementation. - * @param options Options object to be used by getDescription. - * @param modifiers Array with one time use description modifiers. - * @returns Promise that resolves with the local description to be used for the session. - * @throws {ClosedSessionDescriptionHandlerError} When this method - * is called after close or when close occurs before complete. - */ - getDescription(options?: SessionDescriptionHandlerOptions, modifiers?: SessionDescriptionHandlerModifiers): Promise; - /** - * Returns true if the Session Description Handler can handle the Content-Type described by a SIP message. - * @param contentType The content type that is in the SIP Message. - * @returns True if the content type is handled by this session description handler. False otherwise. - */ - hasDescription(contentType: string): boolean; - /** - * The modifier that should be used when the session would like to place the call on hold. - * @param sessionDescription The description that will be modified. - * @returns Promise that resolves with modified SDP. - * @throws {ClosedSessionDescriptionHandlerError} When this method - * is called after close or when close occurs before complete. - */ - holdModifier(sessionDescription: RTCSessionDescriptionInit): Promise; - /** - * Sets the remote description to the underlying media implementation. - * @param sessionDescription The description provided by a SIP message to be set on the media implementation. - * @param options Options object to be used by setDescription. - * @param modifiers Array with one time use description modifiers. - * @returns Promise that resolves once the description is set. - * @throws {ClosedSessionDescriptionHandlerError} When this method - * is called after close or when close occurs before complete. - */ - setDescription(sdp: string, options?: SessionDescriptionHandlerOptions, modifiers?: SessionDescriptionHandlerModifiers): Promise; - /** - * Send DTMF via RTP (RFC 4733). - * Returns true if DTMF send is successful, false otherwise. - * @param tones A string containing DTMF digits. - * @param options Options object to be used by sendDtmf. - * @returns True if DTMF send is successful, false otherwise. - */ - sendDtmf(tones: string, options?: any): boolean; -} -export interface SessionDescriptionHandlerModifier { - (sessionDescription: RTCSessionDescriptionInit): Promise; -} -export declare type SessionDescriptionHandlerModifiers = Array; -/** - * SessionDescriptionHandler options. - * These options are provided to various UserAgent methods (invite() for example) - * and passed through on calls to getDescription() and setDescription(). - */ -export interface SessionDescriptionHandlerOptions { - modifiers?: SessionDescriptionHandlerModifiers; - constraints?: object; -} -/** - * SIP message body and content type. - */ -export interface BodyObj { - body: string; - contentType: string; -} -//# sourceMappingURL=session-description-handler.d.ts.map \ No newline at end of file diff --git a/lib/session-description-handler.d.ts.map b/lib/session-description-handler.d.ts.map deleted file mode 100644 index 279f5566c..000000000 --- a/lib/session-description-handler.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"session-description-handler.d.ts","sourceRoot":"","sources":["../src/session-description-handler.ts"],"names":[],"mappings":"AAEA;;GAEG;AACH,MAAM,WAAW,yBAAyB;IACxC;;OAEG;IACH,KAAK,IAAI,IAAI,CAAC;IAEd;;;;;;;OAOG;IACH,cAAc,CACZ,OAAO,CAAC,EAAE,gCAAgC,EAC1C,SAAS,CAAC,EAAE,kCAAkC,GAC7C,OAAO,CAAC,OAAO,CAAC,CAAC;IAEpB;;;;OAIG;IACH,cAAc,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC;IAE7C;;;;;;OAMG;IACH,YAAY,CAAC,kBAAkB,EAAE,yBAAyB,GAAG,OAAO,CAAC,yBAAyB,CAAC,CAAC;IAEhG;;;;;;;;OAQG;IACH,cAAc,CACZ,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,gCAAgC,EAC1C,SAAS,CAAC,EAAE,kCAAkC,GAC7C,OAAO,CAAC,IAAI,CAAC,CAAC;IAEjB;;;;;;OAMG;IACH,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,GAAG,GAAG,OAAO,CAAC;CACjD;AAED,MAAM,WAAW,iCAAiC;IAChD,CAAC,kBAAkB,EAAE,yBAAyB,GAAG,OAAO,CAAC,yBAAyB,CAAC,CAAC;CACrF;AAED,oBAAY,kCAAkC,GAAG,KAAK,CAAC,iCAAiC,CAAC,CAAC;AAE1F;;;;GAIG;AACH,MAAM,WAAW,gCAAgC;IAC/C,SAAS,CAAC,EAAE,kCAAkC,CAAC;IAC/C,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED;;GAEG;AACH,MAAM,WAAW,OAAO;IACtB,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;CACrB"} \ No newline at end of file diff --git a/lib/session-description-handler.js b/lib/session-description-handler.js deleted file mode 100644 index 993644a62..000000000 --- a/lib/session-description-handler.js +++ /dev/null @@ -1,3 +0,0 @@ -"use strict"; -// tslint:disable:callable-types -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/version.d.ts b/lib/version.d.ts deleted file mode 100644 index 50c206168..000000000 --- a/lib/version.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export declare const LIBRARY_VERSION = "0.15.5"; -//# sourceMappingURL=version.d.ts.map \ No newline at end of file diff --git a/lib/version.d.ts.map b/lib/version.d.ts.map deleted file mode 100644 index fb526ad54..000000000 --- a/lib/version.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../src/version.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,eAAe,WAAW,CAAC"} \ No newline at end of file diff --git a/lib/version.js b/lib/version.js deleted file mode 100644 index 9ed9b5c1a..000000000 --- a/lib/version.js +++ /dev/null @@ -1,3 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.LIBRARY_VERSION = "0.15.5";