From 0c7d355650547ba59573fb44da98ea96c076de22 Mon Sep 17 00:00:00 2001 From: James Criscuolo Date: Wed, 23 Dec 2020 10:22:12 -0500 Subject: [PATCH] dist/ lib/ files for 0.18.0 --- dist/sip-0.18.0.js | 20884 ++++++++++++++++ dist/sip-0.18.0.min.js | 1 + dist/sip.js | 20884 ++++++++++++++++ dist/sip.min.js | 1 + lib/api/bye.d.ts | 17 + lib/api/bye.d.ts.map | 1 + lib/api/bye.js | 24 + lib/api/dtmf.d.ts | 16 + lib/api/dtmf.d.ts.map | 1 + lib/api/dtmf.js | 20 + lib/api/emitter.d.ts | 89 + lib/api/emitter.d.ts.map | 1 + lib/api/emitter.js | 67 + .../exceptions/content-type-unsupported.d.ts | 9 + .../content-type-unsupported.d.ts.map | 1 + .../exceptions/content-type-unsupported.js | 10 + lib/api/exceptions/index.d.ts | 6 + lib/api/exceptions/index.d.ts.map | 1 + lib/api/exceptions/index.js | 5 + lib/api/exceptions/request-pending.d.ts | 10 + lib/api/exceptions/request-pending.d.ts.map | 1 + lib/api/exceptions/request-pending.js | 11 + .../session-description-handler.d.ts | 9 + .../session-description-handler.d.ts.map | 1 + .../exceptions/session-description-handler.js | 10 + lib/api/exceptions/session-terminated.d.ts | 9 + .../exceptions/session-terminated.d.ts.map | 1 + lib/api/exceptions/session-terminated.js | 10 + lib/api/exceptions/state-transition.d.ts | 9 + lib/api/exceptions/state-transition.d.ts.map | 1 + lib/api/exceptions/state-transition.js | 10 + lib/api/index.d.ts | 59 + lib/api/index.d.ts.map | 1 + lib/api/index.js | 58 + lib/api/info.d.ts | 17 + lib/api/info.d.ts.map | 1 + lib/api/info.js | 24 + lib/api/invitation-accept-options.d.ts | 16 + lib/api/invitation-accept-options.d.ts.map | 1 + lib/api/invitation-accept-options.js | 1 + lib/api/invitation-progress-options.d.ts | 39 + lib/api/invitation-progress-options.d.ts.map | 1 + lib/api/invitation-progress-options.js | 1 + lib/api/invitation-reject-options.d.ts | 26 + lib/api/invitation-reject-options.d.ts.map | 1 + lib/api/invitation-reject-options.js | 1 + lib/api/invitation.d.ts | 196 + lib/api/invitation.d.ts.map | 1 + lib/api/invitation.js | 708 + lib/api/inviter-cancel-options.d.ts | 10 + lib/api/inviter-cancel-options.d.ts.map | 1 + lib/api/inviter-cancel-options.js | 1 + lib/api/inviter-invite-options.d.ts | 29 + lib/api/inviter-invite-options.d.ts.map | 1 + lib/api/inviter-invite-options.js | 1 + lib/api/inviter-options.d.ts | 44 + lib/api/inviter-options.d.ts.map | 1 + lib/api/inviter-options.js | 1 + lib/api/inviter.d.ts | 237 + lib/api/inviter.d.ts.map | 1 + lib/api/inviter.js | 977 + lib/api/message.d.ts | 17 + lib/api/message.d.ts.map | 1 + lib/api/message.js | 24 + lib/api/messager-message-options.d.ts | 12 + lib/api/messager-message-options.d.ts.map | 1 + lib/api/messager-message-options.js | 1 + lib/api/messager-options.d.ts | 18 + lib/api/messager-options.d.ts.map | 1 + lib/api/messager-options.js | 1 + lib/api/messager.d.ts | 27 + lib/api/messager.d.ts.map | 1 + lib/api/messager.js | 59 + lib/api/notification.d.ts | 17 + lib/api/notification.d.ts.map | 1 + lib/api/notification.js | 24 + lib/api/notifier.d.ts | 9 + lib/api/notifier.d.ts.map | 1 + lib/api/notifier.js | 8 + lib/api/publisher-options.d.ts | 34 + lib/api/publisher-options.d.ts.map | 1 + lib/api/publisher-options.js | 1 + lib/api/publisher-publish-options.d.ts | 7 + lib/api/publisher-publish-options.d.ts.map | 1 + lib/api/publisher-publish-options.js | 1 + lib/api/publisher-state.d.ts | 22 + lib/api/publisher-state.d.ts.map | 1 + lib/api/publisher-state.js | 22 + lib/api/publisher-unpublish-options.d.ts | 7 + lib/api/publisher-unpublish-options.d.ts.map | 1 + lib/api/publisher-unpublish-options.js | 1 + lib/api/publisher.d.ts | 66 + lib/api/publisher.d.ts.map | 1 + lib/api/publisher.js | 326 + lib/api/referral.d.ts | 39 + lib/api/referral.d.ts.map | 1 + lib/api/referral.js | 75 + lib/api/registerer-options.d.ts | 42 + lib/api/registerer-options.d.ts.map | 1 + lib/api/registerer-options.js | 1 + lib/api/registerer-register-options.d.ts | 12 + lib/api/registerer-register-options.d.ts.map | 1 + lib/api/registerer-register-options.js | 1 + lib/api/registerer-state.d.ts | 22 + lib/api/registerer-state.d.ts.map | 1 + lib/api/registerer-state.js | 22 + lib/api/registerer-unregister-options.d.ts | 17 + .../registerer-unregister-options.d.ts.map | 1 + lib/api/registerer-unregister-options.js | 1 + lib/api/registerer.d.ts | 143 + lib/api/registerer.d.ts.map | 1 + lib/api/registerer.js | 663 + lib/api/session-bye-options.d.ts | 12 + lib/api/session-bye-options.d.ts.map | 1 + lib/api/session-bye-options.js | 1 + lib/api/session-delegate.d.ts | 74 + lib/api/session-delegate.d.ts.map | 1 + lib/api/session-delegate.js | 1 + .../session-description-handler-factory.d.ts | 16 + ...ssion-description-handler-factory.d.ts.map | 1 + .../session-description-handler-factory.js | 1 + lib/api/session-description-handler.d.ts | 75 + lib/api/session-description-handler.d.ts.map | 1 + lib/api/session-description-handler.js | 1 + lib/api/session-info-options.d.ts | 12 + lib/api/session-info-options.d.ts.map | 1 + lib/api/session-info-options.js | 1 + lib/api/session-invite-options.d.ts | 29 + lib/api/session-invite-options.d.ts.map | 1 + lib/api/session-invite-options.js | 1 + lib/api/session-message-options.d.ts | 12 + lib/api/session-message-options.d.ts.map | 1 + lib/api/session-message-options.js | 1 + lib/api/session-options.d.ts | 9 + lib/api/session-options.d.ts.map | 1 + lib/api/session-options.js | 1 + lib/api/session-refer-options.d.ts | 15 + lib/api/session-refer-options.d.ts.map | 1 + lib/api/session-refer-options.js | 1 + lib/api/session-state.d.ts | 46 + lib/api/session-state.d.ts.map | 1 + lib/api/session-state.js | 46 + lib/api/session.d.ts | 360 + lib/api/session.d.ts.map | 1 + lib/api/session.js | 1229 + lib/api/subscriber-options.d.ts | 12 + lib/api/subscriber-options.d.ts.map | 1 + lib/api/subscriber-options.js | 1 + lib/api/subscriber-subscribe-options.d.ts | 7 + lib/api/subscriber-subscribe-options.d.ts.map | 1 + lib/api/subscriber-subscribe-options.js | 1 + lib/api/subscriber.d.ts | 95 + lib/api/subscriber.d.ts.map | 1 + lib/api/subscriber.js | 427 + lib/api/subscription-delegate.d.ts | 13 + lib/api/subscription-delegate.d.ts.map | 1 + lib/api/subscription-delegate.js | 1 + lib/api/subscription-options.d.ts | 9 + lib/api/subscription-options.d.ts.map | 1 + lib/api/subscription-options.js | 1 + lib/api/subscription-state.d.ts | 20 + 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 | 1 + lib/api/subscription-unsubscribe-options.d.ts | 7 + .../subscription-unsubscribe-options.d.ts.map | 1 + lib/api/subscription-unsubscribe-options.js | 1 + lib/api/subscription.d.ts | 85 + lib/api/subscription.d.ts.map | 1 + lib/api/subscription.js | 102 + lib/api/transport-state.d.ts | 38 + lib/api/transport-state.d.ts.map | 1 + lib/api/transport-state.js | 38 + lib/api/transport.d.ts | 160 + lib/api/transport.d.ts.map | 1 + lib/api/transport.js | 1 + lib/api/user-agent-delegate.d.ts | 85 + lib/api/user-agent-delegate.d.ts.map | 1 + lib/api/user-agent-delegate.js | 1 + lib/api/user-agent-options.d.ts | 250 + lib/api/user-agent-options.d.ts.map | 1 + lib/api/user-agent-options.js | 51 + lib/api/user-agent-state.d.ts | 15 + lib/api/user-agent-state.d.ts.map | 1 + lib/api/user-agent-state.js | 15 + lib/api/user-agent.d.ts | 201 + lib/api/user-agent.d.ts.map | 1 + lib/api/user-agent.js | 862 + lib/core/dialogs/dialog-state.d.ts | 35 + lib/core/dialogs/dialog-state.d.ts.map | 1 + lib/core/dialogs/dialog-state.js | 1 + lib/core/dialogs/dialog.d.ts | 162 + lib/core/dialogs/dialog.d.ts.map | 1 + lib/core/dialogs/dialog.js | 532 + lib/core/dialogs/index.d.ts | 5 + lib/core/dialogs/index.d.ts.map | 1 + lib/core/dialogs/index.js | 4 + lib/core/dialogs/session-dialog.d.ts | 197 + lib/core/dialogs/session-dialog.d.ts.map | 1 + lib/core/dialogs/session-dialog.js | 895 + lib/core/dialogs/subscription-dialog.d.ts | 121 + lib/core/dialogs/subscription-dialog.d.ts.map | 1 + lib/core/dialogs/subscription-dialog.js | 471 + lib/core/exceptions/exception.d.ts | 9 + lib/core/exceptions/exception.d.ts.map | 1 + lib/core/exceptions/exception.js | 11 + lib/core/exceptions/index.d.ts | 4 + lib/core/exceptions/index.d.ts.map | 1 + lib/core/exceptions/index.js | 3 + .../exceptions/transaction-state-error.d.ts | 9 + .../transaction-state-error.d.ts.map | 1 + .../exceptions/transaction-state-error.js | 10 + lib/core/exceptions/transport-error.d.ts | 9 + lib/core/exceptions/transport-error.d.ts.map | 1 + lib/core/exceptions/transport-error.js | 10 + lib/core/index.d.ts | 16 + lib/core/index.d.ts.map | 1 + lib/core/index.js | 17 + lib/core/log/index.d.ts | 4 + lib/core/log/index.d.ts.map | 1 + lib/core/log/index.js | 3 + lib/core/log/levels.d.ts | 11 + lib/core/log/levels.d.ts.map | 1 + lib/core/log/levels.js | 11 + lib/core/log/logger-factory.d.ts | 22 + lib/core/log/logger-factory.d.ts.map | 1 + lib/core/log/logger-factory.js | 103 + lib/core/log/logger.d.ts | 20 + lib/core/log/logger.d.ts.map | 1 + lib/core/log/logger.js | 33 + lib/core/messages/body.d.ts | 65 + lib/core/messages/body.d.ts.map | 1 + lib/core/messages/body.js | 118 + lib/core/messages/digest-authentication.d.ts | 52 + .../messages/digest-authentication.d.ts.map | 1 + lib/core/messages/digest-authentication.js | 149 + lib/core/messages/incoming-message.d.ts | 80 + lib/core/messages/incoming-message.d.ts.map | 1 + lib/core/messages/incoming-message.js | 129 + .../messages/incoming-request-message.d.ts | 11 + .../incoming-request-message.d.ts.map | 1 + lib/core/messages/incoming-request-message.js | 10 + lib/core/messages/incoming-request.d.ts | 68 + lib/core/messages/incoming-request.d.ts.map | 1 + lib/core/messages/incoming-request.js | 1 + .../messages/incoming-response-message.d.ts | 11 + .../incoming-response-message.d.ts.map | 1 + .../messages/incoming-response-message.js | 10 + lib/core/messages/incoming-response.d.ts | 13 + lib/core/messages/incoming-response.d.ts.map | 1 + lib/core/messages/incoming-response.js | 1 + lib/core/messages/index.d.ts | 14 + lib/core/messages/index.d.ts.map | 1 + lib/core/messages/index.js | 16 + lib/core/messages/md5.d.ts | 33 + lib/core/messages/md5.d.ts.map | 1 + lib/core/messages/md5.js | 399 + lib/core/messages/methods/ack.d.ts | 19 + lib/core/messages/methods/ack.d.ts.map | 1 + lib/core/messages/methods/ack.js | 1 + lib/core/messages/methods/bye.d.ts | 22 + lib/core/messages/methods/bye.d.ts.map | 1 + lib/core/messages/methods/bye.js | 1 + lib/core/messages/methods/cancel.d.ts | 22 + lib/core/messages/methods/cancel.d.ts.map | 1 + lib/core/messages/methods/cancel.js | 1 + lib/core/messages/methods/constants.d.ts | 21 + lib/core/messages/methods/constants.d.ts.map | 1 + lib/core/messages/methods/constants.js | 22 + lib/core/messages/methods/index.d.ts | 14 + lib/core/messages/methods/index.d.ts.map | 1 + lib/core/messages/methods/index.js | 13 + lib/core/messages/methods/info.d.ts | 22 + lib/core/messages/methods/info.d.ts.map | 1 + lib/core/messages/methods/info.js | 1 + lib/core/messages/methods/invite.d.ts | 87 + lib/core/messages/methods/invite.d.ts.map | 1 + lib/core/messages/methods/invite.js | 1 + lib/core/messages/methods/message.d.ts | 22 + lib/core/messages/methods/message.d.ts.map | 1 + lib/core/messages/methods/message.js | 1 + lib/core/messages/methods/notify.d.ts | 22 + lib/core/messages/methods/notify.d.ts.map | 1 + lib/core/messages/methods/notify.js | 1 + lib/core/messages/methods/prack.d.ts | 22 + lib/core/messages/methods/prack.d.ts.map | 1 + lib/core/messages/methods/prack.js | 1 + lib/core/messages/methods/publish.d.ts | 22 + lib/core/messages/methods/publish.d.ts.map | 1 + lib/core/messages/methods/publish.js | 1 + lib/core/messages/methods/refer.d.ts | 22 + lib/core/messages/methods/refer.d.ts.map | 1 + lib/core/messages/methods/refer.js | 1 + lib/core/messages/methods/register.d.ts | 22 + lib/core/messages/methods/register.d.ts.map | 1 + lib/core/messages/methods/register.js | 1 + lib/core/messages/methods/subscribe.d.ts | 55 + lib/core/messages/methods/subscribe.d.ts.map | 1 + lib/core/messages/methods/subscribe.js | 1 + .../messages/outgoing-request-message.d.ts | 95 + .../outgoing-request-message.d.ts.map | 1 + lib/core/messages/outgoing-request-message.js | 229 + lib/core/messages/outgoing-request.d.ts | 68 + lib/core/messages/outgoing-request.d.ts.map | 1 + lib/core/messages/outgoing-request.js | 1 + lib/core/messages/outgoing-response.d.ts | 43 + lib/core/messages/outgoing-response.d.ts.map | 1 + lib/core/messages/outgoing-response.js | 126 + lib/core/messages/parser.d.ts | 15 + lib/core/messages/parser.d.ts.map | 1 + lib/core/messages/parser.js | 241 + lib/core/messages/utils.d.ts | 25 + lib/core/messages/utils.d.ts.map | 1 + lib/core/messages/utils.js | 138 + lib/core/session/index.d.ts | 3 + lib/core/session/index.d.ts.map | 1 + lib/core/session/index.js | 2 + lib/core/session/session-delegate.d.ts | 71 + lib/core/session/session-delegate.d.ts.map | 1 + lib/core/session/session-delegate.js | 1 + lib/core/session/session.d.ts | 135 + lib/core/session/session.d.ts.map | 1 + lib/core/session/session.js | 40 + lib/core/subscription/index.d.ts | 3 + lib/core/subscription/index.d.ts.map | 1 + lib/core/subscription/index.js | 2 + .../subscription/subscription-delegate.d.ts | 28 + .../subscription-delegate.d.ts.map | 1 + .../subscription/subscription-delegate.js | 1 + lib/core/subscription/subscription.d.ts | 56 + lib/core/subscription/subscription.d.ts.map | 1 + lib/core/subscription/subscription.js | 14 + lib/core/timers.d.ts | 21 + lib/core/timers.d.ts.map | 1 + lib/core/timers.js | 23 + lib/core/transactions/client-transaction.d.ts | 46 + .../transactions/client-transaction.d.ts.map | 1 + lib/core/transactions/client-transaction.js | 60 + lib/core/transactions/index.d.ts | 11 + lib/core/transactions/index.d.ts.map | 1 + lib/core/transactions/index.js | 10 + .../invite-client-transaction.d.ts | 117 + .../invite-client-transaction.d.ts.map | 1 + .../transactions/invite-client-transaction.js | 467 + .../invite-server-transaction.d.ts | 128 + .../invite-server-transaction.d.ts.map | 1 + .../transactions/invite-server-transaction.js | 376 + .../non-invite-client-transaction.d.ts | 70 + .../non-invite-client-transaction.d.ts.map | 1 + .../non-invite-client-transaction.js | 233 + .../non-invite-server-transaction.d.ts | 58 + .../non-invite-server-transaction.d.ts.map | 1 + .../non-invite-server-transaction.js | 218 + lib/core/transactions/server-transaction.d.ts | 36 + .../transactions/server-transaction.d.ts.map | 1 + lib/core/transactions/server-transaction.js | 23 + lib/core/transactions/transaction-state.d.ts | 14 + .../transactions/transaction-state.d.ts.map | 1 + lib/core/transactions/transaction-state.js | 14 + lib/core/transactions/transaction-user.d.ts | 73 + .../transactions/transaction-user.d.ts.map | 1 + lib/core/transactions/transaction-user.js | 1 + lib/core/transactions/transaction.d.ts | 80 + lib/core/transactions/transaction.d.ts.map | 1 + lib/core/transactions/transaction.js | 126 + lib/core/transport.d.ts | 32 + lib/core/transport.d.ts.map | 1 + lib/core/transport.js | 1 + 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 | 18 + 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 | 3 + .../user-agent-core-configuration.d.ts | 100 + .../user-agent-core-configuration.d.ts.map | 1 + .../user-agent-core-configuration.js | 1 + .../user-agent-core-delegate.d.ts | 38 + .../user-agent-core-delegate.d.ts.map | 1 + .../user-agent-core-delegate.js | 1 + 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 | 782 + .../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 | 14 + .../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 | 11 + .../user-agents/cancel-user-agent-client.d.ts | 11 + .../cancel-user-agent-client.d.ts.map | 1 + .../user-agents/cancel-user-agent-client.js | 11 + lib/core/user-agents/index.d.ts | 27 + lib/core/user-agents/index.d.ts.map | 1 + lib/core/user-agents/index.js | 26 + .../user-agents/info-user-agent-client.d.ts | 11 + .../info-user-agent-client.d.ts.map | 1 + .../user-agents/info-user-agent-client.js | 13 + .../user-agents/info-user-agent-server.d.ts | 11 + .../info-user-agent-server.d.ts.map | 1 + .../user-agents/info-user-agent-server.js | 11 + .../user-agents/invite-user-agent-client.d.ts | 36 + .../invite-user-agent-client.d.ts.map | 1 + .../user-agents/invite-user-agent-client.js | 362 + .../user-agents/invite-user-agent-server.d.ts | 78 + .../invite-user-agent-server.d.ts.map | 1 + .../user-agents/invite-user-agent-server.js | 232 + .../message-user-agent-client.d.ts | 11 + .../message-user-agent-client.d.ts.map | 1 + .../user-agents/message-user-agent-client.js | 11 + .../message-user-agent-server.d.ts | 11 + .../message-user-agent-server.d.ts.map | 1 + .../user-agents/message-user-agent-server.js | 11 + .../user-agents/notify-user-agent-client.d.ts | 11 + .../notify-user-agent-client.d.ts.map | 1 + .../user-agents/notify-user-agent-client.js | 13 + .../user-agents/notify-user-agent-server.d.ts | 17 + .../notify-user-agent-server.d.ts.map | 1 + .../user-agents/notify-user-agent-server.js | 21 + .../user-agents/prack-user-agent-client.d.ts | 11 + .../prack-user-agent-client.d.ts.map | 1 + .../user-agents/prack-user-agent-client.js | 14 + .../user-agents/prack-user-agent-server.d.ts | 17 + .../prack-user-agent-server.d.ts.map | 1 + .../user-agents/prack-user-agent-server.js | 25 + .../publish-user-agent-client.d.ts | 11 + .../publish-user-agent-client.d.ts.map | 1 + .../user-agents/publish-user-agent-client.js | 11 + .../re-invite-user-agent-client.d.ts | 19 + .../re-invite-user-agent-client.d.ts.map | 1 + .../re-invite-user-agent-client.js | 108 + .../re-invite-user-agent-server.d.ts | 42 + .../re-invite-user-agent-server.d.ts.map | 1 + .../re-invite-user-agent-server.js | 86 + .../re-subscribe-user-agent-client.d.ts | 18 + .../re-subscribe-user-agent-client.d.ts.map | 1 + .../re-subscribe-user-agent-client.js | 65 + .../re-subscribe-user-agent-server.d.ts | 11 + .../re-subscribe-user-agent-server.d.ts.map | 1 + .../re-subscribe-user-agent-server.js | 11 + .../user-agents/refer-user-agent-client.d.ts | 11 + .../refer-user-agent-client.d.ts.map | 1 + .../user-agents/refer-user-agent-client.js | 13 + .../user-agents/refer-user-agent-server.d.ts | 17 + .../refer-user-agent-server.d.ts.map | 1 + .../user-agents/refer-user-agent-server.js | 21 + .../register-user-agent-client.d.ts | 11 + .../register-user-agent-client.d.ts.map | 1 + .../user-agents/register-user-agent-client.js | 11 + .../register-user-agent-server.d.ts | 12 + .../register-user-agent-server.d.ts.map | 1 + .../user-agents/register-user-agent-server.js | 12 + .../subscribe-user-agent-client.d.ts | 66 + .../subscribe-user-agent-client.d.ts.map | 1 + .../subscribe-user-agent-client.js | 287 + .../subscribe-user-agent-server.d.ts | 12 + .../subscribe-user-agent-server.d.ts.map | 1 + .../subscribe-user-agent-server.js | 12 + lib/core/user-agents/user-agent-client.d.ts | 104 + .../user-agents/user-agent-client.d.ts.map | 1 + lib/core/user-agents/user-agent-client.js | 309 + 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 | 222 + lib/grammar/grammar.d.ts | 27 + lib/grammar/grammar.d.ts.map | 1 + lib/grammar/grammar.js | 50 + lib/grammar/index.d.ts | 5 + lib/grammar/index.d.ts.map | 1 + lib/grammar/index.js | 4 + lib/grammar/name-addr-header.d.ts | 25 + lib/grammar/name-addr-header.d.ts.map | 1 + lib/grammar/name-addr-header.js | 42 + lib/grammar/parameters.d.ts | 17 + lib/grammar/parameters.d.ts.map | 1 + lib/grammar/parameters.js | 39 + lib/grammar/pegjs/dist/grammar.d.ts | 51 + lib/grammar/pegjs/dist/grammar.d.ts.map | 1 + lib/grammar/pegjs/dist/grammar.js | 1475 ++ lib/grammar/uri.d.ts | 45 + lib/grammar/uri.d.ts.map | 1 + lib/grammar/uri.js | 188 + lib/index.d.ts | 10 + lib/index.d.ts.map | 1 + lib/index.js | 15 + lib/platform/web/index.d.ts | 5 + lib/platform/web/index.d.ts.map | 1 + lib/platform/web/index.js | 4 + lib/platform/web/modifiers/index.d.ts | 6 + lib/platform/web/modifiers/index.d.ts.map | 1 + lib/platform/web/modifiers/index.js | 5 + lib/platform/web/modifiers/modifiers.d.ts | 42 + lib/platform/web/modifiers/modifiers.d.ts.map | 1 + lib/platform/web/modifiers/modifiers.js | 163 + .../session-description-handler/index.d.ts | 15 + .../index.d.ts.map | 1 + .../web/session-description-handler/index.js | 14 + .../media-stream-factory-default.d.ts | 7 + .../media-stream-factory-default.d.ts.map | 1 + .../media-stream-factory-default.js | 20 + .../media-stream-factory.d.ts | 7 + .../media-stream-factory.d.ts.map | 1 + .../media-stream-factory.js | 1 + ...peer-connection-configuration-default.d.ts | 6 + ...-connection-configuration-default.d.ts.map | 1 + .../peer-connection-configuration-default.js | 16 + .../peer-connection-delegate.d.ts | 64 + .../peer-connection-delegate.d.ts.map | 1 + .../peer-connection-delegate.js | 1 + ...ion-description-handler-configuration.d.ts | 17 + ...description-handler-configuration.d.ts.map | 1 + ...ssion-description-handler-configuration.js | 1 + ...n-description-handler-factory-default.d.ts | 12 + ...scription-handler-factory-default.d.ts.map | 1 + ...ion-description-handler-factory-default.js | 28 + ...n-description-handler-factory-options.d.ts | 10 + ...scription-handler-factory-options.d.ts.map | 1 + ...ion-description-handler-factory-options.js | 1 + .../session-description-handler-factory.d.ts | 17 + ...ssion-description-handler-factory.d.ts.map | 1 + .../session-description-handler-factory.js | 1 + .../session-description-handler-options.d.ts | 44 + ...ssion-description-handler-options.d.ts.map | 1 + .../session-description-handler-options.js | 1 + .../session-description-handler.d.ts | 208 + .../session-description-handler.d.ts.map | 1 + .../session-description-handler.js | 661 + lib/platform/web/simple-user/index.d.ts | 8 + lib/platform/web/simple-user/index.d.ts.map | 1 + lib/platform/web/simple-user/index.js | 7 + .../web/simple-user/simple-user-delegate.d.ts | 73 + .../simple-user/simple-user-delegate.d.ts.map | 1 + .../web/simple-user/simple-user-delegate.js | 1 + .../web/simple-user/simple-user-options.d.ts | 91 + .../simple-user/simple-user-options.d.ts.map | 1 + .../web/simple-user/simple-user-options.js | 1 + lib/platform/web/simple-user/simple-user.d.ts | 224 + .../web/simple-user/simple-user.d.ts.map | 1 + lib/platform/web/simple-user/simple-user.js | 925 + lib/platform/web/transport/index.d.ts | 7 + lib/platform/web/transport/index.d.ts.map | 1 + lib/platform/web/transport/index.js | 6 + .../web/transport/transport-options.d.ts | 31 + .../web/transport/transport-options.d.ts.map | 1 + .../web/transport/transport-options.js | 1 + lib/platform/web/transport/transport.d.ts | 126 + lib/platform/web/transport/transport.d.ts.map | 1 + lib/platform/web/transport/transport.js | 648 + lib/version.d.ts | 2 + lib/version.d.ts.map | 1 + lib/version.js | 1 + 553 files changed, 68162 insertions(+) create mode 100644 dist/sip-0.18.0.js create mode 100644 dist/sip-0.18.0.min.js create mode 100644 dist/sip.js create mode 100644 dist/sip.min.js create mode 100644 lib/api/bye.d.ts create mode 100644 lib/api/bye.d.ts.map create mode 100644 lib/api/bye.js create mode 100644 lib/api/dtmf.d.ts create mode 100644 lib/api/dtmf.d.ts.map create mode 100644 lib/api/dtmf.js create mode 100644 lib/api/emitter.d.ts create mode 100644 lib/api/emitter.d.ts.map create mode 100644 lib/api/emitter.js create mode 100644 lib/api/exceptions/content-type-unsupported.d.ts create mode 100644 lib/api/exceptions/content-type-unsupported.d.ts.map create mode 100644 lib/api/exceptions/content-type-unsupported.js create mode 100644 lib/api/exceptions/index.d.ts create mode 100644 lib/api/exceptions/index.d.ts.map create mode 100644 lib/api/exceptions/index.js create mode 100644 lib/api/exceptions/request-pending.d.ts create mode 100644 lib/api/exceptions/request-pending.d.ts.map create mode 100644 lib/api/exceptions/request-pending.js create mode 100644 lib/api/exceptions/session-description-handler.d.ts create mode 100644 lib/api/exceptions/session-description-handler.d.ts.map create mode 100644 lib/api/exceptions/session-description-handler.js create mode 100644 lib/api/exceptions/session-terminated.d.ts create mode 100644 lib/api/exceptions/session-terminated.d.ts.map create mode 100644 lib/api/exceptions/session-terminated.js create mode 100644 lib/api/exceptions/state-transition.d.ts create mode 100644 lib/api/exceptions/state-transition.d.ts.map create mode 100644 lib/api/exceptions/state-transition.js create mode 100644 lib/api/index.d.ts create mode 100644 lib/api/index.d.ts.map create mode 100644 lib/api/index.js create mode 100644 lib/api/info.d.ts create mode 100644 lib/api/info.d.ts.map create mode 100644 lib/api/info.js create mode 100644 lib/api/invitation-accept-options.d.ts create mode 100644 lib/api/invitation-accept-options.d.ts.map create mode 100644 lib/api/invitation-accept-options.js create mode 100644 lib/api/invitation-progress-options.d.ts create mode 100644 lib/api/invitation-progress-options.d.ts.map create mode 100644 lib/api/invitation-progress-options.js create mode 100644 lib/api/invitation-reject-options.d.ts create mode 100644 lib/api/invitation-reject-options.d.ts.map create mode 100644 lib/api/invitation-reject-options.js create mode 100644 lib/api/invitation.d.ts create mode 100644 lib/api/invitation.d.ts.map create mode 100644 lib/api/invitation.js create mode 100644 lib/api/inviter-cancel-options.d.ts create mode 100644 lib/api/inviter-cancel-options.d.ts.map create mode 100644 lib/api/inviter-cancel-options.js create mode 100644 lib/api/inviter-invite-options.d.ts create mode 100644 lib/api/inviter-invite-options.d.ts.map create mode 100644 lib/api/inviter-invite-options.js create mode 100644 lib/api/inviter-options.d.ts create mode 100644 lib/api/inviter-options.d.ts.map create mode 100644 lib/api/inviter-options.js create mode 100644 lib/api/inviter.d.ts create mode 100644 lib/api/inviter.d.ts.map create mode 100644 lib/api/inviter.js create mode 100644 lib/api/message.d.ts create mode 100644 lib/api/message.d.ts.map create mode 100644 lib/api/message.js create mode 100644 lib/api/messager-message-options.d.ts create mode 100644 lib/api/messager-message-options.d.ts.map create mode 100644 lib/api/messager-message-options.js create mode 100644 lib/api/messager-options.d.ts create mode 100644 lib/api/messager-options.d.ts.map create mode 100644 lib/api/messager-options.js create mode 100644 lib/api/messager.d.ts create mode 100644 lib/api/messager.d.ts.map create mode 100644 lib/api/messager.js create mode 100644 lib/api/notification.d.ts create mode 100644 lib/api/notification.d.ts.map create mode 100644 lib/api/notification.js create mode 100644 lib/api/notifier.d.ts create mode 100644 lib/api/notifier.d.ts.map create mode 100644 lib/api/notifier.js create mode 100644 lib/api/publisher-options.d.ts create mode 100644 lib/api/publisher-options.d.ts.map create mode 100644 lib/api/publisher-options.js create mode 100644 lib/api/publisher-publish-options.d.ts create mode 100644 lib/api/publisher-publish-options.d.ts.map create mode 100644 lib/api/publisher-publish-options.js create mode 100644 lib/api/publisher-state.d.ts create mode 100644 lib/api/publisher-state.d.ts.map create mode 100644 lib/api/publisher-state.js create mode 100644 lib/api/publisher-unpublish-options.d.ts create mode 100644 lib/api/publisher-unpublish-options.d.ts.map create mode 100644 lib/api/publisher-unpublish-options.js create mode 100644 lib/api/publisher.d.ts create mode 100644 lib/api/publisher.d.ts.map create mode 100644 lib/api/publisher.js create mode 100644 lib/api/referral.d.ts create mode 100644 lib/api/referral.d.ts.map create mode 100644 lib/api/referral.js create mode 100644 lib/api/registerer-options.d.ts create mode 100644 lib/api/registerer-options.d.ts.map create mode 100644 lib/api/registerer-options.js create mode 100644 lib/api/registerer-register-options.d.ts create mode 100644 lib/api/registerer-register-options.d.ts.map create mode 100644 lib/api/registerer-register-options.js create mode 100644 lib/api/registerer-state.d.ts create mode 100644 lib/api/registerer-state.d.ts.map create mode 100644 lib/api/registerer-state.js create mode 100644 lib/api/registerer-unregister-options.d.ts create mode 100644 lib/api/registerer-unregister-options.d.ts.map create mode 100644 lib/api/registerer-unregister-options.js create mode 100644 lib/api/registerer.d.ts create mode 100644 lib/api/registerer.d.ts.map create mode 100644 lib/api/registerer.js create mode 100644 lib/api/session-bye-options.d.ts create mode 100644 lib/api/session-bye-options.d.ts.map create mode 100644 lib/api/session-bye-options.js create mode 100644 lib/api/session-delegate.d.ts create mode 100644 lib/api/session-delegate.d.ts.map create mode 100644 lib/api/session-delegate.js create mode 100644 lib/api/session-description-handler-factory.d.ts create mode 100644 lib/api/session-description-handler-factory.d.ts.map create mode 100644 lib/api/session-description-handler-factory.js create mode 100644 lib/api/session-description-handler.d.ts create mode 100644 lib/api/session-description-handler.d.ts.map create mode 100644 lib/api/session-description-handler.js create mode 100644 lib/api/session-info-options.d.ts create mode 100644 lib/api/session-info-options.d.ts.map create mode 100644 lib/api/session-info-options.js create mode 100644 lib/api/session-invite-options.d.ts create mode 100644 lib/api/session-invite-options.d.ts.map create mode 100644 lib/api/session-invite-options.js create mode 100644 lib/api/session-message-options.d.ts create mode 100644 lib/api/session-message-options.d.ts.map create mode 100644 lib/api/session-message-options.js create mode 100644 lib/api/session-options.d.ts create mode 100644 lib/api/session-options.d.ts.map create mode 100644 lib/api/session-options.js create mode 100644 lib/api/session-refer-options.d.ts create mode 100644 lib/api/session-refer-options.d.ts.map create mode 100644 lib/api/session-refer-options.js create mode 100644 lib/api/session-state.d.ts create mode 100644 lib/api/session-state.d.ts.map create mode 100644 lib/api/session-state.js create mode 100644 lib/api/session.d.ts create mode 100644 lib/api/session.d.ts.map create mode 100644 lib/api/session.js create mode 100644 lib/api/subscriber-options.d.ts create mode 100644 lib/api/subscriber-options.d.ts.map create mode 100644 lib/api/subscriber-options.js create mode 100644 lib/api/subscriber-subscribe-options.d.ts create mode 100644 lib/api/subscriber-subscribe-options.d.ts.map create mode 100644 lib/api/subscriber-subscribe-options.js create mode 100644 lib/api/subscriber.d.ts create mode 100644 lib/api/subscriber.d.ts.map create mode 100644 lib/api/subscriber.js create mode 100644 lib/api/subscription-delegate.d.ts create mode 100644 lib/api/subscription-delegate.d.ts.map create mode 100644 lib/api/subscription-delegate.js create mode 100644 lib/api/subscription-options.d.ts create mode 100644 lib/api/subscription-options.d.ts.map create mode 100644 lib/api/subscription-options.js create mode 100644 lib/api/subscription-state.d.ts create mode 100644 lib/api/subscription-state.d.ts.map create mode 100644 lib/api/subscription-state.js create mode 100644 lib/api/subscription-subscribe-options.d.ts create mode 100644 lib/api/subscription-subscribe-options.d.ts.map create mode 100644 lib/api/subscription-subscribe-options.js create mode 100644 lib/api/subscription-unsubscribe-options.d.ts create mode 100644 lib/api/subscription-unsubscribe-options.d.ts.map create mode 100644 lib/api/subscription-unsubscribe-options.js create mode 100644 lib/api/subscription.d.ts create mode 100644 lib/api/subscription.d.ts.map create mode 100644 lib/api/subscription.js create mode 100644 lib/api/transport-state.d.ts create mode 100644 lib/api/transport-state.d.ts.map create mode 100644 lib/api/transport-state.js create mode 100644 lib/api/transport.d.ts create mode 100644 lib/api/transport.d.ts.map create mode 100644 lib/api/transport.js create mode 100644 lib/api/user-agent-delegate.d.ts create mode 100644 lib/api/user-agent-delegate.d.ts.map create mode 100644 lib/api/user-agent-delegate.js create mode 100644 lib/api/user-agent-options.d.ts create mode 100644 lib/api/user-agent-options.d.ts.map create mode 100644 lib/api/user-agent-options.js create mode 100644 lib/api/user-agent-state.d.ts create mode 100644 lib/api/user-agent-state.d.ts.map create mode 100644 lib/api/user-agent-state.js create mode 100644 lib/api/user-agent.d.ts create mode 100644 lib/api/user-agent.d.ts.map create mode 100644 lib/api/user-agent.js create mode 100644 lib/core/dialogs/dialog-state.d.ts create mode 100644 lib/core/dialogs/dialog-state.d.ts.map create mode 100644 lib/core/dialogs/dialog-state.js create mode 100644 lib/core/dialogs/dialog.d.ts create mode 100644 lib/core/dialogs/dialog.d.ts.map create mode 100644 lib/core/dialogs/dialog.js create mode 100644 lib/core/dialogs/index.d.ts create mode 100644 lib/core/dialogs/index.d.ts.map create mode 100644 lib/core/dialogs/index.js create mode 100644 lib/core/dialogs/session-dialog.d.ts create mode 100644 lib/core/dialogs/session-dialog.d.ts.map create mode 100644 lib/core/dialogs/session-dialog.js create mode 100644 lib/core/dialogs/subscription-dialog.d.ts create mode 100644 lib/core/dialogs/subscription-dialog.d.ts.map create mode 100644 lib/core/dialogs/subscription-dialog.js create mode 100644 lib/core/exceptions/exception.d.ts create mode 100644 lib/core/exceptions/exception.d.ts.map create mode 100644 lib/core/exceptions/exception.js create mode 100644 lib/core/exceptions/index.d.ts create mode 100644 lib/core/exceptions/index.d.ts.map create mode 100644 lib/core/exceptions/index.js create mode 100644 lib/core/exceptions/transaction-state-error.d.ts create mode 100644 lib/core/exceptions/transaction-state-error.d.ts.map create mode 100644 lib/core/exceptions/transaction-state-error.js create mode 100644 lib/core/exceptions/transport-error.d.ts create mode 100644 lib/core/exceptions/transport-error.d.ts.map create mode 100644 lib/core/exceptions/transport-error.js create mode 100644 lib/core/index.d.ts create mode 100644 lib/core/index.d.ts.map create mode 100644 lib/core/index.js create mode 100644 lib/core/log/index.d.ts create mode 100644 lib/core/log/index.d.ts.map create mode 100644 lib/core/log/index.js create mode 100644 lib/core/log/levels.d.ts create mode 100644 lib/core/log/levels.d.ts.map create mode 100644 lib/core/log/levels.js create mode 100644 lib/core/log/logger-factory.d.ts create mode 100644 lib/core/log/logger-factory.d.ts.map create mode 100644 lib/core/log/logger-factory.js create mode 100644 lib/core/log/logger.d.ts create mode 100644 lib/core/log/logger.d.ts.map create mode 100644 lib/core/log/logger.js create mode 100644 lib/core/messages/body.d.ts create mode 100644 lib/core/messages/body.d.ts.map create mode 100644 lib/core/messages/body.js create mode 100644 lib/core/messages/digest-authentication.d.ts create mode 100644 lib/core/messages/digest-authentication.d.ts.map create mode 100644 lib/core/messages/digest-authentication.js create mode 100644 lib/core/messages/incoming-message.d.ts create mode 100644 lib/core/messages/incoming-message.d.ts.map create mode 100644 lib/core/messages/incoming-message.js create mode 100644 lib/core/messages/incoming-request-message.d.ts create mode 100644 lib/core/messages/incoming-request-message.d.ts.map create mode 100644 lib/core/messages/incoming-request-message.js create mode 100644 lib/core/messages/incoming-request.d.ts create mode 100644 lib/core/messages/incoming-request.d.ts.map create mode 100644 lib/core/messages/incoming-request.js create mode 100644 lib/core/messages/incoming-response-message.d.ts create mode 100644 lib/core/messages/incoming-response-message.d.ts.map create mode 100644 lib/core/messages/incoming-response-message.js create mode 100644 lib/core/messages/incoming-response.d.ts create mode 100644 lib/core/messages/incoming-response.d.ts.map create mode 100644 lib/core/messages/incoming-response.js create mode 100644 lib/core/messages/index.d.ts create mode 100644 lib/core/messages/index.d.ts.map create mode 100644 lib/core/messages/index.js create mode 100644 lib/core/messages/md5.d.ts create mode 100644 lib/core/messages/md5.d.ts.map create mode 100644 lib/core/messages/md5.js create mode 100644 lib/core/messages/methods/ack.d.ts create mode 100644 lib/core/messages/methods/ack.d.ts.map create mode 100644 lib/core/messages/methods/ack.js create mode 100644 lib/core/messages/methods/bye.d.ts create mode 100644 lib/core/messages/methods/bye.d.ts.map create mode 100644 lib/core/messages/methods/bye.js create mode 100644 lib/core/messages/methods/cancel.d.ts create mode 100644 lib/core/messages/methods/cancel.d.ts.map create mode 100644 lib/core/messages/methods/cancel.js create mode 100644 lib/core/messages/methods/constants.d.ts create mode 100644 lib/core/messages/methods/constants.d.ts.map create mode 100644 lib/core/messages/methods/constants.js create mode 100644 lib/core/messages/methods/index.d.ts create mode 100644 lib/core/messages/methods/index.d.ts.map create mode 100644 lib/core/messages/methods/index.js create mode 100644 lib/core/messages/methods/info.d.ts create mode 100644 lib/core/messages/methods/info.d.ts.map create mode 100644 lib/core/messages/methods/info.js create mode 100644 lib/core/messages/methods/invite.d.ts create mode 100644 lib/core/messages/methods/invite.d.ts.map create mode 100644 lib/core/messages/methods/invite.js create mode 100644 lib/core/messages/methods/message.d.ts create mode 100644 lib/core/messages/methods/message.d.ts.map create mode 100644 lib/core/messages/methods/message.js create mode 100644 lib/core/messages/methods/notify.d.ts create mode 100644 lib/core/messages/methods/notify.d.ts.map create mode 100644 lib/core/messages/methods/notify.js create mode 100644 lib/core/messages/methods/prack.d.ts create mode 100644 lib/core/messages/methods/prack.d.ts.map create mode 100644 lib/core/messages/methods/prack.js create mode 100644 lib/core/messages/methods/publish.d.ts create mode 100644 lib/core/messages/methods/publish.d.ts.map create mode 100644 lib/core/messages/methods/publish.js create mode 100644 lib/core/messages/methods/refer.d.ts create mode 100644 lib/core/messages/methods/refer.d.ts.map create mode 100644 lib/core/messages/methods/refer.js create mode 100644 lib/core/messages/methods/register.d.ts create mode 100644 lib/core/messages/methods/register.d.ts.map create mode 100644 lib/core/messages/methods/register.js create mode 100644 lib/core/messages/methods/subscribe.d.ts create mode 100644 lib/core/messages/methods/subscribe.d.ts.map create mode 100644 lib/core/messages/methods/subscribe.js create mode 100644 lib/core/messages/outgoing-request-message.d.ts create mode 100644 lib/core/messages/outgoing-request-message.d.ts.map create mode 100644 lib/core/messages/outgoing-request-message.js create mode 100644 lib/core/messages/outgoing-request.d.ts create mode 100644 lib/core/messages/outgoing-request.d.ts.map create mode 100644 lib/core/messages/outgoing-request.js create mode 100644 lib/core/messages/outgoing-response.d.ts create mode 100644 lib/core/messages/outgoing-response.d.ts.map create mode 100644 lib/core/messages/outgoing-response.js create mode 100644 lib/core/messages/parser.d.ts create mode 100644 lib/core/messages/parser.d.ts.map create mode 100644 lib/core/messages/parser.js create mode 100644 lib/core/messages/utils.d.ts create mode 100644 lib/core/messages/utils.d.ts.map create mode 100644 lib/core/messages/utils.js create mode 100644 lib/core/session/index.d.ts create mode 100644 lib/core/session/index.d.ts.map create mode 100644 lib/core/session/index.js create mode 100644 lib/core/session/session-delegate.d.ts create mode 100644 lib/core/session/session-delegate.d.ts.map create mode 100644 lib/core/session/session-delegate.js create mode 100644 lib/core/session/session.d.ts create mode 100644 lib/core/session/session.d.ts.map create mode 100644 lib/core/session/session.js create mode 100644 lib/core/subscription/index.d.ts create mode 100644 lib/core/subscription/index.d.ts.map create mode 100644 lib/core/subscription/index.js create mode 100644 lib/core/subscription/subscription-delegate.d.ts create mode 100644 lib/core/subscription/subscription-delegate.d.ts.map create mode 100644 lib/core/subscription/subscription-delegate.js create mode 100644 lib/core/subscription/subscription.d.ts create mode 100644 lib/core/subscription/subscription.d.ts.map create mode 100644 lib/core/subscription/subscription.js create mode 100644 lib/core/timers.d.ts create mode 100644 lib/core/timers.d.ts.map create mode 100644 lib/core/timers.js create mode 100644 lib/core/transactions/client-transaction.d.ts create mode 100644 lib/core/transactions/client-transaction.d.ts.map create mode 100644 lib/core/transactions/client-transaction.js create mode 100644 lib/core/transactions/index.d.ts create mode 100644 lib/core/transactions/index.d.ts.map create mode 100644 lib/core/transactions/index.js create mode 100644 lib/core/transactions/invite-client-transaction.d.ts create mode 100644 lib/core/transactions/invite-client-transaction.d.ts.map create mode 100644 lib/core/transactions/invite-client-transaction.js create mode 100644 lib/core/transactions/invite-server-transaction.d.ts create mode 100644 lib/core/transactions/invite-server-transaction.d.ts.map create mode 100644 lib/core/transactions/invite-server-transaction.js create mode 100644 lib/core/transactions/non-invite-client-transaction.d.ts create mode 100644 lib/core/transactions/non-invite-client-transaction.d.ts.map create mode 100644 lib/core/transactions/non-invite-client-transaction.js create mode 100644 lib/core/transactions/non-invite-server-transaction.d.ts create mode 100644 lib/core/transactions/non-invite-server-transaction.d.ts.map create mode 100644 lib/core/transactions/non-invite-server-transaction.js create mode 100644 lib/core/transactions/server-transaction.d.ts create mode 100644 lib/core/transactions/server-transaction.d.ts.map create mode 100644 lib/core/transactions/server-transaction.js create mode 100644 lib/core/transactions/transaction-state.d.ts create mode 100644 lib/core/transactions/transaction-state.d.ts.map create mode 100644 lib/core/transactions/transaction-state.js create mode 100644 lib/core/transactions/transaction-user.d.ts create mode 100644 lib/core/transactions/transaction-user.d.ts.map create mode 100644 lib/core/transactions/transaction-user.js create mode 100644 lib/core/transactions/transaction.d.ts create mode 100644 lib/core/transactions/transaction.d.ts.map create mode 100644 lib/core/transactions/transaction.js create mode 100644 lib/core/transport.d.ts create mode 100644 lib/core/transport.d.ts.map create mode 100644 lib/core/transport.js create mode 100644 lib/core/user-agent-core/allowed-methods.d.ts create mode 100644 lib/core/user-agent-core/allowed-methods.d.ts.map create mode 100644 lib/core/user-agent-core/allowed-methods.js create mode 100644 lib/core/user-agent-core/index.d.ts create mode 100644 lib/core/user-agent-core/index.d.ts.map create mode 100644 lib/core/user-agent-core/index.js create mode 100644 lib/core/user-agent-core/user-agent-core-configuration.d.ts create mode 100644 lib/core/user-agent-core/user-agent-core-configuration.d.ts.map create mode 100644 lib/core/user-agent-core/user-agent-core-configuration.js create mode 100644 lib/core/user-agent-core/user-agent-core-delegate.d.ts create mode 100644 lib/core/user-agent-core/user-agent-core-delegate.d.ts.map create mode 100644 lib/core/user-agent-core/user-agent-core-delegate.js create mode 100644 lib/core/user-agent-core/user-agent-core.d.ts create mode 100644 lib/core/user-agent-core/user-agent-core.d.ts.map create mode 100644 lib/core/user-agent-core/user-agent-core.js create mode 100644 lib/core/user-agents/bye-user-agent-client.d.ts create mode 100644 lib/core/user-agents/bye-user-agent-client.d.ts.map create mode 100644 lib/core/user-agents/bye-user-agent-client.js create mode 100644 lib/core/user-agents/bye-user-agent-server.d.ts create mode 100644 lib/core/user-agents/bye-user-agent-server.d.ts.map create mode 100644 lib/core/user-agents/bye-user-agent-server.js create mode 100644 lib/core/user-agents/cancel-user-agent-client.d.ts create mode 100644 lib/core/user-agents/cancel-user-agent-client.d.ts.map create mode 100644 lib/core/user-agents/cancel-user-agent-client.js create mode 100644 lib/core/user-agents/index.d.ts create mode 100644 lib/core/user-agents/index.d.ts.map create mode 100644 lib/core/user-agents/index.js create mode 100644 lib/core/user-agents/info-user-agent-client.d.ts create mode 100644 lib/core/user-agents/info-user-agent-client.d.ts.map create mode 100644 lib/core/user-agents/info-user-agent-client.js create mode 100644 lib/core/user-agents/info-user-agent-server.d.ts create mode 100644 lib/core/user-agents/info-user-agent-server.d.ts.map create mode 100644 lib/core/user-agents/info-user-agent-server.js create mode 100644 lib/core/user-agents/invite-user-agent-client.d.ts create mode 100644 lib/core/user-agents/invite-user-agent-client.d.ts.map create mode 100644 lib/core/user-agents/invite-user-agent-client.js create mode 100644 lib/core/user-agents/invite-user-agent-server.d.ts create mode 100644 lib/core/user-agents/invite-user-agent-server.d.ts.map create mode 100644 lib/core/user-agents/invite-user-agent-server.js create mode 100644 lib/core/user-agents/message-user-agent-client.d.ts create mode 100644 lib/core/user-agents/message-user-agent-client.d.ts.map create mode 100644 lib/core/user-agents/message-user-agent-client.js create mode 100644 lib/core/user-agents/message-user-agent-server.d.ts create mode 100644 lib/core/user-agents/message-user-agent-server.d.ts.map create mode 100644 lib/core/user-agents/message-user-agent-server.js create mode 100644 lib/core/user-agents/notify-user-agent-client.d.ts create mode 100644 lib/core/user-agents/notify-user-agent-client.d.ts.map create mode 100644 lib/core/user-agents/notify-user-agent-client.js create mode 100644 lib/core/user-agents/notify-user-agent-server.d.ts create mode 100644 lib/core/user-agents/notify-user-agent-server.d.ts.map create mode 100644 lib/core/user-agents/notify-user-agent-server.js create mode 100644 lib/core/user-agents/prack-user-agent-client.d.ts create mode 100644 lib/core/user-agents/prack-user-agent-client.d.ts.map create mode 100644 lib/core/user-agents/prack-user-agent-client.js create mode 100644 lib/core/user-agents/prack-user-agent-server.d.ts create mode 100644 lib/core/user-agents/prack-user-agent-server.d.ts.map create mode 100644 lib/core/user-agents/prack-user-agent-server.js create mode 100644 lib/core/user-agents/publish-user-agent-client.d.ts create mode 100644 lib/core/user-agents/publish-user-agent-client.d.ts.map create mode 100644 lib/core/user-agents/publish-user-agent-client.js create mode 100644 lib/core/user-agents/re-invite-user-agent-client.d.ts create mode 100644 lib/core/user-agents/re-invite-user-agent-client.d.ts.map create mode 100644 lib/core/user-agents/re-invite-user-agent-client.js create mode 100644 lib/core/user-agents/re-invite-user-agent-server.d.ts create mode 100644 lib/core/user-agents/re-invite-user-agent-server.d.ts.map create mode 100644 lib/core/user-agents/re-invite-user-agent-server.js create mode 100644 lib/core/user-agents/re-subscribe-user-agent-client.d.ts create mode 100644 lib/core/user-agents/re-subscribe-user-agent-client.d.ts.map create mode 100644 lib/core/user-agents/re-subscribe-user-agent-client.js create mode 100644 lib/core/user-agents/re-subscribe-user-agent-server.d.ts create mode 100644 lib/core/user-agents/re-subscribe-user-agent-server.d.ts.map create mode 100644 lib/core/user-agents/re-subscribe-user-agent-server.js create mode 100644 lib/core/user-agents/refer-user-agent-client.d.ts create mode 100644 lib/core/user-agents/refer-user-agent-client.d.ts.map create mode 100644 lib/core/user-agents/refer-user-agent-client.js create mode 100644 lib/core/user-agents/refer-user-agent-server.d.ts create mode 100644 lib/core/user-agents/refer-user-agent-server.d.ts.map create mode 100644 lib/core/user-agents/refer-user-agent-server.js create mode 100644 lib/core/user-agents/register-user-agent-client.d.ts create mode 100644 lib/core/user-agents/register-user-agent-client.d.ts.map create mode 100644 lib/core/user-agents/register-user-agent-client.js create mode 100644 lib/core/user-agents/register-user-agent-server.d.ts create mode 100644 lib/core/user-agents/register-user-agent-server.d.ts.map create mode 100644 lib/core/user-agents/register-user-agent-server.js create mode 100644 lib/core/user-agents/subscribe-user-agent-client.d.ts create mode 100644 lib/core/user-agents/subscribe-user-agent-client.d.ts.map create mode 100644 lib/core/user-agents/subscribe-user-agent-client.js create mode 100644 lib/core/user-agents/subscribe-user-agent-server.d.ts create mode 100644 lib/core/user-agents/subscribe-user-agent-server.d.ts.map create mode 100644 lib/core/user-agents/subscribe-user-agent-server.js create mode 100644 lib/core/user-agents/user-agent-client.d.ts create mode 100644 lib/core/user-agents/user-agent-client.d.ts.map create mode 100644 lib/core/user-agents/user-agent-client.js create mode 100644 lib/core/user-agents/user-agent-server.d.ts create mode 100644 lib/core/user-agents/user-agent-server.d.ts.map create mode 100644 lib/core/user-agents/user-agent-server.js create mode 100644 lib/grammar/grammar.d.ts create mode 100644 lib/grammar/grammar.d.ts.map create mode 100644 lib/grammar/grammar.js create mode 100644 lib/grammar/index.d.ts create mode 100644 lib/grammar/index.d.ts.map create mode 100644 lib/grammar/index.js create mode 100644 lib/grammar/name-addr-header.d.ts create mode 100644 lib/grammar/name-addr-header.d.ts.map create mode 100644 lib/grammar/name-addr-header.js create mode 100644 lib/grammar/parameters.d.ts create mode 100644 lib/grammar/parameters.d.ts.map create mode 100644 lib/grammar/parameters.js create mode 100644 lib/grammar/pegjs/dist/grammar.d.ts create mode 100644 lib/grammar/pegjs/dist/grammar.d.ts.map create mode 100644 lib/grammar/pegjs/dist/grammar.js create mode 100644 lib/grammar/uri.d.ts create mode 100644 lib/grammar/uri.d.ts.map create mode 100644 lib/grammar/uri.js create mode 100644 lib/index.d.ts create mode 100644 lib/index.d.ts.map create mode 100644 lib/index.js create mode 100644 lib/platform/web/index.d.ts create mode 100644 lib/platform/web/index.d.ts.map create mode 100644 lib/platform/web/index.js create mode 100644 lib/platform/web/modifiers/index.d.ts create mode 100644 lib/platform/web/modifiers/index.d.ts.map create mode 100644 lib/platform/web/modifiers/index.js create mode 100644 lib/platform/web/modifiers/modifiers.d.ts create mode 100644 lib/platform/web/modifiers/modifiers.d.ts.map create mode 100644 lib/platform/web/modifiers/modifiers.js create mode 100644 lib/platform/web/session-description-handler/index.d.ts create mode 100644 lib/platform/web/session-description-handler/index.d.ts.map create mode 100644 lib/platform/web/session-description-handler/index.js create mode 100644 lib/platform/web/session-description-handler/media-stream-factory-default.d.ts create mode 100644 lib/platform/web/session-description-handler/media-stream-factory-default.d.ts.map create mode 100644 lib/platform/web/session-description-handler/media-stream-factory-default.js create mode 100644 lib/platform/web/session-description-handler/media-stream-factory.d.ts create mode 100644 lib/platform/web/session-description-handler/media-stream-factory.d.ts.map create mode 100644 lib/platform/web/session-description-handler/media-stream-factory.js create mode 100644 lib/platform/web/session-description-handler/peer-connection-configuration-default.d.ts create mode 100644 lib/platform/web/session-description-handler/peer-connection-configuration-default.d.ts.map create mode 100644 lib/platform/web/session-description-handler/peer-connection-configuration-default.js create mode 100644 lib/platform/web/session-description-handler/peer-connection-delegate.d.ts create mode 100644 lib/platform/web/session-description-handler/peer-connection-delegate.d.ts.map create mode 100644 lib/platform/web/session-description-handler/peer-connection-delegate.js create mode 100644 lib/platform/web/session-description-handler/session-description-handler-configuration.d.ts create mode 100644 lib/platform/web/session-description-handler/session-description-handler-configuration.d.ts.map create mode 100644 lib/platform/web/session-description-handler/session-description-handler-configuration.js create mode 100644 lib/platform/web/session-description-handler/session-description-handler-factory-default.d.ts create mode 100644 lib/platform/web/session-description-handler/session-description-handler-factory-default.d.ts.map create mode 100644 lib/platform/web/session-description-handler/session-description-handler-factory-default.js create mode 100644 lib/platform/web/session-description-handler/session-description-handler-factory-options.d.ts create mode 100644 lib/platform/web/session-description-handler/session-description-handler-factory-options.d.ts.map create mode 100644 lib/platform/web/session-description-handler/session-description-handler-factory-options.js create mode 100644 lib/platform/web/session-description-handler/session-description-handler-factory.d.ts create mode 100644 lib/platform/web/session-description-handler/session-description-handler-factory.d.ts.map create mode 100644 lib/platform/web/session-description-handler/session-description-handler-factory.js create mode 100644 lib/platform/web/session-description-handler/session-description-handler-options.d.ts create mode 100644 lib/platform/web/session-description-handler/session-description-handler-options.d.ts.map create mode 100644 lib/platform/web/session-description-handler/session-description-handler-options.js create mode 100644 lib/platform/web/session-description-handler/session-description-handler.d.ts create mode 100644 lib/platform/web/session-description-handler/session-description-handler.d.ts.map create mode 100644 lib/platform/web/session-description-handler/session-description-handler.js create mode 100644 lib/platform/web/simple-user/index.d.ts create mode 100644 lib/platform/web/simple-user/index.d.ts.map create mode 100644 lib/platform/web/simple-user/index.js create mode 100644 lib/platform/web/simple-user/simple-user-delegate.d.ts create mode 100644 lib/platform/web/simple-user/simple-user-delegate.d.ts.map create mode 100644 lib/platform/web/simple-user/simple-user-delegate.js create mode 100644 lib/platform/web/simple-user/simple-user-options.d.ts create mode 100644 lib/platform/web/simple-user/simple-user-options.d.ts.map create mode 100644 lib/platform/web/simple-user/simple-user-options.js create mode 100644 lib/platform/web/simple-user/simple-user.d.ts create mode 100644 lib/platform/web/simple-user/simple-user.d.ts.map create mode 100644 lib/platform/web/simple-user/simple-user.js create mode 100644 lib/platform/web/transport/index.d.ts create mode 100644 lib/platform/web/transport/index.d.ts.map create mode 100644 lib/platform/web/transport/index.js create mode 100644 lib/platform/web/transport/transport-options.d.ts create mode 100644 lib/platform/web/transport/transport-options.d.ts.map create mode 100644 lib/platform/web/transport/transport-options.js create mode 100644 lib/platform/web/transport/transport.d.ts create mode 100644 lib/platform/web/transport/transport.d.ts.map create mode 100644 lib/platform/web/transport/transport.js create mode 100644 lib/version.d.ts create mode 100644 lib/version.d.ts.map create mode 100644 lib/version.js diff --git a/dist/sip-0.18.0.js b/dist/sip-0.18.0.js new file mode 100644 index 000000000..082cecbe8 --- /dev/null +++ b/dist/sip-0.18.0.js @@ -0,0 +1,20884 @@ +/*! + * + * SIP version 0.18.0 + * Copyright (c) 2014-2020 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, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "name", function() { return name; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "version", function() { return version; }); +/* harmony import */ var _version__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1); +/* harmony import */ var _api__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ContentTypeUnsupportedError", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["ContentTypeUnsupportedError"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RequestPendingError", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["RequestPendingError"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionDescriptionHandlerError", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["SessionDescriptionHandlerError"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionTerminatedError", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["SessionTerminatedError"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StateTransitionError", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["StateTransitionError"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Bye", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["Bye"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EmitterImpl", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["EmitterImpl"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Info", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["Info"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Invitation", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["Invitation"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Inviter", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["Inviter"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Message", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["Message"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Messager", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["Messager"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Notification", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["Notification"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PublisherState", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["PublisherState"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Publisher", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["Publisher"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Referral", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["Referral"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RegistererState", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["RegistererState"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Registerer", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["Registerer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionState", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["SessionState"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Session", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["Session"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Subscriber", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["Subscriber"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubscriptionState", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Subscription", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["Subscription"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransportState", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["TransportState"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SIPExtension", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["SIPExtension"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgentRegisteredOptionTags", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["UserAgentRegisteredOptionTags"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgentState", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["UserAgentState"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgent", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["UserAgent"]; }); + +/* harmony import */ var _grammar__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(9); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Grammar", function() { return _grammar__WEBPACK_IMPORTED_MODULE_2__["Grammar"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NameAddrHeader", function() { return _grammar__WEBPACK_IMPORTED_MODULE_2__["NameAddrHeader"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Parameters", function() { return _grammar__WEBPACK_IMPORTED_MODULE_2__["Parameters"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "URI", function() { return _grammar__WEBPACK_IMPORTED_MODULE_2__["URI"]; }); + +/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(5); +/* harmony reexport (module object) */ __webpack_require__.d(__webpack_exports__, "Core", function() { return _core__WEBPACK_IMPORTED_MODULE_3__; }); +/* harmony import */ var _platform_web__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(174); +/* harmony reexport (module object) */ __webpack_require__.d(__webpack_exports__, "Web", function() { return _platform_web__WEBPACK_IMPORTED_MODULE_4__; }); +// Helpful name and version exports + +const version = _version__WEBPACK_IMPORTED_MODULE_0__["LIBRARY_VERSION"]; +const name = "sip.js"; + +// Export api + +// Export grammar + +// Export namespaced core + + +// Export namespaced web + + + + +/***/ }), +/* 1 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LIBRARY_VERSION", function() { return LIBRARY_VERSION; }); +const LIBRARY_VERSION = "0.18.0"; + + +/***/ }), +/* 2 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _exceptions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ContentTypeUnsupportedError", function() { return _exceptions__WEBPACK_IMPORTED_MODULE_0__["ContentTypeUnsupportedError"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RequestPendingError", function() { return _exceptions__WEBPACK_IMPORTED_MODULE_0__["RequestPendingError"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionDescriptionHandlerError", function() { return _exceptions__WEBPACK_IMPORTED_MODULE_0__["SessionDescriptionHandlerError"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionTerminatedError", function() { return _exceptions__WEBPACK_IMPORTED_MODULE_0__["SessionTerminatedError"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StateTransitionError", function() { return _exceptions__WEBPACK_IMPORTED_MODULE_0__["StateTransitionError"]; }); + +/* harmony import */ var _bye__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(107); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Bye", function() { return _bye__WEBPACK_IMPORTED_MODULE_1__["Bye"]; }); + +/* harmony import */ var _emitter__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(108); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EmitterImpl", function() { return _emitter__WEBPACK_IMPORTED_MODULE_2__["EmitterImpl"]; }); + +/* harmony import */ var _info__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(109); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Info", function() { return _info__WEBPACK_IMPORTED_MODULE_3__["Info"]; }); + +/* harmony import */ var _invitation_accept_options__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(110); +/* empty/unused harmony star reexport *//* harmony import */ var _invitation_progress_options__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(111); +/* empty/unused harmony star reexport *//* harmony import */ var _invitation_reject_options__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(112); +/* empty/unused harmony star reexport *//* harmony import */ var _invitation__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(113); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Invitation", function() { return _invitation__WEBPACK_IMPORTED_MODULE_7__["Invitation"]; }); + +/* harmony import */ var _inviter_cancel_options__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(120); +/* empty/unused harmony star reexport *//* harmony import */ var _inviter_invite_options__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(121); +/* empty/unused harmony star reexport *//* harmony import */ var _inviter_options__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(122); +/* empty/unused harmony star reexport *//* harmony import */ var _inviter__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(123); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Inviter", function() { return _inviter__WEBPACK_IMPORTED_MODULE_11__["Inviter"]; }); + +/* harmony import */ var _message__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(115); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Message", function() { return _message__WEBPACK_IMPORTED_MODULE_12__["Message"]; }); + +/* harmony import */ var _messager_message_options__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(124); +/* empty/unused harmony star reexport *//* harmony import */ var _messager_options__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(125); +/* empty/unused harmony star reexport *//* harmony import */ var _messager__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(126); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Messager", function() { return _messager__WEBPACK_IMPORTED_MODULE_15__["Messager"]; }); + +/* harmony import */ var _notification__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(116); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Notification", function() { return _notification__WEBPACK_IMPORTED_MODULE_16__["Notification"]; }); + +/* harmony import */ var _publisher_options__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(127); +/* empty/unused harmony star reexport *//* harmony import */ var _publisher_publish_options__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(128); +/* empty/unused harmony star reexport *//* harmony import */ var _publisher_state__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(129); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PublisherState", function() { return _publisher_state__WEBPACK_IMPORTED_MODULE_19__["PublisherState"]; }); + +/* harmony import */ var _publisher_unpublish_options__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(130); +/* empty/unused harmony star reexport *//* harmony import */ var _publisher__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(131); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Publisher", function() { return _publisher__WEBPACK_IMPORTED_MODULE_21__["Publisher"]; }); + +/* harmony import */ var _referral__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(117); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Referral", function() { return _referral__WEBPACK_IMPORTED_MODULE_22__["Referral"]; }); + +/* harmony import */ var _registerer_options__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(132); +/* empty/unused harmony star reexport *//* harmony import */ var _registerer_register_options__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(133); +/* empty/unused harmony star reexport *//* harmony import */ var _registerer_state__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(134); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RegistererState", function() { return _registerer_state__WEBPACK_IMPORTED_MODULE_25__["RegistererState"]; }); + +/* harmony import */ var _registerer_unregister_options__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(135); +/* empty/unused harmony star reexport *//* harmony import */ var _registerer__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(136); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Registerer", function() { return _registerer__WEBPACK_IMPORTED_MODULE_27__["Registerer"]; }); + +/* harmony import */ var _session_bye_options__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(137); +/* empty/unused harmony star reexport *//* harmony import */ var _session_delegate__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(138); +/* empty/unused harmony star reexport *//* harmony import */ var _session_description_handler_factory__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(139); +/* empty/unused harmony star reexport *//* harmony import */ var _session_description_handler__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(140); +/* empty/unused harmony star reexport *//* harmony import */ var _session_info_options__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(141); +/* empty/unused harmony star reexport *//* harmony import */ var _session_invite_options__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(142); +/* empty/unused harmony star reexport *//* harmony import */ var _session_message_options__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(143); +/* empty/unused harmony star reexport *//* harmony import */ var _session_options__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(144); +/* empty/unused harmony star reexport *//* harmony import */ var _session_refer_options__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(145); +/* empty/unused harmony star reexport *//* harmony import */ var _session_state__WEBPACK_IMPORTED_MODULE_37__ = __webpack_require__(118); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionState", function() { return _session_state__WEBPACK_IMPORTED_MODULE_37__["SessionState"]; }); + +/* harmony import */ var _session__WEBPACK_IMPORTED_MODULE_38__ = __webpack_require__(114); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Session", function() { return _session__WEBPACK_IMPORTED_MODULE_38__["Session"]; }); + +/* harmony import */ var _subscriber_options__WEBPACK_IMPORTED_MODULE_39__ = __webpack_require__(146); +/* empty/unused harmony star reexport *//* harmony import */ var _subscriber_subscribe_options__WEBPACK_IMPORTED_MODULE_40__ = __webpack_require__(147); +/* empty/unused harmony star reexport *//* harmony import */ var _subscriber__WEBPACK_IMPORTED_MODULE_41__ = __webpack_require__(148); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Subscriber", function() { return _subscriber__WEBPACK_IMPORTED_MODULE_41__["Subscriber"]; }); + +/* harmony import */ var _subscription_delegate__WEBPACK_IMPORTED_MODULE_42__ = __webpack_require__(151); +/* empty/unused harmony star reexport *//* harmony import */ var _subscription_options__WEBPACK_IMPORTED_MODULE_43__ = __webpack_require__(152); +/* empty/unused harmony star reexport *//* harmony import */ var _subscription_state__WEBPACK_IMPORTED_MODULE_44__ = __webpack_require__(150); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubscriptionState", function() { return _subscription_state__WEBPACK_IMPORTED_MODULE_44__["SubscriptionState"]; }); + +/* harmony import */ var _subscription_subscribe_options__WEBPACK_IMPORTED_MODULE_45__ = __webpack_require__(153); +/* empty/unused harmony star reexport *//* harmony import */ var _subscription_unsubscribe_options__WEBPACK_IMPORTED_MODULE_46__ = __webpack_require__(154); +/* empty/unused harmony star reexport *//* harmony import */ var _subscription__WEBPACK_IMPORTED_MODULE_47__ = __webpack_require__(149); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Subscription", function() { return _subscription__WEBPACK_IMPORTED_MODULE_47__["Subscription"]; }); + +/* harmony import */ var _transport__WEBPACK_IMPORTED_MODULE_48__ = __webpack_require__(155); +/* empty/unused harmony star reexport *//* harmony import */ var _transport_state__WEBPACK_IMPORTED_MODULE_49__ = __webpack_require__(156); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransportState", function() { return _transport_state__WEBPACK_IMPORTED_MODULE_49__["TransportState"]; }); + +/* harmony import */ var _user_agent_delegate__WEBPACK_IMPORTED_MODULE_50__ = __webpack_require__(157); +/* empty/unused harmony star reexport *//* harmony import */ var _user_agent_options__WEBPACK_IMPORTED_MODULE_51__ = __webpack_require__(119); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SIPExtension", function() { return _user_agent_options__WEBPACK_IMPORTED_MODULE_51__["SIPExtension"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgentRegisteredOptionTags", function() { return _user_agent_options__WEBPACK_IMPORTED_MODULE_51__["UserAgentRegisteredOptionTags"]; }); + +/* harmony import */ var _user_agent_state__WEBPACK_IMPORTED_MODULE_52__ = __webpack_require__(158); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgentState", function() { return _user_agent_state__WEBPACK_IMPORTED_MODULE_52__["UserAgentState"]; }); + +/* harmony import */ var _user_agent__WEBPACK_IMPORTED_MODULE_53__ = __webpack_require__(159); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgent", function() { return _user_agent__WEBPACK_IMPORTED_MODULE_53__["UserAgent"]; }); + +/** + * A simple yet powerful API which takes care of SIP signaling and WebRTC media sessions for you. + * @packageDocumentation + */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/***/ }), +/* 3 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _content_type_unsupported__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ContentTypeUnsupportedError", function() { return _content_type_unsupported__WEBPACK_IMPORTED_MODULE_0__["ContentTypeUnsupportedError"]; }); + +/* harmony import */ var _request_pending__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(103); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RequestPendingError", function() { return _request_pending__WEBPACK_IMPORTED_MODULE_1__["RequestPendingError"]; }); + +/* harmony import */ var _session_description_handler__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(104); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionDescriptionHandlerError", function() { return _session_description_handler__WEBPACK_IMPORTED_MODULE_2__["SessionDescriptionHandlerError"]; }); + +/* harmony import */ var _session_terminated__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(105); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionTerminatedError", function() { return _session_terminated__WEBPACK_IMPORTED_MODULE_3__["SessionTerminatedError"]; }); + +/* harmony import */ var _state_transition__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(106); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StateTransitionError", function() { return _state_transition__WEBPACK_IMPORTED_MODULE_4__["StateTransitionError"]; }); + + + + + + + + +/***/ }), +/* 4 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ContentTypeUnsupportedError", function() { return ContentTypeUnsupportedError; }); +/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); + +/** + * An exception indicating an unsupported content type prevented execution. + * @public + */ +class ContentTypeUnsupportedError extends _core__WEBPACK_IMPORTED_MODULE_0__["Exception"] { + constructor(message) { + super(message ? message : "Unsupported content type."); + } +} + + +/***/ }), +/* 5 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _dialogs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Dialog", function() { return _dialogs__WEBPACK_IMPORTED_MODULE_0__["Dialog"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionDialog", function() { return _dialogs__WEBPACK_IMPORTED_MODULE_0__["SessionDialog"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubscriptionDialog", function() { return _dialogs__WEBPACK_IMPORTED_MODULE_0__["SubscriptionDialog"]; }); + +/* harmony import */ var _exceptions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(51); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Exception", function() { return _exceptions__WEBPACK_IMPORTED_MODULE_1__["Exception"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransactionStateError", function() { return _exceptions__WEBPACK_IMPORTED_MODULE_1__["TransactionStateError"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransportError", function() { return _exceptions__WEBPACK_IMPORTED_MODULE_1__["TransportError"]; }); + +/* harmony import */ var _log__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(84); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Levels", function() { return _log__WEBPACK_IMPORTED_MODULE_2__["Levels"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LoggerFactory", function() { return _log__WEBPACK_IMPORTED_MODULE_2__["LoggerFactory"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Logger", function() { return _log__WEBPACK_IMPORTED_MODULE_2__["Logger"]; }); + +/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Grammar", function() { return _messages__WEBPACK_IMPORTED_MODULE_3__["Grammar"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NameAddrHeader", function() { return _messages__WEBPACK_IMPORTED_MODULE_3__["NameAddrHeader"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Parameters", function() { return _messages__WEBPACK_IMPORTED_MODULE_3__["Parameters"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "URI", function() { return _messages__WEBPACK_IMPORTED_MODULE_3__["URI"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "C", function() { return _messages__WEBPACK_IMPORTED_MODULE_3__["C"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "fromBodyLegacy", function() { return _messages__WEBPACK_IMPORTED_MODULE_3__["fromBodyLegacy"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isBody", function() { return _messages__WEBPACK_IMPORTED_MODULE_3__["isBody"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getBody", function() { return _messages__WEBPACK_IMPORTED_MODULE_3__["getBody"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DigestAuthentication", function() { return _messages__WEBPACK_IMPORTED_MODULE_3__["DigestAuthentication"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IncomingMessage", function() { return _messages__WEBPACK_IMPORTED_MODULE_3__["IncomingMessage"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IncomingRequestMessage", function() { return _messages__WEBPACK_IMPORTED_MODULE_3__["IncomingRequestMessage"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IncomingResponseMessage", function() { return _messages__WEBPACK_IMPORTED_MODULE_3__["IncomingResponseMessage"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OutgoingRequestMessage", function() { return _messages__WEBPACK_IMPORTED_MODULE_3__["OutgoingRequestMessage"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "constructOutgoingResponse", function() { return _messages__WEBPACK_IMPORTED_MODULE_3__["constructOutgoingResponse"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Parser", function() { return _messages__WEBPACK_IMPORTED_MODULE_3__["Parser"]; }); + +/* harmony import */ var _session__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(44); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionState", function() { return _session__WEBPACK_IMPORTED_MODULE_4__["SessionState"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SignalingState", function() { return _session__WEBPACK_IMPORTED_MODULE_4__["SignalingState"]; }); + +/* harmony import */ var _subscription__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(79); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubscriptionState", function() { return _subscription__WEBPACK_IMPORTED_MODULE_5__["SubscriptionState"]; }); + +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(48); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ClientTransaction", function() { return _transactions__WEBPACK_IMPORTED_MODULE_6__["ClientTransaction"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InviteClientTransaction", function() { return _transactions__WEBPACK_IMPORTED_MODULE_6__["InviteClientTransaction"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InviteServerTransaction", function() { return _transactions__WEBPACK_IMPORTED_MODULE_6__["InviteServerTransaction"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NonInviteClientTransaction", function() { return _transactions__WEBPACK_IMPORTED_MODULE_6__["NonInviteClientTransaction"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NonInviteServerTransaction", function() { return _transactions__WEBPACK_IMPORTED_MODULE_6__["NonInviteServerTransaction"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ServerTransaction", function() { return _transactions__WEBPACK_IMPORTED_MODULE_6__["ServerTransaction"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransactionState", function() { return _transactions__WEBPACK_IMPORTED_MODULE_6__["TransactionState"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Transaction", function() { return _transactions__WEBPACK_IMPORTED_MODULE_6__["Transaction"]; }); + +/* harmony import */ var _user_agent_core__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(88); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgentCore", function() { return _user_agent_core__WEBPACK_IMPORTED_MODULE_7__["UserAgentCore"]; }); + +/* harmony import */ var _user_agents__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(90); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ByeUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["ByeUserAgentClient"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ByeUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["ByeUserAgentServer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CancelUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["CancelUserAgentClient"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InfoUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["InfoUserAgentClient"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InfoUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["InfoUserAgentServer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InviteUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["InviteUserAgentClient"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InviteUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["InviteUserAgentServer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MessageUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["MessageUserAgentClient"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MessageUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["MessageUserAgentServer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NotifyUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["NotifyUserAgentClient"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NotifyUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["NotifyUserAgentServer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PublishUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["PublishUserAgentClient"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PrackUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["PrackUserAgentClient"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PrackUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["PrackUserAgentServer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReInviteUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["ReInviteUserAgentClient"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReInviteUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["ReInviteUserAgentServer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReSubscribeUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["ReSubscribeUserAgentClient"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReSubscribeUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["ReSubscribeUserAgentServer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReferUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["ReferUserAgentClient"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReferUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["ReferUserAgentServer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RegisterUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["RegisterUserAgentClient"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RegisterUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["RegisterUserAgentServer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubscribeUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["SubscribeUserAgentClient"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubscribeUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["SubscribeUserAgentServer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["UserAgentClient"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["UserAgentServer"]; }); + +/* harmony import */ var _timers__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(47); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Timers", function() { return _timers__WEBPACK_IMPORTED_MODULE_9__["Timers"]; }); + +/* harmony import */ var _transport__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(102); +/* empty/unused harmony star reexport *//** + * A core library implementing low level SIP protocol elements. + * @packageDocumentation + */ +// Directories + + + + + + + + + +// Files + + + + +/***/ }), +/* 6 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _dialog__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(7); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Dialog", function() { return _dialog__WEBPACK_IMPORTED_MODULE_0__["Dialog"]; }); + +/* harmony import */ var _dialog_state__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(42); +/* empty/unused harmony star reexport *//* harmony import */ var _session_dialog__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(43); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionDialog", function() { return _session_dialog__WEBPACK_IMPORTED_MODULE_2__["SessionDialog"]; }); + +/* harmony import */ var _subscription_dialog__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(78); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubscriptionDialog", function() { return _subscription_dialog__WEBPACK_IMPORTED_MODULE_3__["SubscriptionDialog"]; }); + + + + + + + +/***/ }), +/* 7 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Dialog", function() { return Dialog; }); +/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); + +/** + * 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 + */ +class Dialog { + /** + * Dialog constructor. + * @param core - User agent core. + * @param dialogState - Initial dialog state. + */ + constructor(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. + */ + static initialDialogStateForUserAgentClient(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 + const 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 + const routeSet = incomingResponseMessage.getHeaders("record-route").reverse(); + // 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. + // https://tools.ietf.org/html/rfc3261#section-12.1.1 + const contact = incomingResponseMessage.parseHeader("contact"); + if (!contact) { + // TODO: Review to make sure this will never happen + throw new Error("Contact undefined."); + } + if (!(contact instanceof _messages__WEBPACK_IMPORTED_MODULE_0__["NameAddrHeader"])) { + throw new Error("Contact not instance of NameAddrHeader."); + } + const 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 + const localSequenceNumber = outgoingRequestMessage.cseq; + const remoteSequenceNumber = undefined; + const callId = outgoingRequestMessage.callId; + const localTag = outgoingRequestMessage.fromTag; + const 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."); + } + const localURI = outgoingRequestMessage.from.uri; + const 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."); + } + const early = incomingResponseMessage.statusCode < 200 ? true : false; + const dialogState = { + id: callId + localTag + remoteTag, + early, + callId, + localTag, + remoteTag, + localSequenceNumber, + remoteSequenceNumber, + localURI, + remoteURI, + remoteTarget, + routeSet, + 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. + */ + static initialDialogStateForUserAgentServer(incomingRequestMessage, toTag, 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 + const 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 + const routeSet = incomingRequestMessage.getHeaders("record-route"); + const contact = incomingRequestMessage.parseHeader("contact"); + if (!contact) { + // TODO: Review to make sure this will never happen + throw new Error("Contact undefined."); + } + if (!(contact instanceof _messages__WEBPACK_IMPORTED_MODULE_0__["NameAddrHeader"])) { + throw new Error("Contact not instance of NameAddrHeader."); + } + const 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 + const remoteSequenceNumber = incomingRequestMessage.cseq; + const localSequenceNumber = undefined; + const callId = incomingRequestMessage.callId; + const localTag = toTag; + const 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 + const remoteURI = incomingRequestMessage.from.uri; + const localURI = incomingRequestMessage.to.uri; + const dialogState = { + id: callId + localTag + remoteTag, + early, + callId, + localTag, + remoteTag, + localSequenceNumber, + remoteSequenceNumber, + localURI, + remoteURI, + remoteTarget, + routeSet, + secure + }; + return dialogState; + } + /** Destructor. */ + dispose() { + this.core.dialogs.delete(this.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 id() { + return this.dialogState.id; + } + /** + * 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 early() { + return this.dialogState.early; + } + /** Call identifier component of the dialog id. */ + get callId() { + return this.dialogState.callId; + } + /** Local tag component of the dialog id. */ + get localTag() { + return this.dialogState.localTag; + } + /** Remote tag component of the dialog id. */ + get remoteTag() { + return this.dialogState.remoteTag; + } + /** Local sequence number (used to order requests from the UA to its peer). */ + get localSequenceNumber() { + return this.dialogState.localSequenceNumber; + } + /** Remote sequence number (used to order requests from its peer to the UA). */ + get remoteSequenceNumber() { + return this.dialogState.remoteSequenceNumber; + } + /** Local URI. */ + get localURI() { + return this.dialogState.localURI; + } + /** Remote URI. */ + get remoteURI() { + return this.dialogState.remoteURI; + } + /** Remote target. */ + get remoteTarget() { + return this.dialogState.remoteTarget; + } + /** + * 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 routeSet() { + return this.dialogState.routeSet; + } + /** + * 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 secure() { + return this.dialogState.secure; + } + /** The user agent core servicing this dialog. */ + get userAgentCore() { + return this.core; + } + /** Confirm the dialog. Only matters if dialog is currently early. */ + confirm() { + 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. + */ + receiveRequest(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__WEBPACK_IMPORTED_MODULE_0__["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 + */ + recomputeRouteSet(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. + */ + createOutgoingRequestMessage(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 + const toUri = this.remoteURI; + const toTag = this.remoteTag; + const fromUri = this.localURI; + const 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 + const callId = this.callId; + let 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). + const ruri = this.remoteTarget; + const routeSet = this.routeSet; + const extraHeaders = options && options.extraHeaders; + const 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 + const message = this.userAgentCore.makeOutgoingRequestMessage(method, ruri, fromUri, toUri, { + callId, + cseq, + fromTag, + toTag, + routeSet + }, extraHeaders, body); + return message; + } + /** + * Increment the local sequence number by one. + * It feels like this should be protected, but the current authentication handling currently + * needs this to keep the dialog in sync when "auto re-sends" request messages. + * @internal + */ + incrementLocalSequenceNumber() { + if (!this.dialogState.localSequenceNumber) { + throw new Error("Local sequence number undefined."); + } + this.dialogState.localSequenceNumber += 1; + } + /** + * 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. + */ + sequenceGuard(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__WEBPACK_IMPORTED_MODULE_0__["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; + } +} + + +/***/ }), +/* 8 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _grammar__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Grammar", function() { return _grammar__WEBPACK_IMPORTED_MODULE_0__["Grammar"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NameAddrHeader", function() { return _grammar__WEBPACK_IMPORTED_MODULE_0__["NameAddrHeader"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Parameters", function() { return _grammar__WEBPACK_IMPORTED_MODULE_0__["Parameters"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "URI", function() { return _grammar__WEBPACK_IMPORTED_MODULE_0__["URI"]; }); + +/* harmony import */ var _methods__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(15); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "C", function() { return _methods__WEBPACK_IMPORTED_MODULE_1__["C"]; }); + +/* harmony import */ var _body__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(29); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "fromBodyLegacy", function() { return _body__WEBPACK_IMPORTED_MODULE_2__["fromBodyLegacy"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isBody", function() { return _body__WEBPACK_IMPORTED_MODULE_2__["isBody"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getBody", function() { return _body__WEBPACK_IMPORTED_MODULE_2__["getBody"]; }); + +/* harmony import */ var _digest_authentication__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(35); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DigestAuthentication", function() { return _digest_authentication__WEBPACK_IMPORTED_MODULE_3__["DigestAuthentication"]; }); + +/* harmony import */ var _incoming_message__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(31); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IncomingMessage", function() { return _incoming_message__WEBPACK_IMPORTED_MODULE_4__["IncomingMessage"]; }); + +/* harmony import */ var _incoming_request_message__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(30); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IncomingRequestMessage", function() { return _incoming_request_message__WEBPACK_IMPORTED_MODULE_5__["IncomingRequestMessage"]; }); + +/* harmony import */ var _incoming_request__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(37); +/* empty/unused harmony star reexport *//* harmony import */ var _incoming_response_message__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(33); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IncomingResponseMessage", function() { return _incoming_response_message__WEBPACK_IMPORTED_MODULE_7__["IncomingResponseMessage"]; }); + +/* harmony import */ var _incoming_response__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(38); +/* empty/unused harmony star reexport *//* harmony import */ var _outgoing_request_message__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(34); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OutgoingRequestMessage", function() { return _outgoing_request_message__WEBPACK_IMPORTED_MODULE_9__["OutgoingRequestMessage"]; }); + +/* harmony import */ var _outgoing_request__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(39); +/* empty/unused harmony star reexport *//* harmony import */ var _outgoing_response__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(40); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "constructOutgoingResponse", function() { return _outgoing_response__WEBPACK_IMPORTED_MODULE_11__["constructOutgoingResponse"]; }); + +/* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(41); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Parser", function() { return _parser__WEBPACK_IMPORTED_MODULE_12__["Parser"]; }); + +// Grammar + +// Directories + +// Files + + + + + + + + + + + + + +/***/ }), +/* 9 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _grammar__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(10); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Grammar", function() { return _grammar__WEBPACK_IMPORTED_MODULE_0__["Grammar"]; }); + +/* harmony import */ var _name_addr_header__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(12); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NameAddrHeader", function() { return _name_addr_header__WEBPACK_IMPORTED_MODULE_1__["NameAddrHeader"]; }); + +/* harmony import */ var _parameters__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(13); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Parameters", function() { return _parameters__WEBPACK_IMPORTED_MODULE_2__["Parameters"]; }); + +/* harmony import */ var _uri__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(14); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "URI", function() { return _uri__WEBPACK_IMPORTED_MODULE_3__["URI"]; }); + + + + + + + +/***/ }), +/* 10 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Grammar", function() { return Grammar; }); +/* harmony import */ var _pegjs_dist_grammar__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(11); +/* eslint-disable @typescript-eslint/no-namespace */ +/* eslint-disable no-inner-declarations */ + +/** + * Grammar. + * @internal + */ +var Grammar; +(function (Grammar) { + /** + * Parse. + * @param input - + * @param startRule - + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + function parse(input, startRule) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const options = { startRule }; + try { + _pegjs_dist_grammar__WEBPACK_IMPORTED_MODULE_0__["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) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const 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) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const parsedUri = Grammar.parse(uri, "SIP_URI"); + return parsedUri !== -1 ? parsedUri : undefined; + } + Grammar.URIParse = URIParse; +})(Grammar || (Grammar = {})); + + +/***/ }), +/* 11 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SyntaxError", function() { return SyntaxError; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parse", function() { return parse; }); +/* harmony import */ var _name_addr_header__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(12); +/* harmony import */ var _uri__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(14); + + +class SyntaxError extends Error { + constructor(message, expected, found, location) { + super(); + this.message = message; + this.expected = expected; + this.found = found; + this.location = location; + this.name = "SyntaxError"; + if (typeof Error.captureStackTrace === "function") { + Error.captureStackTrace(this, SyntaxError); + } + } + static buildMessage(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, (ch) => "\\x0" + hex(ch)) + .replace(/[\x10-\x1F\x7F-\x9F]/g, (ch) => "\\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, (ch) => "\\x0" + hex(ch)) + .replace(/[\x10-\x1F\x7F-\x9F]/g, (ch) => "\\x" + hex(ch)); + } + function describeExpectation(expectation) { + switch (expectation.type) { + case "literal": + return "\"" + literalEscape(expectation.text) + "\""; + case "class": + const escapedParts = expectation.parts.map((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) { + const descriptions = expected1.map(describeExpectation); + let i; + let 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."; + } +} +function peg$parse(input, options) { + options = options !== undefined ? options : {}; + const peg$FAILED = {}; + const 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 }; + let peg$startRuleIndex = 119; + const 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__WEBPACK_IMPORTED_MODULE_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__WEBPACK_IMPORTED_MODULE_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__WEBPACK_IMPORTED_MODULE_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__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_0__["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) + ]; + const 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((ch) => ch.charCodeAt(0) - 32); + } + function peg$parseRule(index) { + const bc = peg$bytecode[index]; + let ip = 0; + const ips = []; + let end = bc.length; + const ends = []; + const stack = []; + let 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)); + } +} +const parse = peg$parse; + + +/***/ }), +/* 12 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NameAddrHeader", function() { return NameAddrHeader; }); +/* harmony import */ var _parameters__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(13); + +/** + * Name Address SIP header. + * @public + */ +class NameAddrHeader extends _parameters__WEBPACK_IMPORTED_MODULE_0__["Parameters"] { + /** + * Constructor + * @param uri - + * @param displayName - + * @param parameters - + */ + constructor(uri, displayName, parameters) { + super(parameters); + this.uri = uri; + this._displayName = displayName; + } + get friendlyName() { + return this.displayName || this.uri.aor; + } + get displayName() { return this._displayName; } + set displayName(value) { + this._displayName = value; + } + clone() { + return new NameAddrHeader(this.uri.clone(), this._displayName, JSON.parse(JSON.stringify(this.parameters))); + } + toString() { + let body = (this.displayName || this.displayName === "0") ? '"' + this.displayName + '" ' : ""; + body += "<" + this.uri.toString() + ">"; + for (const parameter in this.parameters) { + // eslint-disable-next-line no-prototype-builtins + if (this.parameters.hasOwnProperty(parameter)) { + body += ";" + parameter; + if (this.parameters[parameter] !== null) { + body += "=" + this.parameters[parameter]; + } + } + } + return body; + } +} + + +/***/ }), +/* 13 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Parameters", function() { return Parameters; }); +/** + * @internal + */ +class Parameters { + constructor(parameters) { + this.parameters = {}; + // for in is required here as the Grammar parser is adding to the prototype chain + for (const param in parameters) { + // eslint-disable-next-line no-prototype-builtins + if (parameters.hasOwnProperty(param)) { + this.setParam(param, parameters[param]); + } + } + } + setParam(key, value) { + if (key) { + this.parameters[key.toLowerCase()] = (typeof value === "undefined" || value === null) ? null : value.toString(); + } + } + getParam(key) { + if (key) { + return this.parameters[key.toLowerCase()]; + } + } + hasParam(key) { + return !!(key && this.parameters[key.toLowerCase()] !== undefined); + } + deleteParam(key) { + key = key.toLowerCase(); + if (this.hasParam(key)) { + const value = this.parameters[key]; + delete this.parameters[key]; + return value; + } + } + clearParams() { + this.parameters = {}; + } +} + + +/***/ }), +/* 14 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "URI", function() { return URI; }); +/* harmony import */ var _parameters__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(13); +/* eslint-disable @typescript-eslint/no-explicit-any */ + +/** + * URI. + * @public + */ +class URI extends _parameters__WEBPACK_IMPORTED_MODULE_0__["Parameters"] { + /** + * Constructor + * @param scheme - + * @param user - + * @param host - + * @param port - + * @param parameters - + * @param headers - + */ + constructor(scheme = "sip", user, host, port, parameters, headers) { + super(parameters || {}); + this.headers = {}; + // Checks + if (!host) { + throw new TypeError('missing or invalid "host" parameter'); + } + for (const header in headers) { + // eslint-disable-next-line no-prototype-builtins + if (headers.hasOwnProperty(header)) { + this.setHeader(header, headers[header]); + } + } + // Raw URI + this.raw = { + scheme, + user, + host, + port + }; + // Normalized URI + this.normal = { + scheme: scheme.toLowerCase(), + user, + host: host.toLowerCase(), + port + }; + } + get scheme() { return this.normal.scheme; } + set scheme(value) { + this.raw.scheme = value; + this.normal.scheme = value.toLowerCase(); + } + get user() { return this.normal.user; } + set user(value) { + this.normal.user = this.raw.user = value; + } + get host() { return this.normal.host; } + set host(value) { + this.raw.host = value; + this.normal.host = value.toLowerCase(); + } + get aor() { return this.normal.user + "@" + this.normal.host; } + get port() { return this.normal.port; } + set port(value) { + this.normal.port = this.raw.port = value === 0 ? value : value; + } + setHeader(name, value) { + this.headers[this.headerize(name)] = (value instanceof Array) ? value : [value]; + } + getHeader(name) { + if (name) { + return this.headers[this.headerize(name)]; + } + } + hasHeader(name) { + // eslint-disable-next-line no-prototype-builtins + return !!name && !!this.headers.hasOwnProperty(this.headerize(name)); + } + deleteHeader(header) { + header = this.headerize(header); + // eslint-disable-next-line no-prototype-builtins + if (this.headers.hasOwnProperty(header)) { + const value = this.headers[header]; + delete this.headers[header]; + return value; + } + } + clearHeaders() { + this.headers = {}; + } + clone() { + 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))); + } + toRaw() { + return this._toString(this._raw); + } + toString() { + return this._toString(this._normal); + } + get _normal() { return this.normal; } + get _raw() { return this.raw; } + _toString(uri) { + let 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 (const parameter in this.parameters) { + // eslint-disable-next-line no-prototype-builtins + if (this.parameters.hasOwnProperty(parameter)) { + uriString += ";" + parameter; + if (this.parameters[parameter] !== null) { + uriString += "=" + this.parameters[parameter]; + } + } + } + const headers = []; + for (const header in this.headers) { + // eslint-disable-next-line no-prototype-builtins + if (this.headers.hasOwnProperty(header)) { + for (const idx in this.headers[header]) { + // eslint-disable-next-line no-prototype-builtins + 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 + */ + escapeUser(user) { + let 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. + // eslint-disable-next-line no-useless-catch + 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, "/"); + } + headerize(str) { + const exceptions = { + "Call-Id": "Call-ID", + "Cseq": "CSeq", + "Min-Se": "Min-SE", + "Rack": "RAck", + "Rseq": "RSeq", + "Www-Authenticate": "WWW-Authenticate", + }; + const name = str.toLowerCase().replace(/_/g, "-").split("-"); + const parts = name.length; + let hname = ""; + for (let 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; + } +} + + +/***/ }), +/* 15 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(16); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "C", function() { return _constants__WEBPACK_IMPORTED_MODULE_0__["C"]; }); + +/* harmony import */ var _ack__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(17); +/* empty/unused harmony star reexport *//* harmony import */ var _bye__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(18); +/* empty/unused harmony star reexport *//* harmony import */ var _cancel__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(19); +/* empty/unused harmony star reexport *//* harmony import */ var _info__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(20); +/* empty/unused harmony star reexport *//* harmony import */ var _invite__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(21); +/* empty/unused harmony star reexport *//* harmony import */ var _message__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(22); +/* empty/unused harmony star reexport *//* harmony import */ var _notify__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(23); +/* empty/unused harmony star reexport *//* harmony import */ var _prack__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(24); +/* empty/unused harmony star reexport *//* harmony import */ var _publish__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(25); +/* empty/unused harmony star reexport *//* harmony import */ var _register__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(26); +/* empty/unused harmony star reexport *//* harmony import */ var _refer__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(27); +/* empty/unused harmony star reexport *//* harmony import */ var _subscribe__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(28); +/* empty/unused harmony star reexport */ + + + + + + + + + + + + + + +/***/ }), +/* 16 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "C", function() { return C; }); +/* eslint-disable @typescript-eslint/no-namespace */ +/** + * 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 || (C = {})); + + +/***/ }), +/* 17 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 18 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 19 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 20 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 21 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 22 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 23 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 24 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 25 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 26 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 27 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 28 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 29 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fromBodyLegacy", function() { return fromBodyLegacy; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isBody", function() { return isBody; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getBody", function() { return getBody; }); +/* harmony import */ var _incoming_request_message__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(30); +/* harmony import */ var _incoming_response_message__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(33); +/* harmony import */ var _outgoing_request_message__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(34); + + + +// 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"; + } +} +/** + * Create a Body given a legacy body type. + * @param bodyLegacy - Body Object + * @internal + */ +function fromBodyLegacy(bodyLegacy) { + const content = typeof bodyLegacy === "string" ? bodyLegacy : bodyLegacy.body; + const contentType = typeof bodyLegacy === "string" ? "application/sdp" : bodyLegacy.contentType; + const contentDisposition = contentTypeToContentDisposition(contentType); + const body = { contentDisposition, contentType, content }; + return body; +} +/** + * User-Defined Type Guard for Body. + * @param body - Body to check. + * @internal + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function isBody(body) { + return body && + typeof body.content === "string" && + typeof body.contentType === "string" && + body.contentDisposition === undefined + ? true + : typeof body.contentDisposition === "string"; +} +/** + * Given a message, get a normalized body. + * The content disposition is inferred if not set. + * @param message - The message. + * @internal + */ +function getBody(message) { + let contentDisposition; + let contentType; + let content; + // We're in UAS role, receiving incoming request + if (message instanceof _incoming_request_message__WEBPACK_IMPORTED_MODULE_0__["IncomingRequestMessage"]) { + if (message.body) { + // FIXME: Parsing needs typing + const 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__WEBPACK_IMPORTED_MODULE_1__["IncomingResponseMessage"]) { + if (message.body) { + // FIXME: Parsing needs typing + const 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__WEBPACK_IMPORTED_MODULE_2__["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, + contentType, + content + }; +} + + +/***/ }), +/* 30 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "IncomingRequestMessage", function() { return IncomingRequestMessage; }); +/* harmony import */ var _incoming_message__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(31); + +/** + * Incoming request message. + * @public + */ +class IncomingRequestMessage extends _incoming_message__WEBPACK_IMPORTED_MODULE_0__["IncomingMessage"] { + constructor() { + super(); + } +} + + +/***/ }), +/* 31 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "IncomingMessage", function() { return IncomingMessage; }); +/* harmony import */ var _grammar__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9); +/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(32); + + +/** + * Incoming message. + * @public + */ +class IncomingMessage { + constructor() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + 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 + */ + addHeader(name, value) { + const header = { raw: value }; + name = Object(_utils__WEBPACK_IMPORTED_MODULE_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. + */ + getHeader(name) { + const header = this.headers[Object(_utils__WEBPACK_IMPORTED_MODULE_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. + */ + getHeaders(name) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const header = this.headers[Object(_utils__WEBPACK_IMPORTED_MODULE_1__["headerize"])(name)]; + const result = []; + if (!header) { + return []; + } + for (const headerPart of header) { + 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 + */ + hasHeader(name) { + return !!this.headers[Object(_utils__WEBPACK_IMPORTED_MODULE_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. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + parseHeader(name, idx = 0) { + name = Object(_utils__WEBPACK_IMPORTED_MODULE_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; + } + const header = this.headers[name][idx]; + const value = header.raw; + if (header.parsed) { + return header.parsed; + } + // substitute '-' by '_' for grammar rule matching. + const parsed = _grammar__WEBPACK_IMPORTED_MODULE_0__["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 + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + s(name, 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 + */ + setHeader(name, value) { + this.headers[Object(_utils__WEBPACK_IMPORTED_MODULE_1__["headerize"])(name)] = [{ raw: value }]; + } + toString() { + return this.data; + } +} + + +/***/ }), +/* 32 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createRandomToken", function() { return createRandomToken; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getReasonPhrase", function() { return getReasonPhrase; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "newTag", function() { return newTag; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "headerize", function() { return headerize; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "utf8Length", function() { return utf8Length; }); +/** + * SIP Response Reasons + * DOC: http://www.iana.org/assignments/sip-parameters + * @internal + */ +const 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" +}; +/** + * @param size - + * @param base - + * @internal + */ +function createRandomToken(size, base = 32) { + let token = ""; + for (let i = 0; i < size; i++) { + const r = Math.floor(Math.random() * base); + token += r.toString(base); + } + return token; +} +/** + * @internal + */ +function getReasonPhrase(code) { + return REASON_PHRASE[code] || ""; +} +/** + * @internal + */ +function newTag() { + return createRandomToken(10); +} +/** + * @param str - + * @internal + */ +function headerize(str) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const exceptions = { + "Call-Id": "Call-ID", + Cseq: "CSeq", + "Min-Se": "Min-SE", + Rack: "RAck", + Rseq: "RSeq", + "Www-Authenticate": "WWW-Authenticate" + }; + const name = str.toLowerCase().replace(/_/g, "-").split("-"); + const parts = name.length; + let hname = ""; + for (let 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; +} +/** + * @param str - + * @internal + */ +function utf8Length(str) { + return encodeURIComponent(str).replace(/%[A-F\d]{2}/g, "U").length; +} + + +/***/ }), +/* 33 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "IncomingResponseMessage", function() { return IncomingResponseMessage; }); +/* harmony import */ var _incoming_message__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(31); + +/** + * Incoming response message. + * @public + */ +class IncomingResponseMessage extends _incoming_message__WEBPACK_IMPORTED_MODULE_0__["IncomingMessage"] { + constructor() { + super(); + } +} + + +/***/ }), +/* 34 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OutgoingRequestMessage", function() { return OutgoingRequestMessage; }); +/* harmony import */ var _grammar__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9); +/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(32); + + +/** + * Outgoing SIP request message. + * @public + */ +class OutgoingRequestMessage { + constructor(method, ruri, fromURI, toURI, options, extraHeaders, body) { + this.headers = {}; + this.extraHeaders = []; + // Initialize default options + this.options = OutgoingRequestMessage.getDefaultOptions(); + // Options - merge a deep copy + if (options) { + this.options = Object.assign(Object.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 : Object(_utils__WEBPACK_IMPORTED_MODULE_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 + Object(_utils__WEBPACK_IMPORTED_MODULE_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. */ + static getDefaultOptions() { + return { + callId: "", + callIdPrefix: "", + cseq: 1, + toDisplayName: "", + toTag: "", + fromDisplayName: "", + fromTag: "", + forceRport: false, + hackViaTcp: false, + optionTags: ["outbound"], + routeSet: [], + userAgentString: "sip.js", + viaHost: "" + }; + } + static makeNameAddrHeader(uri, displayName, tag) { + const parameters = {}; + if (tag) { + parameters.tag = tag; + } + return new _grammar__WEBPACK_IMPORTED_MODULE_0__["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. + */ + getHeader(name) { + const header = this.headers[Object(_utils__WEBPACK_IMPORTED_MODULE_1__["headerize"])(name)]; + if (header) { + if (header[0]) { + return header[0]; + } + } + else { + const regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); + for (const exHeader of this.extraHeaders) { + 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. + */ + getHeaders(name) { + const result = []; + const headerArray = this.headers[Object(_utils__WEBPACK_IMPORTED_MODULE_1__["headerize"])(name)]; + if (headerArray) { + for (const headerPart of headerArray) { + result.push(headerPart); + } + } + else { + const regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); + for (const exHeader of this.extraHeaders) { + 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 + */ + hasHeader(name) { + if (this.headers[Object(_utils__WEBPACK_IMPORTED_MODULE_1__["headerize"])(name)]) { + return true; + } + else { + const regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); + for (const extraHeader of this.extraHeaders) { + 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 + */ + setHeader(name, value) { + this.headers[Object(_utils__WEBPACK_IMPORTED_MODULE_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 transport - The sent protocol transport. + */ + setViaHeader(branch, transport) { + // FIXME: Hack + if (this.options.hackViaTcp) { + transport = "TCP"; + } + let via = "SIP/2.0/" + transport; + via += " " + this.options.viaHost + ";branch=" + branch; + if (this.options.forceRport) { + via += ";rport"; + } + this.setHeader("via", via); + this.branch = branch; + } + toString() { + let msg = ""; + msg += this.method + " " + this.ruri.toRaw() + " SIP/2.0\r\n"; + for (const header in this.headers) { + if (this.headers[header]) { + for (const headerPart of this.headers[header]) { + msg += header + ": " + headerPart + "\r\n"; + } + } + } + for (const header of this.extraHeaders) { + 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: " + Object(_utils__WEBPACK_IMPORTED_MODULE_1__["utf8Length"])(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: " + Object(_utils__WEBPACK_IMPORTED_MODULE_1__["utf8Length"])(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; + } +} + + +/***/ }), +/* 35 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DigestAuthentication", function() { return DigestAuthentication; }); +/* harmony import */ var _md5__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); +/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(32); + + +function MD5(s) { + return _md5__WEBPACK_IMPORTED_MODULE_0__["Md5"].hashStr(s); +} +/** + * Digest Authentication. + * @internal + */ +class DigestAuthentication { + /** + * Constructor. + * @param loggerFactory - LoggerFactory. + * @param username - Username. + * @param password - Password. + */ + constructor(loggerFactory, ha1, username, password) { + this.logger = loggerFactory.getLogger("sipjs.digestauthentication"); + this.username = username; + this.password = password; + this.ha1 = ha1; + 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. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + authenticate(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 = Object(_utils__WEBPACK_IMPORTED_MODULE_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. + */ + toString() { + const 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. + */ + updateNcHex() { + const hex = Number(this.nc).toString(16); + this.ncHex = "00000000".substr(0, 8 - hex.length) + hex; + } + /** + * Generate Digest 'response' value. + */ + calculateResponse(body) { + let ha1, ha2; + // HA1 = MD5(A1) = MD5(username:realm:password) + ha1 = this.ha1; + if (ha1 === "" || ha1 === undefined) { + ha1 = MD5(this.username + ":" + this.realm + ":" + this.password); + } + if (this.qop === "auth") { + // HA2 = MD5(A2) = MD5(method:digestURI) + ha2 = MD5(this.method + ":" + this.uri); + // response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2)` + this.response = MD5(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(this.method + ":" + this.uri + ":" + MD5(body ? body : "")); + // response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2) + this.response = MD5(ha1 + ":" + this.nonce + ":" + this.ncHex + ":" + this.cnonce + ":auth-int:" + ha2); + } + else if (this.qop === undefined) { + // HA2 = MD5(A2) = MD5(method:digestURI) + ha2 = MD5(this.method + ":" + this.uri); + // response = MD5(HA1:nonce:HA2) + this.response = MD5(ha1 + ":" + this.nonce + ":" + ha2); + } + } +} + + +/***/ }), +/* 36 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Md5", function() { return Md5; }); +/* eslint-disable */ +// +// Scoped from: https://github.com/cotag/ts-md5 +// +/* + +TypeScript Md5 +============== + +Based on work by +* Joseph Myers: http://www.myersdaily.org/joseph/javascript/md5-text.html +* André Cruz: https://github.com/satazor/SparkMD5 +* Raymond Hill: https://github.com/gorhill/yamd5.js + +Effectively a TypeScrypt re-write of Raymond Hill JS Library + +The MIT License (MIT) + +Copyright (C) 2014 Raymond Hill + +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. + + + + DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE + Version 2, December 2004 + + Copyright (C) 2015 André Cruz + + Everyone is permitted to copy and distribute verbatim or modified + copies of this license document, and changing it is allowed as long + as the name is changed. + + DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. You just DO WHAT THE FUCK YOU WANT TO. + + +*/ +class Md5 { + constructor() { + this._dataLength = 0; + this._bufferLength = 0; + this._state = new Int32Array(4); + this._buffer = new ArrayBuffer(68); + this._buffer8 = new Uint8Array(this._buffer, 0, 68); + this._buffer32 = new Uint32Array(this._buffer, 0, 17); + this.start(); + } + static hashStr(str, raw = false) { + return this.onePassHasher + .start() + .appendStr(str) + .end(raw); + } + static hashAsciiStr(str, raw = false) { + return this.onePassHasher + .start() + .appendAsciiStr(str) + .end(raw); + } + static _hex(x) { + const hc = Md5.hexChars; + const ho = Md5.hexOut; + let n; + let offset; + let j; + let i; + for (i = 0; i < 4; i += 1) { + offset = i * 8; + n = x[i]; + for (j = 0; j < 8; j += 2) { + ho[offset + 1 + j] = hc.charAt(n & 0x0F); + n >>>= 4; + ho[offset + 0 + j] = hc.charAt(n & 0x0F); + n >>>= 4; + } + } + return ho.join(''); + } + static _md5cycle(x, k) { + let a = x[0]; + let b = x[1]; + let c = x[2]; + let d = x[3]; + // ff() + a += (b & c | ~b & d) + k[0] - 680876936 | 0; + a = (a << 7 | a >>> 25) + b | 0; + d += (a & b | ~a & c) + k[1] - 389564586 | 0; + d = (d << 12 | d >>> 20) + a | 0; + c += (d & a | ~d & b) + k[2] + 606105819 | 0; + c = (c << 17 | c >>> 15) + d | 0; + b += (c & d | ~c & a) + k[3] - 1044525330 | 0; + b = (b << 22 | b >>> 10) + c | 0; + a += (b & c | ~b & d) + k[4] - 176418897 | 0; + a = (a << 7 | a >>> 25) + b | 0; + d += (a & b | ~a & c) + k[5] + 1200080426 | 0; + d = (d << 12 | d >>> 20) + a | 0; + c += (d & a | ~d & b) + k[6] - 1473231341 | 0; + c = (c << 17 | c >>> 15) + d | 0; + b += (c & d | ~c & a) + k[7] - 45705983 | 0; + b = (b << 22 | b >>> 10) + c | 0; + a += (b & c | ~b & d) + k[8] + 1770035416 | 0; + a = (a << 7 | a >>> 25) + b | 0; + d += (a & b | ~a & c) + k[9] - 1958414417 | 0; + d = (d << 12 | d >>> 20) + a | 0; + c += (d & a | ~d & b) + k[10] - 42063 | 0; + c = (c << 17 | c >>> 15) + d | 0; + b += (c & d | ~c & a) + k[11] - 1990404162 | 0; + b = (b << 22 | b >>> 10) + c | 0; + a += (b & c | ~b & d) + k[12] + 1804603682 | 0; + a = (a << 7 | a >>> 25) + b | 0; + d += (a & b | ~a & c) + k[13] - 40341101 | 0; + d = (d << 12 | d >>> 20) + a | 0; + c += (d & a | ~d & b) + k[14] - 1502002290 | 0; + c = (c << 17 | c >>> 15) + d | 0; + b += (c & d | ~c & a) + k[15] + 1236535329 | 0; + b = (b << 22 | b >>> 10) + c | 0; + // gg() + a += (b & d | c & ~d) + k[1] - 165796510 | 0; + a = (a << 5 | a >>> 27) + b | 0; + d += (a & c | b & ~c) + k[6] - 1069501632 | 0; + d = (d << 9 | d >>> 23) + a | 0; + c += (d & b | a & ~b) + k[11] + 643717713 | 0; + c = (c << 14 | c >>> 18) + d | 0; + b += (c & a | d & ~a) + k[0] - 373897302 | 0; + b = (b << 20 | b >>> 12) + c | 0; + a += (b & d | c & ~d) + k[5] - 701558691 | 0; + a = (a << 5 | a >>> 27) + b | 0; + d += (a & c | b & ~c) + k[10] + 38016083 | 0; + d = (d << 9 | d >>> 23) + a | 0; + c += (d & b | a & ~b) + k[15] - 660478335 | 0; + c = (c << 14 | c >>> 18) + d | 0; + b += (c & a | d & ~a) + k[4] - 405537848 | 0; + b = (b << 20 | b >>> 12) + c | 0; + a += (b & d | c & ~d) + k[9] + 568446438 | 0; + a = (a << 5 | a >>> 27) + b | 0; + d += (a & c | b & ~c) + k[14] - 1019803690 | 0; + d = (d << 9 | d >>> 23) + a | 0; + c += (d & b | a & ~b) + k[3] - 187363961 | 0; + c = (c << 14 | c >>> 18) + d | 0; + b += (c & a | d & ~a) + k[8] + 1163531501 | 0; + b = (b << 20 | b >>> 12) + c | 0; + a += (b & d | c & ~d) + k[13] - 1444681467 | 0; + a = (a << 5 | a >>> 27) + b | 0; + d += (a & c | b & ~c) + k[2] - 51403784 | 0; + d = (d << 9 | d >>> 23) + a | 0; + c += (d & b | a & ~b) + k[7] + 1735328473 | 0; + c = (c << 14 | c >>> 18) + d | 0; + b += (c & a | d & ~a) + k[12] - 1926607734 | 0; + b = (b << 20 | b >>> 12) + c | 0; + // hh() + a += (b ^ c ^ d) + k[5] - 378558 | 0; + a = (a << 4 | a >>> 28) + b | 0; + d += (a ^ b ^ c) + k[8] - 2022574463 | 0; + d = (d << 11 | d >>> 21) + a | 0; + c += (d ^ a ^ b) + k[11] + 1839030562 | 0; + c = (c << 16 | c >>> 16) + d | 0; + b += (c ^ d ^ a) + k[14] - 35309556 | 0; + b = (b << 23 | b >>> 9) + c | 0; + a += (b ^ c ^ d) + k[1] - 1530992060 | 0; + a = (a << 4 | a >>> 28) + b | 0; + d += (a ^ b ^ c) + k[4] + 1272893353 | 0; + d = (d << 11 | d >>> 21) + a | 0; + c += (d ^ a ^ b) + k[7] - 155497632 | 0; + c = (c << 16 | c >>> 16) + d | 0; + b += (c ^ d ^ a) + k[10] - 1094730640 | 0; + b = (b << 23 | b >>> 9) + c | 0; + a += (b ^ c ^ d) + k[13] + 681279174 | 0; + a = (a << 4 | a >>> 28) + b | 0; + d += (a ^ b ^ c) + k[0] - 358537222 | 0; + d = (d << 11 | d >>> 21) + a | 0; + c += (d ^ a ^ b) + k[3] - 722521979 | 0; + c = (c << 16 | c >>> 16) + d | 0; + b += (c ^ d ^ a) + k[6] + 76029189 | 0; + b = (b << 23 | b >>> 9) + c | 0; + a += (b ^ c ^ d) + k[9] - 640364487 | 0; + a = (a << 4 | a >>> 28) + b | 0; + d += (a ^ b ^ c) + k[12] - 421815835 | 0; + d = (d << 11 | d >>> 21) + a | 0; + c += (d ^ a ^ b) + k[15] + 530742520 | 0; + c = (c << 16 | c >>> 16) + d | 0; + b += (c ^ d ^ a) + k[2] - 995338651 | 0; + b = (b << 23 | b >>> 9) + c | 0; + // ii() + a += (c ^ (b | ~d)) + k[0] - 198630844 | 0; + a = (a << 6 | a >>> 26) + b | 0; + d += (b ^ (a | ~c)) + k[7] + 1126891415 | 0; + d = (d << 10 | d >>> 22) + a | 0; + c += (a ^ (d | ~b)) + k[14] - 1416354905 | 0; + c = (c << 15 | c >>> 17) + d | 0; + b += (d ^ (c | ~a)) + k[5] - 57434055 | 0; + b = (b << 21 | b >>> 11) + c | 0; + a += (c ^ (b | ~d)) + k[12] + 1700485571 | 0; + a = (a << 6 | a >>> 26) + b | 0; + d += (b ^ (a | ~c)) + k[3] - 1894986606 | 0; + d = (d << 10 | d >>> 22) + a | 0; + c += (a ^ (d | ~b)) + k[10] - 1051523 | 0; + c = (c << 15 | c >>> 17) + d | 0; + b += (d ^ (c | ~a)) + k[1] - 2054922799 | 0; + b = (b << 21 | b >>> 11) + c | 0; + a += (c ^ (b | ~d)) + k[8] + 1873313359 | 0; + a = (a << 6 | a >>> 26) + b | 0; + d += (b ^ (a | ~c)) + k[15] - 30611744 | 0; + d = (d << 10 | d >>> 22) + a | 0; + c += (a ^ (d | ~b)) + k[6] - 1560198380 | 0; + c = (c << 15 | c >>> 17) + d | 0; + b += (d ^ (c | ~a)) + k[13] + 1309151649 | 0; + b = (b << 21 | b >>> 11) + c | 0; + a += (c ^ (b | ~d)) + k[4] - 145523070 | 0; + a = (a << 6 | a >>> 26) + b | 0; + d += (b ^ (a | ~c)) + k[11] - 1120210379 | 0; + d = (d << 10 | d >>> 22) + a | 0; + c += (a ^ (d | ~b)) + k[2] + 718787259 | 0; + c = (c << 15 | c >>> 17) + d | 0; + b += (d ^ (c | ~a)) + k[9] - 343485551 | 0; + b = (b << 21 | b >>> 11) + c | 0; + x[0] = a + x[0] | 0; + x[1] = b + x[1] | 0; + x[2] = c + x[2] | 0; + x[3] = d + x[3] | 0; + } + start() { + this._dataLength = 0; + this._bufferLength = 0; + this._state.set(Md5.stateIdentity); + return this; + } + // Char to code point to to array conversion: + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt + // #Example.3A_Fixing_charCodeAt_to_handle_non-Basic-Multilingual-Plane_characters_if_their_presence_earlier_in_the_string_is_unknown + appendStr(str) { + const buf8 = this._buffer8; + const buf32 = this._buffer32; + let bufLen = this._bufferLength; + let code; + let i; + for (i = 0; i < str.length; i += 1) { + code = str.charCodeAt(i); + if (code < 128) { + buf8[bufLen++] = code; + } + else if (code < 0x800) { + buf8[bufLen++] = (code >>> 6) + 0xC0; + buf8[bufLen++] = code & 0x3F | 0x80; + } + else if (code < 0xD800 || code > 0xDBFF) { + buf8[bufLen++] = (code >>> 12) + 0xE0; + buf8[bufLen++] = (code >>> 6 & 0x3F) | 0x80; + buf8[bufLen++] = (code & 0x3F) | 0x80; + } + else { + code = ((code - 0xD800) * 0x400) + (str.charCodeAt(++i) - 0xDC00) + 0x10000; + if (code > 0x10FFFF) { + throw new Error('Unicode standard supports code points up to U+10FFFF'); + } + buf8[bufLen++] = (code >>> 18) + 0xF0; + buf8[bufLen++] = (code >>> 12 & 0x3F) | 0x80; + buf8[bufLen++] = (code >>> 6 & 0x3F) | 0x80; + buf8[bufLen++] = (code & 0x3F) | 0x80; + } + if (bufLen >= 64) { + this._dataLength += 64; + Md5._md5cycle(this._state, buf32); + bufLen -= 64; + buf32[0] = buf32[16]; + } + } + this._bufferLength = bufLen; + return this; + } + appendAsciiStr(str) { + const buf8 = this._buffer8; + const buf32 = this._buffer32; + let bufLen = this._bufferLength; + let i; + let j = 0; + for (;;) { + i = Math.min(str.length - j, 64 - bufLen); + while (i--) { + buf8[bufLen++] = str.charCodeAt(j++); + } + if (bufLen < 64) { + break; + } + this._dataLength += 64; + Md5._md5cycle(this._state, buf32); + bufLen = 0; + } + this._bufferLength = bufLen; + return this; + } + appendByteArray(input) { + const buf8 = this._buffer8; + const buf32 = this._buffer32; + let bufLen = this._bufferLength; + let i; + let j = 0; + for (;;) { + i = Math.min(input.length - j, 64 - bufLen); + while (i--) { + buf8[bufLen++] = input[j++]; + } + if (bufLen < 64) { + break; + } + this._dataLength += 64; + Md5._md5cycle(this._state, buf32); + bufLen = 0; + } + this._bufferLength = bufLen; + return this; + } + getState() { + const self = this; + const s = self._state; + return { + buffer: String.fromCharCode.apply(null, self._buffer8), + buflen: self._bufferLength, + length: self._dataLength, + state: [s[0], s[1], s[2], s[3]] + }; + } + setState(state) { + const buf = state.buffer; + const x = state.state; + const s = this._state; + let i; + this._dataLength = state.length; + this._bufferLength = state.buflen; + s[0] = x[0]; + s[1] = x[1]; + s[2] = x[2]; + s[3] = x[3]; + for (i = 0; i < buf.length; i += 1) { + this._buffer8[i] = buf.charCodeAt(i); + } + } + end(raw = false) { + const bufLen = this._bufferLength; + const buf8 = this._buffer8; + const buf32 = this._buffer32; + const i = (bufLen >> 2) + 1; + let dataBitsLen; + this._dataLength += bufLen; + buf8[bufLen] = 0x80; + buf8[bufLen + 1] = buf8[bufLen + 2] = buf8[bufLen + 3] = 0; + buf32.set(Md5.buffer32Identity.subarray(i), i); + if (bufLen > 55) { + Md5._md5cycle(this._state, buf32); + buf32.set(Md5.buffer32Identity); + } + // Do the final computation based on the tail and length + // Beware that the final length may not fit in 32 bits so we take care of that + dataBitsLen = this._dataLength * 8; + if (dataBitsLen <= 0xFFFFFFFF) { + buf32[14] = dataBitsLen; + } + else { + const matches = dataBitsLen.toString(16).match(/(.*?)(.{0,8})$/); + if (matches === null) { + return; + } + const lo = parseInt(matches[2], 16); + const hi = parseInt(matches[1], 16) || 0; + buf32[14] = lo; + buf32[15] = hi; + } + Md5._md5cycle(this._state, buf32); + return raw ? this._state : Md5._hex(this._state); + } +} +// Private Static Variables +Md5.stateIdentity = new Int32Array([1732584193, -271733879, -1732584194, 271733878]); +Md5.buffer32Identity = new Int32Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); +Md5.hexChars = '0123456789abcdef'; +Md5.hexOut = []; +// Permanent instance is to use for one-call hashing +Md5.onePassHasher = new Md5(); +if (Md5.hashStr('hello') !== '5d41402abc4b2a76b9719d911017c592') { + console.error('Md5 self test failed.'); +} + + +/***/ }), +/* 37 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 38 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 39 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 40 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "constructOutgoingResponse", function() { return constructOutgoingResponse; }); +/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(32); + +/** + * 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) { + const CRLF = "\r\n"; + if (options.statusCode < 100 || options.statusCode > 699) { + throw new TypeError("Invalid statusCode: " + options.statusCode); + } + const reasonPhrase = options.reasonPhrase ? options.reasonPhrase : Object(_utils__WEBPACK_IMPORTED_MODULE_0__["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 + let 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 + const fromHeader = "From: " + message.getHeader("From") + CRLF; + const callIdHeader = "Call-ID: " + message.callId + CRLF; + const cSeqHeader = "CSeq: " + message.cseq + " " + message.method + CRLF; + const viaHeaders = message.getHeaders("via").reduce((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 + let toHeader = "To: " + message.getHeader("to"); + if (options.statusCode > 100 && !message.parseHeader("to").hasParam("tag")) { + let 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 = Object(_utils__WEBPACK_IMPORTED_MODULE_0__["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... + let supportedHeader = ""; + if (options.supported) { + supportedHeader = "Supported: " + options.supported.join(", ") + CRLF; + } + // FIXME: TODO: needs review... + let userAgentHeader = ""; + if (options.userAgent) { + userAgentHeader = "User-Agent: " + options.userAgent + CRLF; + } + let extensionHeaders = ""; + if (options.extraHeaders) { + extensionHeaders = options.extraHeaders.reduce((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: " + Object(_utils__WEBPACK_IMPORTED_MODULE_0__["utf8Length"])(options.body.content) + CRLF + CRLF; + response += options.body.content; + } + else { + response += "Content-Length: " + 0 + CRLF + CRLF; + } + return { message: response }; +} + + +/***/ }), +/* 41 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Parser", function() { return Parser; }); +/* harmony import */ var _grammar__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9); +/* harmony import */ var _incoming_request_message__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(30); +/* harmony import */ var _incoming_response_message__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(33); +/* eslint-disable no-inner-declarations */ +/* eslint-disable @typescript-eslint/no-namespace */ + + + +/** + * Extract and parse every header of a SIP message. + * @internal + */ +var Parser; +(function (Parser) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + function getHeader(data, headerStart) { + // 'start' position of the header. + let start = headerStart; + // 'end' position of the header. + let end = 0; + // 'partial end' position of the header. + let 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, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + data, headerStart, headerEnd) { + const hcolonIndex = data.indexOf(":", headerStart); + const headerName = data.substring(headerStart, hcolonIndex).trim(); + const headerValue = data.substring(hcolonIndex + 1, headerEnd).trim(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let 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 = _grammar__WEBPACK_IMPORTED_MODULE_0__["Grammar"].parse(headerValue, "Record_Route"); + if (parsed === -1) { + parsed = undefined; + break; + } + if (!(parsed instanceof Array)) { + parsed = undefined; + break; + } + parsed.forEach((header) => { + message.addHeader("record-route", headerValue.substring(header.position, header.offset)); + message.headers["Record-Route"][message.getHeaders("record-route").length - 1].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 = _grammar__WEBPACK_IMPORTED_MODULE_0__["Grammar"].parse(headerValue, "Contact"); + if (parsed === -1) { + parsed = undefined; + break; + } + if (!(parsed instanceof Array)) { + parsed = undefined; + break; + } + parsed.forEach((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 _incoming_response_message__WEBPACK_IMPORTED_MODULE_2__["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; + function parseMessage(data, logger) { + let headerStart = 0; + let 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. + const firstLine = data.substring(0, headerEnd); + const parsed = _grammar__WEBPACK_IMPORTED_MODULE_0__["Grammar"].parse(firstLine, "Request_Response"); + let message; + if (parsed === -1) { + logger.warn('error parsing first line of SIP message: "' + firstLine + '"'); + return; + } + else if (!parsed.status_code) { + message = new _incoming_request_message__WEBPACK_IMPORTED_MODULE_1__["IncomingRequestMessage"](); + message.method = parsed.method; + message.ruri = parsed.uri; + } + else { + message = new _incoming_response_message__WEBPACK_IMPORTED_MODULE_2__["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. + let bodyStart; + // eslint-disable-next-line no-constant-condition + 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; + } + const parsedHeader = parseHeader(message, data, headerStart, headerEnd); + if (parsedHeader && parsedHeader !== true) { + logger.error(parsedHeader.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 || (Parser = {})); + + +/***/ }), +/* 42 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 43 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SessionDialog", function() { return SessionDialog; }); +/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); +/* harmony import */ var _session__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(44); +/* harmony import */ var _timers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(47); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(48); +/* harmony import */ var _user_agents_bye_user_agent_client__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(62); +/* harmony import */ var _user_agents_bye_user_agent_server__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(64); +/* harmony import */ var _user_agents_info_user_agent_client__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(66); +/* harmony import */ var _user_agents_info_user_agent_server__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(67); +/* harmony import */ var _user_agents_message_user_agent_client__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(68); +/* harmony import */ var _user_agents_message_user_agent_server__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(69); +/* harmony import */ var _user_agents_notify_user_agent_client__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(70); +/* harmony import */ var _user_agents_notify_user_agent_server__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(71); +/* harmony import */ var _user_agents_prack_user_agent_client__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(72); +/* harmony import */ var _user_agents_prack_user_agent_server__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(73); +/* harmony import */ var _user_agents_re_invite_user_agent_client__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(74); +/* harmony import */ var _user_agents_re_invite_user_agent_server__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(75); +/* harmony import */ var _user_agents_refer_user_agent_client__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(76); +/* harmony import */ var _user_agents_refer_user_agent_server__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(77); +/* harmony import */ var _dialog__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(7); + + + + + + + + + + + + + + + + + + + +/** + * Session Dialog. + * @public + */ +class SessionDialog extends _dialog__WEBPACK_IMPORTED_MODULE_18__["Dialog"] { + constructor(initialTransaction, core, state, delegate) { + super(core, state); + this.initialTransaction = initialTransaction; + /** The state of the offer/answer exchange. */ + this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Initial; + /** True if waiting for an ACK to the initial transaction 2xx (UAS only). */ + this.ackWait = false; + /** True if processing an ACK to the initial transaction 2xx (UAS only). */ + this.ackProcessing = false; + this.delegate = delegate; + if (initialTransaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["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`); + } + dispose() { + super.dispose(); + this._signalingState = _session__WEBPACK_IMPORTED_MODULE_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`); + } + // FIXME: Need real state machine + get sessionState() { + if (this.early) { + return _session__WEBPACK_IMPORTED_MODULE_1__["SessionState"].Early; + } + else if (this.ackWait) { + return _session__WEBPACK_IMPORTED_MODULE_1__["SessionState"].AckWait; + } + else if (this._signalingState === _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Closed) { + return _session__WEBPACK_IMPORTED_MODULE_1__["SessionState"].Terminated; + } + else { + return _session__WEBPACK_IMPORTED_MODULE_1__["SessionState"].Confirmed; + } + } + /** The state of the offer/answer exchange. */ + get signalingState() { + return this._signalingState; + } + /** The current offer. Undefined unless signaling state HaveLocalOffer, HaveRemoteOffer, of Stable. */ + get offer() { + return this._offer; + } + /** The current answer. Undefined unless signaling state Stable. */ + get answer() { + return this._answer; + } + /** Confirm the dialog. Only matters if dialog is currently early. */ + confirm() { + // When we're confirmed start the retransmitting whatever + // the 2xx final response that may have confirmed us. + if (this.early) { + this.start2xxRetransmissionTimer(); + } + super.confirm(); + } + /** Re-confirm the dialog. Only matters if handling re-INVITE request. */ + reConfirm() { + // 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. + */ + ack(options = {}) { + this.logger.log(`INVITE dialog ${this.id} sending ACK request`); + let transaction; + if (this.reinviteUserAgentClient) { + // We're sending ACK for a re-INVITE + if (!(this.reinviteUserAgentClient.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["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__WEBPACK_IMPORTED_MODULE_3__["InviteClientTransaction"])) { + throw new Error("Initial transaction not instance of InviteClientTransaction."); + } + transaction = this.initialTransaction; + } + const message = this.createOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["C"].ACK, { + cseq: transaction.request.cseq, + extraHeaders: options.extraHeaders, + body: options.body + }); + transaction.ackResponse(message); // See InviteClientTransaction for details. + this.signalingStateTransition(message); + return { 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. + */ + bye(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__WEBPACK_IMPORTED_MODULE_3__["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__WEBPACK_IMPORTED_MODULE_3__["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 _user_agents_bye_user_agent_client__WEBPACK_IMPORTED_MODULE_4__["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. + */ + info(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 _user_agents_info_user_agent_client__WEBPACK_IMPORTED_MODULE_6__["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 + */ + invite(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 _user_agents_re_invite_user_agent_client__WEBPACK_IMPORTED_MODULE_14__["ReInviteUserAgentClient"](this, delegate, options); + } + /** + * A UAC MAY associate a MESSAGE request with an existing dialog. If a + * MESSAGE request is sent within a dialog, it is "associated" with any + * media session or sessions associated with that dialog. + * https://tools.ietf.org/html/rfc3428#section-4 + * @param options - Options bucket. + */ + message(delegate, options) { + this.logger.log(`INVITE dialog ${this.id} sending MESSAGE request`); + if (this.early) { + // FIXME: TODO: This should throw a proper exception. + throw new Error("Dialog not confirmed."); + } + const message = this.createOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["C"].MESSAGE, options); + return new _user_agents_message_user_agent_client__WEBPACK_IMPORTED_MODULE_8__["MessageUserAgentClient"](this.core, message, delegate); + } + /** + * 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, 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 _user_agents_notify_user_agent_client__WEBPACK_IMPORTED_MODULE_10__["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. + */ + prack(delegate, options) { + this.logger.log(`INVITE dialog ${this.id} sending PRACK request`); + return new _user_agents_prack_user_agent_client__WEBPACK_IMPORTED_MODULE_12__["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. + */ + refer(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 _user_agents_refer_user_agent_client__WEBPACK_IMPORTED_MODULE_16__["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. + */ + receiveRequest(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__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_3__["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) { + const promiseOrVoid = this.delegate.onAck({ message }); + if (promiseOrVoid instanceof Promise) { + this.ackProcessing = true; // make sure this is always reset to false + promiseOrVoid.then(() => (this.ackProcessing = false)).catch(() => (this.ackProcessing = false)); + } + } + 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; + } + // Request within a dialog common processing. + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + super.receiveRequest(message); + // Handle various INVITE related cross-over, glare and race conditions + if (message.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE) { + // Hopefully this message is helpful... + const warning = () => { + const reason = this.ackWait ? "waiting for initial ACK" : "processing initial ACK"; + this.logger.warn(`INVITE dialog ${this.id} received re-INVITE while ${reason}`); + let msg = "RFC 5407 suggests the following to avoid this race condition... "; + msg += " Note: Implementation issues are outside the scope of this document,"; + msg += " but the following tip is provided for avoiding race conditions of"; + msg += " this type. The caller can delay sending re-INVITE F6 for some period"; + msg += " of time (2 seconds, perhaps), after which the caller can reasonably"; + msg += " assume that its ACK has been received. Implementors can decouple the"; + msg += " actions of the user (e.g., pressing the hold button) from the actions"; + msg += " of the protocol (the sending of re-INVITE F6), so that the UA can"; + msg += " behave like this. In this case, it is the implementor's choice as to"; + msg += " how long to wait. In most cases, such an implementation may be"; + msg += " useful to prevent the type of race condition shown in this section."; + msg += " This document expresses no preference about whether or not they"; + msg += " should wait for an ACK to be delivered. After considering the impact"; + msg += " on user experience, implementors should decide whether or not to wait"; + msg += " for a while, because the user experience depends on the"; + msg += " implementation and has no direct bearing on protocol behavior."; + this.logger.warn(msg); + return; // drop re-INVITE request message + }; + // 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 + const retryAfter = Math.floor(Math.random() * 10) + 1; + const extraHeaders = [`Retry-After: ${retryAfter}`]; + // There may be ONLY ONE offer/answer negotiation in progress for a + // single dialog at any point in time. Section 4 explains how to ensure + // this. + // https://tools.ietf.org/html/rfc6337#section-2.2 + if (this.ackProcessing) { + // UAS-IsI: While an INVITE server transaction is incomplete or ACK + // transaction associated with an offer/answer is incomplete, + // a UA must reject another INVITE request with a 500 + // response. + // https://tools.ietf.org/html/rfc6337#section-4.3 + this.core.replyStateless(message, { statusCode: 500, extraHeaders }); + warning(); + return; + } + // 3.1.4. Callee Receives re-INVITE (Established State) While in the + // Moratorium State (Case 1) + // https://tools.ietf.org/html/rfc5407#section-3.1.4 + // 3.1.5. Callee Receives re-INVITE (Established State) While in the + // Moratorium State (Case 2) + // https://tools.ietf.org/html/rfc5407#section-3.1.5 + if (this.ackWait && this.signalingState !== _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable) { + // This scenario is basically the same as that of Section 3.1.4, but + // differs in sending an offer in the 200 and an answer in the ACK. In + // contrast to the previous case, the offer in the 200 (F3) and the + // offer in the re-INVITE (F6) collide with each other. + // + // Bob sends a 491 to the re-INVITE (F6) since he is not able to + // properly handle a new request until he receives an answer. (Note: + // 500 with a Retry-After header may be returned if the 491 response is + // understood to indicate request collision. However, 491 is + // recommended here because 500 applies to so many cases that it is + // difficult to determine what the real problem was.) + // https://tools.ietf.org/html/rfc5407#section-3.1.5 + // UAS-IsI: While an INVITE server transaction is incomplete or ACK + // transaction associated with an offer/answer is incomplete, + // a UA must reject another INVITE request with a 500 + // response. + // https://tools.ietf.org/html/rfc6337#section-4.3 + this.core.replyStateless(message, { statusCode: 500, extraHeaders }); + warning(); + return; + } + // 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) { + this.core.replyStateless(message, { statusCode: 500, 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; + } + } + // 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__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE) { + // FIXME: parser needs to be typed... + const contact = message.parseHeader("contact"); + if (!contact) { + // TODO: Review to make sure this will never happen + throw new Error("Contact undefined."); + } + if (!(contact instanceof _messages__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_0__["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 + { + const uas = new _user_agents_bye_user_agent_server__WEBPACK_IMPORTED_MODULE_5__["ByeUserAgentServer"](this, message); + this.delegate && this.delegate.onBye ? this.delegate.onBye(uas) : uas.accept(); + this.dispose(); + } + break; + case _messages__WEBPACK_IMPORTED_MODULE_0__["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. + { + const uas = new _user_agents_info_user_agent_server__WEBPACK_IMPORTED_MODULE_7__["InfoUserAgentServer"](this, message); + this.delegate && this.delegate.onInfo + ? this.delegate.onInfo(uas) + : uas.reject({ + statusCode: 469, + extraHeaders: ["Recv-Info :"] + }); + } + break; + case _messages__WEBPACK_IMPORTED_MODULE_0__["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 + { + const uas = new _user_agents_re_invite_user_agent_server__WEBPACK_IMPORTED_MODULE_15__["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__WEBPACK_IMPORTED_MODULE_0__["C"].MESSAGE: + { + const uas = new _user_agents_message_user_agent_server__WEBPACK_IMPORTED_MODULE_9__["MessageUserAgentServer"](this.core, message); + this.delegate && this.delegate.onMessage ? this.delegate.onMessage(uas) : uas.accept(); + } + break; + case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].NOTIFY: + // https://tools.ietf.org/html/rfc3515#section-2.4.4 + { + const uas = new _user_agents_notify_user_agent_server__WEBPACK_IMPORTED_MODULE_11__["NotifyUserAgentServer"](this, message); + this.delegate && this.delegate.onNotify ? this.delegate.onNotify(uas) : uas.accept(); + } + break; + case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].PRACK: + // https://tools.ietf.org/html/rfc3262#section-4 + { + const uas = new _user_agents_prack_user_agent_server__WEBPACK_IMPORTED_MODULE_13__["PrackUserAgentServer"](this, message); + this.delegate && this.delegate.onPrack ? this.delegate.onPrack(uas) : uas.accept(); + } + break; + case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].REFER: + // https://tools.ietf.org/html/rfc3515#section-2.4.2 + { + const uas = new _user_agents_refer_user_agent_server__WEBPACK_IMPORTED_MODULE_17__["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; + } + } + /** + * Guard against out of order reliable provisional responses and retransmissions. + * Returns false if the response should be discarded, otherwise true. + * @param message - Incoming response message within this dialog. + */ + reliableSequenceGuard(message) { + const 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 + const requireHeader = message.getHeader("require"); + const rseqHeader = message.getHeader("rseq"); + const 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 + this.rseq = this.rseq ? this.rseq + 1 : rseq; + } + } + return true; + } + /** + * If not in a stable signaling state, rollback to prior stable signaling state. + */ + signalingStateRollback() { + if (this._signalingState === _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveLocalOffer || + this.signalingState === _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveRemoteOffer) { + if (this._rollbackOffer && this._rollbackAnswer) { + this._signalingState = _session__WEBPACK_IMPORTED_MODULE_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. + */ + signalingStateTransition(message) { + const body = Object(_messages__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_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__WEBPACK_IMPORTED_MODULE_0__["IncomingRequestMessage"]) { + switch (this._signalingState) { + case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Initial: + case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable: + this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveRemoteOffer; + this._offer = body; + this._answer = undefined; + break; + case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveLocalOffer: + this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable; + this._answer = body; + break; + case _session__WEBPACK_IMPORTED_MODULE_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__WEBPACK_IMPORTED_MODULE_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__WEBPACK_IMPORTED_MODULE_0__["IncomingResponseMessage"]) { + switch (this._signalingState) { + case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Initial: + case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable: + this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveRemoteOffer; + this._offer = body; + this._answer = undefined; + break; + case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveLocalOffer: + this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable; + this._answer = body; + break; + case _session__WEBPACK_IMPORTED_MODULE_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__WEBPACK_IMPORTED_MODULE_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__WEBPACK_IMPORTED_MODULE_0__["OutgoingRequestMessage"]) { + switch (this._signalingState) { + case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Initial: + case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable: + this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveLocalOffer; + this._offer = body; + this._answer = undefined; + break; + case _session__WEBPACK_IMPORTED_MODULE_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__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveRemoteOffer: + this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable; + this._answer = body; + break; + case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Closed: + break; + default: + throw new Error("Unexpected signaling state."); + } + } + // We're in UAS role, sending outgoing response with session description + if (Object(_messages__WEBPACK_IMPORTED_MODULE_0__["isBody"])(message)) { + switch (this._signalingState) { + case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Initial: + case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable: + this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveLocalOffer; + this._offer = body; + this._answer = undefined; + break; + case _session__WEBPACK_IMPORTED_MODULE_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__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveRemoteOffer: + this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable; + this._answer = body; + break; + case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Closed: + break; + default: + throw new Error("Unexpected signaling state."); + } + } + } + start2xxRetransmissionTimer() { + if (this.initialTransaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"]) { + const transaction = 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 + let timeout = _timers__WEBPACK_IMPORTED_MODULE_2__["Timers"].T1; + const retransmission = () => { + if (!this.ackWait) { + this.invite2xxTimer = undefined; + return; + } + this.logger.log("No ACK for 2xx response received, attempting retransmission"); + transaction.retransmitAcceptedResponse(); + timeout = Math.min(timeout * 2, _timers__WEBPACK_IMPORTED_MODULE_2__["Timers"].T2); + this.invite2xxTimer = setTimeout(retransmission, timeout); + }; + this.invite2xxTimer = setTimeout(retransmission, timeout); + // 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 + const stateChanged = () => { + if (transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Terminated) { + transaction.removeStateChangeListener(stateChanged); + 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.addStateChangeListener(stateChanged); + } + } + // FIXME: Refactor + startReInvite2xxRetransmissionTimer() { + if (this.reinviteUserAgentServer && this.reinviteUserAgentServer.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"]) { + const transaction = 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 + let timeout = _timers__WEBPACK_IMPORTED_MODULE_2__["Timers"].T1; + const retransmission = () => { + if (!this.reinviteUserAgentServer) { + this.invite2xxTimer = undefined; + return; + } + this.logger.log("No ACK for 2xx response received, attempting retransmission"); + transaction.retransmitAcceptedResponse(); + timeout = Math.min(timeout * 2, _timers__WEBPACK_IMPORTED_MODULE_2__["Timers"].T2); + this.invite2xxTimer = setTimeout(retransmission, timeout); + }; + this.invite2xxTimer = setTimeout(retransmission, timeout); + // 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 + const stateChanged = () => { + if (transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Terminated) { + transaction.removeStateChangeListener(stateChanged); + if (this.invite2xxTimer) { + clearTimeout(this.invite2xxTimer); + this.invite2xxTimer = undefined; + } + if (this.reinviteUserAgentServer) { + // FIXME: TODO: What to do here + } + } + }; + transaction.addStateChangeListener(stateChanged); + } + } +} + + +/***/ }), +/* 44 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _session__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(45); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionState", function() { return _session__WEBPACK_IMPORTED_MODULE_0__["SessionState"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SignalingState", function() { return _session__WEBPACK_IMPORTED_MODULE_0__["SignalingState"]; }); + +/* harmony import */ var _session_delegate__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(46); +/* empty/unused harmony star reexport */ + + + +/***/ }), +/* 45 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SessionState", function() { return SessionState; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SignalingState", function() { return SignalingState; }); +/** + * 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 || (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 || (SignalingState = {})); + + +/***/ }), +/* 46 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 47 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Timers", function() { return Timers; }); +const T1 = 500; +const T2 = 4000; +const T4 = 5000; +/** + * Timers. + * @public + */ +const Timers = { + T1, + T2, + 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 +}; + + +/***/ }), +/* 48 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _client_transaction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(49); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ClientTransaction", function() { return _client_transaction__WEBPACK_IMPORTED_MODULE_0__["ClientTransaction"]; }); + +/* harmony import */ var _invite_client_transaction__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(55); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InviteClientTransaction", function() { return _invite_client_transaction__WEBPACK_IMPORTED_MODULE_1__["InviteClientTransaction"]; }); + +/* harmony import */ var _invite_server_transaction__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(57); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InviteServerTransaction", function() { return _invite_server_transaction__WEBPACK_IMPORTED_MODULE_2__["InviteServerTransaction"]; }); + +/* harmony import */ var _non_invite_client_transaction__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(59); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NonInviteClientTransaction", function() { return _non_invite_client_transaction__WEBPACK_IMPORTED_MODULE_3__["NonInviteClientTransaction"]; }); + +/* harmony import */ var _non_invite_server_transaction__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(60); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NonInviteServerTransaction", function() { return _non_invite_server_transaction__WEBPACK_IMPORTED_MODULE_4__["NonInviteServerTransaction"]; }); + +/* empty/unused harmony star reexport *//* harmony import */ var _server_transaction__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(58); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ServerTransaction", function() { return _server_transaction__WEBPACK_IMPORTED_MODULE_5__["ServerTransaction"]; }); + +/* harmony import */ var _transaction_state__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(56); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransactionState", function() { return _transaction_state__WEBPACK_IMPORTED_MODULE_6__["TransactionState"]; }); + +/* harmony import */ var _transaction_user__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(61); +/* empty/unused harmony star reexport *//* harmony import */ var _transaction__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(50); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Transaction", function() { return _transaction__WEBPACK_IMPORTED_MODULE_8__["Transaction"]; }); + + + + + + + + + + + + + +/***/ }), +/* 49 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ClientTransaction", function() { return ClientTransaction; }); +/* harmony import */ var _transaction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(50); + +/** + * 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 + */ +class ClientTransaction extends _transaction__WEBPACK_IMPORTED_MODULE_0__["Transaction"] { + constructor(_request, transport, user, state, loggerCategory) { + super(transport, user, ClientTransaction.makeId(_request), state, loggerCategory); + 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 + _request.setViaHeader(this.id, transport.protocol); + } + static makeId(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); + } + } + /** The outgoing request the transaction handling. */ + get request() { + return this._request; + } + /** + * 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 + */ + onRequestTimeout() { + if (this.user.onRequestTimeout) { + this.user.onRequestTimeout(); + } + } +} + + +/***/ }), +/* 50 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Transaction", function() { return Transaction; }); +/* harmony import */ var _exceptions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(51); + +/** + * 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 + */ +class Transaction { + constructor(_transport, _user, _id, _state, loggerCategory) { + this._transport = _transport; + this._user = _user; + this._id = _id; + this._state = _state; + this.listeners = new Array(); + this.logger = _user.loggerFactory.getLogger(loggerCategory, _id); + this.logger.debug(`Constructing ${this.typeToString()} with id ${this.id}.`); + } + /** + * 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() { + this.logger.debug(`Destroyed ${this.typeToString()} with id ${this.id}.`); + } + /** Transaction id. */ + get id() { + return this._id; + } + /** Transaction kind. Deprecated. */ + get kind() { + throw new Error("Invalid kind."); + } + /** Transaction state. */ + get state() { + return this._state; + } + /** Transaction transport. */ + get transport() { + return this._transport; + } + /** + * Sets up a function that will be called whenever the transaction state changes. + * @param listener - Callback function. + * @param options - An options object that specifies characteristics about the listener. + * If once true, indicates that the listener should be invoked at most once after being added. + * If once true, the listener would be automatically removed when invoked. + */ + addStateChangeListener(listener, options) { + const onceWrapper = () => { + this.removeStateChangeListener(onceWrapper); + listener(); + }; + (options === null || options === void 0 ? void 0 : options.once) === true ? this.listeners.push(onceWrapper) : this.listeners.push(listener); + } + /** + * This is currently public so tests may spy on it. + * @internal + */ + notifyStateChangeListeners() { + this.listeners.slice().forEach((listener) => listener()); + } + /** + * Removes a listener previously registered with addStateListener. + * @param listener - Callback function. + */ + removeStateChangeListener(listener) { + this.listeners = this.listeners.filter((l) => l !== listener); + } + logTransportError(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. + */ + send(message) { + return this.transport.send(message).catch((error) => { + // If the transport rejects, it SHOULD reject with a TransportError. + // But the transport may be external code, so we are careful + // make sure we convert it to a TransportError if need be. + if (error instanceof _exceptions__WEBPACK_IMPORTED_MODULE_0__["TransportError"]) { + this.onTransportError(error); + throw error; + } + let transportError; + if (error && typeof error.message === "string") { + transportError = new _exceptions__WEBPACK_IMPORTED_MODULE_0__["TransportError"](error.message); + } + else { + transportError = new _exceptions__WEBPACK_IMPORTED_MODULE_0__["TransportError"](); + } + this.onTransportError(transportError); + throw transportError; + }); + } + setState(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.notifyStateChangeListeners(); + } + typeToString() { + return "UnknownType"; + } +} + + +/***/ }), +/* 51 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _exception__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(52); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Exception", function() { return _exception__WEBPACK_IMPORTED_MODULE_0__["Exception"]; }); + +/* harmony import */ var _transaction_state_error__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(53); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransactionStateError", function() { return _transaction_state_error__WEBPACK_IMPORTED_MODULE_1__["TransactionStateError"]; }); + +/* harmony import */ var _transport_error__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(54); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransportError", function() { return _transport_error__WEBPACK_IMPORTED_MODULE_2__["TransportError"]; }); + + + + + + +/***/ }), +/* 52 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Exception", function() { return Exception; }); +/** + * 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 + */ +class Exception extends Error { + constructor(message) { + super(message); // 'Error' breaks prototype chain here + Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain + } +} + + +/***/ }), +/* 53 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TransactionStateError", function() { return TransactionStateError; }); +/* harmony import */ var _exception__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(52); + +/** + * Indicates that the operation could not be completed given the current transaction state. + * @public + */ +class TransactionStateError extends _exception__WEBPACK_IMPORTED_MODULE_0__["Exception"] { + constructor(message) { + super(message ? message : "Transaction state error."); + } +} + + +/***/ }), +/* 54 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TransportError", function() { return TransportError; }); +/* harmony import */ var _exception__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(52); + +/** + * Transport error. + * @public + */ +class TransportError extends _exception__WEBPACK_IMPORTED_MODULE_0__["Exception"] { + constructor(message) { + super(message ? message : "Unspecified transport error."); + } +} + + +/***/ }), +/* 55 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InviteClientTransaction", function() { return InviteClientTransaction; }); +/* harmony import */ var _timers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(47); +/* harmony import */ var _client_transaction__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(49); +/* harmony import */ var _transaction_state__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(56); + + + +/** + * 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 + */ +class InviteClientTransaction extends _client_transaction__WEBPACK_IMPORTED_MODULE_1__["ClientTransaction"] { + /** + * 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, transport, user) { + super(request, transport, user, _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Calling, "sip.transaction.ict"); + /** + * 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(() => this.timerB(), _timers__WEBPACK_IMPORTED_MODULE_0__["Timers"].TIMER_B); + this.send(request.toString()).catch((error) => { + this.logTransportError(error, "Failed to send initial outgoing request."); + }); + } + /** + * Destructor. + */ + dispose() { + 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.dispose(); + } + /** Transaction kind. Deprecated. */ + get kind() { + return "ict"; + } + /** + * 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) { + const toTag = ack.toTag; + if (!toTag) { + throw new Error("To tag undefined."); + } + const id = "z9hG4bK" + Math.floor(Math.random() * 10000000); + ack.setViaHeader(id, this.transport.protocol); + this.ackRetransmissionCache.set(toTag, ack); // Add to ACK retransmission cache + this.send(ack.toString()).catch((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. + */ + receiveResponse(response) { + const statusCode = response.statusCode; + if (!statusCode || statusCode < 100 || statusCode > 699) { + throw new Error(`Invalid status code ${statusCode}`); + } + switch (this.state) { + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed); + this.ack(response); + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed); + this.ack(response); + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["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. + const ack = this.ackRetransmissionCache.get(response.toTag); + if (ack) { + this.send(ack.toString()).catch((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__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_2__["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 + const 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. + */ + onTransportError(error) { + if (this.user.onTransportError) { + this.user.onTransportError(error); + } + this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated, true); + } + /** For logging. */ + typeToString() { + return "INVITE client transaction"; + } + ack(response) { + // 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 + const ruri = this.request.ruri; + const callId = this.request.callId; + const cseq = this.request.cseq; + const from = this.request.getHeader("from"); + const to = response.getHeader("to"); + const via = this.request.getHeader("via"); + const 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."); + } + let 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((error) => { + this.logTransportError(error, "Failed to send ACK to non-2xx response."); + }); + return; + } + /** + * Execute a state transition. + * @param newState - New state. + */ + stateTransition(newState, dueToTransportError = false) { + // Assert valid state transitions. + const invalidStateTransition = () => { + throw new Error(`Invalid state transition from ${this.state} to ${newState}`); + }; + switch (newState) { + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Calling: + invalidStateTransition(); + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding: + if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Calling) { + invalidStateTransition(); + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Accepted: + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed: + if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Calling && this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding) { + invalidStateTransition(); + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated: + if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Calling && + this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Accepted && + this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed) { + this.D = setTimeout(() => this.timerD(), _timers__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Accepted) { + this.M = setTimeout(() => this.timerM(), _timers__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_2__["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 + */ + timerA() { + // 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 + */ + timerB() { + this.logger.debug(`Timer B expired for INVITE client transaction ${this.id}.`); + if (this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Calling) { + this.onRequestTimeout(); + this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["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 + */ + timerD() { + this.logger.debug(`Timer D expired for INVITE client transaction ${this.id}.`); + if (this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed) { + this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["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 + */ + timerM() { + this.logger.debug(`Timer M expired for INVITE client transaction ${this.id}.`); + if (this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Accepted) { + this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated); + } + } +} + + +/***/ }), +/* 56 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TransactionState", function() { return TransactionState; }); +/** + * 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 || (TransactionState = {})); + + +/***/ }), +/* 57 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InviteServerTransaction", function() { return InviteServerTransaction; }); +/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); +/* harmony import */ var _timers__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(47); +/* harmony import */ var _server_transaction__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(58); +/* harmony import */ var _transaction_state__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(56); + + + + +/** + * INVITE Server Transaction. + * @remarks + * https://tools.ietf.org/html/rfc3261#section-17.2.1 + * @public + */ +class InviteServerTransaction extends _server_transaction__WEBPACK_IMPORTED_MODULE_2__["ServerTransaction"] { + /** + * 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, transport, user) { + super(request, transport, user, _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding, "sip.transaction.ist"); + } + /** + * Destructor. + */ + dispose() { + 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.dispose(); + } + /** Transaction kind. Deprecated. */ + get kind() { + return "ist"; + } + /** + * Receive requests from transport matching this transaction. + * @param request - Request matching this transaction. + */ + receiveRequest(request) { + switch (this.state) { + case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["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__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE) { + if (this.lastProvisionalResponse) { + this.send(this.lastProvisionalResponse).catch((error) => { + this.logTransportError(error, "Failed to send retransmission of provisional response."); + }); + } + return; + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["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__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE) { + return; + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["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__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE) { + if (!this.lastFinalResponse) { + throw new Error("Last final response undefined."); + } + this.send(this.lastFinalResponse).catch((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__WEBPACK_IMPORTED_MODULE_0__["C"].ACK) { + this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Confirmed); + return; + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["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__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE || request.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].ACK) { + return; + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Terminated: + // For good measure absorb any additional messages that arrive (should not happen). + if (request.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE || request.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].ACK) { + return; + } + break; + default: + throw new Error(`Invalid state ${this.state}`); + } + const 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. + */ + receiveResponse(statusCode, response) { + if (statusCode < 100 || statusCode > 699) { + throw new Error(`Invalid status code ${statusCode}`); + } + switch (this.state) { + case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["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((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__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Accepted); + this.send(response).catch((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__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Completed); + this.send(response).catch((error) => { + this.logTransportError(error, "Failed to send non-2xx final response."); + }); + return; + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["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((error) => { + this.logTransportError(error, "Failed to send 2xx response."); + }); + return; + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Completed: + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Confirmed: + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Terminated: + break; + default: + throw new Error(`Invalid state ${this.state}`); + } + const 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. + */ + retransmitAcceptedResponse() { + if (this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Accepted && this.lastFinalResponse) { + this.send(this.lastFinalResponse).catch((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 + */ + onTransportError(error) { + if (this.user.onTransportError) { + this.user.onTransportError(error); + } + } + /** For logging. */ + typeToString() { + return "INVITE server transaction"; + } + /** + * Execute a state transition. + * @param newState - New state. + */ + stateTransition(newState) { + // Assert valid state transitions. + const invalidStateTransition = () => { + throw new Error(`Invalid state transition from ${this.state} to ${newState}`); + }; + switch (newState) { + case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding: + invalidStateTransition(); + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Accepted: + case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Completed: + if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding) { + invalidStateTransition(); + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Confirmed: + if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Completed) { + invalidStateTransition(); + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Terminated: + if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Accepted && + this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Completed && + this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Confirmed) { + invalidStateTransition(); + } + break; + default: + invalidStateTransition(); + } + // On any state transition, stop resending provisional 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__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Accepted) { + this.L = setTimeout(() => this.timerL(), _timers__WEBPACK_IMPORTED_MODULE_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__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Completed) { + // FIXME: Missing timer G for unreliable transports. + this.H = setTimeout(() => this.timerH(), _timers__WEBPACK_IMPORTED_MODULE_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__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Confirmed) { + // FIXME: This timer is not getting set correctly for unreliable transports. + this.I = setTimeout(() => this.timerI(), _timers__WEBPACK_IMPORTED_MODULE_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__WEBPACK_IMPORTED_MODULE_3__["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. + */ + startProgressExtensionTimer() { + // Start the progress extension timer only for the first non-100 provisional response. + if (this.progressExtensionTimer === undefined) { + this.progressExtensionTimer = setInterval(() => { + 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((error) => { + this.logTransportError(error, "Failed to send retransmission of provisional response."); + }); + }, _timers__WEBPACK_IMPORTED_MODULE_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. + */ + stopProgressExtensionTimer() { + 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 + */ + timerG() { + // 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 + */ + timerH() { + this.logger.debug(`Timer H expired for INVITE server transaction ${this.id}.`); + if (this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Completed) { + this.logger.warn("ACK to negative final response was never received, terminating transaction."); + this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Terminated); + } + } + /** + * Once timer I fires, the server MUST transition to the "Terminated" state. + * https://tools.ietf.org/html/rfc3261#section-17.2.1 + */ + timerI() { + this.logger.debug(`Timer I expired for INVITE server transaction ${this.id}.`); + this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_3__["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 + */ + timerL() { + this.logger.debug(`Timer L expired for INVITE server transaction ${this.id}.`); + if (this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Accepted) { + this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Terminated); + } + } +} + + +/***/ }), +/* 58 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ServerTransaction", function() { return ServerTransaction; }); +/* harmony import */ var _transaction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(50); + +/** + * 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 + */ +class ServerTransaction extends _transaction__WEBPACK_IMPORTED_MODULE_0__["Transaction"] { + constructor(_request, transport, user, state, loggerCategory) { + super(transport, user, _request.viaBranch, state, loggerCategory); + this._request = _request; + this.user = user; + } + /** The incoming request the transaction handling. */ + get request() { + return this._request; + } +} + + +/***/ }), +/* 59 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NonInviteClientTransaction", function() { return NonInviteClientTransaction; }); +/* harmony import */ var _timers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(47); +/* harmony import */ var _client_transaction__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(49); +/* harmony import */ var _transaction_state__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(56); + + + +/** + * 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 + */ +class NonInviteClientTransaction extends _client_transaction__WEBPACK_IMPORTED_MODULE_1__["ClientTransaction"] { + /** + * 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, transport, user) { + super(request, transport, user, _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying, "sip.transaction.nict"); + // 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(() => this.timerF(), _timers__WEBPACK_IMPORTED_MODULE_0__["Timers"].TIMER_F); + this.send(request.toString()).catch((error) => { + this.logTransportError(error, "Failed to send initial outgoing request."); + }); + } + /** + * Destructor. + */ + dispose() { + if (this.F) { + clearTimeout(this.F); + this.F = undefined; + } + if (this.K) { + clearTimeout(this.K); + this.K = undefined; + } + super.dispose(); + } + /** Transaction kind. Deprecated. */ + get kind() { + return "nict"; + } + /** + * Handler for incoming responses from the transport which match this transaction. + * @param response - The incoming response. + */ + receiveResponse(response) { + const statusCode = response.statusCode; + if (!statusCode || statusCode < 100 || statusCode > 699) { + throw new Error(`Invalid status code ${statusCode}`); + } + switch (this.state) { + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed); + if (statusCode === 408) { + this.onRequestTimeout(); + return; + } + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed); + if (statusCode === 408) { + this.onRequestTimeout(); + return; + } + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated: + // For good measure just absorb additional response retransmissions. + return; + default: + throw new Error(`Invalid state ${this.state}`); + } + const 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 fail over mechanisms described in [4]. + * https://tools.ietf.org/html/rfc3261#section-17.1.4 + * @param error - Transport error + */ + onTransportError(error) { + if (this.user.onTransportError) { + this.user.onTransportError(error); + } + this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated, true); + } + /** For logging. */ + typeToString() { + return "non-INVITE client transaction"; + } + /** + * Execute a state transition. + * @param newState - New state. + */ + stateTransition(newState, dueToTransportError = false) { + // Assert valid state transitions. + const invalidStateTransition = () => { + throw new Error(`Invalid state transition from ${this.state} to ${newState}`); + }; + switch (newState) { + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying: + invalidStateTransition(); + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding: + if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying) { + invalidStateTransition(); + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed: + if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying && this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding) { + invalidStateTransition(); + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated: + if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying && + this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding && + this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed) { + if (this.F) { + clearTimeout(this.F); + this.F = undefined; + } + this.K = setTimeout(() => this.timerK(), _timers__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_2__["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 + */ + timerF() { + this.logger.debug(`Timer F expired for non-INVITE client transaction ${this.id}.`); + if (this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying || this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding) { + this.onRequestTimeout(); + this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["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 + */ + timerK() { + if (this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed) { + this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated); + } + } +} + + +/***/ }), +/* 60 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NonInviteServerTransaction", function() { return NonInviteServerTransaction; }); +/* harmony import */ var _timers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(47); +/* harmony import */ var _server_transaction__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(58); +/* harmony import */ var _transaction_state__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(56); + + + +/** + * Non-INVITE Server Transaction. + * @remarks + * https://tools.ietf.org/html/rfc3261#section-17.2.2 + * @public + */ +class NonInviteServerTransaction extends _server_transaction__WEBPACK_IMPORTED_MODULE_1__["ServerTransaction"] { + /** + * 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, transport, user) { + super(request, transport, user, _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying, "sip.transaction.nist"); + } + /** + * Destructor. + */ + dispose() { + if (this.J) { + clearTimeout(this.J); + this.J = undefined; + } + super.dispose(); + } + /** Transaction kind. Deprecated. */ + get kind() { + return "nist"; + } + /** + * Receive requests from transport matching this transaction. + * @param request - Request matching this transaction. + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + receiveRequest(request) { + switch (this.state) { + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_2__["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((error) => { + this.logTransportError(error, "Failed to send retransmission of provisional response."); + }); + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["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((error) => { + this.logTransportError(error, "Failed to send retransmission of final response."); + }); + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated: + break; + default: + throw new Error(`Invalid state ${this.state}`); + } + } + /** + * Receive responses from TU for this transaction. + * @param statusCode - Status code of response. 101-199 not allowed per RFC 4320. + * @param response - Response to send. + */ + receiveResponse(statusCode, response) { + 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__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding); + this.send(response).catch((error) => { + this.logTransportError(error, "Failed to send provisional response."); + }); + return; + } + if (statusCode >= 200 && statusCode <= 699) { + this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed); + this.send(response).catch((error) => { + this.logTransportError(error, "Failed to send final response."); + }); + return; + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed); + this.send(response).catch((error) => { + this.logTransportError(error, "Failed to send final response."); + }); + return; + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated: + break; + default: + throw new Error(`Invalid state ${this.state}`); + } + const 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 + */ + onTransportError(error) { + if (this.user.onTransportError) { + this.user.onTransportError(error); + } + this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated, true); + } + /** For logging. */ + typeToString() { + return "non-INVITE server transaction"; + } + stateTransition(newState, dueToTransportError = false) { + // Assert valid state transitions. + const invalidStateTransition = () => { + throw new Error(`Invalid state transition from ${this.state} to ${newState}`); + }; + switch (newState) { + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying: + invalidStateTransition(); + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding: + if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying) { + invalidStateTransition(); + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed: + if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying && this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding) { + invalidStateTransition(); + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated: + if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding && this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed) { + this.J = setTimeout(() => this.timerJ(), _timers__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_2__["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 + */ + timerJ() { + this.logger.debug(`Timer J expired for NON-INVITE server transaction ${this.id}.`); + if (this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed) { + this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated); + } + } +} + + +/***/ }), +/* 61 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 62 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ByeUserAgentClient", function() { return ByeUserAgentClient; }); +/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48); +/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(63); + + + +/** + * BYE UAC. + * @public + */ +class ByeUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_2__["UserAgentClient"] { + constructor(dialog, delegate, options) { + const message = dialog.createOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["C"].BYE, options); + super(_transactions__WEBPACK_IMPORTED_MODULE_1__["NonInviteClientTransaction"], dialog.userAgentCore, message, delegate); + dialog.dispose(); + } +} + + +/***/ }), +/* 63 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UserAgentClient", function() { return UserAgentClient; }); +/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48); + + +/** + * 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 + */ +class UserAgentClient { + constructor(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(); + } + dispose() { + this.transaction.dispose(); + } + get loggerFactory() { + return this.core.loggerFactory; + } + /** The transaction associated with this request. */ + get transaction() { + if (!this._transaction) { + throw new Error("Transaction undefined."); + } + return this._transaction; + } + /** + * 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, 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 + const message = this.core.makeOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_1__["TransactionState"].Proceeding) { + new UserAgentClient(_transactions__WEBPACK_IMPORTED_MODULE_1__["NonInviteClientTransaction"], this.core, message); + } + else { + this.transaction.addStateChangeListener(() => { + if (this.transaction && this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_1__["TransactionState"].Proceeding) { + new UserAgentClient(_transactions__WEBPACK_IMPORTED_MODULE_1__["NonInviteClientTransaction"], this.core, message); + } + }, { once: true }); + } + 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. + * @param dialog - If defined, the dialog within which the response was received. + * @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. + */ + authenticationGuard(message, dialog) { + const 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. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let challenge; + let 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; + } + // If response to out of dialog request, assume incrementing the CSeq will suffice. + let cseq = (this.message.cseq += 1); + // If response to in dialog request, get a valid next CSeq number. + if (dialog && dialog.localSequenceNumber) { + dialog.incrementLocalSequenceNumber(); + cseq = this.message.cseq = dialog.localSequenceNumber; + } + 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; + } + /** + * 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 + */ + onRequestTimeout() { + this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout."); + const message = new _messages__WEBPACK_IMPORTED_MODULE_0__["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 + * @param error - Transport error + */ + onTransportError(error) { + this.logger.error(error.message); + this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable."); + const message = new _messages__WEBPACK_IMPORTED_MODULE_0__["IncomingResponseMessage"](); + message.statusCode = 503; + message.reasonPhrase = "Service Unavailable"; + this.receiveResponse(message); + } + /** + * Receive a response from the transaction layer. + * @param message - Incoming response message. + */ + receiveResponse(message) { + if (!this.authenticationGuard(message)) { + return; + } + const 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 }); + } + break; + case /^1[0-9]{2}$/.test(statusCode): + if (this.delegate && this.delegate.onProgress) { + this.delegate.onProgress({ message }); + } + break; + case /^2[0-9]{2}$/.test(statusCode): + if (this.delegate && this.delegate.onAccept) { + this.delegate.onAccept({ message }); + } + break; + case /^3[0-9]{2}$/.test(statusCode): + if (this.delegate && this.delegate.onRedirect) { + this.delegate.onRedirect({ message }); + } + break; + case /^[4-6][0-9]{2}$/.test(statusCode): + if (this.delegate && this.delegate.onReject) { + this.delegate.onReject({ message }); + } + break; + default: + throw new Error(`Invalid status code ${statusCode}`); + } + } + init() { + // We are the transaction user. + const user = { + loggerFactory: this.loggerFactory, + onRequestTimeout: () => this.onRequestTimeout(), + onStateChange: (newState) => { + if (newState === _transactions__WEBPACK_IMPORTED_MODULE_1__["TransactionState"].Terminated) { + // Remove the terminated transaction from the core. + // eslint-disable-next-line @typescript-eslint/no-use-before-define + 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. + // eslint-disable-next-line @typescript-eslint/no-use-before-define + if (transaction === this._transaction) { + this.dispose(); + } + } + }, + onTransportError: (error) => this.onTransportError(error), + receiveResponse: (message) => this.receiveResponse(message) + }; + // Create a new transaction with us as the user. + const transaction = new this.transactionConstructor(this.message, this.core.transport, user); + this._transaction = transaction; + // Add the new transaction to the core. + const userAgentClientId = transaction.id + transaction.request.method; + this.core.userAgentClients.set(userAgentClientId, this); + } +} + + +/***/ }), +/* 64 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ByeUserAgentServer", function() { return ByeUserAgentServer; }); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); +/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); + + +/** + * BYE UAS. + * @public + */ +class ByeUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { + constructor(dialog, message, delegate) { + super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteServerTransaction"], dialog.userAgentCore, message, delegate); + } +} + + +/***/ }), +/* 65 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UserAgentServer", function() { return UserAgentServer; }); +/* harmony import */ var _exceptions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(51); +/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8); +/* harmony import */ var _messages_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(32); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(48); + + + + +/** + * 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 + */ +class UserAgentServer { + constructor(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 : Object(_messages_utils__WEBPACK_IMPORTED_MODULE_2__["newTag"])(); + this.init(); + } + dispose() { + this.transaction.dispose(); + } + get loggerFactory() { + return this.core.loggerFactory; + } + /** The transaction associated with this request. */ + get transaction() { + if (!this._transaction) { + throw new Error("Transaction undefined."); + } + return this._transaction; + } + accept(options = { statusCode: 200 }) { + if (!this.acceptable) { + throw new _exceptions__WEBPACK_IMPORTED_MODULE_0__["TransactionStateError"](`${this.message.method} not acceptable in state ${this.transaction.state}.`); + } + const statusCode = options.statusCode; + if (statusCode < 200 || statusCode > 299) { + throw new TypeError(`Invalid statusCode: ${statusCode}`); + } + const response = this.reply(options); + return response; + } + progress(options = { statusCode: 180 }) { + if (!this.progressable) { + throw new _exceptions__WEBPACK_IMPORTED_MODULE_0__["TransactionStateError"](`${this.message.method} not progressable in state ${this.transaction.state}.`); + } + const statusCode = options.statusCode; + if (statusCode < 101 || statusCode > 199) { + throw new TypeError(`Invalid statusCode: ${statusCode}`); + } + const response = this.reply(options); + return response; + } + redirect(contacts, options = { statusCode: 302 }) { + if (!this.redirectable) { + throw new _exceptions__WEBPACK_IMPORTED_MODULE_0__["TransactionStateError"](`${this.message.method} not redirectable in state ${this.transaction.state}.`); + } + const statusCode = options.statusCode; + if (statusCode < 300 || statusCode > 399) { + throw new TypeError(`Invalid statusCode: ${statusCode}`); + } + const contactHeaders = new Array(); + contacts.forEach((contact) => contactHeaders.push(`Contact: ${contact.toString()}`)); + options.extraHeaders = (options.extraHeaders || []).concat(contactHeaders); + const response = this.reply(options); + return response; + } + reject(options = { statusCode: 480 }) { + if (!this.rejectable) { + throw new _exceptions__WEBPACK_IMPORTED_MODULE_0__["TransactionStateError"](`${this.message.method} not rejectable in state ${this.transaction.state}.`); + } + const statusCode = options.statusCode; + if (statusCode < 400 || statusCode > 699) { + throw new TypeError(`Invalid statusCode: ${statusCode}`); + } + const response = this.reply(options); + return response; + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + trying(options) { + if (!this.tryingable) { + throw new _exceptions__WEBPACK_IMPORTED_MODULE_0__["TransactionStateError"](`${this.message.method} not tryingable in state ${this.transaction.state}.`); + } + const 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. + */ + receiveCancel(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); + } + } + get acceptable() { + if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"]) { + return (this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding || this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Accepted); + } + if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["NonInviteServerTransaction"]) { + return (this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Trying || this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding); + } + throw new Error("Unknown transaction type."); + } + get progressable() { + if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"]) { + return this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding; + } + if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["NonInviteServerTransaction"]) { + return false; // https://tools.ietf.org/html/rfc4320#section-4.1 + } + throw new Error("Unknown transaction type."); + } + get redirectable() { + if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"]) { + return this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding; + } + if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["NonInviteServerTransaction"]) { + return (this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Trying || this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding); + } + throw new Error("Unknown transaction type."); + } + get rejectable() { + if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"]) { + return this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding; + } + if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["NonInviteServerTransaction"]) { + return (this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Trying || this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding); + } + throw new Error("Unknown transaction type."); + } + get tryingable() { + if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"]) { + return this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding; + } + if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["NonInviteServerTransaction"]) { + return this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Trying; + } + throw new Error("Unknown transaction type."); + } + /** + * 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. + */ + reply(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; + const response = Object(_messages__WEBPACK_IMPORTED_MODULE_1__["constructOutgoingResponse"])(this.message, options); + this.transaction.receiveResponse(options.statusCode, response.message); + return response; + } + init() { + // We are the transaction user. + const user = { + loggerFactory: this.loggerFactory, + onStateChange: (newState) => { + if (newState === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Terminated) { + // Remove the terminated transaction from the core. + // eslint-disable-next-line @typescript-eslint/no-use-before-define + this.core.userAgentServers.delete(userAgentServerId); + this.dispose(); + } + }, + onTransportError: (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. + const transaction = new this.transactionConstructor(this.message, this.core.transport, user); + this._transaction = transaction; + // Add the new transaction to the core. + const userAgentServerId = transaction.id; + this.core.userAgentServers.set(transaction.id, this); + } +} + + +/***/ }), +/* 66 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InfoUserAgentClient", function() { return InfoUserAgentClient; }); +/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48); +/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(63); + + + +/** + * INFO UAC. + * @public + */ +class InfoUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_2__["UserAgentClient"] { + constructor(dialog, delegate, options) { + const message = dialog.createOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["C"].INFO, options); + super(_transactions__WEBPACK_IMPORTED_MODULE_1__["NonInviteClientTransaction"], dialog.userAgentCore, message, delegate); + } +} + + +/***/ }), +/* 67 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InfoUserAgentServer", function() { return InfoUserAgentServer; }); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); +/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); + + +/** + * INFO UAS. + * @public + */ +class InfoUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { + constructor(dialog, message, delegate) { + super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteServerTransaction"], dialog.userAgentCore, message, delegate); + } +} + + +/***/ }), +/* 68 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MessageUserAgentClient", function() { return MessageUserAgentClient; }); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); +/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(63); + + +/** + * MESSAGE UAC. + * @public + */ +class MessageUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_1__["UserAgentClient"] { + constructor(core, message, delegate) { + super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteClientTransaction"], core, message, delegate); + } +} + + +/***/ }), +/* 69 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MessageUserAgentServer", function() { return MessageUserAgentServer; }); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); +/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); + + +/** + * MESSAGE UAS. + * @public + */ +class MessageUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { + constructor(core, message, delegate) { + super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteServerTransaction"], core, message, delegate); + } +} + + +/***/ }), +/* 70 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NotifyUserAgentClient", function() { return NotifyUserAgentClient; }); +/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48); +/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(63); + + + +/** + * NOTIFY UAS. + * @public + */ +class NotifyUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_2__["UserAgentClient"] { + constructor(dialog, delegate, options) { + const message = dialog.createOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["C"].NOTIFY, options); + super(_transactions__WEBPACK_IMPORTED_MODULE_1__["NonInviteClientTransaction"], dialog.userAgentCore, message, delegate); + } +} + + +/***/ }), +/* 71 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NotifyUserAgentServer", function() { return NotifyUserAgentServer; }); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); +/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); + + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function instanceOfDialog(object) { + return object.userAgentCore !== undefined; +} +/** + * NOTIFY UAS. + * @public + */ +class NotifyUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { + /** + * 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, message, delegate) { + const userAgentCore = instanceOfDialog(dialogOrCore) ? dialogOrCore.userAgentCore : dialogOrCore; + super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteServerTransaction"], userAgentCore, message, delegate); + } +} + + +/***/ }), +/* 72 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PrackUserAgentClient", function() { return PrackUserAgentClient; }); +/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48); +/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(63); + + + +/** + * PRACK UAC. + * @public + */ +class PrackUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_2__["UserAgentClient"] { + constructor(dialog, delegate, options) { + const message = dialog.createOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["C"].PRACK, options); + super(_transactions__WEBPACK_IMPORTED_MODULE_1__["NonInviteClientTransaction"], dialog.userAgentCore, message, delegate); + dialog.signalingStateTransition(message); + } +} + + +/***/ }), +/* 73 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PrackUserAgentServer", function() { return PrackUserAgentServer; }); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); +/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); + + +/** + * PRACK UAS. + * @public + */ +class PrackUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { + constructor(dialog, message, delegate) { + super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteServerTransaction"], dialog.userAgentCore, message, delegate); + // Update dialog signaling state with offer/answer in body + dialog.signalingStateTransition(message); + this.dialog = dialog; + } + /** + * Update the dialog signaling state on a 2xx response. + * @param options - Options bucket. + */ + accept(options = { statusCode: 200 }) { + if (options.body) { + // Update dialog signaling state with offer/answer in body + this.dialog.signalingStateTransition(options.body); + } + return super.accept(options); + } +} + + +/***/ }), +/* 74 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReInviteUserAgentClient", function() { return ReInviteUserAgentClient; }); +/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48); +/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(63); + + + +/** + * 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 + */ +class ReInviteUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_2__["UserAgentClient"] { + constructor(dialog, delegate, options) { + const message = dialog.createOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE, options); + super(_transactions__WEBPACK_IMPORTED_MODULE_1__["InviteClientTransaction"], dialog.userAgentCore, message, delegate); + 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; + } + receiveResponse(message) { + if (!this.authenticationGuard(message, this.dialog)) { + return; + } + const 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 }); + } + break; + case /^1[0-9]{2}$/.test(statusCode): + if (this.delegate && this.delegate.onProgress) { + this.delegate.onProgress({ + message, + session: this.dialog, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + prack: (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, + session: this.dialog, + ack: (options) => { + const 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 }); + } + 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 }); + } + 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}`); + } + } +} + + +/***/ }), +/* 75 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReInviteUserAgentServer", function() { return ReInviteUserAgentServer; }); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); +/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); + + +/** + * 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 + */ +class ReInviteUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { + constructor(dialog, message, delegate) { + super(_transactions__WEBPACK_IMPORTED_MODULE_0__["InviteServerTransaction"], dialog.userAgentCore, message, delegate); + dialog.reinviteUserAgentServer = this; + this.dialog = dialog; + } + /** + * Update the dialog signaling state on a 2xx response. + * @param options - Options bucket. + */ + accept(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((route) => `Record-Route: ${route}`)); + // Send and return the response + const response = super.accept(options); + const session = this.dialog; + const result = Object.assign(Object.assign({}, response), { 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. + */ + progress(options = { statusCode: 180 }) { + // Send and return the response + const response = super.progress(options); + const session = this.dialog; + const result = Object.assign(Object.assign({}, response), { 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. + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + redirect(contacts, 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. + */ + reject(options = { statusCode: 488 }) { + this.dialog.signalingStateRollback(); + this.dialog.reinviteUserAgentServer = undefined; // ACK will be handled by transaction + return super.reject(options); + } +} + + +/***/ }), +/* 76 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReferUserAgentClient", function() { return ReferUserAgentClient; }); +/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48); +/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(63); + + + +/** + * REFER UAC. + * @public + */ +class ReferUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_2__["UserAgentClient"] { + constructor(dialog, delegate, options) { + const message = dialog.createOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["C"].REFER, options); + super(_transactions__WEBPACK_IMPORTED_MODULE_1__["NonInviteClientTransaction"], dialog.userAgentCore, message, delegate); + } +} + + +/***/ }), +/* 77 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReferUserAgentServer", function() { return ReferUserAgentServer; }); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); +/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); + + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function instanceOfSessionDialog(object) { + return object.userAgentCore !== undefined; +} +/** + * REFER UAS. + * @public + */ +class ReferUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { + /** + * REFER UAS constructor. + * @param dialogOrCore - Dialog for in dialog REFER, UserAgentCore for out of dialog REFER. + * @param message - Incoming REFER request message. + */ + constructor(dialogOrCore, message, delegate) { + const userAgentCore = instanceOfSessionDialog(dialogOrCore) ? dialogOrCore.userAgentCore : dialogOrCore; + super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteServerTransaction"], userAgentCore, message, delegate); + } +} + + +/***/ }), +/* 78 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubscriptionDialog", function() { return SubscriptionDialog; }); +/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); +/* harmony import */ var _subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(79); +/* harmony import */ var _timers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(47); +/* harmony import */ var _user_agent_core_allowed_methods__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(82); +/* harmony import */ var _user_agents_notify_user_agent_server__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(71); +/* harmony import */ var _user_agents_re_subscribe_user_agent_client__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(83); +/* harmony import */ var _dialog__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(7); + + + + + + + +/** + * 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 + */ +class SubscriptionDialog extends _dialog__WEBPACK_IMPORTED_MODULE_6__["Dialog"] { + constructor(subscriptionEvent, subscriptionExpires, subscriptionState, core, state, delegate) { + super(core, state); + 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`); + } + /** + * 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, 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 + const 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 + const routeSet = incomingNotifyRequestMessage.getHeaders("record-route"); + const contact = incomingNotifyRequestMessage.parseHeader("contact"); + if (!contact) { + // TODO: Review to make sure this will never happen + throw new Error("Contact undefined."); + } + if (!(contact instanceof _messages__WEBPACK_IMPORTED_MODULE_0__["NameAddrHeader"])) { + throw new Error("Contact not instance of NameAddrHeader."); + } + const 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 + const localSequenceNumber = outgoingSubscribeRequestMessage.cseq; + const remoteSequenceNumber = undefined; + const callId = outgoingSubscribeRequestMessage.callId; + const localTag = outgoingSubscribeRequestMessage.fromTag; + const 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."); + } + const localURI = outgoingSubscribeRequestMessage.from.uri; + const 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 + const early = false; + const dialogState = { + id: callId + localTag + remoteTag, + early, + callId, + localTag, + remoteTag, + localSequenceNumber, + remoteSequenceNumber, + localURI, + remoteURI, + remoteTarget, + routeSet, + secure + }; + return dialogState; + } + dispose() { + super.dispose(); + if (this.N) { + clearTimeout(this.N); + this.N = undefined; + } + this.refreshTimerClear(); + this.logger.log(`SUBSCRIBE dialog ${this.id} destroyed`); + } + get autoRefresh() { + return this._autoRefresh; + } + set autoRefresh(autoRefresh) { + this._autoRefresh = true; + this.refreshTimerSet(); + } + get subscriptionEvent() { + return this._subscriptionEvent; + } + /** Number of seconds until subscription expires. */ + get subscriptionExpires() { + const secondsSinceLastSet = Math.floor(Date.now() / 1000) - this._subscriptionExpiresLastSet; + const secondsUntilExpires = this._subscriptionExpires - secondsSinceLastSet; + return Math.max(secondsUntilExpires, 0); + } + set subscriptionExpires(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) { + const refresh = this.subscriptionRefresh; + if (refresh === undefined || refresh >= expires) { + this.refreshTimerSet(); + } + } + } + get subscriptionExpiresInitial() { + return this._subscriptionExpiresInitial; + } + /** Number of seconds until subscription auto refresh. */ + get subscriptionRefresh() { + if (this._subscriptionRefresh === undefined || this._subscriptionRefreshLastSet === undefined) { + return undefined; + } + const secondsSinceLastSet = Math.floor(Date.now() / 1000) - this._subscriptionRefreshLastSet; + const secondsUntilExpires = this._subscriptionRefresh - secondsSinceLastSet; + return Math.max(secondsUntilExpires, 0); + } + get subscriptionState() { + return this._subscriptionState; + } + /** + * Receive in dialog request message from transport. + * @param message - The incoming request message. + */ + receiveRequest(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.receiveRequest(message); + // Switch on method and then delegate. + switch (message.method) { + case _messages__WEBPACK_IMPORTED_MODULE_0__["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 + */ + refresh() { + const allowHeader = "Allow: " + _user_agent_core_allowed_methods__WEBPACK_IMPORTED_MODULE_3__["AllowedMethods"].toString(); + const 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. + */ + subscribe(delegate, options = {}) { + if (this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Pending && this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_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`); + const uac = new _user_agents_re_subscribe_user_agent_client__WEBPACK_IMPORTED_MODULE_5__["ReSubscribeUserAgentClient"](this, delegate, options); + // Abort any outstanding timer (as it would otherwise become guaranteed to terminate us). + if (this.N) { + clearTimeout(this.N); + this.N = undefined; + } + // 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(() => this.timerN(), _timers__WEBPACK_IMPORTED_MODULE_2__["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 + */ + terminate() { + this.stateTransition(_subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated); + this.onTerminated(); + } + /** + * 4.1.2.3. Unsubscribing + * https://tools.ietf.org/html/rfc6665#section-4.1.2.3 + */ + unsubscribe() { + const allowHeader = "Allow: " + _user_agent_core_allowed_methods__WEBPACK_IMPORTED_MODULE_3__["AllowedMethods"].toString(); + const 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. + */ + onNotify(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 + const 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 + const subscriptionState = message.parseHeader("Subscription-State"); + if (!subscriptionState || !subscriptionState.state) { + this.core.replyStateless(message, { statusCode: 489 }); + return; + } + const state = subscriptionState.state; + const expires = subscriptionState.expires ? Math.max(subscriptionState.expires, 0) : undefined; + // Update our state and expiration. + switch (state) { + case "pending": + this.stateTransition(_subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Pending, expires); + break; + case "active": + this.stateTransition(_subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Active, expires); + break; + case "terminated": + this.stateTransition(_subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated, expires); + break; + default: + this.logger.warn("Unrecognized subscription state."); + break; + } + // Delegate remainder of NOTIFY handling. + const uas = new _user_agents_notify_user_agent_server__WEBPACK_IMPORTED_MODULE_4__["NotifyUserAgentServer"](this, message); + if (this.delegate && this.delegate.onNotify) { + this.delegate.onNotify(uas); + } + else { + uas.accept(); + } + } + onRefresh(request) { + if (this.delegate && this.delegate.onRefresh) { + this.delegate.onRefresh(request); + } + } + onTerminated() { + if (this.delegate && this.delegate.onTerminated) { + this.delegate.onTerminated(); + } + } + refreshTimerClear() { + if (this.refreshTimer) { + clearTimeout(this.refreshTimer); + this.refreshTimer = undefined; + } + } + refreshTimerSet() { + this.refreshTimerClear(); + if (this.autoRefresh && this.subscriptionExpires > 0) { + const refresh = this.subscriptionExpires * 900; + this._subscriptionRefresh = Math.floor(refresh / 1000); + this._subscriptionRefreshLastSet = Math.floor(Date.now() / 1000); + this.refreshTimer = setTimeout(() => { + this.refreshTimer = undefined; + this._subscriptionRefresh = undefined; + this._subscriptionRefreshLastSet = undefined; + this.onRefresh(this.refresh()); + }, refresh); + } + } + stateTransition(newState, newExpires) { + // Assert valid state transitions. + const invalidStateTransition = () => { + this.logger.warn(`Invalid subscription state transition from ${this.subscriptionState} to ${newState}`); + }; + switch (newState) { + case _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Initial: + invalidStateTransition(); + return; + case _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].NotifyWait: + invalidStateTransition(); + return; + case _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Pending: + if (this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].NotifyWait && + this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Pending) { + invalidStateTransition(); + return; + } + break; + case _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Active: + if (this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].NotifyWait && + this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Pending && + this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Active) { + invalidStateTransition(); + return; + } + break; + case _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated: + if (this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].NotifyWait && + this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Pending && + this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_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__WEBPACK_IMPORTED_MODULE_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__WEBPACK_IMPORTED_MODULE_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__WEBPACK_IMPORTED_MODULE_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 + */ + timerN() { + this.logger.warn(`Timer N expired for SUBSCRIBE dialog. Timed out waiting for NOTIFY.`); + if (this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated) { + this.stateTransition(_subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated); + this.onTerminated(); + } + } +} + + +/***/ }), +/* 79 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _subscription__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(80); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubscriptionState", function() { return _subscription__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"]; }); + +/* harmony import */ var _subscription_delegate__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(81); +/* empty/unused harmony star reexport */ + + + +/***/ }), +/* 80 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubscriptionState", function() { return SubscriptionState; }); +/** + * 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 || (SubscriptionState = {})); + + +/***/ }), +/* 81 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 82 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AllowedMethods", function() { return AllowedMethods; }); +/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); + +/** + * FIXME: TODO: Should be configurable/variable. + */ +const AllowedMethods = [ + _messages__WEBPACK_IMPORTED_MODULE_0__["C"].ACK, + _messages__WEBPACK_IMPORTED_MODULE_0__["C"].BYE, + _messages__WEBPACK_IMPORTED_MODULE_0__["C"].CANCEL, + _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INFO, + _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE, + _messages__WEBPACK_IMPORTED_MODULE_0__["C"].MESSAGE, + _messages__WEBPACK_IMPORTED_MODULE_0__["C"].NOTIFY, + _messages__WEBPACK_IMPORTED_MODULE_0__["C"].OPTIONS, + _messages__WEBPACK_IMPORTED_MODULE_0__["C"].PRACK, + _messages__WEBPACK_IMPORTED_MODULE_0__["C"].REFER, + _messages__WEBPACK_IMPORTED_MODULE_0__["C"].REGISTER, + _messages__WEBPACK_IMPORTED_MODULE_0__["C"].SUBSCRIBE +]; + + +/***/ }), +/* 83 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReSubscribeUserAgentClient", function() { return ReSubscribeUserAgentClient; }); +/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48); +/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(63); + + + +/** + * Re-SUBSCRIBE UAC. + * @public + */ +class ReSubscribeUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_2__["UserAgentClient"] { + constructor(dialog, delegate, options) { + const message = dialog.createOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["C"].SUBSCRIBE, options); + super(_transactions__WEBPACK_IMPORTED_MODULE_1__["NonInviteClientTransaction"], dialog.userAgentCore, message, delegate); + this.dialog = dialog; + } + waitNotifyStop() { + // TODO: Placeholder. Not utilized currently. + return; + } + /** + * Receive a response from the transaction layer. + * @param message - Incoming response message. + */ + receiveResponse(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 + const expires = message.getHeader("Expires"); + if (!expires) { + this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE"); + } + else { + const 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 + const 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.receiveResponse(message); + } +} + + +/***/ }), +/* 84 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _levels__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(85); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Levels", function() { return _levels__WEBPACK_IMPORTED_MODULE_0__["Levels"]; }); + +/* harmony import */ var _logger_factory__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(86); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LoggerFactory", function() { return _logger_factory__WEBPACK_IMPORTED_MODULE_1__["LoggerFactory"]; }); + +/* harmony import */ var _logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(87); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Logger", function() { return _logger__WEBPACK_IMPORTED_MODULE_2__["Logger"]; }); + + + + + + +/***/ }), +/* 85 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Levels", function() { return Levels; }); +/** + * 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 || (Levels = {})); + + +/***/ }), +/* 86 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LoggerFactory", function() { return LoggerFactory; }); +/* harmony import */ var _levels__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(85); +/* harmony import */ var _logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(87); + + +/** + * Logger. + * @public + */ +class LoggerFactory { + constructor() { + this.builtinEnabled = true; + this._level = _levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].log; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this.loggers = {}; + this.logger = this.getLogger("sip:loggerfactory"); + } + get level() { + return this._level; + } + set level(newLevel) { + if (newLevel >= 0 && newLevel <= 3) { + this._level = newLevel; + } + else if (newLevel > 3) { + this._level = 3; + // eslint-disable-next-line no-prototype-builtins + } + else if (_levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].hasOwnProperty(newLevel)) { + this._level = newLevel; + } + else { + this.logger.error("invalid 'level' parameter value: " + JSON.stringify(newLevel)); + } + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + get connector() { + return this._connector; + } + set connector(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)); + } + } + getLogger(category, label) { + if (label && this.level === 3) { + return new _logger__WEBPACK_IMPORTED_MODULE_1__["Logger"](this, category, label); + } + else if (this.loggers[category]) { + return this.loggers[category]; + } + else { + const logger = new _logger__WEBPACK_IMPORTED_MODULE_1__["Logger"](this, category); + this.loggers[category] = logger; + return logger; + } + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + genericLog(levelToLog, category, label, content) { + if (this.level >= levelToLog) { + if (this.builtinEnabled) { + this.print(levelToLog, category, label, content); + } + } + if (this.connector) { + this.connector(_levels__WEBPACK_IMPORTED_MODULE_0__["Levels"][levelToLog], category, label, content); + } + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + print(levelToLog, category, label, content) { + if (typeof content === "string") { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const prefix = [new Date(), category]; + if (label) { + prefix.push(label); + } + content = prefix.concat(content).join(" | "); + } + switch (levelToLog) { + case _levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].error: + // eslint-disable-next-line no-console + console.error(content); + break; + case _levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].warn: + // eslint-disable-next-line no-console + console.warn(content); + break; + case _levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].log: + // eslint-disable-next-line no-console + console.log(content); + break; + case _levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].debug: + // eslint-disable-next-line no-console + console.debug(content); + break; + default: + break; + } + } +} + + +/***/ }), +/* 87 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Logger", function() { return Logger; }); +/* harmony import */ var _levels__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(85); + +/** + * Logger. + * @public + */ +class Logger { + constructor(logger, category, label) { + this.logger = logger; + this.category = category; + this.label = label; + } + error(content) { + this.genericLog(_levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].error, content); + } + warn(content) { + this.genericLog(_levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].warn, content); + } + log(content) { + this.genericLog(_levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].log, content); + } + debug(content) { + this.genericLog(_levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].debug, content); + } + genericLog(level, content) { + this.logger.genericLog(level, this.category, this.label, content); + } + get level() { + return this.logger.level; + } + set level(newLevel) { + this.logger.level = newLevel; + } +} + + +/***/ }), +/* 88 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _user_agent_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(89); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgentCore", function() { return _user_agent_core__WEBPACK_IMPORTED_MODULE_0__["UserAgentCore"]; }); + +/* harmony import */ var _user_agent_core_configuration__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(100); +/* empty/unused harmony star reexport *//* harmony import */ var _user_agent_core_delegate__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(101); +/* empty/unused harmony star reexport */ + + + + +/***/ }), +/* 89 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UserAgentCore", function() { return UserAgentCore; }); +/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48); +/* harmony import */ var _user_agents__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(90); +/* harmony import */ var _allowed_methods__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(82); + + + + +/** + * This is ported from UA.C.ACCEPTED_BODY_TYPES. + * FIXME: TODO: Should be configurable/variable. + */ +const 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 + */ +class UserAgentCore { + /** + * Constructor. + * @param configuration - Configuration. + * @param delegate - Delegate. + */ + constructor(configuration, 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. */ + dispose() { + this.reset(); + } + /** Reset. */ + reset() { + this.dialogs.forEach((dialog) => dialog.dispose()); + this.dialogs.clear(); + this.subscribers.forEach((subscriber) => subscriber.dispose()); + this.subscribers.clear(); + this.userAgentClients.forEach((uac) => uac.dispose()); + this.userAgentClients.clear(); + this.userAgentServers.forEach((uac) => uac.dispose()); + this.userAgentServers.clear(); + } + /** Logger factory. */ + get loggerFactory() { + return this.configuration.loggerFactory; + } + /** Transport. */ + get transport() { + const transport = this.configuration.transportAccessor(); + if (!transport) { + throw new Error("Transport undefined."); + } + return transport; + } + /** + * Send INVITE. + * @param request - Outgoing request. + * @param delegate - Request delegate. + */ + invite(request, delegate) { + return new _user_agents__WEBPACK_IMPORTED_MODULE_2__["InviteUserAgentClient"](this, request, delegate); + } + /** + * Send MESSAGE. + * @param request - Outgoing request. + * @param delegate - Request delegate. + */ + message(request, delegate) { + return new _user_agents__WEBPACK_IMPORTED_MODULE_2__["MessageUserAgentClient"](this, request, delegate); + } + /** + * Send PUBLISH. + * @param request - Outgoing request. + * @param delegate - Request delegate. + */ + publish(request, delegate) { + return new _user_agents__WEBPACK_IMPORTED_MODULE_2__["PublishUserAgentClient"](this, request, delegate); + } + /** + * Send REGISTER. + * @param request - Outgoing request. + * @param delegate - Request delegate. + */ + register(request, delegate) { + return new _user_agents__WEBPACK_IMPORTED_MODULE_2__["RegisterUserAgentClient"](this, request, delegate); + } + /** + * Send SUBSCRIBE. + * @param request - Outgoing request. + * @param delegate - Request delegate. + */ + subscribe(request, delegate) { + return new _user_agents__WEBPACK_IMPORTED_MODULE_2__["SubscribeUserAgentClient"](this, request, delegate); + } + /** + * Send a request. + * @param request - Outgoing request. + * @param delegate - Request delegate. + */ + request(request, delegate) { + return new _user_agents__WEBPACK_IMPORTED_MODULE_2__["UserAgentClient"](_transactions__WEBPACK_IMPORTED_MODULE_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. + */ + makeOutgoingRequestMessage(method, requestURI, fromURI, toURI, options, extraHeaders, body) { + // default values from user agent configuration + const callIdPrefix = this.configuration.sipjsId; + const fromDisplayName = this.configuration.displayName; + const forceRport = this.configuration.viaForceRport; + const hackViaTcp = this.configuration.hackViaTcp; + const optionTags = this.configuration.supportedOptionTags.slice(); + if (method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].REGISTER) { + optionTags.push("path", "gruu"); + } + if (method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE && (this.configuration.contact.pubGruu || this.configuration.contact.tempGruu)) { + optionTags.push("gruu"); + } + const routeSet = this.configuration.routeSet; + const userAgentString = this.configuration.userAgentHeaderFieldValue; + const viaHost = this.configuration.viaHost; + const defaultOptions = { + callIdPrefix, + forceRport, + fromDisplayName, + hackViaTcp, + optionTags, + routeSet, + userAgentString, + viaHost + }; + // merge provided options with default options + const requestOptions = Object.assign(Object.assign({}, defaultOptions), options); + return new _messages__WEBPACK_IMPORTED_MODULE_0__["OutgoingRequestMessage"](method, requestURI, fromURI, toURI, requestOptions, extraHeaders, body); + } + /** + * Handle an incoming request message from the transport. + * @param message - Incoming request message from transport layer. + */ + receiveIncomingRequestFromTransport(message) { + this.receiveRequestFromTransport(message); + } + /** + * Handle an incoming response message from the transport. + * @param message - Incoming response message from transport layer. + */ + receiveIncomingResponseFromTransport(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. + */ + replyStateless(message, options) { + const userAgent = this.configuration.userAgentHeaderFieldValue; + const supported = this.configuration.supportedOptionTagsResponse; + options = Object.assign(Object.assign({}, options), { userAgent, supported }); + const response = Object(_messages__WEBPACK_IMPORTED_MODULE_0__["constructOutgoingResponse"])(message, options); + this.transport.send(response.message).catch((error) => { + // If the transport rejects, it SHOULD reject with a TransportError. + // But the transport may be external code, so we are careful... + if (error instanceof Error) { + this.logger.error(error.message); + } + this.logger.error(`Transport error occurred sending stateless reply to ${message.method} request.`); + // TODO: Currently there is no hook to provide notification that a transport error occurred + // and throwing would result in an uncaught error (in promise), so we silently eat the error. + // Furthermore, silently eating stateless reply transport errors is arguably what we want to do here. + }); + 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. + */ + receiveRequestFromTransport(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 + const transactionId = message.viaBranch; // FIXME: Currently only using rule 1... + const 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__WEBPACK_IMPORTED_MODULE_0__["C"].ACK) { + if (uas && uas.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_1__["TransactionState"].Accepted) { + if (uas instanceof _user_agents__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_1__["InviteServerTransaction"] && + uas.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_1__["TransactionState"].Proceeding) { + if (uas instanceof _user_agents__WEBPACK_IMPORTED_MODULE_2__["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. + */ + receiveRequest(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__WEBPACK_IMPORTED_MODULE_3__["AllowedMethods"].includes(message.method)) { + const allowHeader = "Allow: " + _allowed_methods__WEBPACK_IMPORTED_MODULE_3__["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 + const ruri = message.ruri; + const ruriMatches = (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__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_0__["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) { + const transactionId = message.viaBranch; + if (!this.userAgentServers.has(transactionId)) { + const mergedRequest = Array.from(this.userAgentServers.values()).some((uas) => 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. + */ + receiveInsideDialogRequest(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__WEBPACK_IMPORTED_MODULE_0__["C"].NOTIFY) { + const event = message.parseHeader("Event"); + if (!event || !event.event) { + this.replyStateless(message, { statusCode: 489 }); + return; + } + // FIXME: Subscriber id should also matching on event id. + const subscriberId = message.callId + message.toTag + event.event; + const subscriber = this.subscribers.get(subscriberId); + if (subscriber) { + const uas = new _user_agents__WEBPACK_IMPORTED_MODULE_2__["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 + const dialogId = message.callId + message.toTag + message.fromTag; + const 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__WEBPACK_IMPORTED_MODULE_0__["C"].OPTIONS) { + const allowHeader = "Allow: " + _allowed_methods__WEBPACK_IMPORTED_MODULE_3__["AllowedMethods"].toString(); + const 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__WEBPACK_IMPORTED_MODULE_0__["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. + */ + receiveOutsideDialogRequest(message) { + switch (message.method) { + case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].ACK: + // Absorb stray out of dialog ACKs + break; + case _messages__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_0__["C"].CANCEL: + throw new Error(`Unexpected out of dialog request method ${message.method}.`); + break; + case _messages__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE: + // https://tools.ietf.org/html/rfc3261#section-13.3.1 + { + const uas = new _user_agents__WEBPACK_IMPORTED_MODULE_2__["InviteUserAgentServer"](this, message); + this.delegate.onInvite ? this.delegate.onInvite(uas) : uas.reject(); + } + break; + case _messages__WEBPACK_IMPORTED_MODULE_0__["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 + { + const uas = new _user_agents__WEBPACK_IMPORTED_MODULE_2__["MessageUserAgentServer"](this, message); + this.delegate.onMessage ? this.delegate.onMessage(uas) : uas.accept(); + } + break; + case _messages__WEBPACK_IMPORTED_MODULE_0__["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 + { + const uas = new _user_agents__WEBPACK_IMPORTED_MODULE_2__["NotifyUserAgentServer"](this, message); + this.delegate.onNotify ? this.delegate.onNotify(uas) : uas.reject({ statusCode: 405 }); + } + break; + case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].OPTIONS: + // https://tools.ietf.org/html/rfc3261#section-11.2 + { + const allowHeader = "Allow: " + _allowed_methods__WEBPACK_IMPORTED_MODULE_3__["AllowedMethods"].toString(); + const acceptHeader = "Accept: " + acceptedBodyTypes.toString(); + this.replyStateless(message, { + statusCode: 200, + extraHeaders: [allowHeader, acceptHeader] + }); + } + break; + case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].REFER: + // https://tools.ietf.org/html/rfc3515#section-2.4.2 + { + const uas = new _user_agents__WEBPACK_IMPORTED_MODULE_2__["ReferUserAgentServer"](this, message); + this.delegate.onRefer ? this.delegate.onRefer(uas) : uas.reject({ statusCode: 405 }); + } + break; + case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].REGISTER: + // https://tools.ietf.org/html/rfc3261#section-10.3 + { + const uas = new _user_agents__WEBPACK_IMPORTED_MODULE_2__["RegisterUserAgentServer"](this, message); + this.delegate.onRegister ? this.delegate.onRegister(uas) : uas.reject({ statusCode: 405 }); + } + break; + case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].SUBSCRIBE: + // https://tools.ietf.org/html/rfc6665#section-4.2 + { + const uas = new _user_agents__WEBPACK_IMPORTED_MODULE_2__["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. + */ + receiveResponseFromTransport(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 + const userAgentClientId = message.viaBranch + message.method; + const 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}.`); + } + } +} + + +/***/ }), +/* 90 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _bye_user_agent_client__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(62); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ByeUserAgentClient", function() { return _bye_user_agent_client__WEBPACK_IMPORTED_MODULE_0__["ByeUserAgentClient"]; }); + +/* harmony import */ var _bye_user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(64); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ByeUserAgentServer", function() { return _bye_user_agent_server__WEBPACK_IMPORTED_MODULE_1__["ByeUserAgentServer"]; }); + +/* harmony import */ var _cancel_user_agent_client__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(91); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CancelUserAgentClient", function() { return _cancel_user_agent_client__WEBPACK_IMPORTED_MODULE_2__["CancelUserAgentClient"]; }); + +/* harmony import */ var _info_user_agent_client__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(66); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InfoUserAgentClient", function() { return _info_user_agent_client__WEBPACK_IMPORTED_MODULE_3__["InfoUserAgentClient"]; }); + +/* harmony import */ var _info_user_agent_server__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(67); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InfoUserAgentServer", function() { return _info_user_agent_server__WEBPACK_IMPORTED_MODULE_4__["InfoUserAgentServer"]; }); + +/* harmony import */ var _invite_user_agent_client__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(92); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InviteUserAgentClient", function() { return _invite_user_agent_client__WEBPACK_IMPORTED_MODULE_5__["InviteUserAgentClient"]; }); + +/* harmony import */ var _invite_user_agent_server__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(93); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InviteUserAgentServer", function() { return _invite_user_agent_server__WEBPACK_IMPORTED_MODULE_6__["InviteUserAgentServer"]; }); + +/* harmony import */ var _message_user_agent_client__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(68); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MessageUserAgentClient", function() { return _message_user_agent_client__WEBPACK_IMPORTED_MODULE_7__["MessageUserAgentClient"]; }); + +/* harmony import */ var _message_user_agent_server__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(69); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MessageUserAgentServer", function() { return _message_user_agent_server__WEBPACK_IMPORTED_MODULE_8__["MessageUserAgentServer"]; }); + +/* harmony import */ var _notify_user_agent_client__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(70); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NotifyUserAgentClient", function() { return _notify_user_agent_client__WEBPACK_IMPORTED_MODULE_9__["NotifyUserAgentClient"]; }); + +/* harmony import */ var _notify_user_agent_server__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(71); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NotifyUserAgentServer", function() { return _notify_user_agent_server__WEBPACK_IMPORTED_MODULE_10__["NotifyUserAgentServer"]; }); + +/* harmony import */ var _publish_user_agent_client__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(94); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PublishUserAgentClient", function() { return _publish_user_agent_client__WEBPACK_IMPORTED_MODULE_11__["PublishUserAgentClient"]; }); + +/* harmony import */ var _prack_user_agent_client__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(72); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PrackUserAgentClient", function() { return _prack_user_agent_client__WEBPACK_IMPORTED_MODULE_12__["PrackUserAgentClient"]; }); + +/* harmony import */ var _prack_user_agent_server__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(73); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PrackUserAgentServer", function() { return _prack_user_agent_server__WEBPACK_IMPORTED_MODULE_13__["PrackUserAgentServer"]; }); + +/* harmony import */ var _re_invite_user_agent_client__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(74); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReInviteUserAgentClient", function() { return _re_invite_user_agent_client__WEBPACK_IMPORTED_MODULE_14__["ReInviteUserAgentClient"]; }); + +/* harmony import */ var _re_invite_user_agent_server__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(75); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReInviteUserAgentServer", function() { return _re_invite_user_agent_server__WEBPACK_IMPORTED_MODULE_15__["ReInviteUserAgentServer"]; }); + +/* harmony import */ var _re_subscribe_user_agent_client__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(83); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReSubscribeUserAgentClient", function() { return _re_subscribe_user_agent_client__WEBPACK_IMPORTED_MODULE_16__["ReSubscribeUserAgentClient"]; }); + +/* harmony import */ var _re_subscribe_user_agent_server__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(95); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReSubscribeUserAgentServer", function() { return _re_subscribe_user_agent_server__WEBPACK_IMPORTED_MODULE_17__["ReSubscribeUserAgentServer"]; }); + +/* harmony import */ var _refer_user_agent_client__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(76); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReferUserAgentClient", function() { return _refer_user_agent_client__WEBPACK_IMPORTED_MODULE_18__["ReferUserAgentClient"]; }); + +/* harmony import */ var _refer_user_agent_server__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(77); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReferUserAgentServer", function() { return _refer_user_agent_server__WEBPACK_IMPORTED_MODULE_19__["ReferUserAgentServer"]; }); + +/* harmony import */ var _register_user_agent_client__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(96); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RegisterUserAgentClient", function() { return _register_user_agent_client__WEBPACK_IMPORTED_MODULE_20__["RegisterUserAgentClient"]; }); + +/* harmony import */ var _register_user_agent_server__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(97); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RegisterUserAgentServer", function() { return _register_user_agent_server__WEBPACK_IMPORTED_MODULE_21__["RegisterUserAgentServer"]; }); + +/* harmony import */ var _subscribe_user_agent_client__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(98); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubscribeUserAgentClient", function() { return _subscribe_user_agent_client__WEBPACK_IMPORTED_MODULE_22__["SubscribeUserAgentClient"]; }); + +/* harmony import */ var _subscribe_user_agent_server__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(99); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubscribeUserAgentServer", function() { return _subscribe_user_agent_server__WEBPACK_IMPORTED_MODULE_23__["SubscribeUserAgentServer"]; }); + +/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(63); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgentClient", function() { return _user_agent_client__WEBPACK_IMPORTED_MODULE_24__["UserAgentClient"]; }); + +/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(65); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgentServer", function() { return _user_agent_server__WEBPACK_IMPORTED_MODULE_25__["UserAgentServer"]; }); + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/***/ }), +/* 91 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CancelUserAgentClient", function() { return CancelUserAgentClient; }); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); +/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(63); + + +/** + * CANCEL UAC. + * @public + */ +class CancelUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_1__["UserAgentClient"] { + constructor(core, message, delegate) { + super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteClientTransaction"], core, message, delegate); + } +} + + +/***/ }), +/* 92 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InviteUserAgentClient", function() { return InviteUserAgentClient; }); +/* harmony import */ var _dialogs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _session__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(44); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(48); +/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(63); + + + + +/** + * 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 + */ +class InviteUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_3__["UserAgentClient"] { + constructor(core, message, delegate) { + super(_transactions__WEBPACK_IMPORTED_MODULE_2__["InviteClientTransaction"], core, message, delegate); + this.confirmedDialogAcks = new Map(); + this.confirmedDialogs = new Map(); + this.earlyDialogs = new Map(); + this.delegate = delegate; + } + dispose() { + // 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((earlyDialog) => earlyDialog.dispose()); + this.earlyDialogs.clear(); + super.dispose(); + } + /** + * Special case for transport error while sending ACK. + * @param error - Transport error + */ + onTransportError(error) { + if (this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Calling) { + return super.onTransportError(error); + } + // If not in 'calling' state, the transport error occurred while sending an ACK. + this.logger.error(error.message); + this.logger.error("User agent client request transport error while sending ACK."); + } + /** + * 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. + */ + receiveResponse(message) { + if (!this.authenticationGuard(message)) { + return; + } + const 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 }); + } + 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 + { + // Dialogs are created through the generation of non-failure responses + // to requests with specific methods. Within this specification, only + // 2xx and 101-199 responses with a To tag, where the request was + // INVITE, will establish a dialog. A dialog established by a non-final + // response to a request is in the "early" state and it is called an + // early dialog. + // https://tools.ietf.org/html/rfc3261#section-12.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; + } + // 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. + // https://tools.ietf.org/html/rfc3261#section-12.1.1 + // Provisional without Contact header field, malformed response. + const contact = message.parseHeader("contact"); + if (!contact) { + this.logger.error("Non-100 1xx INVITE response received without a Contact header field, dropping."); + return; + } + // Compute dialog state. + const dialogState = _dialogs__WEBPACK_IMPORTED_MODULE_0__["Dialog"].initialDialogStateForUserAgentClient(this.message, message); + // Have existing early dialog or create a new one. + let earlyDialog = this.earlyDialogs.get(dialogState.id); + if (!earlyDialog) { + const transaction = this.transaction; + if (!(transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_2__["InviteClientTransaction"])) { + throw new Error("Transaction not instance of InviteClientTransaction."); + } + earlyDialog = new _dialogs__WEBPACK_IMPORTED_MODULE_0__["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 or is a retransmission, 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__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Initial || + earlyDialog.signalingState === _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveLocalOffer) { + earlyDialog.signalingStateTransition(message); + } + // Pass response to delegate. + const session = earlyDialog; + if (this.delegate && this.delegate.onProgress) { + this.delegate.onProgress({ + message, + session, + prack: (options) => { + const outgoingPrackRequest = session.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 + { + // Dialogs are created through the generation of non-failure responses + // to requests with specific methods. Within this specification, only + // 2xx and 101-199 responses with a To tag, where the request was + // INVITE, will establish a dialog. A dialog established by a non-final + // response to a request is in the "early" state and it is called an + // early dialog. + // https://tools.ietf.org/html/rfc3261#section-12.1 + // Final without to tag, malformed response. + if (!message.toTag) { + this.logger.error("2xx INVITE response received without a to tag, dropping."); + return; + } + // 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. + // https://tools.ietf.org/html/rfc3261#section-12.1.1 + // Final without Contact header field, malformed response. + const contact = message.parseHeader("contact"); + if (!contact) { + this.logger.error("2xx INVITE response received without a Contact header field, dropping."); + return; + } + // Compute dialog state. + const dialogState = _dialogs__WEBPACK_IMPORTED_MODULE_0__["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. + let 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 + const outgoingAckRequest = this.confirmedDialogAcks.get(dialogState.id); + if (outgoingAckRequest) { + const transaction = this.transaction; + if (!(transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_2__["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 { + const transaction = this.transaction; + if (!(transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_2__["InviteClientTransaction"])) { + throw new Error("Transaction not instance of InviteClientTransaction."); + } + dialog = new _dialogs__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Initial || + dialog.signalingState === _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveLocalOffer) { + dialog.signalingStateTransition(message); + } + // Session Initiated! :) + const session = 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, + session, + ack: (options) => { + const outgoingAckRequest = session.ack(options); + this.confirmedDialogAcks.set(session.id, outgoingAckRequest); + return outgoingAckRequest; + } + }); + } + else { + const outgoingAckRequest = session.ack(); + this.confirmedDialogAcks.set(session.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((earlyDialog) => 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 }); + } + 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((earlyDialog) => 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 }); + } + return; + default: + throw new Error(`Invalid status code ${statusCode}`); + } + throw new Error(`Executing what should be an unreachable code path receiving ${statusCode} response.`); + } +} + + +/***/ }), +/* 93 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InviteUserAgentServer", function() { return InviteUserAgentServer; }); +/* harmony import */ var _dialogs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _exceptions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(51); +/* harmony import */ var _session__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(44); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(48); +/* harmony import */ var _user_agent_core_allowed_methods__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(82); +/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(65); + + + + + + +/** + * 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 + */ +class InviteUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_5__["UserAgentServer"] { + constructor(core, message, delegate) { + super(_transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"], core, message, delegate); + this.core = core; + } + dispose() { + if (this.earlyDialog) { + this.earlyDialog.dispose(); + } + super.dispose(); + } + /** + * 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 = { statusCode: 200 }) { + if (!this.acceptable) { + throw new _exceptions__WEBPACK_IMPORTED_MODULE_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 { + const transaction = this.transaction; + if (!(transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"])) { + throw new Error("Transaction not instance of InviteClientTransaction."); + } + const state = _dialogs__WEBPACK_IMPORTED_MODULE_0__["Dialog"].initialDialogStateForUserAgentServer(this.message, this.toTag); + this.confirmedDialog = new _dialogs__WEBPACK_IMPORTED_MODULE_0__["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 + const recordRouteHeader = this.message.getHeaders("record-route").map((header) => `Record-Route: ${header}`); + const 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. + const allowHeader = "Allow: " + _user_agent_core_allowed_methods__WEBPACK_IMPORTED_MODULE_4__["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__WEBPACK_IMPORTED_MODULE_2__["SignalingState"].Stable) { + options.body = this.confirmedDialog.answer; // resend the answer sent in provisional response + } + else if (this.confirmedDialog.signalingState === _session__WEBPACK_IMPORTED_MODULE_2__["SignalingState"].Initial || + this.confirmedDialog.signalingState === _session__WEBPACK_IMPORTED_MODULE_2__["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); + const response = super.accept(options); + const session = this.confirmedDialog; + const result = Object.assign(Object.assign({}, response), { 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__WEBPACK_IMPORTED_MODULE_2__["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. + */ + progress(options = { statusCode: 180 }) { + if (!this.progressable) { + throw new _exceptions__WEBPACK_IMPORTED_MODULE_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) { + const transaction = this.transaction; + if (!(transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"])) { + throw new Error("Transaction not instance of InviteClientTransaction."); + } + const state = _dialogs__WEBPACK_IMPORTED_MODULE_0__["Dialog"].initialDialogStateForUserAgentServer(this.message, this.toTag, true); + this.earlyDialog = new _dialogs__WEBPACK_IMPORTED_MODULE_0__["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 + const recordRouteHeader = this.message.getHeaders("record-route").map((header) => `Record-Route: ${header}`); + const contactHeader = `Contact: ${this.core.configuration.contact}`; + options.extraHeaders = options.extraHeaders || []; + options.extraHeaders = options.extraHeaders.concat(recordRouteHeader); + options.extraHeaders.push(contactHeader); + const response = super.progress(options); + const session = this.earlyDialog; + const result = Object.assign(Object.assign({}, response), { 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__WEBPACK_IMPORTED_MODULE_2__["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. + */ + redirect(contacts, options = { statusCode: 302 }) { + return super.redirect(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. + */ + reject(options = { statusCode: 486 }) { + return super.reject(options); + } +} + + +/***/ }), +/* 94 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PublishUserAgentClient", function() { return PublishUserAgentClient; }); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); +/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(63); + + +/** + * PUBLISH UAC. + * @public + */ +class PublishUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_1__["UserAgentClient"] { + constructor(core, message, delegate) { + super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteClientTransaction"], core, message, delegate); + } +} + + +/***/ }), +/* 95 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReSubscribeUserAgentServer", function() { return ReSubscribeUserAgentServer; }); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); +/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); + + +/** + * Re-SUBSCRIBE UAS. + * @public + */ +class ReSubscribeUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { + constructor(dialog, message, delegate) { + super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteServerTransaction"], dialog.userAgentCore, message, delegate); + } +} + + +/***/ }), +/* 96 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RegisterUserAgentClient", function() { return RegisterUserAgentClient; }); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); +/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(63); + + +/** + * REGISTER UAC. + * @public + */ +class RegisterUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_1__["UserAgentClient"] { + constructor(core, message, delegate) { + super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteClientTransaction"], core, message, delegate); + } +} + + +/***/ }), +/* 97 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RegisterUserAgentServer", function() { return RegisterUserAgentServer; }); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); +/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); + + +/** + * REGISTER UAS. + * @public + */ +class RegisterUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { + constructor(core, message, delegate) { + super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteServerTransaction"], core, message, delegate); + this.core = core; + } +} + + +/***/ }), +/* 98 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubscribeUserAgentClient", function() { return SubscribeUserAgentClient; }); +/* harmony import */ var _dialogs_subscription_dialog__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(78); +/* harmony import */ var _subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(79); +/* harmony import */ var _timers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(47); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(48); +/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(63); + + + + + +/** + * 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 requests. + * @public + */ +class SubscribeUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_4__["UserAgentClient"] { + constructor(core, message, delegate) { + // Get event from request message. + const event = message.getHeader("Event"); + if (!event) { + throw new Error("Event undefined"); + } + // Get expires from request message. + const expires = message.getHeader("Expires"); + if (!expires) { + throw new Error("Expires undefined"); + } + super(_transactions__WEBPACK_IMPORTED_MODULE_3__["NonInviteClientTransaction"], core, message, delegate); + 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__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].NotifyWait; + // Start waiting for a NOTIFY we can use to create a subscription. + this.waitNotifyStart(); + } + /** + * 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() { + super.dispose(); + } + /** + * Handle out of dialog NOTIFY associated 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) { + // 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 + const 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 + const 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. + const 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 + const 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 multiple subscriptions. + // As such and in accordance with the specification, 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 subscription state. + switch (state) { + case "pending": + this.subscriptionState = _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Pending; + break; + case "active": + this.subscriptionState = _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Active; + break; + case "terminated": + this.subscriptionState = _subscription__WEBPACK_IMPORTED_MODULE_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__WEBPACK_IMPORTED_MODULE_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 + const dialogState = _dialogs_subscription_dialog__WEBPACK_IMPORTED_MODULE_0__["SubscriptionDialog"].initialDialogStateForSubscription(this.message, uas.message); + // Subscription Initiated! :) + this.dialog = new _dialogs_subscription_dialog__WEBPACK_IMPORTED_MODULE_0__["SubscriptionDialog"](this.subscriptionEvent, this.subscriptionExpires, this.subscriptionState, this.core, dialogState); + } + // Delegate. + if (this.delegate && this.delegate.onNotify) { + const request = uas; + const subscription = this.dialog; + this.delegate.onNotify({ request, subscription }); + } + else { + uas.accept(); + } + } + waitNotifyStart() { + 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(() => this.timerN(), _timers__WEBPACK_IMPORTED_MODULE_2__["Timers"].TIMER_N); + } + } + waitNotifyStop() { + 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. + */ + receiveResponse(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 + const expires = message.getHeader("Expires"); + if (!expires) { + this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE"); + } + else { + const 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.receiveResponse(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 + */ + timerN() { + 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(); + } + } +} + + +/***/ }), +/* 99 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubscribeUserAgentServer", function() { return SubscribeUserAgentServer; }); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); +/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); + + +/** + * SUBSCRIBE UAS. + * @public + */ +class SubscribeUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { + constructor(core, message, delegate) { + super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteServerTransaction"], core, message, delegate); + this.core = core; + } +} + + +/***/ }), +/* 100 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 101 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 102 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 103 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RequestPendingError", function() { return RequestPendingError; }); +/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); + +/** + * An exception indicating an outstanding prior request prevented execution. + * @public + */ +class RequestPendingError extends _core__WEBPACK_IMPORTED_MODULE_0__["Exception"] { + /** @internal */ + constructor(message) { + super(message ? message : "Request pending."); + } +} + + +/***/ }), +/* 104 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SessionDescriptionHandlerError", function() { return SessionDescriptionHandlerError; }); +/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); + +/** + * An exception indicating a session description handler error occured. + * @public + */ +class SessionDescriptionHandlerError extends _core__WEBPACK_IMPORTED_MODULE_0__["Exception"] { + constructor(message) { + super(message ? message : "Unspecified session description handler error."); + } +} + + +/***/ }), +/* 105 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SessionTerminatedError", function() { return SessionTerminatedError; }); +/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); + +/** + * An exception indicating the session terminated before the action completed. + * @public + */ +class SessionTerminatedError extends _core__WEBPACK_IMPORTED_MODULE_0__["Exception"] { + constructor() { + super("The session has terminated."); + } +} + + +/***/ }), +/* 106 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StateTransitionError", function() { return StateTransitionError; }); +/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); + +/** + * An exception indicating an invalid state transition error occured. + * @public + */ +class StateTransitionError extends _core__WEBPACK_IMPORTED_MODULE_0__["Exception"] { + constructor(message) { + super(message ? message : "An error occurred during state transition."); + } +} + + +/***/ }), +/* 107 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Bye", function() { return Bye; }); +/** + * A request to end a {@link Session} (incoming BYE). + * @public + */ +class Bye { + /** @internal */ + constructor(incomingByeRequest) { + this.incomingByeRequest = incomingByeRequest; + } + /** Incoming BYE request message. */ + get request() { + return this.incomingByeRequest.message; + } + /** Accept the request. */ + accept(options) { + this.incomingByeRequest.accept(options); + return Promise.resolve(); + } + /** Reject the request. */ + reject(options) { + this.incomingByeRequest.reject(options); + return Promise.resolve(); + } +} + + +/***/ }), +/* 108 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EmitterImpl", function() { return EmitterImpl; }); +/** + * An {@link Emitter} implementation. + * @internal + */ +class EmitterImpl { + constructor() { + this.listeners = new Array(); + } + /** + * Sets up a function that will be called whenever the target changes. + * @param listener - Callback function. + * @param options - An options object that specifies characteristics about the listener. + * If once true, indicates that the listener should be invoked at most once after being added. + * If once true, the listener would be automatically removed when invoked. + */ + addListener(listener, options) { + const onceWrapper = (data) => { + this.removeListener(onceWrapper); + listener(data); + }; + (options === null || options === void 0 ? void 0 : options.once) === true ? this.listeners.push(onceWrapper) : this.listeners.push(listener); + } + /** + * Emit change. + * @param data - Data to emit. + */ + emit(data) { + this.listeners.slice().forEach((listener) => listener(data)); + } + /** + * Removes all listeners previously registered with addListener. + */ + removeAllListeners() { + this.listeners = []; + } + /** + * Removes a listener previously registered with addListener. + * @param listener - Callback function. + */ + removeListener(listener) { + this.listeners = this.listeners.filter((l) => l !== listener); + } + /** + * Registers a listener. + * @param listener - Callback function. + * @deprecated Use addListener. + */ + on(listener) { + return this.addListener(listener); + } + /** + * Unregisters a listener. + * @param listener - Callback function. + * @deprecated Use removeListener. + */ + off(listener) { + return this.removeListener(listener); + } + /** + * Registers a listener then unregisters the listener after one event emission. + * @param listener - Callback function. + * @deprecated Use addListener. + */ + once(listener) { + return this.addListener(listener, { once: true }); + } +} + + +/***/ }), +/* 109 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Info", function() { return Info; }); +/** + * An exchange of information (incoming INFO). + * @public + */ +class Info { + /** @internal */ + constructor(incomingInfoRequest) { + this.incomingInfoRequest = incomingInfoRequest; + } + /** Incoming MESSAGE request message. */ + get request() { + return this.incomingInfoRequest.message; + } + /** Accept the request. */ + accept(options) { + this.incomingInfoRequest.accept(options); + return Promise.resolve(); + } + /** Reject the request. */ + reject(options) { + this.incomingInfoRequest.reject(options); + return Promise.resolve(); + } +} + + +/***/ }), +/* 110 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 111 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 112 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 113 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Invitation", function() { return Invitation; }); +/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); +/* harmony import */ var _core_messages_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(32); +/* harmony import */ var _exceptions__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(3); +/* harmony import */ var _session__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(114); +/* harmony import */ var _session_state__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(118); +/* harmony import */ var _user_agent_options__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(119); + + + + + + +/** + * An invitation is an offer to establish a {@link Session} (incoming INVITE). + * @public + */ +class Invitation extends _session__WEBPACK_IMPORTED_MODULE_3__["Session"] { + /** @internal */ + constructor(userAgent, incomingInviteRequest) { + super(userAgent); + this.incomingInviteRequest = incomingInviteRequest; + /** True if dispose() has been called. */ + this.disposed = false; + /** INVITE will be rejected if not accepted within a certain period time. */ + this.expiresTimer = undefined; + /** True if this Session has been Terminated due to a CANCEL request. */ + this.isCanceled = false; + /** Are reliable provisional responses required or supported. */ + this.rel100 = "none"; + /** The current RSeq header value. */ + this.rseq = Math.floor(Math.random() * 10000); + /** INVITE will be rejected if final response not sent in a certain period time. */ + this.userNoAnswerTimer = undefined; + /** True if waiting for a PRACK before sending a 200 Ok. */ + this.waitingForPrack = false; + this.logger = userAgent.getLogger("sip.Invitation"); + const incomingRequestMessage = this.incomingInviteRequest.message; + // Set 100rel if necessary + const requireHeader = incomingRequestMessage.getHeader("require"); + if (requireHeader && requireHeader.toLowerCase().includes("100rel")) { + this.rel100 = "required"; + } + const supportedHeader = incomingRequestMessage.getHeader("supported"); + if (supportedHeader && supportedHeader.toLowerCase().includes("100rel")) { + this.rel100 = "supported"; + } + // FIXME: HACK: This is a hack to port an existing behavior. + // Set the toTag on the incoming request message to the toTag which + // will be used in the response to the incoming request!!! + // 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). + // eslint-disable-next-line @typescript-eslint/no-explicit-any + incomingRequestMessage.toTag = incomingInviteRequest.toTag; + if (typeof incomingRequestMessage.toTag !== "string") { + throw new TypeError("toTag should have been a string."); + } + // The following mapping values are RECOMMENDED: + // ... + // 19 no answer from the user 480 Temporarily unavailable + // https://tools.ietf.org/html/rfc3398#section-7.2.4.1 + this.userNoAnswerTimer = setTimeout(() => { + incomingInviteRequest.reject({ statusCode: 480 }); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Terminated); + }, this.userAgent.configuration.noAnswerTimeout ? this.userAgent.configuration.noAnswerTimeout * 1000 : 60000); + // 1. If the request is an INVITE that contains an Expires header + // field, the UAS core sets a timer for the number of seconds + // indicated in the header field value. When the timer fires, the + // invitation is considered to be expired. If the invitation + // expires before the UAS has generated a final response, a 487 + // (Request Terminated) response SHOULD be generated. + // https://tools.ietf.org/html/rfc3261#section-13.3.1 + if (incomingRequestMessage.hasHeader("expires")) { + const expires = Number(incomingRequestMessage.getHeader("expires") || 0) * 1000; + this.expiresTimer = setTimeout(() => { + if (this.state === _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Initial) { + incomingInviteRequest.reject({ statusCode: 487 }); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Terminated); + } + }, expires); + } + // Session parent properties + const assertedIdentity = this.request.getHeader("P-Asserted-Identity"); + if (assertedIdentity) { + this._assertedIdentity = _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].nameAddrHeaderParse(assertedIdentity); + } + this._contact = this.userAgent.contact.toString(); + const contentDisposition = incomingRequestMessage.parseHeader("Content-Disposition"); + if (contentDisposition && contentDisposition.type === "render") { + this._renderbody = incomingRequestMessage.body; + this._rendertype = incomingRequestMessage.getHeader("Content-Type"); + } + // Identifier + this._id = incomingRequestMessage.callId + incomingRequestMessage.fromTag; + // Add to the user agent's session collection. + this.userAgent._sessions[this._id] = this; + } + /** + * Destructor. + */ + dispose() { + // Only run through this once. It can and does get called multiple times + // depending on the what the sessions state is when first called. + // For example, if called when "establishing" it will be called again + // at least once when the session transitions to "terminated". + // Regardless, running through this more than once is pointless. + if (this.disposed) { + return Promise.resolve(); + } + this.disposed = true; + // Clear timers + if (this.expiresTimer) { + clearTimeout(this.expiresTimer); + this.expiresTimer = undefined; + } + if (this.userNoAnswerTimer) { + clearTimeout(this.userNoAnswerTimer); + this.userNoAnswerTimer = undefined; + } + // If accept() is still waiting for a PRACK, make sure it rejects + this.prackNeverArrived(); + // If the final response for the initial INVITE not yet been sent, reject it + switch (this.state) { + case _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Initial: + return this.reject().then(() => super.dispose()); + case _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Establishing: + return this.reject().then(() => super.dispose()); + case _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Established: + return super.dispose(); + case _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Terminating: + return super.dispose(); + case _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Terminated: + return super.dispose(); + default: + throw new Error("Unknown state."); + } + } + /** + * 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 autoSendAnInitialProvisionalResponse() { + return this.rel100 === "required" ? false : true; + } + /** + * Initial incoming INVITE request message body. + */ + get body() { + return this.incomingInviteRequest.message.body; + } + /** + * The identity of the local user. + */ + get localIdentity() { + return this.request.to; + } + /** + * The identity of the remote user. + */ + get remoteIdentity() { + return this.request.from; + } + /** + * Initial incoming INVITE request message. + */ + get request() { + return this.incomingInviteRequest.message; + } + /** + * Accept the invitation. + * + * @remarks + * Accept the incoming INVITE request to start a Session. + * Replies to the INVITE request with a 200 Ok response. + * Resolves once the response sent, otherwise rejects. + * + * This method may reject for a variety of reasons including + * the receipt of a CANCEL request before `accept` is able + * to construct a response. + * @param options - Options bucket. + */ + accept(options = {}) { + this.logger.log("Invitation.accept"); + // validate state + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Initial) { + const error = new Error(`Invalid session state ${this.state}`); + this.logger.error(error.message); + return Promise.reject(error); + } + // Modifiers and options for initial INVITE transaction + if (options.sessionDescriptionHandlerModifiers) { + this.sessionDescriptionHandlerModifiers = options.sessionDescriptionHandlerModifiers; + } + if (options.sessionDescriptionHandlerOptions) { + this.sessionDescriptionHandlerOptions = options.sessionDescriptionHandlerOptions; + } + // transition state + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Establishing); + return (this.sendAccept() + // eslint-disable-next-line @typescript-eslint/no-unused-vars + .then(({ message, session }) => { + session.delegate = { + onAck: (ackRequest) => this.onAckRequest(ackRequest), + onAckTimeout: () => this.onAckTimeout(), + onBye: (byeRequest) => this.onByeRequest(byeRequest), + onInfo: (infoRequest) => this.onInfoRequest(infoRequest), + onInvite: (inviteRequest) => this.onInviteRequest(inviteRequest), + onMessage: (messageRequest) => this.onMessageRequest(messageRequest), + onNotify: (notifyRequest) => this.onNotifyRequest(notifyRequest), + onPrack: (prackRequest) => this.onPrackRequest(prackRequest), + onRefer: (referRequest) => this.onReferRequest(referRequest) + }; + this._dialog = session; + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Established); + // TODO: Reconsider this "automagic" send of a BYE to replacee behavior. + // This behavior has been ported forward from legacy versions. + if (this._replacee) { + this._replacee._bye(); + } + }) + .catch((error) => this.handleResponseError(error))); + } + /** + * Indicate progress processing the invitation. + * + * @remarks + * Report progress to the the caller. + * Replies to the INVITE request with a 1xx provisional response. + * Resolves once the response sent, otherwise rejects. + * @param options - Options bucket. + */ + progress(options = {}) { + this.logger.log("Invitation.progress"); + // validate state + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Initial) { + const error = new Error(`Invalid session state ${this.state}`); + this.logger.error(error.message); + return Promise.reject(error); + } + // Ported + const statusCode = options.statusCode || 180; + if (statusCode < 100 || statusCode > 199) { + throw new TypeError("Invalid statusCode: " + statusCode); + } + // Modifiers and options for initial INVITE transaction + if (options.sessionDescriptionHandlerModifiers) { + this.sessionDescriptionHandlerModifiers = options.sessionDescriptionHandlerModifiers; + } + if (options.sessionDescriptionHandlerOptions) { + this.sessionDescriptionHandlerOptions = options.sessionDescriptionHandlerOptions; + } + // 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.waitingForPrack) { + this.logger.warn("Unexpected call for progress while waiting for prack, ignoring"); + return Promise.resolve(); + } + // Trying provisional response + if (options.statusCode === 100) { + return this.sendProgressTrying() + .then(() => { + return; + }) + .catch((error) => this.handleResponseError(error)); + } + // Standard provisional response + if (!(this.rel100 === "required") && + !(this.rel100 === "supported" && options.rel100) && + !(this.rel100 === "supported" && this.userAgent.configuration.sipExtension100rel === _user_agent_options__WEBPACK_IMPORTED_MODULE_5__["SIPExtension"].Required)) { + return this.sendProgress(options) + .then(() => { + return; + }) + .catch((error) => this.handleResponseError(error)); + } + // Reliable provisional response + return this.sendProgressReliableWaitForPrack(options) + .then(() => { + return; + }) + .catch((error) => this.handleResponseError(error)); + } + /** + * Reject the invitation. + * + * @remarks + * Replies to the INVITE request with a 4xx, 5xx, or 6xx final response. + * Resolves once the response sent, otherwise rejects. + * + * The expectation is that this method is used to reject an INVITE request. + * That is indeed the case - a call to `progress` followed by `reject` is + * a typical way to "decline" an incoming INVITE request. However it may + * also be called after calling `accept` (but only before it completes) + * which will reject the call and cause `accept` to reject. + * @param options - Options bucket. + */ + reject(options = {}) { + this.logger.log("Invitation.reject"); + // validate state + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Initial && this.state !== _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Establishing) { + const error = new Error(`Invalid session state ${this.state}`); + this.logger.error(error.message); + return Promise.reject(error); + } + const statusCode = options.statusCode || 480; + const reasonPhrase = options.reasonPhrase ? options.reasonPhrase : Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["getReasonPhrase"])(statusCode); + const extraHeaders = options.extraHeaders || []; + if (statusCode < 300 || statusCode > 699) { + throw new TypeError("Invalid statusCode: " + statusCode); + } + const body = options.body ? Object(_core__WEBPACK_IMPORTED_MODULE_0__["fromBodyLegacy"])(options.body) : undefined; + // FIXME: Need to redirect to someplace + statusCode < 400 + ? this.incomingInviteRequest.redirect([], { statusCode, reasonPhrase, extraHeaders, body }) + : this.incomingInviteRequest.reject({ statusCode, reasonPhrase, extraHeaders, body }); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Terminated); + return Promise.resolve(); + } + /** + * Handle CANCEL request. + * + * @param message - CANCEL message. + * @internal + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _onCancel(message) { + this.logger.log("Invitation._onCancel"); + // validate state + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Initial && this.state !== _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Establishing) { + this.logger.error(`CANCEL received while in state ${this.state}, dropping request`); + return; + } + // flag canceled + this.isCanceled = true; + // reject INVITE with 487 status code + this.incomingInviteRequest.reject({ statusCode: 487 }); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Terminated); + } + /** + * Helper function to handle offer/answer in a PRACK. + */ + handlePrackOfferAnswer(request) { + if (!this.dialog) { + throw new Error("Dialog undefined."); + } + // If the PRACK doesn't have an offer/answer, nothing to be done. + const body = Object(_core__WEBPACK_IMPORTED_MODULE_0__["getBody"])(request.message); + if (!body || body.contentDisposition !== "session") { + return Promise.resolve(undefined); + } + const options = { + sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, + sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers + }; + // 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__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Stable: + // Receved answer. + return this.setAnswer(body, options).then(() => undefined); + case _core__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].HaveRemoteOffer: + // Received offer, generate answer. + return this.setOfferAndGetAnswer(body, options); + case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Closed: + throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`); + default: + throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`); + } + } + /** + * A handler for errors which occur while attempting to send 1xx and 2xx responses. + * In all cases, an attempt is made to reject the request if it is still outstanding. + * And while there are a variety of things which can go wrong and we log something here + * for all errors, there are a handful of common exceptions we pay some extra attention to. + * @param error - The error which occurred. + */ + handleResponseError(error) { + let statusCode = 480; // "Temporarily Unavailable" + // Log Error message + if (error instanceof Error) { + this.logger.error(error.message); + } + else { + // We don't actually know what a session description handler implementation might throw our way, + // and more generally as a last resort catch all, just assume we are getting an "unknown" and log it. + this.logger.error(error); + } + // Log Exception message + if (error instanceof _exceptions__WEBPACK_IMPORTED_MODULE_2__["ContentTypeUnsupportedError"]) { + this.logger.error("A session description handler occurred while sending response (content type unsupported"); + statusCode = 415; // "Unsupported Media Type" + } + else if (error instanceof _exceptions__WEBPACK_IMPORTED_MODULE_2__["SessionDescriptionHandlerError"]) { + this.logger.error("A session description handler occurred while sending response"); + } + else if (error instanceof _exceptions__WEBPACK_IMPORTED_MODULE_2__["SessionTerminatedError"]) { + this.logger.error("Session ended before response could be formulated and sent (while waiting for PRACK)"); + } + else if (error instanceof _core__WEBPACK_IMPORTED_MODULE_0__["TransactionStateError"]) { + this.logger.error("Session changed state before response could be formulated and sent"); + } + // Reject if still in "initial" or "establishing" state. + if (this.state === _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Initial || this.state === _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Establishing) { + try { + this.incomingInviteRequest.reject({ statusCode }); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Terminated); + } + catch (e) { + this.logger.error("An error occurred attempting to reject the request while handling another error"); + throw e; // This is not a good place to be... + } + } + // FIXME: TODO: + // Here we are squelching the throwing of errors due to an 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 + // these race errors to the caller of `accept()`, we are squelching the throwing + // of ALL errors when/if they occur after receiving a CANCEL to catch the ONE we know + // is a "normal" exceptional condition. While this is a completely reasonable approach, + // the decision should be left up to the library user. Furthermore, as we are eating + // ALL errors in this case, we are potentially (likely) hiding "real" errors which occur. + // + // Only rethrow error if the session has not been canceled. + if (this.isCanceled) { + this.logger.warn("An error occurred while attempting to formulate and send a response to an incoming INVITE." + + " However a CANCEL was received and processed while doing so which can (and often does) result" + + " in errors occurring as the session terminates in the meantime. Said error is being ignored."); + return; + } + throw error; + } + /** + * Callback for when ACK for a 2xx response is never received. + * @param session - Session the ACK never arrived for. + */ + onAckTimeout() { + 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__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Terminated); + } + /** + * A version of `accept` which resolves a session when the 200 Ok response is sent. + * @param options - Options bucket. + */ + sendAccept() { + const responseOptions = { + sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, + sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers + }; + // 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.waitingForPrack) { + return this.waitForArrivalOfPrack() + .then(() => clearTimeout(this.userNoAnswerTimer)) // Ported + .then(() => this.generateResponseOfferAnswer(this.incomingInviteRequest, responseOptions)) + .then((body) => this.incomingInviteRequest.accept({ statusCode: 200, body })); + } + clearTimeout(this.userNoAnswerTimer); // Ported + return this.generateResponseOfferAnswer(this.incomingInviteRequest, responseOptions).then((body) => this.incomingInviteRequest.accept({ statusCode: 200, body })); + } + /** + * A version of `progress` which resolves when the provisional response is sent. + * @param options - Options bucket. + */ + sendProgress(options = {}) { + const statusCode = options.statusCode || 180; + const reasonPhrase = options.reasonPhrase; + const extraHeaders = (options.extraHeaders || []).slice(); + const body = options.body ? Object(_core__WEBPACK_IMPORTED_MODULE_0__["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.sendProgressWithSDP(options); + } + try { + const progressResponse = this.incomingInviteRequest.progress({ statusCode, reasonPhrase, extraHeaders, body }); + 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. + */ + sendProgressWithSDP(options = {}) { + const responseOptions = { + sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, + sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers + }; + const statusCode = options.statusCode || 183; + const reasonPhrase = options.reasonPhrase; + const extraHeaders = (options.extraHeaders || []).slice(); + // Get an offer/answer and send a reply. + return this.generateResponseOfferAnswer(this.incomingInviteRequest, responseOptions) + .then((body) => this.incomingInviteRequest.progress({ statusCode, reasonPhrase, extraHeaders, body })) + .then((progressResponse) => { + this._dialog = progressResponse.session; + return progressResponse; + }); + } + /** + * A version of `progress` which resolves when the reliable provisional response is sent. + * @param options - Options bucket. + */ + sendProgressReliable(options = {}) { + options.extraHeaders = (options.extraHeaders || []).slice(); + options.extraHeaders.push("Require: 100rel"); + options.extraHeaders.push("RSeq: " + Math.floor(Math.random() * 10000)); + return this.sendProgressWithSDP(options); + } + /** + * A version of `progress` which resolves when the reliable provisional response is acknowledged. + * @param options - Options bucket. + */ + sendProgressReliableWaitForPrack(options = {}) { + const responseOptions = { + sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, + sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers + }; + const statusCode = options.statusCode || 183; + const reasonPhrase = options.reasonPhrase; + const extraHeaders = (options.extraHeaders || []).slice(); + extraHeaders.push("Require: 100rel"); + extraHeaders.push("RSeq: " + this.rseq++); + let body; + return new Promise((resolve, reject) => { + this.waitingForPrack = true; + this.generateResponseOfferAnswer(this.incomingInviteRequest, responseOptions) + .then((offerAnswer) => { + body = offerAnswer; + return this.incomingInviteRequest.progress({ statusCode, reasonPhrase, extraHeaders, body }); + }) + .then((progressResponse) => { + this._dialog = progressResponse.session; + let prackRequest; + let prackResponse; + progressResponse.session.delegate = { + onPrack: (request) => { + prackRequest = request; + // eslint-disable-next-line @typescript-eslint/no-use-before-define + clearTimeout(prackWaitTimeoutTimer); + // eslint-disable-next-line @typescript-eslint/no-use-before-define + clearTimeout(rel1xxRetransmissionTimer); + if (!this.waitingForPrack) { + return; + } + this.waitingForPrack = false; + this.handlePrackOfferAnswer(prackRequest) + .then((prackResponseBody) => { + try { + prackResponse = prackRequest.accept({ statusCode: 200, body: prackResponseBody }); + this.prackArrived(); + resolve({ prackRequest, prackResponse, progressResponse }); + } + catch (error) { + reject(error); + } + }) + .catch((error) => reject(error)); + } + }; + // https://tools.ietf.org/html/rfc3262#section-3 + const prackWaitTimeout = () => { + if (!this.waitingForPrack) { + return; + } + this.waitingForPrack = false; + this.logger.warn("No PRACK received, rejecting INVITE."); + // eslint-disable-next-line @typescript-eslint/no-use-before-define + clearTimeout(rel1xxRetransmissionTimer); + this.reject({ statusCode: 504 }) + .then(() => reject(new _exceptions__WEBPACK_IMPORTED_MODULE_2__["SessionTerminatedError"]())) + .catch((error) => reject(error)); + }; + const prackWaitTimeoutTimer = setTimeout(prackWaitTimeout, _core__WEBPACK_IMPORTED_MODULE_0__["Timers"].T1 * 64); + // https://tools.ietf.org/html/rfc3262#section-3 + const rel1xxRetransmission = () => { + try { + this.incomingInviteRequest.progress({ statusCode, reasonPhrase, extraHeaders, body }); + } + catch (error) { + this.waitingForPrack = false; + reject(error); + return; + } + // eslint-disable-next-line @typescript-eslint/no-use-before-define + rel1xxRetransmissionTimer = setTimeout(rel1xxRetransmission, (timeout *= 2)); + }; + let timeout = _core__WEBPACK_IMPORTED_MODULE_0__["Timers"].T1; + let rel1xxRetransmissionTimer = setTimeout(rel1xxRetransmission, timeout); + }) + .catch((error) => { + this.waitingForPrack = false; + reject(error); + }); + }); + } + /** + * A version of `progress` which resolves when a 100 Trying provisional response is sent. + */ + sendProgressTrying() { + try { + const progressResponse = this.incomingInviteRequest.trying(); + return Promise.resolve(progressResponse); + } + catch (error) { + return Promise.reject(error); + } + } + /** + * When attempting to accept the INVITE, an invitation waits + * for any outstanding PRACK to arrive before sending the 200 Ok. + * It will be waiting on this Promise to resolve which lets it know + * the PRACK has arrived and it may proceed to send the 200 Ok. + */ + waitForArrivalOfPrack() { + if (this.waitingForPrackPromise) { + throw new Error("Already waiting for PRACK"); + } + this.waitingForPrackPromise = new Promise((resolve, reject) => { + this.waitingForPrackResolve = resolve; + this.waitingForPrackReject = reject; + }); + return this.waitingForPrackPromise; + } + /** + * Here we are resolving the promise which in turn will cause + * the accept to proceed (it may still fail for other reasons, but...). + */ + prackArrived() { + if (this.waitingForPrackResolve) { + this.waitingForPrackResolve(); + } + this.waitingForPrackPromise = undefined; + this.waitingForPrackResolve = undefined; + this.waitingForPrackReject = undefined; + } + /** + * Here we are rejecting the promise which in turn will cause + * the accept to fail and the session to transition to "terminated". + */ + prackNeverArrived() { + if (this.waitingForPrackReject) { + this.waitingForPrackReject(new _exceptions__WEBPACK_IMPORTED_MODULE_2__["SessionTerminatedError"]()); + } + this.waitingForPrackPromise = undefined; + this.waitingForPrackResolve = undefined; + this.waitingForPrackReject = undefined; + } +} + + +/***/ }), +/* 114 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Session", function() { return Session; }); +/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); +/* harmony import */ var _core_messages_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(32); +/* harmony import */ var _core_user_agent_core_allowed_methods__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(82); +/* harmony import */ var _bye__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(107); +/* harmony import */ var _emitter__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(108); +/* harmony import */ var _exceptions__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(3); +/* harmony import */ var _info__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(109); +/* harmony import */ var _message__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(115); +/* harmony import */ var _notification__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(116); +/* harmony import */ var _referral__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(117); +/* harmony import */ var _session_state__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(118); + + + + + + + + + + + +/** + * A session provides real time communication between one or more participants. + * + * @remarks + * The transport behaves in a deterministic manner according to the + * the state defined in {@link SessionState}. + * @public + */ +class Session { + /** + * Constructor. + * @param userAgent - User agent. See {@link UserAgent} for details. + * @internal + */ + constructor(userAgent, options = {}) { + /** True if there is an outgoing re-INVITE request outstanding. */ + this.pendingReinvite = false; + /** True if there is an incoming re-INVITE ACK request outstanding. */ + this.pendingReinviteAck = false; + /** Session state. */ + this._state = _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Initial; + this.delegate = options.delegate; + this._stateEventEmitter = new _emitter__WEBPACK_IMPORTED_MODULE_4__["EmitterImpl"](); + this._userAgent = userAgent; + } + /** + * Destructor. + */ + dispose() { + this.logger.log(`Session ${this.id} in state ${this._state} is being disposed`); + // Remove from the user agent's session collection + delete this.userAgent._sessions[this.id]; + // Dispose of dialog media + if (this._sessionDescriptionHandler) { + this._sessionDescriptionHandler.close(); + // TODO: The SDH needs to remain defined as it will be called after it is closed in cases + // where an answer/offer arrives while the session is being torn down. There are a variety + // of circumstances where this can happen - sending a BYE during a re-INVITE for example. + // The code is currently written such that it lazily makes a new SDH when it needs one + // and one is not yet defined. Thus if we undefined it here, it will currently make a + // new one which is out of sync and then never gets cleaned up. + // + // The downside of leaving it defined are that calls this closed SDH will continue to be + // made (think setDescription) and those should/will fail. These failures are handled, but + // it would be nice to have it all coded up in a way where having an undefined SDH where + // one is expected throws an error. + // + // this._sessionDescriptionHandler = undefined; + } + switch (this.state) { + case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Initial: + break; // the Inviter/Invitation sub class dispose method handles this case + case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Establishing: + break; // the Inviter/Invitation sub class dispose method handles this case + case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established: + return new Promise((resolve) => { + this._bye({ + // wait for the response to the BYE before resolving + onAccept: () => resolve(), + onRedirect: () => resolve(), + onReject: () => resolve() + }); + }); + case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminating: + break; // nothing to be done + case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated: + break; // nothing to be done + default: + throw new Error("Unknown state."); + } + return Promise.resolve(); + } + /** + * The asserted identity of the remote user. + */ + get assertedIdentity() { + return this._assertedIdentity; + } + /** + * The confirmed session dialog. + */ + get dialog() { + return this._dialog; + } + /** + * A unique identifier for this session. + */ + get id() { + return this._id; + } + /** + * The session being replace by this one. + */ + get replacee() { + return this._replacee; + } + /** + * Session description handler. + * @remarks + * If `this` is an instance of `Invitation`, + * `sessionDescriptionHandler` will be defined when the session state changes to "established". + * If `this` is an instance of `Inviter` and an offer was sent in the INVITE, + * `sessionDescriptionHandler` will be defined when the session state changes to "establishing". + * If `this` is an instance of `Inviter` and an offer was not sent in the INVITE, + * `sessionDescriptionHandler` will be defined when the session state changes to "established". + * Otherwise `undefined`. + */ + get sessionDescriptionHandler() { + return this._sessionDescriptionHandler; + } + /** + * Session description handler factory. + */ + get sessionDescriptionHandlerFactory() { + return this.userAgent.configuration.sessionDescriptionHandlerFactory; + } + /** + * SDH modifiers for the initial INVITE transaction. + * @remarks + * Used in all cases when handling the initial INVITE transaction as either UAC or UAS. + * May be set directly at anytime. + * May optionally be set via constructor option. + * May optionally be set via options passed to Inviter.invite() or Invitation.accept(). + */ + get sessionDescriptionHandlerModifiers() { + return this._sessionDescriptionHandlerModifiers || []; + } + set sessionDescriptionHandlerModifiers(modifiers) { + this._sessionDescriptionHandlerModifiers = modifiers.slice(); + } + /** + * SDH options for the initial INVITE transaction. + * @remarks + * Used in all cases when handling the initial INVITE transaction as either UAC or UAS. + * May be set directly at anytime. + * May optionally be set via constructor option. + * May optionally be set via options passed to Inviter.invite() or Invitation.accept(). + */ + get sessionDescriptionHandlerOptions() { + return this._sessionDescriptionHandlerOptions || {}; + } + set sessionDescriptionHandlerOptions(options) { + this._sessionDescriptionHandlerOptions = Object.assign({}, options); + } + /** + * SDH modifiers for re-INVITE transactions. + * @remarks + * Used in all cases when handling a re-INVITE transaction as either UAC or UAS. + * May be set directly at anytime. + * May optionally be set via constructor option. + * May optionally be set via options passed to Session.invite(). + */ + get sessionDescriptionHandlerModifiersReInvite() { + return this._sessionDescriptionHandlerModifiersReInvite || []; + } + set sessionDescriptionHandlerModifiersReInvite(modifiers) { + this._sessionDescriptionHandlerModifiersReInvite = modifiers.slice(); + } + /** + * SDH options for re-INVITE transactions. + * @remarks + * Used in all cases when handling a re-INVITE transaction as either UAC or UAS. + * May be set directly at anytime. + * May optionally be set via constructor option. + * May optionally be set via options passed to Session.invite(). + */ + get sessionDescriptionHandlerOptionsReInvite() { + return this._sessionDescriptionHandlerOptionsReInvite || {}; + } + set sessionDescriptionHandlerOptionsReInvite(options) { + this._sessionDescriptionHandlerOptionsReInvite = Object.assign({}, options); + } + /** + * Session state. + */ + get state() { + return this._state; + } + /** + * Session state change emitter. + */ + get stateChange() { + return this._stateEventEmitter; + } + /** + * The user agent. + */ + get userAgent() { + return this._userAgent; + } + /** + * End the {@link Session}. Sends a BYE. + * @param options - Options bucket. See {@link SessionByeOptions} for details. + */ + bye(options = {}) { + let message = "Session.bye() may only be called if established session."; + switch (this.state) { + case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Initial: + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (typeof this.cancel === "function") { + message += " However Inviter.invite() has not yet been called."; + message += " Perhaps you should have called Inviter.cancel()?"; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } + else if (typeof this.reject === "function") { + message += " However Invitation.accept() has not yet been called."; + message += " Perhaps you should have called Invitation.reject()?"; + } + break; + case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Establishing: + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (typeof this.cancel === "function") { + message += " However a dialog does not yet exist."; + message += " Perhaps you should have called Inviter.cancel()?"; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } + else if (typeof this.reject === "function") { + message += " However Invitation.accept() has not yet been called (or not yet resolved)."; + message += " Perhaps you should have called Invitation.reject()?"; + } + break; + case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established: { + const requestDelegate = options.requestDelegate; + const requestOptions = this.copyRequestOptions(options.requestOptions); + return this._bye(requestDelegate, requestOptions); + } + case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminating: + message += " However this session is already terminating."; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (typeof this.cancel === "function") { + message += " Perhaps you have already called Inviter.cancel()?"; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } + else if (typeof this.reject === "function") { + message += " Perhaps you have already called Session.bye()?"; + } + break; + case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated: + message += " However this session is already terminated."; + break; + default: + throw new Error("Unknown state"); + } + this.logger.error(message); + return Promise.reject(new Error(`Invalid session state ${this.state}`)); + } + /** + * Share {@link Info} with peer. Sends an INFO. + * @param options - Options bucket. See {@link SessionInfoOptions} for details. + */ + info(options = {}) { + // guard session state + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { + const message = "Session.info() may only be called if established session."; + this.logger.error(message); + return Promise.reject(new Error(`Invalid session state ${this.state}`)); + } + const requestDelegate = options.requestDelegate; + const requestOptions = this.copyRequestOptions(options.requestOptions); + return this._info(requestDelegate, requestOptions); + } + /** + * Renegotiate the session. Sends a re-INVITE. + * @param options - Options bucket. See {@link SessionInviteOptions} for details. + */ + invite(options = {}) { + this.logger.log("Session.invite"); + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { + return Promise.reject(new Error(`Invalid session state ${this.state}`)); + } + if (this.pendingReinvite) { + return Promise.reject(new _exceptions__WEBPACK_IMPORTED_MODULE_5__["RequestPendingError"]("Reinvite in progress. Please wait until complete, then try again.")); + } + this.pendingReinvite = true; + // Modifiers and options for initial INVITE transaction + if (options.sessionDescriptionHandlerModifiers) { + this.sessionDescriptionHandlerModifiersReInvite = options.sessionDescriptionHandlerModifiers; + } + if (options.sessionDescriptionHandlerOptions) { + this.sessionDescriptionHandlerOptionsReInvite = options.sessionDescriptionHandlerOptions; + } + const delegate = { + onAccept: (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 + const body = Object(_core__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); + this.pendingReinvite = false; + return; + } + if (options.withoutSdp) { + // INVITE without SDP - set remote offer and send an answer in the ACK + const answerOptions = { + sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptionsReInvite, + sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiersReInvite + }; + this.setOfferAndGetAnswer(body, answerOptions) + .then((answerBody) => { + response.ack({ body: answerBody }); + }) + .catch((error) => { + // No way to recover, so terminate session and mark as failed. + this.logger.error("Failed to handle offer in 2xx response to re-INVITE"); + this.logger.error(error.message); + if (this.state === _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated) { + // A BYE should not be sent if already terminated. + // For example, a BYE may be sent/received while re-INVITE is outstanding. + response.ack(); + } + else { + this.ackAndBye(response, 488, "Bad Media Description"); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); + } + }) + .then(() => { + this.pendingReinvite = false; + if (options.requestDelegate && options.requestDelegate.onAccept) { + options.requestDelegate.onAccept(response); + } + }); + } + else { + // INVITE with SDP - set remote answer and send an ACK + const answerOptions = { + sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptionsReInvite, + sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiersReInvite + }; + this.setAnswer(body, answerOptions) + .then(() => { + response.ack(); + }) + .catch((error) => { + // No way to recover, so terminate session and mark as failed. + this.logger.error("Failed to handle answer in 2xx response to re-INVITE"); + this.logger.error(error.message); + // A BYE should only be sent if session is not already terminated. + // For example, a BYE may be sent/received while re-INVITE is outstanding. + // The ACK needs to be sent regardless as it was not handled by the transaction. + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated) { + this.ackAndBye(response, 488, "Bad Media Description"); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); + } + else { + response.ack(); + } + }) + .then(() => { + this.pendingReinvite = false; + if (options.requestDelegate && options.requestDelegate.onAccept) { + options.requestDelegate.onAccept(response); + } + }); + } + }, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onProgress: (response) => { + return; + }, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onRedirect: (response) => { + return; + }, + onReject: (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((error) => { + // No way to recover, so terminate session and mark as failed. + this.logger.error("Failed to rollback offer on non-2xx response to re-INVITE"); + this.logger.error(error.message); + // A BYE should only be sent if session is not already terminated. + // For example, a BYE may be sent/received while re-INVITE is outstanding. + // Note that the ACK was already sent by the transaction, so just need to send BYE. + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated) { + if (!this.dialog) { + throw new Error("Dialog undefined."); + } + const extraHeaders = []; + extraHeaders.push("Reason: " + this.getReasonHeaderValue(500, "Internal Server Error")); + this.dialog.bye(undefined, { extraHeaders }); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); + } + }) + .then(() => { + if (options.requestDelegate && options.requestDelegate.onReject) { + options.requestDelegate.onReject(response); + } + }); + } + }, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onTrying: (response) => { + return; + } + }; + const requestOptions = options.requestOptions || {}; + requestOptions.extraHeaders = (requestOptions.extraHeaders || []).slice(); + requestOptions.extraHeaders.push("Allow: " + _core_user_agent_core_allowed_methods__WEBPACK_IMPORTED_MODULE_2__["AllowedMethods"].toString()); + requestOptions.extraHeaders.push("Contact: " + this._contact); + // Just send an INVITE with no sdp... + if (options.withoutSdp) { + if (!this.dialog) { + this.pendingReinvite = false; + throw new Error("Dialog undefined."); + } + return Promise.resolve(this.dialog.invite(delegate, requestOptions)); + } + // Get an offer and send it in an INVITE + const offerOptions = { + sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptionsReInvite, + sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiersReInvite + }; + return this.getOffer(offerOptions) + .then((offerBody) => { + if (!this.dialog) { + this.pendingReinvite = false; + throw new Error("Dialog undefined."); + } + requestOptions.body = offerBody; + return this.dialog.invite(delegate, requestOptions); + }) + .catch((error) => { + this.logger.error(error.message); + this.logger.error("Failed to send re-INVITE"); + this.pendingReinvite = false; + throw error; + }); + } + /** + * Deliver a {@link Message}. Sends a MESSAGE. + * @param options - Options bucket. See {@link SessionMessageOptions} for details. + */ + message(options = {}) { + // guard session state + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { + const message = "Session.message() may only be called if established session."; + this.logger.error(message); + return Promise.reject(new Error(`Invalid session state ${this.state}`)); + } + const requestDelegate = options.requestDelegate; + const requestOptions = this.copyRequestOptions(options.requestOptions); + return this._message(requestDelegate, requestOptions); + } + /** + * Proffer a {@link Referral}. Send a REFER. + * @param referTo - The referral target. If a `Session`, a REFER w/Replaces is sent. + * @param options - Options bucket. See {@link SessionReferOptions} for details. + */ + refer(referTo, options = {}) { + // guard session state + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { + const message = "Session.refer() may only be called if established session."; + this.logger.error(message); + return Promise.reject(new Error(`Invalid session state ${this.state}`)); + } + const requestDelegate = options.requestDelegate; + const requestOptions = this.copyRequestOptions(options.requestOptions); + requestOptions.extraHeaders = requestOptions.extraHeaders + ? requestOptions.extraHeaders.concat(this.referExtraHeaders(this.referToString(referTo))) + : this.referExtraHeaders(this.referToString(referTo)); + return this._refer(options.onNotify, requestDelegate, requestOptions); + } + /** + * Send BYE. + * @param delegate - Request delegate. + * @param options - Request options bucket. + * @internal + */ + _bye(delegate, options) { + // Using core session dialog + if (!this.dialog) { + return Promise.reject(new Error("Session dialog undefined.")); + } + const 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__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Initial: + throw new Error(`Invalid dialog state ${dialog.sessionState}`); + case _core__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Early: // Implementation choice - not sending BYE for early dialogs. + throw new Error(`Invalid dialog state ${dialog.sessionState}`); + case _core__WEBPACK_IMPORTED_MODULE_0__["SessionState"].AckWait: { + // This state only occurs if we are the callee. + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminating); // We're terminating + return new Promise((resolve) => { + dialog.delegate = { + // When ACK shows up, say BYE. + onAck: () => { + const request = dialog.bye(delegate, options); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); + resolve(request); + return Promise.resolve(); + }, + // Or the server transaction times out before the ACK arrives. + onAckTimeout: () => { + const request = dialog.bye(delegate, options); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); + resolve(request); + } + }; + }); + } + case _core__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Confirmed: { + const request = dialog.bye(delegate, options); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); + return Promise.resolve(request); + } + case _core__WEBPACK_IMPORTED_MODULE_0__["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 + */ + _info(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 MESSAGE. + * @param delegate - Request delegate. + * @param options - Request options bucket. + * @internal + */ + _message(delegate, options) { + // Using core session dialog + if (!this.dialog) { + return Promise.reject(new Error("Session dialog undefined.")); + } + return Promise.resolve(this.dialog.message(delegate, options)); + } + /** + * Send REFER. + * @param onNotify - Notification callback. + * @param delegate - Request delegate. + * @param options - Request options bucket. + * @internal + */ + _refer(onNotify, delegate, options) { + // Using core session dialog + if (!this.dialog) { + return Promise.reject(new Error("Session dialog undefined.")); + } + // If set, deliver any in-dialog NOTIFY requests here... + this.onNotify = onNotify; + return Promise.resolve(this.dialog.refer(delegate, options)); + } + /** + * 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 send a BYE. + * Note that the BYE is sent in the dialog associated with the response + * which is not necessarily `this.dialog`. And, accordingly, the + * session state is not transitioned to terminated and session is not closed. + * @param inviteResponse - The response causing the error. + * @param statusCode - Status code for he reason phrase. + * @param reasonPhrase - Reason phrase for the BYE. + * @internal + */ + ackAndBye(response, statusCode, reasonPhrase) { + response.ack(); + const extraHeaders = []; + if (statusCode) { + extraHeaders.push("Reason: " + this.getReasonHeaderValue(statusCode, reasonPhrase)); + } + // Using the dialog session associate with the response (which might not be this.dialog) + response.session.bye(undefined, { extraHeaders }); + } + /** + * Handle in dialog ACK request. + * @internal + */ + onAckRequest(request) { + this.logger.log("Session.onAckRequest"); + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established && this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminating) { + this.logger.error(`ACK received while in state ${this.state}, dropping request`); + return Promise.resolve(); + } + const dialog = this.dialog; + if (!dialog) { + throw new Error("Dialog undefined."); + } + // if received answer in ACK. + const answerOptions = { + sessionDescriptionHandlerOptions: this.pendingReinviteAck + ? this.sessionDescriptionHandlerOptionsReInvite + : this.sessionDescriptionHandlerOptions, + sessionDescriptionHandlerModifiers: this.pendingReinviteAck + ? this._sessionDescriptionHandlerModifiersReInvite + : this._sessionDescriptionHandlerModifiers + }; + // reset pending ACK flag + this.pendingReinviteAck = false; + switch (dialog.signalingState) { + case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Initial: { + // State should never be reached as first reliable response must have answer/offer. + // So we must have never has sent an offer. + this.logger.error(`Invalid signaling state ${dialog.signalingState}.`); + const extraHeaders = ["Reason: " + this.getReasonHeaderValue(488, "Bad Media Description")]; + dialog.bye(undefined, { extraHeaders }); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); + return Promise.resolve(); + } + case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Stable: { + // State we should be in. + // Either the ACK has the answer that got us here, or we were in this state prior to the ACK. + const body = Object(_core__WEBPACK_IMPORTED_MODULE_0__["getBody"])(request.message); + // If the ACK doesn't have an answer, nothing to be done. + if (!body) { + return Promise.resolve(); + } + if (body.contentDisposition === "render") { + this._renderbody = body.content; + this._rendertype = body.contentType; + return Promise.resolve(); + } + if (body.contentDisposition !== "session") { + return Promise.resolve(); + } + return this.setAnswer(body, answerOptions).catch((error) => { + this.logger.error(error.message); + const extraHeaders = ["Reason: " + this.getReasonHeaderValue(488, "Bad Media Description")]; + dialog.bye(undefined, { extraHeaders }); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); + }); + } + case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].HaveLocalOffer: { + // State should never be reached as local offer would be answered by this ACK. + // So we must have received an ACK without an answer. + this.logger.error(`Invalid signaling state ${dialog.signalingState}.`); + const extraHeaders = ["Reason: " + this.getReasonHeaderValue(488, "Bad Media Description")]; + dialog.bye(undefined, { extraHeaders }); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); + return Promise.resolve(); + } + case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].HaveRemoteOffer: { + // State should never be reached as remote offer would be answered in first reliable response. + // So we must have never has sent an answer. + this.logger.error(`Invalid signaling state ${dialog.signalingState}.`); + const extraHeaders = ["Reason: " + this.getReasonHeaderValue(488, "Bad Media Description")]; + dialog.bye(undefined, { extraHeaders }); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); + return Promise.resolve(); + } + case _core__WEBPACK_IMPORTED_MODULE_0__["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 + */ + onByeRequest(request) { + this.logger.log("Session.onByeRequest"); + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { + this.logger.error(`BYE received while in state ${this.state}, dropping request`); + return; + } + if (this.delegate && this.delegate.onBye) { + const bye = new _bye__WEBPACK_IMPORTED_MODULE_3__["Bye"](request); + this.delegate.onBye(bye); + } + else { + request.accept(); + } + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); + } + /** + * Handle in dialog INFO request. + * @internal + */ + onInfoRequest(request) { + this.logger.log("Session.onInfoRequest"); + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { + this.logger.error(`INFO received while in state ${this.state}, dropping request`); + return; + } + if (this.delegate && this.delegate.onInfo) { + const info = new _info__WEBPACK_IMPORTED_MODULE_6__["Info"](request); + this.delegate.onInfo(info); + } + else { + // FIXME: TODO: We should reject request... + // + // 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. + // https://tools.ietf.org/html/rfc6086#section-4.2.2 + request.accept(); + } + } + /** + * Handle in dialog INVITE request. + * @internal + */ + onInviteRequest(request) { + this.logger.log("Session.onInviteRequest"); + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { + this.logger.error(`INVITE received while in state ${this.state}, dropping request`); + return; + } + // set pending ACK flag + this.pendingReinviteAck = true; + // 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. + const extraHeaders = ["Contact: " + this._contact]; + // Handle P-Asserted-Identity + if (request.message.hasHeader("P-Asserted-Identity")) { + const header = request.message.getHeader("P-Asserted-Identity"); + if (!header) { + throw new Error("Header undefined."); + } + this._assertedIdentity = _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].nameAddrHeaderParse(header); + } + const options = { + sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptionsReInvite, + sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiersReInvite + }; + this.generateResponseOfferAnswerInDialog(options) + .then((body) => { + const outgoingResponse = request.accept({ statusCode: 200, extraHeaders, body }); + if (this.delegate && this.delegate.onInvite) { + this.delegate.onInvite(request.message, outgoingResponse.message, 200); + } + }) + .catch((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__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Stable) { + const 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(() => { + const outgoingResponse = request.reject({ statusCode: 488 }); // Not Acceptable Here + if (this.delegate && this.delegate.onInvite) { + this.delegate.onInvite(request.message, outgoingResponse.message, 488); + } + }) + .catch((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"); + const outgoingResponse = request.reject({ statusCode: 488 }); // Not Acceptable Here + // A BYE should only be sent if session is not already terminated. + // For example, a BYE may be sent/received while re-INVITE is outstanding. + // Note that the ACK was already sent by the transaction, so just need to send BYE. + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated) { + if (!this.dialog) { + throw new Error("Dialog undefined."); + } + const extraHeadersBye = []; + extraHeadersBye.push("Reason: " + this.getReasonHeaderValue(500, "Internal Server Error")); + this.dialog.bye(undefined, { extraHeaders }); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); + } + if (this.delegate && this.delegate.onInvite) { + this.delegate.onInvite(request.message, outgoingResponse.message, 488); + } + }); + }); + } + /** + * Handle in dialog MESSAGE request. + * @internal + */ + onMessageRequest(request) { + this.logger.log("Session.onMessageRequest"); + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { + this.logger.error(`MESSAGE received while in state ${this.state}, dropping request`); + return; + } + if (this.delegate && this.delegate.onMessage) { + const message = new _message__WEBPACK_IMPORTED_MODULE_7__["Message"](request); + this.delegate.onMessage(message); + } + else { + request.accept(); + } + } + /** + * Handle in dialog NOTIFY request. + * @internal + */ + onNotifyRequest(request) { + this.logger.log("Session.onNotifyRequest"); + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { + this.logger.error(`NOTIFY received while in state ${this.state}, dropping request`); + return; + } + // If this a NOTIFY associated with the progress of a REFER, + // look to delegate handling to the associated callback. + if (this.onNotify) { + const notification = new _notification__WEBPACK_IMPORTED_MODULE_8__["Notification"](request); + this.onNotify(notification); + return; + } + // Otherwise accept the NOTIFY. + if (this.delegate && this.delegate.onNotify) { + const notification = new _notification__WEBPACK_IMPORTED_MODULE_8__["Notification"](request); + this.delegate.onNotify(notification); + } + else { + request.accept(); + } + } + /** + * Handle in dialog PRACK request. + * @internal + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onPrackRequest(request) { + this.logger.log("Session.onPrackRequest"); + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["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 + */ + onReferRequest(request) { + this.logger.log("Session.onReferRequest"); + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { + this.logger.error(`REFER received while in state ${this.state}, dropping request`); + return; + } + // 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 + if (!request.message.hasHeader("refer-to")) { + this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting."); + request.reject(); + return; + } + const referral = new _referral__WEBPACK_IMPORTED_MODULE_9__["Referral"](request, this); + if (this.delegate && this.delegate.onRefer) { + this.delegate.onRefer(referral); + } + else { + this.logger.log("No delegate available to handle REFER, automatically accepting and following."); + referral + .accept() + .then(() => referral.makeInviter(this._referralInviterOptions).invite()) + .catch((error) => { + // FIXME: logging and eating error... + this.logger.error(error.message); + }); + } + } + /** + * 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 + */ + generateResponseOfferAnswer(request, options) { + if (this.dialog) { + return this.generateResponseOfferAnswerInDialog(options); + } + const body = Object(_core__WEBPACK_IMPORTED_MODULE_0__["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 + */ + generateResponseOfferAnswerInDialog(options) { + if (!this.dialog) { + throw new Error("Dialog undefined."); + } + switch (this.dialog.signalingState) { + case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Initial: + return this.getOffer(options); + case _core__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { + return Promise.resolve(undefined); + } + // In dialog INVITE without offer, get an offer for the response. + return this.getOffer(options); + case _core__WEBPACK_IMPORTED_MODULE_0__["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 + */ + getOffer(options) { + const sdh = this.setupSessionDescriptionHandler(); + const sdhOptions = options.sessionDescriptionHandlerOptions; + const sdhModifiers = options.sessionDescriptionHandlerModifiers; + // This is intentionally written very defensively. Don't trust SDH to behave. + try { + return sdh + .getDescription(sdhOptions, sdhModifiers) + .then((bodyAndContentType) => Object(_core__WEBPACK_IMPORTED_MODULE_0__["fromBodyLegacy"])(bodyAndContentType)) + .catch((error) => { + // don't trust SDH to reject with Error + this.logger.error("Session.getOffer: SDH getDescription rejected..."); + const e = error instanceof Error ? error : new Error("Session.getOffer unknown error."); + this.logger.error(e.message); + throw e; + }); + } + catch (error) { + // don't trust SDH to throw an Error + this.logger.error("Session.getOffer: SDH getDescription threw..."); + const e = error instanceof Error ? error : new Error(error); + this.logger.error(e.message); + return Promise.reject(e); + } + } + /** + * Rollback local/remote offer. + * @internal + */ + rollbackOffer() { + const sdh = this.setupSessionDescriptionHandler(); + if (sdh.rollbackDescription === undefined) { + return Promise.resolve(); + } + // This is intentionally written very defensively. Don't trust SDH to behave. + try { + return sdh.rollbackDescription().catch((error) => { + // don't trust SDH to reject with Error + this.logger.error("Session.rollbackOffer: SDH rollbackDescription rejected..."); + const e = error instanceof Error ? error : new Error("Session.rollbackOffer unknown error."); + this.logger.error(e.message); + throw e; + }); + } + catch (error) { + // don't trust SDH to throw an Error + this.logger.error("Session.rollbackOffer: SDH rollbackDescription threw..."); + const e = error instanceof Error ? error : new Error(error); + this.logger.error(e.message); + return Promise.reject(e); + } + } + /** + * Set remote answer. + * @internal + */ + setAnswer(answer, options) { + const sdh = this.setupSessionDescriptionHandler(); + const sdhOptions = options.sessionDescriptionHandlerOptions; + const sdhModifiers = options.sessionDescriptionHandlerModifiers; + // This is intentionally written very defensively. Don't trust SDH to behave. + try { + if (!sdh.hasDescription(answer.contentType)) { + return Promise.reject(new _exceptions__WEBPACK_IMPORTED_MODULE_5__["ContentTypeUnsupportedError"]()); + } + } + catch (error) { + this.logger.error("Session.setAnswer: SDH hasDescription threw..."); + const e = error instanceof Error ? error : new Error(error); + this.logger.error(e.message); + return Promise.reject(e); + } + try { + return sdh.setDescription(answer.content, sdhOptions, sdhModifiers).catch((error) => { + // don't trust SDH to reject with Error + this.logger.error("Session.setAnswer: SDH setDescription rejected..."); + const e = error instanceof Error ? error : new Error("Session.setAnswer unknown error."); + this.logger.error(e.message); + throw e; + }); + } + catch (error) { + // don't trust SDH to throw an Error + this.logger.error("Session.setAnswer: SDH setDescription threw..."); + const e = error instanceof Error ? error : new Error(error); + this.logger.error(e.message); + return Promise.reject(e); + } + } + /** + * Set remote offer and get local answer. + * @internal + */ + setOfferAndGetAnswer(offer, options) { + const sdh = this.setupSessionDescriptionHandler(); + const sdhOptions = options.sessionDescriptionHandlerOptions; + const sdhModifiers = options.sessionDescriptionHandlerModifiers; + // This is intentionally written very defensively. Don't trust SDH to behave. + try { + if (!sdh.hasDescription(offer.contentType)) { + return Promise.reject(new _exceptions__WEBPACK_IMPORTED_MODULE_5__["ContentTypeUnsupportedError"]()); + } + } + catch (error) { + this.logger.error("Session.setOfferAndGetAnswer: SDH hasDescription threw..."); + const e = error instanceof Error ? error : new Error(error); + this.logger.error(e.message); + return Promise.reject(e); + } + try { + return sdh + .setDescription(offer.content, sdhOptions, sdhModifiers) + .then(() => sdh.getDescription(sdhOptions, sdhModifiers)) + .then((bodyAndContentType) => Object(_core__WEBPACK_IMPORTED_MODULE_0__["fromBodyLegacy"])(bodyAndContentType)) + .catch((error) => { + // don't trust SDH to reject with Error + this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription rejected..."); + const e = error instanceof Error ? error : new Error("Session.setOfferAndGetAnswer unknown error."); + this.logger.error(e.message); + throw e; + }); + } + catch (error) { + // don't trust SDH to throw an Error + this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription threw..."); + const e = error instanceof Error ? error : new Error(error); + this.logger.error(e.message); + return Promise.reject(e); + } + } + /** + * SDH for confirmed dialog. + * @internal + */ + setSessionDescriptionHandler(sdh) { + if (this._sessionDescriptionHandler) { + throw new Error("Session description handler defined."); + } + this._sessionDescriptionHandler = sdh; + } + /** + * SDH for confirmed dialog. + * @internal + */ + setupSessionDescriptionHandler() { + var _a; + if (this._sessionDescriptionHandler) { + return this._sessionDescriptionHandler; + } + this._sessionDescriptionHandler = this.sessionDescriptionHandlerFactory(this, this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions); + if ((_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onSessionDescriptionHandler) { + this.delegate.onSessionDescriptionHandler(this._sessionDescriptionHandler, false); + } + return this._sessionDescriptionHandler; + } + /** + * Transition session state. + * @internal + */ + stateTransition(newState) { + const invalidTransition = () => { + throw new Error(`Invalid state transition from ${this._state} to ${newState}`); + }; + // Validate transition + switch (this._state) { + case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Initial: + if (newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Establishing && + newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established && + newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminating && + newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated) { + invalidTransition(); + } + break; + case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Establishing: + if (newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established && + newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminating && + newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated) { + invalidTransition(); + } + break; + case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established: + if (newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminating && newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated) { + invalidTransition(); + } + break; + case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminating: + if (newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated) { + invalidTransition(); + } + break; + case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated: + invalidTransition(); + break; + default: + throw new Error("Unrecognized state."); + } + // Transition + this._state = newState; + this.logger.log(`Session ${this.id} transitioned to state ${this._state}`); + this._stateEventEmitter.emit(this._state); + // Dispose + if (newState === _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated) { + this.dispose(); + } + } + copyRequestOptions(requestOptions = {}) { + const extraHeaders = requestOptions.extraHeaders ? requestOptions.extraHeaders.slice() : undefined; + const body = requestOptions.body + ? { + contentDisposition: requestOptions.body.contentDisposition || "render", + contentType: requestOptions.body.contentType || "text/plain", + content: requestOptions.body.content || "" + } + : undefined; + return { + extraHeaders, + body + }; + } + getReasonHeaderValue(code, reason) { + const cause = code; + let text = Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["getReasonPhrase"])(code); + if (!text && reason) { + text = reason; + } + return "SIP;cause=" + cause + ';text="' + text + '"'; + } + referExtraHeaders(referTo) { + const extraHeaders = []; + extraHeaders.push("Referred-By: <" + this.userAgent.configuration.uri + ">"); + extraHeaders.push("Contact: " + this._contact); + extraHeaders.push("Allow: " + ["ACK", "CANCEL", "INVITE", "MESSAGE", "BYE", "OPTIONS", "INFO", "NOTIFY", "REFER"].toString()); + extraHeaders.push("Refer-To: " + referTo); + return extraHeaders; + } + referToString(target) { + let referTo; + if (target instanceof _core__WEBPACK_IMPORTED_MODULE_0__["URI"]) { + // REFER without Replaces (Blind Transfer) + referTo = target.toString(); + } + else { + // REFER with Replaces (Attended Transfer) + if (!target.dialog) { + throw new Error("Dialog undefined."); + } + const displayName = target.remoteIdentity.friendlyName; + const remoteTarget = target.dialog.remoteTarget.toString(); + const callId = target.dialog.callId; + const remoteTag = target.dialog.remoteTag; + const localTag = target.dialog.localTag; + const replaces = encodeURIComponent(`${callId};to-tag=${remoteTag};from-tag=${localTag}`); + referTo = `"${displayName}" <${remoteTarget}?Replaces=${replaces}>`; + } + return referTo; + } +} + + +/***/ }), +/* 115 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Message", function() { return Message; }); +/** + * A received message (incoming MESSAGE). + * @public + */ +class Message { + /** @internal */ + constructor(incomingMessageRequest) { + this.incomingMessageRequest = incomingMessageRequest; + } + /** Incoming MESSAGE request message. */ + get request() { + return this.incomingMessageRequest.message; + } + /** Accept the request. */ + accept(options) { + this.incomingMessageRequest.accept(options); + return Promise.resolve(); + } + /** Reject the request. */ + reject(options) { + this.incomingMessageRequest.reject(options); + return Promise.resolve(); + } +} + + +/***/ }), +/* 116 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Notification", function() { return Notification; }); +/** + * A notification of an event (incoming NOTIFY). + * @public + */ +class Notification { + /** @internal */ + constructor(incomingNotifyRequest) { + this.incomingNotifyRequest = incomingNotifyRequest; + } + /** Incoming NOTIFY request message. */ + get request() { + return this.incomingNotifyRequest.message; + } + /** Accept the request. */ + accept(options) { + this.incomingNotifyRequest.accept(options); + return Promise.resolve(); + } + /** Reject the request. */ + reject(options) { + this.incomingNotifyRequest.reject(options); + return Promise.resolve(); + } +} + + +/***/ }), +/* 117 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Referral", function() { return Referral; }); +/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); + +/** + * A request to establish a {@link Session} elsewhere (incoming REFER). + * @public + */ +class Referral { + /** @internal */ + constructor(incomingReferRequest, session) { + this.incomingReferRequest = incomingReferRequest; + this.session = session; + } + get referTo() { + const referTo = this.incomingReferRequest.message.parseHeader("refer-to"); + if (!(referTo instanceof _core__WEBPACK_IMPORTED_MODULE_0__["NameAddrHeader"])) { + throw new Error("Failed to parse Refer-To header."); + } + return referTo; + } + get referredBy() { + return this.incomingReferRequest.message.getHeader("referred-by"); + } + get replaces() { + return this.referTo.uri.getHeader("replaces"); + } + /** Incoming REFER request message. */ + get request() { + return this.incomingReferRequest.message; + } + /** Accept the request. */ + accept(options = { statusCode: 202 }) { + this.incomingReferRequest.accept(options); + return Promise.resolve(); + } + /** Reject the request. */ + reject(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. + */ + makeInviter(options) { + if (this.inviter) { + return this.inviter; + } + const targetURI = this.referTo.uri.clone(); + targetURI.clearHeaders(); + options = options || {}; + const extraHeaders = (options.extraHeaders || []).slice(); + const replaces = this.replaces; + if (replaces) { + // decodeURIComponent is a holdover from 2c086eb4. Not sure that it is actually necessary + extraHeaders.push("Replaces: " + decodeURIComponent(replaces)); + } + const 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; + } +} + + +/***/ }), +/* 118 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SessionState", function() { return SessionState; }); +/** + * {@link Session} state. + * + * @remarks + * The {@link Session} behaves in a deterministic manner according to the following + * Finite State Machine (FSM). + * ```txt + * ___________________________________________________________ + * | ____________________________________________ | + * | | ____________________________ | | + * Session | | | v v v + * Constructed -> Initial -> Establishing -> Established -> Terminating -> Terminated + * | |___________________________^ ^ + * |_______________________________________________| + * ``` + * @public + */ +var SessionState; +(function (SessionState) { + /** + * If `Inviter`, INVITE not sent yet. + * If `Invitation`, received INVITE (but no final response sent yet). + */ + SessionState["Initial"] = "Initial"; + /** + * If `Inviter`, sent INVITE and waiting for a final response. + * If `Invitation`, received INVITE and attempting to send 200 final response (but has not sent it yet). + */ + SessionState["Establishing"] = "Establishing"; + /** + * If `Inviter`, sent INVITE and received 200 final response and sent ACK. + * If `Invitation`, received INVITE and sent 200 final response. + */ + SessionState["Established"] = "Established"; + /** + * If `Inviter`, sent INVITE, sent CANCEL and now waiting for 487 final response to ACK (or 200 to ACK & BYE). + * If `Invitation`, received INVITE, sent 200 final response and now waiting on ACK and upon receipt will attempt BYE + * (as the protocol specification requires, before sending a BYE we must receive the ACK - so we are waiting). + */ + SessionState["Terminating"] = "Terminating"; + /** + * If `Inviter`, sent INVITE and received non-200 final response (or sent/received BYE after receiving 200). + * If `Invitation`, received INVITE and sent non-200 final response (or sent/received BYE after sending 200). + */ + SessionState["Terminated"] = "Terminated"; +})(SessionState || (SessionState = {})); + + +/***/ }), +/* 119 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SIPExtension", function() { return SIPExtension; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UserAgentRegisteredOptionTags", function() { return UserAgentRegisteredOptionTags; }); +/** + * SIP extension support level. + * @public + */ +var SIPExtension; +(function (SIPExtension) { + SIPExtension["Required"] = "Required"; + SIPExtension["Supported"] = "Supported"; + SIPExtension["Unsupported"] = "Unsupported"; +})(SIPExtension || (SIPExtension = {})); +/** + * SIP Option Tags + * @remarks + * http://www.iana.org/assignments/sip-parameters/sip-parameters.xhtml#sip-parameters-4 + * @public + */ +const 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 +}; + + +/***/ }), +/* 120 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 121 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 122 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 123 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Inviter", function() { return Inviter; }); +/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); +/* harmony import */ var _core_messages_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(32); +/* harmony import */ var _session__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(114); +/* harmony import */ var _session_state__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(118); +/* harmony import */ var _user_agent_options__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(119); + + + + + +/** + * An inviter offers to establish a {@link Session} (outgoing INVITE). + * @public + */ +class Inviter extends _session__WEBPACK_IMPORTED_MODULE_2__["Session"] { + /** + * 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, targetURI, options = {}) { + super(userAgent, options); + /** True if dispose() has been called. */ + this.disposed = false; + /** True if early media use is enabled. */ + this.earlyMedia = false; + /** The early media session description handlers. */ + this.earlyMediaSessionDescriptionHandlers = new Map(); + /** True if cancel() was called. */ + this.isCanceled = false; + /** True if initial INVITE without SDP. */ + this.inviteWithoutSdp = false; + this.logger = userAgent.getLogger("sip.Inviter"); + // Early media + this.earlyMedia = options.earlyMedia !== undefined ? options.earlyMedia : this.earlyMedia; + // From tag + this.fromTag = Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["newTag"])(); + // Invite without SDP + this.inviteWithoutSdp = options.inviteWithoutSdp !== undefined ? options.inviteWithoutSdp : this.inviteWithoutSdp; + // Inviter options (could do better copying these options) + const inviterOptions = Object.assign({}, options); + inviterOptions.params = Object.assign({}, options.params); + // Anonymous call + const anonymous = options.anonymous || false; + // Contact + const contact = userAgent.contact.toString({ + anonymous, + // Do not add ;ob in initial forming dialog requests if the + // registration over the current connection got a GRUU URI. + outbound: anonymous ? !userAgent.contact.tempGruu : !userAgent.contact.pubGruu + }); + // FIXME: TODO: We should not be parsing URIs here as if it fails we have to throw an exception + // which is not something we want our constructor to do. URIs should be passed in as params. + // URIs + if (anonymous && userAgent.configuration.uri) { + inviterOptions.params.fromDisplayName = "Anonymous"; + inviterOptions.params.fromUri = "sip:anonymous@anonymous.invalid"; + } + let fromURI = userAgent.userAgentCore.configuration.aor; + if (inviterOptions.params.fromUri) { + fromURI = + typeof inviterOptions.params.fromUri === "string" + ? _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].URIParse(inviterOptions.params.fromUri) + : inviterOptions.params.fromUri; + } + if (!fromURI) { + throw new TypeError("Invalid from URI: " + inviterOptions.params.fromUri); + } + let toURI = targetURI; + if (inviterOptions.params.toUri) { + toURI = + typeof inviterOptions.params.toUri === "string" + ? _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].URIParse(inviterOptions.params.toUri) + : inviterOptions.params.toUri; + } + if (!toURI) { + throw new TypeError("Invalid to URI: " + inviterOptions.params.toUri); + } + // Params + const messageOptions = Object.assign({}, inviterOptions.params); + messageOptions.fromTag = this.fromTag; + // Extra headers + const extraHeaders = (inviterOptions.extraHeaders || []).slice(); + if (anonymous && userAgent.configuration.uri) { + extraHeaders.push("P-Preferred-Identity: " + userAgent.configuration.uri.toString()); + extraHeaders.push("Privacy: id"); + } + extraHeaders.push("Contact: " + contact); + extraHeaders.push("Allow: " + ["ACK", "CANCEL", "INVITE", "MESSAGE", "BYE", "OPTIONS", "INFO", "NOTIFY", "REFER"].toString()); + if (userAgent.configuration.sipExtension100rel === _user_agent_options__WEBPACK_IMPORTED_MODULE_4__["SIPExtension"].Required) { + extraHeaders.push("Require: 100rel"); + } + if (userAgent.configuration.sipExtensionReplaces === _user_agent_options__WEBPACK_IMPORTED_MODULE_4__["SIPExtension"].Required) { + extraHeaders.push("Require: replaces"); + } + inviterOptions.extraHeaders = extraHeaders; + // Body + const body = undefined; + // Make initial outgoing request message + this.outgoingRequestMessage = userAgent.userAgentCore.makeOutgoingRequestMessage(_core__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE, targetURI, fromURI, toURI, messageOptions, extraHeaders, body); + // Session parent properties + this._contact = contact; + this._referralInviterOptions = inviterOptions; + this._renderbody = options.renderbody; + this._rendertype = options.rendertype; + // Modifiers and options for initial INVITE transaction + if (options.sessionDescriptionHandlerModifiers) { + this.sessionDescriptionHandlerModifiers = options.sessionDescriptionHandlerModifiers; + } + if (options.sessionDescriptionHandlerOptions) { + this.sessionDescriptionHandlerOptions = options.sessionDescriptionHandlerOptions; + } + // Modifiers and options for re-INVITE transactions + if (options.sessionDescriptionHandlerModifiersReInvite) { + this.sessionDescriptionHandlerModifiersReInvite = options.sessionDescriptionHandlerModifiersReInvite; + } + if (options.sessionDescriptionHandlerOptionsReInvite) { + this.sessionDescriptionHandlerOptionsReInvite = options.sessionDescriptionHandlerOptionsReInvite; + } + // Identifier + this._id = this.outgoingRequestMessage.callId + this.fromTag; + // Add to the user agent's session collection. + this.userAgent._sessions[this._id] = this; + } + /** + * Destructor. + */ + dispose() { + // Only run through this once. It can and does get called multiple times + // depending on the what the sessions state is when first called. + // For example, if called when "establishing" it will be called again + // at least once when the session transitions to "terminated". + // Regardless, running through this more than once is pointless. + if (this.disposed) { + return Promise.resolve(); + } + this.disposed = true; + // Dispose of early dialog media + this.disposeEarlyMedia(); + // If the final response for the initial INVITE not yet been received, cancel it + switch (this.state) { + case _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Initial: + return this.cancel().then(() => super.dispose()); + case _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Establishing: + return this.cancel().then(() => super.dispose()); + case _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Established: + return super.dispose(); + case _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminating: + return super.dispose(); + case _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated: + return super.dispose(); + default: + throw new Error("Unknown state."); + } + } + /** + * Initial outgoing INVITE request message body. + */ + get body() { + return this.outgoingRequestMessage.body; + } + /** + * The identity of the local user. + */ + get localIdentity() { + return this.outgoingRequestMessage.from; + } + /** + * The identity of the remote user. + */ + get remoteIdentity() { + return this.outgoingRequestMessage.to; + } + /** + * Initial outgoing INVITE request message. + */ + get request() { + return this.outgoingRequestMessage; + } + /** + * Cancels the INVITE request. + * + * @remarks + * Sends a CANCEL request. + * Resolves once the response sent, otherwise rejects. + * + * After sending a CANCEL request the expectation is that a 487 final response + * will be received for the INVITE. However a 200 final response to the INVITE + * may nonetheless arrive (it's a race between the CANCEL reaching the UAS before + * the UAS sends a 200) in which case an ACK & BYE will be sent. The net effect + * is that this method will terminate the session regardless of the race. + * @param options - Options bucket. + */ + cancel(options = {}) { + this.logger.log("Inviter.cancel"); + // validate state + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Initial && this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Establishing) { + const error = new Error(`Invalid session state ${this.state}`); + this.logger.error(error.message); + return Promise.reject(error); + } + // flag canceled + this.isCanceled = true; + // transition state + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminating); + // helper function + function getCancelReason(code, reason) { + if ((code && code < 200) || code > 699) { + throw new TypeError("Invalid statusCode: " + code); + } + else if (code) { + const cause = code; + const text = Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["getReasonPhrase"])(code) || reason; + return "SIP;cause=" + cause + ';text="' + text + '"'; + } + } + if (this.outgoingInviteRequest) { + // the CANCEL may not be respected by peer(s), so don't transition to terminated + let cancelReason; + if (options.statusCode && options.reasonPhrase) { + cancelReason = getCancelReason(options.statusCode, options.reasonPhrase); + } + this.outgoingInviteRequest.cancel(cancelReason, options); + } + else { + this.logger.warn("Canceled session before INVITE was sent"); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["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 behavior 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 behavior of the SIP + * servers being utilized is configured to disallow forking. + */ + invite(options = {}) { + this.logger.log("Inviter.invite"); + // validate state + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Initial) { + // re-invite + return super.invite(options); + } + // Modifiers and options for initial INVITE transaction + if (options.sessionDescriptionHandlerModifiers) { + this.sessionDescriptionHandlerModifiers = options.sessionDescriptionHandlerModifiers; + } + if (options.sessionDescriptionHandlerOptions) { + this.sessionDescriptionHandlerOptions = options.sessionDescriptionHandlerOptions; + } + // just send an INVITE with no sdp... + if (options.withoutSdp || this.inviteWithoutSdp) { + if (this._renderbody && this._rendertype) { + this.outgoingRequestMessage.body = { contentType: this._rendertype, body: this._renderbody }; + } + // transition state + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Establishing); + return Promise.resolve(this.sendInvite(options)); + } + // get an offer and send it in an INVITE + const offerOptions = { + sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers, + sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions + }; + return this.getOffer(offerOptions) + .then((body) => { + this.outgoingRequestMessage.body = { body: body.content, contentType: body.contentType }; + // transition state + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Establishing); + return this.sendInvite(options); + }) + .catch((error) => { + this.logger.log(error.message); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); + 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 + */ + sendInvite(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 + // 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 environments 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.outgoingRequestMessage, { + onAccept: (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__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); + return; + } + this.notifyReferer(inviteResponse); + this.onAccept(inviteResponse) + .then(() => { + this.disposeEarlyMedia(); + }) + .catch(() => { + this.disposeEarlyMedia(); + }) + .then(() => { + if (options.requestDelegate && options.requestDelegate.onAccept) { + options.requestDelegate.onAccept(inviteResponse); + } + }); + }, + onProgress: (inviteResponse) => { + // If the user requested cancellation, ignore response. + if (this.isCanceled) { + return; + } + this.notifyReferer(inviteResponse); + this.onProgress(inviteResponse) + .catch(() => { + this.disposeEarlyMedia(); + }) + .then(() => { + if (options.requestDelegate && options.requestDelegate.onProgress) { + options.requestDelegate.onProgress(inviteResponse); + } + }); + }, + onRedirect: (inviteResponse) => { + this.notifyReferer(inviteResponse); + this.onRedirect(inviteResponse); + if (options.requestDelegate && options.requestDelegate.onRedirect) { + options.requestDelegate.onRedirect(inviteResponse); + } + }, + onReject: (inviteResponse) => { + this.notifyReferer(inviteResponse); + this.onReject(inviteResponse); + if (options.requestDelegate && options.requestDelegate.onReject) { + options.requestDelegate.onReject(inviteResponse); + } + }, + onTrying: (inviteResponse) => { + this.notifyReferer(inviteResponse); + this.onTrying(inviteResponse); + if (options.requestDelegate && options.requestDelegate.onTrying) { + options.requestDelegate.onTrying(inviteResponse); + } + } + }); + return this.outgoingInviteRequest; + } + disposeEarlyMedia() { + this.earlyMediaSessionDescriptionHandlers.forEach((sessionDescriptionHandler) => { + sessionDescriptionHandler.close(); + }); + this.earlyMediaSessionDescriptionHandlers.clear(); + } + notifyReferer(response) { + if (!this._referred) { + return; + } + if (!(this._referred instanceof _session__WEBPACK_IMPORTED_MODULE_2__["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."); + } + const statusCode = response.message.statusCode; + const reasonPhrase = response.message.reasonPhrase; + const body = `SIP/2.0 ${statusCode} ${reasonPhrase}`.trim(); + const 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: () => { + this._referred = undefined; + } + }; + } + /** + * Handle final response to initial INVITE. + * @param inviteResponse - 2xx response. + */ + onAccept(inviteResponse) { + this.logger.log("Inviter.onAccept"); + // validate state + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Establishing) { + this.logger.error(`Accept received while in state ${this.state}, dropping response`); + return Promise.reject(new Error(`Invalid session state ${this.state}`)); + } + const response = inviteResponse.message; + const session = inviteResponse.session; + // Ported behavior. + if (response.hasHeader("P-Asserted-Identity")) { + this._assertedIdentity = _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].nameAddrHeaderParse(response.getHeader("P-Asserted-Identity")); + } + // We have a confirmed dialog. + session.delegate = { + onAck: (ackRequest) => this.onAckRequest(ackRequest), + onBye: (byeRequest) => this.onByeRequest(byeRequest), + onInfo: (infoRequest) => this.onInfoRequest(infoRequest), + onInvite: (inviteRequest) => this.onInviteRequest(inviteRequest), + onMessage: (messageRequest) => this.onMessageRequest(messageRequest), + onNotify: (notifyRequest) => this.onNotifyRequest(notifyRequest), + onPrack: (prackRequest) => this.onPrackRequest(prackRequest), + onRefer: (referRequest) => this.onReferRequest(referRequest) + }; + this._dialog = session; + switch (session.signalingState) { + case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Initial: + // INVITE without offer, so MUST have offer at this point, so invalid state. + this.logger.error("Received 2xx response to INVITE without a session description"); + this.ackAndBye(inviteResponse, 400, "Missing session description"); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); + return Promise.reject(new Error("Bad Media Description")); + case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].HaveLocalOffer: + // INVITE with offer, so MUST have answer at this point, so invalid state. + this.logger.error("Received 2xx response to INVITE without a session description"); + this.ackAndBye(inviteResponse, 400, "Missing session description"); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); + return Promise.reject(new Error("Bad Media Description")); + case _core__WEBPACK_IMPORTED_MODULE_0__["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}.`); + } + const options = { + sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers, + sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions + }; + return this.setOfferAndGetAnswer(this._dialog.offer, options) + .then((body) => { + inviteResponse.ack({ body }); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Established); + }) + .catch((error) => { + this.ackAndBye(inviteResponse, 488, "Invalid session description"); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); + throw error; + }); + } + case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Stable: { + // If INVITE without offer and we have already completed the initial exchange. + if (this.earlyMediaSessionDescriptionHandlers.size > 0) { + const sdh = this.earlyMediaSessionDescriptionHandlers.get(session.id); + if (!sdh) { + throw new Error("Session description handler undefined."); + } + this.setSessionDescriptionHandler(sdh); + this.earlyMediaSessionDescriptionHandlers.delete(session.id); + inviteResponse.ack(); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["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) { + const 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 behavior 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); + } + const 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.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); + return Promise.reject(error); + } + // Otherwise we are good to go. + inviteResponse.ack(); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Established); + return Promise.resolve(); + } + // If INVITE with offer and we have been waiting till now to apply the answer. + const answer = session.answer; + if (!answer) { + throw new Error("Answer is undefined."); + } + const options = { + sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers, + sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions + }; + return this.setAnswer(answer, options) + .then(() => { + // This session has completed an initial offer/answer exchange... + let ackOptions; + if (this._renderbody && this._rendertype) { + ackOptions = { + body: { contentDisposition: "render", contentType: this._rendertype, content: this._renderbody } + }; + } + inviteResponse.ack(ackOptions); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Established); + }) + .catch((error) => { + this.logger.error(error.message); + this.ackAndBye(inviteResponse, 488, "Not Acceptable Here"); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); + throw error; + }); + } + case _core__WEBPACK_IMPORTED_MODULE_0__["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. + */ + onProgress(inviteResponse) { + var _a; + this.logger.log("Inviter.onProgress"); + // validate state + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["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."); + } + const response = inviteResponse.message; + const session = inviteResponse.session; + // Ported - Set assertedIdentity. + if (response.hasHeader("P-Asserted-Identity")) { + this._assertedIdentity = _core__WEBPACK_IMPORTED_MODULE_0__["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 + const requireHeader = response.getHeader("require"); + const rseqHeader = response.getHeader("rseq"); + const rseq = requireHeader && requireHeader.includes("100rel") && rseqHeader ? Number(rseqHeader) : undefined; + const responseReliable = !!rseq; + const extraHeaders = []; + if (responseReliable) { + extraHeaders.push("RAck: " + response.getHeader("rseq") + " " + response.getHeader("cseq")); + } + switch (session.signalingState) { + case _core__WEBPACK_IMPORTED_MODULE_0__["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 }); + } + return Promise.resolve(); + case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].HaveLocalOffer: + // INVITE with offer and session only has that initial local offer. + if (responseReliable) { + inviteResponse.prack({ extraHeaders }); + } + return Promise.resolve(); + case _core__WEBPACK_IMPORTED_MODULE_0__["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 + const sdh = this.sessionDescriptionHandlerFactory(this, this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions || {}); + if ((_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onSessionDescriptionHandler) { + this.delegate.onSessionDescriptionHandler(sdh, true); + } + this.earlyMediaSessionDescriptionHandlers.set(session.id, sdh); + return sdh + .setDescription(response.body, this.sessionDescriptionHandlerOptions, this.sessionDescriptionHandlerModifiers) + .then(() => sdh.getDescription(this.sessionDescriptionHandlerOptions, this.sessionDescriptionHandlerModifiers)) + .then((description) => { + const body = { + contentDisposition: "session", + contentType: description.contentType, + content: description.body + }; + inviteResponse.prack({ extraHeaders, body }); + }) + .catch((error) => { + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); + throw error; + }); + } + case _core__WEBPACK_IMPORTED_MODULE_0__["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 }); + } + if (this.earlyMedia && !this.earlyMediaDialog) { + this.earlyMediaDialog = session; + const answer = session.answer; + if (!answer) { + throw new Error("Answer is undefined."); + } + const options = { + sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers, + sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions + }; + return this.setAnswer(answer, options).catch((error) => { + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); + throw error; + }); + } + return Promise.resolve(); + case _core__WEBPACK_IMPORTED_MODULE_0__["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. + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onRedirect(inviteResponse) { + this.logger.log("Inviter.onRedirect"); + // validate state + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Establishing && this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminating) { + this.logger.error(`Redirect received while in state ${this.state}, dropping response`); + return; + } + // transition state + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); + } + /** + * Handle final response to initial INVITE. + * @param inviteResponse - 4xx, 5xx, or 6xx response. + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onReject(inviteResponse) { + this.logger.log("Inviter.onReject"); + // validate state + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Establishing && this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminating) { + this.logger.error(`Reject received while in state ${this.state}, dropping response`); + return; + } + // transition state + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); + } + /** + * Handle final response to initial INVITE. + * @param inviteResponse - 100 response. + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onTrying(inviteResponse) { + this.logger.log("Inviter.onTrying"); + // validate state + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Establishing) { + this.logger.error(`Trying received while in state ${this.state}, dropping response`); + return; + } + } +} + + +/***/ }), +/* 124 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 125 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 126 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Messager", function() { return Messager; }); +/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); + +/** + * A messager sends a {@link Message} (outgoing MESSAGE). + * @public + */ +class Messager { + /** + * 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, targetURI, content, contentType = "text/plain", options = {}) { + // Logger + this.logger = userAgent.getLogger("sip.Messager"); + // Default options params + options.params = options.params || {}; + // URIs + let fromURI = userAgent.userAgentCore.configuration.aor; + if (options.params.fromUri) { + fromURI = + typeof options.params.fromUri === "string" ? _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].URIParse(options.params.fromUri) : options.params.fromUri; + } + if (!fromURI) { + throw new TypeError("Invalid from URI: " + options.params.fromUri); + } + let toURI = targetURI; + if (options.params.toUri) { + toURI = typeof options.params.toUri === "string" ? _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].URIParse(options.params.toUri) : options.params.toUri; + } + if (!toURI) { + throw new TypeError("Invalid to URI: " + options.params.toUri); + } + // Message params + const params = options.params ? Object.assign({}, options.params) : {}; + // Extra headers + const extraHeaders = (options.extraHeaders || []).slice(); + // Body + const contentDisposition = "render"; + const body = { + contentDisposition, + contentType, + content + }; + // Build the request + this.request = userAgent.userAgentCore.makeOutgoingRequestMessage(_core__WEBPACK_IMPORTED_MODULE_0__["C"].MESSAGE, targetURI, fromURI, toURI, params, extraHeaders, body); + // User agent + this.userAgent = userAgent; + } + /** + * Send the message. + */ + message(options = {}) { + this.userAgent.userAgentCore.request(this.request, options.requestDelegate); + return Promise.resolve(); + } +} + + +/***/ }), +/* 127 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 128 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 129 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PublisherState", function() { return PublisherState; }); +/** + * {@link Publisher} state. + * @remarks + * The {@link Publisher} behaves in a deterministic manner according to the following + * Finite State Machine (FSM). + * ```txt + * __________________________________________ + * | __________________________ | + * Publisher | | v v + * Constructed -> Initial -> Published -> Unpublished -> Terminated + * | ^____________| ^ + * |______________________________| + * ``` + * @public + */ +var PublisherState; +(function (PublisherState) { + PublisherState["Initial"] = "Initial"; + PublisherState["Published"] = "Published"; + PublisherState["Unpublished"] = "Unpublished"; + PublisherState["Terminated"] = "Terminated"; +})(PublisherState || (PublisherState = {})); + + +/***/ }), +/* 130 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 131 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Publisher", function() { return Publisher; }); +/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); +/* harmony import */ var _emitter__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(108); +/* harmony import */ var _publisher_state__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(129); + + + +/** + * A publisher publishes a publication (outgoing PUBLISH). + * @public + */ +class Publisher { + /** + * 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, targetURI, eventType, options = {}) { + this.disposed = false; + /** The publication state. */ + this._state = _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Initial; + // state emitter + this._stateEventEmitter = new _emitter__WEBPACK_IMPORTED_MODULE_1__["EmitterImpl"](); + this.userAgent = userAgent; + 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 = options.expires; + this.logger = userAgent.getLogger("sip.Publisher"); + const params = options.params || {}; + const fromURI = params.fromUri ? params.fromUri : userAgent.userAgentCore.configuration.aor; + const toURI = params.toUri ? params.toUri : targetURI; + let body; + if (options.body && options.contentType) { + const contentDisposition = "render"; + const contentType = options.contentType; + const content = options.body; + body = { + contentDisposition, + contentType, + content + }; + } + const extraHeaders = (options.extraHeaders || []).slice(); + // Build the request + this.request = userAgent.userAgentCore.makeOutgoingRequestMessage(_core__WEBPACK_IMPORTED_MODULE_0__["C"].PUBLISH, targetURI, fromURI, toURI, params, extraHeaders, body); + // Identifier + this.id = this.target.toString() + ":" + this.event; + // Add to the user agent's publisher collection. + this.userAgent._publishers[this.id] = this; + } + /** + * Destructor. + */ + dispose() { + if (this.disposed) { + return Promise.resolve(); + } + this.disposed = true; + this.logger.log(`Publisher ${this.id} in state ${this.state} is being disposed`); + // Remove from the user agent's publisher collection + delete this.userAgent._publishers[this.id]; + // Send unpublish, if requested + if (this.options.unpublishOnClose && this.state === _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Published) { + return this.unpublish(); + } + if (this.publishRefreshTimer) { + clearTimeout(this.publishRefreshTimer); + this.publishRefreshTimer = undefined; + } + this.pubRequestBody = undefined; + this.pubRequestExpires = 0; + this.pubRequestEtag = undefined; + return Promise.resolve(); + } + /** The publication state. */ + get state() { + return this._state; + } + /** Emits when the publisher state changes. */ + get stateChange() { + return this._stateEventEmitter; + } + /** + * Publish. + * @param content - Body to publish + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + publish(content, 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 + if (this.options.expires === undefined) { + throw new Error("Expires undefined."); + } + this.pubRequestExpires = this.options.expires; + this.pubRequestEtag = undefined; + } + this.sendPublishRequest(); + return Promise.resolve(); + } + /** + * Unpublish. + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + unpublish(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(); + } + return Promise.resolve(); + } + /** @internal */ + receiveResponse(response) { + const statusCode = response.statusCode || 0; + switch (true) { + case /^1[0-9]{2}$/.test(statusCode.toString()): + 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")) { + const 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(() => this.refreshRequest(), this.pubRequestExpires * 900); + this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Published); + } + else { + this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Unpublished); + } + 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; + if (this.options.body === undefined) { + throw new Error("Body undefined."); + } + this.publish(this.options.body); + } + else { + this.logger.warn("412 response to PUBLISH, recovery failed"); + this.pubRequestExpires = 0; + this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Unpublished); + this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Terminated); + } + 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")) { + const 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; + if (this.options.body === undefined) { + throw new Error("Body undefined."); + } + this.publish(this.options.body); + } + else { + this.logger.warn("Bad 423 response Min-Expires header received for PUBLISH"); + this.pubRequestExpires = 0; + this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Unpublished); + this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Terminated); + } + } + else { + this.logger.warn("423 response to PUBLISH, recovery failed"); + this.pubRequestExpires = 0; + this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Unpublished); + this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Terminated); + } + break; + default: + this.pubRequestExpires = 0; + this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Unpublished); + this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Terminated); + break; + } + // Do the cleanup + if (this.pubRequestExpires === 0) { + if (this.publishRefreshTimer) { + clearTimeout(this.publishRefreshTimer); + this.publishRefreshTimer = undefined; + } + this.pubRequestBody = undefined; + this.pubRequestEtag = undefined; + } + } + /** @internal */ + send() { + return this.userAgent.userAgentCore.publish(this.request, { + onAccept: (response) => this.receiveResponse(response.message), + onProgress: (response) => this.receiveResponse(response.message), + onRedirect: (response) => this.receiveResponse(response.message), + onReject: (response) => this.receiveResponse(response.message), + onTrying: (response) => this.receiveResponse(response.message) + }); + } + refreshRequest() { + // 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) { + throw new Error("Etag undefined"); + } + if (this.pubRequestExpires === 0) { + throw new Error("Expires zero"); + } + this.sendPublishRequest(); + } + sendPublishRequest() { + const reqOptions = Object.assign({}, this.options); + 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); + } + const ruri = this.target; + const params = this.options.params || {}; + let bodyAndContentType; + if (this.pubRequestBody !== undefined) { + if (this.options.contentType === undefined) { + throw new Error("Content type undefined."); + } + bodyAndContentType = { + body: this.pubRequestBody, + contentType: this.options.contentType + }; + } + let body; + if (bodyAndContentType) { + body = Object(_core__WEBPACK_IMPORTED_MODULE_0__["fromBodyLegacy"])(bodyAndContentType); + } + this.request = this.userAgent.userAgentCore.makeOutgoingRequestMessage(_core__WEBPACK_IMPORTED_MODULE_0__["C"].PUBLISH, ruri, params.fromUri ? params.fromUri : this.userAgent.userAgentCore.configuration.aor, params.toUri ? params.toUri : this.target, params, reqOptions.extraHeaders, body); + return this.send(); + } + /** + * Transition publication state. + */ + stateTransition(newState) { + const invalidTransition = () => { + throw new Error(`Invalid state transition from ${this._state} to ${newState}`); + }; + // Validate transition + switch (this._state) { + case _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Initial: + if (newState !== _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Published && + newState !== _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Unpublished && + newState !== _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Terminated) { + invalidTransition(); + } + break; + case _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Published: + if (newState !== _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Unpublished && newState !== _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Terminated) { + invalidTransition(); + } + break; + case _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Unpublished: + if (newState !== _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Published && newState !== _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Terminated) { + invalidTransition(); + } + break; + case _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Terminated: + invalidTransition(); + break; + default: + throw new Error("Unrecognized state."); + } + // Transition + this._state = newState; + this.logger.log(`Publication transitioned to state ${this._state}`); + this._stateEventEmitter.emit(this._state); + // Dispose + if (newState === _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Terminated) { + this.dispose(); + } + } +} + + +/***/ }), +/* 132 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 133 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 134 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RegistererState", function() { return RegistererState; }); +/** + * {@link Registerer} state. + * @remarks + * The {@link Registerer} behaves in a deterministic manner according to the following + * Finite State Machine (FSM). + * ```txt + * __________________________________________ + * | __________________________ | + * Registerer | | v v + * Constructed -> Initial -> Registered -> Unregistered -> Terminated + * | ^____________| ^ + * |______________________________| + * ``` + * @public + */ +var RegistererState; +(function (RegistererState) { + RegistererState["Initial"] = "Initial"; + RegistererState["Registered"] = "Registered"; + RegistererState["Unregistered"] = "Unregistered"; + RegistererState["Terminated"] = "Terminated"; +})(RegistererState || (RegistererState = {})); + + +/***/ }), +/* 135 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 136 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Registerer", function() { return Registerer; }); +/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); +/* harmony import */ var _emitter__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(108); +/* harmony import */ var _exceptions__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(3); +/* harmony import */ var _registerer_state__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(134); + + + + +/** + * A registerer registers a contact for an address of record (outgoing REGISTER). + * @public + */ +class Registerer { + /** + * 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, options = {}) { + this.disposed = false; + /** The contacts returned from the most recent accepted REGISTER request. */ + this._contacts = []; + /** The number of seconds to wait before retrying to register. */ + this._retryAfter = undefined; + /** The registration state. */ + this._state = _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Initial; + /** True is waiting for final response to outstanding REGISTER request. */ + this._waiting = false; + // state emitter + this._stateEventEmitter = new _emitter__WEBPACK_IMPORTED_MODULE_1__["EmitterImpl"](); + // waiting emitter + this._waitingEventEmitter = new _emitter__WEBPACK_IMPORTED_MODULE_1__["EmitterImpl"](); + // Set user agent + this.userAgent = userAgent; + // Default registrar is domain portion of user agent uri + const defaultUserAgentRegistrar = userAgent.configuration.uri.clone(); + defaultUserAgentRegistrar.user = undefined; + // Initialize configuration + this.options = Object.assign(Object.assign(Object.assign({}, Registerer.defaultOptions()), { registrar: defaultUserAgentRegistrar }), Registerer.stripUndefinedProperties(options)); + // Make sure we are not using references to array options + this.options.extraContactHeaderParams = (this.options.extraContactHeaderParams || []).slice(); + this.options.extraHeaders = (this.options.extraHeaders || []).slice(); + // Make sure we are not using references to registrar uri + if (!this.options.registrar) { + throw new Error("Registrar undefined."); + } + this.options.registrar = this.options.registrar.clone(); + // Set instanceId and regId conditional defaults and validate + if (this.options.regId && !this.options.instanceId) { + this.options.instanceId = Registerer.newUUID(); + } + else if (!this.options.regId && this.options.instanceId) { + this.options.regId = 1; + } + if (this.options.instanceId && _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].parse(this.options.instanceId, "uuid") === -1) { + throw new Error("Invalid instanceId."); + } + if (this.options.regId && this.options.regId < 0) { + throw new Error("Invalid regId."); + } + const registrar = this.options.registrar; + const fromURI = (this.options.params && this.options.params.fromUri) || userAgent.userAgentCore.configuration.aor; + const toURI = (this.options.params && this.options.params.toUri) || userAgent.configuration.uri; + const params = this.options.params || {}; + const extraHeaders = (options.extraHeaders || []).slice(); + // Build the request + this.request = userAgent.userAgentCore.makeOutgoingRequestMessage(_core__WEBPACK_IMPORTED_MODULE_0__["C"].REGISTER, registrar, fromURI, toURI, params, extraHeaders, undefined); + // Registration expires + this.expires = this.options.expires || Registerer.defaultExpires; + if (this.expires < 0) { + throw new Error("Invalid expires."); + } + // initialize logger + this.logger = userAgent.getLogger("sip.Registerer"); + if (this.options.logConfiguration) { + this.logger.log("Configuration:"); + Object.keys(this.options).forEach((key) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const value = this.options[key]; + switch (key) { + case "registrar": + this.logger.log("· " + key + ": " + value); + break; + default: + this.logger.log("· " + key + ": " + JSON.stringify(value)); + } + }); + } + // Identifier + this.id = this.request.callId + this.request.from.parameters.tag; + // Add to the user agent's session collection. + this.userAgent._registerers[this.id] = this; + } + /** Default registerer options. */ + static defaultOptions() { + return { + expires: Registerer.defaultExpires, + extraContactHeaderParams: [], + extraHeaders: [], + logConfiguration: true, + instanceId: "", + params: {}, + regId: 0, + registrar: new _core__WEBPACK_IMPORTED_MODULE_0__["URI"]("sip", "anonymous", "anonymous.invalid") + }; + } + // http://stackoverflow.com/users/109538/broofa + static newUUID() { + const UUID = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => { + const r = Math.floor(Math.random() * 16); + const v = c === "x" ? r : (r % 4) + 8; + return v.toString(16); + }); + return UUID; + } + /** + * Strip properties with undefined values from options. + * This is a work around while waiting for missing vs undefined to be addressed (or not)... + * https://github.com/Microsoft/TypeScript/issues/13195 + * @param options - Options to reduce + */ + static stripUndefinedProperties(options) { + return Object.keys(options).reduce((object, key) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (options[key] !== undefined) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + object[key] = options[key]; + } + return object; + }, {}); + } + /** The registered contacts. */ + get contacts() { + return this._contacts.slice(); + } + /** + * The number of seconds to wait before retrying to register. + * @defaultValue `undefined` + * @remarks + * When the server rejects a registration request, if it provides a suggested + * duration to wait before retrying, that value is available here when and if + * the state transitions to `Unsubscribed`. It is also available during the + * callback to `onReject` after a call to `register`. (Note that if the state + * if already `Unsubscribed`, a rejected request created by `register` will + * not cause the state to transition to `Unsubscribed`. One way to avoid this + * case is to dispose of `Registerer` when unregistered and create a new + * `Registerer` for any attempts to retry registering.) + * @example + * ```ts + * // Checking for retry after on state change + * registerer.stateChange.addListener((newState) => { + * switch (newState) { + * case RegistererState.Unregistered: + * const retryAfter = registerer.retryAfter; + * break; + * } + * }); + * + * // Checking for retry after on request rejection + * registerer.register({ + * requestDelegate: { + * onReject: () => { + * const retryAfter = registerer.retryAfter; + * } + * } + * }); + * ``` + */ + get retryAfter() { + return this._retryAfter; + } + /** The registration state. */ + get state() { + return this._state; + } + /** Emits when the registerer state changes. */ + get stateChange() { + return this._stateEventEmitter; + } + /** Destructor. */ + dispose() { + if (this.disposed) { + return Promise.resolve(); + } + this.disposed = true; + this.logger.log(`Registerer ${this.id} in state ${this.state} is being disposed`); + // Remove from the user agent's registerer collection + delete this.userAgent._registerers[this.id]; + // If registered, unregisters and resolves after final response received. + return new Promise((resolve) => { + const doClose = () => { + // If we are registered, unregister and resolve after our state changes + if (!this.waiting && this._state === _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Registered) { + this.stateChange.addListener(() => { + this.terminated(); + resolve(); + }, { once: true }); + this.unregister(); + return; + } + // Otherwise just resolve + this.terminated(); + 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.addListener(() => { + doClose(); + }, { once: true }); + } + else { + doClose(); + } + }); + } + /** + * Sends the REGISTER request. + * @remarks + * If successful, sends re-REGISTER requests prior to registration expiration until `unsubscribe()` is called. + * Rejects with `RequestPendingError` if a REGISTER request is already in progress. + */ + register(options = {}) { + if (this.state === _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated) { + this.stateError(); + throw new Error("Registerer terminated. Unable to register."); + } + if (this.disposed) { + this.stateError(); + throw new Error("Registerer disposed. Unable to register."); + } + // 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) { + this.waitingWarning(); + const error = new _exceptions__WEBPACK_IMPORTED_MODULE_2__["RequestPendingError"]("REGISTER request already in progress, waiting for final response"); + return Promise.reject(error); + } + // Options + if (options.requestOptions) { + this.options = Object.assign(Object.assign({}, this.options), options.requestOptions); + } + // Extra headers + const 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); + const outgoingRegisterRequest = this.userAgent.userAgentCore.register(this.request, { + onAccept: (response) => { + let 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"); + let 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 + let contact; + while (contacts--) { + contact = response.message.parseHeader("contact", contacts); + if (!contact) { + throw new Error("Contact undefined"); + } + if (contact.uri.user === this.userAgent.contact.uri.user && + contact.uri.host === this.userAgent.contact.uri.host && + contact.uri.port === this.userAgent.contact.uri.port) { + expires = Number(contact.getParam("expires")); + break; + } + 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")) { + const gruu = contact.getParam("temp-gruu"); + if (gruu) { + this.userAgent.contact.tempGruu = _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].URIParse(gruu.replace(/"/g, "")); + } + } + if (contact.hasParam("pub-gruu")) { + const gruu = contact.getParam("pub-gruu"); + if (gruu) { + this.userAgent.contact.pubGruu = _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].URIParse(gruu.replace(/"/g, "")); + } + } + this.registered(expires); + if (options.requestDelegate && options.requestDelegate.onAccept) { + options.requestDelegate.onAccept(response); + } + this.waitingToggle(false); + }, + onProgress: (response) => { + if (options.requestDelegate && options.requestDelegate.onProgress) { + options.requestDelegate.onProgress(response); + } + }, + onRedirect: (response) => { + this.logger.error("Redirect received. Not supported."); + this.unregistered(); + if (options.requestDelegate && options.requestDelegate.onRedirect) { + options.requestDelegate.onRedirect(response); + } + this.waitingToggle(false); + }, + onReject: (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, dropping response"); + 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}`); + // The Retry-After header field can be used with a 500 (Server Internal + // Error) or 503 (Service Unavailable) response to indicate how long the + // service is expected to be unavailable to the requesting client... + // https://tools.ietf.org/html/rfc3261#section-20.33 + let retryAfterDuration = NaN; + if (response.message.statusCode === 500 || response.message.statusCode === 503) { + const header = response.message.getHeader("retry-after"); + if (header) { + retryAfterDuration = Number.parseInt(header, undefined); + } + } + // Set for the state change (if any) and the delegate callback (if any) + this._retryAfter = isNaN(retryAfterDuration) ? undefined : retryAfterDuration; + this.unregistered(); + if (options.requestDelegate && options.requestDelegate.onReject) { + options.requestDelegate.onReject(response); + } + this._retryAfter = undefined; + this.waitingToggle(false); + }, + onTrying: (response) => { + if (options.requestDelegate && options.requestDelegate.onTrying) { + options.requestDelegate.onTrying(response); + } + } + }); + return Promise.resolve(outgoingRegisterRequest); + } + /** + * Sends the REGISTER request with expires equal to zero. + * @remarks + * Rejects with `RequestPendingError` if a REGISTER request is already in progress. + */ + unregister(options = {}) { + if (this.state === _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated) { + this.stateError(); + throw new Error("Registerer terminated. Unable to register."); + } + if (this.disposed) { + if (this.state !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Registered) { + // allows unregister while disposing and registered + this.stateError(); + throw new Error("Registerer disposed. Unable to register."); + } + } + // 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) { + this.waitingWarning(); + const error = new _exceptions__WEBPACK_IMPORTED_MODULE_2__["RequestPendingError"]("REGISTER request already in progress, waiting for final response"); + return Promise.reject(error); + } + if (this._state !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Registered && !options.all) { + this.logger.warn("Not currently registered, but sending an unregister anyway."); + } + // Extra headers + const 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-emptive 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); + const outgoingRegisterRequest = this.userAgent.userAgentCore.register(this.request, { + onAccept: (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: (response) => { + if (options.requestDelegate && options.requestDelegate.onProgress) { + options.requestDelegate.onProgress(response); + } + }, + onRedirect: (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: (response) => { + 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: (response) => { + if (options.requestDelegate && options.requestDelegate.onTrying) { + options.requestDelegate.onTrying(response); + } + } + }); + return Promise.resolve(outgoingRegisterRequest); + } + /** + * Clear registration timers. + */ + clearTimers() { + if (this.registrationTimer !== undefined) { + clearTimeout(this.registrationTimer); + this.registrationTimer = undefined; + } + if (this.registrationExpiredTimer !== undefined) { + clearTimeout(this.registrationExpiredTimer); + this.registrationExpiredTimer = undefined; + } + } + /** + * Generate Contact Header + */ + generateContactHeader(expires) { + let contact = this.userAgent.contact.toString(); + if (this.options.regId && this.options.instanceId) { + contact += ";reg-id=" + this.options.regId; + contact += ';+sip.instance=""'; + } + if (this.options.extraContactHeaderParams) { + this.options.extraContactHeaderParams.forEach((header) => { + contact += ";" + header; + }); + } + contact += ";expires=" + expires; + return contact; + } + /** + * Helper function, called when registered. + */ + registered(expires) { + this.clearTimers(); + // Re-Register before the expiration interval has elapsed. + // For that, decrease the expires value. ie: 3 seconds + this.registrationTimer = setTimeout(() => { + this.registrationTimer = undefined; + this.register(); + }, expires * 1000 - 3000); + // We are unregistered if the registration expires. + this.registrationExpiredTimer = setTimeout(() => { + this.logger.warn("Registration expired"); + this.unregistered(); + }, expires * 1000); + if (this._state !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Registered) { + this.stateTransition(_registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Registered); + } + } + /** + * Helper function, called when unregistered. + */ + unregistered() { + this.clearTimers(); + if (this._state !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Unregistered) { + this.stateTransition(_registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Unregistered); + } + } + /** + * Helper function, called when terminated. + */ + terminated() { + this.clearTimers(); + if (this._state !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated) { + this.stateTransition(_registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated); + } + } + /** + * Transition registration state. + */ + stateTransition(newState) { + const invalidTransition = () => { + throw new Error(`Invalid state transition from ${this._state} to ${newState}`); + }; + // Validate transition + switch (this._state) { + case _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Initial: + if (newState !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Registered && + newState !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Unregistered && + newState !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated) { + invalidTransition(); + } + break; + case _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Registered: + if (newState !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Unregistered && newState !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated) { + invalidTransition(); + } + break; + case _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Unregistered: + if (newState !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Registered && newState !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated) { + invalidTransition(); + } + break; + case _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated: + invalidTransition(); + break; + default: + throw new Error("Unrecognized state."); + } + // Transition + this._state = newState; + this.logger.log(`Registration transitioned to state ${this._state}`); + this._stateEventEmitter.emit(this._state); + // Dispose + if (newState === _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated) { + this.dispose(); + } + } + /** True if the registerer is currently waiting for final response to a REGISTER request. */ + get waiting() { + return this._waiting; + } + /** Emits when the registerer waiting state changes. */ + get waitingChange() { + return this._waitingEventEmitter; + } + /** + * Toggle waiting. + */ + waitingToggle(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(this._waiting); + } + /** Hopefully helpful as the standard behavior has been found to be unexpected. */ + waitingWarning() { + let message = "An attempt was made to send a REGISTER request while a prior one was still in progress."; + message += " RFC 3261 requires UAs MUST NOT send a new registration until they have received a final response"; + message += " from the registrar for the previous one or the previous REGISTER request has timed out."; + message += " Note that if the transport disconnects, you still must wait for the prior request to time out before"; + message += + " sending a new REGISTER request or alternatively dispose of the current Registerer and create a new Registerer."; + this.logger.warn(message); + } + /** Hopefully helpful as the standard behavior has been found to be unexpected. */ + stateError() { + const reason = this.state === _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated ? "is in 'Terminated' state" : "has been disposed"; + let message = `An attempt was made to send a REGISTER request when the Registerer ${reason}.`; + message += " The Registerer transitions to 'Terminated' when Registerer.dispose() is called."; + message += " Perhaps you called UserAgent.stop() which dipsoses of all Registerers?"; + this.logger.error(message); + } +} +Registerer.defaultExpires = 600; + + +/***/ }), +/* 137 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 138 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 139 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 140 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 141 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 142 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 143 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 144 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 145 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 146 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 147 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 148 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Subscriber", function() { return Subscriber; }); +/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); +/* harmony import */ var _core_user_agent_core_allowed_methods__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(82); +/* harmony import */ var _notification__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(116); +/* harmony import */ var _subscription__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(149); +/* harmony import */ var _subscription_state__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(150); + + + + + +/** + * 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.addListener((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 + */ +class Subscriber extends _subscription__WEBPACK_IMPORTED_MODULE_3__["Subscription"] { + /** + * 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, targetURI, eventType, options = {}) { + super(userAgent, options); + this.body = undefined; + this.logger = userAgent.getLogger("sip.Subscriber"); + if (options.body) { + this.body = { + body: options.body, + contentType: options.contentType ? options.contentType : "application/sdp" + }; + } + 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.subscriberRequest = this.initSubscriberRequest(); + this.outgoingRequestMessage = this.subscriberRequest.message; + // Add to UserAgent's collection + this.id = this.outgoingRequestMessage.callId + this.outgoingRequestMessage.from.parameters.tag + this.event; + this._userAgent._subscriptions[this.id] = this; + } + /** + * Destructor. + * @internal + */ + dispose() { + if (this.disposed) { + return Promise.resolve(); + } + this.logger.log(`Subscription ${this.id} in state ${this.state} is being disposed`); + // Remove from the user agent's subscription collection + delete this._userAgent._subscriptions[this.id]; + // Clear timers + if (this.retryAfterTimer) { + clearTimeout(this.retryAfterTimer); + this.retryAfterTimer = undefined; + } + // Dispose subscriber request + this.subscriberRequest.dispose(); + // Make sure to dispose of our parent, then unsubscribe the + // subscription dialog (if need be) and resolve when it has terminated. + return super.dispose().then(() => { + // If we have never subscribed there is nothing to wait on. + // If we are already transitioned to terminated there is no need to unsubscribe again. + if (this.state !== _subscription_state__WEBPACK_IMPORTED_MODULE_4__["SubscriptionState"].Subscribed) { + return; + } + if (!this._dialog) { + throw new Error("Dialog undefined."); + } + if (this._dialog.subscriptionState === _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Pending || + this._dialog.subscriptionState === _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Active) { + const dialog = this._dialog; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + return new Promise((resolve, reject) => { + dialog.delegate = { + onTerminated: () => resolve() + }; + dialog.unsubscribe(); + }); + } + }); + } + /** + * 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". + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + subscribe(options = {}) { + switch (this.subscriberRequest.state) { + case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Initial: + // we can end up here when retrying so only state transition if in SubscriptionState.Initial state + if (this.state === _subscription_state__WEBPACK_IMPORTED_MODULE_4__["SubscriptionState"].Initial) { + this.stateTransition(_subscription_state__WEBPACK_IMPORTED_MODULE_4__["SubscriptionState"].NotifyWait); + } + this.subscriberRequest.subscribe().then((result) => { + if (result.success) { + if (result.success.subscription) { + this._dialog = result.success.subscription; + this._dialog.delegate = { + onNotify: (request) => this.onNotify(request), + onRefresh: (request) => this.onRefresh(request), + onTerminated: () => { + // If a call to unsubscribe will state transition to SubscriptionState.Terminated, + // but we can end up here after that if the NOTIFY never arrives and timer N fires. + if (this.state !== _subscription_state__WEBPACK_IMPORTED_MODULE_4__["SubscriptionState"].Terminated) { + this.stateTransition(_subscription_state__WEBPACK_IMPORTED_MODULE_4__["SubscriptionState"].Terminated); + } + } + }; + } + this.onNotify(result.success.request); + } + else if (result.failure) { + this.unsubscribe(); + } + }); + break; + case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].NotifyWait: + break; + case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Pending: + break; + case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Active: + if (this._dialog) { + const request = this._dialog.refresh(); + request.delegate = { + onAccept: (response) => this.onAccepted(response), + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onRedirect: (response) => this.unsubscribe(), + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onReject: (response) => this.unsubscribe() + }; + } + break; + case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Terminated: + break; + default: + break; + } + return Promise.resolve(); + } + /** + * {@inheritDoc Subscription.unsubscribe} + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + unsubscribe(options = {}) { + if (this.disposed) { + return Promise.resolve(); + } + switch (this.subscriberRequest.state) { + case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Initial: + break; + case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].NotifyWait: + break; + case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Pending: + if (this._dialog) { + this._dialog.unsubscribe(); + // responses intentionally ignored + } + break; + case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Active: + if (this._dialog) { + this._dialog.unsubscribe(); + // responses intentionally ignored + } + break; + case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Terminated: + break; + default: + throw new Error("Unknown state."); + } + this.stateTransition(_subscription_state__WEBPACK_IMPORTED_MODULE_4__["SubscriptionState"].Terminated); + return Promise.resolve(); + } + /** + * Sends a re-SUBSCRIBE request if the subscription is "active". + * @deprecated Use `subscribe` instead. + * @internal + */ + _refresh() { + if (this.subscriberRequest.state === _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Active) { + return this.subscribe(); + } + return Promise.resolve(); + } + /** @internal */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onAccepted(response) { + // NOTE: If you think you should do something with this response, + // please make sure you understand what it is you are doing and why. + // Per the RFC, the first NOTIFY is all that actually matters. + } + /** @internal */ + onNotify(request) { + // 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__WEBPACK_IMPORTED_MODULE_4__["SubscriptionState"].Subscribed) { + this.stateTransition(_subscription_state__WEBPACK_IMPORTED_MODULE_4__["SubscriptionState"].Subscribed); + } + // Delegate notification. + if (this.delegate && this.delegate.onNotify) { + const notification = new _notification__WEBPACK_IMPORTED_MODULE_2__["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 + const 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.initSubscriberRequest(); + this.subscribe(); + return; + case "probation": + case "giveup": + this.initSubscriberRequest(); + if (subscriptionState.params && subscriptionState.params["retry-after"]) { + this.retryAfterTimer = setTimeout(() => { + this.subscribe(); + }, subscriptionState.params["retry-after"]); + } + else { + this.subscribe(); + } + return; + case "rejected": + case "noresource": + case "invariant": + break; + } + } + this.unsubscribe(); + break; + default: + break; + } + } + } + /** @internal */ + onRefresh(request) { + request.delegate = { + onAccept: (response) => this.onAccepted(response) + }; + } + initSubscriberRequest() { + const options = { + extraHeaders: this.extraHeaders, + body: this.body ? Object(_core__WEBPACK_IMPORTED_MODULE_0__["fromBodyLegacy"])(this.body) : undefined + }; + // eslint-disable-next-line @typescript-eslint/no-use-before-define + this.subscriberRequest = new SubscriberRequest(this._userAgent.userAgentCore, this.targetURI, this.event, this.expires, options); + this.subscriberRequest.delegate = { + onAccept: (response) => this.onAccepted(response) + }; + return this.subscriberRequest; + } +} +class SubscriberRequest { + constructor(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.Subscriber"); + this.delegate = delegate; + const allowHeader = "Allow: " + _core_user_agent_core_allowed_methods__WEBPACK_IMPORTED_MODULE_1__["AllowedMethods"].toString(); + const 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()); + const body = options && options.body; + this.message = core.makeOutgoingRequestMessage(_core__WEBPACK_IMPORTED_MODULE_0__["C"].SUBSCRIBE, this.target, this.core.configuration.aor, this.target, {}, extraHeaders, body); + } + /** Destructor. */ + dispose() { + if (this.request) { + this.request.waitNotifyStop(); + this.request.dispose(); + this.request = undefined; + } + } + /** Subscription state. */ + get state() { + if (this.subscription) { + return this.subscription.subscriptionState; + } + else if (this.subscribed) { + return _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].NotifyWait; + } + else { + return _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Initial; + } + } + /** + * Establish subscription. + * @param options Options bucket. + */ + subscribe() { + 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((resolve) => { + 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: (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: (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: () => { + 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: (response) => { + resolve({ failure: { 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: (response) => { + resolve({ failure: { response } }); + } + }); + }); + } +} + + +/***/ }), +/* 149 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Subscription", function() { return Subscription; }); +/* harmony import */ var _emitter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(108); +/* harmony import */ var _subscription_state__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(150); + + +/** + * A subscription provides {@link Notification} of events. + * + * @remarks + * See {@link Subscriber} for details on establishing a subscription. + * + * @public + */ +class Subscription { + /** + * Constructor. + * @param userAgent - User agent. See {@link UserAgent} for details. + * @internal + */ + constructor(userAgent, options = {}) { + this._disposed = false; + this._state = _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Initial; + this._logger = userAgent.getLogger("sip.Subscription"); + this._stateEventEmitter = new _emitter__WEBPACK_IMPORTED_MODULE_0__["EmitterImpl"](); + this._userAgent = userAgent; + this.delegate = options.delegate; + } + /** + * Destructor. + */ + dispose() { + if (this._disposed) { + return Promise.resolve(); + } + this._disposed = true; + this._stateEventEmitter.removeAllListeners(); + return Promise.resolve(); + } + /** + * The subscribed subscription dialog. + */ + get dialog() { + return this._dialog; + } + /** + * True if disposed. + * @internal + */ + get disposed() { + return this._disposed; + } + /** + * Subscription state. See {@link SubscriptionState} for details. + */ + get state() { + return this._state; + } + /** + * Emits when the subscription `state` property changes. + */ + get stateChange() { + return this._stateEventEmitter; + } + /** @internal */ + stateTransition(newState) { + const invalidTransition = () => { + throw new Error(`Invalid state transition from ${this._state} to ${newState}`); + }; + // Validate transition + switch (this._state) { + case _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Initial: + if (newState !== _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].NotifyWait && newState !== _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated) { + invalidTransition(); + } + break; + case _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].NotifyWait: + if (newState !== _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Subscribed && newState !== _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated) { + invalidTransition(); + } + break; + case _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Subscribed: + if (newState !== _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated) { + invalidTransition(); + } + break; + case _subscription_state__WEBPACK_IMPORTED_MODULE_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(this._state); + // Dispose + if (newState === _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated) { + this.dispose(); + } + } +} + + +/***/ }), +/* 150 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubscriptionState", function() { return SubscriptionState; }); +/** + * {@link Subscription} state. + * @remarks + * The {@link Subscription} behaves in a deterministic manner according to the following + * Finite State Machine (FSM). + * ```txt + * _______________________________________ + * Subscription | v + * Constructed -> Initial -> NotifyWait -> Subscribed -> Terminated + * |____________________________^ + * ``` + * @public + */ +var SubscriptionState; +(function (SubscriptionState) { + SubscriptionState["Initial"] = "Initial"; + SubscriptionState["NotifyWait"] = "NotifyWait"; + SubscriptionState["Subscribed"] = "Subscribed"; + SubscriptionState["Terminated"] = "Terminated"; +})(SubscriptionState || (SubscriptionState = {})); + + +/***/ }), +/* 151 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 152 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 153 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 154 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 155 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 156 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TransportState", function() { return TransportState; }); +/** + * {@link Transport} state. + * + * @remarks + * The {@link Transport} behaves in a deterministic manner according to the following + * Finite State Machine (FSM). + * ```txt + * ______________________________ + * | ____________ | + * Transport v v | | + * Constructed -> Disconnected -> Connecting -> Connected -> Disconnecting + * ^ ^ |_____________________^ | | + * | |_____________________________| | + * |_____________________________________________| + * ``` + * @public + */ +var TransportState; +(function (TransportState) { + /** + * The `connect()` method was called. + */ + TransportState["Connecting"] = "Connecting"; + /** + * The `connect()` method resolved. + */ + TransportState["Connected"] = "Connected"; + /** + * The `disconnect()` method was called. + */ + TransportState["Disconnecting"] = "Disconnecting"; + /** + * The `connect()` method was rejected, or + * the `disconnect()` method completed, or + * network connectivity was lost. + */ + TransportState["Disconnected"] = "Disconnected"; +})(TransportState || (TransportState = {})); + + +/***/ }), +/* 157 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 158 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UserAgentState", function() { return UserAgentState; }); +/** + * {@link UserAgent} state. + * @remarks + * Valid state transitions: + * ``` + * 1. "Started" --> "Stopped" + * 2. "Stopped" --> "Started" + * ``` + * @public + */ +var UserAgentState; +(function (UserAgentState) { + UserAgentState["Started"] = "Started"; + UserAgentState["Stopped"] = "Stopped"; +})(UserAgentState || (UserAgentState = {})); + + +/***/ }), +/* 159 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UserAgent", function() { return UserAgent; }); +/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); +/* harmony import */ var _core_messages_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(32); +/* harmony import */ var _platform_web_session_description_handler__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(160); +/* harmony import */ var _platform_web_transport__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(171); +/* harmony import */ var _version__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1); +/* harmony import */ var _emitter__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(108); +/* harmony import */ var _invitation__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(113); +/* harmony import */ var _inviter__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(123); +/* harmony import */ var _message__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(115); +/* harmony import */ var _notification__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(116); +/* harmony import */ var _user_agent_options__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(119); +/* harmony import */ var _user_agent_state__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(158); + + + + + + + + + + + + +/** + * 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 + */ +class UserAgent { + /** + * Constructs a new instance of the `UserAgent` class. + * @param options - Options bucket. See {@link UserAgentOptions} for details. + */ + constructor(options = {}) { + /** @internal */ + this._publishers = {}; + /** @internal */ + this._registerers = {}; + /** @internal */ + this._sessions = {}; + /** @internal */ + this._subscriptions = {}; + this._state = _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Stopped; + /** Unload listener. */ + this.unloadListener = () => { + this.stop(); + }; + // state emitter + this._stateEventEmitter = new _emitter__WEBPACK_IMPORTED_MODULE_5__["EmitterImpl"](); + // initialize delegate + this.delegate = options.delegate; + // initialize configuration + this.options = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, UserAgent.defaultOptions()), { sipjsId: Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["createRandomToken"])(5) }), { uri: new _core__WEBPACK_IMPORTED_MODULE_0__["URI"]("sip", "anonymous." + Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["createRandomToken"])(6), "anonymous.invalid") }), { viaHost: Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["createRandomToken"])(12) + ".invalid" }), UserAgent.stripUndefinedProperties(options)); + // viaHost is hack + if (this.options.hackIpInContact) { + if (typeof this.options.hackIpInContact === "boolean" && this.options.hackIpInContact) { + const from = 1; + const to = 254; + const 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.loggerFactory = new _core__WEBPACK_IMPORTED_MODULE_0__["LoggerFactory"](); + 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__WEBPACK_IMPORTED_MODULE_0__["Levels"].error; + break; + case "warn": + this.loggerFactory.level = _core__WEBPACK_IMPORTED_MODULE_0__["Levels"].warn; + break; + case "log": + this.loggerFactory.level = _core__WEBPACK_IMPORTED_MODULE_0__["Levels"].log; + break; + case "debug": + this.loggerFactory.level = _core__WEBPACK_IMPORTED_MODULE_0__["Levels"].debug; + break; + default: + break; + } + if (this.options.logConfiguration) { + this.logger.log("Configuration:"); + Object.keys(this.options).forEach((key) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const value = this.options[key]; + 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)); + } + }); + } + // guard deprecated transport options (remove this in version 16.x) + if (this.options.transportOptions) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const optionsDeprecated = this.options.transportOptions; + const maxReconnectionAttemptsDeprecated = optionsDeprecated.maxReconnectionAttempts; + const reconnectionTimeoutDeprecated = optionsDeprecated.reconnectionTimeout; + if (maxReconnectionAttemptsDeprecated !== undefined) { + const deprecatedMessage = `The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. ` + + "It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly."; + this.logger.warn(deprecatedMessage); + } + if (reconnectionTimeoutDeprecated !== undefined) { + const deprecatedMessage = `The transport option "reconnectionTimeout" as has apparently been specified and has been deprecated. ` + + "It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly."; + this.logger.warn(deprecatedMessage); + } + // hack + if (options.reconnectionDelay === undefined && reconnectionTimeoutDeprecated !== undefined) { + this.options.reconnectionDelay = reconnectionTimeoutDeprecated; + } + if (options.reconnectionAttempts === undefined && maxReconnectionAttemptsDeprecated !== undefined) { + this.options.reconnectionAttempts = maxReconnectionAttemptsDeprecated; + } + } + // guard deprecated user agent options (remove this in version 16.x) + if (options.reconnectionDelay !== undefined) { + const deprecatedMessage = `The user agent option "reconnectionDelay" as has apparently been specified and has been deprecated. ` + + "It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly."; + this.logger.warn(deprecatedMessage); + } + if (options.reconnectionAttempts !== undefined) { + const deprecatedMessage = `The user agent option "reconnectionAttempts" as has apparently been specified and has been deprecated. ` + + "It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly."; + this.logger.warn(deprecatedMessage); + } + // Initialize Transport + this._transport = new this.options.transportConstructor(this.getLogger("sip.Transport"), this.options.transportOptions); + this.initTransportCallbacks(); + // Initialize Contact + this._contact = this.initContact(); + // Initialize UserAgentCore + 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"); + * ``` + */ + static makeURI(uri) { + return _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].URIParse(uri); + } + /** Default user agent options. */ + static defaultOptions() { + return { + allowLegacyNotifications: false, + authorizationHa1: "", + authorizationPassword: "", + authorizationUsername: "", + autoStart: false, + autoStop: true, + delegate: {}, + contactName: "", + contactParams: { transport: "ws" }, + displayName: "", + forceRport: false, + hackAllowUnregisteredOptionTags: false, + hackIpInContact: false, + hackViaTcp: false, + logBuiltinEnabled: true, + logConfiguration: true, + logConnector: () => { + /* noop */ + }, + logLevel: "log", + noAnswerTimeout: 60, + preloadedRouteSet: [], + reconnectionAttempts: 0, + reconnectionDelay: 4, + sessionDescriptionHandlerFactory: Object(_platform_web_session_description_handler__WEBPACK_IMPORTED_MODULE_2__["defaultSessionDescriptionHandlerFactory"])(), + sessionDescriptionHandlerFactoryOptions: {}, + sipExtension100rel: _user_agent_options__WEBPACK_IMPORTED_MODULE_10__["SIPExtension"].Unsupported, + sipExtensionReplaces: _user_agent_options__WEBPACK_IMPORTED_MODULE_10__["SIPExtension"].Unsupported, + sipExtensionExtraSupported: [], + sipjsId: "", + transportConstructor: _platform_web_transport__WEBPACK_IMPORTED_MODULE_3__["Transport"], + transportOptions: {}, + uri: new _core__WEBPACK_IMPORTED_MODULE_0__["URI"]("sip", "anonymous", "anonymous.invalid"), + userAgentString: "SIP.js/" + _version__WEBPACK_IMPORTED_MODULE_4__["LIBRARY_VERSION"], + viaHost: "" + }; + } + /** + * Strip properties with undefined values from options. + * This is a work around while waiting for missing vs undefined to be addressed (or not)... + * https://github.com/Microsoft/TypeScript/issues/13195 + * @param options - Options to reduce + */ + static stripUndefinedProperties(options) { + return Object.keys(options).reduce((object, key) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (options[key] !== undefined) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + object[key] = options[key]; + } + return object; + }, {}); + } + /** + * User agent configuration. + */ + get configuration() { + return this.options; + } + /** + * User agent contact. + */ + get contact() { + return this._contact; + } + /** + * User agent state. + */ + get state() { + return this._state; + } + /** + * User agent state change emitter. + */ + get stateChange() { + return this._stateEventEmitter; + } + /** + * User agent transport. + */ + get transport() { + return this._transport; + } + /** + * User agent core. + */ + get userAgentCore() { + return this._userAgentCore; + } + /** + * The logger. + */ + getLogger(category, label) { + return this.loggerFactory.getLogger(category, label); + } + /** + * The logger factory. + */ + getLoggerFactory() { + return this.loggerFactory; + } + /** + * True if transport is connected. + */ + isConnected() { + return this.transport.isConnected(); + } + /** + * Reconnect the transport. + */ + reconnect() { + if (this.state === _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Stopped) { + return Promise.reject(new Error("User agent stopped.")); + } + // Make sure we don't call synchronously + return Promise.resolve().then(() => this.transport.connect()); + } + /** + * Start the user agent. + * + * @remarks + * Resolves if transport connects, otherwise rejects. + * + * @example + * ```ts + * userAgent.start() + * .then(() => { + * // userAgent.isConnected() === true + * }) + * .catch((error: Error) => { + * // userAgent.isConnected() === false + * }); + * ``` + */ + start() { + if (this.state === _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Started) { + this.logger.warn(`User agent already started`); + return Promise.resolve(); + } + this.logger.log(`Starting ${this.configuration.uri}`); + // Transition state + this.transitionState(_user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Started); + // TODO: Review this as it is not clear it has any benefit and at worst causes additional load the server. + // On unload it may be best to simply in most scenarios to do nothing. Furthermore and regardless, this + // kind of behavior seems more appropriate to be managed by the consumer of the API than the API itself. + // Should this perhaps be deprecated? + // + // Add window unload event listener + if (this.options.autoStop) { + // Google Chrome Packaged Apps don't allow 'unload' listeners: unload is not available in packaged apps + const 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.transport.connect(); + } + /** + * Stop the user agent. + * + * @remarks + * Resolves when the user agent has completed a graceful shutdown. + * ```txt + * 1) Sessions terminate. + * 2) Registerers unregister. + * 3) Subscribers unsubscribe. + * 4) Publishers unpublish. + * 5) Transport disconnects. + * 6) User Agent Core resets. + * ``` + * NOTE: While this is a "graceful shutdown", it can also be very slow one if you + * are waiting for the returned Promise to resolve. The disposal of the clients and + * dialogs is done serially - waiting on one to finish before moving on to the next. + * This can be slow if there are lot of subscriptions to unsubscribe for example. + * + * THE SLOW PACE IS INTENTIONAL! + * While one could spin them all down in parallel, this could slam the remote server. + * It is bad practice to denial of service attack (DoS attack) servers!!! + * Moreover, production servers will automatically blacklist clients which send too + * many requests in too short a period of time - dropping any additional requests. + * + * If a different approach to disposing is needed, one can implement whatever is + * needed and execute that prior to calling `stop()`. Alternatively one may simply + * not wait for the Promise returned by `stop()` to complete. + */ + async stop() { + if (this.state === _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Stopped) { + this.logger.warn(`User agent already stopped`); + return Promise.resolve(); + } + this.logger.log(`Stopping ${this.configuration.uri}`); + // Transition state + this.transitionState(_user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Stopped); + // TODO: See comments with associated complimentary code in start(). Should this perhaps be deprecated? + // Remove window unload event listener + if (this.options.autoStop) { + // Google Chrome Packaged Apps don't allow 'unload' listeners: unload is not available in packaged apps + const googleChromePackagedApp = typeof chrome !== "undefined" && chrome.app && chrome.app.runtime ? true : false; + if (typeof window !== "undefined" && window.removeEventListener && !googleChromePackagedApp) { + window.removeEventListener("unload", this.unloadListener); + } + } + // Be careful here to use a local references as start() can be called + // again before we complete and we don't want to touch new clients + // and we don't want to step on the new instances (or vice versa). + const publishers = Object.assign({}, this._publishers); + const registerers = Object.assign({}, this._registerers); + const sessions = Object.assign({}, this._sessions); + const subscriptions = Object.assign({}, this._subscriptions); + const transport = this.transport; + const userAgentCore = this.userAgentCore; + // + // At this point we have completed the state transition and everything + // following will effectively run async and MUST NOT cause any issues + // if UserAgent.start() is called while the following code continues. + // + // TODO: Minor optimization. + // The disposal in all cases involves, in part, sending messages which + // is not worth doing if the transport is not connected as we know attempting + // to send messages will be futile. But none of these disposal methods check + // if that's is the case and it would be easy for them to do so at this point. + // Dispose of Registerers + this.logger.log(`Dispose of registerers`); + for (const id in registerers) { + if (registerers[id]) { + await registerers[id].dispose().catch((error) => { + this.logger.error(error.message); + delete this._registerers[id]; + throw error; + }); + } + } + // Dispose of Sessions + this.logger.log(`Dispose of sessions`); + for (const id in sessions) { + if (sessions[id]) { + await sessions[id].dispose().catch((error) => { + this.logger.error(error.message); + delete this._sessions[id]; + throw error; + }); + } + } + // Dispose of Subscriptions + this.logger.log(`Dispose of subscriptions`); + for (const id in subscriptions) { + if (subscriptions[id]) { + await subscriptions[id].dispose().catch((error) => { + this.logger.error(error.message); + delete this._subscriptions[id]; + throw error; + }); + } + } + // Dispose of Publishers + this.logger.log(`Dispose of publishers`); + for (const id in publishers) { + if (publishers[id]) { + await publishers[id].dispose().catch((error) => { + this.logger.error(error.message); + delete this._publishers[id]; + throw error; + }); + } + } + // Dispose of the transport (disconnecting) + this.logger.log(`Dispose of transport`); + await transport.dispose().catch((error) => { + this.logger.error(error.message); + throw error; + }); + // Dispose of the user agent core (resetting) + this.logger.log(`Dispose of core`); + userAgentCore.dispose(); + } + /** + * Used to avoid circular references. + * @internal + */ + _makeInviter(targetURI, options) { + return new _inviter__WEBPACK_IMPORTED_MODULE_7__["Inviter"](this, targetURI, options); + } + /** + * Attempt reconnection up to `maxReconnectionAttempts` times. + * @param reconnectionAttempt - Current attempt number. + */ + attemptReconnection(reconnectionAttempt = 1) { + const reconnectionAttempts = this.options.reconnectionAttempts; + const reconnectionDelay = this.options.reconnectionDelay; + if (reconnectionAttempt > reconnectionAttempts) { + this.logger.log(`Maximum reconnection attempts reached`); + return; + } + this.logger.log(`Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - trying`); + setTimeout(() => { + this.reconnect() + .then(() => { + this.logger.log(`Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - succeeded`); + }) + .catch((error) => { + this.logger.error(error.message); + this.logger.log(`Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - failed`); + this.attemptReconnection(++reconnectionAttempt); + }); + }, reconnectionAttempt === 1 ? 0 : reconnectionDelay * 1000); + } + /** + * Initialize contact. + */ + initContact() { + const contactName = this.options.contactName != "" ? this.options.contactName : Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["createRandomToken"])(8); + const contactParams = this.options.contactParams; + const contact = { + pubGruu: undefined, + tempGruu: undefined, + uri: new _core__WEBPACK_IMPORTED_MODULE_0__["URI"]("sip", contactName, this.options.viaHost, undefined, contactParams), + toString: (contactToStringOptions = {}) => { + const anonymous = contactToStringOptions.anonymous || false; + const outbound = contactToStringOptions.outbound || false; + let contactString = "<"; + if (anonymous) { + contactString += + this.contact.tempGruu || + `sip:anonymous@anonymous.invalid;transport=${contactParams.transport ? contactParams.transport : "ws"}`; + } + else { + contactString += this.contact.pubGruu || this.contact.uri; + } + if (outbound) { + contactString += ";ob"; + } + contactString += ">"; + return contactString; + } + }; + return contact; + } + /** + * Initialize user agent core. + */ + initCore() { + // supported options + let supportedOptionTags = []; + supportedOptionTags.push("outbound"); // TODO: is this really supported? + if (this.options.sipExtension100rel === _user_agent_options__WEBPACK_IMPORTED_MODULE_10__["SIPExtension"].Supported) { + supportedOptionTags.push("100rel"); + } + if (this.options.sipExtensionReplaces === _user_agent_options__WEBPACK_IMPORTED_MODULE_10__["SIPExtension"].Supported) { + supportedOptionTags.push("replaces"); + } + if (this.options.sipExtensionExtraSupported) { + supportedOptionTags.push(...this.options.sipExtensionExtraSupported); + } + if (!this.options.hackAllowUnregisteredOptionTags) { + supportedOptionTags = supportedOptionTags.filter((optionTag) => _user_agent_options__WEBPACK_IMPORTED_MODULE_10__["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. + const supportedOptionTagsResponse = supportedOptionTags.slice(); + if (this.contact.pubGruu || this.contact.tempGruu) { + supportedOptionTagsResponse.push("gruu"); + } + // core configuration + const userAgentCoreConfiguration = { + aor: this.options.uri, + contact: this.contact, + displayName: this.options.displayName, + loggerFactory: this.loggerFactory, + hackViaTcp: this.options.hackViaTcp, + routeSet: this.options.preloadedRouteSet, + supportedOptionTags, + supportedOptionTagsResponse, + sipjsId: this.options.sipjsId, + userAgentHeaderFieldValue: this.options.userAgentString, + viaForceRport: this.options.forceRport, + viaHost: this.options.viaHost, + authenticationFactory: () => { + const username = this.options.authorizationUsername + ? this.options.authorizationUsername + : this.options.uri.user; // if authorization username not provided, use uri user as username + const password = this.options.authorizationPassword ? this.options.authorizationPassword : undefined; + const ha1 = this.options.authorizationHa1 ? this.options.authorizationHa1 : undefined; + return new _core__WEBPACK_IMPORTED_MODULE_0__["DigestAuthentication"](this.getLoggerFactory(), ha1, username, password); + }, + transportAccessor: () => this.transport + }; + const userAgentCoreDelegate = { + onInvite: (incomingInviteRequest) => { + var _a; + const invitation = new _invitation__WEBPACK_IMPORTED_MODULE_6__["Invitation"](this, incomingInviteRequest); + incomingInviteRequest.delegate = { + onCancel: (cancel) => { + invitation._onCancel(cancel); + }, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onTransportError: (error) => { + // A server transaction MUST NOT discard transaction state based only on + // encountering a non-recoverable transport error when sending a + // response. Instead, the associated INVITE server transaction state + // machine MUST remain in its current state. (Timers will eventually + // cause it to transition to the "Terminated" state). + // https://tools.ietf.org/html/rfc6026#section-7.1 + // As noted in the comment above, we are to leaving it to the transaction + // timers to eventually cause the transaction to sort itself out in the case + // of a transport failure in an invite server transaction. This delegate method + // is here simply here for completeness and to make it clear that it provides + // nothing more than informational hook into the core. That is, if you think + // you should be trying to deal with a transport error here, you are likely wrong. + this.logger.error("A transport error has occurred while handling an incoming INVITE request."); + } + }; + // 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__WEBPACK_IMPORTED_MODULE_10__["SIPExtension"].Unsupported) { + const message = incomingInviteRequest.message; + const replaces = message.parseHeader("replaces"); + if (replaces) { + const callId = replaces.call_id; + if (typeof callId !== "string") { + throw new Error("Type of call id is not string"); + } + const toTag = replaces.replaces_to_tag; + if (typeof toTag !== "string") { + throw new Error("Type of to tag is not string"); + } + const fromTag = replaces.replaces_from_tag; + if (typeof fromTag !== "string") { + throw new Error("type of from tag is not string"); + } + const targetDialogId = callId + toTag + fromTag; + const 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. + const targetSession = this._sessions[callId + fromTag] || this._sessions[callId + toTag] || undefined; + if (!targetSession) { + throw new Error("Session does not exist."); + } + invitation._replacee = targetSession; + } + } + // Delegate invitation handling. + if ((_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onInvite) { + if (invitation.autoSendAnInitialProvisionalResponse) { + invitation.progress().then(() => { + var _a; + if (((_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onInvite) === undefined) { + throw new Error("onInvite undefined."); + } + this.delegate.onInvite(invitation); + }); + return; + } + this.delegate.onInvite(invitation); + return; + } + // 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 + invitation.reject({ statusCode: 486 }); + }, + onMessage: (incomingMessageRequest) => { + if (this.delegate && this.delegate.onMessage) { + const message = new _message__WEBPACK_IMPORTED_MODULE_8__["Message"](incomingMessageRequest); + this.delegate.onMessage(message); + } + else { + // Accept the MESSAGE request, but do nothing with it. + incomingMessageRequest.accept(); + } + }, + onNotify: (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) { + const notification = new _notification__WEBPACK_IMPORTED_MODULE_9__["Notification"](incomingNotifyRequest); + this.delegate.onNotify(notification); + } + else { + // Per the above which obsoletes 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: (incomingReferRequest) => { + this.logger.warn("Received an out of dialog REFER request"); + // TOOD: this.delegate.onRefer(...) + if (this.delegate && this.delegate.onReferRequest) { + this.delegate.onReferRequest(incomingReferRequest); + } + else { + incomingReferRequest.reject({ statusCode: 405 }); + } + }, + onRegister: (incomingRegisterRequest) => { + this.logger.warn("Received an out of dialog REGISTER request"); + // TOOD: this.delegate.onRegister(...) + if (this.delegate && this.delegate.onRegisterRequest) { + this.delegate.onRegisterRequest(incomingRegisterRequest); + } + else { + incomingRegisterRequest.reject({ statusCode: 405 }); + } + }, + onSubscribe: (incomingSubscribeRequest) => { + this.logger.warn("Received an out of dialog SUBSCRIBE request"); + // TOOD: this.delegate.onSubscribe(...) + if (this.delegate && this.delegate.onSubscribeRequest) { + this.delegate.onSubscribeRequest(incomingSubscribeRequest); + } + else { + incomingSubscribeRequest.reject({ statusCode: 405 }); + } + } + }; + return new _core__WEBPACK_IMPORTED_MODULE_0__["UserAgentCore"](userAgentCoreConfiguration, userAgentCoreDelegate); + } + initTransportCallbacks() { + this.transport.onConnect = () => this.onTransportConnect(); + this.transport.onDisconnect = (error) => this.onTransportDisconnect(error); + this.transport.onMessage = (message) => this.onTransportMessage(message); + } + onTransportConnect() { + if (this.state === _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Stopped) { + return; + } + if (this.delegate && this.delegate.onConnect) { + this.delegate.onConnect(); + } + } + onTransportDisconnect(error) { + if (this.state === _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Stopped) { + return; + } + if (this.delegate && this.delegate.onDisconnect) { + this.delegate.onDisconnect(error); + } + // Only attempt to reconnect if network/server dropped the connection. + if (error && this.options.reconnectionAttempts > 0) { + this.attemptReconnection(); + } + } + onTransportMessage(messageString) { + const message = _core__WEBPACK_IMPORTED_MODULE_0__["Parser"].parseMessage(messageString, this.getLogger("sip.Parser")); + if (!message) { + this.logger.warn("Failed to parse incoming message. Dropping."); + return; + } + if (this.state === _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Stopped && message instanceof _core__WEBPACK_IMPORTED_MODULE_0__["IncomingRequestMessage"]) { + this.logger.warn(`Received ${message.method} request while stopped. 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 + const hasMinimumHeaders = () => { + const mandatoryHeaders = ["from", "to", "call_id", "cseq", "via"]; + for (const header of mandatoryHeaders) { + if (!message.hasHeader(header)) { + this.logger.warn(`Missing mandatory header field : ${header}.`); + return false; + } + } + return true; + }; + // Request Checks + if (message instanceof _core__WEBPACK_IMPORTED_MODULE_0__["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 configurable 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(). + const len = Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["utf8Length"])(message.body); + const contentLength = message.getHeader("content-length"); + if (contentLength && len < Number(contentLength)) { + this.userAgentCore.replyStateless(message, { statusCode: 400 }); + return; + } + } + // Response Checks + if (message instanceof _core__WEBPACK_IMPORTED_MODULE_0__["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(). + const len = Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["utf8Length"])(message.body); + const 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__WEBPACK_IMPORTED_MODULE_0__["IncomingRequestMessage"]) { + this.userAgentCore.receiveIncomingRequestFromTransport(message); + return; + } + // Handle Response + if (message instanceof _core__WEBPACK_IMPORTED_MODULE_0__["IncomingResponseMessage"]) { + this.userAgentCore.receiveIncomingResponseFromTransport(message); + return; + } + throw new Error("Invalid message type."); + } + /** + * Transition state. + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + transitionState(newState, error) { + const invalidTransition = () => { + throw new Error(`Invalid state transition from ${this._state} to ${newState}`); + }; + // Validate state transition + switch (this._state) { + case _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Started: + if (newState !== _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Stopped) { + invalidTransition(); + } + break; + case _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Stopped: + if (newState !== _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Started) { + invalidTransition(); + } + break; + default: + throw new Error("Unknown state."); + } + // Update state + this.logger.log(`Transitioned from ${this._state} to ${newState}`); + this._state = newState; + this._stateEventEmitter.emit(this._state); + } +} + + +/***/ }), +/* 160 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _media_stream_factory_default__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(161); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "defaultMediaStreamFactory", function() { return _media_stream_factory_default__WEBPACK_IMPORTED_MODULE_0__["defaultMediaStreamFactory"]; }); + +/* harmony import */ var _media_stream_factory__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(162); +/* empty/unused harmony star reexport *//* harmony import */ var _peer_connection_configuration_default__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(163); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "defaultPeerConnectionConfiguration", function() { return _peer_connection_configuration_default__WEBPACK_IMPORTED_MODULE_2__["defaultPeerConnectionConfiguration"]; }); + +/* harmony import */ var _peer_connection_delegate__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(164); +/* empty/unused harmony star reexport *//* harmony import */ var _session_description_handler_configuration__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(165); +/* empty/unused harmony star reexport *//* harmony import */ var _session_description_handler_factory_default__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(166); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "defaultSessionDescriptionHandlerFactory", function() { return _session_description_handler_factory_default__WEBPACK_IMPORTED_MODULE_5__["defaultSessionDescriptionHandlerFactory"]; }); + +/* harmony import */ var _session_description_handler_factory_options__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(168); +/* empty/unused harmony star reexport *//* harmony import */ var _session_description_handler_factory__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(169); +/* empty/unused harmony star reexport *//* harmony import */ var _session_description_handler_options__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(170); +/* empty/unused harmony star reexport *//* harmony import */ var _session_description_handler__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(167); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionDescriptionHandler", function() { return _session_description_handler__WEBPACK_IMPORTED_MODULE_9__["SessionDescriptionHandler"]; }); + +/** + * A SessionDescriptionHandler for web browsers. + * @packageDocumentation + */ + + + + + + + + + + + + +/***/ }), +/* 161 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaultMediaStreamFactory", function() { return defaultMediaStreamFactory; }); +/** + * Function which returns a MediaStreamFactory. + * @public + */ +function defaultMediaStreamFactory() { + return (constraints) => { + // if no audio or video, return a media stream without tracks + if (!constraints.audio && !constraints.video) { + return Promise.resolve(new MediaStream()); + } + // getUserMedia() is a powerful feature which can only be used in secure contexts; in insecure contexts, + // navigator.mediaDevices is undefined, preventing access to getUserMedia(). A secure context is, in short, + // a page loaded using HTTPS or the file:/// URL scheme, or a page loaded from localhost. + // https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia#Privacy_and_security + if (navigator.mediaDevices === undefined) { + return Promise.reject(new Error("Media devices not available in insecure contexts.")); + } + return navigator.mediaDevices.getUserMedia.call(navigator.mediaDevices, constraints); + }; +} + + +/***/ }), +/* 162 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 163 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaultPeerConnectionConfiguration", function() { return defaultPeerConnectionConfiguration; }); +/** + * Function which returns an RTCConfiguration. + * @public + */ +function defaultPeerConnectionConfiguration() { + const configuration = { + bundlePolicy: "balanced", + certificates: undefined, + iceCandidatePoolSize: 0, + iceServers: [{ urls: "stun:stun.l.google.com:19302" }], + iceTransportPolicy: "all", + peerIdentity: undefined, + rtcpMuxPolicy: "require" + }; + return configuration; +} + + +/***/ }), +/* 164 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 165 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 166 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaultSessionDescriptionHandlerFactory", function() { return defaultSessionDescriptionHandlerFactory; }); +/* harmony import */ var _media_stream_factory_default__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(161); +/* harmony import */ var _peer_connection_configuration_default__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(163); +/* harmony import */ var _session_description_handler__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(167); + + + +/** + * Function which returns a SessionDescriptionHandlerFactory. + * @remarks + * See {@link defaultPeerConnectionConfiguration} for the default peer connection configuration. + * The ICE gathering timeout defaults to 5000ms. + * @param mediaStreamFactory - MediaStream factory. + * @public + */ +function defaultSessionDescriptionHandlerFactory(mediaStreamFactory) { + return (session, options) => { + // provide a default media stream factory if need be + if (mediaStreamFactory === undefined) { + mediaStreamFactory = Object(_media_stream_factory_default__WEBPACK_IMPORTED_MODULE_0__["defaultMediaStreamFactory"])(); + } + // make sure we allow `0` to be passed in so timeout can be disabled + const iceGatheringTimeout = (options === null || options === void 0 ? void 0 : options.iceGatheringTimeout) !== undefined ? options === null || options === void 0 ? void 0 : options.iceGatheringTimeout : 5000; + // merge passed factory options into default session description configuration + const sessionDescriptionHandlerConfiguration = { + iceGatheringTimeout, + peerConnectionConfiguration: Object.assign(Object.assign({}, Object(_peer_connection_configuration_default__WEBPACK_IMPORTED_MODULE_1__["defaultPeerConnectionConfiguration"])()), options === null || options === void 0 ? void 0 : options.peerConnectionConfiguration) + }; + const logger = session.userAgent.getLogger("sip.SessionDescriptionHandler"); + return new _session_description_handler__WEBPACK_IMPORTED_MODULE_2__["SessionDescriptionHandler"](logger, mediaStreamFactory, sessionDescriptionHandlerConfiguration); + }; +} + + +/***/ }), +/* 167 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SessionDescriptionHandler", function() { return SessionDescriptionHandler; }); +/** + * A base class implementing a WebRTC session description handler for sip.js. + * @remarks + * It is expected/intended to be extended by specific WebRTC based applications. + * @privateRemarks + * So do not put application specific implementation in here. + * @public + */ +class SessionDescriptionHandler { + /** + * Constructor + * @param logger - A logger + * @param mediaStreamFactory - A factory to provide a MediaStream + * @param options - Options passed from the SessionDescriptionHandleFactory + */ + constructor(logger, mediaStreamFactory, sessionDescriptionHandlerConfiguration) { + logger.debug("SessionDescriptionHandler.constructor"); + this.logger = logger; + this.mediaStreamFactory = mediaStreamFactory; + this.sessionDescriptionHandlerConfiguration = sessionDescriptionHandlerConfiguration; + this._localMediaStream = new MediaStream(); + this._remoteMediaStream = new MediaStream(); + this._peerConnection = new RTCPeerConnection(sessionDescriptionHandlerConfiguration === null || sessionDescriptionHandlerConfiguration === void 0 ? void 0 : sessionDescriptionHandlerConfiguration.peerConnectionConfiguration); + this.initPeerConnectionEventHandlers(); + } + /** + * The local media stream currently being sent. + * + * @remarks + * The local media stream initially has no tracks, so the presence of tracks + * should not be assumed. Furthermore, tracks may be added or removed if the + * local media changes - for example, on upgrade from audio only to a video session. + * At any given time there will be at most one audio track and one video track + * (it's possible that this restriction may not apply to sub-classes). + * Use `MediaStream.onaddtrack` or add a listener for the `addtrack` event + * to detect when a new track becomes available: + * https://developer.mozilla.org/en-US/docs/Web/API/MediaStream/onaddtrack + */ + get localMediaStream() { + return this._localMediaStream; + } + /** + * The remote media stream currently being received. + * + * @remarks + * The remote media stream initially has no tracks, so the presence of tracks + * should not be assumed. Furthermore, tracks may be added or removed if the + * remote media changes - for example, on upgrade from audio only to a video session. + * At any given time there will be at most one audio track and one video track + * (it's possible that this restriction may not apply to sub-classes). + * Use `MediaStream.onaddtrack` or add a listener for the `addtrack` event + * to detect when a new track becomes available: + * https://developer.mozilla.org/en-US/docs/Web/API/MediaStream/onaddtrack + */ + get remoteMediaStream() { + return this._remoteMediaStream; + } + /** + * The data channel. Undefined before it is created. + */ + get dataChannel() { + return this._dataChannel; + } + /** + * The peer connection. Undefined if peer connection has closed. + * + * @remarks + * While access to the underlying `RTCPeerConnection` is provided, note that + * using methods with modify it may break the operation of this class. + * In particular, this class depends on exclusive access to the + * event handler properties. If you need access to the peer connection + * events, either register for events using `addEventListener()` on + * the `RTCPeerConnection` or set the `peerConnectionDelegate` on + * this `SessionDescriptionHandler`. + */ + get peerConnection() { + return this._peerConnection; + } + /** + * A delegate which provides access to the peer connection event handlers. + * + * @remarks + * Setting the peer connection event handlers directly is not supported + * and may break this class. As this class depends on exclusive access + * to them, a delegate may be set which provides alternative access to + * the event handlers in a fashion which is supported. + */ + get peerConnectionDelegate() { + return this._peerConnectionDelegate; + } + set peerConnectionDelegate(delegate) { + this._peerConnectionDelegate = delegate; + } + // The addtrack event does not get fired when JavaScript code explicitly adds tracks to the stream (by calling addTrack()). + // https://developer.mozilla.org/en-US/docs/Web/API/MediaStream/onaddtrack + static dispatchAddTrackEvent(stream, track) { + stream.dispatchEvent(new MediaStreamTrackEvent("addtrack", { track })); + } + // The removetrack event does not get fired when JavaScript code explicitly removes tracks from the stream (by calling removeTrack()). + // https://developer.mozilla.org/en-US/docs/Web/API/MediaStream/onremovetrack + static dispatchRemoveTrackEvent(stream, track) { + stream.dispatchEvent(new MediaStreamTrackEvent("removetrack", { track })); + } + /** + * Stop tracks and close peer connection. + */ + close() { + this.logger.debug("SessionDescriptionHandler.close"); + if (this._peerConnection === undefined) { + return; + } + this._peerConnection.getReceivers().forEach((receiver) => { + receiver.track && receiver.track.stop(); + }); + this._peerConnection.getSenders().forEach((sender) => { + sender.track && sender.track.stop(); + }); + if (this._dataChannel) { + this._dataChannel.close(); + } + this._peerConnection.close(); + this._peerConnection = undefined; + } + /** + * Creates an offer or answer. + * @param options - Options bucket. + * @param modifiers - Modifiers. + */ + getDescription(options, modifiers) { + var _a, _b; + this.logger.debug("SessionDescriptionHandler.getDescription"); + if (this._peerConnection === undefined) { + return Promise.reject(new Error("Peer connection closed.")); + } + // Callback on data channel creation + this.onDataChannel = options === null || options === void 0 ? void 0 : options.onDataChannel; + // ICE will restart upon applying an offer created with the iceRestart option + const iceRestart = (_a = options === null || options === void 0 ? void 0 : options.offerOptions) === null || _a === void 0 ? void 0 : _a.iceRestart; + // ICE gathering timeout may be set on a per call basis, otherwise the configured default is used + const iceTimeout = (options === null || options === void 0 ? void 0 : options.iceGatheringTimeout) === undefined + ? (_b = this.sessionDescriptionHandlerConfiguration) === null || _b === void 0 ? void 0 : _b.iceGatheringTimeout : options === null || options === void 0 ? void 0 : options.iceGatheringTimeout; + return this.getLocalMediaStream(options) + .then(() => this.createDataChannel(options)) + .then(() => this.createLocalOfferOrAnswer(options)) + .then((sessionDescription) => this.applyModifiers(sessionDescription, modifiers)) + .then((sessionDescription) => this.setLocalSessionDescription(sessionDescription)) + .then(() => this.waitForIceGatheringComplete(iceRestart, iceTimeout)) + .then(() => this.getLocalSessionDescription()) + .then((sessionDescription) => { + return { + body: sessionDescription.sdp, + contentType: "application/sdp" + }; + }) + .catch((error) => { + this.logger.error("SessionDescriptionHandler.getDescription failed - " + error); + throw error; + }); + } + /** + * Returns true if the SessionDescriptionHandler can handle the Content-Type described by a SIP message. + * @param contentType - The content type that is in the SIP Message. + */ + hasDescription(contentType) { + this.logger.debug("SessionDescriptionHandler.hasDescription"); + return contentType === "application/sdp"; + } + /** + * 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. + */ + sendDtmf(tones, options) { + this.logger.debug("SessionDescriptionHandler.sendDtmf"); + if (this._peerConnection === undefined) { + this.logger.error("SessionDescriptionHandler.sendDtmf failed - peer connection closed"); + return false; + } + const senders = this._peerConnection.getSenders(); + if (senders.length === 0) { + this.logger.error("SessionDescriptionHandler.sendDtmf failed - no senders"); + return false; + } + const dtmfSender = senders[0].dtmf; + if (!dtmfSender) { + this.logger.error("SessionDescriptionHandler.sendDtmf failed - no DTMF sender"); + return false; + } + const duration = options === null || options === void 0 ? void 0 : options.duration; + const interToneGap = options === null || options === void 0 ? void 0 : options.interToneGap; + try { + dtmfSender.insertDTMF(tones, duration, interToneGap); + } + catch (e) { + this.logger.error(e); + return false; + } + this.logger.log("SessionDescriptionHandler.sendDtmf sent via RTP: " + tones.toString()); + return true; + } + /** + * Sets an offer or answer. + * @param sdp - The session description. + * @param options - Options bucket. + * @param modifiers - Modifiers. + */ + setDescription(sdp, options, modifiers) { + this.logger.debug("SessionDescriptionHandler.setDescription"); + if (this._peerConnection === undefined) { + return Promise.reject(new Error("Peer connection closed.")); + } + // Callback on data channel creation + this.onDataChannel = options === null || options === void 0 ? void 0 : options.onDataChannel; + // SDP type + const type = this._peerConnection.signalingState === "have-local-offer" ? "answer" : "offer"; + return this.getLocalMediaStream(options) + .then(() => this.applyModifiers({ sdp, type }, modifiers)) + .then((sessionDescription) => this.setRemoteSessionDescription(sessionDescription)) + .catch((error) => { + this.logger.error("SessionDescriptionHandler.setDescription failed - " + error); + throw error; + }); + } + /** + * Applies modifiers to SDP prior to setting the local or remote description. + * @param sdp - SDP to modify. + * @param modifiers - Modifiers to apply. + */ + applyModifiers(sdp, modifiers) { + this.logger.debug("SessionDescriptionHandler.applyModifiers"); + if (!modifiers || modifiers.length === 0) { + return Promise.resolve(sdp); + } + return modifiers + .reduce((cur, next) => cur.then(next), Promise.resolve(sdp)) + .then((modified) => { + this.logger.debug("SessionDescriptionHandler.applyModifiers - modified sdp"); + if (!modified.sdp || !modified.type) { + throw new Error("Invalid SDP."); + } + return { sdp: modified.sdp, type: modified.type }; + }); + } + /** + * Create a data channel. + * @remarks + * Only creates a data channel if SessionDescriptionHandlerOptions.dataChannel is true. + * Only creates a data channel if creating a local offer. + * Only if one does not already exist. + * @param options - Session description handler options. + */ + createDataChannel(options) { + if (this._peerConnection === undefined) { + return Promise.reject(new Error("Peer connection closed.")); + } + // only create a data channel if requested + if ((options === null || options === void 0 ? void 0 : options.dataChannel) !== true) { + return Promise.resolve(); + } + // do not create a data channel if we already have one + if (this._dataChannel) { + return Promise.resolve(); + } + switch (this._peerConnection.signalingState) { + case "stable": + // if we are stable, assume we are creating a local offer so create a data channel + this.logger.debug("SessionDescriptionHandler.createDataChannel - creating data channel"); + try { + this._dataChannel = this._peerConnection.createDataChannel((options === null || options === void 0 ? void 0 : options.dataChannelLabel) || "", options === null || options === void 0 ? void 0 : options.dataChannelOptions); + if (this.onDataChannel) { + this.onDataChannel(this._dataChannel); + } + return Promise.resolve(); + } + catch (error) { + return Promise.reject(error); + } + case "have-remote-offer": + return Promise.resolve(); + case "have-local-offer": + case "have-local-pranswer": + case "have-remote-pranswer": + case "closed": + default: + return Promise.reject(new Error("Invalid signaling state " + this._peerConnection.signalingState)); + } + } + /** + * Depending on current signaling state, create a local offer or answer. + * @param options - Session description handler options. + */ + createLocalOfferOrAnswer(options) { + if (this._peerConnection === undefined) { + return Promise.reject(new Error("Peer connection closed.")); + } + switch (this._peerConnection.signalingState) { + case "stable": + // if we are stable, assume we are creating a local offer + this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP offer"); + return this._peerConnection.createOffer(options === null || options === void 0 ? void 0 : options.offerOptions); + case "have-remote-offer": + // if we have a remote offer, assume we are creating a local answer + this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP answer"); + return this._peerConnection.createAnswer(options === null || options === void 0 ? void 0 : options.answerOptions); + case "have-local-offer": + case "have-local-pranswer": + case "have-remote-pranswer": + case "closed": + default: + return Promise.reject(new Error("Invalid signaling state " + this._peerConnection.signalingState)); + } + } + /** + * Get a media stream from the media stream factory and set the local media stream. + * @param options - Session description handler options. + */ + getLocalMediaStream(options) { + this.logger.debug("SessionDescriptionHandler.getLocalMediaStream"); + if (this._peerConnection === undefined) { + return Promise.reject(new Error("Peer connection closed.")); + } + let constraints = Object.assign({}, options === null || options === void 0 ? void 0 : options.constraints); + // if we already have a local media stream... + if (this.localMediaStreamConstraints) { + // ignore constraint "downgrades" + constraints.audio = constraints.audio || this.localMediaStreamConstraints.audio; + constraints.video = constraints.video || this.localMediaStreamConstraints.video; + // if constraints have not changed, do not get a new media stream + if (JSON.stringify(this.localMediaStreamConstraints.audio) === JSON.stringify(constraints.audio) && + JSON.stringify(this.localMediaStreamConstraints.video) === JSON.stringify(constraints.video)) { + return Promise.resolve(); + } + } + else { + // if no constraints have been specified, default to audio for initial media stream + if (constraints.audio === undefined && constraints.video === undefined) { + constraints = { audio: true }; + } + } + this.localMediaStreamConstraints = constraints; + return this.mediaStreamFactory(constraints, this).then((mediaStream) => this.setLocalMediaStream(mediaStream)); + } + /** + * Sets the peer connection's sender tracks and local media stream tracks. + * + * @remarks + * Only the first audio and video tracks of the provided MediaStream are utilized. + * Adds tracks if audio and/or video tracks are not already present, otherwise replaces tracks. + * + * @param stream - Media stream containing tracks to be utilized. + */ + setLocalMediaStream(stream) { + this.logger.debug("SessionDescriptionHandler.setLocalMediaStream"); + if (!this._peerConnection) { + throw new Error("Peer connection undefined."); + } + const pc = this._peerConnection; + const localStream = this._localMediaStream; + const trackUpdates = []; + const updateTrack = (newTrack) => { + const kind = newTrack.kind; + if (kind !== "audio" && kind !== "video") { + throw new Error(`Unknown new track kind ${kind}.`); + } + const sender = pc.getSenders().find((sender) => sender.track && sender.track.kind === kind); + if (sender) { + trackUpdates.push(new Promise((resolve) => { + this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - replacing sender ${kind} track`); + resolve(); + }).then(() => sender + .replaceTrack(newTrack) + .then(() => { + const oldTrack = localStream.getTracks().find((localTrack) => localTrack.kind === kind); + if (oldTrack) { + oldTrack.stop(); + localStream.removeTrack(oldTrack); + SessionDescriptionHandler.dispatchRemoveTrackEvent(localStream, oldTrack); + } + localStream.addTrack(newTrack); + SessionDescriptionHandler.dispatchAddTrackEvent(localStream, newTrack); + }) + .catch((error) => { + this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to replace sender ${kind} track`); + throw error; + }))); + } + else { + trackUpdates.push(new Promise((resolve) => { + this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - adding sender ${kind} track`); + resolve(); + }).then(() => { + // Review: could make streamless tracks a configurable option? + // https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/addTrack#Usage_notes + try { + pc.addTrack(newTrack, localStream); + } + catch (error) { + this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to add sender ${kind} track`); + throw error; + } + localStream.addTrack(newTrack); + SessionDescriptionHandler.dispatchAddTrackEvent(localStream, newTrack); + })); + } + }; + // update peer connection audio tracks + const audioTracks = stream.getAudioTracks(); + if (audioTracks.length) { + updateTrack(audioTracks[0]); + } + // update peer connection video tracks + const videoTracks = stream.getVideoTracks(); + if (videoTracks.length) { + updateTrack(videoTracks[0]); + } + return trackUpdates.reduce((p, x) => p.then(() => x), Promise.resolve()); + } + /** + * Gets the peer connection's local session description. + */ + getLocalSessionDescription() { + this.logger.debug("SessionDescriptionHandler.getLocalSessionDescription"); + if (this._peerConnection === undefined) { + return Promise.reject(new Error("Peer connection closed.")); + } + const sdp = this._peerConnection.localDescription; + if (!sdp) { + return Promise.reject(new Error("Failed to get local session description")); + } + return Promise.resolve(sdp); + } + /** + * Sets the peer connection's local session description. + * @param sessionDescription - sessionDescription The session description. + */ + setLocalSessionDescription(sessionDescription) { + this.logger.debug("SessionDescriptionHandler.setLocalSessionDescription"); + if (this._peerConnection === undefined) { + return Promise.reject(new Error("Peer connection closed.")); + } + return this._peerConnection.setLocalDescription(sessionDescription); + } + /** + * Sets the peer connection's remote session description. + * @param sessionDescription - The session description. + */ + setRemoteSessionDescription(sessionDescription) { + this.logger.debug("SessionDescriptionHandler.setRemoteSessionDescription"); + if (this._peerConnection === undefined) { + return Promise.reject(new Error("Peer connection closed.")); + } + const sdp = sessionDescription.sdp; + let type; + switch (this._peerConnection.signalingState) { + case "stable": + // if we are stable assume this is a remote offer + type = "offer"; + break; + case "have-local-offer": + // if we made an offer, assume this is a remote answer + type = "answer"; + break; + case "have-local-pranswer": + case "have-remote-offer": + case "have-remote-pranswer": + case "closed": + default: + return Promise.reject(new Error("Invalid signaling state " + this._peerConnection.signalingState)); + } + if (!sdp) { + this.logger.error("SessionDescriptionHandler.setRemoteSessionDescription failed - cannot set null sdp"); + return Promise.reject(new Error("SDP is undefined")); + } + return this._peerConnection.setRemoteDescription({ sdp, type }); + } + /** + * Sets a remote media stream track. + * + * @remarks + * Adds tracks if audio and/or video tracks are not already present, otherwise replaces tracks. + * + * @param track - Media stream track to be utilized. + */ + setRemoteTrack(track) { + this.logger.debug("SessionDescriptionHandler.setRemoteTrack"); + const remoteStream = this._remoteMediaStream; + if (remoteStream.getTrackById(track.id)) { + this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - have remote ${track.kind} track`); + } + else if (track.kind === "audio") { + this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${track.kind} track`); + remoteStream.getAudioTracks().forEach((track) => { + track.stop(); + remoteStream.removeTrack(track); + SessionDescriptionHandler.dispatchRemoveTrackEvent(remoteStream, track); + }); + remoteStream.addTrack(track); + SessionDescriptionHandler.dispatchAddTrackEvent(remoteStream, track); + } + else if (track.kind === "video") { + this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${track.kind} track`); + remoteStream.getVideoTracks().forEach((track) => { + track.stop(); + remoteStream.removeTrack(track); + SessionDescriptionHandler.dispatchRemoveTrackEvent(remoteStream, track); + }); + remoteStream.addTrack(track); + SessionDescriptionHandler.dispatchAddTrackEvent(remoteStream, track); + } + } + /** + * Called when ICE gathering completes and resolves any waiting promise. + */ + iceGatheringComplete() { + this.logger.debug("SessionDescriptionHandler.iceGatheringComplete"); + // clear timer if need be + if (this.iceGatheringCompleteTimeoutId !== undefined) { + this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - clearing timeout"); + clearTimeout(this.iceGatheringCompleteTimeoutId); + this.iceGatheringCompleteTimeoutId = undefined; + } + // resolve and cleanup promise if need be + if (this.iceGatheringCompletePromise !== undefined) { + this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - resolving promise"); + this.iceGatheringCompleteResolve && this.iceGatheringCompleteResolve(); + this.iceGatheringCompletePromise = undefined; + this.iceGatheringCompleteResolve = undefined; + this.iceGatheringCompleteReject = undefined; + } + } + /** + * Wait for ICE gathering to complete. + * @param restart - If true, waits if current state is "complete" (waits for transition to "complete"). + * @param timeout - Milliseconds after which waiting times out. No timeout if 0. + */ + waitForIceGatheringComplete(restart = false, timeout = 0) { + this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete"); + if (this._peerConnection === undefined) { + return Promise.reject("Peer connection closed."); + } + // guard already complete + if (!restart && this._peerConnection.iceGatheringState === "complete") { + this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - already complete"); + return Promise.resolve(); + } + // only one may be waiting, reject any prior + if (this.iceGatheringCompletePromise !== undefined) { + this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - rejecting prior waiting promise"); + this.iceGatheringCompleteReject && this.iceGatheringCompleteReject(new Error("Promise superseded.")); + this.iceGatheringCompletePromise = undefined; + this.iceGatheringCompleteResolve = undefined; + this.iceGatheringCompleteReject = undefined; + } + this.iceGatheringCompletePromise = new Promise((resolve, reject) => { + this.iceGatheringCompleteResolve = resolve; + this.iceGatheringCompleteReject = reject; + if (timeout > 0) { + this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout in " + timeout); + this.iceGatheringCompleteTimeoutId = setTimeout(() => { + this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout"); + this.iceGatheringComplete(); + }, timeout); + } + }); + return this.iceGatheringCompletePromise; + } + /** + * Initializes the peer connection event handlers + */ + initPeerConnectionEventHandlers() { + this.logger.debug("SessionDescriptionHandler.initPeerConnectionEventHandlers"); + if (!this._peerConnection) + throw new Error("Peer connection undefined."); + const peerConnection = this._peerConnection; + peerConnection.onconnectionstatechange = (event) => { + var _a; + const newState = peerConnection.connectionState; + this.logger.debug(`SessionDescriptionHandler.onconnectionstatechange ${newState}`); + if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onconnectionstatechange) { + this._peerConnectionDelegate.onconnectionstatechange(event); + } + }; + peerConnection.ondatachannel = (event) => { + var _a; + this.logger.debug(`SessionDescriptionHandler.ondatachannel`); + this._dataChannel = event.channel; + if (this.onDataChannel) { + this.onDataChannel(this._dataChannel); + } + if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.ondatachannel) { + this._peerConnectionDelegate.ondatachannel(event); + } + }; + peerConnection.onicecandidate = (event) => { + var _a; + this.logger.debug(`SessionDescriptionHandler.onicecandidate`); + if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onicecandidate) { + this._peerConnectionDelegate.onicecandidate(event); + } + }; + peerConnection.onicecandidateerror = (event) => { + var _a; + this.logger.debug(`SessionDescriptionHandler.onicecandidateerror`); + if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onicecandidateerror) { + this._peerConnectionDelegate.onicecandidateerror(event); + } + }; + peerConnection.oniceconnectionstatechange = (event) => { + var _a; + const newState = peerConnection.iceConnectionState; + this.logger.debug(`SessionDescriptionHandler.oniceconnectionstatechange ${newState}`); + if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.oniceconnectionstatechange) { + this._peerConnectionDelegate.oniceconnectionstatechange(event); + } + }; + peerConnection.onicegatheringstatechange = (event) => { + var _a; + const newState = peerConnection.iceGatheringState; + this.logger.debug(`SessionDescriptionHandler.onicegatheringstatechange ${newState}`); + if (newState === "complete") { + this.iceGatheringComplete(); // complete waiting for ICE gathering to complete + } + if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onicegatheringstatechange) { + this._peerConnectionDelegate.onicegatheringstatechange(event); + } + }; + peerConnection.onnegotiationneeded = (event) => { + var _a; + this.logger.debug(`SessionDescriptionHandler.onnegotiationneeded`); + if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onnegotiationneeded) { + this._peerConnectionDelegate.onnegotiationneeded(event); + } + }; + peerConnection.onsignalingstatechange = (event) => { + var _a; + const newState = peerConnection.signalingState; + this.logger.debug(`SessionDescriptionHandler.onsignalingstatechange ${newState}`); + if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onsignalingstatechange) { + this._peerConnectionDelegate.onsignalingstatechange(event); + } + }; + peerConnection.onstatsended = (event) => { + var _a; + this.logger.debug(`SessionDescriptionHandler.onstatsended`); + if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onstatsended) { + this._peerConnectionDelegate.onstatsended(event); + } + }; + peerConnection.ontrack = (event) => { + var _a; + const kind = event.track.kind; + const enabled = event.track.enabled ? "enabled" : "disabled"; + this.logger.debug(`SessionDescriptionHandler.ontrack ${kind} ${enabled}`); + this.setRemoteTrack(event.track); + if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.ontrack) { + this._peerConnectionDelegate.ontrack(event); + } + }; + } +} + + +/***/ }), +/* 168 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 169 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 170 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 171 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _transport__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(172); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Transport", function() { return _transport__WEBPACK_IMPORTED_MODULE_0__["Transport"]; }); + +/* harmony import */ var _transport_options__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(173); +/* empty/unused harmony star reexport *//** + * A Transport implementation for web browsers. + * @packageDocumentation + */ + + + + +/***/ }), +/* 172 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Transport", function() { return Transport; }); +/* harmony import */ var _api_emitter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(108); +/* harmony import */ var _api_exceptions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3); +/* harmony import */ var _api_transport_state__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(156); +/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(5); + + + + +/** + * Transport for SIP over secure WebSocket (WSS). + * @public + */ +class Transport { + constructor(logger, options) { + this._state = _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected; + this.transitioningState = false; + // state emitter + this._stateEventEmitter = new _api_emitter__WEBPACK_IMPORTED_MODULE_0__["EmitterImpl"](); + // logger + this.logger = logger; + // guard deprecated options (remove this in version 16.x) + if (options) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const optionsDeprecated = options; + const wsServersDeprecated = optionsDeprecated === null || optionsDeprecated === void 0 ? void 0 : optionsDeprecated.wsServers; + const maxReconnectionAttemptsDeprecated = optionsDeprecated === null || optionsDeprecated === void 0 ? void 0 : optionsDeprecated.maxReconnectionAttempts; + if (wsServersDeprecated !== undefined) { + const deprecatedMessage = `The transport option "wsServers" as has apparently been specified and has been deprecated. ` + + "It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly."; + this.logger.warn(deprecatedMessage); + } + if (maxReconnectionAttemptsDeprecated !== undefined) { + const deprecatedMessage = `The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. ` + + "It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly."; + this.logger.warn(deprecatedMessage); + } + // hack + if (wsServersDeprecated && !options.server) { + if (typeof wsServersDeprecated === "string") { + options.server = wsServersDeprecated; + } + if (wsServersDeprecated instanceof Array) { + options.server = wsServersDeprecated[0]; + } + } + } + // initialize configuration + this.configuration = Object.assign(Object.assign({}, Transport.defaultOptions), options); + // validate server URL + const url = this.configuration.server; + const parsed = _core__WEBPACK_IMPORTED_MODULE_3__["Grammar"].parse(url, "absoluteURI"); + if (parsed === -1) { + this.logger.error(`Invalid WebSocket Server URL "${url}"`); + throw new Error("Invalid WebSocket Server URL"); + } + if (!["wss", "ws", "udp"].includes(parsed.scheme)) { + this.logger.error(`Invalid scheme in WebSocket Server URL "${url}"`); + throw new Error("Invalid scheme in WebSocket Server URL"); + } + this._protocol = parsed.scheme.toUpperCase(); + } + dispose() { + return this.disconnect(); + } + /** + * The protocol. + * + * @remarks + * Formatted as defined for the Via header sent-protocol transport. + * https://tools.ietf.org/html/rfc3261#section-20.42 + */ + get protocol() { + return this._protocol; + } + /** + * The URL of the WebSocket Server. + */ + get server() { + return this.configuration.server; + } + /** + * Transport state. + */ + get state() { + return this._state; + } + /** + * Transport state change emitter. + */ + get stateChange() { + return this._stateEventEmitter; + } + /** + * The WebSocket. + */ + get ws() { + return this._ws; + } + /** + * Connect to network. + * Resolves once connected. Otherwise rejects with an Error. + */ + connect() { + return this._connect(); + } + /** + * Disconnect from network. + * Resolves once disconnected. Otherwise rejects with an Error. + */ + disconnect() { + return this._disconnect(); + } + /** + * Returns true if the `state` equals "Connected". + * @remarks + * This is equivalent to `state === TransportState.Connected`. + */ + isConnected() { + return this.state === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected; + } + /** + * Sends a message. + * Resolves once message is sent. Otherwise rejects with an Error. + * @param message - Message to send. + */ + send(message) { + // Error handling is independent of whether the message was a request or + // response. + // + // If the transport user asks for a message to be sent over an + // unreliable transport, and the result is an ICMP error, the behavior + // depends on the type of ICMP error. Host, network, port or protocol + // unreachable errors, or parameter problem errors SHOULD cause the + // transport layer to inform the transport user of a failure in sending. + // Source quench and TTL exceeded ICMP errors SHOULD be ignored. + // + // If the transport user asks for a request to be sent over a reliable + // transport, and the result is a connection failure, the transport + // layer SHOULD inform the transport user of a failure in sending. + // https://tools.ietf.org/html/rfc3261#section-18.4 + return this._send(message); + } + _connect() { + this.logger.log(`Connecting ${this.server}`); + switch (this.state) { + case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting: + // If `state` is "Connecting", `state` MUST NOT transition before returning. + if (this.transitioningState) { + return Promise.reject(this.transitionLoopDetectedError(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting)); + } + if (!this.connectPromise) { + throw new Error("Connect promise must be defined."); + } + return this.connectPromise; // Already connecting + case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected: + // If `state` is "Connected", `state` MUST NOT transition before returning. + if (this.transitioningState) { + return Promise.reject(this.transitionLoopDetectedError(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting)); + } + if (this.connectPromise) { + throw new Error("Connect promise must not be defined."); + } + return Promise.resolve(); // Already connected + case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting: + // If `state` is "Disconnecting", `state` MUST transition to "Connecting" before returning + if (this.connectPromise) { + throw new Error("Connect promise must not be defined."); + } + try { + this.transitionState(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting); + } + catch (e) { + if (e instanceof _api_exceptions__WEBPACK_IMPORTED_MODULE_1__["StateTransitionError"]) { + return Promise.reject(e); // Loop detected + } + throw e; + } + break; + case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected: + // If `state` is "Disconnected" `state` MUST transition to "Connecting" before returning + if (this.connectPromise) { + throw new Error("Connect promise must not be defined."); + } + try { + this.transitionState(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting); + } + catch (e) { + if (e instanceof _api_exceptions__WEBPACK_IMPORTED_MODULE_1__["StateTransitionError"]) { + return Promise.reject(e); // Loop detected + } + throw e; + } + break; + default: + throw new Error("Unknown state"); + } + let ws; + try { + // WebSocket() + // https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/WebSocket + ws = new WebSocket(this.server, "sip"); + ws.binaryType = "arraybuffer"; // set data type of received binary messages + ws.addEventListener("close", (ev) => this.onWebSocketClose(ev, ws)); + ws.addEventListener("error", (ev) => this.onWebSocketError(ev, ws)); + ws.addEventListener("open", (ev) => this.onWebSocketOpen(ev, ws)); + ws.addEventListener("message", (ev) => this.onWebSocketMessage(ev, ws)); + this._ws = ws; + } + catch (error) { + this._ws = undefined; + this.logger.error("WebSocket construction failed."); + this.logger.error(error); + return new Promise((resolve, reject) => { + this.connectResolve = resolve; + this.connectReject = reject; + // The `state` MUST transition to "Disconnecting" or "Disconnected" before rejecting + this.transitionState(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected, error); + }); + } + this.connectPromise = new Promise((resolve, reject) => { + this.connectResolve = resolve; + this.connectReject = reject; + this.connectTimeout = setTimeout(() => { + this.logger.warn("Connect timed out. " + + "Exceeded time set in configuration.connectionTimeout: " + + this.configuration.connectionTimeout + + "s."); + ws.close(1000); // careful here to use a local reference instead of this._ws + }, this.configuration.connectionTimeout * 1000); + }); + return this.connectPromise; + } + _disconnect() { + this.logger.log(`Disconnecting ${this.server}`); + switch (this.state) { + case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting: + // If `state` is "Connecting", `state` MUST transition to "Disconnecting" before returning. + if (this.disconnectPromise) { + throw new Error("Disconnect promise must not be defined."); + } + try { + this.transitionState(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting); + } + catch (e) { + if (e instanceof _api_exceptions__WEBPACK_IMPORTED_MODULE_1__["StateTransitionError"]) { + return Promise.reject(e); // Loop detected + } + throw e; + } + break; + case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected: + // If `state` is "Connected", `state` MUST transition to "Disconnecting" before returning. + if (this.disconnectPromise) { + throw new Error("Disconnect promise must not be defined."); + } + try { + this.transitionState(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting); + } + catch (e) { + if (e instanceof _api_exceptions__WEBPACK_IMPORTED_MODULE_1__["StateTransitionError"]) { + return Promise.reject(e); // Loop detected + } + throw e; + } + break; + case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting: + // If `state` is "Disconnecting", `state` MUST NOT transition before returning. + if (this.transitioningState) { + return Promise.reject(this.transitionLoopDetectedError(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting)); + } + if (!this.disconnectPromise) { + throw new Error("Disconnect promise must be defined."); + } + return this.disconnectPromise; // Already disconnecting + case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected: + // If `state` is "Disconnected", `state` MUST NOT transition before returning. + if (this.transitioningState) { + return Promise.reject(this.transitionLoopDetectedError(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting)); + } + if (this.disconnectPromise) { + throw new Error("Disconnect promise must not be defined."); + } + return Promise.resolve(); // Already disconnected + default: + throw new Error("Unknown state"); + } + if (!this._ws) { + throw new Error("WebSocket must be defined."); + } + const ws = this._ws; + this.disconnectPromise = new Promise((resolve, reject) => { + this.disconnectResolve = resolve; + this.disconnectReject = reject; + try { + // WebSocket.close() + // https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close + ws.close(1000); // careful here to use a local reference instead of this._ws + } + catch (error) { + // Treating this as a coding error as it apparently can only happen + // if you pass close() invalid parameters (so it should never happen) + this.logger.error("WebSocket close failed."); + this.logger.error(error); + throw error; + } + }); + return this.disconnectPromise; + } + _send(message) { + if (this.configuration.traceSip === true) { + this.logger.log("Sending WebSocket message:\n\n" + message + "\n"); + } + if (this._state !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected) { + return Promise.reject(new Error("Not connected.")); + } + if (!this._ws) { + throw new Error("WebSocket undefined."); + } + try { + // WebSocket.send() + // https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send + this._ws.send(message); + } + catch (error) { + if (error instanceof Error) { + return Promise.reject(error); + } + return Promise.reject(new Error("WebSocket send failed.")); + } + return Promise.resolve(); + } + /** + * WebSocket "onclose" event handler. + * @param ev - Event. + */ + onWebSocketClose(ev, ws) { + if (ws !== this._ws) { + return; + } + const message = `WebSocket closed ${this.server} (code: ${ev.code})`; + const error = !this.disconnectPromise ? new Error(message) : undefined; + if (error) { + this.logger.warn("WebSocket closed unexpectedly"); + } + this.logger.log(message); + // We are about to transition to disconnected, so clear our web socket + this._ws = undefined; + // The `state` MUST transition to "Disconnected" before resolving (assuming `state` is not already "Disconnected"). + this.transitionState(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected, error); + } + /** + * WebSocket "onerror" event handler. + * @param ev - Event. + */ + onWebSocketError(ev, ws) { + if (ws !== this._ws) { + return; + } + this.logger.error("WebSocket error occurred."); + } + /** + * WebSocket "onmessage" event handler. + * @param ev - Event. + */ + onWebSocketMessage(ev, ws) { + if (ws !== this._ws) { + return; + } + const data = ev.data; + let 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; + } + if (!data) { + this.logger.warn("Received empty message, discarding..."); + return; + } + if (typeof data !== "string") { + // WebSocket binary message. + try { + finishedData = new TextDecoder().decode(new Uint8Array(data)); + // TextDecoder (above) is not supported by old browsers, but it correctly decodes UTF-8. + // The line below is an ISO 8859-1 (Latin 1) decoder, so just UTF-8 code points that are 1 byte. + // It's old code and works in old browsers (IE), so leaving it here in a comment in case someone needs it. + // finishedData = String.fromCharCode.apply(null, (new Uint8Array(data) as unknown as Array)); + } + catch (err) { + this.logger.error(err); + this.logger.error("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" + finishedData + "\n"); + } + } + else { + // WebSocket text message. + finishedData = data; + if (this.configuration.traceSip === true) { + this.logger.log("Received WebSocket text message:\n\n" + finishedData + "\n"); + } + } + if (this.state !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected) { + this.logger.warn("Received message while not connected, discarding..."); + return; + } + if (this.onMessage) { + try { + this.onMessage(finishedData); + } + catch (e) { + this.logger.error(e); + this.logger.error("Exception thrown by onMessage callback"); + throw e; // rethrow unhandled exception + } + } + } + /** + * WebSocket "onopen" event handler. + * @param ev - Event. + */ + onWebSocketOpen(ev, ws) { + if (ws !== this._ws) { + return; + } + if (this._state === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting) { + this.logger.log(`WebSocket opened ${this.server}`); + this.transitionState(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected); + } + } + /** + * Helper function to generate an Error. + * @param state - State transitioning to. + */ + transitionLoopDetectedError(state) { + let message = `A state transition loop has been detected.`; + message += ` An attempt to transition from ${this._state} to ${state} before the prior transition completed.`; + message += ` Perhaps you are synchronously calling connect() or disconnect() from a callback or state change handler?`; + this.logger.error(message); + return new _api_exceptions__WEBPACK_IMPORTED_MODULE_1__["StateTransitionError"]("Loop detected."); + } + /** + * Transition transport state. + * @internal + */ + transitionState(newState, error) { + const invalidTransition = () => { + throw new Error(`Invalid state transition from ${this._state} to ${newState}`); + }; + if (this.transitioningState) { + throw this.transitionLoopDetectedError(newState); + } + this.transitioningState = true; + // Validate state transition + switch (this._state) { + case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting: + if (newState !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected && + newState !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting && + newState !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected) { + invalidTransition(); + } + break; + case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected: + if (newState !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting && newState !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected) { + invalidTransition(); + } + break; + case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting: + if (newState !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting && newState !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected) { + invalidTransition(); + } + break; + case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected: + if (newState !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting) { + invalidTransition(); + } + break; + default: + throw new Error("Unknown state."); + } + // Update state + const oldState = this._state; + this._state = newState; + // Local copies of connect promises (guarding against callbacks changing them indirectly) + // const connectPromise = this.connectPromise; + const connectResolve = this.connectResolve; + const connectReject = this.connectReject; + // Reset connect promises if no longer connecting + if (oldState === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting) { + this.connectPromise = undefined; + this.connectResolve = undefined; + this.connectReject = undefined; + } + // Local copies of disconnect promises (guarding against callbacks changing them indirectly) + // const disconnectPromise = this.disconnectPromise; + const disconnectResolve = this.disconnectResolve; + const disconnectReject = this.disconnectReject; + // Reset disconnect promises if no longer disconnecting + if (oldState === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting) { + this.disconnectPromise = undefined; + this.disconnectResolve = undefined; + this.disconnectReject = undefined; + } + // Clear any outstanding connect timeout + if (this.connectTimeout) { + clearTimeout(this.connectTimeout); + this.connectTimeout = undefined; + } + this.logger.log(`Transitioned from ${oldState} to ${this._state}`); + this._stateEventEmitter.emit(this._state); + // Transition to Connected + if (newState === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected) { + this.startSendingKeepAlives(); + if (this.onConnect) { + try { + this.onConnect(); + } + catch (e) { + this.logger.error(e); + this.logger.error("Exception thrown by onConnect callback"); + throw e; // rethrow unhandled exception + } + } + } + // Transition from Connected + if (oldState === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected) { + this.stopSendingKeepAlives(); + if (this.onDisconnect) { + try { + if (error) { + this.onDisconnect(error); + } + else { + this.onDisconnect(); + } + } + catch (e) { + this.logger.error(e); + this.logger.error("Exception thrown by onDisconnect callback"); + throw e; // rethrow unhandled exception + } + } + } + // Complete connect promise + if (oldState === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting) { + if (!connectResolve) { + throw new Error("Connect resolve undefined."); + } + if (!connectReject) { + throw new Error("Connect reject undefined."); + } + newState === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected ? connectResolve() : connectReject(error || new Error("Connect aborted.")); + } + // Complete disconnect promise + if (oldState === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting) { + if (!disconnectResolve) { + throw new Error("Disconnect resolve undefined."); + } + if (!disconnectReject) { + throw new Error("Disconnect reject undefined."); + } + newState === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected + ? disconnectResolve() + : disconnectReject(error || new Error("Disconnect aborted.")); + } + this.transitioningState = false; + } + // TODO: Review "KeepAlive Stuff". + // It is not clear if it works and there are no tests for it. + // It was blindly lifted the keep alive code unchanged from earlier transport code. + // + // From the RFC... + // + // SIP WebSocket Clients and Servers may keep their WebSocket + // connections open by sending periodic WebSocket "Ping" frames as + // described in [RFC6455], Section 5.5.2. + // ... + // The indication and use of the CRLF NAT keep-alive mechanism defined + // for SIP connection-oriented transports in [RFC5626], Section 3.5.1 or + // [RFC6223] are, of course, usable over the transport defined in this + // specification. + // https://tools.ietf.org/html/rfc7118#section-6 + // + // and... + // + // The Ping frame contains an opcode of 0x9. + // https://tools.ietf.org/html/rfc6455#section-5.5.2 + // + // ============================== + // KeepAlive Stuff + // ============================== + clearKeepAliveTimeout() { + if (this.keepAliveDebounceTimeout) { + clearTimeout(this.keepAliveDebounceTimeout); + } + this.keepAliveDebounceTimeout = undefined; + } + /** + * Send a keep-alive (a double-CRLF sequence). + */ + sendKeepAlive() { + if (this.keepAliveDebounceTimeout) { + // We already have an outstanding keep alive, do not send another. + return Promise.resolve(); + } + this.keepAliveDebounceTimeout = setTimeout(() => { + this.clearKeepAliveTimeout(); + }, this.configuration.keepAliveDebounce * 1000); + return this.send("\r\n\r\n"); + } + /** + * Start sending keep-alives. + */ + startSendingKeepAlives() { + // Compute an amount of time in seconds to wait before sending another keep-alive. + const computeKeepAliveTimeout = (upperBound) => { + const lowerBound = upperBound * 0.8; + return 1000 * (Math.random() * (upperBound - lowerBound) + lowerBound); + }; + if (this.configuration.keepAliveInterval && !this.keepAliveInterval) { + this.keepAliveInterval = setInterval(() => { + this.sendKeepAlive(); + this.startSendingKeepAlives(); + }, computeKeepAliveTimeout(this.configuration.keepAliveInterval)); + } + } + /** + * Stop sending keep-alives. + */ + stopSendingKeepAlives() { + if (this.keepAliveInterval) { + clearInterval(this.keepAliveInterval); + } + if (this.keepAliveDebounceTimeout) { + clearTimeout(this.keepAliveDebounceTimeout); + } + this.keepAliveInterval = undefined; + this.keepAliveDebounceTimeout = undefined; + } +} +Transport.defaultOptions = { + server: "", + connectionTimeout: 5, + keepAliveInterval: 0, + keepAliveDebounce: 10, + traceSip: true +}; + + +/***/ }), +/* 173 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 174 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _modifiers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(175); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripTcpCandidates", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripTcpCandidates"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripTelephoneEvent", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripTelephoneEvent"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "cleanJitsiSdpImageattr", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["cleanJitsiSdpImageattr"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripG722", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripG722"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripRtpPayload", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripRtpPayload"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripVideo", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripVideo"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "addMidLines", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["addMidLines"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "holdModifier", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["holdModifier"]; }); + +/* harmony import */ var _session_description_handler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(160); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "defaultMediaStreamFactory", function() { return _session_description_handler__WEBPACK_IMPORTED_MODULE_1__["defaultMediaStreamFactory"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "defaultPeerConnectionConfiguration", function() { return _session_description_handler__WEBPACK_IMPORTED_MODULE_1__["defaultPeerConnectionConfiguration"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "defaultSessionDescriptionHandlerFactory", function() { return _session_description_handler__WEBPACK_IMPORTED_MODULE_1__["defaultSessionDescriptionHandlerFactory"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionDescriptionHandler", function() { return _session_description_handler__WEBPACK_IMPORTED_MODULE_1__["SessionDescriptionHandler"]; }); + +/* harmony import */ var _simple_user__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(177); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SimpleUser", function() { return _simple_user__WEBPACK_IMPORTED_MODULE_2__["SimpleUser"]; }); + +/* harmony import */ var _transport__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(171); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Transport", function() { return _transport__WEBPACK_IMPORTED_MODULE_3__["Transport"]; }); + + + + + + + +/***/ }), +/* 175 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _modifiers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(176); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripTcpCandidates", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripTcpCandidates"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripTelephoneEvent", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripTelephoneEvent"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "cleanJitsiSdpImageattr", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["cleanJitsiSdpImageattr"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripG722", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripG722"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripRtpPayload", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripRtpPayload"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripVideo", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripVideo"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "addMidLines", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["addMidLines"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "holdModifier", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["holdModifier"]; }); + +/** + * SessionDescriptionHandlerModifer functions for web browsers. + * @packageDocumentation + */ + + + +/***/ }), +/* 176 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stripTcpCandidates", function() { return stripTcpCandidates; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stripTelephoneEvent", function() { return stripTelephoneEvent; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "cleanJitsiSdpImageattr", function() { return cleanJitsiSdpImageattr; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stripG722", function() { return stripG722; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stripRtpPayload", function() { return stripRtpPayload; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stripVideo", function() { return stripVideo; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addMidLines", function() { return addMidLines; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "holdModifier", function() { return holdModifier; }); +const stripPayload = (sdp, payload) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const mediaDescs = []; + const lines = sdp.split(/\r\n/); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let currentMediaDesc; + for (let i = 0; i < lines.length;) { + const line = lines[i]; + if (/^m=(?:audio|video)/.test(line)) { + currentMediaDesc = { + index: i, + stripped: [] + }; + mediaDescs.push(currentMediaDesc); + } + else if (currentMediaDesc) { + const 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 (const mediaDesc of mediaDescs) { + const mline = lines[mediaDesc.index].split(" "); + // Ignore the first 3 parameters of the mline. The codec information is after that + for (let 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"); +}; +const stripMediaDescription = (sdp, description) => { + const descriptionRegExp = new RegExp("m=" + description + ".*$", "gm"); + const groupRegExp = new RegExp("^a=group:.*$", "gm"); + if (descriptionRegExp.test(sdp)) { + let midLineToRemove; + sdp = sdp.split(/^m=/gm).filter((section) => { + if (section.substr(0, description.length) === description) { + midLineToRemove = section.match(/^a=mid:.*$/gm); + if (midLineToRemove) { + const step = midLineToRemove[0].match(/:.+$/g); + if (step) { + midLineToRemove = step[0].substr(1); + } + } + return false; + } + return true; + }).join("m="); + const groupLine = sdp.match(groupRegExp); + if (groupLine && groupLine.length === 1) { + let groupLinePortion = groupLine[0]; + // eslint-disable-next-line no-useless-escape + const groupRegExpReplace = new RegExp("\ *" + midLineToRemove + "[^\ ]*", "g"); + groupLinePortion = groupLinePortion.replace(groupRegExpReplace, ""); + sdp = sdp.split(groupRegExp).join(groupLinePortion); + } + } + return sdp; +}; +/** + * Modifier. + * @public + */ +function stripTcpCandidates(description) { + description.sdp = (description.sdp || "").replace(/^a=candidate:\d+ \d+ tcp .*?\r\n/img, ""); + return Promise.resolve(description); +} +/** + * Modifier. + * @public + */ +function stripTelephoneEvent(description) { + description.sdp = stripPayload(description.sdp || "", "telephone-event"); + return Promise.resolve(description); +} +/** + * Modifier. + * @public + */ +function cleanJitsiSdpImageattr(description) { + description.sdp = (description.sdp || "").replace(/^(a=imageattr:.*?)(x|y)=\[0-/gm, "$1$2=[1:"); + return Promise.resolve(description); +} +/** + * Modifier. + * @public + */ +function stripG722(description) { + description.sdp = stripPayload(description.sdp || "", "G722"); + return Promise.resolve(description); +} +/** + * Modifier. + * @public + */ +function stripRtpPayload(payload) { + return (description) => { + description.sdp = stripPayload(description.sdp || "", payload); + return Promise.resolve(description); + }; +} +/** + * Modifier. + * @public + */ +function stripVideo(description) { + description.sdp = stripMediaDescription(description.sdp || "", "video"); + return Promise.resolve(description); +} +/** + * Modifier. + * @public + */ +function addMidLines(description) { + let sdp = description.sdp || ""; + if (sdp.search(/^a=mid.*$/gm) === -1) { + const mlines = sdp.match(/^m=.*$/gm); + const sdpArray = sdp.split(/^m=.*$/gm); + if (mlines) { + mlines.forEach((elem, idx) => { + mlines[idx] = elem + "\na=mid:" + idx; + }); + } + sdpArray.forEach((elem, idx) => { + if (mlines && mlines[idx]) { + sdpArray[idx] = elem + mlines[idx]; + } + }); + sdp = sdpArray.join(""); + description.sdp = sdp; + } + return Promise.resolve(description); +} +/** + * The modifier that should be used when the session would like to place the call on hold. + * @param description - The description that will be modified. + */ +function holdModifier(description) { + if (!description.sdp || !description.type) { + throw new Error("Invalid SDP"); + } + let sdp = description.sdp; + const type = description.type; + if (sdp) { + if (!/a=(sendrecv|sendonly|recvonly|inactive)/.test(sdp)) { + sdp = sdp.replace(/(m=[^\r]*\r\n)/g, "$1a=sendonly\r\n"); + } + else { + sdp = sdp.replace(/a=sendrecv\r\n/g, "a=sendonly\r\n"); + sdp = sdp.replace(/a=recvonly\r\n/g, "a=inactive\r\n"); + } + } + return Promise.resolve({ sdp, type }); +} + + +/***/ }), +/* 177 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _simple_user__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(178); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SimpleUser", function() { return _simple_user__WEBPACK_IMPORTED_MODULE_0__["SimpleUser"]; }); + +/* harmony import */ var _simple_user_delegate__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(179); +/* empty/unused harmony star reexport *//* harmony import */ var _simple_user_options__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(180); +/* empty/unused harmony star reexport *//** + * A simple SIP user implementation for web browsers. + * @packageDocumentation + */ + + + + + +/***/ }), +/* 178 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SimpleUser", function() { return SimpleUser; }); +/* harmony import */ var _api__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); +/* harmony import */ var _modifiers__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(175); +/* harmony import */ var _session_description_handler__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(160); +/* harmony import */ var _transport__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(171); + + + + +/** + * A simple SIP user class. + * @remarks + * While this class is completely functional for simple use cases, it is not intended + * to provide an interface which is suitable for most (must less all) applications. + * While this class has many limitations (for example, it only handles a single concurrent session), + * it is, however, intended to serve as a simple example of using the SIP.js API. + * @public + */ +class SimpleUser { + /** + * Constructs a new instance of the `SimpleUser` class. + * @param server - SIP WebSocket Server URL. + * @param options - Options bucket. See {@link SimpleUserOptions} for details. + */ + constructor(server, options = {}) { + this.attemptingReconnection = false; + this.connectRequested = false; + this.held = false; + this.registerer = undefined; + this.registerRequested = false; + this.session = undefined; + // Delegate + this.delegate = options.delegate; + // Copy options + this.options = Object.assign({}, options); + // UserAgentOptions + const userAgentOptions = Object.assign({}, options.userAgentOptions); + // Transport + if (!userAgentOptions.transportConstructor) { + userAgentOptions.transportConstructor = _transport__WEBPACK_IMPORTED_MODULE_3__["Transport"]; + } + // TransportOptions + if (!userAgentOptions.transportOptions) { + userAgentOptions.transportOptions = { + server + }; + } + // URI + if (!userAgentOptions.uri) { + // If an AOR was provided, convert it to a URI + if (options.aor) { + const uri = _api__WEBPACK_IMPORTED_MODULE_0__["UserAgent"].makeURI(options.aor); + if (!uri) { + throw new Error(`Failed to create valid URI from ${options.aor}`); + } + userAgentOptions.uri = uri; + } + } + // UserAgent + this.userAgent = new _api__WEBPACK_IMPORTED_MODULE_0__["UserAgent"](userAgentOptions); + // UserAgent's delegate + this.userAgent.delegate = { + // Handle connection with server established + onConnect: () => { + this.logger.log(`[${this.id}] Connected`); + if (this.delegate && this.delegate.onServerConnect) { + this.delegate.onServerConnect(); + } + if (this.registerer && this.registerRequested) { + this.logger.log(`[${this.id}] Registering...`); + this.registerer.register().catch((e) => { + this.logger.error(`[${this.id}] Error occurred registering after connection with server was obtained.`); + this.logger.error(e.toString()); + }); + } + }, + // Handle connection with server lost + onDisconnect: (error) => { + this.logger.log(`[${this.id}] Disconnected`); + if (this.delegate && this.delegate.onServerDisconnect) { + this.delegate.onServerDisconnect(error); + } + if (this.session) { + this.logger.log(`[${this.id}] Hanging up...`); + this.hangup() // cleanup hung calls + .catch((e) => { + this.logger.error(`[${this.id}] Error occurred hanging up call after connection with server was lost.`); + this.logger.error(e.toString()); + }); + } + if (this.registerer) { + this.logger.log(`[${this.id}] Unregistering...`); + this.registerer + .unregister() // cleanup invalid registrations + .catch((e) => { + this.logger.error(`[${this.id}] Error occurred unregistering after connection with server was lost.`); + this.logger.error(e.toString()); + }); + } + // Only attempt to reconnect if network/server dropped the connection. + if (error) { + this.attemptReconnection(); + } + }, + // Handle incoming invitations + onInvite: (invitation) => { + this.logger.log(`[${this.id}] Received INVITE`); + // Guard against a pre-existing session. This implementation only supports one session at a time. + // However an incoming INVITE request may be received at any time and/or while in the process + // of sending an outgoing INVITE request. So we reject any incoming INVITE in those cases. + if (this.session) { + this.logger.warn(`[${this.id}] Session already in progress, rejecting INVITE...`); + invitation + .reject() + .then(() => { + this.logger.log(`[${this.id}] Rejected INVITE`); + }) + .catch((error) => { + this.logger.error(`[${this.id}] Failed to reject INVITE`); + this.logger.error(error.toString()); + }); + return; + } + // Use our configured constraints as options for any Inviter created as result of a REFER + const referralInviterOptions = { + sessionDescriptionHandlerOptions: { constraints: this.constraints } + }; + // Initialize our session + this.initSession(invitation, referralInviterOptions); + // Delegate + if (this.delegate && this.delegate.onCallReceived) { + this.delegate.onCallReceived(); + } + else { + this.logger.warn(`[${this.id}] No handler available, rejecting INVITE...`); + invitation + .reject() + .then(() => { + this.logger.log(`[${this.id}] Rejected INVITE`); + }) + .catch((error) => { + this.logger.error(`[${this.id}] Failed to reject INVITE`); + this.logger.error(error.toString()); + }); + } + }, + // Handle incoming messages + onMessage: (message) => { + message.accept().then(() => { + if (this.delegate && this.delegate.onMessageReceived) { + this.delegate.onMessageReceived(message.request.body); + } + }); + } + }; + // Use the SIP.js logger + this.logger = this.userAgent.getLogger("sip.SimpleUser"); + // Monitor network connectivity and attempt reconnection when we come online + window.addEventListener("online", () => { + this.logger.log(`[${this.id}] Online`); + this.attemptReconnection(); + }); + } + /** + * Instance identifier. + * @internal + */ + get id() { + return (this.options.userAgentOptions && this.options.userAgentOptions.displayName) || "Anonymous"; + } + /** The local media stream. Undefined if call not answered. */ + get localMediaStream() { + var _a; + const sdh = (_a = this.session) === null || _a === void 0 ? void 0 : _a.sessionDescriptionHandler; + if (!sdh) { + return undefined; + } + if (!(sdh instanceof _session_description_handler__WEBPACK_IMPORTED_MODULE_2__["SessionDescriptionHandler"])) { + throw new Error("Session description handler not instance of web SessionDescriptionHandler"); + } + return sdh.localMediaStream; + } + /** The remote media stream. Undefined if call not answered. */ + get remoteMediaStream() { + var _a; + const sdh = (_a = this.session) === null || _a === void 0 ? void 0 : _a.sessionDescriptionHandler; + if (!sdh) { + return undefined; + } + if (!(sdh instanceof _session_description_handler__WEBPACK_IMPORTED_MODULE_2__["SessionDescriptionHandler"])) { + throw new Error("Session description handler not instance of web SessionDescriptionHandler"); + } + return sdh.remoteMediaStream; + } + /** + * The local audio track, if available. + * @deprecated Use localMediaStream and get track from the stream. + */ + get localAudioTrack() { + var _a; + return (_a = this.localMediaStream) === null || _a === void 0 ? void 0 : _a.getTracks().find((track) => track.kind === "audio"); + } + /** + * The local video track, if available. + * @deprecated Use localMediaStream and get track from the stream. + */ + get localVideoTrack() { + var _a; + return (_a = this.localMediaStream) === null || _a === void 0 ? void 0 : _a.getTracks().find((track) => track.kind === "video"); + } + /** + * The remote audio track, if available. + * @deprecated Use remoteMediaStream and get track from the stream. + */ + get remoteAudioTrack() { + var _a; + return (_a = this.remoteMediaStream) === null || _a === void 0 ? void 0 : _a.getTracks().find((track) => track.kind === "audio"); + } + /** + * The remote video track, if available. + * @deprecated Use remoteMediaStream and get track from the stream. + */ + get remoteVideoTrack() { + var _a; + return (_a = this.remoteMediaStream) === null || _a === void 0 ? void 0 : _a.getTracks().find((track) => track.kind === "video"); + } + /** + * Connect. + * @remarks + * Start the UserAgent's WebSocket Transport. + */ + connect() { + this.logger.log(`[${this.id}] Connecting UserAgent...`); + this.connectRequested = true; + if (this.userAgent.state !== _api__WEBPACK_IMPORTED_MODULE_0__["UserAgentState"].Started) { + return this.userAgent.start(); + } + return this.userAgent.reconnect(); + } + /** + * Disconnect. + * @remarks + * Stop the UserAgent's WebSocket Transport. + */ + disconnect() { + this.logger.log(`[${this.id}] Disconnecting UserAgent...`); + this.connectRequested = false; + return this.userAgent.stop(); + } + /** + * Return true if connected. + */ + isConnected() { + return this.userAgent.isConnected(); + } + /** + * Start receiving incoming calls. + * @remarks + * Send a REGISTER request for the UserAgent's AOR. + * Resolves when the REGISTER request is sent, otherwise rejects. + */ + register(registererOptions, registererRegisterOptions) { + this.logger.log(`[${this.id}] Registering UserAgent...`); + this.registerRequested = true; + if (!this.registerer) { + this.registerer = new _api__WEBPACK_IMPORTED_MODULE_0__["Registerer"](this.userAgent, registererOptions); + this.registerer.stateChange.addListener((state) => { + switch (state) { + case _api__WEBPACK_IMPORTED_MODULE_0__["RegistererState"].Initial: + break; + case _api__WEBPACK_IMPORTED_MODULE_0__["RegistererState"].Registered: + if (this.delegate && this.delegate.onRegistered) { + this.delegate.onRegistered(); + } + break; + case _api__WEBPACK_IMPORTED_MODULE_0__["RegistererState"].Unregistered: + if (this.delegate && this.delegate.onUnregistered) { + this.delegate.onUnregistered(); + } + break; + case _api__WEBPACK_IMPORTED_MODULE_0__["RegistererState"].Terminated: + this.registerer = undefined; + break; + default: + throw new Error("Unknown registerer state."); + } + }); + } + return this.registerer.register(registererRegisterOptions).then(() => { + return; + }); + } + /** + * Stop receiving incoming calls. + * @remarks + * Send an un-REGISTER request for the UserAgent's AOR. + * Resolves when the un-REGISTER request is sent, otherwise rejects. + */ + unregister(registererUnregisterOptions) { + this.logger.log(`[${this.id}] Unregistering UserAgent...`); + this.registerRequested = false; + if (!this.registerer) { + return Promise.resolve(); + } + return this.registerer.unregister(registererUnregisterOptions).then(() => { + return; + }); + } + /** + * Make an outgoing call. + * @remarks + * Send an INVITE request to create a new Session. + * Resolves when the INVITE request is sent, otherwise rejects. + * Use `onCallAnswered` delegate method to determine if Session is established. + * @param destination - The target destination to call. A SIP address to send the INVITE to. + * @param inviterOptions - Optional options for Inviter constructor. + * @param inviterInviteOptions - Optional options for Inviter.invite(). + */ + call(destination, inviterOptions, inviterInviteOptions) { + this.logger.log(`[${this.id}] Beginning Session...`); + if (this.session) { + return Promise.reject(new Error("Session already exists.")); + } + const target = _api__WEBPACK_IMPORTED_MODULE_0__["UserAgent"].makeURI(destination); + if (!target) { + return Promise.reject(new Error(`Failed to create a valid URI from "${destination}"`)); + } + // Use our configured constraints as InviterOptions if none provided + if (!inviterOptions) { + inviterOptions = {}; + } + if (!inviterOptions.sessionDescriptionHandlerOptions) { + inviterOptions.sessionDescriptionHandlerOptions = {}; + } + if (!inviterOptions.sessionDescriptionHandlerOptions.constraints) { + inviterOptions.sessionDescriptionHandlerOptions.constraints = this.constraints; + } + // Create a new Inviter for the outgoing Session + const inviter = new _api__WEBPACK_IMPORTED_MODULE_0__["Inviter"](this.userAgent, target, inviterOptions); + // Send INVITE + return this.sendInvite(inviter, inviterOptions, inviterInviteOptions).then(() => { + return; + }); + } + /** + * Hangup a call. + * @remarks + * Send a BYE request, CANCEL request or reject response to end the current Session. + * Resolves when the request/response is sent, otherwise rejects. + * Use `onCallTerminated` delegate method to determine if and when call is ended. + */ + hangup() { + this.logger.log(`[${this.id}] Hangup...`); + return this.terminate(); + } + /** + * Answer an incoming call. + * @remarks + * Accept an incoming INVITE request creating a new Session. + * Resolves with the response is sent, otherwise rejects. + * Use `onCallAnswered` delegate method to determine if and when call is established. + * @param invitationAcceptOptions - Optional options for Inviter.accept(). + */ + answer(invitationAcceptOptions) { + this.logger.log(`[${this.id}] Accepting Invitation...`); + if (!this.session) { + return Promise.reject(new Error("Session does not exist.")); + } + if (!(this.session instanceof _api__WEBPACK_IMPORTED_MODULE_0__["Invitation"])) { + return Promise.reject(new Error("Session not instance of Invitation.")); + } + // Use our configured constraints as InvitationAcceptOptions if none provided + if (!invitationAcceptOptions) { + invitationAcceptOptions = {}; + } + if (!invitationAcceptOptions.sessionDescriptionHandlerOptions) { + invitationAcceptOptions.sessionDescriptionHandlerOptions = {}; + } + if (!invitationAcceptOptions.sessionDescriptionHandlerOptions.constraints) { + invitationAcceptOptions.sessionDescriptionHandlerOptions.constraints = this.constraints; + } + return this.session.accept(invitationAcceptOptions); + } + /** + * Decline an incoming call. + * @remarks + * Reject an incoming INVITE request. + * Resolves with the response is sent, otherwise rejects. + * Use `onCallTerminated` delegate method to determine if and when call is ended. + */ + decline() { + this.logger.log(`[${this.id}] rejecting Invitation...`); + if (!this.session) { + return Promise.reject(new Error("Session does not exist.")); + } + if (!(this.session instanceof _api__WEBPACK_IMPORTED_MODULE_0__["Invitation"])) { + return Promise.reject(new Error("Session not instance of Invitation.")); + } + return this.session.reject(); + } + /** + * Hold call + * @remarks + * Send a re-INVITE with new offer indicating "hold". + * Resolves when the re-INVITE request is sent, otherwise rejects. + * Use `onCallHold` delegate method to determine if request is accepted or rejected. + * See: https://tools.ietf.org/html/rfc6337 + */ + hold() { + this.logger.log(`[${this.id}] holding session...`); + return this.setHold(true); + } + /** + * Unhold call. + * @remarks + * Send a re-INVITE with new offer indicating "unhold". + * Resolves when the re-INVITE request is sent, otherwise rejects. + * Use `onCallHold` delegate method to determine if request is accepted or rejected. + * See: https://tools.ietf.org/html/rfc6337 + */ + unhold() { + this.logger.log(`[${this.id}] unholding session...`); + return this.setHold(false); + } + /** + * Hold state. + * @remarks + * True if session media is on hold. + */ + isHeld() { + return this.held; + } + /** + * Mute call. + * @remarks + * Disable sender's media tracks. + */ + mute() { + this.logger.log(`[${this.id}] disabling media tracks...`); + this.setMute(true); + } + /** + * Unmute call. + * @remarks + * Enable sender's media tracks. + */ + unmute() { + this.logger.log(`[${this.id}] enabling media tracks...`); + this.setMute(false); + } + /** + * Mute state. + * @remarks + * True if sender's media track is disabled. + */ + isMuted() { + const track = this.localAudioTrack || this.localVideoTrack; + return track ? !track.enabled : false; + } + /** + * Send DTMF. + * @remarks + * Send an INFO request with content type application/dtmf-relay. + * @param tone - Tone to send. + */ + sendDTMF(tone) { + this.logger.log(`[${this.id}] sending DTMF...`); + // As RFC 6086 states, sending DTMF via INFO is not standardized... + // + // Companies have been using INFO messages in order to transport + // Dual-Tone Multi-Frequency (DTMF) tones. All mechanisms are + // proprietary and have not been standardized. + // https://tools.ietf.org/html/rfc6086#section-2 + // + // It is however widely supported based on this draft: + // https://tools.ietf.org/html/draft-kaplan-dispatch-info-dtmf-package-00 + // Validate tone + if (!/^[0-9A-D#*,]$/.exec(tone)) { + return Promise.reject(new Error("Invalid DTMF tone.")); + } + if (!this.session) { + return Promise.reject(new Error("Session does not exist.")); + } + // The UA MUST populate the "application/dtmf-relay" body, as defined + // earlier, with the button pressed and the duration it was pressed + // for. Technically, this actually requires the INFO to be generated + // when the user *releases* the button, however if the user has still + // not released a button after 5 seconds, which is the maximum duration + // supported by this mechanism, the UA should generate the INFO at that + // time. + // https://tools.ietf.org/html/draft-kaplan-dispatch-info-dtmf-package-00#section-5.3 + this.logger.log(`[${this.id}] Sending DTMF tone: ${tone}`); + const dtmf = tone; + const duration = 2000; + const body = { + contentDisposition: "render", + contentType: "application/dtmf-relay", + content: "Signal=" + dtmf + "\r\nDuration=" + duration + }; + const requestOptions = { body }; + return this.session.info({ requestOptions }).then(() => { + return; + }); + } + /** + * Send a message. + * @remarks + * Send a MESSAGE request. + * @param destination - The target destination for the message. A SIP address to send the MESSAGE to. + */ + message(destination, message) { + this.logger.log(`[${this.id}] sending message...`); + const target = _api__WEBPACK_IMPORTED_MODULE_0__["UserAgent"].makeURI(destination); + if (!target) { + return Promise.reject(new Error(`Failed to create a valid URI from "${destination}"`)); + } + return new _api__WEBPACK_IMPORTED_MODULE_0__["Messager"](this.userAgent, target, message).message(); + } + /** Media constraints. */ + get constraints() { + var _a; + let constraints = { audio: true, video: false }; // default to audio only calls + if ((_a = this.options.media) === null || _a === void 0 ? void 0 : _a.constraints) { + constraints = Object.assign({}, this.options.media.constraints); + } + return constraints; + } + /** + * Attempt reconnection up to `maxReconnectionAttempts` times. + * @param reconnectionAttempt - Current attempt number. + */ + attemptReconnection(reconnectionAttempt = 1) { + const reconnectionAttempts = this.options.reconnectionAttempts || 3; + const reconnectionDelay = this.options.reconnectionDelay || 4; + if (!this.connectRequested) { + this.logger.log(`[${this.id}] Reconnection not currently desired`); + return; // If intentionally disconnected, don't reconnect. + } + if (this.attemptingReconnection) { + this.logger.log(`[${this.id}] Reconnection attempt already in progress`); + } + if (reconnectionAttempt > reconnectionAttempts) { + this.logger.log(`[${this.id}] Reconnection maximum attempts reached`); + return; + } + if (reconnectionAttempt === 1) { + this.logger.log(`[${this.id}] Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - trying`); + } + else { + this.logger.log(`[${this.id}] Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - trying in ${reconnectionDelay} seconds`); + } + this.attemptingReconnection = true; + setTimeout(() => { + if (!this.connectRequested) { + this.logger.log(`[${this.id}] Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - aborted`); + this.attemptingReconnection = false; + return; // If intentionally disconnected, don't reconnect. + } + this.userAgent + .reconnect() + .then(() => { + this.logger.log(`[${this.id}] Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - succeeded`); + this.attemptingReconnection = false; + }) + .catch((error) => { + this.logger.log(`[${this.id}] Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - failed`); + this.logger.error(error.message); + this.attemptingReconnection = false; + this.attemptReconnection(++reconnectionAttempt); + }); + }, reconnectionAttempt === 1 ? 0 : reconnectionDelay * 1000); + } + /** Helper function to remove media from html elements. */ + cleanupMedia() { + if (this.options.media) { + if (this.options.media.local) { + if (this.options.media.local.video) { + this.options.media.local.video.srcObject = null; + this.options.media.local.video.pause(); + } + } + if (this.options.media.remote) { + if (this.options.media.remote.audio) { + this.options.media.remote.audio.srcObject = null; + this.options.media.remote.audio.pause(); + } + if (this.options.media.remote.video) { + this.options.media.remote.video.srcObject = null; + this.options.media.remote.video.pause(); + } + } + } + } + /** Helper function to enable/disable media tracks. */ + enableSenderTracks(enable) { + if (!this.session) { + throw new Error("Session does not exist."); + } + const sessionDescriptionHandler = this.session.sessionDescriptionHandler; + if (!(sessionDescriptionHandler instanceof _session_description_handler__WEBPACK_IMPORTED_MODULE_2__["SessionDescriptionHandler"])) { + throw new Error("Session's session description handler not instance of SessionDescriptionHandler."); + } + const peerConnection = sessionDescriptionHandler.peerConnection; + if (!peerConnection) { + throw new Error("Peer connection closed."); + } + peerConnection.getSenders().forEach((sender) => { + if (sender.track) { + sender.track.enabled = enable; + } + }); + } + /** + * Setup session delegate and state change handler. + * @param session - Session to setup + * @param referralInviterOptions - Options for any Inviter created as result of a REFER. + */ + initSession(session, referralInviterOptions) { + // Set session + this.session = session; + // Call session created callback + if (this.delegate && this.delegate.onCallCreated) { + this.delegate.onCallCreated(); + } + // Setup session state change handler + this.session.stateChange.addListener((state) => { + if (this.session !== session) { + return; // if our session has changed, just return + } + this.logger.log(`[${this.id}] session state changed to ${state}`); + switch (state) { + case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Initial: + break; + case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Establishing: + break; + case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Established: + this.setupLocalMedia(); + this.setupRemoteMedia(); + if (this.delegate && this.delegate.onCallAnswered) { + this.delegate.onCallAnswered(); + } + break; + case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Terminating: + // fall through + case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Terminated: + this.session = undefined; + this.cleanupMedia(); + if (this.delegate && this.delegate.onCallHangup) { + this.delegate.onCallHangup(); + } + break; + default: + throw new Error("Unknown session state."); + } + }); + // Setup delegate + this.session.delegate = { + onInfo: (info) => { + // As RFC 6086 states, sending DTMF via INFO is not standardized... + // + // Companies have been using INFO messages in order to transport + // Dual-Tone Multi-Frequency (DTMF) tones. All mechanisms are + // proprietary and have not been standardized. + // https://tools.ietf.org/html/rfc6086#section-2 + // + // It is however widely supported based on this draft: + // https://tools.ietf.org/html/draft-kaplan-dispatch-info-dtmf-package-00 + var _a; + // FIXME: TODO: We should reject correctly... + // + // 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. + // https://tools.ietf.org/html/rfc6086#section-4.2.2 + // No delegate + if (((_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onCallDTMFReceived) === undefined) { + info.reject(); + return; + } + // Invalid content type + const contentType = info.request.getHeader("content-type"); + if (!contentType || !/^application\/dtmf-relay/i.exec(contentType)) { + info.reject(); + return; + } + // Invalid body + const body = info.request.body.split("\r\n", 2); + if (body.length !== 2) { + info.reject(); + return; + } + // Invalid tone + let tone; + const toneRegExp = /^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/; + if (toneRegExp.test(body[0])) { + tone = body[0].replace(toneRegExp, "$2"); + } + if (!tone) { + info.reject(); + return; + } + // Invalid duration + let duration; + const durationRegExp = /^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/; + if (durationRegExp.test(body[1])) { + duration = parseInt(body[1].replace(durationRegExp, "$2"), 10); + } + if (!duration) { + info.reject(); + return; + } + info + .accept() + .then(() => { + if (this.delegate && this.delegate.onCallDTMFReceived) { + if (!tone || !duration) { + throw new Error("Tone or duration undefined."); + } + this.delegate.onCallDTMFReceived(tone, duration); + } + }) + .catch((error) => { + this.logger.error(error.message); + }); + }, + onRefer: (referral) => { + referral + .accept() + .then(() => this.sendInvite(referral.makeInviter(referralInviterOptions), referralInviterOptions)) + .catch((error) => { + this.logger.error(error.message); + }); + } + }; + } + /** Helper function to init send then send invite. */ + sendInvite(inviter, inviterOptions, inviterInviteOptions) { + // Initialize our session + this.initSession(inviter, inviterOptions); + // Send the INVITE + return inviter.invite(inviterInviteOptions).then(() => { + this.logger.log(`[${this.id}] sent INVITE`); + }); + } + /** + * Puts Session on hold. + * @param hold - Hold on if true, off if false. + */ + setHold(hold) { + if (!this.session) { + return Promise.reject(new Error("Session does not exist.")); + } + const session = this.session; + // Just resolve if we are already in correct state + if (this.held === hold) { + return Promise.resolve(); + } + const sessionDescriptionHandler = this.session.sessionDescriptionHandler; + if (!(sessionDescriptionHandler instanceof _session_description_handler__WEBPACK_IMPORTED_MODULE_2__["SessionDescriptionHandler"])) { + throw new Error("Session's session description handler not instance of SessionDescriptionHandler."); + } + const options = { + requestDelegate: { + onAccept: () => { + this.held = hold; + if (this.delegate && this.delegate.onCallHold) { + this.delegate.onCallHold(this.held); + } + }, + onReject: () => { + this.logger.warn(`[${this.id}] re-invite request was rejected`); + if (this.delegate && this.delegate.onCallHold) { + this.delegate.onCallHold(this.held); + } + } + } + }; + // Session properties used to pass modifiers to the SessionDescriptionHandler: + // + // 1) Session.sessionDescriptionHandlerModifiers + // - used in all cases when handling the initial INVITE transaction as either UAC or UAS + // - may be set directly at anytime + // - may optionally be set via constructor option + // - may optionally be set via options passed to Inviter.invite() or Invitation.accept() + // + // 2) Session.sessionDescriptionHandlerModifiersReInvite + // - used in all cases when handling a re-INVITE transaction as either UAC or UAS + // - may be set directly at anytime + // - may optionally be set via constructor option + // - may optionally be set via options passed to Session.invite() + // Set the session's SDH re-INVITE modifiers to produce the appropriate SDP offer to place call on hold + session.sessionDescriptionHandlerModifiersReInvite = hold ? [_modifiers__WEBPACK_IMPORTED_MODULE_1__["holdModifier"]] : []; + // Send re-INVITE + return this.session + .invite(options) + .then(() => { + // Reset the session's SDH re-INVITE modifiers. + // Note that if the modifiers are not reset, they will be applied + // to the SDP answer as well (which we do not want in this case). + session.sessionDescriptionHandlerModifiersReInvite = []; + this.enableSenderTracks(!hold); // mute/unmute + }) + .catch((error) => { + if (error instanceof _api__WEBPACK_IMPORTED_MODULE_0__["RequestPendingError"]) { + this.logger.error(`[${this.id}] A hold request is already in progress.`); + } + throw error; + }); + } + /** + * Puts Session on mute. + * @param mute - Mute on if true, off if false. + */ + setMute(mute) { + if (!this.session) { + this.logger.warn(`[${this.id}] A session is required to enabled/disable media tracks`); + return; + } + if (this.session.state !== _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Established) { + this.logger.warn(`[${this.id}] An established session is required to enable/disable media tracks`); + return; + } + this.enableSenderTracks(!mute); + } + /** Helper function to attach local media to html elements. */ + setupLocalMedia() { + var _a, _b; + if (!this.session) { + throw new Error("Session does not exist."); + } + const mediaElement = (_b = (_a = this.options.media) === null || _a === void 0 ? void 0 : _a.local) === null || _b === void 0 ? void 0 : _b.video; + if (mediaElement) { + const localStream = this.localMediaStream; + if (!localStream) { + throw new Error("Local media stream undefiend."); + } + mediaElement.srcObject = localStream; + mediaElement.volume = 0; + mediaElement.play().catch((error) => { + this.logger.error(`[${this.id}] Failed to play local media`); + this.logger.error(error.message); + }); + } + } + /** Helper function to attach remote media to html elements. */ + setupRemoteMedia() { + var _a, _b, _c, _d; + if (!this.session) { + throw new Error("Session does not exist."); + } + const mediaElement = ((_b = (_a = this.options.media) === null || _a === void 0 ? void 0 : _a.remote) === null || _b === void 0 ? void 0 : _b.video) || ((_d = (_c = this.options.media) === null || _c === void 0 ? void 0 : _c.remote) === null || _d === void 0 ? void 0 : _d.audio); + if (mediaElement) { + const remoteStream = this.remoteMediaStream; + if (!remoteStream) { + throw new Error("Remote media stream undefiend."); + } + mediaElement.autoplay = true; // Safari hack, because you cannot call .play() from a non user action + mediaElement.srcObject = remoteStream; + mediaElement.play().catch((error) => { + this.logger.error(`[${this.id}] Failed to play remote media`); + this.logger.error(error.message); + }); + remoteStream.onaddtrack = () => { + this.logger.log(`[${this.id}] Remote media onaddtrack`); + mediaElement.load(); // Safari hack, as it doesn't work otheriwse + mediaElement.play().catch((error) => { + this.logger.error(`[${this.id}] Failed to play remote media`); + this.logger.error(error.message); + }); + }; + } + } + /** + * End a session. + * @remarks + * Send a BYE request, CANCEL request or reject response to end the current Session. + * Resolves when the request/response is sent, otherwise rejects. + * Use `onCallTerminated` delegate method to determine if and when Session is terminated. + */ + terminate() { + this.logger.log(`[${this.id}] Terminating...`); + if (!this.session) { + return Promise.reject(new Error("Session does not exist.")); + } + switch (this.session.state) { + case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Initial: + if (this.session instanceof _api__WEBPACK_IMPORTED_MODULE_0__["Inviter"]) { + return this.session.cancel().then(() => { + this.logger.log(`[${this.id}] Inviter never sent INVITE (canceled)`); + }); + } + else if (this.session instanceof _api__WEBPACK_IMPORTED_MODULE_0__["Invitation"]) { + return this.session.reject().then(() => { + this.logger.log(`[${this.id}] Invitation rejected (sent 480)`); + }); + } + else { + throw new Error("Unknown session type."); + } + case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Establishing: + if (this.session instanceof _api__WEBPACK_IMPORTED_MODULE_0__["Inviter"]) { + return this.session.cancel().then(() => { + this.logger.log(`[${this.id}] Inviter canceled (sent CANCEL)`); + }); + } + else if (this.session instanceof _api__WEBPACK_IMPORTED_MODULE_0__["Invitation"]) { + return this.session.reject().then(() => { + this.logger.log(`[${this.id}] Invitation rejected (sent 480)`); + }); + } + else { + throw new Error("Unknown session type."); + } + case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Established: + return this.session.bye().then(() => { + this.logger.log(`[${this.id}] Session ended (sent BYE)`); + }); + case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Terminating: + break; + case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Terminated: + break; + default: + throw new Error("Unknown state"); + } + this.logger.log(`[${this.id}] Terminating in state ${this.session.state}, no action taken`); + return Promise.resolve(); + } +} + + +/***/ }), +/* 179 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 180 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }) +/******/ ]); +}); \ No newline at end of file diff --git a/dist/sip-0.18.0.min.js b/dist/sip-0.18.0.min.js new file mode 100644 index 000000000..1c78309aa --- /dev/null +++ b/dist/sip-0.18.0.min.js @@ -0,0 +1 @@ +!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 s(i){if(t[i])return t[i].exports;var r=t[i]={i:i,l:!1,exports:{}};return e[i].call(r.exports,r,r.exports,s),r.l=!0,r.exports}return s.m=e,s.c=t,s.d=function(e,t,i){s.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:i})},s.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},s.t=function(e,t){if(1&t&&(e=s(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var i=Object.create(null);if(s.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)s.d(i,r,function(t){return e[t]}.bind(null,r));return i},s.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return s.d(t,"a",t),t},s.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},s.p="",s(s.s=62)}({62:function(e,t,s){"use strict";s.r(t),s.d(t,"name",(function(){return Tt})),s.d(t,"version",(function(){return bt})),s.d(t,"ContentTypeUnsupportedError",(function(){return o})),s.d(t,"RequestPendingError",(function(){return a})),s.d(t,"SessionDescriptionHandlerError",(function(){return c})),s.d(t,"SessionTerminatedError",(function(){return h})),s.d(t,"StateTransitionError",(function(){return d})),s.d(t,"Bye",(function(){return l})),s.d(t,"EmitterImpl",(function(){return g})),s.d(t,"Info",(function(){return u})),s.d(t,"Invitation",(function(){return Z})),s.d(t,"Inviter",(function(){return J})),s.d(t,"Message",(function(){return L})),s.d(t,"Messager",(function(){return z})),s.d(t,"Notification",(function(){return B})),s.d(t,"PublisherState",(function(){return X})),s.d(t,"Publisher",(function(){return oe})),s.d(t,"Referral",(function(){return V})),s.d(t,"RegistererState",(function(){return Q})),s.d(t,"Registerer",(function(){return ae})),s.d(t,"SessionState",(function(){return G})),s.d(t,"Session",(function(){return W})),s.d(t,"Subscriber",(function(){return he})),s.d(t,"SubscriptionState",(function(){return te})),s.d(t,"Subscription",(function(){return ce})),s.d(t,"TransportState",(function(){return se})),s.d(t,"SIPExtension",(function(){return K})),s.d(t,"UserAgentRegisteredOptionTags",(function(){return Y})),s.d(t,"UserAgentState",(function(){return ie})),s.d(t,"UserAgent",(function(){return ot})),s.d(t,"Grammar",(function(){return b})),s.d(t,"NameAddrHeader",(function(){return f})),s.d(t,"Parameters",(function(){return p})),s.d(t,"URI",(function(){return m})),s.d(t,"Core",(function(){return i})),s.d(t,"Web",(function(){return r}));var i={};s.r(i),s.d(i,"Dialog",(function(){return ye})),s.d(i,"SessionDialog",(function(){return Le})),s.d(i,"SubscriptionDialog",(function(){return We})),s.d(i,"Exception",(function(){return n})),s.d(i,"TransactionStateError",(function(){return M})),s.d(i,"TransportError",(function(){return ve})),s.d(i,"Levels",(function(){return re})),s.d(i,"LoggerFactory",(function(){return ge})),s.d(i,"Logger",(function(){return le})),s.d(i,"Grammar",(function(){return b})),s.d(i,"NameAddrHeader",(function(){return f})),s.d(i,"Parameters",(function(){return p})),s.d(i,"URI",(function(){return m})),s.d(i,"C",(function(){return j})),s.d(i,"fromBodyLegacy",(function(){return k})),s.d(i,"isBody",(function(){return x})),s.d(i,"getBody",(function(){return q})),s.d(i,"DigestAuthentication",(function(){return fe})),s.d(i,"IncomingMessage",(function(){return C})),s.d(i,"IncomingRequestMessage",(function(){return A})),s.d(i,"IncomingResponseMessage",(function(){return D})),s.d(i,"OutgoingRequestMessage",(function(){return H})),s.d(i,"constructOutgoingResponse",(function(){return me})),s.d(i,"Parser",(function(){return et})),s.d(i,"SessionState",(function(){return P})),s.d(i,"SignalingState",(function(){return N})),s.d(i,"SubscriptionState",(function(){return ee})),s.d(i,"ClientTransaction",(function(){return be})),s.d(i,"InviteClientTransaction",(function(){return Ee})),s.d(i,"InviteServerTransaction",(function(){return Re})),s.d(i,"NonInviteClientTransaction",(function(){return Te})),s.d(i,"NonInviteServerTransaction",(function(){return Ce})),s.d(i,"ServerTransaction",(function(){return Se})),s.d(i,"TransactionState",(function(){return ne})),s.d(i,"Transaction",(function(){return we})),s.d(i,"UserAgentCore",(function(){return Qe})),s.d(i,"ByeUserAgentClient",(function(){return Ie})),s.d(i,"ByeUserAgentServer",(function(){return De})),s.d(i,"CancelUserAgentClient",(function(){return at})),s.d(i,"InfoUserAgentClient",(function(){return He})),s.d(i,"InfoUserAgentServer",(function(){return _e})),s.d(i,"InviteUserAgentClient",(function(){return Be})),s.d(i,"InviteUserAgentServer",(function(){return Ze})),s.d(i,"MessageUserAgentClient",(function(){return ke})),s.d(i,"MessageUserAgentServer",(function(){return xe})),s.d(i,"NotifyUserAgentClient",(function(){return qe})),s.d(i,"NotifyUserAgentServer",(function(){return Pe})),s.d(i,"PublishUserAgentClient",(function(){return Ve})),s.d(i,"PrackUserAgentClient",(function(){return Ne})),s.d(i,"PrackUserAgentServer",(function(){return Me})),s.d(i,"ReInviteUserAgentClient",(function(){return Oe})),s.d(i,"ReInviteUserAgentServer",(function(){return Ue})),s.d(i,"ReSubscribeUserAgentClient",(function(){return Ke})),s.d(i,"ReSubscribeUserAgentServer",(function(){return ct})),s.d(i,"ReferUserAgentClient",(function(){return je})),s.d(i,"ReferUserAgentServer",(function(){return Fe})),s.d(i,"RegisterUserAgentClient",(function(){return Ge})),s.d(i,"RegisterUserAgentServer",(function(){return Je})),s.d(i,"SubscribeUserAgentClient",(function(){return Ye})),s.d(i,"SubscribeUserAgentServer",(function(){return ze})),s.d(i,"UserAgentClient",(function(){return $e})),s.d(i,"UserAgentServer",(function(){return Ae})),s.d(i,"Timers",(function(){return U}));var r={};s.r(r),s.d(r,"stripTcpCandidates",(function(){return dt})),s.d(r,"stripTelephoneEvent",(function(){return lt})),s.d(r,"cleanJitsiSdpImageattr",(function(){return gt})),s.d(r,"stripG722",(function(){return ut})),s.d(r,"stripRtpPayload",(function(){return pt})),s.d(r,"stripVideo",(function(){return ft})),s.d(r,"addMidLines",(function(){return mt})),s.d(r,"holdModifier",(function(){return vt})),s.d(r,"defaultMediaStreamFactory",(function(){return tt})),s.d(r,"defaultPeerConnectionConfiguration",(function(){return st})),s.d(r,"defaultSessionDescriptionHandlerFactory",(function(){return rt})),s.d(r,"SessionDescriptionHandler",(function(){return it})),s.d(r,"SimpleUser",(function(){return wt})),s.d(r,"Transport",(function(){return nt}));class n extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}class o extends n{constructor(e){super(e||"Unsupported content type.")}}class a extends n{constructor(e){super(e||"Request pending.")}}class c extends n{constructor(e){super(e||"Unspecified session description handler error.")}}class h extends n{constructor(){super("The session has terminated.")}}class d extends n{constructor(e){super(e||"An error occurred during state transition.")}}class l{constructor(e){this.incomingByeRequest=e}get request(){return this.incomingByeRequest.message}accept(e){return this.incomingByeRequest.accept(e),Promise.resolve()}reject(e){return this.incomingByeRequest.reject(e),Promise.resolve()}}class g{constructor(){this.listeners=new Array}addListener(e,t){const s=t=>{this.removeListener(s),e(t)};!0===(null==t?void 0:t.once)?this.listeners.push(s):this.listeners.push(e)}emit(e){this.listeners.slice().forEach(t=>t(e))}removeAllListeners(){this.listeners=[]}removeListener(e){this.listeners=this.listeners.filter(t=>t!==e)}on(e){return this.addListener(e)}off(e){return this.removeListener(e)}once(e){return this.addListener(e,{once:!0})}}class u{constructor(e){this.incomingInfoRequest=e}get request(){return this.incomingInfoRequest.message}accept(e){return this.incomingInfoRequest.accept(e),Promise.resolve()}reject(e){return this.incomingInfoRequest.reject(e),Promise.resolve()}}class p{constructor(e){this.parameters={};for(const t in e)e.hasOwnProperty(t)&&this.setParam(t,e[t])}setParam(e,t){e&&(this.parameters[e.toLowerCase()]=null==t?null:t.toString())}getParam(e){if(e)return this.parameters[e.toLowerCase()]}hasParam(e){return!(!e||void 0===this.parameters[e.toLowerCase()])}deleteParam(e){if(e=e.toLowerCase(),this.hasParam(e)){const t=this.parameters[e];return delete this.parameters[e],t}}clearParams(){this.parameters={}}}class f extends p{constructor(e,t,s){super(s),this.uri=e,this._displayName=t}get friendlyName(){return this.displayName||this.uri.aor}get displayName(){return this._displayName}set displayName(e){this._displayName=e}clone(){return new f(this.uri.clone(),this._displayName,JSON.parse(JSON.stringify(this.parameters)))}toString(){let e=this.displayName||"0"===this.displayName?'"'+this.displayName+'" ':"";e+="<"+this.uri.toString()+">";for(const t in this.parameters)this.parameters.hasOwnProperty(t)&&(e+=";"+t,null!==this.parameters[t]&&(e+="="+this.parameters[t]));return e}}class m extends p{constructor(e="sip",t,s,i,r,n){if(super(r||{}),this.headers={},!s)throw new TypeError('missing or invalid "host" parameter');for(const e in n)n.hasOwnProperty(e)&&this.setHeader(e,n[e]);this.raw={scheme:e,user:t,host:s,port:i},this.normal={scheme:e.toLowerCase(),user:t,host:s.toLowerCase(),port:i}}get scheme(){return this.normal.scheme}set scheme(e){this.raw.scheme=e,this.normal.scheme=e.toLowerCase()}get user(){return this.normal.user}set user(e){this.normal.user=this.raw.user=e}get host(){return this.normal.host}set host(e){this.raw.host=e,this.normal.host=e.toLowerCase()}get aor(){return this.normal.user+"@"+this.normal.host}get port(){return this.normal.port}set port(e){this.normal.port=this.raw.port=e}setHeader(e,t){this.headers[this.headerize(e)]=t instanceof Array?t:[t]}getHeader(e){if(e)return this.headers[this.headerize(e)]}hasHeader(e){return!!e&&!!this.headers.hasOwnProperty(this.headerize(e))}deleteHeader(e){if(e=this.headerize(e),this.headers.hasOwnProperty(e)){const t=this.headers[e];return delete this.headers[e],t}}clearHeaders(){this.headers={}}clone(){return new m(this._raw.scheme,this._raw.user||"",this._raw.host,this._raw.port,JSON.parse(JSON.stringify(this.parameters)),JSON.parse(JSON.stringify(this.headers)))}toRaw(){return this._toString(this._raw)}toString(){return this._toString(this._normal)}get _normal(){return this.normal}get _raw(){return this.raw}_toString(e){let t=e.scheme+":";e.scheme.toLowerCase().match("^sips?$")||(t+="//"),e.user&&(t+=this.escapeUser(e.user)+"@"),t+=e.host,(e.port||0===e.port)&&(t+=":"+e.port);for(const e in this.parameters)this.parameters.hasOwnProperty(e)&&(t+=";"+e,null!==this.parameters[e]&&(t+="="+this.parameters[e]));const s=[];for(const e in this.headers)if(this.headers.hasOwnProperty(e))for(const t in this.headers[e])this.headers[e].hasOwnProperty(t)&&s.push(e+"="+this.headers[e][t]);return s.length>0&&(t+="?"+s.join("&")),t}escapeUser(e){let t;try{t=decodeURIComponent(e)}catch(e){throw e}return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%2B/gi,"+").replace(/%3F/gi,"?").replace(/%2F/gi,"/")}headerize(e){const t={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},s=e.toLowerCase().replace(/_/g,"-").split("-"),i=s.length;let r="";for(let e=0;e"\\x0"+s(e)).replace(/[\x10-\x1F\x7F-\x9F]/g,e=>"\\x"+s(e))}function r(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,e=>"\\x0"+s(e)).replace(/[\x10-\x1F\x7F-\x9F]/g,e=>"\\x"+s(e))}function n(e){switch(e.type){case"literal":return'"'+i(e.text)+'"';case"class":const t=e.parts.map(e=>Array.isArray(e)?r(e[0])+"-"+r(e[1]):r(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){const t=e.map(n);let s,i;if(t.sort(),t.length>0){for(s=1,i=1;s",b(">",!1),"\\",b("\\",!1),"[",b("[",!1),"]",b("]",!1),"{",b("{",!1),"}",b("}",!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 m(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 m(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",b("sips",!0),"sip",b("sip",!0),function(e){(t=t||{data:{}}).data.scheme=e},function(){(t=t||{data:{}}).data.user=decodeURIComponent(p().slice(0,-1))},function(){(t=t||{data:{}}).data.password=p()},function(){return(t=t||{data:{}}).data.host=p(),t.data.host},function(){return(t=t||{data:{}}).data.host_type="domain",p()},/^[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",p()},"::",b("::",!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",p()},function(){return(t=t||{data:{}}).data.host_type="IPv4",p()},"25",b("25",!1),/^[0-5]/,T([["0","5"]],!1,!1),"2",b("2",!1),/^[0-4]/,T([["0","4"]],!1,!1),"1",b("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=",b("transport=",!0),"udp",b("udp",!0),"tcp",b("tcp",!0),"sctp",b("sctp",!0),"tls",b("tls",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.transport=e.toLowerCase()},"user=",b("user=",!0),"phone",b("phone",!0),"ip",b("ip",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.user=e.toLowerCase()},"method=",b("method=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.method=e},"ttl=",b("ttl=",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.ttl=e},"maddr=",b("maddr=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.maddr=e},"lr",b("lr",!0),function(){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.lr=void 0},function(e,s){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),s=null===s?void 0:s[1],t.data.uri_params[e.toLowerCase()]=s},function(e,s){e=e.join("").toLowerCase(),s=s.join(""),(t=t||{data:{}}).data.uri_headers||(t.data.uri_headers={}),t.data.uri_headers[e]?t.data.uri_headers[e].push(s):t.data.uri_headers[e]=[s]},function(){"Refer_To"===(t=t||{data:{}}).startRule&&(t.data.uri=new m(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)},"//",b("//",!1),function(){(t=t||{data:{}}).data.scheme=p()},b("SIP",!0),function(){(t=t||{data:{}}).data.sip_version=p()},"INVITE",b("INVITE",!1),"ACK",b("ACK",!1),"VXACH",b("VXACH",!1),"OPTIONS",b("OPTIONS",!1),"BYE",b("BYE",!1),"CANCEL",b("CANCEL",!1),"REGISTER",b("REGISTER",!1),"SUBSCRIBE",b("SUBSCRIBE",!1),"NOTIFY",b("NOTIFY",!1),"REFER",b("REFER",!1),"PUBLISH",b("PUBLISH",!1),function(){return(t=t||{data:{}}).data.method=p(),t.data.method},function(e){(t=t||{data:{}}).data.status_code=parseInt(e.join(""))},function(){(t=t||{data:{}}).data.reason_phrase=p()},function(){(t=t||{data:{}}).data=p()},function(){var e,s;for(s=(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#;l&&(l=a,g=[]),g.push(e))}function E(e,t,s){return new v(v.buildMessage(e,t),e,t,s)}function $(e){return e.split("").map(e=>e.charCodeAt(0)-32)}if(t.data={},d=function t(i){const r=o[i];let h=0;const d=[];let l=r.length;const g=[],p=[];let f;for(;;){for(;ha?(l=h+3+r[h+1],h+=3):(l=h+3+r[h+1]+r[h+2],h+=3+r[h+1]);break;case 18:g.push(l),d.push(h+4+r[h+2]+r[h+3]),e.substr(a,n[r[h+1]].length)===n[r[h+1]]?(l=h+4+r[h+2],h+=4):(l=h+4+r[h+2]+r[h+3],h+=4+r[h+2]);break;case 19:g.push(l),d.push(h+4+r[h+2]+r[h+3]),e.substr(a,n[r[h+1]].length).toLowerCase()===n[r[h+1]]?(l=h+4+r[h+2],h+=4):(l=h+4+r[h+2]+r[h+3],h+=4+r[h+2]);break;case 20:g.push(l),d.push(h+4+r[h+2]+r[h+3]),n[r[h+1]].test(e.charAt(a))?(l=h+4+r[h+2],h+=4):(l=h+4+r[h+2]+r[h+3],h+=4+r[h+2]);break;case 21:p.push(e.substr(a,r[h+1])),a+=r[h+1],h+=2;break;case 22:p.push(n[r[h+1]]),a+=n[r[h+1]].length,h+=2;break;case 23:p.push(s),0===u&&y(n[r[h+1]]),h+=2;break;case 24:c=p[p.length-1-r[h+1]],h+=2;break;case 25:c=a,h++;break;case 26:f=r.slice(h+4,h+4+r[h+3]).map((function(e){return p[p.length-1-e]})),p.splice(p.length-r[h+2],r[h+2],n[r[h+1]].apply(null,f)),h+=4+r[h+3];break;case 27:p.push(t(r[h+1])),h+=2;break;case 28:u++,h++;break;case 29:u--,h++;break;default:throw new Error("Invalid opcode: "+r[h]+".")}if(!(g.length>0))break;l=g.pop(),h=d.pop()}return p[0]}(r),d!==s&&a===e.length)return d;throw d!==s&&a=this.headers[e].length)return;const s=this.headers[e][t],i=s.raw;if(s.parsed)return s.parsed;const r=b.parse(i,e.replace(/-/g,"_"));return-1===r?void this.headers[e].splice(t,1):(s.parsed=r,r)}s(e,t=0){return this.parseHeader(e,t)}setHeader(e,t){this.headers[$(e)]=[{raw:t}]}toString(){return this.data}}class A extends C{constructor(){super()}}class D extends C{constructor(){super()}}class H{constructor(e,t,s,i,r,n,o){this.headers={},this.extraHeaders=[],this.options=H.getDefaultOptions(),r&&(this.options=Object.assign(Object.assign({},this.options),r),this.options.optionTags&&this.options.optionTags.length&&(this.options.optionTags=this.options.optionTags.slice()),this.options.routeSet&&this.options.routeSet.length&&(this.options.routeSet=this.options.routeSet.slice())),n&&n.length&&(this.extraHeaders=n.slice()),o&&(this.body={body:o.content,contentType:o.contentType}),this.method=e,this.ruri=t.clone(),this.fromURI=s.clone(),this.fromTag=this.options.fromTag?this.options.fromTag:E(),this.from=H.makeNameAddrHeader(this.fromURI,this.options.fromDisplayName,this.fromTag),this.toURI=i.clone(),this.toTag=this.options.toTag,this.to=H.makeNameAddrHeader(this.toURI,this.options.toDisplayName,this.toTag),this.callId=this.options.callId?this.options.callId:this.options.callIdPrefix+R(15),this.cseq=this.options.cseq,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")}static getDefaultOptions(){return{callId:"",callIdPrefix:"",cseq:1,toDisplayName:"",toTag:"",fromDisplayName:"",fromTag:"",forceRport:!1,hackViaTcp:!1,optionTags:["outbound"],routeSet:[],userAgentString:"sip.js",viaHost:""}}static makeNameAddrHeader(e,t,s){const i={};return s&&(i.tag=s),new f(e,t,i)}getHeader(e){const t=this.headers[$(e)];if(t){if(t[0])return t[0]}else{const t=new RegExp("^\\s*"+e+"\\s*:","i");for(const e of this.extraHeaders)if(t.test(e))return e.substring(e.indexOf(":")+1).trim()}}getHeaders(e){const t=[],s=this.headers[$(e)];if(s)for(const e of s)t.push(e);else{const s=new RegExp("^\\s*"+e+"\\s*:","i");for(const e of this.extraHeaders)s.test(e)&&t.push(e.substring(e.indexOf(":")+1).trim())}return t}hasHeader(e){if(this.headers[$(e)])return!0;{const t=new RegExp("^\\s*"+e+"\\s*:","i");for(const e of this.extraHeaders)if(t.test(e))return!0}return!1}setHeader(e,t){this.headers[$(e)]=t instanceof Array?t:[t]}setViaHeader(e,t){this.options.hackViaTcp&&(t="TCP");let s="SIP/2.0/"+t;s+=" "+this.options.viaHost+";branch="+e,this.options.forceRport&&(s+=";rport"),this.setHeader("via",s),this.branch=e}toString(){let e="";e+=this.method+" "+this.ruri.toRaw()+" SIP/2.0\r\n";for(const t in this.headers)if(this.headers[t])for(const s of this.headers[t])e+=t+": "+s+"\r\n";for(const t of this.extraHeaders)e+=t.trim()+"\r\n";return e+="Supported: "+this.options.optionTags.join(", ")+"\r\n",e+="User-Agent: "+this.options.userAgentString+"\r\n",this.body?"string"==typeof this.body?(e+="Content-Length: "+I(this.body)+"\r\n\r\n",e+=this.body):this.body.body&&this.body.contentType?(e+="Content-Type: "+this.body.contentType+"\r\n",e+="Content-Length: "+I(this.body.body)+"\r\n\r\n",e+=this.body.body):e+="Content-Length: 0\r\n\r\n":e+="Content-Length: 0\r\n\r\n",e}}function _(e){return"application/sdp"===e?"session":"render"}function k(e){const t="string"==typeof e?e:e.body,s="string"==typeof e?"application/sdp":e.contentType;return{contentDisposition:_(s),contentType:s,content:t}}function x(e){return!(!e||"string"!=typeof e.content||"string"!=typeof e.contentType||void 0!==e.contentDisposition)||"string"==typeof e.contentDisposition}function q(e){let t,s,i;if(e instanceof A&&e.body){const r=e.parseHeader("Content-Disposition");t=r?r.type:void 0,s=e.parseHeader("Content-Type"),i=e.body}if(e instanceof D&&e.body){const r=e.parseHeader("Content-Disposition");t=r?r.type:void 0,s=e.parseHeader("Content-Type"),i=e.body}if(e instanceof H&&e.body)if(t=e.getHeader("Content-Disposition"),s=e.getHeader("Content-Type"),"string"==typeof e.body){if(!s)throw new Error("Header content type header does not equal body content type.");i=e.body}else{if(s&&s!==e.body.contentType)throw new Error("Header content type header does not equal body content type.");s=e.body.contentType,i=e.body.body}if(x(e)&&(t=e.contentDisposition,s=e.contentType,i=e.content),i){if(s&&!t&&(t=_(s)),!t)throw new Error("Content disposition undefined.");if(!s)throw new Error("Content type undefined.");return{contentDisposition:t,contentType:s,content:i}}}var P,N;!function(e){e.Initial="Initial",e.Early="Early",e.AckWait="AckWait",e.Confirmed="Confirmed",e.Terminated="Terminated"}(P||(P={})),function(e){e.Initial="Initial",e.HaveLocalOffer="HaveLocalOffer",e.HaveRemoteOffer="HaveRemoteOffer",e.Stable="Stable",e.Closed="Closed"}(N||(N={}));class M extends n{constructor(e){super(e||"Transaction state error.")}}const O=500,U={T1:O,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};var j;!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"}(j||(j={}));const F=[j.ACK,j.BYE,j.CANCEL,j.INFO,j.INVITE,j.MESSAGE,j.NOTIFY,j.OPTIONS,j.PRACK,j.REFER,j.REGISTER,j.SUBSCRIBE];class L{constructor(e){this.incomingMessageRequest=e}get request(){return this.incomingMessageRequest.message}accept(e){return this.incomingMessageRequest.accept(e),Promise.resolve()}reject(e){return this.incomingMessageRequest.reject(e),Promise.resolve()}}class B{constructor(e){this.incomingNotifyRequest=e}get request(){return this.incomingNotifyRequest.message}accept(e){return this.incomingNotifyRequest.accept(e),Promise.resolve()}reject(e){return this.incomingNotifyRequest.reject(e),Promise.resolve()}}class V{constructor(e,t){this.incomingReferRequest=e,this.session=t}get referTo(){const e=this.incomingReferRequest.message.parseHeader("refer-to");if(!(e instanceof f))throw new Error("Failed to parse Refer-To header.");return e}get referredBy(){return this.incomingReferRequest.message.getHeader("referred-by")}get replaces(){return this.referTo.uri.getHeader("replaces")}get request(){return this.incomingReferRequest.message}accept(e={statusCode:202}){return this.incomingReferRequest.accept(e),Promise.resolve()}reject(e){return this.incomingReferRequest.reject(e),Promise.resolve()}makeInviter(e){if(this.inviter)return this.inviter;const t=this.referTo.uri.clone();t.clearHeaders();const s=((e=e||{}).extraHeaders||[]).slice(),i=this.replaces;i&&s.push("Replaces: "+decodeURIComponent(i));const r=this.referredBy;return r&&s.push("Referred-By: "+r),e.extraHeaders=s,this.inviter=this.session.userAgent._makeInviter(t,e),this.inviter._referred=this.session,this.session._referral=this.inviter,this.inviter}}var G,K;!function(e){e.Initial="Initial",e.Establishing="Establishing",e.Established="Established",e.Terminating="Terminating",e.Terminated="Terminated"}(G||(G={}));class W{constructor(e,t={}){this.pendingReinvite=!1,this.pendingReinviteAck=!1,this._state=G.Initial,this.delegate=t.delegate,this._stateEventEmitter=new g,this._userAgent=e}dispose(){switch(this.logger.log(`Session ${this.id} in state ${this._state} is being disposed`),delete this.userAgent._sessions[this.id],this._sessionDescriptionHandler&&this._sessionDescriptionHandler.close(),this.state){case G.Initial:case G.Establishing:break;case G.Established:return new Promise(e=>{this._bye({onAccept:()=>e(),onRedirect:()=>e(),onReject:()=>e()})});case G.Terminating:case G.Terminated:break;default:throw new Error("Unknown state.")}return Promise.resolve()}get assertedIdentity(){return this._assertedIdentity}get dialog(){return this._dialog}get id(){return this._id}get replacee(){return this._replacee}get sessionDescriptionHandler(){return this._sessionDescriptionHandler}get sessionDescriptionHandlerFactory(){return this.userAgent.configuration.sessionDescriptionHandlerFactory}get sessionDescriptionHandlerModifiers(){return this._sessionDescriptionHandlerModifiers||[]}set sessionDescriptionHandlerModifiers(e){this._sessionDescriptionHandlerModifiers=e.slice()}get sessionDescriptionHandlerOptions(){return this._sessionDescriptionHandlerOptions||{}}set sessionDescriptionHandlerOptions(e){this._sessionDescriptionHandlerOptions=Object.assign({},e)}get sessionDescriptionHandlerModifiersReInvite(){return this._sessionDescriptionHandlerModifiersReInvite||[]}set sessionDescriptionHandlerModifiersReInvite(e){this._sessionDescriptionHandlerModifiersReInvite=e.slice()}get sessionDescriptionHandlerOptionsReInvite(){return this._sessionDescriptionHandlerOptionsReInvite||{}}set sessionDescriptionHandlerOptionsReInvite(e){this._sessionDescriptionHandlerOptionsReInvite=Object.assign({},e)}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get userAgent(){return this._userAgent}bye(e={}){let t="Session.bye() may only be called if established session.";switch(this.state){case G.Initial:"function"==typeof this.cancel?(t+=" However Inviter.invite() has not yet been called.",t+=" Perhaps you should have called Inviter.cancel()?"):"function"==typeof this.reject&&(t+=" However Invitation.accept() has not yet been called.",t+=" Perhaps you should have called Invitation.reject()?");break;case G.Establishing:"function"==typeof this.cancel?(t+=" However a dialog does not yet exist.",t+=" Perhaps you should have called Inviter.cancel()?"):"function"==typeof this.reject&&(t+=" However Invitation.accept() has not yet been called (or not yet resolved).",t+=" Perhaps you should have called Invitation.reject()?");break;case G.Established:{const t=e.requestDelegate,s=this.copyRequestOptions(e.requestOptions);return this._bye(t,s)}case G.Terminating:t+=" However this session is already terminating.","function"==typeof this.cancel?t+=" Perhaps you have already called Inviter.cancel()?":"function"==typeof this.reject&&(t+=" Perhaps you have already called Session.bye()?");break;case G.Terminated:t+=" However this session is already terminated.";break;default:throw new Error("Unknown state")}return this.logger.error(t),Promise.reject(new Error("Invalid session state "+this.state))}info(e={}){if(this.state!==G.Established){const e="Session.info() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error("Invalid session state "+this.state))}const t=e.requestDelegate,s=this.copyRequestOptions(e.requestOptions);return this._info(t,s)}invite(e={}){if(this.logger.log("Session.invite"),this.state!==G.Established)return Promise.reject(new Error("Invalid session state "+this.state));if(this.pendingReinvite)return Promise.reject(new a("Reinvite in progress. Please wait until complete, then try again."));this.pendingReinvite=!0,e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiersReInvite=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptionsReInvite=e.sessionDescriptionHandlerOptions);const t={onAccept:t=>{const s=q(t.message);if(!s)return this.logger.error("Received 2xx response to re-INVITE without a session description"),this.ackAndBye(t,400,"Missing session description"),this.stateTransition(G.Terminated),void(this.pendingReinvite=!1);if(e.withoutSdp){const i={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.setOfferAndGetAnswer(s,i).then(e=>{t.ack({body:e})}).catch(e=>{this.logger.error("Failed to handle offer in 2xx response to re-INVITE"),this.logger.error(e.message),this.state===G.Terminated?t.ack():(this.ackAndBye(t,488,"Bad Media Description"),this.stateTransition(G.Terminated))}).then(()=>{this.pendingReinvite=!1,e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t)})}else{const i={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.setAnswer(s,i).then(()=>{t.ack()}).catch(e=>{this.logger.error("Failed to handle answer in 2xx response to re-INVITE"),this.logger.error(e.message),this.state!==G.Terminated?(this.ackAndBye(t,488,"Bad Media Description"),this.stateTransition(G.Terminated)):t.ack()}).then(()=>{this.pendingReinvite=!1,e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t)})}},onProgress:e=>{},onRedirect:e=>{},onReject:t=>{this.logger.warn("Received a non-2xx response to re-INVITE"),this.pendingReinvite=!1,e.withoutSdp?e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t):this.rollbackOffer().catch(e=>{if(this.logger.error("Failed to rollback offer on non-2xx response to re-INVITE"),this.logger.error(e.message),this.state!==G.Terminated){if(!this.dialog)throw new Error("Dialog undefined.");const e=[];e.push("Reason: "+this.getReasonHeaderValue(500,"Internal Server Error")),this.dialog.bye(void 0,{extraHeaders:e}),this.stateTransition(G.Terminated)}}).then(()=>{e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t)})},onTrying:e=>{}},s=e.requestOptions||{};if(s.extraHeaders=(s.extraHeaders||[]).slice(),s.extraHeaders.push("Allow: "+F.toString()),s.extraHeaders.push("Contact: "+this._contact),e.withoutSdp){if(!this.dialog)throw this.pendingReinvite=!1,new Error("Dialog undefined.");return Promise.resolve(this.dialog.invite(t,s))}const i={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};return this.getOffer(i).then(e=>{if(!this.dialog)throw this.pendingReinvite=!1,new Error("Dialog undefined.");return s.body=e,this.dialog.invite(t,s)}).catch(e=>{throw this.logger.error(e.message),this.logger.error("Failed to send re-INVITE"),this.pendingReinvite=!1,e})}message(e={}){if(this.state!==G.Established){const e="Session.message() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error("Invalid session state "+this.state))}const t=e.requestDelegate,s=this.copyRequestOptions(e.requestOptions);return this._message(t,s)}refer(e,t={}){if(this.state!==G.Established){const e="Session.refer() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error("Invalid session state "+this.state))}const s=t.requestDelegate,i=this.copyRequestOptions(t.requestOptions);return i.extraHeaders=i.extraHeaders?i.extraHeaders.concat(this.referExtraHeaders(this.referToString(e))):this.referExtraHeaders(this.referToString(e)),this._refer(t.onNotify,s,i)}_bye(e,t){if(!this.dialog)return Promise.reject(new Error("Session dialog undefined."));const s=this.dialog;switch(s.sessionState){case P.Initial:case P.Early:throw new Error("Invalid dialog state "+s.sessionState);case P.AckWait:return this.stateTransition(G.Terminating),new Promise(i=>{s.delegate={onAck:()=>{const r=s.bye(e,t);return this.stateTransition(G.Terminated),i(r),Promise.resolve()},onAckTimeout:()=>{const r=s.bye(e,t);this.stateTransition(G.Terminated),i(r)}}});case P.Confirmed:{const i=s.bye(e,t);return this.stateTransition(G.Terminated),Promise.resolve(i)}case P.Terminated:throw new Error("Invalid dialog state "+s.sessionState);default:throw new Error("Unrecognized state.")}}_info(e,t){return this.dialog?Promise.resolve(this.dialog.info(e,t)):Promise.reject(new Error("Session dialog undefined."))}_message(e,t){return this.dialog?Promise.resolve(this.dialog.message(e,t)):Promise.reject(new Error("Session dialog undefined."))}_refer(e,t,s){return this.dialog?(this.onNotify=e,Promise.resolve(this.dialog.refer(t,s))):Promise.reject(new Error("Session dialog undefined."))}ackAndBye(e,t,s){e.ack();const i=[];t&&i.push("Reason: "+this.getReasonHeaderValue(t,s)),e.session.bye(void 0,{extraHeaders:i})}onAckRequest(e){if(this.logger.log("Session.onAckRequest"),this.state!==G.Established&&this.state!==G.Terminating)return this.logger.error(`ACK received while in state ${this.state}, dropping request`),Promise.resolve();const t=this.dialog;if(!t)throw new Error("Dialog undefined.");const s={sessionDescriptionHandlerOptions:this.pendingReinviteAck?this.sessionDescriptionHandlerOptionsReInvite:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.pendingReinviteAck?this._sessionDescriptionHandlerModifiersReInvite:this._sessionDescriptionHandlerModifiers};switch(this.pendingReinviteAck=!1,t.signalingState){case N.Initial:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const e=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:e}),this.stateTransition(G.Terminated),Promise.resolve()}case N.Stable:{const i=q(e.message);return i?"render"===i.contentDisposition?(this._renderbody=i.content,this._rendertype=i.contentType,Promise.resolve()):"session"!==i.contentDisposition?Promise.resolve():this.setAnswer(i,s).catch(e=>{this.logger.error(e.message);const s=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];t.bye(void 0,{extraHeaders:s}),this.stateTransition(G.Terminated)}):Promise.resolve()}case N.HaveLocalOffer:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const e=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:e}),this.stateTransition(G.Terminated),Promise.resolve()}case N.HaveRemoteOffer:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const e=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:e}),this.stateTransition(G.Terminated),Promise.resolve()}case N.Closed:default:throw new Error(`Invalid signaling state ${t.signalingState}.`)}}onByeRequest(e){if(this.logger.log("Session.onByeRequest"),this.state===G.Established){if(this.delegate&&this.delegate.onBye){const t=new l(e);this.delegate.onBye(t)}else e.accept();this.stateTransition(G.Terminated)}else this.logger.error(`BYE received while in state ${this.state}, dropping request`)}onInfoRequest(e){if(this.logger.log("Session.onInfoRequest"),this.state===G.Established)if(this.delegate&&this.delegate.onInfo){const t=new u(e);this.delegate.onInfo(t)}else e.accept();else this.logger.error(`INFO received while in state ${this.state}, dropping request`)}onInviteRequest(e){if(this.logger.log("Session.onInviteRequest"),this.state!==G.Established)return void this.logger.error(`INVITE received while in state ${this.state}, dropping request`);this.pendingReinviteAck=!0;const t=["Contact: "+this._contact];if(e.message.hasHeader("P-Asserted-Identity")){const t=e.message.getHeader("P-Asserted-Identity");if(!t)throw new Error("Header undefined.");this._assertedIdentity=b.nameAddrHeaderParse(t)}const s={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.generateResponseOfferAnswerInDialog(s).then(s=>{const i=e.accept({statusCode:200,extraHeaders:t,body:s});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,i.message,200)}).catch(s=>{if(this.logger.error(s.message),this.logger.error("Failed to handle to re-INVITE request"),!this.dialog)throw new Error("Dialog undefined.");if(this.logger.error(this.dialog.signalingState),this.dialog.signalingState!==N.Stable)this.rollbackOffer().then(()=>{const t=e.reject({statusCode:488});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,t.message,488)}).catch(s=>{this.logger.error(s.message),this.logger.error("Failed to rollback offer on re-INVITE request");const i=e.reject({statusCode:488});if(this.state!==G.Terminated){if(!this.dialog)throw new Error("Dialog undefined.");[].push("Reason: "+this.getReasonHeaderValue(500,"Internal Server Error")),this.dialog.bye(void 0,{extraHeaders:t}),this.stateTransition(G.Terminated)}this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,i.message,488)});else{const t=e.reject({statusCode:488});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,t.message,488)}})}onMessageRequest(e){if(this.logger.log("Session.onMessageRequest"),this.state===G.Established)if(this.delegate&&this.delegate.onMessage){const t=new L(e);this.delegate.onMessage(t)}else e.accept();else this.logger.error(`MESSAGE received while in state ${this.state}, dropping request`)}onNotifyRequest(e){if(this.logger.log("Session.onNotifyRequest"),this.state===G.Established)if(this.onNotify){const t=new B(e);this.onNotify(t)}else if(this.delegate&&this.delegate.onNotify){const t=new B(e);this.delegate.onNotify(t)}else e.accept();else this.logger.error(`NOTIFY received while in state ${this.state}, dropping request`)}onPrackRequest(e){if(this.logger.log("Session.onPrackRequest"),this.state===G.Established)throw new Error("Unimplemented.");this.logger.error(`PRACK received while in state ${this.state}, dropping request`)}onReferRequest(e){if(this.logger.log("Session.onReferRequest"),this.state!==G.Established)return void this.logger.error(`REFER received while in state ${this.state}, dropping request`);if(!e.message.hasHeader("refer-to"))return this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting."),void e.reject();const t=new V(e,this);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(t):(this.logger.log("No delegate available to handle REFER, automatically accepting and following."),t.accept().then(()=>t.makeInviter(this._referralInviterOptions).invite()).catch(e=>{this.logger.error(e.message)}))}generateResponseOfferAnswer(e,t){if(this.dialog)return this.generateResponseOfferAnswerInDialog(t);const s=q(e.message);return s&&"session"===s.contentDisposition?this.setOfferAndGetAnswer(s,t):this.getOffer(t)}generateResponseOfferAnswerInDialog(e){if(!this.dialog)throw new Error("Dialog undefined.");switch(this.dialog.signalingState){case N.Initial:return this.getOffer(e);case N.HaveLocalOffer:return Promise.resolve(void 0);case N.HaveRemoteOffer:if(!this.dialog.offer)throw new Error(`Session offer undefined in signaling state ${this.dialog.signalingState}.`);return this.setOfferAndGetAnswer(this.dialog.offer,e);case N.Stable:return this.state!==G.Established?Promise.resolve(void 0):this.getOffer(e);case N.Closed:default:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`)}}getOffer(e){const t=this.setupSessionDescriptionHandler(),s=e.sessionDescriptionHandlerOptions,i=e.sessionDescriptionHandlerModifiers;try{return t.getDescription(s,i).then(e=>k(e)).catch(e=>{this.logger.error("Session.getOffer: SDH getDescription rejected...");const t=e instanceof Error?e:new Error("Session.getOffer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.getOffer: SDH getDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}rollbackOffer(){const e=this.setupSessionDescriptionHandler();if(void 0===e.rollbackDescription)return Promise.resolve();try{return e.rollbackDescription().catch(e=>{this.logger.error("Session.rollbackOffer: SDH rollbackDescription rejected...");const t=e instanceof Error?e:new Error("Session.rollbackOffer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.rollbackOffer: SDH rollbackDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}setAnswer(e,t){const s=this.setupSessionDescriptionHandler(),i=t.sessionDescriptionHandlerOptions,r=t.sessionDescriptionHandlerModifiers;try{if(!s.hasDescription(e.contentType))return Promise.reject(new o)}catch(e){this.logger.error("Session.setAnswer: SDH hasDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}try{return s.setDescription(e.content,i,r).catch(e=>{this.logger.error("Session.setAnswer: SDH setDescription rejected...");const t=e instanceof Error?e:new Error("Session.setAnswer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.setAnswer: SDH setDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}setOfferAndGetAnswer(e,t){const s=this.setupSessionDescriptionHandler(),i=t.sessionDescriptionHandlerOptions,r=t.sessionDescriptionHandlerModifiers;try{if(!s.hasDescription(e.contentType))return Promise.reject(new o)}catch(e){this.logger.error("Session.setOfferAndGetAnswer: SDH hasDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}try{return s.setDescription(e.content,i,r).then(()=>s.getDescription(i,r)).then(e=>k(e)).catch(e=>{this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription rejected...");const t=e instanceof Error?e:new Error("Session.setOfferAndGetAnswer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}setSessionDescriptionHandler(e){if(this._sessionDescriptionHandler)throw new Error("Session description handler defined.");this._sessionDescriptionHandler=e}setupSessionDescriptionHandler(){var e;return this._sessionDescriptionHandler||(this._sessionDescriptionHandler=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions),(null===(e=this.delegate)||void 0===e?void 0:e.onSessionDescriptionHandler)&&this.delegate.onSessionDescriptionHandler(this._sessionDescriptionHandler,!1)),this._sessionDescriptionHandler}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case G.Initial:e!==G.Establishing&&e!==G.Established&&e!==G.Terminating&&e!==G.Terminated&&t();break;case G.Establishing:e!==G.Established&&e!==G.Terminating&&e!==G.Terminated&&t();break;case G.Established:e!==G.Terminating&&e!==G.Terminated&&t();break;case G.Terminating:e!==G.Terminated&&t();break;case G.Terminated:t();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log(`Session ${this.id} transitioned to state ${this._state}`),this._stateEventEmitter.emit(this._state),e===G.Terminated&&this.dispose()}copyRequestOptions(e={}){return{extraHeaders:e.extraHeaders?e.extraHeaders.slice():void 0,body:e.body?{contentDisposition:e.body.contentDisposition||"render",contentType:e.body.contentType||"text/plain",content:e.body.content||""}:void 0}}getReasonHeaderValue(e,t){const s=e;let i=y(e);return!i&&t&&(i=t),"SIP;cause="+s+';text="'+i+'"'}referExtraHeaders(e){const t=[];return t.push("Referred-By: <"+this.userAgent.configuration.uri+">"),t.push("Contact: "+this._contact),t.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),t.push("Refer-To: "+e),t}referToString(e){let t;if(e instanceof m)t=e.toString();else{if(!e.dialog)throw new Error("Dialog undefined.");const s=e.remoteIdentity.friendlyName,i=e.dialog.remoteTarget.toString(),r=e.dialog.callId,n=e.dialog.remoteTag,o=e.dialog.localTag;t=`"${s}" <${i}?Replaces=${encodeURIComponent(`${r};to-tag=${n};from-tag=${o}`)}>`}return t}}!function(e){e.Required="Required",e.Supported="Supported",e.Unsupported="Unsupported"}(K||(K={}));const Y={"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};class Z extends W{constructor(e,t){super(e),this.incomingInviteRequest=t,this.disposed=!1,this.expiresTimer=void 0,this.isCanceled=!1,this.rel100="none",this.rseq=Math.floor(1e4*Math.random()),this.userNoAnswerTimer=void 0,this.waitingForPrack=!1,this.logger=e.getLogger("sip.Invitation");const s=this.incomingInviteRequest.message,i=s.getHeader("require");i&&i.toLowerCase().includes("100rel")&&(this.rel100="required");const r=s.getHeader("supported");if(r&&r.toLowerCase().includes("100rel")&&(this.rel100="supported"),s.toTag=t.toTag,"string"!=typeof s.toTag)throw new TypeError("toTag should have been a string.");if(this.userNoAnswerTimer=setTimeout(()=>{t.reject({statusCode:480}),this.stateTransition(G.Terminated)},this.userAgent.configuration.noAnswerTimeout?1e3*this.userAgent.configuration.noAnswerTimeout:6e4),s.hasHeader("expires")){const e=1e3*Number(s.getHeader("expires")||0);this.expiresTimer=setTimeout(()=>{this.state===G.Initial&&(t.reject({statusCode:487}),this.stateTransition(G.Terminated))},e)}const n=this.request.getHeader("P-Asserted-Identity");n&&(this._assertedIdentity=b.nameAddrHeaderParse(n)),this._contact=this.userAgent.contact.toString();const o=s.parseHeader("Content-Disposition");o&&"render"===o.type&&(this._renderbody=s.body,this._rendertype=s.getHeader("Content-Type")),this._id=s.callId+s.fromTag,this.userAgent._sessions[this._id]=this}dispose(){if(this.disposed)return Promise.resolve();switch(this.disposed=!0,this.expiresTimer&&(clearTimeout(this.expiresTimer),this.expiresTimer=void 0),this.userNoAnswerTimer&&(clearTimeout(this.userNoAnswerTimer),this.userNoAnswerTimer=void 0),this.prackNeverArrived(),this.state){case G.Initial:case G.Establishing:return this.reject().then(()=>super.dispose());case G.Established:case G.Terminating:case G.Terminated:return super.dispose();default:throw new Error("Unknown state.")}}get autoSendAnInitialProvisionalResponse(){return"required"!==this.rel100}get body(){return this.incomingInviteRequest.message.body}get localIdentity(){return this.request.to}get remoteIdentity(){return this.request.from}get request(){return this.incomingInviteRequest.message}accept(e={}){if(this.logger.log("Invitation.accept"),this.state!==G.Initial){const e=new Error("Invalid session state "+this.state);return this.logger.error(e.message),Promise.reject(e)}return e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),this.stateTransition(G.Establishing),this.sendAccept().then(({message:e,session:t})=>{t.delegate={onAck:e=>this.onAckRequest(e),onAckTimeout:()=>this.onAckTimeout(),onBye:e=>this.onByeRequest(e),onInfo:e=>this.onInfoRequest(e),onInvite:e=>this.onInviteRequest(e),onMessage:e=>this.onMessageRequest(e),onNotify:e=>this.onNotifyRequest(e),onPrack:e=>this.onPrackRequest(e),onRefer:e=>this.onReferRequest(e)},this._dialog=t,this.stateTransition(G.Established),this._replacee&&this._replacee._bye()}).catch(e=>this.handleResponseError(e))}progress(e={}){if(this.logger.log("Invitation.progress"),this.state!==G.Initial){const e=new Error("Invalid session state "+this.state);return this.logger.error(e.message),Promise.reject(e)}const t=e.statusCode||180;if(t<100||t>199)throw new TypeError("Invalid statusCode: "+t);return e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),this.waitingForPrack?(this.logger.warn("Unexpected call for progress while waiting for prack, ignoring"),Promise.resolve()):100===e.statusCode?this.sendProgressTrying().then(()=>{}).catch(e=>this.handleResponseError(e)):"required"===this.rel100||"supported"===this.rel100&&e.rel100||"supported"===this.rel100&&this.userAgent.configuration.sipExtension100rel===K.Required?this.sendProgressReliableWaitForPrack(e).then(()=>{}).catch(e=>this.handleResponseError(e)):this.sendProgress(e).then(()=>{}).catch(e=>this.handleResponseError(e))}reject(e={}){if(this.logger.log("Invitation.reject"),this.state!==G.Initial&&this.state!==G.Establishing){const e=new Error("Invalid session state "+this.state);return this.logger.error(e.message),Promise.reject(e)}const t=e.statusCode||480,s=e.reasonPhrase?e.reasonPhrase:y(t),i=e.extraHeaders||[];if(t<300||t>699)throw new TypeError("Invalid statusCode: "+t);const r=e.body?k(e.body):void 0;return t<400?this.incomingInviteRequest.redirect([],{statusCode:t,reasonPhrase:s,extraHeaders:i,body:r}):this.incomingInviteRequest.reject({statusCode:t,reasonPhrase:s,extraHeaders:i,body:r}),this.stateTransition(G.Terminated),Promise.resolve()}_onCancel(e){this.logger.log("Invitation._onCancel"),this.state===G.Initial||this.state===G.Establishing?(this.isCanceled=!0,this.incomingInviteRequest.reject({statusCode:487}),this.stateTransition(G.Terminated)):this.logger.error(`CANCEL received while in state ${this.state}, dropping request`)}handlePrackOfferAnswer(e){if(!this.dialog)throw new Error("Dialog undefined.");const t=q(e.message);if(!t||"session"!==t.contentDisposition)return Promise.resolve(void 0);const s={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers};switch(this.dialog.signalingState){case N.Initial:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case N.Stable:return this.setAnswer(t,s).then(()=>{});case N.HaveLocalOffer:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case N.HaveRemoteOffer:return this.setOfferAndGetAnswer(t,s);case N.Closed:default:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`)}}handleResponseError(e){let t=480;if(e instanceof Error?this.logger.error(e.message):this.logger.error(e),e instanceof o?(this.logger.error("A session description handler occurred while sending response (content type unsupported"),t=415):e instanceof c?this.logger.error("A session description handler occurred while sending response"):e instanceof h?this.logger.error("Session ended before response could be formulated and sent (while waiting for PRACK)"):e instanceof M&&this.logger.error("Session changed state before response could be formulated and sent"),this.state===G.Initial||this.state===G.Establishing)try{this.incomingInviteRequest.reject({statusCode:t}),this.stateTransition(G.Terminated)}catch(e){throw this.logger.error("An error occurred attempting to reject the request while handling another error"),e}if(!this.isCanceled)throw e;this.logger.warn("An error occurred while attempting to formulate and send a response to an incoming INVITE. However a CANCEL was received and processed while doing so which can (and often does) result in errors occurring as the session terminates in the meantime. Said error is being ignored.")}onAckTimeout(){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(G.Terminated)}sendAccept(){const e={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers};return this.waitingForPrack?this.waitForArrivalOfPrack().then(()=>clearTimeout(this.userNoAnswerTimer)).then(()=>this.generateResponseOfferAnswer(this.incomingInviteRequest,e)).then(e=>this.incomingInviteRequest.accept({statusCode:200,body:e})):(clearTimeout(this.userNoAnswerTimer),this.generateResponseOfferAnswer(this.incomingInviteRequest,e).then(e=>this.incomingInviteRequest.accept({statusCode:200,body:e})))}sendProgress(e={}){const t=e.statusCode||180,s=e.reasonPhrase,i=(e.extraHeaders||[]).slice(),r=e.body?k(e.body):void 0;if(183===t&&!r)return this.sendProgressWithSDP(e);try{const e=this.incomingInviteRequest.progress({statusCode:t,reasonPhrase:s,extraHeaders:i,body:r});return this._dialog=e.session,Promise.resolve(e)}catch(e){return Promise.reject(e)}}sendProgressWithSDP(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},s=e.statusCode||183,i=e.reasonPhrase,r=(e.extraHeaders||[]).slice();return this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then(e=>this.incomingInviteRequest.progress({statusCode:s,reasonPhrase:i,extraHeaders:r,body:e})).then(e=>(this._dialog=e.session,e))}sendProgressReliable(e={}){return e.extraHeaders=(e.extraHeaders||[]).slice(),e.extraHeaders.push("Require: 100rel"),e.extraHeaders.push("RSeq: "+Math.floor(1e4*Math.random())),this.sendProgressWithSDP(e)}sendProgressReliableWaitForPrack(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},s=e.statusCode||183,i=e.reasonPhrase,r=(e.extraHeaders||[]).slice();let n;return r.push("Require: 100rel"),r.push("RSeq: "+this.rseq++),new Promise((e,o)=>{this.waitingForPrack=!0,this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then(e=>(n=e,this.incomingInviteRequest.progress({statusCode:s,reasonPhrase:i,extraHeaders:r,body:n}))).then(t=>{let a,c;this._dialog=t.session,t.session.delegate={onPrack:s=>{a=s,clearTimeout(d),clearTimeout(u),this.waitingForPrack&&(this.waitingForPrack=!1,this.handlePrackOfferAnswer(a).then(s=>{try{c=a.accept({statusCode:200,body:s}),this.prackArrived(),e({prackRequest:a,prackResponse:c,progressResponse:t})}catch(e){o(e)}}).catch(e=>o(e)))}};const d=setTimeout(()=>{this.waitingForPrack&&(this.waitingForPrack=!1,this.logger.warn("No PRACK received, rejecting INVITE."),clearTimeout(u),this.reject({statusCode:504}).then(()=>o(new h)).catch(e=>o(e)))},64*U.T1),l=()=>{try{this.incomingInviteRequest.progress({statusCode:s,reasonPhrase:i,extraHeaders:r,body:n})}catch(e){return this.waitingForPrack=!1,void o(e)}u=setTimeout(l,g*=2)};let g=U.T1,u=setTimeout(l,g)}).catch(e=>{this.waitingForPrack=!1,o(e)})})}sendProgressTrying(){try{const e=this.incomingInviteRequest.trying();return Promise.resolve(e)}catch(e){return Promise.reject(e)}}waitForArrivalOfPrack(){if(this.waitingForPrackPromise)throw new Error("Already waiting for PRACK");return this.waitingForPrackPromise=new Promise((e,t)=>{this.waitingForPrackResolve=e,this.waitingForPrackReject=t}),this.waitingForPrackPromise}prackArrived(){this.waitingForPrackResolve&&this.waitingForPrackResolve(),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0}prackNeverArrived(){this.waitingForPrackReject&&this.waitingForPrackReject(new h),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0}}class J extends W{constructor(e,t,s={}){super(e,s),this.disposed=!1,this.earlyMedia=!1,this.earlyMediaSessionDescriptionHandlers=new Map,this.isCanceled=!1,this.inviteWithoutSdp=!1,this.logger=e.getLogger("sip.Inviter"),this.earlyMedia=void 0!==s.earlyMedia?s.earlyMedia:this.earlyMedia,this.fromTag=E(),this.inviteWithoutSdp=void 0!==s.inviteWithoutSdp?s.inviteWithoutSdp:this.inviteWithoutSdp;const i=Object.assign({},s);i.params=Object.assign({},s.params);const r=s.anonymous||!1,n=e.contact.toString({anonymous:r,outbound:r?!e.contact.tempGruu:!e.contact.pubGruu});r&&e.configuration.uri&&(i.params.fromDisplayName="Anonymous",i.params.fromUri="sip:anonymous@anonymous.invalid");let o=e.userAgentCore.configuration.aor;if(i.params.fromUri&&(o="string"==typeof i.params.fromUri?b.URIParse(i.params.fromUri):i.params.fromUri),!o)throw new TypeError("Invalid from URI: "+i.params.fromUri);let a=t;if(i.params.toUri&&(a="string"==typeof i.params.toUri?b.URIParse(i.params.toUri):i.params.toUri),!a)throw new TypeError("Invalid to URI: "+i.params.toUri);const c=Object.assign({},i.params);c.fromTag=this.fromTag;const h=(i.extraHeaders||[]).slice();r&&e.configuration.uri&&(h.push("P-Preferred-Identity: "+e.configuration.uri.toString()),h.push("Privacy: id")),h.push("Contact: "+n),h.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),e.configuration.sipExtension100rel===K.Required&&h.push("Require: 100rel"),e.configuration.sipExtensionReplaces===K.Required&&h.push("Require: replaces"),i.extraHeaders=h;this.outgoingRequestMessage=e.userAgentCore.makeOutgoingRequestMessage(j.INVITE,t,o,a,c,h,void 0),this._contact=n,this._referralInviterOptions=i,this._renderbody=s.renderbody,this._rendertype=s.rendertype,s.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=s.sessionDescriptionHandlerModifiers),s.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=s.sessionDescriptionHandlerOptions),s.sessionDescriptionHandlerModifiersReInvite&&(this.sessionDescriptionHandlerModifiersReInvite=s.sessionDescriptionHandlerModifiersReInvite),s.sessionDescriptionHandlerOptionsReInvite&&(this.sessionDescriptionHandlerOptionsReInvite=s.sessionDescriptionHandlerOptionsReInvite),this._id=this.outgoingRequestMessage.callId+this.fromTag,this.userAgent._sessions[this._id]=this}dispose(){if(this.disposed)return Promise.resolve();switch(this.disposed=!0,this.disposeEarlyMedia(),this.state){case G.Initial:case G.Establishing:return this.cancel().then(()=>super.dispose());case G.Established:case G.Terminating:case G.Terminated:return super.dispose();default:throw new Error("Unknown state.")}}get body(){return this.outgoingRequestMessage.body}get localIdentity(){return this.outgoingRequestMessage.from}get remoteIdentity(){return this.outgoingRequestMessage.to}get request(){return this.outgoingRequestMessage}cancel(e={}){if(this.logger.log("Inviter.cancel"),this.state!==G.Initial&&this.state!==G.Establishing){const e=new Error("Invalid session state "+this.state);return this.logger.error(e.message),Promise.reject(e)}if(this.isCanceled=!0,this.stateTransition(G.Terminating),this.outgoingInviteRequest){let t;e.statusCode&&e.reasonPhrase&&(t=function(e,t){if(e&&e<200||e>699)throw new TypeError("Invalid statusCode: "+e);if(e){return"SIP;cause="+e+';text="'+(y(e)||t)+'"'}}(e.statusCode,e.reasonPhrase)),this.outgoingInviteRequest.cancel(t,e)}else this.logger.warn("Canceled session before INVITE was sent"),this.stateTransition(G.Terminated);return Promise.resolve()}invite(e={}){if(this.logger.log("Inviter.invite"),this.state!==G.Initial)return super.invite(e);if(e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),e.withoutSdp||this.inviteWithoutSdp)return this._renderbody&&this._rendertype&&(this.outgoingRequestMessage.body={contentType:this._rendertype,body:this._renderbody}),this.stateTransition(G.Establishing),Promise.resolve(this.sendInvite(e));const t={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.getOffer(t).then(t=>(this.outgoingRequestMessage.body={body:t.content,contentType:t.contentType},this.stateTransition(G.Establishing),this.sendInvite(e))).catch(e=>{throw this.logger.log(e.message),this.stateTransition(G.Terminated),e})}sendInvite(e={}){return this.outgoingInviteRequest=this.userAgent.userAgentCore.invite(this.outgoingRequestMessage,{onAccept:t=>this.dialog?(this.logger.log("Additional confirmed dialog, sending ACK and BYE"),void this.ackAndBye(t)):this.isCanceled?(this.logger.log("Canceled session accepted, sending ACK and BYE"),this.ackAndBye(t),void this.stateTransition(G.Terminated)):(this.notifyReferer(t),void this.onAccept(t).then(()=>{this.disposeEarlyMedia()}).catch(()=>{this.disposeEarlyMedia()}).then(()=>{e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t)})),onProgress:t=>{this.isCanceled||(this.notifyReferer(t),this.onProgress(t).catch(()=>{this.disposeEarlyMedia()}).then(()=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)}))},onRedirect:t=>{this.notifyReferer(t),this.onRedirect(t),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t)},onReject:t=>{this.notifyReferer(t),this.onReject(t),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t)},onTrying:t=>{this.notifyReferer(t),this.onTrying(t),e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}}),this.outgoingInviteRequest}disposeEarlyMedia(){this.earlyMediaSessionDescriptionHandlers.forEach(e=>{e.close()}),this.earlyMediaSessionDescriptionHandlers.clear()}notifyReferer(e){if(!this._referred)return;if(!(this._referred instanceof W))throw new Error("Referred session not instance of session");if(!this._referred.dialog)return;if(!e.message.statusCode)throw new Error("Status code undefined.");if(!e.message.reasonPhrase)throw new Error("Reason phrase undefined.");const t=`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:t}}).delegate={onReject:()=>{this._referred=void 0}}}onAccept(e){if(this.logger.log("Inviter.onAccept"),this.state!==G.Establishing)return this.logger.error(`Accept received while in state ${this.state}, dropping response`),Promise.reject(new Error("Invalid session state "+this.state));const t=e.message,s=e.session;switch(t.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=b.nameAddrHeaderParse(t.getHeader("P-Asserted-Identity"))),s.delegate={onAck:e=>this.onAckRequest(e),onBye:e=>this.onByeRequest(e),onInfo:e=>this.onInfoRequest(e),onInvite:e=>this.onInviteRequest(e),onMessage:e=>this.onMessageRequest(e),onNotify:e=>this.onNotifyRequest(e),onPrack:e=>this.onPrackRequest(e),onRefer:e=>this.onReferRequest(e)},this._dialog=s,s.signalingState){case N.Initial:case N.HaveLocalOffer:return this.logger.error("Received 2xx response to INVITE without a session description"),this.ackAndBye(e,400,"Missing session description"),this.stateTransition(G.Terminated),Promise.reject(new Error("Bad Media Description"));case N.HaveRemoteOffer:{if(!this._dialog.offer)throw new Error(`Session offer undefined in signaling state ${this._dialog.signalingState}.`);const t={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setOfferAndGetAnswer(this._dialog.offer,t).then(t=>{e.ack({body:t}),this.stateTransition(G.Established)}).catch(t=>{throw this.ackAndBye(e,488,"Invalid session description"),this.stateTransition(G.Terminated),t})}case N.Stable:{if(this.earlyMediaSessionDescriptionHandlers.size>0){const t=this.earlyMediaSessionDescriptionHandlers.get(s.id);if(!t)throw new Error("Session description handler undefined.");return this.setSessionDescriptionHandler(t),this.earlyMediaSessionDescriptionHandlers.delete(s.id),e.ack(),this.stateTransition(G.Established),Promise.resolve()}if(this.earlyMediaDialog){if(this.earlyMediaDialog!==s){if(this.earlyMedia){const e="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 behavior 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(e)}const t=new Error("Early media dialog does not equal confirmed dialog, terminating session");return this.logger.error(t.message),this.ackAndBye(e,488,"Not Acceptable Here"),this.stateTransition(G.Terminated),Promise.reject(t)}return e.ack(),this.stateTransition(G.Established),Promise.resolve()}const t=s.answer;if(!t)throw new Error("Answer is undefined.");const i={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(t,i).then(()=>{let t;this._renderbody&&this._rendertype&&(t={body:{contentDisposition:"render",contentType:this._rendertype,content:this._renderbody}}),e.ack(t),this.stateTransition(G.Established)}).catch(t=>{throw this.logger.error(t.message),this.ackAndBye(e,488,"Not Acceptable Here"),this.stateTransition(G.Terminated),t})}case N.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onProgress(e){var t;if(this.logger.log("Inviter.onProgress"),this.state!==G.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.");const s=e.message,i=e.session;s.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=b.nameAddrHeaderParse(s.getHeader("P-Asserted-Identity")));const r=s.getHeader("require"),n=s.getHeader("rseq"),o=!!(r&&r.includes("100rel")&&n?Number(n):void 0),a=[];switch(o&&a.push("RAck: "+s.getHeader("rseq")+" "+s.getHeader("cseq")),i.signalingState){case N.Initial:return o&&(this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."),e.prack({extraHeaders:a})),Promise.resolve();case N.HaveLocalOffer:return o&&e.prack({extraHeaders:a}),Promise.resolve();case N.HaveRemoteOffer:if(!o)return this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response."),Promise.resolve();{const r=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions||{});return(null===(t=this.delegate)||void 0===t?void 0:t.onSessionDescriptionHandler)&&this.delegate.onSessionDescriptionHandler(r,!0),this.earlyMediaSessionDescriptionHandlers.set(i.id,r),r.setDescription(s.body,this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers).then(()=>r.getDescription(this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers)).then(t=>{const s={contentDisposition:"session",contentType:t.contentType,content:t.body};e.prack({extraHeaders:a,body:s})}).catch(e=>{throw this.stateTransition(G.Terminated),e})}case N.Stable:if(o&&e.prack({extraHeaders:a}),this.earlyMedia&&!this.earlyMediaDialog){this.earlyMediaDialog=i;const e=i.answer;if(!e)throw new Error("Answer is undefined.");const t={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(e,t).catch(e=>{throw this.stateTransition(G.Terminated),e})}return Promise.resolve();case N.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onRedirect(e){this.logger.log("Inviter.onRedirect"),this.state===G.Establishing||this.state===G.Terminating?this.stateTransition(G.Terminated):this.logger.error(`Redirect received while in state ${this.state}, dropping response`)}onReject(e){this.logger.log("Inviter.onReject"),this.state===G.Establishing||this.state===G.Terminating?this.stateTransition(G.Terminated):this.logger.error(`Reject received while in state ${this.state}, dropping response`)}onTrying(e){this.logger.log("Inviter.onTrying"),this.state===G.Establishing||this.logger.error(`Trying received while in state ${this.state}, dropping response`)}}class z{constructor(e,t,s,i="text/plain",r={}){this.logger=e.getLogger("sip.Messager"),r.params=r.params||{};let n=e.userAgentCore.configuration.aor;if(r.params.fromUri&&(n="string"==typeof r.params.fromUri?b.URIParse(r.params.fromUri):r.params.fromUri),!n)throw new TypeError("Invalid from URI: "+r.params.fromUri);let o=t;if(r.params.toUri&&(o="string"==typeof r.params.toUri?b.URIParse(r.params.toUri):r.params.toUri),!o)throw new TypeError("Invalid to URI: "+r.params.toUri);const a=r.params?Object.assign({},r.params):{},c=(r.extraHeaders||[]).slice(),h={contentDisposition:"render",contentType:i,content:s};this.request=e.userAgentCore.makeOutgoingRequestMessage(j.MESSAGE,t,n,o,a,c,h),this.userAgent=e}message(e={}){return this.userAgent.userAgentCore.request(this.request,e.requestDelegate),Promise.resolve()}}var X,Q,ee,te,se,ie,re,ne;!function(e){e.Initial="Initial",e.Published="Published",e.Unpublished="Unpublished",e.Terminated="Terminated"}(X||(X={}));class oe{constructor(e,t,s,i={}){this.disposed=!1,this._state=X.Initial,this._stateEventEmitter=new g,this.userAgent=e,i.extraHeaders=(i.extraHeaders||[]).slice(),i.contentType=i.contentType||"text/plain","number"!=typeof i.expires||i.expires%1!=0?i.expires=3600:i.expires=Number(i.expires),"boolean"!=typeof i.unpublishOnClose&&(i.unpublishOnClose=!0),this.target=t,this.event=s,this.options=i,this.pubRequestExpires=i.expires,this.logger=e.getLogger("sip.Publisher");const r=i.params||{},n=r.fromUri?r.fromUri:e.userAgentCore.configuration.aor,o=r.toUri?r.toUri:t;let a;if(i.body&&i.contentType){a={contentDisposition:"render",contentType:i.contentType,content:i.body}}const c=(i.extraHeaders||[]).slice();this.request=e.userAgentCore.makeOutgoingRequestMessage(j.PUBLISH,t,n,o,r,c,a),this.id=this.target.toString()+":"+this.event,this.userAgent._publishers[this.id]=this}dispose(){return this.disposed?Promise.resolve():(this.disposed=!0,this.logger.log(`Publisher ${this.id} in state ${this.state} is being disposed`),delete this.userAgent._publishers[this.id],this.options.unpublishOnClose&&this.state===X.Published?this.unpublish():(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,this.pubRequestExpires=0,this.pubRequestEtag=void 0,Promise.resolve()))}get state(){return this._state}get stateChange(){return this._stateEventEmitter}publish(e,t={}){if(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.options.body=e,this.pubRequestBody=this.options.body,0===this.pubRequestExpires){if(void 0===this.options.expires)throw new Error("Expires undefined.");this.pubRequestExpires=this.options.expires,this.pubRequestEtag=void 0}return this.sendPublishRequest(),Promise.resolve()}unpublish(e={}){return this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,this.pubRequestExpires=0,void 0!==this.pubRequestEtag&&this.sendPublishRequest(),Promise.resolve()}receiveResponse(e){const t=e.statusCode||0;switch(!0){case/^1[0-9]{2}$/.test(t.toString()):break;case/^2[0-9]{2}$/.test(t.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")){const t=Number(e.getHeader("Expires"));"number"==typeof t&&t>=0&&t<=this.pubRequestExpires?this.pubRequestExpires=t: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(()=>this.refreshRequest(),900*this.pubRequestExpires),this.stateTransition(X.Published)):this.stateTransition(X.Unpublished);break;case/^412$/.test(t.toString()):if(void 0!==this.pubRequestEtag&&0!==this.pubRequestExpires){if(this.logger.warn("412 response to PUBLISH, recovering"),this.pubRequestEtag=void 0,void 0===this.options.body)throw new Error("Body undefined.");this.publish(this.options.body)}else this.logger.warn("412 response to PUBLISH, recovery failed"),this.pubRequestExpires=0,this.stateTransition(X.Unpublished),this.stateTransition(X.Terminated);break;case/^423$/.test(t.toString()):if(0!==this.pubRequestExpires&&e.hasHeader("Min-Expires")){const t=Number(e.getHeader("Min-Expires"));if("number"==typeof t||t>this.pubRequestExpires){if(this.logger.warn("423 code in response to PUBLISH, adjusting the Expires value and trying to recover"),this.pubRequestExpires=t,void 0===this.options.body)throw new Error("Body undefined.");this.publish(this.options.body)}else this.logger.warn("Bad 423 response Min-Expires header received for PUBLISH"),this.pubRequestExpires=0,this.stateTransition(X.Unpublished),this.stateTransition(X.Terminated)}else this.logger.warn("423 response to PUBLISH, recovery failed"),this.pubRequestExpires=0,this.stateTransition(X.Unpublished),this.stateTransition(X.Terminated);break;default:this.pubRequestExpires=0,this.stateTransition(X.Unpublished),this.stateTransition(X.Terminated)}0===this.pubRequestExpires&&(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,this.pubRequestEtag=void 0)}send(){return this.userAgent.userAgentCore.publish(this.request,{onAccept:e=>this.receiveResponse(e.message),onProgress:e=>this.receiveResponse(e.message),onRedirect:e=>this.receiveResponse(e.message),onReject:e=>this.receiveResponse(e.message),onTrying:e=>this.receiveResponse(e.message)})}refreshRequest(){if(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,void 0===this.pubRequestEtag)throw new Error("Etag undefined");if(0===this.pubRequestExpires)throw new Error("Expires zero");this.sendPublishRequest()}sendPublishRequest(){const e=Object.assign({},this.options);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);const t=this.target,s=this.options.params||{};let i,r;if(void 0!==this.pubRequestBody){if(void 0===this.options.contentType)throw new Error("Content type undefined.");i={body:this.pubRequestBody,contentType:this.options.contentType}}return i&&(r=k(i)),this.request=this.userAgent.userAgentCore.makeOutgoingRequestMessage(j.PUBLISH,t,s.fromUri?s.fromUri:this.userAgent.userAgentCore.configuration.aor,s.toUri?s.toUri:this.target,s,e.extraHeaders,r),this.send()}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case X.Initial:e!==X.Published&&e!==X.Unpublished&&e!==X.Terminated&&t();break;case X.Published:e!==X.Unpublished&&e!==X.Terminated&&t();break;case X.Unpublished:e!==X.Published&&e!==X.Terminated&&t();break;case X.Terminated:t();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log("Publication transitioned to state "+this._state),this._stateEventEmitter.emit(this._state),e===X.Terminated&&this.dispose()}}!function(e){e.Initial="Initial",e.Registered="Registered",e.Unregistered="Unregistered",e.Terminated="Terminated"}(Q||(Q={}));class ae{constructor(e,t={}){this.disposed=!1,this._contacts=[],this._retryAfter=void 0,this._state=Q.Initial,this._waiting=!1,this._stateEventEmitter=new g,this._waitingEventEmitter=new g,this.userAgent=e;const s=e.configuration.uri.clone();if(s.user=void 0,this.options=Object.assign(Object.assign(Object.assign({},ae.defaultOptions()),{registrar:s}),ae.stripUndefinedProperties(t)),this.options.extraContactHeaderParams=(this.options.extraContactHeaderParams||[]).slice(),this.options.extraHeaders=(this.options.extraHeaders||[]).slice(),!this.options.registrar)throw new Error("Registrar undefined.");if(this.options.registrar=this.options.registrar.clone(),this.options.regId&&!this.options.instanceId?this.options.instanceId=ae.newUUID():!this.options.regId&&this.options.instanceId&&(this.options.regId=1),this.options.instanceId&&-1===b.parse(this.options.instanceId,"uuid"))throw new Error("Invalid instanceId.");if(this.options.regId&&this.options.regId<0)throw new Error("Invalid regId.");const i=this.options.registrar,r=this.options.params&&this.options.params.fromUri||e.userAgentCore.configuration.aor,n=this.options.params&&this.options.params.toUri||e.configuration.uri,o=this.options.params||{},a=(t.extraHeaders||[]).slice();if(this.request=e.userAgentCore.makeOutgoingRequestMessage(j.REGISTER,i,r,n,o,a,void 0),this.expires=this.options.expires||ae.defaultExpires,this.expires<0)throw new Error("Invalid expires.");this.logger=e.getLogger("sip.Registerer"),this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach(e=>{const t=this.options[e];switch(e){case"registrar":this.logger.log("\xb7 "+e+": "+t);break;default:this.logger.log("\xb7 "+e+": "+JSON.stringify(t))}})),this.id=this.request.callId+this.request.from.parameters.tag,this.userAgent._registerers[this.id]=this}static defaultOptions(){return{expires:ae.defaultExpires,extraContactHeaderParams:[],extraHeaders:[],logConfiguration:!0,instanceId:"",params:{},regId:0,registrar:new m("sip","anonymous","anonymous.invalid")}}static newUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.floor(16*Math.random());return("x"===e?t:t%4+8).toString(16)})}static stripUndefinedProperties(e){return Object.keys(e).reduce((t,s)=>(void 0!==e[s]&&(t[s]=e[s]),t),{})}get contacts(){return this._contacts.slice()}get retryAfter(){return this._retryAfter}get state(){return this._state}get stateChange(){return this._stateEventEmitter}dispose(){return this.disposed?Promise.resolve():(this.disposed=!0,this.logger.log(`Registerer ${this.id} in state ${this.state} is being disposed`),delete this.userAgent._registerers[this.id],new Promise(e=>{const t=()=>{if(!this.waiting&&this._state===Q.Registered)return this.stateChange.addListener(()=>{this.terminated(),e()},{once:!0}),void this.unregister();this.terminated(),e()};this.waiting?this.waitingChange.addListener(()=>{t()},{once:!0}):t()}))}register(e={}){if(this.state===Q.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();const e=new a("REGISTER request already in progress, waiting for final response");return Promise.reject(e)}e.requestOptions&&(this.options=Object.assign(Object.assign({},this.options),e.requestOptions));const t=(this.options.extraHeaders||[]).slice();t.push("Contact: "+this.generateContactHeader(this.expires)),t.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=t,this.waitingToggle(!0);const s=this.userAgent.userAgentCore.register(this.request,{onAccept:t=>{let s;t.message.hasHeader("expires")&&(s=Number(t.message.getHeader("expires"))),this._contacts=t.message.getHeaders("contact");let i,r=this._contacts.length;if(!r)return this.logger.error("No Contact header in response to REGISTER, dropping response."),void this.unregistered();for(;r--;){if(i=t.message.parseHeader("contact",r),!i)throw new Error("Contact undefined");if(i.uri.user===this.userAgent.contact.uri.user&&i.uri.host===this.userAgent.contact.uri.host&&i.uri.port===this.userAgent.contact.uri.port){s=Number(i.getParam("expires"));break}i=void 0}if(void 0===i)return this.logger.error("No Contact header pointing to us, dropping response"),this.unregistered(),void this.waitingToggle(!1);if(void 0===s)return this.logger.error("Contact pointing to us is missing expires parameter, dropping response"),this.unregistered(),void this.waitingToggle(!1);if(i.hasParam("temp-gruu")){const e=i.getParam("temp-gruu");e&&(this.userAgent.contact.tempGruu=b.URIParse(e.replace(/"/g,"")))}if(i.hasParam("pub-gruu")){const e=i.getParam("pub-gruu");e&&(this.userAgent.contact.pubGruu=b.URIParse(e.replace(/"/g,"")))}this.registered(s),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t),this.waitingToggle(!1)},onProgress:t=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)},onRedirect:t=>{this.logger.error("Redirect received. Not supported."),this.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t),this.waitingToggle(!1)},onReject:t=>{if(423===t.message.statusCode)return t.message.hasHeader("min-expires")?(this.expires=Number(t.message.getHeader("min-expires")),this.waitingToggle(!1),void this.register()):(this.logger.error("423 response received for REGISTER without Min-Expires, dropping response"),this.unregistered(),void this.waitingToggle(!1));this.logger.warn("Failed to register, status code "+t.message.statusCode);let s=NaN;if(500===t.message.statusCode||503===t.message.statusCode){const e=t.message.getHeader("retry-after");e&&(s=Number.parseInt(e,void 0))}this._retryAfter=isNaN(s)?void 0:s,this.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t),this._retryAfter=void 0,this.waitingToggle(!1)},onTrying:t=>{e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}});return Promise.resolve(s)}unregister(e={}){if(this.state===Q.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed&&this.state!==Q.Registered)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();const e=new a("REGISTER request already in progress, waiting for final response");return Promise.reject(e)}this._state===Q.Registered||e.all||this.logger.warn("Not currently registered, but sending an unregister anyway.");const t=(e.requestOptions&&e.requestOptions.extraHeaders||[]).slice();this.request.extraHeaders=t,e.all?(t.push("Contact: *"),t.push("Expires: 0")):t.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);const s=this.userAgent.userAgentCore.register(this.request,{onAccept:t=>{this._contacts=t.message.getHeaders("contact"),this.unregistered(),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t),this.waitingToggle(!1)},onProgress:t=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)},onRedirect:t=>{this.logger.error("Unregister redirected. Not currently supported."),this.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t),this.waitingToggle(!1)},onReject:t=>{this.logger.error("Unregister rejected with status code "+t.message.statusCode),this.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t),this.waitingToggle(!1)},onTrying:t=>{e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}});return Promise.resolve(s)}clearTimers(){void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),void 0!==this.registrationExpiredTimer&&(clearTimeout(this.registrationExpiredTimer),this.registrationExpiredTimer=void 0)}generateContactHeader(e){let t=this.userAgent.contact.toString();return this.options.regId&&this.options.instanceId&&(t+=";reg-id="+this.options.regId,t+=';+sip.instance=""'),this.options.extraContactHeaderParams&&this.options.extraContactHeaderParams.forEach(e=>{t+=";"+e}),t+=";expires="+e,t}registered(e){this.clearTimers(),this.registrationTimer=setTimeout(()=>{this.registrationTimer=void 0,this.register()},1e3*e-3e3),this.registrationExpiredTimer=setTimeout(()=>{this.logger.warn("Registration expired"),this.unregistered()},1e3*e),this._state!==Q.Registered&&this.stateTransition(Q.Registered)}unregistered(){this.clearTimers(),this._state!==Q.Unregistered&&this.stateTransition(Q.Unregistered)}terminated(){this.clearTimers(),this._state!==Q.Terminated&&this.stateTransition(Q.Terminated)}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case Q.Initial:e!==Q.Registered&&e!==Q.Unregistered&&e!==Q.Terminated&&t();break;case Q.Registered:e!==Q.Unregistered&&e!==Q.Terminated&&t();break;case Q.Unregistered:e!==Q.Registered&&e!==Q.Terminated&&t();break;case Q.Terminated:t();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log("Registration transitioned to state "+this._state),this._stateEventEmitter.emit(this._state),e===Q.Terminated&&this.dispose()}get waiting(){return this._waiting}get waitingChange(){return this._waitingEventEmitter}waitingToggle(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(this._waiting)}waitingWarning(){let e="An attempt was made to send a REGISTER request while a prior one was still in progress.";e+=" RFC 3261 requires UAs MUST NOT send a new registration until they have received a final response",e+=" from the registrar for the previous one or the previous REGISTER request has timed out.",e+=" Note that if the transport disconnects, you still must wait for the prior request to time out before",e+=" sending a new REGISTER request or alternatively dispose of the current Registerer and create a new Registerer.",this.logger.warn("An attempt was made to send a REGISTER request while a prior one was still in progress. RFC 3261 requires UAs MUST NOT send a new registration until they have received a final response from the registrar for the previous one or the previous REGISTER request has timed out. Note that if the transport disconnects, you still must wait for the prior request to time out before sending a new REGISTER request or alternatively dispose of the current Registerer and create a new Registerer.")}stateError(){let e=`An attempt was made to send a REGISTER request when the Registerer ${this.state===Q.Terminated?"is in 'Terminated' state":"has been disposed"}.`;e+=" The Registerer transitions to 'Terminated' when Registerer.dispose() is called.",e+=" Perhaps you called UserAgent.stop() which dipsoses of all Registerers?",this.logger.error(e)}}ae.defaultExpires=600,function(e){e.Initial="Initial",e.NotifyWait="NotifyWait",e.Pending="Pending",e.Active="Active",e.Terminated="Terminated"}(ee||(ee={})),function(e){e.Initial="Initial",e.NotifyWait="NotifyWait",e.Subscribed="Subscribed",e.Terminated="Terminated"}(te||(te={}));class ce{constructor(e,t={}){this._disposed=!1,this._state=te.Initial,this._logger=e.getLogger("sip.Subscription"),this._stateEventEmitter=new g,this._userAgent=e,this.delegate=t.delegate}dispose(){return this._disposed||(this._disposed=!0,this._stateEventEmitter.removeAllListeners()),Promise.resolve()}get dialog(){return this._dialog}get disposed(){return this._disposed}get state(){return this._state}get stateChange(){return this._stateEventEmitter}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case te.Initial:e!==te.NotifyWait&&e!==te.Terminated&&t();break;case te.NotifyWait:e!==te.Subscribed&&e!==te.Terminated&&t();break;case te.Subscribed:e!==te.Terminated&&t();break;case te.Terminated:t();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(this._state),e===te.Terminated&&this.dispose())}}class he extends ce{constructor(e,t,s,i={}){super(e,i),this.body=void 0,this.logger=e.getLogger("sip.Subscriber"),i.body&&(this.body={body:i.body,contentType:i.contentType?i.contentType:"application/sdp"}),this.targetURI=t,this.event=s,void 0===i.expires?this.expires=3600:"number"!=typeof i.expires?(this.logger.warn('Option "expires" must be a number. Using default of 3600.'),this.expires=3600):this.expires=i.expires,this.extraHeaders=(i.extraHeaders||[]).slice(),this.subscriberRequest=this.initSubscriberRequest(),this.outgoingRequestMessage=this.subscriberRequest.message,this.id=this.outgoingRequestMessage.callId+this.outgoingRequestMessage.from.parameters.tag+this.event,this._userAgent._subscriptions[this.id]=this}dispose(){return this.disposed?Promise.resolve():(this.logger.log(`Subscription ${this.id} in state ${this.state} is being disposed`),delete this._userAgent._subscriptions[this.id],this.retryAfterTimer&&(clearTimeout(this.retryAfterTimer),this.retryAfterTimer=void 0),this.subscriberRequest.dispose(),super.dispose().then(()=>{if(this.state===te.Subscribed){if(!this._dialog)throw new Error("Dialog undefined.");if(this._dialog.subscriptionState===ee.Pending||this._dialog.subscriptionState===ee.Active){const e=this._dialog;return new Promise((t,s)=>{e.delegate={onTerminated:()=>t()},e.unsubscribe()})}}}))}subscribe(e={}){switch(this.subscriberRequest.state){case ee.Initial:this.state===te.Initial&&this.stateTransition(te.NotifyWait),this.subscriberRequest.subscribe().then(e=>{e.success?(e.success.subscription&&(this._dialog=e.success.subscription,this._dialog.delegate={onNotify:e=>this.onNotify(e),onRefresh:e=>this.onRefresh(e),onTerminated:()=>{this.state!==te.Terminated&&this.stateTransition(te.Terminated)}}),this.onNotify(e.success.request)):e.failure&&this.unsubscribe()});break;case ee.NotifyWait:case ee.Pending:break;case ee.Active:if(this._dialog){this._dialog.refresh().delegate={onAccept:e=>this.onAccepted(e),onRedirect:e=>this.unsubscribe(),onReject:e=>this.unsubscribe()}}break;case ee.Terminated:}return Promise.resolve()}unsubscribe(e={}){if(this.disposed)return Promise.resolve();switch(this.subscriberRequest.state){case ee.Initial:case ee.NotifyWait:break;case ee.Pending:case ee.Active:this._dialog&&this._dialog.unsubscribe();break;case ee.Terminated:break;default:throw new Error("Unknown state.")}return this.stateTransition(te.Terminated),Promise.resolve()}_refresh(){return this.subscriberRequest.state===ee.Active?this.subscribe():Promise.resolve()}onAccepted(e){}onNotify(e){if(this.disposed)return void e.accept();if(this.state!==te.Subscribed&&this.stateTransition(te.Subscribed),this.delegate&&this.delegate.onNotify){const t=new B(e);this.delegate.onNotify(t)}else e.accept();const t=e.message.parseHeader("Subscription-State");if(t&&t.state)switch(t.state){case"terminated":if(t.reason)switch(this.logger.log("Terminated subscription with reason "+t.reason),t.reason){case"deactivated":case"timeout":return this.initSubscriberRequest(),void this.subscribe();case"probation":case"giveup":return this.initSubscriberRequest(),void(t.params&&t.params["retry-after"]?this.retryAfterTimer=setTimeout(()=>{this.subscribe()},t.params["retry-after"]):this.subscribe())}this.unsubscribe()}}onRefresh(e){e.delegate={onAccept:e=>this.onAccepted(e)}}initSubscriberRequest(){const e={extraHeaders:this.extraHeaders,body:this.body?k(this.body):void 0};return this.subscriberRequest=new de(this._userAgent.userAgentCore,this.targetURI,this.event,this.expires,e),this.subscriberRequest.delegate={onAccept:e=>this.onAccepted(e)},this.subscriberRequest}}class de{constructor(e,t,s,i,r,n){this.core=e,this.target=t,this.event=s,this.expires=i,this.subscribed=!1,this.logger=e.loggerFactory.getLogger("sip.Subscriber"),this.delegate=n;const o="Allow: "+F.toString(),a=(r&&r.extraHeaders||[]).slice();a.push(o),a.push("Event: "+this.event),a.push("Expires: "+this.expires),a.push("Contact: "+this.core.configuration.contact.toString());const c=r&&r.body;this.message=e.makeOutgoingRequestMessage(j.SUBSCRIBE,this.target,this.core.configuration.aor,this.target,{},a,c)}dispose(){this.request&&(this.request.waitNotifyStop(),this.request.dispose(),this.request=void 0)}get state(){return this.subscription?this.subscription.subscriptionState:this.subscribed?ee.NotifyWait:ee.Initial}subscribe(){return this.subscribed?Promise.reject(new Error("Not in initial state. Did you call subscribe more than once?")):(this.subscribed=!0,new Promise(e=>{if(!this.message)throw new Error("Message undefined.");this.request=this.core.subscribe(this.message,{onAccept:e=>{this.delegate&&this.delegate.onAccept&&this.delegate.onAccept(e)},onNotify:t=>{this.subscription=t.subscription,this.subscription&&(this.subscription.autoRefresh=!0),e({success:t})},onNotifyTimeout:()=>{e({failure:{}})},onRedirect:t=>{e({failure:{response:t}})},onReject:t=>{e({failure:{response:t}})}})}))}}!function(e){e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Disconnected="Disconnected"}(se||(se={})),function(e){e.Started="Started",e.Stopped="Stopped"}(ie||(ie={})),function(e){e[e.error=0]="error",e[e.warn=1]="warn",e[e.log=2]="log",e[e.debug=3]="debug"}(re||(re={}));class le{constructor(e,t,s){this.logger=e,this.category=t,this.label=s}error(e){this.genericLog(re.error,e)}warn(e){this.genericLog(re.warn,e)}log(e){this.genericLog(re.log,e)}debug(e){this.genericLog(re.debug,e)}genericLog(e,t){this.logger.genericLog(e,this.category,this.label,t)}get level(){return this.logger.level}set level(e){this.logger.level=e}}class ge{constructor(){this.builtinEnabled=!0,this._level=re.log,this.loggers={},this.logger=this.getLogger("sip:loggerfactory")}get level(){return this._level}set level(e){e>=0&&e<=3?this._level=e:e>3?this._level=3:re.hasOwnProperty(e)?this._level=e:this.logger.error("invalid 'level' parameter value: "+JSON.stringify(e))}get connector(){return this._connector}set connector(e){e?"function"==typeof e?this._connector=e:this.logger.error("invalid 'connector' parameter value: "+JSON.stringify(e)):this._connector=void 0}getLogger(e,t){if(t&&3===this.level)return new le(this,e,t);if(this.loggers[e])return this.loggers[e];{const t=new le(this,e);return this.loggers[e]=t,t}}genericLog(e,t,s,i){this.level>=e&&this.builtinEnabled&&this.print(e,t,s,i),this.connector&&this.connector(re[e],t,s,i)}print(e,t,s,i){if("string"==typeof i){const e=[new Date,t];s&&e.push(s),i=e.concat(i).join(" | ")}switch(e){case re.error:console.error(i);break;case re.warn:console.warn(i);break;case re.log:console.log(i);break;case re.debug:console.debug(i)}}}class ue{constructor(){this._dataLength=0,this._bufferLength=0,this._state=new Int32Array(4),this._buffer=new ArrayBuffer(68),this._buffer8=new Uint8Array(this._buffer,0,68),this._buffer32=new Uint32Array(this._buffer,0,17),this.start()}static hashStr(e,t=!1){return this.onePassHasher.start().appendStr(e).end(t)}static hashAsciiStr(e,t=!1){return this.onePassHasher.start().appendAsciiStr(e).end(t)}static _hex(e){const t=ue.hexChars,s=ue.hexOut;let i,r,n,o;for(o=0;o<4;o+=1)for(r=8*o,i=e[o],n=0;n<8;n+=2)s[r+1+n]=t.charAt(15&i),i>>>=4,s[r+0+n]=t.charAt(15&i),i>>>=4;return s.join("")}static _md5cycle(e,t){let s=e[0],i=e[1],r=e[2],n=e[3];s+=(i&r|~i&n)+t[0]-680876936|0,s=(s<<7|s>>>25)+i|0,n+=(s&i|~s&r)+t[1]-389564586|0,n=(n<<12|n>>>20)+s|0,r+=(n&s|~n&i)+t[2]+606105819|0,r=(r<<17|r>>>15)+n|0,i+=(r&n|~r&s)+t[3]-1044525330|0,i=(i<<22|i>>>10)+r|0,s+=(i&r|~i&n)+t[4]-176418897|0,s=(s<<7|s>>>25)+i|0,n+=(s&i|~s&r)+t[5]+1200080426|0,n=(n<<12|n>>>20)+s|0,r+=(n&s|~n&i)+t[6]-1473231341|0,r=(r<<17|r>>>15)+n|0,i+=(r&n|~r&s)+t[7]-45705983|0,i=(i<<22|i>>>10)+r|0,s+=(i&r|~i&n)+t[8]+1770035416|0,s=(s<<7|s>>>25)+i|0,n+=(s&i|~s&r)+t[9]-1958414417|0,n=(n<<12|n>>>20)+s|0,r+=(n&s|~n&i)+t[10]-42063|0,r=(r<<17|r>>>15)+n|0,i+=(r&n|~r&s)+t[11]-1990404162|0,i=(i<<22|i>>>10)+r|0,s+=(i&r|~i&n)+t[12]+1804603682|0,s=(s<<7|s>>>25)+i|0,n+=(s&i|~s&r)+t[13]-40341101|0,n=(n<<12|n>>>20)+s|0,r+=(n&s|~n&i)+t[14]-1502002290|0,r=(r<<17|r>>>15)+n|0,i+=(r&n|~r&s)+t[15]+1236535329|0,i=(i<<22|i>>>10)+r|0,s+=(i&n|r&~n)+t[1]-165796510|0,s=(s<<5|s>>>27)+i|0,n+=(s&r|i&~r)+t[6]-1069501632|0,n=(n<<9|n>>>23)+s|0,r+=(n&i|s&~i)+t[11]+643717713|0,r=(r<<14|r>>>18)+n|0,i+=(r&s|n&~s)+t[0]-373897302|0,i=(i<<20|i>>>12)+r|0,s+=(i&n|r&~n)+t[5]-701558691|0,s=(s<<5|s>>>27)+i|0,n+=(s&r|i&~r)+t[10]+38016083|0,n=(n<<9|n>>>23)+s|0,r+=(n&i|s&~i)+t[15]-660478335|0,r=(r<<14|r>>>18)+n|0,i+=(r&s|n&~s)+t[4]-405537848|0,i=(i<<20|i>>>12)+r|0,s+=(i&n|r&~n)+t[9]+568446438|0,s=(s<<5|s>>>27)+i|0,n+=(s&r|i&~r)+t[14]-1019803690|0,n=(n<<9|n>>>23)+s|0,r+=(n&i|s&~i)+t[3]-187363961|0,r=(r<<14|r>>>18)+n|0,i+=(r&s|n&~s)+t[8]+1163531501|0,i=(i<<20|i>>>12)+r|0,s+=(i&n|r&~n)+t[13]-1444681467|0,s=(s<<5|s>>>27)+i|0,n+=(s&r|i&~r)+t[2]-51403784|0,n=(n<<9|n>>>23)+s|0,r+=(n&i|s&~i)+t[7]+1735328473|0,r=(r<<14|r>>>18)+n|0,i+=(r&s|n&~s)+t[12]-1926607734|0,i=(i<<20|i>>>12)+r|0,s+=(i^r^n)+t[5]-378558|0,s=(s<<4|s>>>28)+i|0,n+=(s^i^r)+t[8]-2022574463|0,n=(n<<11|n>>>21)+s|0,r+=(n^s^i)+t[11]+1839030562|0,r=(r<<16|r>>>16)+n|0,i+=(r^n^s)+t[14]-35309556|0,i=(i<<23|i>>>9)+r|0,s+=(i^r^n)+t[1]-1530992060|0,s=(s<<4|s>>>28)+i|0,n+=(s^i^r)+t[4]+1272893353|0,n=(n<<11|n>>>21)+s|0,r+=(n^s^i)+t[7]-155497632|0,r=(r<<16|r>>>16)+n|0,i+=(r^n^s)+t[10]-1094730640|0,i=(i<<23|i>>>9)+r|0,s+=(i^r^n)+t[13]+681279174|0,s=(s<<4|s>>>28)+i|0,n+=(s^i^r)+t[0]-358537222|0,n=(n<<11|n>>>21)+s|0,r+=(n^s^i)+t[3]-722521979|0,r=(r<<16|r>>>16)+n|0,i+=(r^n^s)+t[6]+76029189|0,i=(i<<23|i>>>9)+r|0,s+=(i^r^n)+t[9]-640364487|0,s=(s<<4|s>>>28)+i|0,n+=(s^i^r)+t[12]-421815835|0,n=(n<<11|n>>>21)+s|0,r+=(n^s^i)+t[15]+530742520|0,r=(r<<16|r>>>16)+n|0,i+=(r^n^s)+t[2]-995338651|0,i=(i<<23|i>>>9)+r|0,s+=(r^(i|~n))+t[0]-198630844|0,s=(s<<6|s>>>26)+i|0,n+=(i^(s|~r))+t[7]+1126891415|0,n=(n<<10|n>>>22)+s|0,r+=(s^(n|~i))+t[14]-1416354905|0,r=(r<<15|r>>>17)+n|0,i+=(n^(r|~s))+t[5]-57434055|0,i=(i<<21|i>>>11)+r|0,s+=(r^(i|~n))+t[12]+1700485571|0,s=(s<<6|s>>>26)+i|0,n+=(i^(s|~r))+t[3]-1894986606|0,n=(n<<10|n>>>22)+s|0,r+=(s^(n|~i))+t[10]-1051523|0,r=(r<<15|r>>>17)+n|0,i+=(n^(r|~s))+t[1]-2054922799|0,i=(i<<21|i>>>11)+r|0,s+=(r^(i|~n))+t[8]+1873313359|0,s=(s<<6|s>>>26)+i|0,n+=(i^(s|~r))+t[15]-30611744|0,n=(n<<10|n>>>22)+s|0,r+=(s^(n|~i))+t[6]-1560198380|0,r=(r<<15|r>>>17)+n|0,i+=(n^(r|~s))+t[13]+1309151649|0,i=(i<<21|i>>>11)+r|0,s+=(r^(i|~n))+t[4]-145523070|0,s=(s<<6|s>>>26)+i|0,n+=(i^(s|~r))+t[11]-1120210379|0,n=(n<<10|n>>>22)+s|0,r+=(s^(n|~i))+t[2]+718787259|0,r=(r<<15|r>>>17)+n|0,i+=(n^(r|~s))+t[9]-343485551|0,i=(i<<21|i>>>11)+r|0,e[0]=s+e[0]|0,e[1]=i+e[1]|0,e[2]=r+e[2]|0,e[3]=n+e[3]|0}start(){return this._dataLength=0,this._bufferLength=0,this._state.set(ue.stateIdentity),this}appendStr(e){const t=this._buffer8,s=this._buffer32;let i,r,n=this._bufferLength;for(r=0;r>>6),t[n++]=63&i|128;else if(i<55296||i>56319)t[n++]=224+(i>>>12),t[n++]=i>>>6&63|128,t[n++]=63&i|128;else{if(i=1024*(i-55296)+(e.charCodeAt(++r)-56320)+65536,i>1114111)throw new Error("Unicode standard supports code points up to U+10FFFF");t[n++]=240+(i>>>18),t[n++]=i>>>12&63|128,t[n++]=i>>>6&63|128,t[n++]=63&i|128}n>=64&&(this._dataLength+=64,ue._md5cycle(this._state,s),n-=64,s[0]=s[16])}return this._bufferLength=n,this}appendAsciiStr(e){const t=this._buffer8,s=this._buffer32;let i,r=this._bufferLength,n=0;for(;;){for(i=Math.min(e.length-n,64-r);i--;)t[r++]=e.charCodeAt(n++);if(r<64)break;this._dataLength+=64,ue._md5cycle(this._state,s),r=0}return this._bufferLength=r,this}appendByteArray(e){const t=this._buffer8,s=this._buffer32;let i,r=this._bufferLength,n=0;for(;;){for(i=Math.min(e.length-n,64-r);i--;)t[r++]=e[n++];if(r<64)break;this._dataLength+=64,ue._md5cycle(this._state,s),r=0}return this._bufferLength=r,this}getState(){const e=this._state;return{buffer:String.fromCharCode.apply(null,this._buffer8),buflen:this._bufferLength,length:this._dataLength,state:[e[0],e[1],e[2],e[3]]}}setState(e){const t=e.buffer,s=e.state,i=this._state;let r;for(this._dataLength=e.length,this._bufferLength=e.buflen,i[0]=s[0],i[1]=s[1],i[2]=s[2],i[3]=s[3],r=0;r>2);let n;if(this._dataLength+=t,s[t]=128,s[t+1]=s[t+2]=s[t+3]=0,i.set(ue.buffer32Identity.subarray(r),r),t>55&&(ue._md5cycle(this._state,i),i.set(ue.buffer32Identity)),n=8*this._dataLength,n<=4294967295)i[14]=n;else{const e=n.toString(16).match(/(.*?)(.{0,8})$/);if(null===e)return;const t=parseInt(e[2],16),s=parseInt(e[1],16)||0;i[14]=t,i[15]=s}return ue._md5cycle(this._state,i),e?this._state:ue._hex(this._state)}}function pe(e){return ue.hashStr(e)}ue.stateIdentity=new Int32Array([1732584193,-271733879,-1732584194,271733878]),ue.buffer32Identity=new Int32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),ue.hexChars="0123456789abcdef",ue.hexOut=[],ue.onePassHasher=new ue,"5d41402abc4b2a76b9719d911017c592"!==ue.hashStr("hello")&&console.error("Md5 self test failed.");class fe{constructor(e,t,s,i){this.logger=e.getLogger("sipjs.digestauthentication"),this.username=s,this.password=i,this.ha1=t,this.nc=0,this.ncHex="00000000"}authenticate(e,t,s){if(this.algorithm=t.algorithm,this.realm=t.realm,this.nonce=t.nonce,this.opaque=t.opaque,this.stale=t.stale,this.algorithm){if("MD5"!==this.algorithm)return this.logger.warn("challenge with Digest algorithm different than 'MD5', authentication aborted"),!1}else this.algorithm="MD5";if(!this.realm)return this.logger.warn("challenge without Digest realm, authentication aborted"),!1;if(!this.nonce)return this.logger.warn("challenge without Digest nonce, authentication aborted"),!1;if(t.qop)if(t.qop.indexOf("auth")>-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=R(12),this.nc+=1,this.updateNcHex(),4294967296===this.nc&&(this.nc=1,this.ncHex="00000001"),this.calculateResponse(s),!0}toString(){const 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(", ")}updateNcHex(){const e=Number(this.nc).toString(16);this.ncHex="00000000".substr(0,8-e.length)+e}calculateResponse(e){let t,s;t=this.ha1,""!==t&&void 0!==t||(t=pe(this.username+":"+this.realm+":"+this.password)),"auth"===this.qop?(s=pe(this.method+":"+this.uri),this.response=pe(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth:"+s)):"auth-int"===this.qop?(s=pe(this.method+":"+this.uri+":"+pe(e||"")),this.response=pe(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth-int:"+s)):void 0===this.qop&&(s=pe(this.method+":"+this.uri),this.response=pe(t+":"+this.nonce+":"+s))}}function me(e,t){if(t.statusCode<100||t.statusCode>699)throw new TypeError("Invalid statusCode: "+t.statusCode);const s=t.reasonPhrase?t.reasonPhrase:y(t.statusCode);let i="SIP/2.0 "+t.statusCode+" "+s+"\r\n";t.statusCode>=100&&t.statusCode,t.statusCode;const r="From: "+e.getHeader("From")+"\r\n",n="Call-ID: "+e.callId+"\r\n",o="CSeq: "+e.cseq+" "+e.method+"\r\n",a=e.getHeaders("via").reduce((e,t)=>e+"Via: "+t+"\r\n","");let c="To: "+e.getHeader("to");if(t.statusCode>100&&!e.parseHeader("to").hasParam("tag")){let e=t.toTag;e||(e=E()),c+=";tag="+e}c+="\r\n";let h="";t.supported&&(h="Supported: "+t.supported.join(", ")+"\r\n");let d="";t.userAgent&&(d="User-Agent: "+t.userAgent+"\r\n");let l="";return t.extraHeaders&&(l=t.extraHeaders.reduce((e,t)=>e+t.trim()+"\r\n","")),i+=a,i+=r,i+=c,i+=o,i+=n,i+=h,i+=d,i+=l,t.body?(i+="Content-Type: "+t.body.contentType+"\r\n",i+="Content-Length: "+I(t.body.content)+"\r\n\r\n",i+=t.body.content):i+="Content-Length: 0\r\n\r\n",{message:i}}class ve extends n{constructor(e){super(e||"Unspecified transport error.")}}class we{constructor(e,t,s,i,r){this._transport=e,this._user=t,this._id=s,this._state=i,this.listeners=new Array,this.logger=t.loggerFactory.getLogger(r,s),this.logger.debug(`Constructing ${this.typeToString()} with id ${this.id}.`)}dispose(){this.logger.debug(`Destroyed ${this.typeToString()} with id ${this.id}.`)}get id(){return this._id}get kind(){throw new Error("Invalid kind.")}get state(){return this._state}get transport(){return this._transport}addStateChangeListener(e,t){const s=()=>{this.removeStateChangeListener(s),e()};!0===(null==t?void 0:t.once)?this.listeners.push(s):this.listeners.push(e)}notifyStateChangeListeners(){this.listeners.slice().forEach(e=>e())}removeStateChangeListener(e){this.listeners=this.listeners.filter(t=>t!==e)}logTransportError(e,t){this.logger.error(e.message),this.logger.error(`Transport error occurred in ${this.typeToString()} with id ${this.id}.`),this.logger.error(t)}send(e){return this.transport.send(e).catch(e=>{if(e instanceof ve)throw this.onTransportError(e),e;let t;throw t=e&&"string"==typeof e.message?new ve(e.message):new ve,this.onTransportError(t),t})}setState(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.notifyStateChangeListeners()}typeToString(){return"UnknownType"}}class be extends we{constructor(e,t,s,i,r){super(t,s,be.makeId(e),i,r),this._request=e,this.user=s,e.setViaHeader(this.id,t.protocol)}static makeId(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())}get request(){return this._request}onRequestTimeout(){this.user.onRequestTimeout&&this.user.onRequestTimeout()}}!function(e){e.Accepted="Accepted",e.Calling="Calling",e.Completed="Completed",e.Confirmed="Confirmed",e.Proceeding="Proceeding",e.Terminated="Terminated",e.Trying="Trying"}(ne||(ne={}));class Te extends be{constructor(e,t,s){super(e,t,s,ne.Trying,"sip.transaction.nict"),this.F=setTimeout(()=>this.timerF(),U.TIMER_F),this.send(e.toString()).catch(e=>{this.logTransportError(e,"Failed to send initial outgoing request.")})}dispose(){this.F&&(clearTimeout(this.F),this.F=void 0),this.K&&(clearTimeout(this.K),this.K=void 0),super.dispose()}get kind(){return"nict"}receiveResponse(e){const t=e.statusCode;if(!t||t<100||t>699)throw new Error("Invalid status code "+t);switch(this.state){case ne.Trying:if(t>=100&&t<=199)return this.stateTransition(ne.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=699)return this.stateTransition(ne.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case ne.Proceeding:if(t>=100&&t<=199&&this.user.receiveResponse)return this.user.receiveResponse(e);if(t>=200&&t<=699)return this.stateTransition(ne.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case ne.Completed:case ne.Terminated:return;default:throw new Error("Invalid state "+this.state)}const s=`Non-INVITE client transaction received unexpected ${t} response while in state ${this.state}.`;this.logger.warn(s)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(ne.Terminated,!0)}typeToString(){return"non-INVITE client transaction"}stateTransition(e,t=!1){const s=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case ne.Trying:s();break;case ne.Proceeding:this.state!==ne.Trying&&s();break;case ne.Completed:this.state!==ne.Trying&&this.state!==ne.Proceeding&&s();break;case ne.Terminated:this.state!==ne.Trying&&this.state!==ne.Proceeding&&this.state!==ne.Completed&&(t||s());break;default:s()}e===ne.Completed&&(this.F&&(clearTimeout(this.F),this.F=void 0),this.K=setTimeout(()=>this.timerK(),U.TIMER_K)),e===ne.Terminated&&this.dispose(),this.setState(e)}timerF(){this.logger.debug(`Timer F expired for non-INVITE client transaction ${this.id}.`),this.state!==ne.Trying&&this.state!==ne.Proceeding||(this.onRequestTimeout(),this.stateTransition(ne.Terminated))}timerK(){this.state===ne.Completed&&this.stateTransition(ne.Terminated)}}class Se extends we{constructor(e,t,s,i,r){super(t,s,e.viaBranch,i,r),this._request=e,this.user=s}get request(){return this._request}}class Re extends Se{constructor(e,t,s){super(e,t,s,ne.Proceeding,"sip.transaction.ist")}dispose(){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),super.dispose()}get kind(){return"ist"}receiveRequest(e){switch(this.state){case ne.Proceeding:if(e.method===j.INVITE)return void(this.lastProvisionalResponse&&this.send(this.lastProvisionalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")}));break;case ne.Accepted:if(e.method===j.INVITE)return;break;case ne.Completed:if(e.method===j.INVITE){if(!this.lastFinalResponse)throw new Error("Last final response undefined.");return void this.send(this.lastFinalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of final response.")})}if(e.method===j.ACK)return void this.stateTransition(ne.Confirmed);break;case ne.Confirmed:case ne.Terminated:if(e.method===j.INVITE||e.method===j.ACK)return;break;default:throw new Error("Invalid state "+this.state)}const t=`INVITE server transaction received unexpected ${e.method} request while in state ${this.state}.`;this.logger.warn(t)}receiveResponse(e,t){if(e<100||e>699)throw new Error("Invalid status code "+e);switch(this.state){case ne.Proceeding:if(e>=100&&e<=199)return this.lastProvisionalResponse=t,e>100&&this.startProgressExtensionTimer(),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 1xx response.")});if(e>=200&&e<=299)return this.lastFinalResponse=t,this.stateTransition(ne.Accepted),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")});if(e>=300&&e<=699)return this.lastFinalResponse=t,this.stateTransition(ne.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send non-2xx final response.")});break;case ne.Accepted:if(e>=200&&e<=299)return void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")});break;case ne.Completed:case ne.Confirmed:case ne.Terminated:break;default:throw new Error("Invalid state "+this.state)}const s=`INVITE server transaction received unexpected ${e} response from TU while in state ${this.state}.`;throw this.logger.error(s),new Error(s)}retransmitAcceptedResponse(){this.state===ne.Accepted&&this.lastFinalResponse&&this.send(this.lastFinalResponse).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")})}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e)}typeToString(){return"INVITE server transaction"}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case ne.Proceeding:t();break;case ne.Accepted:case ne.Completed:this.state!==ne.Proceeding&&t();break;case ne.Confirmed:this.state!==ne.Completed&&t();break;case ne.Terminated:this.state!==ne.Accepted&&this.state!==ne.Completed&&this.state!==ne.Confirmed&&t();break;default:t()}this.stopProgressExtensionTimer(),e===ne.Accepted&&(this.L=setTimeout(()=>this.timerL(),U.TIMER_L)),e===ne.Completed&&(this.H=setTimeout(()=>this.timerH(),U.TIMER_H)),e===ne.Confirmed&&(this.I=setTimeout(()=>this.timerI(),U.TIMER_I)),e===ne.Terminated&&this.dispose(),this.setState(e)}startProgressExtensionTimer(){void 0===this.progressExtensionTimer&&(this.progressExtensionTimer=setInterval(()=>{if(this.logger.debug(`Progress extension timer expired for INVITE server transaction ${this.id}.`),!this.lastProvisionalResponse)throw new Error("Last provisional response undefined.");this.send(this.lastProvisionalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")})},U.PROVISIONAL_RESPONSE_INTERVAL))}stopProgressExtensionTimer(){void 0!==this.progressExtensionTimer&&(clearInterval(this.progressExtensionTimer),this.progressExtensionTimer=void 0)}timerG(){}timerH(){this.logger.debug(`Timer H expired for INVITE server transaction ${this.id}.`),this.state===ne.Completed&&(this.logger.warn("ACK to negative final response was never received, terminating transaction."),this.stateTransition(ne.Terminated))}timerI(){this.logger.debug(`Timer I expired for INVITE server transaction ${this.id}.`),this.stateTransition(ne.Terminated)}timerL(){this.logger.debug(`Timer L expired for INVITE server transaction ${this.id}.`),this.state===ne.Accepted&&this.stateTransition(ne.Terminated)}}class ye{constructor(e,t){this.core=e,this.dialogState=t,this.core.dialogs.set(this.id,this)}static initialDialogStateForUserAgentClient(e,t){const s=t.getHeaders("record-route").reverse(),i=t.parseHeader("contact");if(!i)throw new Error("Contact undefined.");if(!(i instanceof f))throw new Error("Contact not instance of NameAddrHeader.");const r=i.uri,n=e.cseq,o=e.callId,a=e.fromTag,c=t.toTag;if(!o)throw new Error("Call id undefined.");if(!a)throw new Error("From tag undefined.");if(!c)throw new Error("To tag undefined.");if(!e.from)throw new Error("From undefined.");if(!e.to)throw new Error("To undefined.");const h=e.from.uri,d=e.to.uri;if(!t.statusCode)throw new Error("Incoming response status code undefined.");return{id:o+a+c,early:t.statusCode<200,callId:o,localTag:a,remoteTag:c,localSequenceNumber:n,remoteSequenceNumber:void 0,localURI:h,remoteURI:d,remoteTarget:r,routeSet:s,secure:!1}}static initialDialogStateForUserAgentServer(e,t,s=!1){const i=e.getHeaders("record-route"),r=e.parseHeader("contact");if(!r)throw new Error("Contact undefined.");if(!(r instanceof f))throw new Error("Contact not instance of NameAddrHeader.");const n=r.uri,o=e.cseq,a=e.callId,c=t,h=e.fromTag,d=e.from.uri;return{id:a+c+h,early:s,callId:a,localTag:c,remoteTag:h,localSequenceNumber:void 0,remoteSequenceNumber:o,localURI:e.to.uri,remoteURI:d,remoteTarget:n,routeSet:i,secure:!1}}dispose(){this.core.dialogs.delete(this.id)}get id(){return this.dialogState.id}get early(){return this.dialogState.early}get callId(){return this.dialogState.callId}get localTag(){return this.dialogState.localTag}get remoteTag(){return this.dialogState.remoteTag}get localSequenceNumber(){return this.dialogState.localSequenceNumber}get remoteSequenceNumber(){return this.dialogState.remoteSequenceNumber}get localURI(){return this.dialogState.localURI}get remoteURI(){return this.dialogState.remoteURI}get remoteTarget(){return this.dialogState.remoteTarget}get routeSet(){return this.dialogState.routeSet}get secure(){return this.dialogState.secure}get userAgentCore(){return this.core}confirm(){this.dialogState.early=!1}receiveRequest(e){if(e.method!==j.ACK){if(this.remoteSequenceNumber){if(e.cseq<=this.remoteSequenceNumber)throw new Error("Out of sequence in dialog request. Did you forget to call sequenceGuard()?");this.dialogState.remoteSequenceNumber=e.cseq}this.remoteSequenceNumber||(this.dialogState.remoteSequenceNumber=e.cseq)}}recomputeRouteSet(e){this.dialogState.routeSet=e.getHeaders("record-route").reverse()}createOutgoingRequestMessage(e,t){const s=this.remoteURI,i=this.remoteTag,r=this.localURI,n=this.localTag,o=this.callId;let a;a=t&&t.cseq?t.cseq:this.dialogState.localSequenceNumber?this.dialogState.localSequenceNumber+=1:this.dialogState.localSequenceNumber=1;const c=this.remoteTarget,h=this.routeSet,d=t&&t.extraHeaders,l=t&&t.body;return this.userAgentCore.makeOutgoingRequestMessage(e,c,r,s,{callId:o,cseq:a,fromTag:n,toTag:i,routeSet:h},d,l)}incrementLocalSequenceNumber(){if(!this.dialogState.localSequenceNumber)throw new Error("Local sequence number undefined.");this.dialogState.localSequenceNumber+=1}sequenceGuard(e){return e.method===j.ACK||(!(this.remoteSequenceNumber&&e.cseq<=this.remoteSequenceNumber)||(this.core.replyStateless(e,{statusCode:500}),!1))}}class Ee extends be{constructor(e,t,s){super(e,t,s,ne.Calling,"sip.transaction.ict"),this.ackRetransmissionCache=new Map,this.B=setTimeout(()=>this.timerB(),U.TIMER_B),this.send(e.toString()).catch(e=>{this.logTransportError(e,"Failed to send initial outgoing request.")})}dispose(){this.B&&(clearTimeout(this.B),this.B=void 0),this.D&&(clearTimeout(this.D),this.D=void 0),this.M&&(clearTimeout(this.M),this.M=void 0),super.dispose()}get kind(){return"ict"}ackResponse(e){const t=e.toTag;if(!t)throw new Error("To tag undefined.");const s="z9hG4bK"+Math.floor(1e7*Math.random());e.setViaHeader(s,this.transport.protocol),this.ackRetransmissionCache.set(t,e),this.send(e.toString()).catch(e=>{this.logTransportError(e,"Failed to send ACK to 2xx response.")})}receiveResponse(e){const t=e.statusCode;if(!t||t<100||t>699)throw new Error("Invalid status code "+t);switch(this.state){case ne.Calling:if(t>=100&&t<=199)return this.stateTransition(ne.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(ne.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(ne.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case ne.Proceeding:if(t>=100&&t<=199)return void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(ne.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(ne.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case ne.Accepted:if(t>=200&&t<=299){if(!this.ackRetransmissionCache.has(e.toTag))return this.ackRetransmissionCache.set(e.toTag,void 0),void(this.user.receiveResponse&&this.user.receiveResponse(e));const t=this.ackRetransmissionCache.get(e.toTag);return t?void this.send(t.toString()).catch(e=>{this.logTransportError(e,"Failed to send retransmission of ACK to 2xx response.")}):void 0}break;case ne.Completed:if(t>=300&&t<=699)return void this.ack(e);break;case ne.Terminated:break;default:throw new Error("Invalid state "+this.state)}const s=`Received unexpected ${t} response while in state ${this.state}.`;this.logger.warn(s)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(ne.Terminated,!0)}typeToString(){return"INVITE client transaction"}ack(e){const t=this.request.ruri,s=this.request.callId,i=this.request.cseq,r=this.request.getHeader("from"),n=e.getHeader("to"),o=this.request.getHeader("via"),a=this.request.getHeader("route");if(!r)throw new Error("From undefined.");if(!n)throw new Error("To undefined.");if(!o)throw new Error("Via undefined.");let c=`ACK ${t} SIP/2.0\r\n`;a&&(c+=`Route: ${a}\r\n`),c+=`Via: ${o}\r\n`,c+=`To: ${n}\r\n`,c+=`From: ${r}\r\n`,c+=`Call-ID: ${s}\r\n`,c+=`CSeq: ${i} ACK\r\n`,c+="Max-Forwards: 70\r\n",c+="Content-Length: 0\r\n\r\n",this.send(c).catch(e=>{this.logTransportError(e,"Failed to send ACK to non-2xx response.")})}stateTransition(e,t=!1){const s=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case ne.Calling:s();break;case ne.Proceeding:this.state!==ne.Calling&&s();break;case ne.Accepted:case ne.Completed:this.state!==ne.Calling&&this.state!==ne.Proceeding&&s();break;case ne.Terminated:this.state!==ne.Calling&&this.state!==ne.Accepted&&this.state!==ne.Completed&&(t||s());break;default:s()}this.B&&(clearTimeout(this.B),this.B=void 0),ne.Proceeding,e===ne.Completed&&(this.D=setTimeout(()=>this.timerD(),U.TIMER_D)),e===ne.Accepted&&(this.M=setTimeout(()=>this.timerM(),U.TIMER_M)),e===ne.Terminated&&this.dispose(),this.setState(e)}timerA(){}timerB(){this.logger.debug(`Timer B expired for INVITE client transaction ${this.id}.`),this.state===ne.Calling&&(this.onRequestTimeout(),this.stateTransition(ne.Terminated))}timerD(){this.logger.debug(`Timer D expired for INVITE client transaction ${this.id}.`),this.state===ne.Completed&&this.stateTransition(ne.Terminated)}timerM(){this.logger.debug(`Timer M expired for INVITE client transaction ${this.id}.`),this.state===ne.Accepted&&this.stateTransition(ne.Terminated)}}class $e{constructor(e,t,s,i){this.transactionConstructor=e,this.core=t,this.message=s,this.delegate=i,this.challenged=!1,this.stale=!1,this.logger=this.loggerFactory.getLogger("sip.user-agent-client"),this.init()}dispose(){this.transaction.dispose()}get loggerFactory(){return this.core.loggerFactory}get transaction(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction}cancel(e,t={}){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.");const s=this.core.makeOutgoingRequestMessage(j.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},t.extraHeaders);return s.branch=this.message.branch,this.message.headers.Route&&(s.headers.Route=this.message.headers.Route),e&&s.setHeader("Reason",e),this.transaction.state===ne.Proceeding?new $e(Te,this.core,s):this.transaction.addStateChangeListener(()=>{this.transaction&&this.transaction.state===ne.Proceeding&&new $e(Te,this.core,s)},{once:!0}),s}authenticationGuard(e,t){const s=e.statusCode;if(!s)throw new Error("Response status code undefined.");if(401!==s&&407!==s)return!0;let i,r;if(401===s?(i=e.parseHeader("www-authenticate"),r="authorization"):(i=e.parseHeader("proxy-authenticate"),r="proxy-authorization"),!i)return this.logger.warn(s+" with wrong or missing challenge, cannot authenticate"),!0;if(this.challenged&&(this.stale||!0!==i.stale))return this.logger.warn(s+" 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,i))return!0;this.challenged=!0,i.stale&&(this.stale=!0);let n=this.message.cseq+=1;return t&&t.localSequenceNumber&&(t.incrementLocalSequenceNumber(),n=this.message.cseq=t.localSequenceNumber),this.message.setHeader("cseq",n+" "+this.message.method),this.message.setHeader(r,this.credentials.toString()),this.init(),!1}onRequestTimeout(){this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout.");const e=new D;e.statusCode=408,e.reasonPhrase="Request Timeout",this.receiveResponse(e)}onTransportError(e){this.logger.error(e.message),this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable.");const t=new D;t.statusCode=503,t.reasonPhrase="Service Unavailable",this.receiveResponse(t)}receiveResponse(e){if(!this.authenticationGuard(e))return;const 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)}}init(){const e={loggerFactory:this.loggerFactory,onRequestTimeout:()=>this.onRequestTimeout(),onStateChange:e=>{e===ne.Terminated&&(this.core.userAgentClients.delete(s),t===this._transaction&&this.dispose())},onTransportError:e=>this.onTransportError(e),receiveResponse:e=>this.receiveResponse(e)},t=new this.transactionConstructor(this.message,this.core.transport,e);this._transaction=t;const s=t.id+t.request.method;this.core.userAgentClients.set(s,this)}}class Ie extends $e{constructor(e,t,s){const i=e.createOutgoingRequestMessage(j.BYE,s);super(Te,e.userAgentCore,i,t),e.dispose()}}class Ce extends Se{constructor(e,t,s){super(e,t,s,ne.Trying,"sip.transaction.nist")}dispose(){this.J&&(clearTimeout(this.J),this.J=void 0),super.dispose()}get kind(){return"nist"}receiveRequest(e){switch(this.state){case ne.Trying:break;case ne.Proceeding:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")});break;case ne.Completed:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of final response.")});break;case ne.Terminated:break;default:throw new Error("Invalid state "+this.state)}}receiveResponse(e,t){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 ne.Trying:if(this.lastResponse=t,e>=100&&e<200)return this.stateTransition(ne.Proceeding),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send provisional response.")});if(e>=200&&e<=699)return this.stateTransition(ne.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send final response.")});break;case ne.Proceeding:if(this.lastResponse=t,e>=200&&e<=699)return this.stateTransition(ne.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send final response.")});break;case ne.Completed:return;case ne.Terminated:break;default:throw new Error("Invalid state "+this.state)}const s=`Non-INVITE server transaction received unexpected ${e} response from TU while in state ${this.state}.`;throw this.logger.error(s),new Error(s)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(ne.Terminated,!0)}typeToString(){return"non-INVITE server transaction"}stateTransition(e,t=!1){const s=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case ne.Trying:s();break;case ne.Proceeding:this.state!==ne.Trying&&s();break;case ne.Completed:this.state!==ne.Trying&&this.state!==ne.Proceeding&&s();break;case ne.Terminated:this.state!==ne.Proceeding&&this.state!==ne.Completed&&(t||s());break;default:s()}e===ne.Completed&&(this.J=setTimeout(()=>this.timerJ(),U.TIMER_J)),e===ne.Terminated&&this.dispose(),this.setState(e)}timerJ(){this.logger.debug(`Timer J expired for NON-INVITE server transaction ${this.id}.`),this.state===ne.Completed&&this.stateTransition(ne.Terminated)}}class Ae{constructor(e,t,s,i){this.transactionConstructor=e,this.core=t,this.message=s,this.delegate=i,this.logger=this.loggerFactory.getLogger("sip.user-agent-server"),this.toTag=s.toTag?s.toTag:E(),this.init()}dispose(){this.transaction.dispose()}get loggerFactory(){return this.core.loggerFactory}get transaction(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction}accept(e={statusCode:200}){if(!this.acceptable)throw new M(`${this.message.method} not acceptable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<200||t>299)throw new TypeError("Invalid statusCode: "+t);return this.reply(e)}progress(e={statusCode:180}){if(!this.progressable)throw new M(`${this.message.method} not progressable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<101||t>199)throw new TypeError("Invalid statusCode: "+t);return this.reply(e)}redirect(e,t={statusCode:302}){if(!this.redirectable)throw new M(`${this.message.method} not redirectable in state ${this.transaction.state}.`);const s=t.statusCode;if(s<300||s>399)throw new TypeError("Invalid statusCode: "+s);const i=new Array;e.forEach(e=>i.push("Contact: "+e.toString())),t.extraHeaders=(t.extraHeaders||[]).concat(i);return this.reply(t)}reject(e={statusCode:480}){if(!this.rejectable)throw new M(`${this.message.method} not rejectable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<400||t>699)throw new TypeError("Invalid statusCode: "+t);return this.reply(e)}trying(e){if(!this.tryingable)throw new M(`${this.message.method} not tryingable in state ${this.transaction.state}.`);return this.reply({statusCode:100})}receiveCancel(e){this.delegate&&this.delegate.onCancel&&this.delegate.onCancel(e)}get acceptable(){if(this.transaction instanceof Re)return this.transaction.state===ne.Proceeding||this.transaction.state===ne.Accepted;if(this.transaction instanceof Ce)return this.transaction.state===ne.Trying||this.transaction.state===ne.Proceeding;throw new Error("Unknown transaction type.")}get progressable(){if(this.transaction instanceof Re)return this.transaction.state===ne.Proceeding;if(this.transaction instanceof Ce)return!1;throw new Error("Unknown transaction type.")}get redirectable(){if(this.transaction instanceof Re)return this.transaction.state===ne.Proceeding;if(this.transaction instanceof Ce)return this.transaction.state===ne.Trying||this.transaction.state===ne.Proceeding;throw new Error("Unknown transaction type.")}get rejectable(){if(this.transaction instanceof Re)return this.transaction.state===ne.Proceeding;if(this.transaction instanceof Ce)return this.transaction.state===ne.Trying||this.transaction.state===ne.Proceeding;throw new Error("Unknown transaction type.")}get tryingable(){if(this.transaction instanceof Re)return this.transaction.state===ne.Proceeding;if(this.transaction instanceof Ce)return this.transaction.state===ne.Trying;throw new Error("Unknown transaction type.")}reply(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;const t=me(this.message,e);return this.transaction.receiveResponse(e.statusCode,t.message),t}init(){const e={loggerFactory:this.loggerFactory,onStateChange:e=>{e===ne.Terminated&&(this.core.userAgentServers.delete(s),this.dispose())},onTransportError:e=>{this.logger.error(e.message),this.delegate&&this.delegate.onTransportError?this.delegate.onTransportError(e):this.logger.error("User agent server response transport error.")}},t=new this.transactionConstructor(this.message,this.core.transport,e);this._transaction=t;const s=t.id;this.core.userAgentServers.set(t.id,this)}}class De extends Ae{constructor(e,t,s){super(Ce,e.userAgentCore,t,s)}}class He extends $e{constructor(e,t,s){const i=e.createOutgoingRequestMessage(j.INFO,s);super(Te,e.userAgentCore,i,t)}}class _e extends Ae{constructor(e,t,s){super(Ce,e.userAgentCore,t,s)}}class ke extends $e{constructor(e,t,s){super(Te,e,t,s)}}class xe extends Ae{constructor(e,t,s){super(Ce,e,t,s)}}class qe extends $e{constructor(e,t,s){const i=e.createOutgoingRequestMessage(j.NOTIFY,s);super(Te,e.userAgentCore,i,t)}}class Pe extends Ae{constructor(e,t,s){const i=void 0!==e.userAgentCore?e.userAgentCore:e;super(Ce,i,t,s)}}class Ne extends $e{constructor(e,t,s){const i=e.createOutgoingRequestMessage(j.PRACK,s);super(Te,e.userAgentCore,i,t),e.signalingStateTransition(i)}}class Me extends Ae{constructor(e,t,s){super(Ce,e.userAgentCore,t,s),e.signalingStateTransition(t),this.dialog=e}accept(e={statusCode:200}){return e.body&&this.dialog.signalingStateTransition(e.body),super.accept(e)}}class Oe extends $e{constructor(e,t,s){const i=e.createOutgoingRequestMessage(j.INVITE,s);super(Ee,e.userAgentCore,i,t),this.delegate=t,e.signalingStateTransition(i),e.reinviteUserAgentClient=this,this.dialog=e}receiveResponse(e){if(!this.authenticationGuard(e,this.dialog))return;const 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,session:this.dialog,prack:e=>{throw new Error("Unimplemented.")}});break;case/^2[0-9]{2}$/.test(t):this.dialog.signalingStateTransition(e),this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e,session:this.dialog,ack:e=>this.dialog.ack(e)});break;case/^3[0-9]{2}$/.test(t):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(t):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 "+t)}}}class Ue extends Ae{constructor(e,t,s){super(Re,e.userAgentCore,t,s),e.reinviteUserAgentServer=this,this.dialog=e}accept(e={statusCode:200}){e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(this.dialog.routeSet.map(e=>"Record-Route: "+e));const t=super.accept(e),s=this.dialog,i=Object.assign(Object.assign({},t),{session:s});return e.body&&this.dialog.signalingStateTransition(e.body),this.dialog.reConfirm(),i}progress(e={statusCode:180}){const t=super.progress(e),s=this.dialog,i=Object.assign(Object.assign({},t),{session:s});return e.body&&this.dialog.signalingStateTransition(e.body),i}redirect(e,t={statusCode:302}){throw this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,new Error("Unimplemented.")}reject(e={statusCode:488}){return this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,super.reject(e)}}class je extends $e{constructor(e,t,s){const i=e.createOutgoingRequestMessage(j.REFER,s);super(Te,e.userAgentCore,i,t)}}class Fe extends Ae{constructor(e,t,s){const i=void 0!==e.userAgentCore?e.userAgentCore:e;super(Ce,i,t,s)}}class Le extends ye{constructor(e,t,s,i){super(t,s),this.initialTransaction=e,this._signalingState=N.Initial,this.ackWait=!1,this.ackProcessing=!1,this.delegate=i,e instanceof Re&&(this.ackWait=!0),this.early||this.start2xxRetransmissionTimer(),this.signalingStateTransition(e.request),this.logger=t.loggerFactory.getLogger("sip.invite-dialog"),this.logger.log(`INVITE dialog ${this.id} constructed`)}dispose(){super.dispose(),this._signalingState=N.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`)}get sessionState(){return this.early?P.Early:this.ackWait?P.AckWait:this._signalingState===N.Closed?P.Terminated:P.Confirmed}get signalingState(){return this._signalingState}get offer(){return this._offer}get answer(){return this._answer}confirm(){this.early&&this.start2xxRetransmissionTimer(),super.confirm()}reConfirm(){this.reinviteUserAgentServer&&this.startReInvite2xxRetransmissionTimer()}ack(e={}){let t;if(this.logger.log(`INVITE dialog ${this.id} sending ACK request`),this.reinviteUserAgentClient){if(!(this.reinviteUserAgentClient.transaction instanceof Ee))throw new Error("Transaction not instance of InviteClientTransaction.");t=this.reinviteUserAgentClient.transaction,this.reinviteUserAgentClient=void 0}else{if(!(this.initialTransaction instanceof Ee))throw new Error("Initial transaction not instance of InviteClientTransaction.");t=this.initialTransaction}const s=this.createOutgoingRequestMessage(j.ACK,{cseq:t.request.cseq,extraHeaders:e.extraHeaders,body:e.body});return t.ackResponse(s),this.signalingStateTransition(s),{message:s}}bye(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending BYE request`),this.initialTransaction instanceof Re){if(this.early)throw new Error("UAS MUST NOT send a BYE on early dialogs.");if(this.ackWait&&this.initialTransaction.state!==ne.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 Ie(this,e,t)}info(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending INFO request`),this.early)throw new Error("Dialog not confirmed.");return new He(this,e,t)}invite(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 Oe(this,e,t)}message(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending MESSAGE request`),this.early)throw new Error("Dialog not confirmed.");const s=this.createOutgoingRequestMessage(j.MESSAGE,t);return new ke(this.core,s,e)}notify(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending NOTIFY request`),this.early)throw new Error("Dialog not confirmed.");return new qe(this,e,t)}prack(e,t){return this.logger.log(`INVITE dialog ${this.id} sending PRACK request`),new Ne(this,e,t)}refer(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending REFER request`),this.early)throw new Error("Dialog not confirmed.");return new je(this,e,t)}receiveRequest(e){if(this.logger.log(`INVITE dialog ${this.id} received ${e.method} request`),e.method!==j.ACK)if(this.sequenceGuard(e)){if(super.receiveRequest(e),e.method===j.INVITE){const t=()=>{const e=this.ackWait?"waiting for initial ACK":"processing initial ACK";this.logger.warn(`INVITE dialog ${this.id} received re-INVITE while ${e}`);let t="RFC 5407 suggests the following to avoid this race condition... ";t+=" Note: Implementation issues are outside the scope of this document,",t+=" but the following tip is provided for avoiding race conditions of",t+=" this type. The caller can delay sending re-INVITE F6 for some period",t+=" of time (2 seconds, perhaps), after which the caller can reasonably",t+=" assume that its ACK has been received. Implementors can decouple the",t+=" actions of the user (e.g., pressing the hold button) from the actions",t+=" of the protocol (the sending of re-INVITE F6), so that the UA can",t+=" behave like this. In this case, it is the implementor's choice as to",t+=" how long to wait. In most cases, such an implementation may be",t+=" useful to prevent the type of race condition shown in this section.",t+=" This document expresses no preference about whether or not they",t+=" should wait for an ACK to be delivered. After considering the impact",t+=" on user experience, implementors should decide whether or not to wait",t+=" for a while, because the user experience depends on the",t+=" implementation and has no direct bearing on protocol behavior.",this.logger.warn("RFC 5407 suggests the following to avoid this race condition... Note: Implementation issues are outside the scope of this document, but the following tip is provided for avoiding race conditions of this type. The caller can delay sending re-INVITE F6 for some period of time (2 seconds, perhaps), after which the caller can reasonably assume that its ACK has been received. Implementors can decouple the actions of the user (e.g., pressing the hold button) from the actions of the protocol (the sending of re-INVITE F6), so that the UA can behave like this. In this case, it is the implementor's choice as to how long to wait. In most cases, such an implementation may be useful to prevent the type of race condition shown in this section. This document expresses no preference about whether or not they should wait for an ACK to be delivered. After considering the impact on user experience, implementors should decide whether or not to wait for a while, because the user experience depends on the implementation and has no direct bearing on protocol behavior.")},s=["Retry-After: "+(Math.floor(10*Math.random())+1)];if(this.ackProcessing)return this.core.replyStateless(e,{statusCode:500,extraHeaders:s}),void t();if(this.ackWait&&this.signalingState!==N.Stable)return this.core.replyStateless(e,{statusCode:500,extraHeaders:s}),void t();if(this.reinviteUserAgentServer)return void this.core.replyStateless(e,{statusCode:500,extraHeaders:s});if(this.reinviteUserAgentClient)return void this.core.replyStateless(e,{statusCode:491})}if(e.method===j.INVITE){const t=e.parseHeader("contact");if(!t)throw new Error("Contact undefined.");if(!(t instanceof f))throw new Error("Contact not instance of NameAddrHeader.");this.dialogState.remoteTarget=t.uri}switch(e.method){case j.BYE:{const t=new De(this,e);this.delegate&&this.delegate.onBye?this.delegate.onBye(t):t.accept(),this.dispose()}break;case j.INFO:{const t=new _e(this,e);this.delegate&&this.delegate.onInfo?this.delegate.onInfo(t):t.reject({statusCode:469,extraHeaders:["Recv-Info :"]})}break;case j.INVITE:{const t=new Ue(this,e);this.signalingStateTransition(e),this.delegate&&this.delegate.onInvite?this.delegate.onInvite(t):t.reject({statusCode:488})}break;case j.MESSAGE:{const t=new xe(this.core,e);this.delegate&&this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case j.NOTIFY:{const t=new Pe(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(t):t.accept()}break;case j.PRACK:{const t=new Me(this,e);this.delegate&&this.delegate.onPrack?this.delegate.onPrack(t):t.accept()}break;case j.REFER:{const t=new Fe(this,e);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(t):t.reject()}break;default:this.logger.log(`INVITE dialog ${this.id} received unimplemented ${e.method} request`),this.core.replyStateless(e,{statusCode:501})}}else this.logger.log(`INVITE dialog ${this.id} rejected out of order ${e.method} request.`);else{if(this.ackWait){if(this.initialTransaction instanceof Ee)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);if(this.initialTransaction.request.cseq!==e.cseq)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);this.ackWait=!1}else{if(!this.reinviteUserAgentServer)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);if(this.reinviteUserAgentServer.transaction.request.cseq!==e.cseq)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);this.reinviteUserAgentServer=void 0}if(this.signalingStateTransition(e),this.delegate&&this.delegate.onAck){const t=this.delegate.onAck({message:e});t instanceof Promise&&(this.ackProcessing=!0,t.then(()=>this.ackProcessing=!1).catch(()=>this.ackProcessing=!1))}}}reliableSequenceGuard(e){const t=e.statusCode;if(!t)throw new Error("Status code undefined");if(t>100&&t<200){const t=e.getHeader("require"),s=e.getHeader("rseq"),i=t&&t.includes("100rel")&&s?Number(s):void 0;if(i){if(this.rseq&&this.rseq+1!==i)return!1;this.rseq=this.rseq?this.rseq+1:i}}return!0}signalingStateRollback(){this._signalingState!==N.HaveLocalOffer&&this.signalingState!==N.HaveRemoteOffer||this._rollbackOffer&&this._rollbackAnswer&&(this._signalingState=N.Stable,this._offer=this._rollbackOffer,this._answer=this._rollbackAnswer)}signalingStateTransition(e){const t=q(e);if(t&&"session"===t.contentDisposition){if(this._signalingState===N.Stable&&(this._rollbackOffer=this._offer,this._rollbackAnswer=this._answer),e instanceof A)switch(this._signalingState){case N.Initial:case N.Stable:this._signalingState=N.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case N.HaveLocalOffer:this._signalingState=N.Stable,this._answer=t;break;case N.HaveRemoteOffer:case N.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof D)switch(this._signalingState){case N.Initial:case N.Stable:this._signalingState=N.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case N.HaveLocalOffer:this._signalingState=N.Stable,this._answer=t;break;case N.HaveRemoteOffer:case N.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof H)switch(this._signalingState){case N.Initial:case N.Stable:this._signalingState=N.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case N.HaveLocalOffer:break;case N.HaveRemoteOffer:this._signalingState=N.Stable,this._answer=t;break;case N.Closed:break;default:throw new Error("Unexpected signaling state.")}if(x(e))switch(this._signalingState){case N.Initial:case N.Stable:this._signalingState=N.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case N.HaveLocalOffer:break;case N.HaveRemoteOffer:this._signalingState=N.Stable,this._answer=t;break;case N.Closed:break;default:throw new Error("Unexpected signaling state.")}}}start2xxRetransmissionTimer(){if(this.initialTransaction instanceof Re){const e=this.initialTransaction;let t=U.T1;const s=()=>{this.ackWait?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,U.T2),this.invite2xxTimer=setTimeout(s,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(s,t);const i=()=>{e.state===ne.Terminated&&(e.removeStateChangeListener(i),this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.ackWait&&(this.delegate&&this.delegate.onAckTimeout?this.delegate.onAckTimeout():this.bye()))};e.addStateChangeListener(i)}}startReInvite2xxRetransmissionTimer(){if(this.reinviteUserAgentServer&&this.reinviteUserAgentServer.transaction instanceof Re){const e=this.reinviteUserAgentServer.transaction;let t=U.T1;const s=()=>{this.reinviteUserAgentServer?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,U.T2),this.invite2xxTimer=setTimeout(s,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(s,t);const i=()=>{e.state===ne.Terminated&&(e.removeStateChangeListener(i),this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.reinviteUserAgentServer)};e.addStateChangeListener(i)}}}class Be extends $e{constructor(e,t,s){super(Ee,e,t,s),this.confirmedDialogAcks=new Map,this.confirmedDialogs=new Map,this.earlyDialogs=new Map,this.delegate=s}dispose(){this.earlyDialogs.forEach(e=>e.dispose()),this.earlyDialogs.clear(),super.dispose()}onTransportError(e){if(this.transaction.state===ne.Calling)return super.onTransportError(e);this.logger.error(e.message),this.logger.error("User agent client request transport error while sending ACK.")}receiveResponse(e){if(!this.authenticationGuard(e))return;const t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):return void(this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e}));case/^1[0-9]{2}$/.test(t):{if(!e.toTag)return void this.logger.warn("Non-100 1xx INVITE response received without a to tag, dropping.");if(!e.parseHeader("contact"))return void this.logger.error("Non-100 1xx INVITE response received without a Contact header field, dropping.");const t=ye.initialDialogStateForUserAgentClient(this.message,e);let s=this.earlyDialogs.get(t.id);if(!s){const e=this.transaction;if(!(e instanceof Ee))throw new Error("Transaction not instance of InviteClientTransaction.");s=new Le(e,this.core,t),this.earlyDialogs.set(s.id,s)}if(!s.reliableSequenceGuard(e))return void this.logger.warn("1xx INVITE reliable response received out of order or is a retransmission, dropping.");s.signalingState!==N.Initial&&s.signalingState!==N.HaveLocalOffer||s.signalingStateTransition(e);const i=s;this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:i,prack:e=>i.prack(void 0,e)})}return;case/^2[0-9]{2}$/.test(t):{if(!e.toTag)return void this.logger.error("2xx INVITE response received without a to tag, dropping.");if(!e.parseHeader("contact"))return void this.logger.error("2xx INVITE response received without a Contact header field, dropping.");const t=ye.initialDialogStateForUserAgentClient(this.message,e);let s=this.confirmedDialogs.get(t.id);if(s){const e=this.confirmedDialogAcks.get(t.id);if(e){const t=this.transaction;if(!(t instanceof Ee))throw new Error("Client transaction not instance of InviteClientTransaction.");t.ackResponse(e.message)}return}if(s=this.earlyDialogs.get(t.id),s)s.confirm(),s.recomputeRouteSet(e),this.earlyDialogs.delete(s.id),this.confirmedDialogs.set(s.id,s);else{const e=this.transaction;if(!(e instanceof Ee))throw new Error("Transaction not instance of InviteClientTransaction.");s=new Le(e,this.core,t),this.confirmedDialogs.set(s.id,s)}s.signalingState!==N.Initial&&s.signalingState!==N.HaveLocalOffer||s.signalingStateTransition(e);const i=s;if(this.delegate&&this.delegate.onAccept)this.delegate.onAccept({message:e,session:i,ack:e=>{const t=i.ack(e);return this.confirmedDialogAcks.set(i.id,t),t}});else{const e=i.ack();this.confirmedDialogAcks.set(i.id,e)}}return;case/^3[0-9]{2}$/.test(t):return this.earlyDialogs.forEach(e=>e.dispose()),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e}));case/^[4-6][0-9]{2}$/.test(t):return this.earlyDialogs.forEach(e=>e.dispose()),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e}));default:throw new Error("Invalid status code "+t)}throw new Error(`Executing what should be an unreachable code path receiving ${t} response.`)}}class Ve extends $e{constructor(e,t,s){super(Te,e,t,s)}}class Ge extends $e{constructor(e,t,s){super(Te,e,t,s)}}class Ke extends $e{constructor(e,t,s){const i=e.createOutgoingRequestMessage(j.SUBSCRIBE,s);super(Te,e.userAgentCore,i,t),this.dialog=e}waitNotifyStop(){}receiveResponse(e){if(e.statusCode&&e.statusCode>=200&&e.statusCode<300){const t=e.getHeader("Expires");if(t){const e=Number(t);this.dialog.subscriptionExpires>e&&(this.dialog.subscriptionExpires=e)}else this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE")}if(e.statusCode&&e.statusCode>=400&&e.statusCode<700){[404,405,410,416,480,481,482,483,484,485,489,501,604].includes(e.statusCode)&&this.dialog.terminate()}super.receiveResponse(e)}}class We extends ye{constructor(e,t,s,i,r,n){super(i,r),this.delegate=n,this._autoRefresh=!1,this._subscriptionEvent=e,this._subscriptionExpires=t,this._subscriptionExpiresInitial=t,this._subscriptionExpiresLastSet=Math.floor(Date.now()/1e3),this._subscriptionRefresh=void 0,this._subscriptionRefreshLastSet=void 0,this._subscriptionState=s,this.logger=i.loggerFactory.getLogger("sip.subscribe-dialog"),this.logger.log(`SUBSCRIBE dialog ${this.id} constructed`)}static initialDialogStateForSubscription(e,t){const s=t.getHeaders("record-route"),i=t.parseHeader("contact");if(!i)throw new Error("Contact undefined.");if(!(i instanceof f))throw new Error("Contact not instance of NameAddrHeader.");const r=i.uri,n=e.cseq,o=e.callId,a=e.fromTag,c=t.fromTag;if(!o)throw new Error("Call id undefined.");if(!a)throw new Error("From tag undefined.");if(!c)throw new Error("To tag undefined.");if(!e.from)throw new Error("From undefined.");if(!e.to)throw new Error("To undefined.");return{id:o+a+c,early:!1,callId:o,localTag:a,remoteTag:c,localSequenceNumber:n,remoteSequenceNumber:void 0,localURI:e.from.uri,remoteURI:e.to.uri,remoteTarget:r,routeSet:s,secure:!1}}dispose(){super.dispose(),this.N&&(clearTimeout(this.N),this.N=void 0),this.refreshTimerClear(),this.logger.log(`SUBSCRIBE dialog ${this.id} destroyed`)}get autoRefresh(){return this._autoRefresh}set autoRefresh(e){this._autoRefresh=!0,this.refreshTimerSet()}get subscriptionEvent(){return this._subscriptionEvent}get subscriptionExpires(){const e=Math.floor(Date.now()/1e3)-this._subscriptionExpiresLastSet,t=this._subscriptionExpires-e;return Math.max(t,0)}set subscriptionExpires(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){const t=this.subscriptionRefresh;(void 0===t||t>=e)&&this.refreshTimerSet()}}get subscriptionExpiresInitial(){return this._subscriptionExpiresInitial}get subscriptionRefresh(){if(void 0===this._subscriptionRefresh||void 0===this._subscriptionRefreshLastSet)return;const e=Math.floor(Date.now()/1e3)-this._subscriptionRefreshLastSet,t=this._subscriptionRefresh-e;return Math.max(t,0)}get subscriptionState(){return this._subscriptionState}receiveRequest(e){if(this.logger.log(`SUBSCRIBE dialog ${this.id} received ${e.method} request`),this.sequenceGuard(e))switch(super.receiveRequest(e),e.method){case j.NOTIFY:this.onNotify(e);break;default:this.logger.log(`SUBSCRIBE dialog ${this.id} received unimplemented ${e.method} request`),this.core.replyStateless(e,{statusCode:501})}else this.logger.log(`SUBSCRIBE dialog ${this.id} rejected out of order ${e.method} request.`)}refresh(){const e="Allow: "+F.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)}subscribe(e,t={}){if(this.subscriptionState!==ee.Pending&&this.subscriptionState!==ee.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`);const s=new Ke(this,e,t);return this.N&&(clearTimeout(this.N),this.N=void 0),this.N=setTimeout(()=>this.timerN(),U.TIMER_N),s}terminate(){this.stateTransition(ee.Terminated),this.onTerminated()}unsubscribe(){const e="Allow: "+F.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)}onNotify(e){const t=e.parseHeader("Event").event;if(!t||t!==this.subscriptionEvent)return void this.core.replyStateless(e,{statusCode:489});this.N&&(clearTimeout(this.N),this.N=void 0);const s=e.parseHeader("Subscription-State");if(!s||!s.state)return void this.core.replyStateless(e,{statusCode:489});const i=s.state,r=s.expires?Math.max(s.expires,0):void 0;switch(i){case"pending":this.stateTransition(ee.Pending,r);break;case"active":this.stateTransition(ee.Active,r);break;case"terminated":this.stateTransition(ee.Terminated,r);break;default:this.logger.warn("Unrecognized subscription state.")}const n=new Pe(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(n):n.accept()}onRefresh(e){this.delegate&&this.delegate.onRefresh&&this.delegate.onRefresh(e)}onTerminated(){this.delegate&&this.delegate.onTerminated&&this.delegate.onTerminated()}refreshTimerClear(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=void 0)}refreshTimerSet(){if(this.refreshTimerClear(),this.autoRefresh&&this.subscriptionExpires>0){const e=900*this.subscriptionExpires;this._subscriptionRefresh=Math.floor(e/1e3),this._subscriptionRefreshLastSet=Math.floor(Date.now()/1e3),this.refreshTimer=setTimeout(()=>{this.refreshTimer=void 0,this._subscriptionRefresh=void 0,this._subscriptionRefreshLastSet=void 0,this.onRefresh(this.refresh())},e)}}stateTransition(e,t){const s=()=>{this.logger.warn(`Invalid subscription state transition from ${this.subscriptionState} to ${e}`)};switch(e){case ee.Initial:case ee.NotifyWait:return void s();case ee.Pending:if(this.subscriptionState!==ee.NotifyWait&&this.subscriptionState!==ee.Pending)return void s();break;case ee.Active:case ee.Terminated:if(this.subscriptionState!==ee.NotifyWait&&this.subscriptionState!==ee.Pending&&this.subscriptionState!==ee.Active)return void s();break;default:return void s()}e===ee.Pending&&t&&(this.subscriptionExpires=t),e===ee.Active&&t&&(this.subscriptionExpires=t),e===ee.Terminated&&this.dispose(),this._subscriptionState=e}timerN(){this.logger.warn("Timer N expired for SUBSCRIBE dialog. Timed out waiting for NOTIFY."),this.subscriptionState!==ee.Terminated&&(this.stateTransition(ee.Terminated),this.onTerminated())}}class Ye extends $e{constructor(e,t,s){const i=t.getHeader("Event");if(!i)throw new Error("Event undefined");const r=t.getHeader("Expires");if(!r)throw new Error("Expires undefined");super(Te,e,t,s),this.delegate=s,this.subscriberId=t.callId+t.fromTag+i,this.subscriptionExpiresRequested=this.subscriptionExpires=Number(r),this.subscriptionEvent=i,this.subscriptionState=ee.NotifyWait,this.waitNotifyStart()}dispose(){super.dispose()}onNotify(e){const t=e.message.parseHeader("Event").event;if(!t||t!==this.subscriptionEvent)return this.logger.warn("Failed to parse event."),void e.reject({statusCode:489});const s=e.message.parseHeader("Subscription-State");if(!s||!s.state)return this.logger.warn("Failed to parse subscription state."),void e.reject({statusCode:489});const i=s.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){if(!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=s.expires?Math.min(this.subscriptionExpires,Math.max(s.expires,0)):this.subscriptionExpires,i){case"pending":this.subscriptionState=ee.Pending;break;case"active":this.subscriptionState=ee.Active;break;case"terminated":this.subscriptionState=ee.Terminated;break;default:throw new Error(`Unrecognized state ${i}.`)}if(this.subscriptionState!==ee.Terminated){const t=We.initialDialogStateForSubscription(this.message,e.message);this.dialog=new We(this.subscriptionEvent,this.subscriptionExpires,this.subscriptionState,this.core,t)}if(this.delegate&&this.delegate.onNotify){const t=e,s=this.dialog;this.delegate.onNotify({request:t,subscription:s})}else e.accept()}waitNotifyStart(){this.N||(this.core.subscribers.set(this.subscriberId,this),this.N=setTimeout(()=>this.timerN(),U.TIMER_N))}waitNotifyStop(){this.N&&(this.core.subscribers.delete(this.subscriberId),clearTimeout(this.N),this.N=void 0)}receiveResponse(e){if(this.authenticationGuard(e)){if(e.statusCode&&e.statusCode>=200&&e.statusCode<300){const t=e.getHeader("Expires");if(t){const e=Number(t);e>this.subscriptionExpiresRequested&&this.logger.warn("Expires header in a 200-class response to SUBSCRIBE with a higher value than the one in the request"),ethis.subscriptionExpires&&(this.dialog.subscriptionExpires=this.subscriptionExpires)}e.statusCode&&e.statusCode>=300&&e.statusCode<700&&this.waitNotifyStop(),super.receiveResponse(e)}}timerN(){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()}}class Ze extends Ae{constructor(e,t,s){super(Re,e,t,s),this.core=e}dispose(){this.earlyDialog&&this.earlyDialog.dispose(),super.dispose()}accept(e={statusCode:200}){if(!this.acceptable)throw new M(`${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{const e=this.transaction;if(!(e instanceof Re))throw new Error("Transaction not instance of InviteClientTransaction.");const t=ye.initialDialogStateForUserAgentServer(this.message,this.toTag);this.confirmedDialog=new Le(e,this.core,t)}const t=this.message.getHeaders("record-route").map(e=>"Record-Route: "+e),s="Contact: "+this.core.configuration.contact.toString(),i="Allow: "+F.toString();if(!e.body)if(this.confirmedDialog.signalingState===N.Stable)e.body=this.confirmedDialog.answer;else if(this.confirmedDialog.signalingState===N.Initial||this.confirmedDialog.signalingState===N.HaveRemoteOffer)throw new Error("Response must have a body.");e.statusCode=e.statusCode||200,e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(t),e.extraHeaders.push(i),e.extraHeaders.push(s);const r=super.accept(e),n=this.confirmedDialog,o=Object.assign(Object.assign({},r),{session:n});return e.body&&this.confirmedDialog.signalingState!==N.Stable&&this.confirmedDialog.signalingStateTransition(e.body),o}progress(e={statusCode:180}){if(!this.progressable)throw new M(`${this.message.method} not progressable in state ${this.transaction.state}.`);if(!this.earlyDialog){const e=this.transaction;if(!(e instanceof Re))throw new Error("Transaction not instance of InviteClientTransaction.");const t=ye.initialDialogStateForUserAgentServer(this.message,this.toTag,!0);this.earlyDialog=new Le(e,this.core,t)}const t=this.message.getHeaders("record-route").map(e=>"Record-Route: "+e),s="Contact: "+this.core.configuration.contact;e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(t),e.extraHeaders.push(s);const i=super.progress(e),r=this.earlyDialog,n=Object.assign(Object.assign({},i),{session:r});return e.body&&this.earlyDialog.signalingState!==N.Stable&&this.earlyDialog.signalingStateTransition(e.body),n}redirect(e,t={statusCode:302}){return super.redirect(e,t)}reject(e={statusCode:486}){return super.reject(e)}}class Je extends Ae{constructor(e,t,s){super(Ce,e,t,s),this.core=e}}class ze extends Ae{constructor(e,t,s){super(Ce,e,t,s),this.core=e}}const Xe=["application/sdp","application/dtmf-relay"];class Qe{constructor(e,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")}dispose(){this.reset()}reset(){this.dialogs.forEach(e=>e.dispose()),this.dialogs.clear(),this.subscribers.forEach(e=>e.dispose()),this.subscribers.clear(),this.userAgentClients.forEach(e=>e.dispose()),this.userAgentClients.clear(),this.userAgentServers.forEach(e=>e.dispose()),this.userAgentServers.clear()}get loggerFactory(){return this.configuration.loggerFactory}get transport(){const e=this.configuration.transportAccessor();if(!e)throw new Error("Transport undefined.");return e}invite(e,t){return new Be(this,e,t)}message(e,t){return new ke(this,e,t)}publish(e,t){return new Ve(this,e,t)}register(e,t){return new Ge(this,e,t)}subscribe(e,t){return new Ye(this,e,t)}request(e,t){return new $e(Te,this,e,t)}makeOutgoingRequestMessage(e,t,s,i,r,n,o){const a=this.configuration.sipjsId,c=this.configuration.displayName,h=this.configuration.viaForceRport,d=this.configuration.hackViaTcp,l=this.configuration.supportedOptionTags.slice();e===j.REGISTER&&l.push("path","gruu"),e===j.INVITE&&(this.configuration.contact.pubGruu||this.configuration.contact.tempGruu)&&l.push("gruu");const g={callIdPrefix:a,forceRport:h,fromDisplayName:c,hackViaTcp:d,optionTags:l,routeSet:this.configuration.routeSet,userAgentString:this.configuration.userAgentHeaderFieldValue,viaHost:this.configuration.viaHost},u=Object.assign(Object.assign({},g),r);return new H(e,t,s,i,u,n,o)}receiveIncomingRequestFromTransport(e){this.receiveRequestFromTransport(e)}receiveIncomingResponseFromTransport(e){this.receiveResponseFromTransport(e)}replyStateless(e,t){const s=this.configuration.userAgentHeaderFieldValue,i=this.configuration.supportedOptionTagsResponse;t=Object.assign(Object.assign({},t),{userAgent:s,supported:i});const r=me(e,t);return this.transport.send(r.message).catch(t=>{t instanceof Error&&this.logger.error(t.message),this.logger.error(`Transport error occurred sending stateless reply to ${e.method} request.`)}),r}receiveRequestFromTransport(e){const t=e.viaBranch,s=this.userAgentServers.get(t);e.method===j.ACK&&s&&s.transaction.state===ne.Accepted&&s instanceof Ze?this.logger.warn(`Discarding out of dialog ACK after 2xx response sent on transaction ${t}.`):e.method!==j.CANCEL?s?s.transaction.receiveRequest(e):this.receiveRequest(e):s?(this.replyStateless(e,{statusCode:200}),s.transaction instanceof Re&&s.transaction.state===ne.Proceeding&&s instanceof Ze&&s.receiveCancel(e)):this.replyStateless(e,{statusCode:481})}receiveRequest(e){if(!F.includes(e.method)){const t="Allow: "+F.toString();return void this.replyStateless(e,{statusCode:405,extraHeaders:[t]})}if(!e.ruri)throw new Error("Request-URI undefined.");if("sip"!==e.ruri.scheme)return void this.replyStateless(e,{statusCode:416});const t=e.ruri,s=e=>!!e&&e.user===t.user;if(!s(this.configuration.aor)&&!(s(this.configuration.contact.uri)||s(this.configuration.contact.pubGruu)||s(this.configuration.contact.tempGruu)))return this.logger.warn("Request-URI does not point to us."),void(e.method!==j.ACK&&this.replyStateless(e,{statusCode:404}));if(e.method!==j.INVITE||e.hasHeader("Contact")){if(!e.toTag){const t=e.viaBranch;if(!this.userAgentServers.has(t)){if(Array.from(this.userAgentServers.values()).some(t=>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"})}receiveInsideDialogRequest(e){if(e.method===j.NOTIFY){const t=e.parseHeader("Event");if(!t||!t.event)return void this.replyStateless(e,{statusCode:489});const s=e.callId+e.toTag+t.event,i=this.subscribers.get(s);if(i){const t=new Pe(this,e);return void i.onNotify(t)}}const t=e.callId+e.toTag+e.fromTag,s=this.dialogs.get(t);if(s){if(e.method===j.OPTIONS){const t="Allow: "+F.toString(),s="Accept: "+Xe.toString();return void this.replyStateless(e,{statusCode:200,extraHeaders:[t,s]})}s.receiveRequest(e)}else e.method!==j.ACK&&this.replyStateless(e,{statusCode:481})}receiveOutsideDialogRequest(e){switch(e.method){case j.ACK:break;case j.BYE:this.replyStateless(e,{statusCode:481});break;case j.CANCEL:throw new Error(`Unexpected out of dialog request method ${e.method}.`);case j.INFO:this.replyStateless(e,{statusCode:405});break;case j.INVITE:{const t=new Ze(this,e);this.delegate.onInvite?this.delegate.onInvite(t):t.reject()}break;case j.MESSAGE:{const t=new xe(this,e);this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case j.NOTIFY:{const t=new Pe(this,e);this.delegate.onNotify?this.delegate.onNotify(t):t.reject({statusCode:405})}break;case j.OPTIONS:{const t="Allow: "+F.toString(),s="Accept: "+Xe.toString();this.replyStateless(e,{statusCode:200,extraHeaders:[t,s]})}break;case j.REFER:{const t=new Fe(this,e);this.delegate.onRefer?this.delegate.onRefer(t):t.reject({statusCode:405})}break;case j.REGISTER:{const t=new Je(this,e);this.delegate.onRegister?this.delegate.onRegister(t):t.reject({statusCode:405})}break;case j.SUBSCRIBE:{const t=new ze(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}.`)}}receiveResponseFromTransport(e){if(e.getHeaders("via").length>1)return void this.logger.warn("More than one Via header field present in the response, dropping");const t=e.viaBranch+e.method,s=this.userAgentClients.get(t);s?s.transaction.receiveResponse(e):this.logger.warn(`Discarding unmatched ${e.statusCode} response to ${e.method} ${t}.`)}}var et;function tt(){return e=>e.audio||e.video?void 0===navigator.mediaDevices?Promise.reject(new Error("Media devices not available in insecure contexts.")):navigator.mediaDevices.getUserMedia.call(navigator.mediaDevices,e):Promise.resolve(new MediaStream)}function st(){return{bundlePolicy:"balanced",certificates:void 0,iceCandidatePoolSize:0,iceServers:[{urls:"stun:stun.l.google.com:19302"}],iceTransportPolicy:"all",peerIdentity:void 0,rtcpMuxPolicy:"require"}}!function(e){function t(e,t){let s=t,i=0,r=0;if(e.substring(s,s+2).match(/(^\r\n)/))return-2;for(;0===i;){if(r=e.indexOf("\r\n",s),-1===r)return r;!e.substring(r+2,r+4).match(/(^\r\n)/)&&e.charAt(r+2).match(/(^\s+)/)?s=r+2:i=r}return i}function s(e,t,s,i){const r=t.indexOf(":",s),n=t.substring(s,r).trim(),o=t.substring(r+1,i).trim();let a;switch(n.toLowerCase()){case"via":case"v":e.addHeader("via",o),1===e.getHeaders("via").length?(a=e.parseHeader("Via"),a&&(e.via=a,e.viaBranch=a.branch)):a=0;break;case"from":case"f":e.setHeader("from",o),a=e.parseHeader("from"),a&&(e.from=a,e.fromTag=a.getParam("tag"));break;case"to":case"t":e.setHeader("to",o),a=e.parseHeader("to"),a&&(e.to=a,e.toTag=a.getParam("tag"));break;case"record-route":if(a=b.parse(o,"Record_Route"),-1===a){a=void 0;break}if(!(a instanceof Array)){a=void 0;break}a.forEach(t=>{e.addHeader("record-route",o.substring(t.position,t.offset)),e.headers["Record-Route"][e.getHeaders("record-route").length-1].parsed=t.parsed});break;case"call-id":case"i":e.setHeader("call-id",o),a=e.parseHeader("call-id"),a&&(e.callId=o);break;case"contact":case"m":if(a=b.parse(o,"Contact"),-1===a){a=void 0;break}if(!(a instanceof Array)){a=void 0;break}a.forEach(t=>{e.addHeader("contact",o.substring(t.position,t.offset)),e.headers.Contact[e.getHeaders("contact").length-1].parsed=t.parsed});break;case"content-length":case"l":e.setHeader("content-length",o),a=e.parseHeader("content-length");break;case"content-type":case"c":e.setHeader("content-type",o),a=e.parseHeader("content-type");break;case"cseq":e.setHeader("cseq",o),a=e.parseHeader("cseq"),a&&(e.cseq=a.value),e instanceof D&&(e.method=a.method);break;case"max-forwards":e.setHeader("max-forwards",o),a=e.parseHeader("max-forwards");break;case"www-authenticate":e.setHeader("www-authenticate",o),a=e.parseHeader("www-authenticate");break;case"proxy-authenticate":e.setHeader("proxy-authenticate",o),a=e.parseHeader("proxy-authenticate");break;case"refer-to":case"r":e.setHeader("refer-to",o),a=e.parseHeader("refer-to"),a&&(e.referTo=a);break;default:e.addHeader(n.toLowerCase(),o),a=0}return void 0!==a||{error:"error parsing header '"+n+"'"}}e.getHeader=t,e.parseHeader=s,e.parseMessage=function(e,i){let r=0,n=e.indexOf("\r\n");if(-1===n)return void i.warn("no CRLF found, not a SIP message, discarded");const o=e.substring(0,n),a=b.parse(o,"Request_Response");let c,h;if(-1!==a){for(a.status_code?(c=new D,c.statusCode=a.status_code,c.reasonPhrase=a.reason_phrase):(c=new A,c.method=a.method,c.ruri=a.uri),c.data=e,r=n+2;;){if(n=t(e,r),-2===n){h=r+2;break}if(-1===n)return void i.error("malformed message");const o=s(c,e,r,n);if(o&&!0!==o)return void i.error(o.error);r=n+2}return c.hasHeader("content-length")?c.body=e.substr(h,Number(c.getHeader("content-length"))):c.body=e.substring(h),c}i.warn('error parsing first line of SIP message: "'+o+'"')}}(et||(et={}));class it{constructor(e,t,s){e.debug("SessionDescriptionHandler.constructor"),this.logger=e,this.mediaStreamFactory=t,this.sessionDescriptionHandlerConfiguration=s,this._localMediaStream=new MediaStream,this._remoteMediaStream=new MediaStream,this._peerConnection=new RTCPeerConnection(null==s?void 0:s.peerConnectionConfiguration),this.initPeerConnectionEventHandlers()}get localMediaStream(){return this._localMediaStream}get remoteMediaStream(){return this._remoteMediaStream}get dataChannel(){return this._dataChannel}get peerConnection(){return this._peerConnection}get peerConnectionDelegate(){return this._peerConnectionDelegate}set peerConnectionDelegate(e){this._peerConnectionDelegate=e}static dispatchAddTrackEvent(e,t){e.dispatchEvent(new MediaStreamTrackEvent("addtrack",{track:t}))}static dispatchRemoveTrackEvent(e,t){e.dispatchEvent(new MediaStreamTrackEvent("removetrack",{track:t}))}close(){this.logger.debug("SessionDescriptionHandler.close"),void 0!==this._peerConnection&&(this._peerConnection.getReceivers().forEach(e=>{e.track&&e.track.stop()}),this._peerConnection.getSenders().forEach(e=>{e.track&&e.track.stop()}),this._dataChannel&&this._dataChannel.close(),this._peerConnection.close(),this._peerConnection=void 0)}getDescription(e,t){var s,i;if(this.logger.debug("SessionDescriptionHandler.getDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));this.onDataChannel=null==e?void 0:e.onDataChannel;const r=null===(s=null==e?void 0:e.offerOptions)||void 0===s?void 0:s.iceRestart,n=void 0===(null==e?void 0:e.iceGatheringTimeout)?null===(i=this.sessionDescriptionHandlerConfiguration)||void 0===i?void 0:i.iceGatheringTimeout:null==e?void 0:e.iceGatheringTimeout;return this.getLocalMediaStream(e).then(()=>this.createDataChannel(e)).then(()=>this.createLocalOfferOrAnswer(e)).then(e=>this.applyModifiers(e,t)).then(e=>this.setLocalSessionDescription(e)).then(()=>this.waitForIceGatheringComplete(r,n)).then(()=>this.getLocalSessionDescription()).then(e=>({body:e.sdp,contentType:"application/sdp"})).catch(e=>{throw this.logger.error("SessionDescriptionHandler.getDescription failed - "+e),e})}hasDescription(e){return this.logger.debug("SessionDescriptionHandler.hasDescription"),"application/sdp"===e}sendDtmf(e,t){if(this.logger.debug("SessionDescriptionHandler.sendDtmf"),void 0===this._peerConnection)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - peer connection closed"),!1;const s=this._peerConnection.getSenders();if(0===s.length)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no senders"),!1;const i=s[0].dtmf;if(!i)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no DTMF sender"),!1;const r=null==t?void 0:t.duration,n=null==t?void 0:t.interToneGap;try{i.insertDTMF(e,r,n)}catch(e){return this.logger.error(e),!1}return this.logger.log("SessionDescriptionHandler.sendDtmf sent via RTP: "+e.toString()),!0}setDescription(e,t,s){if(this.logger.debug("SessionDescriptionHandler.setDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));this.onDataChannel=null==t?void 0:t.onDataChannel;const i="have-local-offer"===this._peerConnection.signalingState?"answer":"offer";return this.getLocalMediaStream(t).then(()=>this.applyModifiers({sdp:e,type:i},s)).then(e=>this.setRemoteSessionDescription(e)).catch(e=>{throw this.logger.error("SessionDescriptionHandler.setDescription failed - "+e),e})}applyModifiers(e,t){return this.logger.debug("SessionDescriptionHandler.applyModifiers"),t&&0!==t.length?t.reduce((e,t)=>e.then(t),Promise.resolve(e)).then(e=>{if(this.logger.debug("SessionDescriptionHandler.applyModifiers - modified sdp"),!e.sdp||!e.type)throw new Error("Invalid SDP.");return{sdp:e.sdp,type:e.type}}):Promise.resolve(e)}createDataChannel(e){if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));if(!0!==(null==e?void 0:e.dataChannel))return Promise.resolve();if(this._dataChannel)return Promise.resolve();switch(this._peerConnection.signalingState){case"stable":this.logger.debug("SessionDescriptionHandler.createDataChannel - creating data channel");try{return this._dataChannel=this._peerConnection.createDataChannel((null==e?void 0:e.dataChannelLabel)||"",null==e?void 0:e.dataChannelOptions),this.onDataChannel&&this.onDataChannel(this._dataChannel),Promise.resolve()}catch(e){return Promise.reject(e)}case"have-remote-offer":return Promise.resolve();case"have-local-offer":case"have-local-pranswer":case"have-remote-pranswer":case"closed":default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}}createLocalOfferOrAnswer(e){if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));switch(this._peerConnection.signalingState){case"stable":return this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP offer"),this._peerConnection.createOffer(null==e?void 0:e.offerOptions);case"have-remote-offer":return this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP answer"),this._peerConnection.createAnswer(null==e?void 0:e.answerOptions);case"have-local-offer":case"have-local-pranswer":case"have-remote-pranswer":case"closed":default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}}getLocalMediaStream(e){if(this.logger.debug("SessionDescriptionHandler.getLocalMediaStream"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));let t=Object.assign({},null==e?void 0:e.constraints);if(this.localMediaStreamConstraints){if(t.audio=t.audio||this.localMediaStreamConstraints.audio,t.video=t.video||this.localMediaStreamConstraints.video,JSON.stringify(this.localMediaStreamConstraints.audio)===JSON.stringify(t.audio)&&JSON.stringify(this.localMediaStreamConstraints.video)===JSON.stringify(t.video))return Promise.resolve()}else void 0===t.audio&&void 0===t.video&&(t={audio:!0});return this.localMediaStreamConstraints=t,this.mediaStreamFactory(t,this).then(e=>this.setLocalMediaStream(e))}setLocalMediaStream(e){if(this.logger.debug("SessionDescriptionHandler.setLocalMediaStream"),!this._peerConnection)throw new Error("Peer connection undefined.");const t=this._peerConnection,s=this._localMediaStream,i=[],r=e=>{const r=e.kind;if("audio"!==r&&"video"!==r)throw new Error(`Unknown new track kind ${r}.`);const n=t.getSenders().find(e=>e.track&&e.track.kind===r);n?i.push(new Promise(e=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - replacing sender ${r} track`),e()}).then(()=>n.replaceTrack(e).then(()=>{const t=s.getTracks().find(e=>e.kind===r);t&&(t.stop(),s.removeTrack(t),it.dispatchRemoveTrackEvent(s,t)),s.addTrack(e),it.dispatchAddTrackEvent(s,e)}).catch(e=>{throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to replace sender ${r} track`),e}))):i.push(new Promise(e=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - adding sender ${r} track`),e()}).then(()=>{try{t.addTrack(e,s)}catch(e){throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to add sender ${r} track`),e}s.addTrack(e),it.dispatchAddTrackEvent(s,e)}))},n=e.getAudioTracks();n.length&&r(n[0]);const o=e.getVideoTracks();return o.length&&r(o[0]),i.reduce((e,t)=>e.then(()=>t),Promise.resolve())}getLocalSessionDescription(){if(this.logger.debug("SessionDescriptionHandler.getLocalSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));const e=this._peerConnection.localDescription;return e?Promise.resolve(e):Promise.reject(new Error("Failed to get local session description"))}setLocalSessionDescription(e){return this.logger.debug("SessionDescriptionHandler.setLocalSessionDescription"),void 0===this._peerConnection?Promise.reject(new Error("Peer connection closed.")):this._peerConnection.setLocalDescription(e)}setRemoteSessionDescription(e){if(this.logger.debug("SessionDescriptionHandler.setRemoteSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));const t=e.sdp;let s;switch(this._peerConnection.signalingState){case"stable":s="offer";break;case"have-local-offer":s="answer";break;case"have-local-pranswer":case"have-remote-offer":case"have-remote-pranswer":case"closed":default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}return t?this._peerConnection.setRemoteDescription({sdp:t,type:s}):(this.logger.error("SessionDescriptionHandler.setRemoteSessionDescription failed - cannot set null sdp"),Promise.reject(new Error("SDP is undefined")))}setRemoteTrack(e){this.logger.debug("SessionDescriptionHandler.setRemoteTrack");const t=this._remoteMediaStream;t.getTrackById(e.id)?this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - have remote ${e.kind} track`):"audio"===e.kind?(this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${e.kind} track`),t.getAudioTracks().forEach(e=>{e.stop(),t.removeTrack(e),it.dispatchRemoveTrackEvent(t,e)}),t.addTrack(e),it.dispatchAddTrackEvent(t,e)):"video"===e.kind&&(this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${e.kind} track`),t.getVideoTracks().forEach(e=>{e.stop(),t.removeTrack(e),it.dispatchRemoveTrackEvent(t,e)}),t.addTrack(e),it.dispatchAddTrackEvent(t,e))}iceGatheringComplete(){this.logger.debug("SessionDescriptionHandler.iceGatheringComplete"),void 0!==this.iceGatheringCompleteTimeoutId&&(this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - clearing timeout"),clearTimeout(this.iceGatheringCompleteTimeoutId),this.iceGatheringCompleteTimeoutId=void 0),void 0!==this.iceGatheringCompletePromise&&(this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - resolving promise"),this.iceGatheringCompleteResolve&&this.iceGatheringCompleteResolve(),this.iceGatheringCompletePromise=void 0,this.iceGatheringCompleteResolve=void 0,this.iceGatheringCompleteReject=void 0)}waitForIceGatheringComplete(e=!1,t=0){return this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete"),void 0===this._peerConnection?Promise.reject("Peer connection closed."):e||"complete"!==this._peerConnection.iceGatheringState?(void 0!==this.iceGatheringCompletePromise&&(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - rejecting prior waiting promise"),this.iceGatheringCompleteReject&&this.iceGatheringCompleteReject(new Error("Promise superseded.")),this.iceGatheringCompletePromise=void 0,this.iceGatheringCompleteResolve=void 0,this.iceGatheringCompleteReject=void 0),this.iceGatheringCompletePromise=new Promise((e,s)=>{this.iceGatheringCompleteResolve=e,this.iceGatheringCompleteReject=s,t>0&&(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout in "+t),this.iceGatheringCompleteTimeoutId=setTimeout(()=>{this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout"),this.iceGatheringComplete()},t))}),this.iceGatheringCompletePromise):(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - already complete"),Promise.resolve())}initPeerConnectionEventHandlers(){if(this.logger.debug("SessionDescriptionHandler.initPeerConnectionEventHandlers"),!this._peerConnection)throw new Error("Peer connection undefined.");const e=this._peerConnection;e.onconnectionstatechange=t=>{var s;const i=e.connectionState;this.logger.debug("SessionDescriptionHandler.onconnectionstatechange "+i),(null===(s=this._peerConnectionDelegate)||void 0===s?void 0:s.onconnectionstatechange)&&this._peerConnectionDelegate.onconnectionstatechange(t)},e.ondatachannel=e=>{var t;this.logger.debug("SessionDescriptionHandler.ondatachannel"),this._dataChannel=e.channel,this.onDataChannel&&this.onDataChannel(this._dataChannel),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.ondatachannel)&&this._peerConnectionDelegate.ondatachannel(e)},e.onicecandidate=e=>{var t;this.logger.debug("SessionDescriptionHandler.onicecandidate"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onicecandidate)&&this._peerConnectionDelegate.onicecandidate(e)},e.onicecandidateerror=e=>{var t;this.logger.debug("SessionDescriptionHandler.onicecandidateerror"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onicecandidateerror)&&this._peerConnectionDelegate.onicecandidateerror(e)},e.oniceconnectionstatechange=t=>{var s;const i=e.iceConnectionState;this.logger.debug("SessionDescriptionHandler.oniceconnectionstatechange "+i),(null===(s=this._peerConnectionDelegate)||void 0===s?void 0:s.oniceconnectionstatechange)&&this._peerConnectionDelegate.oniceconnectionstatechange(t)},e.onicegatheringstatechange=t=>{var s;const i=e.iceGatheringState;this.logger.debug("SessionDescriptionHandler.onicegatheringstatechange "+i),"complete"===i&&this.iceGatheringComplete(),(null===(s=this._peerConnectionDelegate)||void 0===s?void 0:s.onicegatheringstatechange)&&this._peerConnectionDelegate.onicegatheringstatechange(t)},e.onnegotiationneeded=e=>{var t;this.logger.debug("SessionDescriptionHandler.onnegotiationneeded"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onnegotiationneeded)&&this._peerConnectionDelegate.onnegotiationneeded(e)},e.onsignalingstatechange=t=>{var s;const i=e.signalingState;this.logger.debug("SessionDescriptionHandler.onsignalingstatechange "+i),(null===(s=this._peerConnectionDelegate)||void 0===s?void 0:s.onsignalingstatechange)&&this._peerConnectionDelegate.onsignalingstatechange(t)},e.onstatsended=e=>{var t;this.logger.debug("SessionDescriptionHandler.onstatsended"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onstatsended)&&this._peerConnectionDelegate.onstatsended(e)},e.ontrack=e=>{var t;const s=e.track.kind,i=e.track.enabled?"enabled":"disabled";this.logger.debug(`SessionDescriptionHandler.ontrack ${s} ${i}`),this.setRemoteTrack(e.track),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.ontrack)&&this._peerConnectionDelegate.ontrack(e)}}}function rt(e){return(t,s)=>{void 0===e&&(e=tt());const i={iceGatheringTimeout:void 0!==(null==s?void 0:s.iceGatheringTimeout)?null==s?void 0:s.iceGatheringTimeout:5e3,peerConnectionConfiguration:Object.assign(Object.assign({},{bundlePolicy:"balanced",certificates:void 0,iceCandidatePoolSize:0,iceServers:[{urls:"stun:stun.l.google.com:19302"}],iceTransportPolicy:"all",peerIdentity:void 0,rtcpMuxPolicy:"require"}),null==s?void 0:s.peerConnectionConfiguration)},r=t.userAgent.getLogger("sip.SessionDescriptionHandler");return new it(r,e,i)}}class nt{constructor(e,t){if(this._state=se.Disconnected,this.transitioningState=!1,this._stateEventEmitter=new g,this.logger=e,t){const e=t,s=null==e?void 0:e.wsServers,i=null==e?void 0:e.maxReconnectionAttempts;if(void 0!==s){const e='The transport option "wsServers" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(void 0!==i){const e='The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}s&&!t.server&&("string"==typeof s&&(t.server=s),s instanceof Array&&(t.server=s[0]))}this.configuration=Object.assign(Object.assign({},nt.defaultOptions),t);const s=this.configuration.server,i=b.parse(s,"absoluteURI");if(-1===i)throw this.logger.error(`Invalid WebSocket Server URL "${s}"`),new Error("Invalid WebSocket Server URL");if(!["wss","ws","udp"].includes(i.scheme))throw this.logger.error(`Invalid scheme in WebSocket Server URL "${s}"`),new Error("Invalid scheme in WebSocket Server URL");this._protocol=i.scheme.toUpperCase()}dispose(){return this.disconnect()}get protocol(){return this._protocol}get server(){return this.configuration.server}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get ws(){return this._ws}connect(){return this._connect()}disconnect(){return this._disconnect()}isConnected(){return this.state===se.Connected}send(e){return this._send(e)}_connect(){switch(this.logger.log("Connecting "+this.server),this.state){case se.Connecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(se.Connecting));if(!this.connectPromise)throw new Error("Connect promise must be defined.");return this.connectPromise;case se.Connected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(se.Connecting));if(this.connectPromise)throw new Error("Connect promise must not be defined.");return Promise.resolve();case se.Disconnecting:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(se.Connecting)}catch(e){if(e instanceof d)return Promise.reject(e);throw e}break;case se.Disconnected:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(se.Connecting)}catch(e){if(e instanceof d)return Promise.reject(e);throw e}break;default:throw new Error("Unknown state")}let e;try{e=new WebSocket(this.server,"sip"),e.binaryType="arraybuffer",e.addEventListener("close",t=>this.onWebSocketClose(t,e)),e.addEventListener("error",t=>this.onWebSocketError(t,e)),e.addEventListener("open",t=>this.onWebSocketOpen(t,e)),e.addEventListener("message",t=>this.onWebSocketMessage(t,e)),this._ws=e}catch(e){return this._ws=void 0,this.logger.error("WebSocket construction failed."),this.logger.error(e),new Promise((t,s)=>{this.connectResolve=t,this.connectReject=s,this.transitionState(se.Disconnected,e)})}return this.connectPromise=new Promise((t,s)=>{this.connectResolve=t,this.connectReject=s,this.connectTimeout=setTimeout(()=>{this.logger.warn("Connect timed out. Exceeded time set in configuration.connectionTimeout: "+this.configuration.connectionTimeout+"s."),e.close(1e3)},1e3*this.configuration.connectionTimeout)}),this.connectPromise}_disconnect(){switch(this.logger.log("Disconnecting "+this.server),this.state){case se.Connecting:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(se.Disconnecting)}catch(e){if(e instanceof d)return Promise.reject(e);throw e}break;case se.Connected:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(se.Disconnecting)}catch(e){if(e instanceof d)return Promise.reject(e);throw e}break;case se.Disconnecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(se.Disconnecting));if(!this.disconnectPromise)throw new Error("Disconnect promise must be defined.");return this.disconnectPromise;case se.Disconnected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(se.Disconnecting));if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");return Promise.resolve();default:throw new Error("Unknown state")}if(!this._ws)throw new Error("WebSocket must be defined.");const e=this._ws;return this.disconnectPromise=new Promise((t,s)=>{this.disconnectResolve=t,this.disconnectReject=s;try{e.close(1e3)}catch(e){throw this.logger.error("WebSocket close failed."),this.logger.error(e),e}}),this.disconnectPromise}_send(e){if(!0===this.configuration.traceSip&&this.logger.log("Sending WebSocket message:\n\n"+e+"\n"),this._state!==se.Connected)return Promise.reject(new Error("Not connected."));if(!this._ws)throw new Error("WebSocket undefined.");try{this._ws.send(e)}catch(e){return e instanceof Error?Promise.reject(e):Promise.reject(new Error("WebSocket send failed."))}return Promise.resolve()}onWebSocketClose(e,t){if(t!==this._ws)return;const s=`WebSocket closed ${this.server} (code: ${e.code})`,i=this.disconnectPromise?void 0:new Error(s);i&&this.logger.warn("WebSocket closed unexpectedly"),this.logger.log(s),this._ws=void 0,this.transitionState(se.Disconnected,i)}onWebSocketError(e,t){t===this._ws&&this.logger.error("WebSocket error occurred.")}onWebSocketMessage(e,t){if(t!==this._ws)return;const s=e.data;let i;if(/^(\r\n)+$/.test(s))return this.clearKeepAliveTimeout(),void(!0===this.configuration.traceSip&&this.logger.log("Received WebSocket message with CRLF Keep Alive response"));if(s){if("string"!=typeof s){try{i=(new TextDecoder).decode(new Uint8Array(s))}catch(e){return this.logger.error(e),void this.logger.error("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"+i+"\n")}else i=s,!0===this.configuration.traceSip&&this.logger.log("Received WebSocket text message:\n\n"+i+"\n");if(this.state===se.Connected){if(this.onMessage)try{this.onMessage(i)}catch(e){throw this.logger.error(e),this.logger.error("Exception thrown by onMessage callback"),e}}else this.logger.warn("Received message while not connected, discarding...")}else this.logger.warn("Received empty message, discarding...")}onWebSocketOpen(e,t){t===this._ws&&this._state===se.Connecting&&(this.logger.log("WebSocket opened "+this.server),this.transitionState(se.Connected))}transitionLoopDetectedError(e){let t="A state transition loop has been detected.";return t+=` An attempt to transition from ${this._state} to ${e} before the prior transition completed.`,t+=" Perhaps you are synchronously calling connect() or disconnect() from a callback or state change handler?",this.logger.error(t),new d("Loop detected.")}transitionState(e,t){const s=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};if(this.transitioningState)throw this.transitionLoopDetectedError(e);switch(this.transitioningState=!0,this._state){case se.Connecting:e!==se.Connected&&e!==se.Disconnecting&&e!==se.Disconnected&&s();break;case se.Connected:e!==se.Disconnecting&&e!==se.Disconnected&&s();break;case se.Disconnecting:e!==se.Connecting&&e!==se.Disconnected&&s();break;case se.Disconnected:e!==se.Connecting&&s();break;default:throw new Error("Unknown state.")}const i=this._state;this._state=e;const r=this.connectResolve,n=this.connectReject;i===se.Connecting&&(this.connectPromise=void 0,this.connectResolve=void 0,this.connectReject=void 0);const o=this.disconnectResolve,a=this.disconnectReject;if(i===se.Disconnecting&&(this.disconnectPromise=void 0,this.disconnectResolve=void 0,this.disconnectReject=void 0),this.connectTimeout&&(clearTimeout(this.connectTimeout),this.connectTimeout=void 0),this.logger.log(`Transitioned from ${i} to ${this._state}`),this._stateEventEmitter.emit(this._state),e===se.Connected&&(this.startSendingKeepAlives(),this.onConnect))try{this.onConnect()}catch(e){throw this.logger.error(e),this.logger.error("Exception thrown by onConnect callback"),e}if(i===se.Connected&&(this.stopSendingKeepAlives(),this.onDisconnect))try{t?this.onDisconnect(t):this.onDisconnect()}catch(e){throw this.logger.error(e),this.logger.error("Exception thrown by onDisconnect callback"),e}if(i===se.Connecting){if(!r)throw new Error("Connect resolve undefined.");if(!n)throw new Error("Connect reject undefined.");e===se.Connected?r():n(t||new Error("Connect aborted."))}if(i===se.Disconnecting){if(!o)throw new Error("Disconnect resolve undefined.");if(!a)throw new Error("Disconnect reject undefined.");e===se.Disconnected?o():a(t||new Error("Disconnect aborted."))}this.transitioningState=!1}clearKeepAliveTimeout(){this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveDebounceTimeout=void 0}sendKeepAlive(){return this.keepAliveDebounceTimeout?Promise.resolve():(this.keepAliveDebounceTimeout=setTimeout(()=>{this.clearKeepAliveTimeout()},1e3*this.configuration.keepAliveDebounce),this.send("\r\n\r\n"))}startSendingKeepAlives(){this.configuration.keepAliveInterval&&!this.keepAliveInterval&&(this.keepAliveInterval=setInterval(()=>{this.sendKeepAlive(),this.startSendingKeepAlives()},(e=>{const t=.8*e;return 1e3*(Math.random()*(e-t)+t)})(this.configuration.keepAliveInterval)))}stopSendingKeepAlives(){this.keepAliveInterval&&clearInterval(this.keepAliveInterval),this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveInterval=void 0,this.keepAliveDebounceTimeout=void 0}}nt.defaultOptions={server:"",connectionTimeout:5,keepAliveInterval:0,keepAliveDebounce:10,traceSip:!0};class ot{constructor(e={}){if(this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this._state=ie.Stopped,this.unloadListener=()=>{this.stop()},this._stateEventEmitter=new g,this.delegate=e.delegate,this.options=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},ot.defaultOptions()),{sipjsId:R(5)}),{uri:new m("sip","anonymous."+R(6),"anonymous.invalid")}),{viaHost:R(12)+".invalid"}),ot.stripUndefinedProperties(e)),this.options.hackIpInContact)if("boolean"==typeof this.options.hackIpInContact&&this.options.hackIpInContact){const e=1,t=254,s=Math.floor(Math.random()*(t-e+1)+e);this.options.viaHost="192.0.2."+s}else this.options.hackIpInContact&&(this.options.viaHost=this.options.hackIpInContact);switch(this.loggerFactory=new ge,this.logger=this.loggerFactory.getLogger("sip.UserAgent"),this.loggerFactory.builtinEnabled=this.options.logBuiltinEnabled,this.loggerFactory.connector=this.options.logConnector,this.options.logLevel){case"error":this.loggerFactory.level=re.error;break;case"warn":this.loggerFactory.level=re.warn;break;case"log":this.loggerFactory.level=re.log;break;case"debug":this.loggerFactory.level=re.debug}if(this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach(e=>{const t=this.options[e];switch(e){case"uri":case"sessionDescriptionHandlerFactory":this.logger.log("\xb7 "+e+": "+t);break;case"authorizationPassword":this.logger.log("\xb7 "+e+": NOT SHOWN");break;case"transportConstructor":this.logger.log("\xb7 "+e+": "+t.name);break;default:this.logger.log("\xb7 "+e+": "+JSON.stringify(t))}})),this.options.transportOptions){const t=this.options.transportOptions,s=t.maxReconnectionAttempts,i=t.reconnectionTimeout;if(void 0!==s){const e='The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(void 0!==i){const e='The transport option "reconnectionTimeout" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}void 0===e.reconnectionDelay&&void 0!==i&&(this.options.reconnectionDelay=i),void 0===e.reconnectionAttempts&&void 0!==s&&(this.options.reconnectionAttempts=s)}if(void 0!==e.reconnectionDelay){const e='The user agent option "reconnectionDelay" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(void 0!==e.reconnectionAttempts){const e='The user agent option "reconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}this._transport=new this.options.transportConstructor(this.getLogger("sip.Transport"),this.options.transportOptions),this.initTransportCallbacks(),this._contact=this.initContact(),this._userAgentCore=this.initCore(),this.options.autoStart&&this.start()}static makeURI(e){return b.URIParse(e)}static defaultOptions(){return{allowLegacyNotifications:!1,authorizationHa1:"",authorizationPassword:"",authorizationUsername:"",autoStart:!1,autoStop:!0,delegate:{},contactName:"",contactParams:{transport:"ws"},displayName:"",forceRport:!1,hackAllowUnregisteredOptionTags:!1,hackIpInContact:!1,hackViaTcp:!1,logBuiltinEnabled:!0,logConfiguration:!0,logConnector:()=>{},logLevel:"log",noAnswerTimeout:60,preloadedRouteSet:[],reconnectionAttempts:0,reconnectionDelay:4,sessionDescriptionHandlerFactory:rt(),sessionDescriptionHandlerFactoryOptions:{},sipExtension100rel:K.Unsupported,sipExtensionReplaces:K.Unsupported,sipExtensionExtraSupported:[],sipjsId:"",transportConstructor:nt,transportOptions:{},uri:new m("sip","anonymous","anonymous.invalid"),userAgentString:"SIP.js/0.18.0",viaHost:""}}static stripUndefinedProperties(e){return Object.keys(e).reduce((t,s)=>(void 0!==e[s]&&(t[s]=e[s]),t),{})}get configuration(){return this.options}get contact(){return this._contact}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get transport(){return this._transport}get userAgentCore(){return this._userAgentCore}getLogger(e,t){return this.loggerFactory.getLogger(e,t)}getLoggerFactory(){return this.loggerFactory}isConnected(){return this.transport.isConnected()}reconnect(){return this.state===ie.Stopped?Promise.reject(new Error("User agent stopped.")):Promise.resolve().then(()=>this.transport.connect())}start(){if(this.state===ie.Started)return this.logger.warn("User agent already started"),Promise.resolve();if(this.logger.log("Starting "+this.configuration.uri),this.transitionState(ie.Started),this.options.autoStop){const e=!("undefined"==typeof chrome||!chrome.app||!chrome.app.runtime);"undefined"==typeof window||"function"!=typeof window.addEventListener||e||window.addEventListener("unload",this.unloadListener)}return this.transport.connect()}async stop(){if(this.state===ie.Stopped)return this.logger.warn("User agent already stopped"),Promise.resolve();if(this.logger.log("Stopping "+this.configuration.uri),this.transitionState(ie.Stopped),this.options.autoStop){const e=!("undefined"==typeof chrome||!chrome.app||!chrome.app.runtime);"undefined"!=typeof window&&window.removeEventListener&&!e&&window.removeEventListener("unload",this.unloadListener)}const e=Object.assign({},this._publishers),t=Object.assign({},this._registerers),s=Object.assign({},this._sessions),i=Object.assign({},this._subscriptions),r=this.transport,n=this.userAgentCore;this.logger.log("Dispose of registerers");for(const e in t)t[e]&&await t[e].dispose().catch(t=>{throw this.logger.error(t.message),delete this._registerers[e],t});this.logger.log("Dispose of sessions");for(const e in s)s[e]&&await s[e].dispose().catch(t=>{throw this.logger.error(t.message),delete this._sessions[e],t});this.logger.log("Dispose of subscriptions");for(const e in i)i[e]&&await i[e].dispose().catch(t=>{throw this.logger.error(t.message),delete this._subscriptions[e],t});this.logger.log("Dispose of publishers");for(const t in e)e[t]&&await e[t].dispose().catch(e=>{throw this.logger.error(e.message),delete this._publishers[t],e});this.logger.log("Dispose of transport"),await r.dispose().catch(e=>{throw this.logger.error(e.message),e}),this.logger.log("Dispose of core"),n.dispose()}_makeInviter(e,t){return new J(this,e,t)}attemptReconnection(e=1){const t=this.options.reconnectionAttempts,s=this.options.reconnectionDelay;e>t?this.logger.log("Maximum reconnection attempts reached"):(this.logger.log(`Reconnection attempt ${e} of ${t} - trying`),setTimeout(()=>{this.reconnect().then(()=>{this.logger.log(`Reconnection attempt ${e} of ${t} - succeeded`)}).catch(s=>{this.logger.error(s.message),this.logger.log(`Reconnection attempt ${e} of ${t} - failed`),this.attemptReconnection(++e)})},1===e?0:1e3*s))}initContact(){const e=""!=this.options.contactName?this.options.contactName:R(8),t=this.options.contactParams;return{pubGruu:void 0,tempGruu:void 0,uri:new m("sip",e,this.options.viaHost,void 0,t),toString:(e={})=>{const s=e.anonymous||!1,i=e.outbound||!1;let r="<";return r+=s?this.contact.tempGruu||"sip:anonymous@anonymous.invalid;transport="+(t.transport?t.transport:"ws"):this.contact.pubGruu||this.contact.uri,i&&(r+=";ob"),r+=">",r}}}initCore(){let e=[];e.push("outbound"),this.options.sipExtension100rel===K.Supported&&e.push("100rel"),this.options.sipExtensionReplaces===K.Supported&&e.push("replaces"),this.options.sipExtensionExtraSupported&&e.push(...this.options.sipExtensionExtraSupported),this.options.hackAllowUnregisteredOptionTags||(e=e.filter(e=>Y[e])),e=Array.from(new Set(e));const t=e.slice();(this.contact.pubGruu||this.contact.tempGruu)&&t.push("gruu");const s={aor:this.options.uri,contact:this.contact,displayName:this.options.displayName,loggerFactory:this.loggerFactory,hackViaTcp:this.options.hackViaTcp,routeSet:this.options.preloadedRouteSet,supportedOptionTags:e,supportedOptionTagsResponse:t,sipjsId:this.options.sipjsId,userAgentHeaderFieldValue:this.options.userAgentString,viaForceRport:this.options.forceRport,viaHost:this.options.viaHost,authenticationFactory:()=>{const e=this.options.authorizationUsername?this.options.authorizationUsername:this.options.uri.user,t=this.options.authorizationPassword?this.options.authorizationPassword:void 0,s=this.options.authorizationHa1?this.options.authorizationHa1:void 0;return new fe(this.getLoggerFactory(),s,e,t)},transportAccessor:()=>this.transport};return new Qe(s,{onInvite:e=>{var t;const s=new Z(this,e);if(e.delegate={onCancel:e=>{s._onCancel(e)},onTransportError:e=>{this.logger.error("A transport error has occurred while handling an incoming INVITE request.")}},e.trying(),this.options.sipExtensionReplaces!==K.Unsupported){const t=e.message.parseHeader("replaces");if(t){const e=t.call_id;if("string"!=typeof e)throw new Error("Type of call id is not string");const i=t.replaces_to_tag;if("string"!=typeof i)throw new Error("Type of to tag is not string");const r=t.replaces_from_tag;if("string"!=typeof r)throw new Error("type of from tag is not string");const n=e+i+r,o=this.userAgentCore.dialogs.get(n);if(!o)return void s.reject({statusCode:481});if(!o.early&&!0===t.early_only)return void s.reject({statusCode:486});const a=this._sessions[e+r]||this._sessions[e+i]||void 0;if(!a)throw new Error("Session does not exist.");s._replacee=a}}if(null===(t=this.delegate)||void 0===t?void 0:t.onInvite)return s.autoSendAnInitialProvisionalResponse?void s.progress().then(()=>{var e;if(void 0===(null===(e=this.delegate)||void 0===e?void 0:e.onInvite))throw new Error("onInvite undefined.");this.delegate.onInvite(s)}):void this.delegate.onInvite(s);s.reject({statusCode:486})},onMessage:e=>{if(this.delegate&&this.delegate.onMessage){const t=new L(e);this.delegate.onMessage(t)}else e.accept()},onNotify:e=>{if(this.delegate&&this.delegate.onNotify){const t=new B(e);this.delegate.onNotify(t)}else this.options.allowLegacyNotifications?e.accept():e.reject({statusCode:481})},onRefer:e=>{this.logger.warn("Received an out of dialog REFER request"),this.delegate&&this.delegate.onReferRequest?this.delegate.onReferRequest(e):e.reject({statusCode:405})},onRegister:e=>{this.logger.warn("Received an out of dialog REGISTER request"),this.delegate&&this.delegate.onRegisterRequest?this.delegate.onRegisterRequest(e):e.reject({statusCode:405})},onSubscribe:e=>{this.logger.warn("Received an out of dialog SUBSCRIBE request"),this.delegate&&this.delegate.onSubscribeRequest?this.delegate.onSubscribeRequest(e):e.reject({statusCode:405})}})}initTransportCallbacks(){this.transport.onConnect=()=>this.onTransportConnect(),this.transport.onDisconnect=e=>this.onTransportDisconnect(e),this.transport.onMessage=e=>this.onTransportMessage(e)}onTransportConnect(){this.state!==ie.Stopped&&this.delegate&&this.delegate.onConnect&&this.delegate.onConnect()}onTransportDisconnect(e){this.state!==ie.Stopped&&(this.delegate&&this.delegate.onDisconnect&&this.delegate.onDisconnect(e),e&&this.options.reconnectionAttempts>0&&this.attemptReconnection())}onTransportMessage(e){const t=et.parseMessage(e,this.getLogger("sip.Parser"));if(!t)return void this.logger.warn("Failed to parse incoming message. Dropping.");if(this.state===ie.Stopped&&t instanceof A)return void this.logger.warn(`Received ${t.method} request while stopped. Dropping.`);const s=()=>{const e=["from","to","call_id","cseq","via"];for(const s of e)if(!t.hasHeader(s))return this.logger.warn(`Missing mandatory header field : ${s}.`),!1;return!0};if(t instanceof A){if(!s())return void this.logger.warn("Request missing mandatory header field. Dropping.");if(!t.toTag&&t.callId.substr(0,5)===this.options.sipjsId)return void this.userAgentCore.replyStateless(t,{statusCode:482});const e=I(t.body),i=t.getHeader("content-length");if(i&&e1)return void this.logger.warn("More than one Via header field present in the response. Dropping.");if(t.via.host!==this.options.viaHost||void 0!==t.via.port)return void this.logger.warn("Via sent-by in the response does not match UA Via host value. Dropping.");const e=I(t.body),i=t.getHeader("content-length");if(i&&e{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case ie.Started:e!==ie.Stopped&&s();break;case ie.Stopped:e!==ie.Started&&s();break;default:throw new Error("Unknown state.")}this.logger.log(`Transitioned from ${this._state} to ${e}`),this._state=e,this._stateEventEmitter.emit(this._state)}}class at extends $e{constructor(e,t,s){super(Te,e,t,s)}}class ct extends Ae{constructor(e,t,s){super(Ce,e.userAgentCore,t,s)}}const ht=(e,t)=>{const s=[],i=e.split(/\r\n/);let r;for(let e=0;e(t.sdp=ht(t.sdp||"",e),Promise.resolve(t))}function ft(e){return e.sdp=((e,t)=>{const s=new RegExp("m="+t+".*$","gm"),i=new RegExp("^a=group:.*$","gm");if(s.test(e)){let s;const r=(e=e.split(/^m=/gm).filter(e=>{if(e.substr(0,t.length)===t){if(s=e.match(/^a=mid:.*$/gm),s){const e=s[0].match(/:.+$/g);e&&(s=e[0].substr(1))}return!1}return!0}).join("m=")).match(i);if(r&&1===r.length){let t=r[0];const n=new RegExp(" *"+s+"[^ ]*","g");t=t.replace(n,""),e=e.split(i).join(t)}}return e})(e.sdp||"","video"),Promise.resolve(e)}function mt(e){let t=e.sdp||"";if(-1===t.search(/^a=mid.*$/gm)){const s=t.match(/^m=.*$/gm),i=t.split(/^m=.*$/gm);s&&s.forEach((e,t)=>{s[t]=e+"\na=mid:"+t}),i.forEach((e,t)=>{s&&s[t]&&(i[t]=e+s[t])}),t=i.join(""),e.sdp=t}return Promise.resolve(e)}function vt(e){if(!e.sdp||!e.type)throw new Error("Invalid SDP");let t=e.sdp;const s=e.type;return t&&(/a=(sendrecv|sendonly|recvonly|inactive)/.test(t)?(t=t.replace(/a=sendrecv\r\n/g,"a=sendonly\r\n"),t=t.replace(/a=recvonly\r\n/g,"a=inactive\r\n")):t=t.replace(/(m=[^\r]*\r\n)/g,"$1a=sendonly\r\n")),Promise.resolve({sdp:t,type:s})}class wt{constructor(e,t={}){this.attemptingReconnection=!1,this.connectRequested=!1,this.held=!1,this.registerer=void 0,this.registerRequested=!1,this.session=void 0,this.delegate=t.delegate,this.options=Object.assign({},t);const s=Object.assign({},t.userAgentOptions);if(s.transportConstructor||(s.transportConstructor=nt),s.transportOptions||(s.transportOptions={server:e}),!s.uri&&t.aor){const e=ot.makeURI(t.aor);if(!e)throw new Error("Failed to create valid URI from "+t.aor);s.uri=e}this.userAgent=new ot(s),this.userAgent.delegate={onConnect:()=>{this.logger.log(`[${this.id}] Connected`),this.delegate&&this.delegate.onServerConnect&&this.delegate.onServerConnect(),this.registerer&&this.registerRequested&&(this.logger.log(`[${this.id}] Registering...`),this.registerer.register().catch(e=>{this.logger.error(`[${this.id}] Error occurred registering after connection with server was obtained.`),this.logger.error(e.toString())}))},onDisconnect:e=>{this.logger.log(`[${this.id}] Disconnected`),this.delegate&&this.delegate.onServerDisconnect&&this.delegate.onServerDisconnect(e),this.session&&(this.logger.log(`[${this.id}] Hanging up...`),this.hangup().catch(e=>{this.logger.error(`[${this.id}] Error occurred hanging up call after connection with server was lost.`),this.logger.error(e.toString())})),this.registerer&&(this.logger.log(`[${this.id}] Unregistering...`),this.registerer.unregister().catch(e=>{this.logger.error(`[${this.id}] Error occurred unregistering after connection with server was lost.`),this.logger.error(e.toString())})),e&&this.attemptReconnection()},onInvite:e=>{if(this.logger.log(`[${this.id}] Received INVITE`),this.session)return this.logger.warn(`[${this.id}] Session already in progress, rejecting INVITE...`),void e.reject().then(()=>{this.logger.log(`[${this.id}] Rejected INVITE`)}).catch(e=>{this.logger.error(`[${this.id}] Failed to reject INVITE`),this.logger.error(e.toString())});const t={sessionDescriptionHandlerOptions:{constraints:this.constraints}};this.initSession(e,t),this.delegate&&this.delegate.onCallReceived?this.delegate.onCallReceived():(this.logger.warn(`[${this.id}] No handler available, rejecting INVITE...`),e.reject().then(()=>{this.logger.log(`[${this.id}] Rejected INVITE`)}).catch(e=>{this.logger.error(`[${this.id}] Failed to reject INVITE`),this.logger.error(e.toString())}))},onMessage:e=>{e.accept().then(()=>{this.delegate&&this.delegate.onMessageReceived&&this.delegate.onMessageReceived(e.request.body)})}},this.logger=this.userAgent.getLogger("sip.SimpleUser"),window.addEventListener("online",()=>{this.logger.log(`[${this.id}] Online`),this.attemptReconnection()})}get id(){return this.options.userAgentOptions&&this.options.userAgentOptions.displayName||"Anonymous"}get localMediaStream(){var e;const t=null===(e=this.session)||void 0===e?void 0:e.sessionDescriptionHandler;if(t){if(!(t instanceof it))throw new Error("Session description handler not instance of web SessionDescriptionHandler");return t.localMediaStream}}get remoteMediaStream(){var e;const t=null===(e=this.session)||void 0===e?void 0:e.sessionDescriptionHandler;if(t){if(!(t instanceof it))throw new Error("Session description handler not instance of web SessionDescriptionHandler");return t.remoteMediaStream}}get localAudioTrack(){var e;return null===(e=this.localMediaStream)||void 0===e?void 0:e.getTracks().find(e=>"audio"===e.kind)}get localVideoTrack(){var e;return null===(e=this.localMediaStream)||void 0===e?void 0:e.getTracks().find(e=>"video"===e.kind)}get remoteAudioTrack(){var e;return null===(e=this.remoteMediaStream)||void 0===e?void 0:e.getTracks().find(e=>"audio"===e.kind)}get remoteVideoTrack(){var e;return null===(e=this.remoteMediaStream)||void 0===e?void 0:e.getTracks().find(e=>"video"===e.kind)}connect(){return this.logger.log(`[${this.id}] Connecting UserAgent...`),this.connectRequested=!0,this.userAgent.state!==ie.Started?this.userAgent.start():this.userAgent.reconnect()}disconnect(){return this.logger.log(`[${this.id}] Disconnecting UserAgent...`),this.connectRequested=!1,this.userAgent.stop()}isConnected(){return this.userAgent.isConnected()}register(e,t){return this.logger.log(`[${this.id}] Registering UserAgent...`),this.registerRequested=!0,this.registerer||(this.registerer=new ae(this.userAgent,e),this.registerer.stateChange.addListener(e=>{switch(e){case Q.Initial:break;case Q.Registered:this.delegate&&this.delegate.onRegistered&&this.delegate.onRegistered();break;case Q.Unregistered:this.delegate&&this.delegate.onUnregistered&&this.delegate.onUnregistered();break;case Q.Terminated:this.registerer=void 0;break;default:throw new Error("Unknown registerer state.")}})),this.registerer.register(t).then(()=>{})}unregister(e){return this.logger.log(`[${this.id}] Unregistering UserAgent...`),this.registerRequested=!1,this.registerer?this.registerer.unregister(e).then(()=>{}):Promise.resolve()}call(e,t,s){if(this.logger.log(`[${this.id}] Beginning Session...`),this.session)return Promise.reject(new Error("Session already exists."));const i=ot.makeURI(e);if(!i)return Promise.reject(new Error(`Failed to create a valid URI from "${e}"`));t||(t={}),t.sessionDescriptionHandlerOptions||(t.sessionDescriptionHandlerOptions={}),t.sessionDescriptionHandlerOptions.constraints||(t.sessionDescriptionHandlerOptions.constraints=this.constraints);const r=new J(this.userAgent,i,t);return this.sendInvite(r,t,s).then(()=>{})}hangup(){return this.logger.log(`[${this.id}] Hangup...`),this.terminate()}answer(e){return this.logger.log(`[${this.id}] Accepting Invitation...`),this.session?this.session instanceof Z?(e||(e={}),e.sessionDescriptionHandlerOptions||(e.sessionDescriptionHandlerOptions={}),e.sessionDescriptionHandlerOptions.constraints||(e.sessionDescriptionHandlerOptions.constraints=this.constraints),this.session.accept(e)):Promise.reject(new Error("Session not instance of Invitation.")):Promise.reject(new Error("Session does not exist."))}decline(){return this.logger.log(`[${this.id}] rejecting Invitation...`),this.session?this.session instanceof Z?this.session.reject():Promise.reject(new Error("Session not instance of Invitation.")):Promise.reject(new Error("Session does not exist."))}hold(){return this.logger.log(`[${this.id}] holding session...`),this.setHold(!0)}unhold(){return this.logger.log(`[${this.id}] unholding session...`),this.setHold(!1)}isHeld(){return this.held}mute(){this.logger.log(`[${this.id}] disabling media tracks...`),this.setMute(!0)}unmute(){this.logger.log(`[${this.id}] enabling media tracks...`),this.setMute(!1)}isMuted(){const e=this.localAudioTrack||this.localVideoTrack;return!!e&&!e.enabled}sendDTMF(e){if(this.logger.log(`[${this.id}] sending DTMF...`),!/^[0-9A-D#*,]$/.exec(e))return Promise.reject(new Error("Invalid DTMF tone."));if(!this.session)return Promise.reject(new Error("Session does not exist."));this.logger.log(`[${this.id}] Sending DTMF tone: ${e}`);const t={body:{contentDisposition:"render",contentType:"application/dtmf-relay",content:"Signal="+e+"\r\nDuration=2000"}};return this.session.info({requestOptions:t}).then(()=>{})}message(e,t){this.logger.log(`[${this.id}] sending message...`);const s=ot.makeURI(e);return s?new z(this.userAgent,s,t).message():Promise.reject(new Error(`Failed to create a valid URI from "${e}"`))}get constraints(){var e;let t={audio:!0,video:!1};return(null===(e=this.options.media)||void 0===e?void 0:e.constraints)&&(t=Object.assign({},this.options.media.constraints)),t}attemptReconnection(e=1){const t=this.options.reconnectionAttempts||3,s=this.options.reconnectionDelay||4;this.connectRequested?(this.attemptingReconnection&&this.logger.log(`[${this.id}] Reconnection attempt already in progress`),e>t?this.logger.log(`[${this.id}] Reconnection maximum attempts reached`):(1===e?this.logger.log(`[${this.id}] Reconnection attempt ${e} of ${t} - trying`):this.logger.log(`[${this.id}] Reconnection attempt ${e} of ${t} - trying in ${s} seconds`),this.attemptingReconnection=!0,setTimeout(()=>{if(!this.connectRequested)return this.logger.log(`[${this.id}] Reconnection attempt ${e} of ${t} - aborted`),void(this.attemptingReconnection=!1);this.userAgent.reconnect().then(()=>{this.logger.log(`[${this.id}] Reconnection attempt ${e} of ${t} - succeeded`),this.attemptingReconnection=!1}).catch(s=>{this.logger.log(`[${this.id}] Reconnection attempt ${e} of ${t} - failed`),this.logger.error(s.message),this.attemptingReconnection=!1,this.attemptReconnection(++e)})},1===e?0:1e3*s))):this.logger.log(`[${this.id}] Reconnection not currently desired`)}cleanupMedia(){this.options.media&&(this.options.media.local&&this.options.media.local.video&&(this.options.media.local.video.srcObject=null,this.options.media.local.video.pause()),this.options.media.remote&&(this.options.media.remote.audio&&(this.options.media.remote.audio.srcObject=null,this.options.media.remote.audio.pause()),this.options.media.remote.video&&(this.options.media.remote.video.srcObject=null,this.options.media.remote.video.pause())))}enableSenderTracks(e){if(!this.session)throw new Error("Session does not exist.");const t=this.session.sessionDescriptionHandler;if(!(t instanceof it))throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");const s=t.peerConnection;if(!s)throw new Error("Peer connection closed.");s.getSenders().forEach(t=>{t.track&&(t.track.enabled=e)})}initSession(e,t){this.session=e,this.delegate&&this.delegate.onCallCreated&&this.delegate.onCallCreated(),this.session.stateChange.addListener(t=>{if(this.session===e)switch(this.logger.log(`[${this.id}] session state changed to ${t}`),t){case G.Initial:case G.Establishing:break;case G.Established:this.setupLocalMedia(),this.setupRemoteMedia(),this.delegate&&this.delegate.onCallAnswered&&this.delegate.onCallAnswered();break;case G.Terminating:case G.Terminated:this.session=void 0,this.cleanupMedia(),this.delegate&&this.delegate.onCallHangup&&this.delegate.onCallHangup();break;default:throw new Error("Unknown session state.")}}),this.session.delegate={onInfo:e=>{var t;if(void 0===(null===(t=this.delegate)||void 0===t?void 0:t.onCallDTMFReceived))return void e.reject();const s=e.request.getHeader("content-type");if(!s||!/^application\/dtmf-relay/i.exec(s))return void e.reject();const i=e.request.body.split("\r\n",2);if(2!==i.length)return void e.reject();let r;const n=/^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/;if(n.test(i[0])&&(r=i[0].replace(n,"$2")),!r)return void e.reject();let o;const a=/^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/;a.test(i[1])&&(o=parseInt(i[1].replace(a,"$2"),10)),o?e.accept().then(()=>{if(this.delegate&&this.delegate.onCallDTMFReceived){if(!r||!o)throw new Error("Tone or duration undefined.");this.delegate.onCallDTMFReceived(r,o)}}).catch(e=>{this.logger.error(e.message)}):e.reject()},onRefer:e=>{e.accept().then(()=>this.sendInvite(e.makeInviter(t),t)).catch(e=>{this.logger.error(e.message)})}}}sendInvite(e,t,s){return this.initSession(e,t),e.invite(s).then(()=>{this.logger.log(`[${this.id}] sent INVITE`)})}setHold(e){if(!this.session)return Promise.reject(new Error("Session does not exist."));const t=this.session;if(this.held===e)return Promise.resolve();if(!(this.session.sessionDescriptionHandler instanceof it))throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");const s={requestDelegate:{onAccept:()=>{this.held=e,this.delegate&&this.delegate.onCallHold&&this.delegate.onCallHold(this.held)},onReject:()=>{this.logger.warn(`[${this.id}] re-invite request was rejected`),this.delegate&&this.delegate.onCallHold&&this.delegate.onCallHold(this.held)}}};return t.sessionDescriptionHandlerModifiersReInvite=e?[vt]:[],this.session.invite(s).then(()=>{t.sessionDescriptionHandlerModifiersReInvite=[],this.enableSenderTracks(!e)}).catch(e=>{throw e instanceof a&&this.logger.error(`[${this.id}] A hold request is already in progress.`),e})}setMute(e){this.session?this.session.state===G.Established?this.enableSenderTracks(!e):this.logger.warn(`[${this.id}] An established session is required to enable/disable media tracks`):this.logger.warn(`[${this.id}] A session is required to enabled/disable media tracks`)}setupLocalMedia(){var e,t;if(!this.session)throw new Error("Session does not exist.");const s=null===(t=null===(e=this.options.media)||void 0===e?void 0:e.local)||void 0===t?void 0:t.video;if(s){const e=this.localMediaStream;if(!e)throw new Error("Local media stream undefiend.");s.srcObject=e,s.volume=0,s.play().catch(e=>{this.logger.error(`[${this.id}] Failed to play local media`),this.logger.error(e.message)})}}setupRemoteMedia(){var e,t,s,i;if(!this.session)throw new Error("Session does not exist.");const r=(null===(t=null===(e=this.options.media)||void 0===e?void 0:e.remote)||void 0===t?void 0:t.video)||(null===(i=null===(s=this.options.media)||void 0===s?void 0:s.remote)||void 0===i?void 0:i.audio);if(r){const e=this.remoteMediaStream;if(!e)throw new Error("Remote media stream undefiend.");r.autoplay=!0,r.srcObject=e,r.play().catch(e=>{this.logger.error(`[${this.id}] Failed to play remote media`),this.logger.error(e.message)}),e.onaddtrack=()=>{this.logger.log(`[${this.id}] Remote media onaddtrack`),r.load(),r.play().catch(e=>{this.logger.error(`[${this.id}] Failed to play remote media`),this.logger.error(e.message)})}}}terminate(){if(this.logger.log(`[${this.id}] Terminating...`),!this.session)return Promise.reject(new Error("Session does not exist."));switch(this.session.state){case G.Initial:if(this.session instanceof J)return this.session.cancel().then(()=>{this.logger.log(`[${this.id}] Inviter never sent INVITE (canceled)`)});if(this.session instanceof Z)return this.session.reject().then(()=>{this.logger.log(`[${this.id}] Invitation rejected (sent 480)`)});throw new Error("Unknown session type.");case G.Establishing:if(this.session instanceof J)return this.session.cancel().then(()=>{this.logger.log(`[${this.id}] Inviter canceled (sent CANCEL)`)});if(this.session instanceof Z)return this.session.reject().then(()=>{this.logger.log(`[${this.id}] Invitation rejected (sent 480)`)});throw new Error("Unknown session type.");case G.Established:return this.session.bye().then(()=>{this.logger.log(`[${this.id}] Session ended (sent BYE)`)});case G.Terminating:case G.Terminated:break;default:throw new Error("Unknown state")}return this.logger.log(`[${this.id}] Terminating in state ${this.session.state}, no action taken`),Promise.resolve()}}const bt="0.18.0",Tt="sip.js"}})})); \ No newline at end of file diff --git a/dist/sip.js b/dist/sip.js new file mode 100644 index 000000000..082cecbe8 --- /dev/null +++ b/dist/sip.js @@ -0,0 +1,20884 @@ +/*! + * + * SIP version 0.18.0 + * Copyright (c) 2014-2020 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, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "name", function() { return name; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "version", function() { return version; }); +/* harmony import */ var _version__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1); +/* harmony import */ var _api__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ContentTypeUnsupportedError", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["ContentTypeUnsupportedError"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RequestPendingError", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["RequestPendingError"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionDescriptionHandlerError", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["SessionDescriptionHandlerError"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionTerminatedError", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["SessionTerminatedError"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StateTransitionError", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["StateTransitionError"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Bye", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["Bye"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EmitterImpl", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["EmitterImpl"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Info", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["Info"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Invitation", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["Invitation"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Inviter", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["Inviter"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Message", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["Message"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Messager", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["Messager"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Notification", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["Notification"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PublisherState", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["PublisherState"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Publisher", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["Publisher"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Referral", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["Referral"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RegistererState", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["RegistererState"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Registerer", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["Registerer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionState", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["SessionState"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Session", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["Session"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Subscriber", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["Subscriber"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubscriptionState", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Subscription", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["Subscription"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransportState", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["TransportState"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SIPExtension", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["SIPExtension"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgentRegisteredOptionTags", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["UserAgentRegisteredOptionTags"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgentState", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["UserAgentState"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgent", function() { return _api__WEBPACK_IMPORTED_MODULE_1__["UserAgent"]; }); + +/* harmony import */ var _grammar__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(9); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Grammar", function() { return _grammar__WEBPACK_IMPORTED_MODULE_2__["Grammar"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NameAddrHeader", function() { return _grammar__WEBPACK_IMPORTED_MODULE_2__["NameAddrHeader"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Parameters", function() { return _grammar__WEBPACK_IMPORTED_MODULE_2__["Parameters"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "URI", function() { return _grammar__WEBPACK_IMPORTED_MODULE_2__["URI"]; }); + +/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(5); +/* harmony reexport (module object) */ __webpack_require__.d(__webpack_exports__, "Core", function() { return _core__WEBPACK_IMPORTED_MODULE_3__; }); +/* harmony import */ var _platform_web__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(174); +/* harmony reexport (module object) */ __webpack_require__.d(__webpack_exports__, "Web", function() { return _platform_web__WEBPACK_IMPORTED_MODULE_4__; }); +// Helpful name and version exports + +const version = _version__WEBPACK_IMPORTED_MODULE_0__["LIBRARY_VERSION"]; +const name = "sip.js"; + +// Export api + +// Export grammar + +// Export namespaced core + + +// Export namespaced web + + + + +/***/ }), +/* 1 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LIBRARY_VERSION", function() { return LIBRARY_VERSION; }); +const LIBRARY_VERSION = "0.18.0"; + + +/***/ }), +/* 2 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _exceptions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ContentTypeUnsupportedError", function() { return _exceptions__WEBPACK_IMPORTED_MODULE_0__["ContentTypeUnsupportedError"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RequestPendingError", function() { return _exceptions__WEBPACK_IMPORTED_MODULE_0__["RequestPendingError"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionDescriptionHandlerError", function() { return _exceptions__WEBPACK_IMPORTED_MODULE_0__["SessionDescriptionHandlerError"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionTerminatedError", function() { return _exceptions__WEBPACK_IMPORTED_MODULE_0__["SessionTerminatedError"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StateTransitionError", function() { return _exceptions__WEBPACK_IMPORTED_MODULE_0__["StateTransitionError"]; }); + +/* harmony import */ var _bye__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(107); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Bye", function() { return _bye__WEBPACK_IMPORTED_MODULE_1__["Bye"]; }); + +/* harmony import */ var _emitter__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(108); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EmitterImpl", function() { return _emitter__WEBPACK_IMPORTED_MODULE_2__["EmitterImpl"]; }); + +/* harmony import */ var _info__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(109); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Info", function() { return _info__WEBPACK_IMPORTED_MODULE_3__["Info"]; }); + +/* harmony import */ var _invitation_accept_options__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(110); +/* empty/unused harmony star reexport *//* harmony import */ var _invitation_progress_options__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(111); +/* empty/unused harmony star reexport *//* harmony import */ var _invitation_reject_options__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(112); +/* empty/unused harmony star reexport *//* harmony import */ var _invitation__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(113); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Invitation", function() { return _invitation__WEBPACK_IMPORTED_MODULE_7__["Invitation"]; }); + +/* harmony import */ var _inviter_cancel_options__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(120); +/* empty/unused harmony star reexport *//* harmony import */ var _inviter_invite_options__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(121); +/* empty/unused harmony star reexport *//* harmony import */ var _inviter_options__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(122); +/* empty/unused harmony star reexport *//* harmony import */ var _inviter__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(123); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Inviter", function() { return _inviter__WEBPACK_IMPORTED_MODULE_11__["Inviter"]; }); + +/* harmony import */ var _message__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(115); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Message", function() { return _message__WEBPACK_IMPORTED_MODULE_12__["Message"]; }); + +/* harmony import */ var _messager_message_options__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(124); +/* empty/unused harmony star reexport *//* harmony import */ var _messager_options__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(125); +/* empty/unused harmony star reexport *//* harmony import */ var _messager__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(126); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Messager", function() { return _messager__WEBPACK_IMPORTED_MODULE_15__["Messager"]; }); + +/* harmony import */ var _notification__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(116); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Notification", function() { return _notification__WEBPACK_IMPORTED_MODULE_16__["Notification"]; }); + +/* harmony import */ var _publisher_options__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(127); +/* empty/unused harmony star reexport *//* harmony import */ var _publisher_publish_options__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(128); +/* empty/unused harmony star reexport *//* harmony import */ var _publisher_state__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(129); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PublisherState", function() { return _publisher_state__WEBPACK_IMPORTED_MODULE_19__["PublisherState"]; }); + +/* harmony import */ var _publisher_unpublish_options__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(130); +/* empty/unused harmony star reexport *//* harmony import */ var _publisher__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(131); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Publisher", function() { return _publisher__WEBPACK_IMPORTED_MODULE_21__["Publisher"]; }); + +/* harmony import */ var _referral__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(117); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Referral", function() { return _referral__WEBPACK_IMPORTED_MODULE_22__["Referral"]; }); + +/* harmony import */ var _registerer_options__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(132); +/* empty/unused harmony star reexport *//* harmony import */ var _registerer_register_options__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(133); +/* empty/unused harmony star reexport *//* harmony import */ var _registerer_state__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(134); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RegistererState", function() { return _registerer_state__WEBPACK_IMPORTED_MODULE_25__["RegistererState"]; }); + +/* harmony import */ var _registerer_unregister_options__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(135); +/* empty/unused harmony star reexport *//* harmony import */ var _registerer__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(136); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Registerer", function() { return _registerer__WEBPACK_IMPORTED_MODULE_27__["Registerer"]; }); + +/* harmony import */ var _session_bye_options__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(137); +/* empty/unused harmony star reexport *//* harmony import */ var _session_delegate__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(138); +/* empty/unused harmony star reexport *//* harmony import */ var _session_description_handler_factory__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(139); +/* empty/unused harmony star reexport *//* harmony import */ var _session_description_handler__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(140); +/* empty/unused harmony star reexport *//* harmony import */ var _session_info_options__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(141); +/* empty/unused harmony star reexport *//* harmony import */ var _session_invite_options__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(142); +/* empty/unused harmony star reexport *//* harmony import */ var _session_message_options__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(143); +/* empty/unused harmony star reexport *//* harmony import */ var _session_options__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(144); +/* empty/unused harmony star reexport *//* harmony import */ var _session_refer_options__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(145); +/* empty/unused harmony star reexport *//* harmony import */ var _session_state__WEBPACK_IMPORTED_MODULE_37__ = __webpack_require__(118); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionState", function() { return _session_state__WEBPACK_IMPORTED_MODULE_37__["SessionState"]; }); + +/* harmony import */ var _session__WEBPACK_IMPORTED_MODULE_38__ = __webpack_require__(114); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Session", function() { return _session__WEBPACK_IMPORTED_MODULE_38__["Session"]; }); + +/* harmony import */ var _subscriber_options__WEBPACK_IMPORTED_MODULE_39__ = __webpack_require__(146); +/* empty/unused harmony star reexport *//* harmony import */ var _subscriber_subscribe_options__WEBPACK_IMPORTED_MODULE_40__ = __webpack_require__(147); +/* empty/unused harmony star reexport *//* harmony import */ var _subscriber__WEBPACK_IMPORTED_MODULE_41__ = __webpack_require__(148); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Subscriber", function() { return _subscriber__WEBPACK_IMPORTED_MODULE_41__["Subscriber"]; }); + +/* harmony import */ var _subscription_delegate__WEBPACK_IMPORTED_MODULE_42__ = __webpack_require__(151); +/* empty/unused harmony star reexport *//* harmony import */ var _subscription_options__WEBPACK_IMPORTED_MODULE_43__ = __webpack_require__(152); +/* empty/unused harmony star reexport *//* harmony import */ var _subscription_state__WEBPACK_IMPORTED_MODULE_44__ = __webpack_require__(150); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubscriptionState", function() { return _subscription_state__WEBPACK_IMPORTED_MODULE_44__["SubscriptionState"]; }); + +/* harmony import */ var _subscription_subscribe_options__WEBPACK_IMPORTED_MODULE_45__ = __webpack_require__(153); +/* empty/unused harmony star reexport *//* harmony import */ var _subscription_unsubscribe_options__WEBPACK_IMPORTED_MODULE_46__ = __webpack_require__(154); +/* empty/unused harmony star reexport *//* harmony import */ var _subscription__WEBPACK_IMPORTED_MODULE_47__ = __webpack_require__(149); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Subscription", function() { return _subscription__WEBPACK_IMPORTED_MODULE_47__["Subscription"]; }); + +/* harmony import */ var _transport__WEBPACK_IMPORTED_MODULE_48__ = __webpack_require__(155); +/* empty/unused harmony star reexport *//* harmony import */ var _transport_state__WEBPACK_IMPORTED_MODULE_49__ = __webpack_require__(156); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransportState", function() { return _transport_state__WEBPACK_IMPORTED_MODULE_49__["TransportState"]; }); + +/* harmony import */ var _user_agent_delegate__WEBPACK_IMPORTED_MODULE_50__ = __webpack_require__(157); +/* empty/unused harmony star reexport *//* harmony import */ var _user_agent_options__WEBPACK_IMPORTED_MODULE_51__ = __webpack_require__(119); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SIPExtension", function() { return _user_agent_options__WEBPACK_IMPORTED_MODULE_51__["SIPExtension"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgentRegisteredOptionTags", function() { return _user_agent_options__WEBPACK_IMPORTED_MODULE_51__["UserAgentRegisteredOptionTags"]; }); + +/* harmony import */ var _user_agent_state__WEBPACK_IMPORTED_MODULE_52__ = __webpack_require__(158); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgentState", function() { return _user_agent_state__WEBPACK_IMPORTED_MODULE_52__["UserAgentState"]; }); + +/* harmony import */ var _user_agent__WEBPACK_IMPORTED_MODULE_53__ = __webpack_require__(159); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgent", function() { return _user_agent__WEBPACK_IMPORTED_MODULE_53__["UserAgent"]; }); + +/** + * A simple yet powerful API which takes care of SIP signaling and WebRTC media sessions for you. + * @packageDocumentation + */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/***/ }), +/* 3 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _content_type_unsupported__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ContentTypeUnsupportedError", function() { return _content_type_unsupported__WEBPACK_IMPORTED_MODULE_0__["ContentTypeUnsupportedError"]; }); + +/* harmony import */ var _request_pending__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(103); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RequestPendingError", function() { return _request_pending__WEBPACK_IMPORTED_MODULE_1__["RequestPendingError"]; }); + +/* harmony import */ var _session_description_handler__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(104); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionDescriptionHandlerError", function() { return _session_description_handler__WEBPACK_IMPORTED_MODULE_2__["SessionDescriptionHandlerError"]; }); + +/* harmony import */ var _session_terminated__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(105); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionTerminatedError", function() { return _session_terminated__WEBPACK_IMPORTED_MODULE_3__["SessionTerminatedError"]; }); + +/* harmony import */ var _state_transition__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(106); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StateTransitionError", function() { return _state_transition__WEBPACK_IMPORTED_MODULE_4__["StateTransitionError"]; }); + + + + + + + + +/***/ }), +/* 4 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ContentTypeUnsupportedError", function() { return ContentTypeUnsupportedError; }); +/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); + +/** + * An exception indicating an unsupported content type prevented execution. + * @public + */ +class ContentTypeUnsupportedError extends _core__WEBPACK_IMPORTED_MODULE_0__["Exception"] { + constructor(message) { + super(message ? message : "Unsupported content type."); + } +} + + +/***/ }), +/* 5 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _dialogs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Dialog", function() { return _dialogs__WEBPACK_IMPORTED_MODULE_0__["Dialog"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionDialog", function() { return _dialogs__WEBPACK_IMPORTED_MODULE_0__["SessionDialog"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubscriptionDialog", function() { return _dialogs__WEBPACK_IMPORTED_MODULE_0__["SubscriptionDialog"]; }); + +/* harmony import */ var _exceptions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(51); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Exception", function() { return _exceptions__WEBPACK_IMPORTED_MODULE_1__["Exception"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransactionStateError", function() { return _exceptions__WEBPACK_IMPORTED_MODULE_1__["TransactionStateError"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransportError", function() { return _exceptions__WEBPACK_IMPORTED_MODULE_1__["TransportError"]; }); + +/* harmony import */ var _log__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(84); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Levels", function() { return _log__WEBPACK_IMPORTED_MODULE_2__["Levels"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LoggerFactory", function() { return _log__WEBPACK_IMPORTED_MODULE_2__["LoggerFactory"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Logger", function() { return _log__WEBPACK_IMPORTED_MODULE_2__["Logger"]; }); + +/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Grammar", function() { return _messages__WEBPACK_IMPORTED_MODULE_3__["Grammar"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NameAddrHeader", function() { return _messages__WEBPACK_IMPORTED_MODULE_3__["NameAddrHeader"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Parameters", function() { return _messages__WEBPACK_IMPORTED_MODULE_3__["Parameters"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "URI", function() { return _messages__WEBPACK_IMPORTED_MODULE_3__["URI"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "C", function() { return _messages__WEBPACK_IMPORTED_MODULE_3__["C"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "fromBodyLegacy", function() { return _messages__WEBPACK_IMPORTED_MODULE_3__["fromBodyLegacy"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isBody", function() { return _messages__WEBPACK_IMPORTED_MODULE_3__["isBody"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getBody", function() { return _messages__WEBPACK_IMPORTED_MODULE_3__["getBody"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DigestAuthentication", function() { return _messages__WEBPACK_IMPORTED_MODULE_3__["DigestAuthentication"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IncomingMessage", function() { return _messages__WEBPACK_IMPORTED_MODULE_3__["IncomingMessage"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IncomingRequestMessage", function() { return _messages__WEBPACK_IMPORTED_MODULE_3__["IncomingRequestMessage"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IncomingResponseMessage", function() { return _messages__WEBPACK_IMPORTED_MODULE_3__["IncomingResponseMessage"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OutgoingRequestMessage", function() { return _messages__WEBPACK_IMPORTED_MODULE_3__["OutgoingRequestMessage"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "constructOutgoingResponse", function() { return _messages__WEBPACK_IMPORTED_MODULE_3__["constructOutgoingResponse"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Parser", function() { return _messages__WEBPACK_IMPORTED_MODULE_3__["Parser"]; }); + +/* harmony import */ var _session__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(44); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionState", function() { return _session__WEBPACK_IMPORTED_MODULE_4__["SessionState"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SignalingState", function() { return _session__WEBPACK_IMPORTED_MODULE_4__["SignalingState"]; }); + +/* harmony import */ var _subscription__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(79); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubscriptionState", function() { return _subscription__WEBPACK_IMPORTED_MODULE_5__["SubscriptionState"]; }); + +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(48); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ClientTransaction", function() { return _transactions__WEBPACK_IMPORTED_MODULE_6__["ClientTransaction"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InviteClientTransaction", function() { return _transactions__WEBPACK_IMPORTED_MODULE_6__["InviteClientTransaction"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InviteServerTransaction", function() { return _transactions__WEBPACK_IMPORTED_MODULE_6__["InviteServerTransaction"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NonInviteClientTransaction", function() { return _transactions__WEBPACK_IMPORTED_MODULE_6__["NonInviteClientTransaction"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NonInviteServerTransaction", function() { return _transactions__WEBPACK_IMPORTED_MODULE_6__["NonInviteServerTransaction"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ServerTransaction", function() { return _transactions__WEBPACK_IMPORTED_MODULE_6__["ServerTransaction"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransactionState", function() { return _transactions__WEBPACK_IMPORTED_MODULE_6__["TransactionState"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Transaction", function() { return _transactions__WEBPACK_IMPORTED_MODULE_6__["Transaction"]; }); + +/* harmony import */ var _user_agent_core__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(88); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgentCore", function() { return _user_agent_core__WEBPACK_IMPORTED_MODULE_7__["UserAgentCore"]; }); + +/* harmony import */ var _user_agents__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(90); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ByeUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["ByeUserAgentClient"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ByeUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["ByeUserAgentServer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CancelUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["CancelUserAgentClient"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InfoUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["InfoUserAgentClient"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InfoUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["InfoUserAgentServer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InviteUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["InviteUserAgentClient"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InviteUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["InviteUserAgentServer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MessageUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["MessageUserAgentClient"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MessageUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["MessageUserAgentServer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NotifyUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["NotifyUserAgentClient"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NotifyUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["NotifyUserAgentServer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PublishUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["PublishUserAgentClient"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PrackUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["PrackUserAgentClient"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PrackUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["PrackUserAgentServer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReInviteUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["ReInviteUserAgentClient"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReInviteUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["ReInviteUserAgentServer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReSubscribeUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["ReSubscribeUserAgentClient"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReSubscribeUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["ReSubscribeUserAgentServer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReferUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["ReferUserAgentClient"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReferUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["ReferUserAgentServer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RegisterUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["RegisterUserAgentClient"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RegisterUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["RegisterUserAgentServer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubscribeUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["SubscribeUserAgentClient"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubscribeUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["SubscribeUserAgentServer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["UserAgentClient"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["UserAgentServer"]; }); + +/* harmony import */ var _timers__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(47); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Timers", function() { return _timers__WEBPACK_IMPORTED_MODULE_9__["Timers"]; }); + +/* harmony import */ var _transport__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(102); +/* empty/unused harmony star reexport *//** + * A core library implementing low level SIP protocol elements. + * @packageDocumentation + */ +// Directories + + + + + + + + + +// Files + + + + +/***/ }), +/* 6 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _dialog__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(7); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Dialog", function() { return _dialog__WEBPACK_IMPORTED_MODULE_0__["Dialog"]; }); + +/* harmony import */ var _dialog_state__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(42); +/* empty/unused harmony star reexport *//* harmony import */ var _session_dialog__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(43); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionDialog", function() { return _session_dialog__WEBPACK_IMPORTED_MODULE_2__["SessionDialog"]; }); + +/* harmony import */ var _subscription_dialog__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(78); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubscriptionDialog", function() { return _subscription_dialog__WEBPACK_IMPORTED_MODULE_3__["SubscriptionDialog"]; }); + + + + + + + +/***/ }), +/* 7 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Dialog", function() { return Dialog; }); +/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); + +/** + * 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 + */ +class Dialog { + /** + * Dialog constructor. + * @param core - User agent core. + * @param dialogState - Initial dialog state. + */ + constructor(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. + */ + static initialDialogStateForUserAgentClient(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 + const 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 + const routeSet = incomingResponseMessage.getHeaders("record-route").reverse(); + // 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. + // https://tools.ietf.org/html/rfc3261#section-12.1.1 + const contact = incomingResponseMessage.parseHeader("contact"); + if (!contact) { + // TODO: Review to make sure this will never happen + throw new Error("Contact undefined."); + } + if (!(contact instanceof _messages__WEBPACK_IMPORTED_MODULE_0__["NameAddrHeader"])) { + throw new Error("Contact not instance of NameAddrHeader."); + } + const 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 + const localSequenceNumber = outgoingRequestMessage.cseq; + const remoteSequenceNumber = undefined; + const callId = outgoingRequestMessage.callId; + const localTag = outgoingRequestMessage.fromTag; + const 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."); + } + const localURI = outgoingRequestMessage.from.uri; + const 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."); + } + const early = incomingResponseMessage.statusCode < 200 ? true : false; + const dialogState = { + id: callId + localTag + remoteTag, + early, + callId, + localTag, + remoteTag, + localSequenceNumber, + remoteSequenceNumber, + localURI, + remoteURI, + remoteTarget, + routeSet, + 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. + */ + static initialDialogStateForUserAgentServer(incomingRequestMessage, toTag, 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 + const 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 + const routeSet = incomingRequestMessage.getHeaders("record-route"); + const contact = incomingRequestMessage.parseHeader("contact"); + if (!contact) { + // TODO: Review to make sure this will never happen + throw new Error("Contact undefined."); + } + if (!(contact instanceof _messages__WEBPACK_IMPORTED_MODULE_0__["NameAddrHeader"])) { + throw new Error("Contact not instance of NameAddrHeader."); + } + const 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 + const remoteSequenceNumber = incomingRequestMessage.cseq; + const localSequenceNumber = undefined; + const callId = incomingRequestMessage.callId; + const localTag = toTag; + const 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 + const remoteURI = incomingRequestMessage.from.uri; + const localURI = incomingRequestMessage.to.uri; + const dialogState = { + id: callId + localTag + remoteTag, + early, + callId, + localTag, + remoteTag, + localSequenceNumber, + remoteSequenceNumber, + localURI, + remoteURI, + remoteTarget, + routeSet, + secure + }; + return dialogState; + } + /** Destructor. */ + dispose() { + this.core.dialogs.delete(this.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 id() { + return this.dialogState.id; + } + /** + * 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 early() { + return this.dialogState.early; + } + /** Call identifier component of the dialog id. */ + get callId() { + return this.dialogState.callId; + } + /** Local tag component of the dialog id. */ + get localTag() { + return this.dialogState.localTag; + } + /** Remote tag component of the dialog id. */ + get remoteTag() { + return this.dialogState.remoteTag; + } + /** Local sequence number (used to order requests from the UA to its peer). */ + get localSequenceNumber() { + return this.dialogState.localSequenceNumber; + } + /** Remote sequence number (used to order requests from its peer to the UA). */ + get remoteSequenceNumber() { + return this.dialogState.remoteSequenceNumber; + } + /** Local URI. */ + get localURI() { + return this.dialogState.localURI; + } + /** Remote URI. */ + get remoteURI() { + return this.dialogState.remoteURI; + } + /** Remote target. */ + get remoteTarget() { + return this.dialogState.remoteTarget; + } + /** + * 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 routeSet() { + return this.dialogState.routeSet; + } + /** + * 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 secure() { + return this.dialogState.secure; + } + /** The user agent core servicing this dialog. */ + get userAgentCore() { + return this.core; + } + /** Confirm the dialog. Only matters if dialog is currently early. */ + confirm() { + 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. + */ + receiveRequest(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__WEBPACK_IMPORTED_MODULE_0__["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 + */ + recomputeRouteSet(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. + */ + createOutgoingRequestMessage(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 + const toUri = this.remoteURI; + const toTag = this.remoteTag; + const fromUri = this.localURI; + const 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 + const callId = this.callId; + let 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). + const ruri = this.remoteTarget; + const routeSet = this.routeSet; + const extraHeaders = options && options.extraHeaders; + const 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 + const message = this.userAgentCore.makeOutgoingRequestMessage(method, ruri, fromUri, toUri, { + callId, + cseq, + fromTag, + toTag, + routeSet + }, extraHeaders, body); + return message; + } + /** + * Increment the local sequence number by one. + * It feels like this should be protected, but the current authentication handling currently + * needs this to keep the dialog in sync when "auto re-sends" request messages. + * @internal + */ + incrementLocalSequenceNumber() { + if (!this.dialogState.localSequenceNumber) { + throw new Error("Local sequence number undefined."); + } + this.dialogState.localSequenceNumber += 1; + } + /** + * 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. + */ + sequenceGuard(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__WEBPACK_IMPORTED_MODULE_0__["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; + } +} + + +/***/ }), +/* 8 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _grammar__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Grammar", function() { return _grammar__WEBPACK_IMPORTED_MODULE_0__["Grammar"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NameAddrHeader", function() { return _grammar__WEBPACK_IMPORTED_MODULE_0__["NameAddrHeader"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Parameters", function() { return _grammar__WEBPACK_IMPORTED_MODULE_0__["Parameters"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "URI", function() { return _grammar__WEBPACK_IMPORTED_MODULE_0__["URI"]; }); + +/* harmony import */ var _methods__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(15); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "C", function() { return _methods__WEBPACK_IMPORTED_MODULE_1__["C"]; }); + +/* harmony import */ var _body__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(29); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "fromBodyLegacy", function() { return _body__WEBPACK_IMPORTED_MODULE_2__["fromBodyLegacy"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isBody", function() { return _body__WEBPACK_IMPORTED_MODULE_2__["isBody"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getBody", function() { return _body__WEBPACK_IMPORTED_MODULE_2__["getBody"]; }); + +/* harmony import */ var _digest_authentication__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(35); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DigestAuthentication", function() { return _digest_authentication__WEBPACK_IMPORTED_MODULE_3__["DigestAuthentication"]; }); + +/* harmony import */ var _incoming_message__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(31); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IncomingMessage", function() { return _incoming_message__WEBPACK_IMPORTED_MODULE_4__["IncomingMessage"]; }); + +/* harmony import */ var _incoming_request_message__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(30); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IncomingRequestMessage", function() { return _incoming_request_message__WEBPACK_IMPORTED_MODULE_5__["IncomingRequestMessage"]; }); + +/* harmony import */ var _incoming_request__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(37); +/* empty/unused harmony star reexport *//* harmony import */ var _incoming_response_message__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(33); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IncomingResponseMessage", function() { return _incoming_response_message__WEBPACK_IMPORTED_MODULE_7__["IncomingResponseMessage"]; }); + +/* harmony import */ var _incoming_response__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(38); +/* empty/unused harmony star reexport *//* harmony import */ var _outgoing_request_message__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(34); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OutgoingRequestMessage", function() { return _outgoing_request_message__WEBPACK_IMPORTED_MODULE_9__["OutgoingRequestMessage"]; }); + +/* harmony import */ var _outgoing_request__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(39); +/* empty/unused harmony star reexport *//* harmony import */ var _outgoing_response__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(40); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "constructOutgoingResponse", function() { return _outgoing_response__WEBPACK_IMPORTED_MODULE_11__["constructOutgoingResponse"]; }); + +/* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(41); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Parser", function() { return _parser__WEBPACK_IMPORTED_MODULE_12__["Parser"]; }); + +// Grammar + +// Directories + +// Files + + + + + + + + + + + + + +/***/ }), +/* 9 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _grammar__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(10); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Grammar", function() { return _grammar__WEBPACK_IMPORTED_MODULE_0__["Grammar"]; }); + +/* harmony import */ var _name_addr_header__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(12); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NameAddrHeader", function() { return _name_addr_header__WEBPACK_IMPORTED_MODULE_1__["NameAddrHeader"]; }); + +/* harmony import */ var _parameters__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(13); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Parameters", function() { return _parameters__WEBPACK_IMPORTED_MODULE_2__["Parameters"]; }); + +/* harmony import */ var _uri__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(14); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "URI", function() { return _uri__WEBPACK_IMPORTED_MODULE_3__["URI"]; }); + + + + + + + +/***/ }), +/* 10 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Grammar", function() { return Grammar; }); +/* harmony import */ var _pegjs_dist_grammar__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(11); +/* eslint-disable @typescript-eslint/no-namespace */ +/* eslint-disable no-inner-declarations */ + +/** + * Grammar. + * @internal + */ +var Grammar; +(function (Grammar) { + /** + * Parse. + * @param input - + * @param startRule - + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + function parse(input, startRule) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const options = { startRule }; + try { + _pegjs_dist_grammar__WEBPACK_IMPORTED_MODULE_0__["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) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const 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) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const parsedUri = Grammar.parse(uri, "SIP_URI"); + return parsedUri !== -1 ? parsedUri : undefined; + } + Grammar.URIParse = URIParse; +})(Grammar || (Grammar = {})); + + +/***/ }), +/* 11 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SyntaxError", function() { return SyntaxError; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parse", function() { return parse; }); +/* harmony import */ var _name_addr_header__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(12); +/* harmony import */ var _uri__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(14); + + +class SyntaxError extends Error { + constructor(message, expected, found, location) { + super(); + this.message = message; + this.expected = expected; + this.found = found; + this.location = location; + this.name = "SyntaxError"; + if (typeof Error.captureStackTrace === "function") { + Error.captureStackTrace(this, SyntaxError); + } + } + static buildMessage(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, (ch) => "\\x0" + hex(ch)) + .replace(/[\x10-\x1F\x7F-\x9F]/g, (ch) => "\\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, (ch) => "\\x0" + hex(ch)) + .replace(/[\x10-\x1F\x7F-\x9F]/g, (ch) => "\\x" + hex(ch)); + } + function describeExpectation(expectation) { + switch (expectation.type) { + case "literal": + return "\"" + literalEscape(expectation.text) + "\""; + case "class": + const escapedParts = expectation.parts.map((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) { + const descriptions = expected1.map(describeExpectation); + let i; + let 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."; + } +} +function peg$parse(input, options) { + options = options !== undefined ? options : {}; + const peg$FAILED = {}; + const 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 }; + let peg$startRuleIndex = 119; + const 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__WEBPACK_IMPORTED_MODULE_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__WEBPACK_IMPORTED_MODULE_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__WEBPACK_IMPORTED_MODULE_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__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_0__["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) + ]; + const 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((ch) => ch.charCodeAt(0) - 32); + } + function peg$parseRule(index) { + const bc = peg$bytecode[index]; + let ip = 0; + const ips = []; + let end = bc.length; + const ends = []; + const stack = []; + let 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)); + } +} +const parse = peg$parse; + + +/***/ }), +/* 12 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NameAddrHeader", function() { return NameAddrHeader; }); +/* harmony import */ var _parameters__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(13); + +/** + * Name Address SIP header. + * @public + */ +class NameAddrHeader extends _parameters__WEBPACK_IMPORTED_MODULE_0__["Parameters"] { + /** + * Constructor + * @param uri - + * @param displayName - + * @param parameters - + */ + constructor(uri, displayName, parameters) { + super(parameters); + this.uri = uri; + this._displayName = displayName; + } + get friendlyName() { + return this.displayName || this.uri.aor; + } + get displayName() { return this._displayName; } + set displayName(value) { + this._displayName = value; + } + clone() { + return new NameAddrHeader(this.uri.clone(), this._displayName, JSON.parse(JSON.stringify(this.parameters))); + } + toString() { + let body = (this.displayName || this.displayName === "0") ? '"' + this.displayName + '" ' : ""; + body += "<" + this.uri.toString() + ">"; + for (const parameter in this.parameters) { + // eslint-disable-next-line no-prototype-builtins + if (this.parameters.hasOwnProperty(parameter)) { + body += ";" + parameter; + if (this.parameters[parameter] !== null) { + body += "=" + this.parameters[parameter]; + } + } + } + return body; + } +} + + +/***/ }), +/* 13 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Parameters", function() { return Parameters; }); +/** + * @internal + */ +class Parameters { + constructor(parameters) { + this.parameters = {}; + // for in is required here as the Grammar parser is adding to the prototype chain + for (const param in parameters) { + // eslint-disable-next-line no-prototype-builtins + if (parameters.hasOwnProperty(param)) { + this.setParam(param, parameters[param]); + } + } + } + setParam(key, value) { + if (key) { + this.parameters[key.toLowerCase()] = (typeof value === "undefined" || value === null) ? null : value.toString(); + } + } + getParam(key) { + if (key) { + return this.parameters[key.toLowerCase()]; + } + } + hasParam(key) { + return !!(key && this.parameters[key.toLowerCase()] !== undefined); + } + deleteParam(key) { + key = key.toLowerCase(); + if (this.hasParam(key)) { + const value = this.parameters[key]; + delete this.parameters[key]; + return value; + } + } + clearParams() { + this.parameters = {}; + } +} + + +/***/ }), +/* 14 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "URI", function() { return URI; }); +/* harmony import */ var _parameters__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(13); +/* eslint-disable @typescript-eslint/no-explicit-any */ + +/** + * URI. + * @public + */ +class URI extends _parameters__WEBPACK_IMPORTED_MODULE_0__["Parameters"] { + /** + * Constructor + * @param scheme - + * @param user - + * @param host - + * @param port - + * @param parameters - + * @param headers - + */ + constructor(scheme = "sip", user, host, port, parameters, headers) { + super(parameters || {}); + this.headers = {}; + // Checks + if (!host) { + throw new TypeError('missing or invalid "host" parameter'); + } + for (const header in headers) { + // eslint-disable-next-line no-prototype-builtins + if (headers.hasOwnProperty(header)) { + this.setHeader(header, headers[header]); + } + } + // Raw URI + this.raw = { + scheme, + user, + host, + port + }; + // Normalized URI + this.normal = { + scheme: scheme.toLowerCase(), + user, + host: host.toLowerCase(), + port + }; + } + get scheme() { return this.normal.scheme; } + set scheme(value) { + this.raw.scheme = value; + this.normal.scheme = value.toLowerCase(); + } + get user() { return this.normal.user; } + set user(value) { + this.normal.user = this.raw.user = value; + } + get host() { return this.normal.host; } + set host(value) { + this.raw.host = value; + this.normal.host = value.toLowerCase(); + } + get aor() { return this.normal.user + "@" + this.normal.host; } + get port() { return this.normal.port; } + set port(value) { + this.normal.port = this.raw.port = value === 0 ? value : value; + } + setHeader(name, value) { + this.headers[this.headerize(name)] = (value instanceof Array) ? value : [value]; + } + getHeader(name) { + if (name) { + return this.headers[this.headerize(name)]; + } + } + hasHeader(name) { + // eslint-disable-next-line no-prototype-builtins + return !!name && !!this.headers.hasOwnProperty(this.headerize(name)); + } + deleteHeader(header) { + header = this.headerize(header); + // eslint-disable-next-line no-prototype-builtins + if (this.headers.hasOwnProperty(header)) { + const value = this.headers[header]; + delete this.headers[header]; + return value; + } + } + clearHeaders() { + this.headers = {}; + } + clone() { + 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))); + } + toRaw() { + return this._toString(this._raw); + } + toString() { + return this._toString(this._normal); + } + get _normal() { return this.normal; } + get _raw() { return this.raw; } + _toString(uri) { + let 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 (const parameter in this.parameters) { + // eslint-disable-next-line no-prototype-builtins + if (this.parameters.hasOwnProperty(parameter)) { + uriString += ";" + parameter; + if (this.parameters[parameter] !== null) { + uriString += "=" + this.parameters[parameter]; + } + } + } + const headers = []; + for (const header in this.headers) { + // eslint-disable-next-line no-prototype-builtins + if (this.headers.hasOwnProperty(header)) { + for (const idx in this.headers[header]) { + // eslint-disable-next-line no-prototype-builtins + 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 + */ + escapeUser(user) { + let 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. + // eslint-disable-next-line no-useless-catch + 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, "/"); + } + headerize(str) { + const exceptions = { + "Call-Id": "Call-ID", + "Cseq": "CSeq", + "Min-Se": "Min-SE", + "Rack": "RAck", + "Rseq": "RSeq", + "Www-Authenticate": "WWW-Authenticate", + }; + const name = str.toLowerCase().replace(/_/g, "-").split("-"); + const parts = name.length; + let hname = ""; + for (let 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; + } +} + + +/***/ }), +/* 15 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(16); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "C", function() { return _constants__WEBPACK_IMPORTED_MODULE_0__["C"]; }); + +/* harmony import */ var _ack__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(17); +/* empty/unused harmony star reexport *//* harmony import */ var _bye__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(18); +/* empty/unused harmony star reexport *//* harmony import */ var _cancel__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(19); +/* empty/unused harmony star reexport *//* harmony import */ var _info__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(20); +/* empty/unused harmony star reexport *//* harmony import */ var _invite__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(21); +/* empty/unused harmony star reexport *//* harmony import */ var _message__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(22); +/* empty/unused harmony star reexport *//* harmony import */ var _notify__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(23); +/* empty/unused harmony star reexport *//* harmony import */ var _prack__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(24); +/* empty/unused harmony star reexport *//* harmony import */ var _publish__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(25); +/* empty/unused harmony star reexport *//* harmony import */ var _register__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(26); +/* empty/unused harmony star reexport *//* harmony import */ var _refer__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(27); +/* empty/unused harmony star reexport *//* harmony import */ var _subscribe__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(28); +/* empty/unused harmony star reexport */ + + + + + + + + + + + + + + +/***/ }), +/* 16 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "C", function() { return C; }); +/* eslint-disable @typescript-eslint/no-namespace */ +/** + * 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 || (C = {})); + + +/***/ }), +/* 17 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 18 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 19 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 20 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 21 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 22 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 23 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 24 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 25 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 26 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 27 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 28 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 29 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fromBodyLegacy", function() { return fromBodyLegacy; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isBody", function() { return isBody; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getBody", function() { return getBody; }); +/* harmony import */ var _incoming_request_message__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(30); +/* harmony import */ var _incoming_response_message__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(33); +/* harmony import */ var _outgoing_request_message__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(34); + + + +// 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"; + } +} +/** + * Create a Body given a legacy body type. + * @param bodyLegacy - Body Object + * @internal + */ +function fromBodyLegacy(bodyLegacy) { + const content = typeof bodyLegacy === "string" ? bodyLegacy : bodyLegacy.body; + const contentType = typeof bodyLegacy === "string" ? "application/sdp" : bodyLegacy.contentType; + const contentDisposition = contentTypeToContentDisposition(contentType); + const body = { contentDisposition, contentType, content }; + return body; +} +/** + * User-Defined Type Guard for Body. + * @param body - Body to check. + * @internal + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function isBody(body) { + return body && + typeof body.content === "string" && + typeof body.contentType === "string" && + body.contentDisposition === undefined + ? true + : typeof body.contentDisposition === "string"; +} +/** + * Given a message, get a normalized body. + * The content disposition is inferred if not set. + * @param message - The message. + * @internal + */ +function getBody(message) { + let contentDisposition; + let contentType; + let content; + // We're in UAS role, receiving incoming request + if (message instanceof _incoming_request_message__WEBPACK_IMPORTED_MODULE_0__["IncomingRequestMessage"]) { + if (message.body) { + // FIXME: Parsing needs typing + const 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__WEBPACK_IMPORTED_MODULE_1__["IncomingResponseMessage"]) { + if (message.body) { + // FIXME: Parsing needs typing + const 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__WEBPACK_IMPORTED_MODULE_2__["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, + contentType, + content + }; +} + + +/***/ }), +/* 30 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "IncomingRequestMessage", function() { return IncomingRequestMessage; }); +/* harmony import */ var _incoming_message__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(31); + +/** + * Incoming request message. + * @public + */ +class IncomingRequestMessage extends _incoming_message__WEBPACK_IMPORTED_MODULE_0__["IncomingMessage"] { + constructor() { + super(); + } +} + + +/***/ }), +/* 31 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "IncomingMessage", function() { return IncomingMessage; }); +/* harmony import */ var _grammar__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9); +/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(32); + + +/** + * Incoming message. + * @public + */ +class IncomingMessage { + constructor() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + 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 + */ + addHeader(name, value) { + const header = { raw: value }; + name = Object(_utils__WEBPACK_IMPORTED_MODULE_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. + */ + getHeader(name) { + const header = this.headers[Object(_utils__WEBPACK_IMPORTED_MODULE_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. + */ + getHeaders(name) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const header = this.headers[Object(_utils__WEBPACK_IMPORTED_MODULE_1__["headerize"])(name)]; + const result = []; + if (!header) { + return []; + } + for (const headerPart of header) { + 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 + */ + hasHeader(name) { + return !!this.headers[Object(_utils__WEBPACK_IMPORTED_MODULE_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. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + parseHeader(name, idx = 0) { + name = Object(_utils__WEBPACK_IMPORTED_MODULE_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; + } + const header = this.headers[name][idx]; + const value = header.raw; + if (header.parsed) { + return header.parsed; + } + // substitute '-' by '_' for grammar rule matching. + const parsed = _grammar__WEBPACK_IMPORTED_MODULE_0__["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 + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + s(name, 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 + */ + setHeader(name, value) { + this.headers[Object(_utils__WEBPACK_IMPORTED_MODULE_1__["headerize"])(name)] = [{ raw: value }]; + } + toString() { + return this.data; + } +} + + +/***/ }), +/* 32 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createRandomToken", function() { return createRandomToken; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getReasonPhrase", function() { return getReasonPhrase; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "newTag", function() { return newTag; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "headerize", function() { return headerize; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "utf8Length", function() { return utf8Length; }); +/** + * SIP Response Reasons + * DOC: http://www.iana.org/assignments/sip-parameters + * @internal + */ +const 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" +}; +/** + * @param size - + * @param base - + * @internal + */ +function createRandomToken(size, base = 32) { + let token = ""; + for (let i = 0; i < size; i++) { + const r = Math.floor(Math.random() * base); + token += r.toString(base); + } + return token; +} +/** + * @internal + */ +function getReasonPhrase(code) { + return REASON_PHRASE[code] || ""; +} +/** + * @internal + */ +function newTag() { + return createRandomToken(10); +} +/** + * @param str - + * @internal + */ +function headerize(str) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const exceptions = { + "Call-Id": "Call-ID", + Cseq: "CSeq", + "Min-Se": "Min-SE", + Rack: "RAck", + Rseq: "RSeq", + "Www-Authenticate": "WWW-Authenticate" + }; + const name = str.toLowerCase().replace(/_/g, "-").split("-"); + const parts = name.length; + let hname = ""; + for (let 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; +} +/** + * @param str - + * @internal + */ +function utf8Length(str) { + return encodeURIComponent(str).replace(/%[A-F\d]{2}/g, "U").length; +} + + +/***/ }), +/* 33 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "IncomingResponseMessage", function() { return IncomingResponseMessage; }); +/* harmony import */ var _incoming_message__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(31); + +/** + * Incoming response message. + * @public + */ +class IncomingResponseMessage extends _incoming_message__WEBPACK_IMPORTED_MODULE_0__["IncomingMessage"] { + constructor() { + super(); + } +} + + +/***/ }), +/* 34 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OutgoingRequestMessage", function() { return OutgoingRequestMessage; }); +/* harmony import */ var _grammar__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9); +/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(32); + + +/** + * Outgoing SIP request message. + * @public + */ +class OutgoingRequestMessage { + constructor(method, ruri, fromURI, toURI, options, extraHeaders, body) { + this.headers = {}; + this.extraHeaders = []; + // Initialize default options + this.options = OutgoingRequestMessage.getDefaultOptions(); + // Options - merge a deep copy + if (options) { + this.options = Object.assign(Object.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 : Object(_utils__WEBPACK_IMPORTED_MODULE_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 + Object(_utils__WEBPACK_IMPORTED_MODULE_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. */ + static getDefaultOptions() { + return { + callId: "", + callIdPrefix: "", + cseq: 1, + toDisplayName: "", + toTag: "", + fromDisplayName: "", + fromTag: "", + forceRport: false, + hackViaTcp: false, + optionTags: ["outbound"], + routeSet: [], + userAgentString: "sip.js", + viaHost: "" + }; + } + static makeNameAddrHeader(uri, displayName, tag) { + const parameters = {}; + if (tag) { + parameters.tag = tag; + } + return new _grammar__WEBPACK_IMPORTED_MODULE_0__["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. + */ + getHeader(name) { + const header = this.headers[Object(_utils__WEBPACK_IMPORTED_MODULE_1__["headerize"])(name)]; + if (header) { + if (header[0]) { + return header[0]; + } + } + else { + const regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); + for (const exHeader of this.extraHeaders) { + 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. + */ + getHeaders(name) { + const result = []; + const headerArray = this.headers[Object(_utils__WEBPACK_IMPORTED_MODULE_1__["headerize"])(name)]; + if (headerArray) { + for (const headerPart of headerArray) { + result.push(headerPart); + } + } + else { + const regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); + for (const exHeader of this.extraHeaders) { + 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 + */ + hasHeader(name) { + if (this.headers[Object(_utils__WEBPACK_IMPORTED_MODULE_1__["headerize"])(name)]) { + return true; + } + else { + const regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); + for (const extraHeader of this.extraHeaders) { + 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 + */ + setHeader(name, value) { + this.headers[Object(_utils__WEBPACK_IMPORTED_MODULE_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 transport - The sent protocol transport. + */ + setViaHeader(branch, transport) { + // FIXME: Hack + if (this.options.hackViaTcp) { + transport = "TCP"; + } + let via = "SIP/2.0/" + transport; + via += " " + this.options.viaHost + ";branch=" + branch; + if (this.options.forceRport) { + via += ";rport"; + } + this.setHeader("via", via); + this.branch = branch; + } + toString() { + let msg = ""; + msg += this.method + " " + this.ruri.toRaw() + " SIP/2.0\r\n"; + for (const header in this.headers) { + if (this.headers[header]) { + for (const headerPart of this.headers[header]) { + msg += header + ": " + headerPart + "\r\n"; + } + } + } + for (const header of this.extraHeaders) { + 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: " + Object(_utils__WEBPACK_IMPORTED_MODULE_1__["utf8Length"])(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: " + Object(_utils__WEBPACK_IMPORTED_MODULE_1__["utf8Length"])(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; + } +} + + +/***/ }), +/* 35 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DigestAuthentication", function() { return DigestAuthentication; }); +/* harmony import */ var _md5__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); +/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(32); + + +function MD5(s) { + return _md5__WEBPACK_IMPORTED_MODULE_0__["Md5"].hashStr(s); +} +/** + * Digest Authentication. + * @internal + */ +class DigestAuthentication { + /** + * Constructor. + * @param loggerFactory - LoggerFactory. + * @param username - Username. + * @param password - Password. + */ + constructor(loggerFactory, ha1, username, password) { + this.logger = loggerFactory.getLogger("sipjs.digestauthentication"); + this.username = username; + this.password = password; + this.ha1 = ha1; + 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. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + authenticate(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 = Object(_utils__WEBPACK_IMPORTED_MODULE_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. + */ + toString() { + const 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. + */ + updateNcHex() { + const hex = Number(this.nc).toString(16); + this.ncHex = "00000000".substr(0, 8 - hex.length) + hex; + } + /** + * Generate Digest 'response' value. + */ + calculateResponse(body) { + let ha1, ha2; + // HA1 = MD5(A1) = MD5(username:realm:password) + ha1 = this.ha1; + if (ha1 === "" || ha1 === undefined) { + ha1 = MD5(this.username + ":" + this.realm + ":" + this.password); + } + if (this.qop === "auth") { + // HA2 = MD5(A2) = MD5(method:digestURI) + ha2 = MD5(this.method + ":" + this.uri); + // response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2)` + this.response = MD5(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(this.method + ":" + this.uri + ":" + MD5(body ? body : "")); + // response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2) + this.response = MD5(ha1 + ":" + this.nonce + ":" + this.ncHex + ":" + this.cnonce + ":auth-int:" + ha2); + } + else if (this.qop === undefined) { + // HA2 = MD5(A2) = MD5(method:digestURI) + ha2 = MD5(this.method + ":" + this.uri); + // response = MD5(HA1:nonce:HA2) + this.response = MD5(ha1 + ":" + this.nonce + ":" + ha2); + } + } +} + + +/***/ }), +/* 36 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Md5", function() { return Md5; }); +/* eslint-disable */ +// +// Scoped from: https://github.com/cotag/ts-md5 +// +/* + +TypeScript Md5 +============== + +Based on work by +* Joseph Myers: http://www.myersdaily.org/joseph/javascript/md5-text.html +* André Cruz: https://github.com/satazor/SparkMD5 +* Raymond Hill: https://github.com/gorhill/yamd5.js + +Effectively a TypeScrypt re-write of Raymond Hill JS Library + +The MIT License (MIT) + +Copyright (C) 2014 Raymond Hill + +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. + + + + DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE + Version 2, December 2004 + + Copyright (C) 2015 André Cruz + + Everyone is permitted to copy and distribute verbatim or modified + copies of this license document, and changing it is allowed as long + as the name is changed. + + DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. You just DO WHAT THE FUCK YOU WANT TO. + + +*/ +class Md5 { + constructor() { + this._dataLength = 0; + this._bufferLength = 0; + this._state = new Int32Array(4); + this._buffer = new ArrayBuffer(68); + this._buffer8 = new Uint8Array(this._buffer, 0, 68); + this._buffer32 = new Uint32Array(this._buffer, 0, 17); + this.start(); + } + static hashStr(str, raw = false) { + return this.onePassHasher + .start() + .appendStr(str) + .end(raw); + } + static hashAsciiStr(str, raw = false) { + return this.onePassHasher + .start() + .appendAsciiStr(str) + .end(raw); + } + static _hex(x) { + const hc = Md5.hexChars; + const ho = Md5.hexOut; + let n; + let offset; + let j; + let i; + for (i = 0; i < 4; i += 1) { + offset = i * 8; + n = x[i]; + for (j = 0; j < 8; j += 2) { + ho[offset + 1 + j] = hc.charAt(n & 0x0F); + n >>>= 4; + ho[offset + 0 + j] = hc.charAt(n & 0x0F); + n >>>= 4; + } + } + return ho.join(''); + } + static _md5cycle(x, k) { + let a = x[0]; + let b = x[1]; + let c = x[2]; + let d = x[3]; + // ff() + a += (b & c | ~b & d) + k[0] - 680876936 | 0; + a = (a << 7 | a >>> 25) + b | 0; + d += (a & b | ~a & c) + k[1] - 389564586 | 0; + d = (d << 12 | d >>> 20) + a | 0; + c += (d & a | ~d & b) + k[2] + 606105819 | 0; + c = (c << 17 | c >>> 15) + d | 0; + b += (c & d | ~c & a) + k[3] - 1044525330 | 0; + b = (b << 22 | b >>> 10) + c | 0; + a += (b & c | ~b & d) + k[4] - 176418897 | 0; + a = (a << 7 | a >>> 25) + b | 0; + d += (a & b | ~a & c) + k[5] + 1200080426 | 0; + d = (d << 12 | d >>> 20) + a | 0; + c += (d & a | ~d & b) + k[6] - 1473231341 | 0; + c = (c << 17 | c >>> 15) + d | 0; + b += (c & d | ~c & a) + k[7] - 45705983 | 0; + b = (b << 22 | b >>> 10) + c | 0; + a += (b & c | ~b & d) + k[8] + 1770035416 | 0; + a = (a << 7 | a >>> 25) + b | 0; + d += (a & b | ~a & c) + k[9] - 1958414417 | 0; + d = (d << 12 | d >>> 20) + a | 0; + c += (d & a | ~d & b) + k[10] - 42063 | 0; + c = (c << 17 | c >>> 15) + d | 0; + b += (c & d | ~c & a) + k[11] - 1990404162 | 0; + b = (b << 22 | b >>> 10) + c | 0; + a += (b & c | ~b & d) + k[12] + 1804603682 | 0; + a = (a << 7 | a >>> 25) + b | 0; + d += (a & b | ~a & c) + k[13] - 40341101 | 0; + d = (d << 12 | d >>> 20) + a | 0; + c += (d & a | ~d & b) + k[14] - 1502002290 | 0; + c = (c << 17 | c >>> 15) + d | 0; + b += (c & d | ~c & a) + k[15] + 1236535329 | 0; + b = (b << 22 | b >>> 10) + c | 0; + // gg() + a += (b & d | c & ~d) + k[1] - 165796510 | 0; + a = (a << 5 | a >>> 27) + b | 0; + d += (a & c | b & ~c) + k[6] - 1069501632 | 0; + d = (d << 9 | d >>> 23) + a | 0; + c += (d & b | a & ~b) + k[11] + 643717713 | 0; + c = (c << 14 | c >>> 18) + d | 0; + b += (c & a | d & ~a) + k[0] - 373897302 | 0; + b = (b << 20 | b >>> 12) + c | 0; + a += (b & d | c & ~d) + k[5] - 701558691 | 0; + a = (a << 5 | a >>> 27) + b | 0; + d += (a & c | b & ~c) + k[10] + 38016083 | 0; + d = (d << 9 | d >>> 23) + a | 0; + c += (d & b | a & ~b) + k[15] - 660478335 | 0; + c = (c << 14 | c >>> 18) + d | 0; + b += (c & a | d & ~a) + k[4] - 405537848 | 0; + b = (b << 20 | b >>> 12) + c | 0; + a += (b & d | c & ~d) + k[9] + 568446438 | 0; + a = (a << 5 | a >>> 27) + b | 0; + d += (a & c | b & ~c) + k[14] - 1019803690 | 0; + d = (d << 9 | d >>> 23) + a | 0; + c += (d & b | a & ~b) + k[3] - 187363961 | 0; + c = (c << 14 | c >>> 18) + d | 0; + b += (c & a | d & ~a) + k[8] + 1163531501 | 0; + b = (b << 20 | b >>> 12) + c | 0; + a += (b & d | c & ~d) + k[13] - 1444681467 | 0; + a = (a << 5 | a >>> 27) + b | 0; + d += (a & c | b & ~c) + k[2] - 51403784 | 0; + d = (d << 9 | d >>> 23) + a | 0; + c += (d & b | a & ~b) + k[7] + 1735328473 | 0; + c = (c << 14 | c >>> 18) + d | 0; + b += (c & a | d & ~a) + k[12] - 1926607734 | 0; + b = (b << 20 | b >>> 12) + c | 0; + // hh() + a += (b ^ c ^ d) + k[5] - 378558 | 0; + a = (a << 4 | a >>> 28) + b | 0; + d += (a ^ b ^ c) + k[8] - 2022574463 | 0; + d = (d << 11 | d >>> 21) + a | 0; + c += (d ^ a ^ b) + k[11] + 1839030562 | 0; + c = (c << 16 | c >>> 16) + d | 0; + b += (c ^ d ^ a) + k[14] - 35309556 | 0; + b = (b << 23 | b >>> 9) + c | 0; + a += (b ^ c ^ d) + k[1] - 1530992060 | 0; + a = (a << 4 | a >>> 28) + b | 0; + d += (a ^ b ^ c) + k[4] + 1272893353 | 0; + d = (d << 11 | d >>> 21) + a | 0; + c += (d ^ a ^ b) + k[7] - 155497632 | 0; + c = (c << 16 | c >>> 16) + d | 0; + b += (c ^ d ^ a) + k[10] - 1094730640 | 0; + b = (b << 23 | b >>> 9) + c | 0; + a += (b ^ c ^ d) + k[13] + 681279174 | 0; + a = (a << 4 | a >>> 28) + b | 0; + d += (a ^ b ^ c) + k[0] - 358537222 | 0; + d = (d << 11 | d >>> 21) + a | 0; + c += (d ^ a ^ b) + k[3] - 722521979 | 0; + c = (c << 16 | c >>> 16) + d | 0; + b += (c ^ d ^ a) + k[6] + 76029189 | 0; + b = (b << 23 | b >>> 9) + c | 0; + a += (b ^ c ^ d) + k[9] - 640364487 | 0; + a = (a << 4 | a >>> 28) + b | 0; + d += (a ^ b ^ c) + k[12] - 421815835 | 0; + d = (d << 11 | d >>> 21) + a | 0; + c += (d ^ a ^ b) + k[15] + 530742520 | 0; + c = (c << 16 | c >>> 16) + d | 0; + b += (c ^ d ^ a) + k[2] - 995338651 | 0; + b = (b << 23 | b >>> 9) + c | 0; + // ii() + a += (c ^ (b | ~d)) + k[0] - 198630844 | 0; + a = (a << 6 | a >>> 26) + b | 0; + d += (b ^ (a | ~c)) + k[7] + 1126891415 | 0; + d = (d << 10 | d >>> 22) + a | 0; + c += (a ^ (d | ~b)) + k[14] - 1416354905 | 0; + c = (c << 15 | c >>> 17) + d | 0; + b += (d ^ (c | ~a)) + k[5] - 57434055 | 0; + b = (b << 21 | b >>> 11) + c | 0; + a += (c ^ (b | ~d)) + k[12] + 1700485571 | 0; + a = (a << 6 | a >>> 26) + b | 0; + d += (b ^ (a | ~c)) + k[3] - 1894986606 | 0; + d = (d << 10 | d >>> 22) + a | 0; + c += (a ^ (d | ~b)) + k[10] - 1051523 | 0; + c = (c << 15 | c >>> 17) + d | 0; + b += (d ^ (c | ~a)) + k[1] - 2054922799 | 0; + b = (b << 21 | b >>> 11) + c | 0; + a += (c ^ (b | ~d)) + k[8] + 1873313359 | 0; + a = (a << 6 | a >>> 26) + b | 0; + d += (b ^ (a | ~c)) + k[15] - 30611744 | 0; + d = (d << 10 | d >>> 22) + a | 0; + c += (a ^ (d | ~b)) + k[6] - 1560198380 | 0; + c = (c << 15 | c >>> 17) + d | 0; + b += (d ^ (c | ~a)) + k[13] + 1309151649 | 0; + b = (b << 21 | b >>> 11) + c | 0; + a += (c ^ (b | ~d)) + k[4] - 145523070 | 0; + a = (a << 6 | a >>> 26) + b | 0; + d += (b ^ (a | ~c)) + k[11] - 1120210379 | 0; + d = (d << 10 | d >>> 22) + a | 0; + c += (a ^ (d | ~b)) + k[2] + 718787259 | 0; + c = (c << 15 | c >>> 17) + d | 0; + b += (d ^ (c | ~a)) + k[9] - 343485551 | 0; + b = (b << 21 | b >>> 11) + c | 0; + x[0] = a + x[0] | 0; + x[1] = b + x[1] | 0; + x[2] = c + x[2] | 0; + x[3] = d + x[3] | 0; + } + start() { + this._dataLength = 0; + this._bufferLength = 0; + this._state.set(Md5.stateIdentity); + return this; + } + // Char to code point to to array conversion: + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt + // #Example.3A_Fixing_charCodeAt_to_handle_non-Basic-Multilingual-Plane_characters_if_their_presence_earlier_in_the_string_is_unknown + appendStr(str) { + const buf8 = this._buffer8; + const buf32 = this._buffer32; + let bufLen = this._bufferLength; + let code; + let i; + for (i = 0; i < str.length; i += 1) { + code = str.charCodeAt(i); + if (code < 128) { + buf8[bufLen++] = code; + } + else if (code < 0x800) { + buf8[bufLen++] = (code >>> 6) + 0xC0; + buf8[bufLen++] = code & 0x3F | 0x80; + } + else if (code < 0xD800 || code > 0xDBFF) { + buf8[bufLen++] = (code >>> 12) + 0xE0; + buf8[bufLen++] = (code >>> 6 & 0x3F) | 0x80; + buf8[bufLen++] = (code & 0x3F) | 0x80; + } + else { + code = ((code - 0xD800) * 0x400) + (str.charCodeAt(++i) - 0xDC00) + 0x10000; + if (code > 0x10FFFF) { + throw new Error('Unicode standard supports code points up to U+10FFFF'); + } + buf8[bufLen++] = (code >>> 18) + 0xF0; + buf8[bufLen++] = (code >>> 12 & 0x3F) | 0x80; + buf8[bufLen++] = (code >>> 6 & 0x3F) | 0x80; + buf8[bufLen++] = (code & 0x3F) | 0x80; + } + if (bufLen >= 64) { + this._dataLength += 64; + Md5._md5cycle(this._state, buf32); + bufLen -= 64; + buf32[0] = buf32[16]; + } + } + this._bufferLength = bufLen; + return this; + } + appendAsciiStr(str) { + const buf8 = this._buffer8; + const buf32 = this._buffer32; + let bufLen = this._bufferLength; + let i; + let j = 0; + for (;;) { + i = Math.min(str.length - j, 64 - bufLen); + while (i--) { + buf8[bufLen++] = str.charCodeAt(j++); + } + if (bufLen < 64) { + break; + } + this._dataLength += 64; + Md5._md5cycle(this._state, buf32); + bufLen = 0; + } + this._bufferLength = bufLen; + return this; + } + appendByteArray(input) { + const buf8 = this._buffer8; + const buf32 = this._buffer32; + let bufLen = this._bufferLength; + let i; + let j = 0; + for (;;) { + i = Math.min(input.length - j, 64 - bufLen); + while (i--) { + buf8[bufLen++] = input[j++]; + } + if (bufLen < 64) { + break; + } + this._dataLength += 64; + Md5._md5cycle(this._state, buf32); + bufLen = 0; + } + this._bufferLength = bufLen; + return this; + } + getState() { + const self = this; + const s = self._state; + return { + buffer: String.fromCharCode.apply(null, self._buffer8), + buflen: self._bufferLength, + length: self._dataLength, + state: [s[0], s[1], s[2], s[3]] + }; + } + setState(state) { + const buf = state.buffer; + const x = state.state; + const s = this._state; + let i; + this._dataLength = state.length; + this._bufferLength = state.buflen; + s[0] = x[0]; + s[1] = x[1]; + s[2] = x[2]; + s[3] = x[3]; + for (i = 0; i < buf.length; i += 1) { + this._buffer8[i] = buf.charCodeAt(i); + } + } + end(raw = false) { + const bufLen = this._bufferLength; + const buf8 = this._buffer8; + const buf32 = this._buffer32; + const i = (bufLen >> 2) + 1; + let dataBitsLen; + this._dataLength += bufLen; + buf8[bufLen] = 0x80; + buf8[bufLen + 1] = buf8[bufLen + 2] = buf8[bufLen + 3] = 0; + buf32.set(Md5.buffer32Identity.subarray(i), i); + if (bufLen > 55) { + Md5._md5cycle(this._state, buf32); + buf32.set(Md5.buffer32Identity); + } + // Do the final computation based on the tail and length + // Beware that the final length may not fit in 32 bits so we take care of that + dataBitsLen = this._dataLength * 8; + if (dataBitsLen <= 0xFFFFFFFF) { + buf32[14] = dataBitsLen; + } + else { + const matches = dataBitsLen.toString(16).match(/(.*?)(.{0,8})$/); + if (matches === null) { + return; + } + const lo = parseInt(matches[2], 16); + const hi = parseInt(matches[1], 16) || 0; + buf32[14] = lo; + buf32[15] = hi; + } + Md5._md5cycle(this._state, buf32); + return raw ? this._state : Md5._hex(this._state); + } +} +// Private Static Variables +Md5.stateIdentity = new Int32Array([1732584193, -271733879, -1732584194, 271733878]); +Md5.buffer32Identity = new Int32Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); +Md5.hexChars = '0123456789abcdef'; +Md5.hexOut = []; +// Permanent instance is to use for one-call hashing +Md5.onePassHasher = new Md5(); +if (Md5.hashStr('hello') !== '5d41402abc4b2a76b9719d911017c592') { + console.error('Md5 self test failed.'); +} + + +/***/ }), +/* 37 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 38 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 39 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 40 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "constructOutgoingResponse", function() { return constructOutgoingResponse; }); +/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(32); + +/** + * 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) { + const CRLF = "\r\n"; + if (options.statusCode < 100 || options.statusCode > 699) { + throw new TypeError("Invalid statusCode: " + options.statusCode); + } + const reasonPhrase = options.reasonPhrase ? options.reasonPhrase : Object(_utils__WEBPACK_IMPORTED_MODULE_0__["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 + let 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 + const fromHeader = "From: " + message.getHeader("From") + CRLF; + const callIdHeader = "Call-ID: " + message.callId + CRLF; + const cSeqHeader = "CSeq: " + message.cseq + " " + message.method + CRLF; + const viaHeaders = message.getHeaders("via").reduce((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 + let toHeader = "To: " + message.getHeader("to"); + if (options.statusCode > 100 && !message.parseHeader("to").hasParam("tag")) { + let 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 = Object(_utils__WEBPACK_IMPORTED_MODULE_0__["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... + let supportedHeader = ""; + if (options.supported) { + supportedHeader = "Supported: " + options.supported.join(", ") + CRLF; + } + // FIXME: TODO: needs review... + let userAgentHeader = ""; + if (options.userAgent) { + userAgentHeader = "User-Agent: " + options.userAgent + CRLF; + } + let extensionHeaders = ""; + if (options.extraHeaders) { + extensionHeaders = options.extraHeaders.reduce((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: " + Object(_utils__WEBPACK_IMPORTED_MODULE_0__["utf8Length"])(options.body.content) + CRLF + CRLF; + response += options.body.content; + } + else { + response += "Content-Length: " + 0 + CRLF + CRLF; + } + return { message: response }; +} + + +/***/ }), +/* 41 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Parser", function() { return Parser; }); +/* harmony import */ var _grammar__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9); +/* harmony import */ var _incoming_request_message__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(30); +/* harmony import */ var _incoming_response_message__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(33); +/* eslint-disable no-inner-declarations */ +/* eslint-disable @typescript-eslint/no-namespace */ + + + +/** + * Extract and parse every header of a SIP message. + * @internal + */ +var Parser; +(function (Parser) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + function getHeader(data, headerStart) { + // 'start' position of the header. + let start = headerStart; + // 'end' position of the header. + let end = 0; + // 'partial end' position of the header. + let 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, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + data, headerStart, headerEnd) { + const hcolonIndex = data.indexOf(":", headerStart); + const headerName = data.substring(headerStart, hcolonIndex).trim(); + const headerValue = data.substring(hcolonIndex + 1, headerEnd).trim(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let 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 = _grammar__WEBPACK_IMPORTED_MODULE_0__["Grammar"].parse(headerValue, "Record_Route"); + if (parsed === -1) { + parsed = undefined; + break; + } + if (!(parsed instanceof Array)) { + parsed = undefined; + break; + } + parsed.forEach((header) => { + message.addHeader("record-route", headerValue.substring(header.position, header.offset)); + message.headers["Record-Route"][message.getHeaders("record-route").length - 1].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 = _grammar__WEBPACK_IMPORTED_MODULE_0__["Grammar"].parse(headerValue, "Contact"); + if (parsed === -1) { + parsed = undefined; + break; + } + if (!(parsed instanceof Array)) { + parsed = undefined; + break; + } + parsed.forEach((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 _incoming_response_message__WEBPACK_IMPORTED_MODULE_2__["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; + function parseMessage(data, logger) { + let headerStart = 0; + let 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. + const firstLine = data.substring(0, headerEnd); + const parsed = _grammar__WEBPACK_IMPORTED_MODULE_0__["Grammar"].parse(firstLine, "Request_Response"); + let message; + if (parsed === -1) { + logger.warn('error parsing first line of SIP message: "' + firstLine + '"'); + return; + } + else if (!parsed.status_code) { + message = new _incoming_request_message__WEBPACK_IMPORTED_MODULE_1__["IncomingRequestMessage"](); + message.method = parsed.method; + message.ruri = parsed.uri; + } + else { + message = new _incoming_response_message__WEBPACK_IMPORTED_MODULE_2__["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. + let bodyStart; + // eslint-disable-next-line no-constant-condition + 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; + } + const parsedHeader = parseHeader(message, data, headerStart, headerEnd); + if (parsedHeader && parsedHeader !== true) { + logger.error(parsedHeader.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 || (Parser = {})); + + +/***/ }), +/* 42 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 43 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SessionDialog", function() { return SessionDialog; }); +/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); +/* harmony import */ var _session__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(44); +/* harmony import */ var _timers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(47); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(48); +/* harmony import */ var _user_agents_bye_user_agent_client__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(62); +/* harmony import */ var _user_agents_bye_user_agent_server__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(64); +/* harmony import */ var _user_agents_info_user_agent_client__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(66); +/* harmony import */ var _user_agents_info_user_agent_server__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(67); +/* harmony import */ var _user_agents_message_user_agent_client__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(68); +/* harmony import */ var _user_agents_message_user_agent_server__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(69); +/* harmony import */ var _user_agents_notify_user_agent_client__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(70); +/* harmony import */ var _user_agents_notify_user_agent_server__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(71); +/* harmony import */ var _user_agents_prack_user_agent_client__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(72); +/* harmony import */ var _user_agents_prack_user_agent_server__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(73); +/* harmony import */ var _user_agents_re_invite_user_agent_client__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(74); +/* harmony import */ var _user_agents_re_invite_user_agent_server__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(75); +/* harmony import */ var _user_agents_refer_user_agent_client__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(76); +/* harmony import */ var _user_agents_refer_user_agent_server__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(77); +/* harmony import */ var _dialog__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(7); + + + + + + + + + + + + + + + + + + + +/** + * Session Dialog. + * @public + */ +class SessionDialog extends _dialog__WEBPACK_IMPORTED_MODULE_18__["Dialog"] { + constructor(initialTransaction, core, state, delegate) { + super(core, state); + this.initialTransaction = initialTransaction; + /** The state of the offer/answer exchange. */ + this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Initial; + /** True if waiting for an ACK to the initial transaction 2xx (UAS only). */ + this.ackWait = false; + /** True if processing an ACK to the initial transaction 2xx (UAS only). */ + this.ackProcessing = false; + this.delegate = delegate; + if (initialTransaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["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`); + } + dispose() { + super.dispose(); + this._signalingState = _session__WEBPACK_IMPORTED_MODULE_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`); + } + // FIXME: Need real state machine + get sessionState() { + if (this.early) { + return _session__WEBPACK_IMPORTED_MODULE_1__["SessionState"].Early; + } + else if (this.ackWait) { + return _session__WEBPACK_IMPORTED_MODULE_1__["SessionState"].AckWait; + } + else if (this._signalingState === _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Closed) { + return _session__WEBPACK_IMPORTED_MODULE_1__["SessionState"].Terminated; + } + else { + return _session__WEBPACK_IMPORTED_MODULE_1__["SessionState"].Confirmed; + } + } + /** The state of the offer/answer exchange. */ + get signalingState() { + return this._signalingState; + } + /** The current offer. Undefined unless signaling state HaveLocalOffer, HaveRemoteOffer, of Stable. */ + get offer() { + return this._offer; + } + /** The current answer. Undefined unless signaling state Stable. */ + get answer() { + return this._answer; + } + /** Confirm the dialog. Only matters if dialog is currently early. */ + confirm() { + // When we're confirmed start the retransmitting whatever + // the 2xx final response that may have confirmed us. + if (this.early) { + this.start2xxRetransmissionTimer(); + } + super.confirm(); + } + /** Re-confirm the dialog. Only matters if handling re-INVITE request. */ + reConfirm() { + // 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. + */ + ack(options = {}) { + this.logger.log(`INVITE dialog ${this.id} sending ACK request`); + let transaction; + if (this.reinviteUserAgentClient) { + // We're sending ACK for a re-INVITE + if (!(this.reinviteUserAgentClient.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["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__WEBPACK_IMPORTED_MODULE_3__["InviteClientTransaction"])) { + throw new Error("Initial transaction not instance of InviteClientTransaction."); + } + transaction = this.initialTransaction; + } + const message = this.createOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["C"].ACK, { + cseq: transaction.request.cseq, + extraHeaders: options.extraHeaders, + body: options.body + }); + transaction.ackResponse(message); // See InviteClientTransaction for details. + this.signalingStateTransition(message); + return { 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. + */ + bye(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__WEBPACK_IMPORTED_MODULE_3__["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__WEBPACK_IMPORTED_MODULE_3__["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 _user_agents_bye_user_agent_client__WEBPACK_IMPORTED_MODULE_4__["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. + */ + info(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 _user_agents_info_user_agent_client__WEBPACK_IMPORTED_MODULE_6__["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 + */ + invite(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 _user_agents_re_invite_user_agent_client__WEBPACK_IMPORTED_MODULE_14__["ReInviteUserAgentClient"](this, delegate, options); + } + /** + * A UAC MAY associate a MESSAGE request with an existing dialog. If a + * MESSAGE request is sent within a dialog, it is "associated" with any + * media session or sessions associated with that dialog. + * https://tools.ietf.org/html/rfc3428#section-4 + * @param options - Options bucket. + */ + message(delegate, options) { + this.logger.log(`INVITE dialog ${this.id} sending MESSAGE request`); + if (this.early) { + // FIXME: TODO: This should throw a proper exception. + throw new Error("Dialog not confirmed."); + } + const message = this.createOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["C"].MESSAGE, options); + return new _user_agents_message_user_agent_client__WEBPACK_IMPORTED_MODULE_8__["MessageUserAgentClient"](this.core, message, delegate); + } + /** + * 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, 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 _user_agents_notify_user_agent_client__WEBPACK_IMPORTED_MODULE_10__["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. + */ + prack(delegate, options) { + this.logger.log(`INVITE dialog ${this.id} sending PRACK request`); + return new _user_agents_prack_user_agent_client__WEBPACK_IMPORTED_MODULE_12__["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. + */ + refer(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 _user_agents_refer_user_agent_client__WEBPACK_IMPORTED_MODULE_16__["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. + */ + receiveRequest(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__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_3__["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) { + const promiseOrVoid = this.delegate.onAck({ message }); + if (promiseOrVoid instanceof Promise) { + this.ackProcessing = true; // make sure this is always reset to false + promiseOrVoid.then(() => (this.ackProcessing = false)).catch(() => (this.ackProcessing = false)); + } + } + 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; + } + // Request within a dialog common processing. + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + super.receiveRequest(message); + // Handle various INVITE related cross-over, glare and race conditions + if (message.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE) { + // Hopefully this message is helpful... + const warning = () => { + const reason = this.ackWait ? "waiting for initial ACK" : "processing initial ACK"; + this.logger.warn(`INVITE dialog ${this.id} received re-INVITE while ${reason}`); + let msg = "RFC 5407 suggests the following to avoid this race condition... "; + msg += " Note: Implementation issues are outside the scope of this document,"; + msg += " but the following tip is provided for avoiding race conditions of"; + msg += " this type. The caller can delay sending re-INVITE F6 for some period"; + msg += " of time (2 seconds, perhaps), after which the caller can reasonably"; + msg += " assume that its ACK has been received. Implementors can decouple the"; + msg += " actions of the user (e.g., pressing the hold button) from the actions"; + msg += " of the protocol (the sending of re-INVITE F6), so that the UA can"; + msg += " behave like this. In this case, it is the implementor's choice as to"; + msg += " how long to wait. In most cases, such an implementation may be"; + msg += " useful to prevent the type of race condition shown in this section."; + msg += " This document expresses no preference about whether or not they"; + msg += " should wait for an ACK to be delivered. After considering the impact"; + msg += " on user experience, implementors should decide whether or not to wait"; + msg += " for a while, because the user experience depends on the"; + msg += " implementation and has no direct bearing on protocol behavior."; + this.logger.warn(msg); + return; // drop re-INVITE request message + }; + // 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 + const retryAfter = Math.floor(Math.random() * 10) + 1; + const extraHeaders = [`Retry-After: ${retryAfter}`]; + // There may be ONLY ONE offer/answer negotiation in progress for a + // single dialog at any point in time. Section 4 explains how to ensure + // this. + // https://tools.ietf.org/html/rfc6337#section-2.2 + if (this.ackProcessing) { + // UAS-IsI: While an INVITE server transaction is incomplete or ACK + // transaction associated with an offer/answer is incomplete, + // a UA must reject another INVITE request with a 500 + // response. + // https://tools.ietf.org/html/rfc6337#section-4.3 + this.core.replyStateless(message, { statusCode: 500, extraHeaders }); + warning(); + return; + } + // 3.1.4. Callee Receives re-INVITE (Established State) While in the + // Moratorium State (Case 1) + // https://tools.ietf.org/html/rfc5407#section-3.1.4 + // 3.1.5. Callee Receives re-INVITE (Established State) While in the + // Moratorium State (Case 2) + // https://tools.ietf.org/html/rfc5407#section-3.1.5 + if (this.ackWait && this.signalingState !== _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable) { + // This scenario is basically the same as that of Section 3.1.4, but + // differs in sending an offer in the 200 and an answer in the ACK. In + // contrast to the previous case, the offer in the 200 (F3) and the + // offer in the re-INVITE (F6) collide with each other. + // + // Bob sends a 491 to the re-INVITE (F6) since he is not able to + // properly handle a new request until he receives an answer. (Note: + // 500 with a Retry-After header may be returned if the 491 response is + // understood to indicate request collision. However, 491 is + // recommended here because 500 applies to so many cases that it is + // difficult to determine what the real problem was.) + // https://tools.ietf.org/html/rfc5407#section-3.1.5 + // UAS-IsI: While an INVITE server transaction is incomplete or ACK + // transaction associated with an offer/answer is incomplete, + // a UA must reject another INVITE request with a 500 + // response. + // https://tools.ietf.org/html/rfc6337#section-4.3 + this.core.replyStateless(message, { statusCode: 500, extraHeaders }); + warning(); + return; + } + // 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) { + this.core.replyStateless(message, { statusCode: 500, 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; + } + } + // 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__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE) { + // FIXME: parser needs to be typed... + const contact = message.parseHeader("contact"); + if (!contact) { + // TODO: Review to make sure this will never happen + throw new Error("Contact undefined."); + } + if (!(contact instanceof _messages__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_0__["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 + { + const uas = new _user_agents_bye_user_agent_server__WEBPACK_IMPORTED_MODULE_5__["ByeUserAgentServer"](this, message); + this.delegate && this.delegate.onBye ? this.delegate.onBye(uas) : uas.accept(); + this.dispose(); + } + break; + case _messages__WEBPACK_IMPORTED_MODULE_0__["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. + { + const uas = new _user_agents_info_user_agent_server__WEBPACK_IMPORTED_MODULE_7__["InfoUserAgentServer"](this, message); + this.delegate && this.delegate.onInfo + ? this.delegate.onInfo(uas) + : uas.reject({ + statusCode: 469, + extraHeaders: ["Recv-Info :"] + }); + } + break; + case _messages__WEBPACK_IMPORTED_MODULE_0__["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 + { + const uas = new _user_agents_re_invite_user_agent_server__WEBPACK_IMPORTED_MODULE_15__["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__WEBPACK_IMPORTED_MODULE_0__["C"].MESSAGE: + { + const uas = new _user_agents_message_user_agent_server__WEBPACK_IMPORTED_MODULE_9__["MessageUserAgentServer"](this.core, message); + this.delegate && this.delegate.onMessage ? this.delegate.onMessage(uas) : uas.accept(); + } + break; + case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].NOTIFY: + // https://tools.ietf.org/html/rfc3515#section-2.4.4 + { + const uas = new _user_agents_notify_user_agent_server__WEBPACK_IMPORTED_MODULE_11__["NotifyUserAgentServer"](this, message); + this.delegate && this.delegate.onNotify ? this.delegate.onNotify(uas) : uas.accept(); + } + break; + case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].PRACK: + // https://tools.ietf.org/html/rfc3262#section-4 + { + const uas = new _user_agents_prack_user_agent_server__WEBPACK_IMPORTED_MODULE_13__["PrackUserAgentServer"](this, message); + this.delegate && this.delegate.onPrack ? this.delegate.onPrack(uas) : uas.accept(); + } + break; + case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].REFER: + // https://tools.ietf.org/html/rfc3515#section-2.4.2 + { + const uas = new _user_agents_refer_user_agent_server__WEBPACK_IMPORTED_MODULE_17__["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; + } + } + /** + * Guard against out of order reliable provisional responses and retransmissions. + * Returns false if the response should be discarded, otherwise true. + * @param message - Incoming response message within this dialog. + */ + reliableSequenceGuard(message) { + const 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 + const requireHeader = message.getHeader("require"); + const rseqHeader = message.getHeader("rseq"); + const 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 + this.rseq = this.rseq ? this.rseq + 1 : rseq; + } + } + return true; + } + /** + * If not in a stable signaling state, rollback to prior stable signaling state. + */ + signalingStateRollback() { + if (this._signalingState === _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveLocalOffer || + this.signalingState === _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveRemoteOffer) { + if (this._rollbackOffer && this._rollbackAnswer) { + this._signalingState = _session__WEBPACK_IMPORTED_MODULE_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. + */ + signalingStateTransition(message) { + const body = Object(_messages__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_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__WEBPACK_IMPORTED_MODULE_0__["IncomingRequestMessage"]) { + switch (this._signalingState) { + case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Initial: + case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable: + this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveRemoteOffer; + this._offer = body; + this._answer = undefined; + break; + case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveLocalOffer: + this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable; + this._answer = body; + break; + case _session__WEBPACK_IMPORTED_MODULE_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__WEBPACK_IMPORTED_MODULE_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__WEBPACK_IMPORTED_MODULE_0__["IncomingResponseMessage"]) { + switch (this._signalingState) { + case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Initial: + case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable: + this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveRemoteOffer; + this._offer = body; + this._answer = undefined; + break; + case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveLocalOffer: + this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable; + this._answer = body; + break; + case _session__WEBPACK_IMPORTED_MODULE_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__WEBPACK_IMPORTED_MODULE_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__WEBPACK_IMPORTED_MODULE_0__["OutgoingRequestMessage"]) { + switch (this._signalingState) { + case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Initial: + case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable: + this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveLocalOffer; + this._offer = body; + this._answer = undefined; + break; + case _session__WEBPACK_IMPORTED_MODULE_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__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveRemoteOffer: + this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable; + this._answer = body; + break; + case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Closed: + break; + default: + throw new Error("Unexpected signaling state."); + } + } + // We're in UAS role, sending outgoing response with session description + if (Object(_messages__WEBPACK_IMPORTED_MODULE_0__["isBody"])(message)) { + switch (this._signalingState) { + case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Initial: + case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable: + this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveLocalOffer; + this._offer = body; + this._answer = undefined; + break; + case _session__WEBPACK_IMPORTED_MODULE_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__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveRemoteOffer: + this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable; + this._answer = body; + break; + case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Closed: + break; + default: + throw new Error("Unexpected signaling state."); + } + } + } + start2xxRetransmissionTimer() { + if (this.initialTransaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"]) { + const transaction = 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 + let timeout = _timers__WEBPACK_IMPORTED_MODULE_2__["Timers"].T1; + const retransmission = () => { + if (!this.ackWait) { + this.invite2xxTimer = undefined; + return; + } + this.logger.log("No ACK for 2xx response received, attempting retransmission"); + transaction.retransmitAcceptedResponse(); + timeout = Math.min(timeout * 2, _timers__WEBPACK_IMPORTED_MODULE_2__["Timers"].T2); + this.invite2xxTimer = setTimeout(retransmission, timeout); + }; + this.invite2xxTimer = setTimeout(retransmission, timeout); + // 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 + const stateChanged = () => { + if (transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Terminated) { + transaction.removeStateChangeListener(stateChanged); + 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.addStateChangeListener(stateChanged); + } + } + // FIXME: Refactor + startReInvite2xxRetransmissionTimer() { + if (this.reinviteUserAgentServer && this.reinviteUserAgentServer.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"]) { + const transaction = 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 + let timeout = _timers__WEBPACK_IMPORTED_MODULE_2__["Timers"].T1; + const retransmission = () => { + if (!this.reinviteUserAgentServer) { + this.invite2xxTimer = undefined; + return; + } + this.logger.log("No ACK for 2xx response received, attempting retransmission"); + transaction.retransmitAcceptedResponse(); + timeout = Math.min(timeout * 2, _timers__WEBPACK_IMPORTED_MODULE_2__["Timers"].T2); + this.invite2xxTimer = setTimeout(retransmission, timeout); + }; + this.invite2xxTimer = setTimeout(retransmission, timeout); + // 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 + const stateChanged = () => { + if (transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Terminated) { + transaction.removeStateChangeListener(stateChanged); + if (this.invite2xxTimer) { + clearTimeout(this.invite2xxTimer); + this.invite2xxTimer = undefined; + } + if (this.reinviteUserAgentServer) { + // FIXME: TODO: What to do here + } + } + }; + transaction.addStateChangeListener(stateChanged); + } + } +} + + +/***/ }), +/* 44 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _session__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(45); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionState", function() { return _session__WEBPACK_IMPORTED_MODULE_0__["SessionState"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SignalingState", function() { return _session__WEBPACK_IMPORTED_MODULE_0__["SignalingState"]; }); + +/* harmony import */ var _session_delegate__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(46); +/* empty/unused harmony star reexport */ + + + +/***/ }), +/* 45 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SessionState", function() { return SessionState; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SignalingState", function() { return SignalingState; }); +/** + * 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 || (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 || (SignalingState = {})); + + +/***/ }), +/* 46 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 47 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Timers", function() { return Timers; }); +const T1 = 500; +const T2 = 4000; +const T4 = 5000; +/** + * Timers. + * @public + */ +const Timers = { + T1, + T2, + 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 +}; + + +/***/ }), +/* 48 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _client_transaction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(49); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ClientTransaction", function() { return _client_transaction__WEBPACK_IMPORTED_MODULE_0__["ClientTransaction"]; }); + +/* harmony import */ var _invite_client_transaction__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(55); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InviteClientTransaction", function() { return _invite_client_transaction__WEBPACK_IMPORTED_MODULE_1__["InviteClientTransaction"]; }); + +/* harmony import */ var _invite_server_transaction__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(57); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InviteServerTransaction", function() { return _invite_server_transaction__WEBPACK_IMPORTED_MODULE_2__["InviteServerTransaction"]; }); + +/* harmony import */ var _non_invite_client_transaction__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(59); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NonInviteClientTransaction", function() { return _non_invite_client_transaction__WEBPACK_IMPORTED_MODULE_3__["NonInviteClientTransaction"]; }); + +/* harmony import */ var _non_invite_server_transaction__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(60); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NonInviteServerTransaction", function() { return _non_invite_server_transaction__WEBPACK_IMPORTED_MODULE_4__["NonInviteServerTransaction"]; }); + +/* empty/unused harmony star reexport *//* harmony import */ var _server_transaction__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(58); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ServerTransaction", function() { return _server_transaction__WEBPACK_IMPORTED_MODULE_5__["ServerTransaction"]; }); + +/* harmony import */ var _transaction_state__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(56); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransactionState", function() { return _transaction_state__WEBPACK_IMPORTED_MODULE_6__["TransactionState"]; }); + +/* harmony import */ var _transaction_user__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(61); +/* empty/unused harmony star reexport *//* harmony import */ var _transaction__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(50); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Transaction", function() { return _transaction__WEBPACK_IMPORTED_MODULE_8__["Transaction"]; }); + + + + + + + + + + + + + +/***/ }), +/* 49 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ClientTransaction", function() { return ClientTransaction; }); +/* harmony import */ var _transaction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(50); + +/** + * 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 + */ +class ClientTransaction extends _transaction__WEBPACK_IMPORTED_MODULE_0__["Transaction"] { + constructor(_request, transport, user, state, loggerCategory) { + super(transport, user, ClientTransaction.makeId(_request), state, loggerCategory); + 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 + _request.setViaHeader(this.id, transport.protocol); + } + static makeId(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); + } + } + /** The outgoing request the transaction handling. */ + get request() { + return this._request; + } + /** + * 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 + */ + onRequestTimeout() { + if (this.user.onRequestTimeout) { + this.user.onRequestTimeout(); + } + } +} + + +/***/ }), +/* 50 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Transaction", function() { return Transaction; }); +/* harmony import */ var _exceptions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(51); + +/** + * 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 + */ +class Transaction { + constructor(_transport, _user, _id, _state, loggerCategory) { + this._transport = _transport; + this._user = _user; + this._id = _id; + this._state = _state; + this.listeners = new Array(); + this.logger = _user.loggerFactory.getLogger(loggerCategory, _id); + this.logger.debug(`Constructing ${this.typeToString()} with id ${this.id}.`); + } + /** + * 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() { + this.logger.debug(`Destroyed ${this.typeToString()} with id ${this.id}.`); + } + /** Transaction id. */ + get id() { + return this._id; + } + /** Transaction kind. Deprecated. */ + get kind() { + throw new Error("Invalid kind."); + } + /** Transaction state. */ + get state() { + return this._state; + } + /** Transaction transport. */ + get transport() { + return this._transport; + } + /** + * Sets up a function that will be called whenever the transaction state changes. + * @param listener - Callback function. + * @param options - An options object that specifies characteristics about the listener. + * If once true, indicates that the listener should be invoked at most once after being added. + * If once true, the listener would be automatically removed when invoked. + */ + addStateChangeListener(listener, options) { + const onceWrapper = () => { + this.removeStateChangeListener(onceWrapper); + listener(); + }; + (options === null || options === void 0 ? void 0 : options.once) === true ? this.listeners.push(onceWrapper) : this.listeners.push(listener); + } + /** + * This is currently public so tests may spy on it. + * @internal + */ + notifyStateChangeListeners() { + this.listeners.slice().forEach((listener) => listener()); + } + /** + * Removes a listener previously registered with addStateListener. + * @param listener - Callback function. + */ + removeStateChangeListener(listener) { + this.listeners = this.listeners.filter((l) => l !== listener); + } + logTransportError(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. + */ + send(message) { + return this.transport.send(message).catch((error) => { + // If the transport rejects, it SHOULD reject with a TransportError. + // But the transport may be external code, so we are careful + // make sure we convert it to a TransportError if need be. + if (error instanceof _exceptions__WEBPACK_IMPORTED_MODULE_0__["TransportError"]) { + this.onTransportError(error); + throw error; + } + let transportError; + if (error && typeof error.message === "string") { + transportError = new _exceptions__WEBPACK_IMPORTED_MODULE_0__["TransportError"](error.message); + } + else { + transportError = new _exceptions__WEBPACK_IMPORTED_MODULE_0__["TransportError"](); + } + this.onTransportError(transportError); + throw transportError; + }); + } + setState(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.notifyStateChangeListeners(); + } + typeToString() { + return "UnknownType"; + } +} + + +/***/ }), +/* 51 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _exception__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(52); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Exception", function() { return _exception__WEBPACK_IMPORTED_MODULE_0__["Exception"]; }); + +/* harmony import */ var _transaction_state_error__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(53); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransactionStateError", function() { return _transaction_state_error__WEBPACK_IMPORTED_MODULE_1__["TransactionStateError"]; }); + +/* harmony import */ var _transport_error__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(54); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransportError", function() { return _transport_error__WEBPACK_IMPORTED_MODULE_2__["TransportError"]; }); + + + + + + +/***/ }), +/* 52 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Exception", function() { return Exception; }); +/** + * 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 + */ +class Exception extends Error { + constructor(message) { + super(message); // 'Error' breaks prototype chain here + Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain + } +} + + +/***/ }), +/* 53 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TransactionStateError", function() { return TransactionStateError; }); +/* harmony import */ var _exception__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(52); + +/** + * Indicates that the operation could not be completed given the current transaction state. + * @public + */ +class TransactionStateError extends _exception__WEBPACK_IMPORTED_MODULE_0__["Exception"] { + constructor(message) { + super(message ? message : "Transaction state error."); + } +} + + +/***/ }), +/* 54 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TransportError", function() { return TransportError; }); +/* harmony import */ var _exception__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(52); + +/** + * Transport error. + * @public + */ +class TransportError extends _exception__WEBPACK_IMPORTED_MODULE_0__["Exception"] { + constructor(message) { + super(message ? message : "Unspecified transport error."); + } +} + + +/***/ }), +/* 55 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InviteClientTransaction", function() { return InviteClientTransaction; }); +/* harmony import */ var _timers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(47); +/* harmony import */ var _client_transaction__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(49); +/* harmony import */ var _transaction_state__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(56); + + + +/** + * 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 + */ +class InviteClientTransaction extends _client_transaction__WEBPACK_IMPORTED_MODULE_1__["ClientTransaction"] { + /** + * 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, transport, user) { + super(request, transport, user, _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Calling, "sip.transaction.ict"); + /** + * 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(() => this.timerB(), _timers__WEBPACK_IMPORTED_MODULE_0__["Timers"].TIMER_B); + this.send(request.toString()).catch((error) => { + this.logTransportError(error, "Failed to send initial outgoing request."); + }); + } + /** + * Destructor. + */ + dispose() { + 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.dispose(); + } + /** Transaction kind. Deprecated. */ + get kind() { + return "ict"; + } + /** + * 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) { + const toTag = ack.toTag; + if (!toTag) { + throw new Error("To tag undefined."); + } + const id = "z9hG4bK" + Math.floor(Math.random() * 10000000); + ack.setViaHeader(id, this.transport.protocol); + this.ackRetransmissionCache.set(toTag, ack); // Add to ACK retransmission cache + this.send(ack.toString()).catch((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. + */ + receiveResponse(response) { + const statusCode = response.statusCode; + if (!statusCode || statusCode < 100 || statusCode > 699) { + throw new Error(`Invalid status code ${statusCode}`); + } + switch (this.state) { + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed); + this.ack(response); + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed); + this.ack(response); + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["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. + const ack = this.ackRetransmissionCache.get(response.toTag); + if (ack) { + this.send(ack.toString()).catch((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__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_2__["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 + const 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. + */ + onTransportError(error) { + if (this.user.onTransportError) { + this.user.onTransportError(error); + } + this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated, true); + } + /** For logging. */ + typeToString() { + return "INVITE client transaction"; + } + ack(response) { + // 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 + const ruri = this.request.ruri; + const callId = this.request.callId; + const cseq = this.request.cseq; + const from = this.request.getHeader("from"); + const to = response.getHeader("to"); + const via = this.request.getHeader("via"); + const 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."); + } + let 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((error) => { + this.logTransportError(error, "Failed to send ACK to non-2xx response."); + }); + return; + } + /** + * Execute a state transition. + * @param newState - New state. + */ + stateTransition(newState, dueToTransportError = false) { + // Assert valid state transitions. + const invalidStateTransition = () => { + throw new Error(`Invalid state transition from ${this.state} to ${newState}`); + }; + switch (newState) { + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Calling: + invalidStateTransition(); + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding: + if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Calling) { + invalidStateTransition(); + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Accepted: + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed: + if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Calling && this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding) { + invalidStateTransition(); + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated: + if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Calling && + this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Accepted && + this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed) { + this.D = setTimeout(() => this.timerD(), _timers__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Accepted) { + this.M = setTimeout(() => this.timerM(), _timers__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_2__["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 + */ + timerA() { + // 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 + */ + timerB() { + this.logger.debug(`Timer B expired for INVITE client transaction ${this.id}.`); + if (this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Calling) { + this.onRequestTimeout(); + this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["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 + */ + timerD() { + this.logger.debug(`Timer D expired for INVITE client transaction ${this.id}.`); + if (this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed) { + this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["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 + */ + timerM() { + this.logger.debug(`Timer M expired for INVITE client transaction ${this.id}.`); + if (this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Accepted) { + this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated); + } + } +} + + +/***/ }), +/* 56 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TransactionState", function() { return TransactionState; }); +/** + * 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 || (TransactionState = {})); + + +/***/ }), +/* 57 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InviteServerTransaction", function() { return InviteServerTransaction; }); +/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); +/* harmony import */ var _timers__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(47); +/* harmony import */ var _server_transaction__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(58); +/* harmony import */ var _transaction_state__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(56); + + + + +/** + * INVITE Server Transaction. + * @remarks + * https://tools.ietf.org/html/rfc3261#section-17.2.1 + * @public + */ +class InviteServerTransaction extends _server_transaction__WEBPACK_IMPORTED_MODULE_2__["ServerTransaction"] { + /** + * 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, transport, user) { + super(request, transport, user, _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding, "sip.transaction.ist"); + } + /** + * Destructor. + */ + dispose() { + 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.dispose(); + } + /** Transaction kind. Deprecated. */ + get kind() { + return "ist"; + } + /** + * Receive requests from transport matching this transaction. + * @param request - Request matching this transaction. + */ + receiveRequest(request) { + switch (this.state) { + case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["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__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE) { + if (this.lastProvisionalResponse) { + this.send(this.lastProvisionalResponse).catch((error) => { + this.logTransportError(error, "Failed to send retransmission of provisional response."); + }); + } + return; + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["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__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE) { + return; + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["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__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE) { + if (!this.lastFinalResponse) { + throw new Error("Last final response undefined."); + } + this.send(this.lastFinalResponse).catch((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__WEBPACK_IMPORTED_MODULE_0__["C"].ACK) { + this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Confirmed); + return; + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["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__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE || request.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].ACK) { + return; + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Terminated: + // For good measure absorb any additional messages that arrive (should not happen). + if (request.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE || request.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].ACK) { + return; + } + break; + default: + throw new Error(`Invalid state ${this.state}`); + } + const 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. + */ + receiveResponse(statusCode, response) { + if (statusCode < 100 || statusCode > 699) { + throw new Error(`Invalid status code ${statusCode}`); + } + switch (this.state) { + case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["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((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__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Accepted); + this.send(response).catch((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__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Completed); + this.send(response).catch((error) => { + this.logTransportError(error, "Failed to send non-2xx final response."); + }); + return; + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["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((error) => { + this.logTransportError(error, "Failed to send 2xx response."); + }); + return; + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Completed: + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Confirmed: + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Terminated: + break; + default: + throw new Error(`Invalid state ${this.state}`); + } + const 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. + */ + retransmitAcceptedResponse() { + if (this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Accepted && this.lastFinalResponse) { + this.send(this.lastFinalResponse).catch((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 + */ + onTransportError(error) { + if (this.user.onTransportError) { + this.user.onTransportError(error); + } + } + /** For logging. */ + typeToString() { + return "INVITE server transaction"; + } + /** + * Execute a state transition. + * @param newState - New state. + */ + stateTransition(newState) { + // Assert valid state transitions. + const invalidStateTransition = () => { + throw new Error(`Invalid state transition from ${this.state} to ${newState}`); + }; + switch (newState) { + case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding: + invalidStateTransition(); + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Accepted: + case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Completed: + if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding) { + invalidStateTransition(); + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Confirmed: + if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Completed) { + invalidStateTransition(); + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Terminated: + if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Accepted && + this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Completed && + this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Confirmed) { + invalidStateTransition(); + } + break; + default: + invalidStateTransition(); + } + // On any state transition, stop resending provisional 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__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Accepted) { + this.L = setTimeout(() => this.timerL(), _timers__WEBPACK_IMPORTED_MODULE_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__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Completed) { + // FIXME: Missing timer G for unreliable transports. + this.H = setTimeout(() => this.timerH(), _timers__WEBPACK_IMPORTED_MODULE_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__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Confirmed) { + // FIXME: This timer is not getting set correctly for unreliable transports. + this.I = setTimeout(() => this.timerI(), _timers__WEBPACK_IMPORTED_MODULE_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__WEBPACK_IMPORTED_MODULE_3__["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. + */ + startProgressExtensionTimer() { + // Start the progress extension timer only for the first non-100 provisional response. + if (this.progressExtensionTimer === undefined) { + this.progressExtensionTimer = setInterval(() => { + 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((error) => { + this.logTransportError(error, "Failed to send retransmission of provisional response."); + }); + }, _timers__WEBPACK_IMPORTED_MODULE_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. + */ + stopProgressExtensionTimer() { + 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 + */ + timerG() { + // 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 + */ + timerH() { + this.logger.debug(`Timer H expired for INVITE server transaction ${this.id}.`); + if (this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Completed) { + this.logger.warn("ACK to negative final response was never received, terminating transaction."); + this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Terminated); + } + } + /** + * Once timer I fires, the server MUST transition to the "Terminated" state. + * https://tools.ietf.org/html/rfc3261#section-17.2.1 + */ + timerI() { + this.logger.debug(`Timer I expired for INVITE server transaction ${this.id}.`); + this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_3__["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 + */ + timerL() { + this.logger.debug(`Timer L expired for INVITE server transaction ${this.id}.`); + if (this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Accepted) { + this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Terminated); + } + } +} + + +/***/ }), +/* 58 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ServerTransaction", function() { return ServerTransaction; }); +/* harmony import */ var _transaction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(50); + +/** + * 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 + */ +class ServerTransaction extends _transaction__WEBPACK_IMPORTED_MODULE_0__["Transaction"] { + constructor(_request, transport, user, state, loggerCategory) { + super(transport, user, _request.viaBranch, state, loggerCategory); + this._request = _request; + this.user = user; + } + /** The incoming request the transaction handling. */ + get request() { + return this._request; + } +} + + +/***/ }), +/* 59 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NonInviteClientTransaction", function() { return NonInviteClientTransaction; }); +/* harmony import */ var _timers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(47); +/* harmony import */ var _client_transaction__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(49); +/* harmony import */ var _transaction_state__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(56); + + + +/** + * 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 + */ +class NonInviteClientTransaction extends _client_transaction__WEBPACK_IMPORTED_MODULE_1__["ClientTransaction"] { + /** + * 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, transport, user) { + super(request, transport, user, _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying, "sip.transaction.nict"); + // 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(() => this.timerF(), _timers__WEBPACK_IMPORTED_MODULE_0__["Timers"].TIMER_F); + this.send(request.toString()).catch((error) => { + this.logTransportError(error, "Failed to send initial outgoing request."); + }); + } + /** + * Destructor. + */ + dispose() { + if (this.F) { + clearTimeout(this.F); + this.F = undefined; + } + if (this.K) { + clearTimeout(this.K); + this.K = undefined; + } + super.dispose(); + } + /** Transaction kind. Deprecated. */ + get kind() { + return "nict"; + } + /** + * Handler for incoming responses from the transport which match this transaction. + * @param response - The incoming response. + */ + receiveResponse(response) { + const statusCode = response.statusCode; + if (!statusCode || statusCode < 100 || statusCode > 699) { + throw new Error(`Invalid status code ${statusCode}`); + } + switch (this.state) { + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed); + if (statusCode === 408) { + this.onRequestTimeout(); + return; + } + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed); + if (statusCode === 408) { + this.onRequestTimeout(); + return; + } + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated: + // For good measure just absorb additional response retransmissions. + return; + default: + throw new Error(`Invalid state ${this.state}`); + } + const 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 fail over mechanisms described in [4]. + * https://tools.ietf.org/html/rfc3261#section-17.1.4 + * @param error - Transport error + */ + onTransportError(error) { + if (this.user.onTransportError) { + this.user.onTransportError(error); + } + this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated, true); + } + /** For logging. */ + typeToString() { + return "non-INVITE client transaction"; + } + /** + * Execute a state transition. + * @param newState - New state. + */ + stateTransition(newState, dueToTransportError = false) { + // Assert valid state transitions. + const invalidStateTransition = () => { + throw new Error(`Invalid state transition from ${this.state} to ${newState}`); + }; + switch (newState) { + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying: + invalidStateTransition(); + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding: + if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying) { + invalidStateTransition(); + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed: + if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying && this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding) { + invalidStateTransition(); + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated: + if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying && + this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding && + this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed) { + if (this.F) { + clearTimeout(this.F); + this.F = undefined; + } + this.K = setTimeout(() => this.timerK(), _timers__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_2__["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 + */ + timerF() { + this.logger.debug(`Timer F expired for non-INVITE client transaction ${this.id}.`); + if (this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying || this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding) { + this.onRequestTimeout(); + this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["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 + */ + timerK() { + if (this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed) { + this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated); + } + } +} + + +/***/ }), +/* 60 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NonInviteServerTransaction", function() { return NonInviteServerTransaction; }); +/* harmony import */ var _timers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(47); +/* harmony import */ var _server_transaction__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(58); +/* harmony import */ var _transaction_state__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(56); + + + +/** + * Non-INVITE Server Transaction. + * @remarks + * https://tools.ietf.org/html/rfc3261#section-17.2.2 + * @public + */ +class NonInviteServerTransaction extends _server_transaction__WEBPACK_IMPORTED_MODULE_1__["ServerTransaction"] { + /** + * 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, transport, user) { + super(request, transport, user, _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying, "sip.transaction.nist"); + } + /** + * Destructor. + */ + dispose() { + if (this.J) { + clearTimeout(this.J); + this.J = undefined; + } + super.dispose(); + } + /** Transaction kind. Deprecated. */ + get kind() { + return "nist"; + } + /** + * Receive requests from transport matching this transaction. + * @param request - Request matching this transaction. + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + receiveRequest(request) { + switch (this.state) { + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_2__["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((error) => { + this.logTransportError(error, "Failed to send retransmission of provisional response."); + }); + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["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((error) => { + this.logTransportError(error, "Failed to send retransmission of final response."); + }); + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated: + break; + default: + throw new Error(`Invalid state ${this.state}`); + } + } + /** + * Receive responses from TU for this transaction. + * @param statusCode - Status code of response. 101-199 not allowed per RFC 4320. + * @param response - Response to send. + */ + receiveResponse(statusCode, response) { + 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__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding); + this.send(response).catch((error) => { + this.logTransportError(error, "Failed to send provisional response."); + }); + return; + } + if (statusCode >= 200 && statusCode <= 699) { + this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed); + this.send(response).catch((error) => { + this.logTransportError(error, "Failed to send final response."); + }); + return; + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed); + this.send(response).catch((error) => { + this.logTransportError(error, "Failed to send final response."); + }); + return; + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated: + break; + default: + throw new Error(`Invalid state ${this.state}`); + } + const 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 + */ + onTransportError(error) { + if (this.user.onTransportError) { + this.user.onTransportError(error); + } + this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated, true); + } + /** For logging. */ + typeToString() { + return "non-INVITE server transaction"; + } + stateTransition(newState, dueToTransportError = false) { + // Assert valid state transitions. + const invalidStateTransition = () => { + throw new Error(`Invalid state transition from ${this.state} to ${newState}`); + }; + switch (newState) { + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying: + invalidStateTransition(); + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding: + if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying) { + invalidStateTransition(); + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed: + if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying && this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding) { + invalidStateTransition(); + } + break; + case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated: + if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding && this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed) { + this.J = setTimeout(() => this.timerJ(), _timers__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_2__["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 + */ + timerJ() { + this.logger.debug(`Timer J expired for NON-INVITE server transaction ${this.id}.`); + if (this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed) { + this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated); + } + } +} + + +/***/ }), +/* 61 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 62 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ByeUserAgentClient", function() { return ByeUserAgentClient; }); +/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48); +/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(63); + + + +/** + * BYE UAC. + * @public + */ +class ByeUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_2__["UserAgentClient"] { + constructor(dialog, delegate, options) { + const message = dialog.createOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["C"].BYE, options); + super(_transactions__WEBPACK_IMPORTED_MODULE_1__["NonInviteClientTransaction"], dialog.userAgentCore, message, delegate); + dialog.dispose(); + } +} + + +/***/ }), +/* 63 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UserAgentClient", function() { return UserAgentClient; }); +/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48); + + +/** + * 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 + */ +class UserAgentClient { + constructor(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(); + } + dispose() { + this.transaction.dispose(); + } + get loggerFactory() { + return this.core.loggerFactory; + } + /** The transaction associated with this request. */ + get transaction() { + if (!this._transaction) { + throw new Error("Transaction undefined."); + } + return this._transaction; + } + /** + * 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, 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 + const message = this.core.makeOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_1__["TransactionState"].Proceeding) { + new UserAgentClient(_transactions__WEBPACK_IMPORTED_MODULE_1__["NonInviteClientTransaction"], this.core, message); + } + else { + this.transaction.addStateChangeListener(() => { + if (this.transaction && this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_1__["TransactionState"].Proceeding) { + new UserAgentClient(_transactions__WEBPACK_IMPORTED_MODULE_1__["NonInviteClientTransaction"], this.core, message); + } + }, { once: true }); + } + 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. + * @param dialog - If defined, the dialog within which the response was received. + * @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. + */ + authenticationGuard(message, dialog) { + const 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. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let challenge; + let 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; + } + // If response to out of dialog request, assume incrementing the CSeq will suffice. + let cseq = (this.message.cseq += 1); + // If response to in dialog request, get a valid next CSeq number. + if (dialog && dialog.localSequenceNumber) { + dialog.incrementLocalSequenceNumber(); + cseq = this.message.cseq = dialog.localSequenceNumber; + } + 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; + } + /** + * 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 + */ + onRequestTimeout() { + this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout."); + const message = new _messages__WEBPACK_IMPORTED_MODULE_0__["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 + * @param error - Transport error + */ + onTransportError(error) { + this.logger.error(error.message); + this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable."); + const message = new _messages__WEBPACK_IMPORTED_MODULE_0__["IncomingResponseMessage"](); + message.statusCode = 503; + message.reasonPhrase = "Service Unavailable"; + this.receiveResponse(message); + } + /** + * Receive a response from the transaction layer. + * @param message - Incoming response message. + */ + receiveResponse(message) { + if (!this.authenticationGuard(message)) { + return; + } + const 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 }); + } + break; + case /^1[0-9]{2}$/.test(statusCode): + if (this.delegate && this.delegate.onProgress) { + this.delegate.onProgress({ message }); + } + break; + case /^2[0-9]{2}$/.test(statusCode): + if (this.delegate && this.delegate.onAccept) { + this.delegate.onAccept({ message }); + } + break; + case /^3[0-9]{2}$/.test(statusCode): + if (this.delegate && this.delegate.onRedirect) { + this.delegate.onRedirect({ message }); + } + break; + case /^[4-6][0-9]{2}$/.test(statusCode): + if (this.delegate && this.delegate.onReject) { + this.delegate.onReject({ message }); + } + break; + default: + throw new Error(`Invalid status code ${statusCode}`); + } + } + init() { + // We are the transaction user. + const user = { + loggerFactory: this.loggerFactory, + onRequestTimeout: () => this.onRequestTimeout(), + onStateChange: (newState) => { + if (newState === _transactions__WEBPACK_IMPORTED_MODULE_1__["TransactionState"].Terminated) { + // Remove the terminated transaction from the core. + // eslint-disable-next-line @typescript-eslint/no-use-before-define + 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. + // eslint-disable-next-line @typescript-eslint/no-use-before-define + if (transaction === this._transaction) { + this.dispose(); + } + } + }, + onTransportError: (error) => this.onTransportError(error), + receiveResponse: (message) => this.receiveResponse(message) + }; + // Create a new transaction with us as the user. + const transaction = new this.transactionConstructor(this.message, this.core.transport, user); + this._transaction = transaction; + // Add the new transaction to the core. + const userAgentClientId = transaction.id + transaction.request.method; + this.core.userAgentClients.set(userAgentClientId, this); + } +} + + +/***/ }), +/* 64 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ByeUserAgentServer", function() { return ByeUserAgentServer; }); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); +/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); + + +/** + * BYE UAS. + * @public + */ +class ByeUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { + constructor(dialog, message, delegate) { + super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteServerTransaction"], dialog.userAgentCore, message, delegate); + } +} + + +/***/ }), +/* 65 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UserAgentServer", function() { return UserAgentServer; }); +/* harmony import */ var _exceptions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(51); +/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8); +/* harmony import */ var _messages_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(32); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(48); + + + + +/** + * 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 + */ +class UserAgentServer { + constructor(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 : Object(_messages_utils__WEBPACK_IMPORTED_MODULE_2__["newTag"])(); + this.init(); + } + dispose() { + this.transaction.dispose(); + } + get loggerFactory() { + return this.core.loggerFactory; + } + /** The transaction associated with this request. */ + get transaction() { + if (!this._transaction) { + throw new Error("Transaction undefined."); + } + return this._transaction; + } + accept(options = { statusCode: 200 }) { + if (!this.acceptable) { + throw new _exceptions__WEBPACK_IMPORTED_MODULE_0__["TransactionStateError"](`${this.message.method} not acceptable in state ${this.transaction.state}.`); + } + const statusCode = options.statusCode; + if (statusCode < 200 || statusCode > 299) { + throw new TypeError(`Invalid statusCode: ${statusCode}`); + } + const response = this.reply(options); + return response; + } + progress(options = { statusCode: 180 }) { + if (!this.progressable) { + throw new _exceptions__WEBPACK_IMPORTED_MODULE_0__["TransactionStateError"](`${this.message.method} not progressable in state ${this.transaction.state}.`); + } + const statusCode = options.statusCode; + if (statusCode < 101 || statusCode > 199) { + throw new TypeError(`Invalid statusCode: ${statusCode}`); + } + const response = this.reply(options); + return response; + } + redirect(contacts, options = { statusCode: 302 }) { + if (!this.redirectable) { + throw new _exceptions__WEBPACK_IMPORTED_MODULE_0__["TransactionStateError"](`${this.message.method} not redirectable in state ${this.transaction.state}.`); + } + const statusCode = options.statusCode; + if (statusCode < 300 || statusCode > 399) { + throw new TypeError(`Invalid statusCode: ${statusCode}`); + } + const contactHeaders = new Array(); + contacts.forEach((contact) => contactHeaders.push(`Contact: ${contact.toString()}`)); + options.extraHeaders = (options.extraHeaders || []).concat(contactHeaders); + const response = this.reply(options); + return response; + } + reject(options = { statusCode: 480 }) { + if (!this.rejectable) { + throw new _exceptions__WEBPACK_IMPORTED_MODULE_0__["TransactionStateError"](`${this.message.method} not rejectable in state ${this.transaction.state}.`); + } + const statusCode = options.statusCode; + if (statusCode < 400 || statusCode > 699) { + throw new TypeError(`Invalid statusCode: ${statusCode}`); + } + const response = this.reply(options); + return response; + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + trying(options) { + if (!this.tryingable) { + throw new _exceptions__WEBPACK_IMPORTED_MODULE_0__["TransactionStateError"](`${this.message.method} not tryingable in state ${this.transaction.state}.`); + } + const 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. + */ + receiveCancel(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); + } + } + get acceptable() { + if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"]) { + return (this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding || this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Accepted); + } + if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["NonInviteServerTransaction"]) { + return (this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Trying || this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding); + } + throw new Error("Unknown transaction type."); + } + get progressable() { + if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"]) { + return this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding; + } + if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["NonInviteServerTransaction"]) { + return false; // https://tools.ietf.org/html/rfc4320#section-4.1 + } + throw new Error("Unknown transaction type."); + } + get redirectable() { + if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"]) { + return this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding; + } + if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["NonInviteServerTransaction"]) { + return (this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Trying || this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding); + } + throw new Error("Unknown transaction type."); + } + get rejectable() { + if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"]) { + return this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding; + } + if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["NonInviteServerTransaction"]) { + return (this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Trying || this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding); + } + throw new Error("Unknown transaction type."); + } + get tryingable() { + if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"]) { + return this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding; + } + if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["NonInviteServerTransaction"]) { + return this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Trying; + } + throw new Error("Unknown transaction type."); + } + /** + * 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. + */ + reply(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; + const response = Object(_messages__WEBPACK_IMPORTED_MODULE_1__["constructOutgoingResponse"])(this.message, options); + this.transaction.receiveResponse(options.statusCode, response.message); + return response; + } + init() { + // We are the transaction user. + const user = { + loggerFactory: this.loggerFactory, + onStateChange: (newState) => { + if (newState === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Terminated) { + // Remove the terminated transaction from the core. + // eslint-disable-next-line @typescript-eslint/no-use-before-define + this.core.userAgentServers.delete(userAgentServerId); + this.dispose(); + } + }, + onTransportError: (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. + const transaction = new this.transactionConstructor(this.message, this.core.transport, user); + this._transaction = transaction; + // Add the new transaction to the core. + const userAgentServerId = transaction.id; + this.core.userAgentServers.set(transaction.id, this); + } +} + + +/***/ }), +/* 66 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InfoUserAgentClient", function() { return InfoUserAgentClient; }); +/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48); +/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(63); + + + +/** + * INFO UAC. + * @public + */ +class InfoUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_2__["UserAgentClient"] { + constructor(dialog, delegate, options) { + const message = dialog.createOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["C"].INFO, options); + super(_transactions__WEBPACK_IMPORTED_MODULE_1__["NonInviteClientTransaction"], dialog.userAgentCore, message, delegate); + } +} + + +/***/ }), +/* 67 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InfoUserAgentServer", function() { return InfoUserAgentServer; }); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); +/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); + + +/** + * INFO UAS. + * @public + */ +class InfoUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { + constructor(dialog, message, delegate) { + super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteServerTransaction"], dialog.userAgentCore, message, delegate); + } +} + + +/***/ }), +/* 68 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MessageUserAgentClient", function() { return MessageUserAgentClient; }); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); +/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(63); + + +/** + * MESSAGE UAC. + * @public + */ +class MessageUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_1__["UserAgentClient"] { + constructor(core, message, delegate) { + super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteClientTransaction"], core, message, delegate); + } +} + + +/***/ }), +/* 69 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MessageUserAgentServer", function() { return MessageUserAgentServer; }); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); +/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); + + +/** + * MESSAGE UAS. + * @public + */ +class MessageUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { + constructor(core, message, delegate) { + super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteServerTransaction"], core, message, delegate); + } +} + + +/***/ }), +/* 70 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NotifyUserAgentClient", function() { return NotifyUserAgentClient; }); +/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48); +/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(63); + + + +/** + * NOTIFY UAS. + * @public + */ +class NotifyUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_2__["UserAgentClient"] { + constructor(dialog, delegate, options) { + const message = dialog.createOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["C"].NOTIFY, options); + super(_transactions__WEBPACK_IMPORTED_MODULE_1__["NonInviteClientTransaction"], dialog.userAgentCore, message, delegate); + } +} + + +/***/ }), +/* 71 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NotifyUserAgentServer", function() { return NotifyUserAgentServer; }); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); +/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); + + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function instanceOfDialog(object) { + return object.userAgentCore !== undefined; +} +/** + * NOTIFY UAS. + * @public + */ +class NotifyUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { + /** + * 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, message, delegate) { + const userAgentCore = instanceOfDialog(dialogOrCore) ? dialogOrCore.userAgentCore : dialogOrCore; + super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteServerTransaction"], userAgentCore, message, delegate); + } +} + + +/***/ }), +/* 72 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PrackUserAgentClient", function() { return PrackUserAgentClient; }); +/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48); +/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(63); + + + +/** + * PRACK UAC. + * @public + */ +class PrackUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_2__["UserAgentClient"] { + constructor(dialog, delegate, options) { + const message = dialog.createOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["C"].PRACK, options); + super(_transactions__WEBPACK_IMPORTED_MODULE_1__["NonInviteClientTransaction"], dialog.userAgentCore, message, delegate); + dialog.signalingStateTransition(message); + } +} + + +/***/ }), +/* 73 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PrackUserAgentServer", function() { return PrackUserAgentServer; }); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); +/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); + + +/** + * PRACK UAS. + * @public + */ +class PrackUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { + constructor(dialog, message, delegate) { + super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteServerTransaction"], dialog.userAgentCore, message, delegate); + // Update dialog signaling state with offer/answer in body + dialog.signalingStateTransition(message); + this.dialog = dialog; + } + /** + * Update the dialog signaling state on a 2xx response. + * @param options - Options bucket. + */ + accept(options = { statusCode: 200 }) { + if (options.body) { + // Update dialog signaling state with offer/answer in body + this.dialog.signalingStateTransition(options.body); + } + return super.accept(options); + } +} + + +/***/ }), +/* 74 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReInviteUserAgentClient", function() { return ReInviteUserAgentClient; }); +/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48); +/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(63); + + + +/** + * 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 + */ +class ReInviteUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_2__["UserAgentClient"] { + constructor(dialog, delegate, options) { + const message = dialog.createOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE, options); + super(_transactions__WEBPACK_IMPORTED_MODULE_1__["InviteClientTransaction"], dialog.userAgentCore, message, delegate); + 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; + } + receiveResponse(message) { + if (!this.authenticationGuard(message, this.dialog)) { + return; + } + const 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 }); + } + break; + case /^1[0-9]{2}$/.test(statusCode): + if (this.delegate && this.delegate.onProgress) { + this.delegate.onProgress({ + message, + session: this.dialog, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + prack: (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, + session: this.dialog, + ack: (options) => { + const 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 }); + } + 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 }); + } + 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}`); + } + } +} + + +/***/ }), +/* 75 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReInviteUserAgentServer", function() { return ReInviteUserAgentServer; }); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); +/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); + + +/** + * 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 + */ +class ReInviteUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { + constructor(dialog, message, delegate) { + super(_transactions__WEBPACK_IMPORTED_MODULE_0__["InviteServerTransaction"], dialog.userAgentCore, message, delegate); + dialog.reinviteUserAgentServer = this; + this.dialog = dialog; + } + /** + * Update the dialog signaling state on a 2xx response. + * @param options - Options bucket. + */ + accept(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((route) => `Record-Route: ${route}`)); + // Send and return the response + const response = super.accept(options); + const session = this.dialog; + const result = Object.assign(Object.assign({}, response), { 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. + */ + progress(options = { statusCode: 180 }) { + // Send and return the response + const response = super.progress(options); + const session = this.dialog; + const result = Object.assign(Object.assign({}, response), { 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. + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + redirect(contacts, 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. + */ + reject(options = { statusCode: 488 }) { + this.dialog.signalingStateRollback(); + this.dialog.reinviteUserAgentServer = undefined; // ACK will be handled by transaction + return super.reject(options); + } +} + + +/***/ }), +/* 76 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReferUserAgentClient", function() { return ReferUserAgentClient; }); +/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48); +/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(63); + + + +/** + * REFER UAC. + * @public + */ +class ReferUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_2__["UserAgentClient"] { + constructor(dialog, delegate, options) { + const message = dialog.createOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["C"].REFER, options); + super(_transactions__WEBPACK_IMPORTED_MODULE_1__["NonInviteClientTransaction"], dialog.userAgentCore, message, delegate); + } +} + + +/***/ }), +/* 77 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReferUserAgentServer", function() { return ReferUserAgentServer; }); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); +/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); + + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function instanceOfSessionDialog(object) { + return object.userAgentCore !== undefined; +} +/** + * REFER UAS. + * @public + */ +class ReferUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { + /** + * REFER UAS constructor. + * @param dialogOrCore - Dialog for in dialog REFER, UserAgentCore for out of dialog REFER. + * @param message - Incoming REFER request message. + */ + constructor(dialogOrCore, message, delegate) { + const userAgentCore = instanceOfSessionDialog(dialogOrCore) ? dialogOrCore.userAgentCore : dialogOrCore; + super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteServerTransaction"], userAgentCore, message, delegate); + } +} + + +/***/ }), +/* 78 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubscriptionDialog", function() { return SubscriptionDialog; }); +/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); +/* harmony import */ var _subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(79); +/* harmony import */ var _timers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(47); +/* harmony import */ var _user_agent_core_allowed_methods__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(82); +/* harmony import */ var _user_agents_notify_user_agent_server__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(71); +/* harmony import */ var _user_agents_re_subscribe_user_agent_client__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(83); +/* harmony import */ var _dialog__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(7); + + + + + + + +/** + * 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 + */ +class SubscriptionDialog extends _dialog__WEBPACK_IMPORTED_MODULE_6__["Dialog"] { + constructor(subscriptionEvent, subscriptionExpires, subscriptionState, core, state, delegate) { + super(core, state); + 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`); + } + /** + * 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, 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 + const 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 + const routeSet = incomingNotifyRequestMessage.getHeaders("record-route"); + const contact = incomingNotifyRequestMessage.parseHeader("contact"); + if (!contact) { + // TODO: Review to make sure this will never happen + throw new Error("Contact undefined."); + } + if (!(contact instanceof _messages__WEBPACK_IMPORTED_MODULE_0__["NameAddrHeader"])) { + throw new Error("Contact not instance of NameAddrHeader."); + } + const 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 + const localSequenceNumber = outgoingSubscribeRequestMessage.cseq; + const remoteSequenceNumber = undefined; + const callId = outgoingSubscribeRequestMessage.callId; + const localTag = outgoingSubscribeRequestMessage.fromTag; + const 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."); + } + const localURI = outgoingSubscribeRequestMessage.from.uri; + const 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 + const early = false; + const dialogState = { + id: callId + localTag + remoteTag, + early, + callId, + localTag, + remoteTag, + localSequenceNumber, + remoteSequenceNumber, + localURI, + remoteURI, + remoteTarget, + routeSet, + secure + }; + return dialogState; + } + dispose() { + super.dispose(); + if (this.N) { + clearTimeout(this.N); + this.N = undefined; + } + this.refreshTimerClear(); + this.logger.log(`SUBSCRIBE dialog ${this.id} destroyed`); + } + get autoRefresh() { + return this._autoRefresh; + } + set autoRefresh(autoRefresh) { + this._autoRefresh = true; + this.refreshTimerSet(); + } + get subscriptionEvent() { + return this._subscriptionEvent; + } + /** Number of seconds until subscription expires. */ + get subscriptionExpires() { + const secondsSinceLastSet = Math.floor(Date.now() / 1000) - this._subscriptionExpiresLastSet; + const secondsUntilExpires = this._subscriptionExpires - secondsSinceLastSet; + return Math.max(secondsUntilExpires, 0); + } + set subscriptionExpires(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) { + const refresh = this.subscriptionRefresh; + if (refresh === undefined || refresh >= expires) { + this.refreshTimerSet(); + } + } + } + get subscriptionExpiresInitial() { + return this._subscriptionExpiresInitial; + } + /** Number of seconds until subscription auto refresh. */ + get subscriptionRefresh() { + if (this._subscriptionRefresh === undefined || this._subscriptionRefreshLastSet === undefined) { + return undefined; + } + const secondsSinceLastSet = Math.floor(Date.now() / 1000) - this._subscriptionRefreshLastSet; + const secondsUntilExpires = this._subscriptionRefresh - secondsSinceLastSet; + return Math.max(secondsUntilExpires, 0); + } + get subscriptionState() { + return this._subscriptionState; + } + /** + * Receive in dialog request message from transport. + * @param message - The incoming request message. + */ + receiveRequest(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.receiveRequest(message); + // Switch on method and then delegate. + switch (message.method) { + case _messages__WEBPACK_IMPORTED_MODULE_0__["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 + */ + refresh() { + const allowHeader = "Allow: " + _user_agent_core_allowed_methods__WEBPACK_IMPORTED_MODULE_3__["AllowedMethods"].toString(); + const 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. + */ + subscribe(delegate, options = {}) { + if (this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Pending && this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_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`); + const uac = new _user_agents_re_subscribe_user_agent_client__WEBPACK_IMPORTED_MODULE_5__["ReSubscribeUserAgentClient"](this, delegate, options); + // Abort any outstanding timer (as it would otherwise become guaranteed to terminate us). + if (this.N) { + clearTimeout(this.N); + this.N = undefined; + } + // 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(() => this.timerN(), _timers__WEBPACK_IMPORTED_MODULE_2__["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 + */ + terminate() { + this.stateTransition(_subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated); + this.onTerminated(); + } + /** + * 4.1.2.3. Unsubscribing + * https://tools.ietf.org/html/rfc6665#section-4.1.2.3 + */ + unsubscribe() { + const allowHeader = "Allow: " + _user_agent_core_allowed_methods__WEBPACK_IMPORTED_MODULE_3__["AllowedMethods"].toString(); + const 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. + */ + onNotify(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 + const 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 + const subscriptionState = message.parseHeader("Subscription-State"); + if (!subscriptionState || !subscriptionState.state) { + this.core.replyStateless(message, { statusCode: 489 }); + return; + } + const state = subscriptionState.state; + const expires = subscriptionState.expires ? Math.max(subscriptionState.expires, 0) : undefined; + // Update our state and expiration. + switch (state) { + case "pending": + this.stateTransition(_subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Pending, expires); + break; + case "active": + this.stateTransition(_subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Active, expires); + break; + case "terminated": + this.stateTransition(_subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated, expires); + break; + default: + this.logger.warn("Unrecognized subscription state."); + break; + } + // Delegate remainder of NOTIFY handling. + const uas = new _user_agents_notify_user_agent_server__WEBPACK_IMPORTED_MODULE_4__["NotifyUserAgentServer"](this, message); + if (this.delegate && this.delegate.onNotify) { + this.delegate.onNotify(uas); + } + else { + uas.accept(); + } + } + onRefresh(request) { + if (this.delegate && this.delegate.onRefresh) { + this.delegate.onRefresh(request); + } + } + onTerminated() { + if (this.delegate && this.delegate.onTerminated) { + this.delegate.onTerminated(); + } + } + refreshTimerClear() { + if (this.refreshTimer) { + clearTimeout(this.refreshTimer); + this.refreshTimer = undefined; + } + } + refreshTimerSet() { + this.refreshTimerClear(); + if (this.autoRefresh && this.subscriptionExpires > 0) { + const refresh = this.subscriptionExpires * 900; + this._subscriptionRefresh = Math.floor(refresh / 1000); + this._subscriptionRefreshLastSet = Math.floor(Date.now() / 1000); + this.refreshTimer = setTimeout(() => { + this.refreshTimer = undefined; + this._subscriptionRefresh = undefined; + this._subscriptionRefreshLastSet = undefined; + this.onRefresh(this.refresh()); + }, refresh); + } + } + stateTransition(newState, newExpires) { + // Assert valid state transitions. + const invalidStateTransition = () => { + this.logger.warn(`Invalid subscription state transition from ${this.subscriptionState} to ${newState}`); + }; + switch (newState) { + case _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Initial: + invalidStateTransition(); + return; + case _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].NotifyWait: + invalidStateTransition(); + return; + case _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Pending: + if (this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].NotifyWait && + this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Pending) { + invalidStateTransition(); + return; + } + break; + case _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Active: + if (this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].NotifyWait && + this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Pending && + this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Active) { + invalidStateTransition(); + return; + } + break; + case _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated: + if (this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].NotifyWait && + this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Pending && + this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_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__WEBPACK_IMPORTED_MODULE_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__WEBPACK_IMPORTED_MODULE_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__WEBPACK_IMPORTED_MODULE_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 + */ + timerN() { + this.logger.warn(`Timer N expired for SUBSCRIBE dialog. Timed out waiting for NOTIFY.`); + if (this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated) { + this.stateTransition(_subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated); + this.onTerminated(); + } + } +} + + +/***/ }), +/* 79 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _subscription__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(80); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubscriptionState", function() { return _subscription__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"]; }); + +/* harmony import */ var _subscription_delegate__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(81); +/* empty/unused harmony star reexport */ + + + +/***/ }), +/* 80 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubscriptionState", function() { return SubscriptionState; }); +/** + * 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 || (SubscriptionState = {})); + + +/***/ }), +/* 81 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 82 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AllowedMethods", function() { return AllowedMethods; }); +/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); + +/** + * FIXME: TODO: Should be configurable/variable. + */ +const AllowedMethods = [ + _messages__WEBPACK_IMPORTED_MODULE_0__["C"].ACK, + _messages__WEBPACK_IMPORTED_MODULE_0__["C"].BYE, + _messages__WEBPACK_IMPORTED_MODULE_0__["C"].CANCEL, + _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INFO, + _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE, + _messages__WEBPACK_IMPORTED_MODULE_0__["C"].MESSAGE, + _messages__WEBPACK_IMPORTED_MODULE_0__["C"].NOTIFY, + _messages__WEBPACK_IMPORTED_MODULE_0__["C"].OPTIONS, + _messages__WEBPACK_IMPORTED_MODULE_0__["C"].PRACK, + _messages__WEBPACK_IMPORTED_MODULE_0__["C"].REFER, + _messages__WEBPACK_IMPORTED_MODULE_0__["C"].REGISTER, + _messages__WEBPACK_IMPORTED_MODULE_0__["C"].SUBSCRIBE +]; + + +/***/ }), +/* 83 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReSubscribeUserAgentClient", function() { return ReSubscribeUserAgentClient; }); +/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48); +/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(63); + + + +/** + * Re-SUBSCRIBE UAC. + * @public + */ +class ReSubscribeUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_2__["UserAgentClient"] { + constructor(dialog, delegate, options) { + const message = dialog.createOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["C"].SUBSCRIBE, options); + super(_transactions__WEBPACK_IMPORTED_MODULE_1__["NonInviteClientTransaction"], dialog.userAgentCore, message, delegate); + this.dialog = dialog; + } + waitNotifyStop() { + // TODO: Placeholder. Not utilized currently. + return; + } + /** + * Receive a response from the transaction layer. + * @param message - Incoming response message. + */ + receiveResponse(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 + const expires = message.getHeader("Expires"); + if (!expires) { + this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE"); + } + else { + const 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 + const 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.receiveResponse(message); + } +} + + +/***/ }), +/* 84 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _levels__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(85); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Levels", function() { return _levels__WEBPACK_IMPORTED_MODULE_0__["Levels"]; }); + +/* harmony import */ var _logger_factory__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(86); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LoggerFactory", function() { return _logger_factory__WEBPACK_IMPORTED_MODULE_1__["LoggerFactory"]; }); + +/* harmony import */ var _logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(87); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Logger", function() { return _logger__WEBPACK_IMPORTED_MODULE_2__["Logger"]; }); + + + + + + +/***/ }), +/* 85 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Levels", function() { return Levels; }); +/** + * 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 || (Levels = {})); + + +/***/ }), +/* 86 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LoggerFactory", function() { return LoggerFactory; }); +/* harmony import */ var _levels__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(85); +/* harmony import */ var _logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(87); + + +/** + * Logger. + * @public + */ +class LoggerFactory { + constructor() { + this.builtinEnabled = true; + this._level = _levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].log; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this.loggers = {}; + this.logger = this.getLogger("sip:loggerfactory"); + } + get level() { + return this._level; + } + set level(newLevel) { + if (newLevel >= 0 && newLevel <= 3) { + this._level = newLevel; + } + else if (newLevel > 3) { + this._level = 3; + // eslint-disable-next-line no-prototype-builtins + } + else if (_levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].hasOwnProperty(newLevel)) { + this._level = newLevel; + } + else { + this.logger.error("invalid 'level' parameter value: " + JSON.stringify(newLevel)); + } + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + get connector() { + return this._connector; + } + set connector(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)); + } + } + getLogger(category, label) { + if (label && this.level === 3) { + return new _logger__WEBPACK_IMPORTED_MODULE_1__["Logger"](this, category, label); + } + else if (this.loggers[category]) { + return this.loggers[category]; + } + else { + const logger = new _logger__WEBPACK_IMPORTED_MODULE_1__["Logger"](this, category); + this.loggers[category] = logger; + return logger; + } + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + genericLog(levelToLog, category, label, content) { + if (this.level >= levelToLog) { + if (this.builtinEnabled) { + this.print(levelToLog, category, label, content); + } + } + if (this.connector) { + this.connector(_levels__WEBPACK_IMPORTED_MODULE_0__["Levels"][levelToLog], category, label, content); + } + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + print(levelToLog, category, label, content) { + if (typeof content === "string") { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const prefix = [new Date(), category]; + if (label) { + prefix.push(label); + } + content = prefix.concat(content).join(" | "); + } + switch (levelToLog) { + case _levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].error: + // eslint-disable-next-line no-console + console.error(content); + break; + case _levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].warn: + // eslint-disable-next-line no-console + console.warn(content); + break; + case _levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].log: + // eslint-disable-next-line no-console + console.log(content); + break; + case _levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].debug: + // eslint-disable-next-line no-console + console.debug(content); + break; + default: + break; + } + } +} + + +/***/ }), +/* 87 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Logger", function() { return Logger; }); +/* harmony import */ var _levels__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(85); + +/** + * Logger. + * @public + */ +class Logger { + constructor(logger, category, label) { + this.logger = logger; + this.category = category; + this.label = label; + } + error(content) { + this.genericLog(_levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].error, content); + } + warn(content) { + this.genericLog(_levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].warn, content); + } + log(content) { + this.genericLog(_levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].log, content); + } + debug(content) { + this.genericLog(_levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].debug, content); + } + genericLog(level, content) { + this.logger.genericLog(level, this.category, this.label, content); + } + get level() { + return this.logger.level; + } + set level(newLevel) { + this.logger.level = newLevel; + } +} + + +/***/ }), +/* 88 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _user_agent_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(89); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgentCore", function() { return _user_agent_core__WEBPACK_IMPORTED_MODULE_0__["UserAgentCore"]; }); + +/* harmony import */ var _user_agent_core_configuration__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(100); +/* empty/unused harmony star reexport *//* harmony import */ var _user_agent_core_delegate__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(101); +/* empty/unused harmony star reexport */ + + + + +/***/ }), +/* 89 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UserAgentCore", function() { return UserAgentCore; }); +/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48); +/* harmony import */ var _user_agents__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(90); +/* harmony import */ var _allowed_methods__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(82); + + + + +/** + * This is ported from UA.C.ACCEPTED_BODY_TYPES. + * FIXME: TODO: Should be configurable/variable. + */ +const 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 + */ +class UserAgentCore { + /** + * Constructor. + * @param configuration - Configuration. + * @param delegate - Delegate. + */ + constructor(configuration, 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. */ + dispose() { + this.reset(); + } + /** Reset. */ + reset() { + this.dialogs.forEach((dialog) => dialog.dispose()); + this.dialogs.clear(); + this.subscribers.forEach((subscriber) => subscriber.dispose()); + this.subscribers.clear(); + this.userAgentClients.forEach((uac) => uac.dispose()); + this.userAgentClients.clear(); + this.userAgentServers.forEach((uac) => uac.dispose()); + this.userAgentServers.clear(); + } + /** Logger factory. */ + get loggerFactory() { + return this.configuration.loggerFactory; + } + /** Transport. */ + get transport() { + const transport = this.configuration.transportAccessor(); + if (!transport) { + throw new Error("Transport undefined."); + } + return transport; + } + /** + * Send INVITE. + * @param request - Outgoing request. + * @param delegate - Request delegate. + */ + invite(request, delegate) { + return new _user_agents__WEBPACK_IMPORTED_MODULE_2__["InviteUserAgentClient"](this, request, delegate); + } + /** + * Send MESSAGE. + * @param request - Outgoing request. + * @param delegate - Request delegate. + */ + message(request, delegate) { + return new _user_agents__WEBPACK_IMPORTED_MODULE_2__["MessageUserAgentClient"](this, request, delegate); + } + /** + * Send PUBLISH. + * @param request - Outgoing request. + * @param delegate - Request delegate. + */ + publish(request, delegate) { + return new _user_agents__WEBPACK_IMPORTED_MODULE_2__["PublishUserAgentClient"](this, request, delegate); + } + /** + * Send REGISTER. + * @param request - Outgoing request. + * @param delegate - Request delegate. + */ + register(request, delegate) { + return new _user_agents__WEBPACK_IMPORTED_MODULE_2__["RegisterUserAgentClient"](this, request, delegate); + } + /** + * Send SUBSCRIBE. + * @param request - Outgoing request. + * @param delegate - Request delegate. + */ + subscribe(request, delegate) { + return new _user_agents__WEBPACK_IMPORTED_MODULE_2__["SubscribeUserAgentClient"](this, request, delegate); + } + /** + * Send a request. + * @param request - Outgoing request. + * @param delegate - Request delegate. + */ + request(request, delegate) { + return new _user_agents__WEBPACK_IMPORTED_MODULE_2__["UserAgentClient"](_transactions__WEBPACK_IMPORTED_MODULE_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. + */ + makeOutgoingRequestMessage(method, requestURI, fromURI, toURI, options, extraHeaders, body) { + // default values from user agent configuration + const callIdPrefix = this.configuration.sipjsId; + const fromDisplayName = this.configuration.displayName; + const forceRport = this.configuration.viaForceRport; + const hackViaTcp = this.configuration.hackViaTcp; + const optionTags = this.configuration.supportedOptionTags.slice(); + if (method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].REGISTER) { + optionTags.push("path", "gruu"); + } + if (method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE && (this.configuration.contact.pubGruu || this.configuration.contact.tempGruu)) { + optionTags.push("gruu"); + } + const routeSet = this.configuration.routeSet; + const userAgentString = this.configuration.userAgentHeaderFieldValue; + const viaHost = this.configuration.viaHost; + const defaultOptions = { + callIdPrefix, + forceRport, + fromDisplayName, + hackViaTcp, + optionTags, + routeSet, + userAgentString, + viaHost + }; + // merge provided options with default options + const requestOptions = Object.assign(Object.assign({}, defaultOptions), options); + return new _messages__WEBPACK_IMPORTED_MODULE_0__["OutgoingRequestMessage"](method, requestURI, fromURI, toURI, requestOptions, extraHeaders, body); + } + /** + * Handle an incoming request message from the transport. + * @param message - Incoming request message from transport layer. + */ + receiveIncomingRequestFromTransport(message) { + this.receiveRequestFromTransport(message); + } + /** + * Handle an incoming response message from the transport. + * @param message - Incoming response message from transport layer. + */ + receiveIncomingResponseFromTransport(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. + */ + replyStateless(message, options) { + const userAgent = this.configuration.userAgentHeaderFieldValue; + const supported = this.configuration.supportedOptionTagsResponse; + options = Object.assign(Object.assign({}, options), { userAgent, supported }); + const response = Object(_messages__WEBPACK_IMPORTED_MODULE_0__["constructOutgoingResponse"])(message, options); + this.transport.send(response.message).catch((error) => { + // If the transport rejects, it SHOULD reject with a TransportError. + // But the transport may be external code, so we are careful... + if (error instanceof Error) { + this.logger.error(error.message); + } + this.logger.error(`Transport error occurred sending stateless reply to ${message.method} request.`); + // TODO: Currently there is no hook to provide notification that a transport error occurred + // and throwing would result in an uncaught error (in promise), so we silently eat the error. + // Furthermore, silently eating stateless reply transport errors is arguably what we want to do here. + }); + 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. + */ + receiveRequestFromTransport(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 + const transactionId = message.viaBranch; // FIXME: Currently only using rule 1... + const 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__WEBPACK_IMPORTED_MODULE_0__["C"].ACK) { + if (uas && uas.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_1__["TransactionState"].Accepted) { + if (uas instanceof _user_agents__WEBPACK_IMPORTED_MODULE_2__["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__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_1__["InviteServerTransaction"] && + uas.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_1__["TransactionState"].Proceeding) { + if (uas instanceof _user_agents__WEBPACK_IMPORTED_MODULE_2__["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. + */ + receiveRequest(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__WEBPACK_IMPORTED_MODULE_3__["AllowedMethods"].includes(message.method)) { + const allowHeader = "Allow: " + _allowed_methods__WEBPACK_IMPORTED_MODULE_3__["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 + const ruri = message.ruri; + const ruriMatches = (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__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_0__["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) { + const transactionId = message.viaBranch; + if (!this.userAgentServers.has(transactionId)) { + const mergedRequest = Array.from(this.userAgentServers.values()).some((uas) => 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. + */ + receiveInsideDialogRequest(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__WEBPACK_IMPORTED_MODULE_0__["C"].NOTIFY) { + const event = message.parseHeader("Event"); + if (!event || !event.event) { + this.replyStateless(message, { statusCode: 489 }); + return; + } + // FIXME: Subscriber id should also matching on event id. + const subscriberId = message.callId + message.toTag + event.event; + const subscriber = this.subscribers.get(subscriberId); + if (subscriber) { + const uas = new _user_agents__WEBPACK_IMPORTED_MODULE_2__["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 + const dialogId = message.callId + message.toTag + message.fromTag; + const 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__WEBPACK_IMPORTED_MODULE_0__["C"].OPTIONS) { + const allowHeader = "Allow: " + _allowed_methods__WEBPACK_IMPORTED_MODULE_3__["AllowedMethods"].toString(); + const 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__WEBPACK_IMPORTED_MODULE_0__["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. + */ + receiveOutsideDialogRequest(message) { + switch (message.method) { + case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].ACK: + // Absorb stray out of dialog ACKs + break; + case _messages__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_0__["C"].CANCEL: + throw new Error(`Unexpected out of dialog request method ${message.method}.`); + break; + case _messages__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE: + // https://tools.ietf.org/html/rfc3261#section-13.3.1 + { + const uas = new _user_agents__WEBPACK_IMPORTED_MODULE_2__["InviteUserAgentServer"](this, message); + this.delegate.onInvite ? this.delegate.onInvite(uas) : uas.reject(); + } + break; + case _messages__WEBPACK_IMPORTED_MODULE_0__["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 + { + const uas = new _user_agents__WEBPACK_IMPORTED_MODULE_2__["MessageUserAgentServer"](this, message); + this.delegate.onMessage ? this.delegate.onMessage(uas) : uas.accept(); + } + break; + case _messages__WEBPACK_IMPORTED_MODULE_0__["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 + { + const uas = new _user_agents__WEBPACK_IMPORTED_MODULE_2__["NotifyUserAgentServer"](this, message); + this.delegate.onNotify ? this.delegate.onNotify(uas) : uas.reject({ statusCode: 405 }); + } + break; + case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].OPTIONS: + // https://tools.ietf.org/html/rfc3261#section-11.2 + { + const allowHeader = "Allow: " + _allowed_methods__WEBPACK_IMPORTED_MODULE_3__["AllowedMethods"].toString(); + const acceptHeader = "Accept: " + acceptedBodyTypes.toString(); + this.replyStateless(message, { + statusCode: 200, + extraHeaders: [allowHeader, acceptHeader] + }); + } + break; + case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].REFER: + // https://tools.ietf.org/html/rfc3515#section-2.4.2 + { + const uas = new _user_agents__WEBPACK_IMPORTED_MODULE_2__["ReferUserAgentServer"](this, message); + this.delegate.onRefer ? this.delegate.onRefer(uas) : uas.reject({ statusCode: 405 }); + } + break; + case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].REGISTER: + // https://tools.ietf.org/html/rfc3261#section-10.3 + { + const uas = new _user_agents__WEBPACK_IMPORTED_MODULE_2__["RegisterUserAgentServer"](this, message); + this.delegate.onRegister ? this.delegate.onRegister(uas) : uas.reject({ statusCode: 405 }); + } + break; + case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].SUBSCRIBE: + // https://tools.ietf.org/html/rfc6665#section-4.2 + { + const uas = new _user_agents__WEBPACK_IMPORTED_MODULE_2__["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. + */ + receiveResponseFromTransport(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 + const userAgentClientId = message.viaBranch + message.method; + const 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}.`); + } + } +} + + +/***/ }), +/* 90 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _bye_user_agent_client__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(62); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ByeUserAgentClient", function() { return _bye_user_agent_client__WEBPACK_IMPORTED_MODULE_0__["ByeUserAgentClient"]; }); + +/* harmony import */ var _bye_user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(64); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ByeUserAgentServer", function() { return _bye_user_agent_server__WEBPACK_IMPORTED_MODULE_1__["ByeUserAgentServer"]; }); + +/* harmony import */ var _cancel_user_agent_client__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(91); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CancelUserAgentClient", function() { return _cancel_user_agent_client__WEBPACK_IMPORTED_MODULE_2__["CancelUserAgentClient"]; }); + +/* harmony import */ var _info_user_agent_client__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(66); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InfoUserAgentClient", function() { return _info_user_agent_client__WEBPACK_IMPORTED_MODULE_3__["InfoUserAgentClient"]; }); + +/* harmony import */ var _info_user_agent_server__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(67); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InfoUserAgentServer", function() { return _info_user_agent_server__WEBPACK_IMPORTED_MODULE_4__["InfoUserAgentServer"]; }); + +/* harmony import */ var _invite_user_agent_client__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(92); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InviteUserAgentClient", function() { return _invite_user_agent_client__WEBPACK_IMPORTED_MODULE_5__["InviteUserAgentClient"]; }); + +/* harmony import */ var _invite_user_agent_server__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(93); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InviteUserAgentServer", function() { return _invite_user_agent_server__WEBPACK_IMPORTED_MODULE_6__["InviteUserAgentServer"]; }); + +/* harmony import */ var _message_user_agent_client__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(68); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MessageUserAgentClient", function() { return _message_user_agent_client__WEBPACK_IMPORTED_MODULE_7__["MessageUserAgentClient"]; }); + +/* harmony import */ var _message_user_agent_server__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(69); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MessageUserAgentServer", function() { return _message_user_agent_server__WEBPACK_IMPORTED_MODULE_8__["MessageUserAgentServer"]; }); + +/* harmony import */ var _notify_user_agent_client__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(70); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NotifyUserAgentClient", function() { return _notify_user_agent_client__WEBPACK_IMPORTED_MODULE_9__["NotifyUserAgentClient"]; }); + +/* harmony import */ var _notify_user_agent_server__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(71); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NotifyUserAgentServer", function() { return _notify_user_agent_server__WEBPACK_IMPORTED_MODULE_10__["NotifyUserAgentServer"]; }); + +/* harmony import */ var _publish_user_agent_client__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(94); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PublishUserAgentClient", function() { return _publish_user_agent_client__WEBPACK_IMPORTED_MODULE_11__["PublishUserAgentClient"]; }); + +/* harmony import */ var _prack_user_agent_client__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(72); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PrackUserAgentClient", function() { return _prack_user_agent_client__WEBPACK_IMPORTED_MODULE_12__["PrackUserAgentClient"]; }); + +/* harmony import */ var _prack_user_agent_server__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(73); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PrackUserAgentServer", function() { return _prack_user_agent_server__WEBPACK_IMPORTED_MODULE_13__["PrackUserAgentServer"]; }); + +/* harmony import */ var _re_invite_user_agent_client__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(74); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReInviteUserAgentClient", function() { return _re_invite_user_agent_client__WEBPACK_IMPORTED_MODULE_14__["ReInviteUserAgentClient"]; }); + +/* harmony import */ var _re_invite_user_agent_server__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(75); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReInviteUserAgentServer", function() { return _re_invite_user_agent_server__WEBPACK_IMPORTED_MODULE_15__["ReInviteUserAgentServer"]; }); + +/* harmony import */ var _re_subscribe_user_agent_client__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(83); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReSubscribeUserAgentClient", function() { return _re_subscribe_user_agent_client__WEBPACK_IMPORTED_MODULE_16__["ReSubscribeUserAgentClient"]; }); + +/* harmony import */ var _re_subscribe_user_agent_server__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(95); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReSubscribeUserAgentServer", function() { return _re_subscribe_user_agent_server__WEBPACK_IMPORTED_MODULE_17__["ReSubscribeUserAgentServer"]; }); + +/* harmony import */ var _refer_user_agent_client__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(76); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReferUserAgentClient", function() { return _refer_user_agent_client__WEBPACK_IMPORTED_MODULE_18__["ReferUserAgentClient"]; }); + +/* harmony import */ var _refer_user_agent_server__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(77); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReferUserAgentServer", function() { return _refer_user_agent_server__WEBPACK_IMPORTED_MODULE_19__["ReferUserAgentServer"]; }); + +/* harmony import */ var _register_user_agent_client__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(96); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RegisterUserAgentClient", function() { return _register_user_agent_client__WEBPACK_IMPORTED_MODULE_20__["RegisterUserAgentClient"]; }); + +/* harmony import */ var _register_user_agent_server__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(97); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RegisterUserAgentServer", function() { return _register_user_agent_server__WEBPACK_IMPORTED_MODULE_21__["RegisterUserAgentServer"]; }); + +/* harmony import */ var _subscribe_user_agent_client__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(98); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubscribeUserAgentClient", function() { return _subscribe_user_agent_client__WEBPACK_IMPORTED_MODULE_22__["SubscribeUserAgentClient"]; }); + +/* harmony import */ var _subscribe_user_agent_server__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(99); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubscribeUserAgentServer", function() { return _subscribe_user_agent_server__WEBPACK_IMPORTED_MODULE_23__["SubscribeUserAgentServer"]; }); + +/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(63); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgentClient", function() { return _user_agent_client__WEBPACK_IMPORTED_MODULE_24__["UserAgentClient"]; }); + +/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(65); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgentServer", function() { return _user_agent_server__WEBPACK_IMPORTED_MODULE_25__["UserAgentServer"]; }); + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/***/ }), +/* 91 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CancelUserAgentClient", function() { return CancelUserAgentClient; }); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); +/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(63); + + +/** + * CANCEL UAC. + * @public + */ +class CancelUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_1__["UserAgentClient"] { + constructor(core, message, delegate) { + super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteClientTransaction"], core, message, delegate); + } +} + + +/***/ }), +/* 92 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InviteUserAgentClient", function() { return InviteUserAgentClient; }); +/* harmony import */ var _dialogs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _session__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(44); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(48); +/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(63); + + + + +/** + * 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 + */ +class InviteUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_3__["UserAgentClient"] { + constructor(core, message, delegate) { + super(_transactions__WEBPACK_IMPORTED_MODULE_2__["InviteClientTransaction"], core, message, delegate); + this.confirmedDialogAcks = new Map(); + this.confirmedDialogs = new Map(); + this.earlyDialogs = new Map(); + this.delegate = delegate; + } + dispose() { + // 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((earlyDialog) => earlyDialog.dispose()); + this.earlyDialogs.clear(); + super.dispose(); + } + /** + * Special case for transport error while sending ACK. + * @param error - Transport error + */ + onTransportError(error) { + if (this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Calling) { + return super.onTransportError(error); + } + // If not in 'calling' state, the transport error occurred while sending an ACK. + this.logger.error(error.message); + this.logger.error("User agent client request transport error while sending ACK."); + } + /** + * 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. + */ + receiveResponse(message) { + if (!this.authenticationGuard(message)) { + return; + } + const 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 }); + } + 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 + { + // Dialogs are created through the generation of non-failure responses + // to requests with specific methods. Within this specification, only + // 2xx and 101-199 responses with a To tag, where the request was + // INVITE, will establish a dialog. A dialog established by a non-final + // response to a request is in the "early" state and it is called an + // early dialog. + // https://tools.ietf.org/html/rfc3261#section-12.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; + } + // 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. + // https://tools.ietf.org/html/rfc3261#section-12.1.1 + // Provisional without Contact header field, malformed response. + const contact = message.parseHeader("contact"); + if (!contact) { + this.logger.error("Non-100 1xx INVITE response received without a Contact header field, dropping."); + return; + } + // Compute dialog state. + const dialogState = _dialogs__WEBPACK_IMPORTED_MODULE_0__["Dialog"].initialDialogStateForUserAgentClient(this.message, message); + // Have existing early dialog or create a new one. + let earlyDialog = this.earlyDialogs.get(dialogState.id); + if (!earlyDialog) { + const transaction = this.transaction; + if (!(transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_2__["InviteClientTransaction"])) { + throw new Error("Transaction not instance of InviteClientTransaction."); + } + earlyDialog = new _dialogs__WEBPACK_IMPORTED_MODULE_0__["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 or is a retransmission, 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__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Initial || + earlyDialog.signalingState === _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveLocalOffer) { + earlyDialog.signalingStateTransition(message); + } + // Pass response to delegate. + const session = earlyDialog; + if (this.delegate && this.delegate.onProgress) { + this.delegate.onProgress({ + message, + session, + prack: (options) => { + const outgoingPrackRequest = session.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 + { + // Dialogs are created through the generation of non-failure responses + // to requests with specific methods. Within this specification, only + // 2xx and 101-199 responses with a To tag, where the request was + // INVITE, will establish a dialog. A dialog established by a non-final + // response to a request is in the "early" state and it is called an + // early dialog. + // https://tools.ietf.org/html/rfc3261#section-12.1 + // Final without to tag, malformed response. + if (!message.toTag) { + this.logger.error("2xx INVITE response received without a to tag, dropping."); + return; + } + // 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. + // https://tools.ietf.org/html/rfc3261#section-12.1.1 + // Final without Contact header field, malformed response. + const contact = message.parseHeader("contact"); + if (!contact) { + this.logger.error("2xx INVITE response received without a Contact header field, dropping."); + return; + } + // Compute dialog state. + const dialogState = _dialogs__WEBPACK_IMPORTED_MODULE_0__["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. + let 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 + const outgoingAckRequest = this.confirmedDialogAcks.get(dialogState.id); + if (outgoingAckRequest) { + const transaction = this.transaction; + if (!(transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_2__["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 { + const transaction = this.transaction; + if (!(transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_2__["InviteClientTransaction"])) { + throw new Error("Transaction not instance of InviteClientTransaction."); + } + dialog = new _dialogs__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Initial || + dialog.signalingState === _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveLocalOffer) { + dialog.signalingStateTransition(message); + } + // Session Initiated! :) + const session = 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, + session, + ack: (options) => { + const outgoingAckRequest = session.ack(options); + this.confirmedDialogAcks.set(session.id, outgoingAckRequest); + return outgoingAckRequest; + } + }); + } + else { + const outgoingAckRequest = session.ack(); + this.confirmedDialogAcks.set(session.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((earlyDialog) => 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 }); + } + 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((earlyDialog) => 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 }); + } + return; + default: + throw new Error(`Invalid status code ${statusCode}`); + } + throw new Error(`Executing what should be an unreachable code path receiving ${statusCode} response.`); + } +} + + +/***/ }), +/* 93 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InviteUserAgentServer", function() { return InviteUserAgentServer; }); +/* harmony import */ var _dialogs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _exceptions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(51); +/* harmony import */ var _session__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(44); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(48); +/* harmony import */ var _user_agent_core_allowed_methods__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(82); +/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(65); + + + + + + +/** + * 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 + */ +class InviteUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_5__["UserAgentServer"] { + constructor(core, message, delegate) { + super(_transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"], core, message, delegate); + this.core = core; + } + dispose() { + if (this.earlyDialog) { + this.earlyDialog.dispose(); + } + super.dispose(); + } + /** + * 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 = { statusCode: 200 }) { + if (!this.acceptable) { + throw new _exceptions__WEBPACK_IMPORTED_MODULE_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 { + const transaction = this.transaction; + if (!(transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"])) { + throw new Error("Transaction not instance of InviteClientTransaction."); + } + const state = _dialogs__WEBPACK_IMPORTED_MODULE_0__["Dialog"].initialDialogStateForUserAgentServer(this.message, this.toTag); + this.confirmedDialog = new _dialogs__WEBPACK_IMPORTED_MODULE_0__["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 + const recordRouteHeader = this.message.getHeaders("record-route").map((header) => `Record-Route: ${header}`); + const 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. + const allowHeader = "Allow: " + _user_agent_core_allowed_methods__WEBPACK_IMPORTED_MODULE_4__["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__WEBPACK_IMPORTED_MODULE_2__["SignalingState"].Stable) { + options.body = this.confirmedDialog.answer; // resend the answer sent in provisional response + } + else if (this.confirmedDialog.signalingState === _session__WEBPACK_IMPORTED_MODULE_2__["SignalingState"].Initial || + this.confirmedDialog.signalingState === _session__WEBPACK_IMPORTED_MODULE_2__["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); + const response = super.accept(options); + const session = this.confirmedDialog; + const result = Object.assign(Object.assign({}, response), { 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__WEBPACK_IMPORTED_MODULE_2__["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. + */ + progress(options = { statusCode: 180 }) { + if (!this.progressable) { + throw new _exceptions__WEBPACK_IMPORTED_MODULE_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) { + const transaction = this.transaction; + if (!(transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"])) { + throw new Error("Transaction not instance of InviteClientTransaction."); + } + const state = _dialogs__WEBPACK_IMPORTED_MODULE_0__["Dialog"].initialDialogStateForUserAgentServer(this.message, this.toTag, true); + this.earlyDialog = new _dialogs__WEBPACK_IMPORTED_MODULE_0__["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 + const recordRouteHeader = this.message.getHeaders("record-route").map((header) => `Record-Route: ${header}`); + const contactHeader = `Contact: ${this.core.configuration.contact}`; + options.extraHeaders = options.extraHeaders || []; + options.extraHeaders = options.extraHeaders.concat(recordRouteHeader); + options.extraHeaders.push(contactHeader); + const response = super.progress(options); + const session = this.earlyDialog; + const result = Object.assign(Object.assign({}, response), { 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__WEBPACK_IMPORTED_MODULE_2__["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. + */ + redirect(contacts, options = { statusCode: 302 }) { + return super.redirect(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. + */ + reject(options = { statusCode: 486 }) { + return super.reject(options); + } +} + + +/***/ }), +/* 94 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PublishUserAgentClient", function() { return PublishUserAgentClient; }); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); +/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(63); + + +/** + * PUBLISH UAC. + * @public + */ +class PublishUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_1__["UserAgentClient"] { + constructor(core, message, delegate) { + super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteClientTransaction"], core, message, delegate); + } +} + + +/***/ }), +/* 95 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReSubscribeUserAgentServer", function() { return ReSubscribeUserAgentServer; }); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); +/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); + + +/** + * Re-SUBSCRIBE UAS. + * @public + */ +class ReSubscribeUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { + constructor(dialog, message, delegate) { + super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteServerTransaction"], dialog.userAgentCore, message, delegate); + } +} + + +/***/ }), +/* 96 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RegisterUserAgentClient", function() { return RegisterUserAgentClient; }); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); +/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(63); + + +/** + * REGISTER UAC. + * @public + */ +class RegisterUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_1__["UserAgentClient"] { + constructor(core, message, delegate) { + super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteClientTransaction"], core, message, delegate); + } +} + + +/***/ }), +/* 97 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RegisterUserAgentServer", function() { return RegisterUserAgentServer; }); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); +/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); + + +/** + * REGISTER UAS. + * @public + */ +class RegisterUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { + constructor(core, message, delegate) { + super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteServerTransaction"], core, message, delegate); + this.core = core; + } +} + + +/***/ }), +/* 98 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubscribeUserAgentClient", function() { return SubscribeUserAgentClient; }); +/* harmony import */ var _dialogs_subscription_dialog__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(78); +/* harmony import */ var _subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(79); +/* harmony import */ var _timers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(47); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(48); +/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(63); + + + + + +/** + * 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 requests. + * @public + */ +class SubscribeUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_4__["UserAgentClient"] { + constructor(core, message, delegate) { + // Get event from request message. + const event = message.getHeader("Event"); + if (!event) { + throw new Error("Event undefined"); + } + // Get expires from request message. + const expires = message.getHeader("Expires"); + if (!expires) { + throw new Error("Expires undefined"); + } + super(_transactions__WEBPACK_IMPORTED_MODULE_3__["NonInviteClientTransaction"], core, message, delegate); + 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__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].NotifyWait; + // Start waiting for a NOTIFY we can use to create a subscription. + this.waitNotifyStart(); + } + /** + * 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() { + super.dispose(); + } + /** + * Handle out of dialog NOTIFY associated 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) { + // 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 + const 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 + const 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. + const 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 + const 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 multiple subscriptions. + // As such and in accordance with the specification, 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 subscription state. + switch (state) { + case "pending": + this.subscriptionState = _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Pending; + break; + case "active": + this.subscriptionState = _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Active; + break; + case "terminated": + this.subscriptionState = _subscription__WEBPACK_IMPORTED_MODULE_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__WEBPACK_IMPORTED_MODULE_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 + const dialogState = _dialogs_subscription_dialog__WEBPACK_IMPORTED_MODULE_0__["SubscriptionDialog"].initialDialogStateForSubscription(this.message, uas.message); + // Subscription Initiated! :) + this.dialog = new _dialogs_subscription_dialog__WEBPACK_IMPORTED_MODULE_0__["SubscriptionDialog"](this.subscriptionEvent, this.subscriptionExpires, this.subscriptionState, this.core, dialogState); + } + // Delegate. + if (this.delegate && this.delegate.onNotify) { + const request = uas; + const subscription = this.dialog; + this.delegate.onNotify({ request, subscription }); + } + else { + uas.accept(); + } + } + waitNotifyStart() { + 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(() => this.timerN(), _timers__WEBPACK_IMPORTED_MODULE_2__["Timers"].TIMER_N); + } + } + waitNotifyStop() { + 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. + */ + receiveResponse(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 + const expires = message.getHeader("Expires"); + if (!expires) { + this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE"); + } + else { + const 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.receiveResponse(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 + */ + timerN() { + 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(); + } + } +} + + +/***/ }), +/* 99 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubscribeUserAgentServer", function() { return SubscribeUserAgentServer; }); +/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); +/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); + + +/** + * SUBSCRIBE UAS. + * @public + */ +class SubscribeUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { + constructor(core, message, delegate) { + super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteServerTransaction"], core, message, delegate); + this.core = core; + } +} + + +/***/ }), +/* 100 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 101 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 102 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 103 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RequestPendingError", function() { return RequestPendingError; }); +/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); + +/** + * An exception indicating an outstanding prior request prevented execution. + * @public + */ +class RequestPendingError extends _core__WEBPACK_IMPORTED_MODULE_0__["Exception"] { + /** @internal */ + constructor(message) { + super(message ? message : "Request pending."); + } +} + + +/***/ }), +/* 104 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SessionDescriptionHandlerError", function() { return SessionDescriptionHandlerError; }); +/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); + +/** + * An exception indicating a session description handler error occured. + * @public + */ +class SessionDescriptionHandlerError extends _core__WEBPACK_IMPORTED_MODULE_0__["Exception"] { + constructor(message) { + super(message ? message : "Unspecified session description handler error."); + } +} + + +/***/ }), +/* 105 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SessionTerminatedError", function() { return SessionTerminatedError; }); +/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); + +/** + * An exception indicating the session terminated before the action completed. + * @public + */ +class SessionTerminatedError extends _core__WEBPACK_IMPORTED_MODULE_0__["Exception"] { + constructor() { + super("The session has terminated."); + } +} + + +/***/ }), +/* 106 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StateTransitionError", function() { return StateTransitionError; }); +/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); + +/** + * An exception indicating an invalid state transition error occured. + * @public + */ +class StateTransitionError extends _core__WEBPACK_IMPORTED_MODULE_0__["Exception"] { + constructor(message) { + super(message ? message : "An error occurred during state transition."); + } +} + + +/***/ }), +/* 107 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Bye", function() { return Bye; }); +/** + * A request to end a {@link Session} (incoming BYE). + * @public + */ +class Bye { + /** @internal */ + constructor(incomingByeRequest) { + this.incomingByeRequest = incomingByeRequest; + } + /** Incoming BYE request message. */ + get request() { + return this.incomingByeRequest.message; + } + /** Accept the request. */ + accept(options) { + this.incomingByeRequest.accept(options); + return Promise.resolve(); + } + /** Reject the request. */ + reject(options) { + this.incomingByeRequest.reject(options); + return Promise.resolve(); + } +} + + +/***/ }), +/* 108 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EmitterImpl", function() { return EmitterImpl; }); +/** + * An {@link Emitter} implementation. + * @internal + */ +class EmitterImpl { + constructor() { + this.listeners = new Array(); + } + /** + * Sets up a function that will be called whenever the target changes. + * @param listener - Callback function. + * @param options - An options object that specifies characteristics about the listener. + * If once true, indicates that the listener should be invoked at most once after being added. + * If once true, the listener would be automatically removed when invoked. + */ + addListener(listener, options) { + const onceWrapper = (data) => { + this.removeListener(onceWrapper); + listener(data); + }; + (options === null || options === void 0 ? void 0 : options.once) === true ? this.listeners.push(onceWrapper) : this.listeners.push(listener); + } + /** + * Emit change. + * @param data - Data to emit. + */ + emit(data) { + this.listeners.slice().forEach((listener) => listener(data)); + } + /** + * Removes all listeners previously registered with addListener. + */ + removeAllListeners() { + this.listeners = []; + } + /** + * Removes a listener previously registered with addListener. + * @param listener - Callback function. + */ + removeListener(listener) { + this.listeners = this.listeners.filter((l) => l !== listener); + } + /** + * Registers a listener. + * @param listener - Callback function. + * @deprecated Use addListener. + */ + on(listener) { + return this.addListener(listener); + } + /** + * Unregisters a listener. + * @param listener - Callback function. + * @deprecated Use removeListener. + */ + off(listener) { + return this.removeListener(listener); + } + /** + * Registers a listener then unregisters the listener after one event emission. + * @param listener - Callback function. + * @deprecated Use addListener. + */ + once(listener) { + return this.addListener(listener, { once: true }); + } +} + + +/***/ }), +/* 109 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Info", function() { return Info; }); +/** + * An exchange of information (incoming INFO). + * @public + */ +class Info { + /** @internal */ + constructor(incomingInfoRequest) { + this.incomingInfoRequest = incomingInfoRequest; + } + /** Incoming MESSAGE request message. */ + get request() { + return this.incomingInfoRequest.message; + } + /** Accept the request. */ + accept(options) { + this.incomingInfoRequest.accept(options); + return Promise.resolve(); + } + /** Reject the request. */ + reject(options) { + this.incomingInfoRequest.reject(options); + return Promise.resolve(); + } +} + + +/***/ }), +/* 110 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 111 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 112 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 113 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Invitation", function() { return Invitation; }); +/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); +/* harmony import */ var _core_messages_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(32); +/* harmony import */ var _exceptions__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(3); +/* harmony import */ var _session__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(114); +/* harmony import */ var _session_state__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(118); +/* harmony import */ var _user_agent_options__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(119); + + + + + + +/** + * An invitation is an offer to establish a {@link Session} (incoming INVITE). + * @public + */ +class Invitation extends _session__WEBPACK_IMPORTED_MODULE_3__["Session"] { + /** @internal */ + constructor(userAgent, incomingInviteRequest) { + super(userAgent); + this.incomingInviteRequest = incomingInviteRequest; + /** True if dispose() has been called. */ + this.disposed = false; + /** INVITE will be rejected if not accepted within a certain period time. */ + this.expiresTimer = undefined; + /** True if this Session has been Terminated due to a CANCEL request. */ + this.isCanceled = false; + /** Are reliable provisional responses required or supported. */ + this.rel100 = "none"; + /** The current RSeq header value. */ + this.rseq = Math.floor(Math.random() * 10000); + /** INVITE will be rejected if final response not sent in a certain period time. */ + this.userNoAnswerTimer = undefined; + /** True if waiting for a PRACK before sending a 200 Ok. */ + this.waitingForPrack = false; + this.logger = userAgent.getLogger("sip.Invitation"); + const incomingRequestMessage = this.incomingInviteRequest.message; + // Set 100rel if necessary + const requireHeader = incomingRequestMessage.getHeader("require"); + if (requireHeader && requireHeader.toLowerCase().includes("100rel")) { + this.rel100 = "required"; + } + const supportedHeader = incomingRequestMessage.getHeader("supported"); + if (supportedHeader && supportedHeader.toLowerCase().includes("100rel")) { + this.rel100 = "supported"; + } + // FIXME: HACK: This is a hack to port an existing behavior. + // Set the toTag on the incoming request message to the toTag which + // will be used in the response to the incoming request!!! + // 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). + // eslint-disable-next-line @typescript-eslint/no-explicit-any + incomingRequestMessage.toTag = incomingInviteRequest.toTag; + if (typeof incomingRequestMessage.toTag !== "string") { + throw new TypeError("toTag should have been a string."); + } + // The following mapping values are RECOMMENDED: + // ... + // 19 no answer from the user 480 Temporarily unavailable + // https://tools.ietf.org/html/rfc3398#section-7.2.4.1 + this.userNoAnswerTimer = setTimeout(() => { + incomingInviteRequest.reject({ statusCode: 480 }); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Terminated); + }, this.userAgent.configuration.noAnswerTimeout ? this.userAgent.configuration.noAnswerTimeout * 1000 : 60000); + // 1. If the request is an INVITE that contains an Expires header + // field, the UAS core sets a timer for the number of seconds + // indicated in the header field value. When the timer fires, the + // invitation is considered to be expired. If the invitation + // expires before the UAS has generated a final response, a 487 + // (Request Terminated) response SHOULD be generated. + // https://tools.ietf.org/html/rfc3261#section-13.3.1 + if (incomingRequestMessage.hasHeader("expires")) { + const expires = Number(incomingRequestMessage.getHeader("expires") || 0) * 1000; + this.expiresTimer = setTimeout(() => { + if (this.state === _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Initial) { + incomingInviteRequest.reject({ statusCode: 487 }); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Terminated); + } + }, expires); + } + // Session parent properties + const assertedIdentity = this.request.getHeader("P-Asserted-Identity"); + if (assertedIdentity) { + this._assertedIdentity = _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].nameAddrHeaderParse(assertedIdentity); + } + this._contact = this.userAgent.contact.toString(); + const contentDisposition = incomingRequestMessage.parseHeader("Content-Disposition"); + if (contentDisposition && contentDisposition.type === "render") { + this._renderbody = incomingRequestMessage.body; + this._rendertype = incomingRequestMessage.getHeader("Content-Type"); + } + // Identifier + this._id = incomingRequestMessage.callId + incomingRequestMessage.fromTag; + // Add to the user agent's session collection. + this.userAgent._sessions[this._id] = this; + } + /** + * Destructor. + */ + dispose() { + // Only run through this once. It can and does get called multiple times + // depending on the what the sessions state is when first called. + // For example, if called when "establishing" it will be called again + // at least once when the session transitions to "terminated". + // Regardless, running through this more than once is pointless. + if (this.disposed) { + return Promise.resolve(); + } + this.disposed = true; + // Clear timers + if (this.expiresTimer) { + clearTimeout(this.expiresTimer); + this.expiresTimer = undefined; + } + if (this.userNoAnswerTimer) { + clearTimeout(this.userNoAnswerTimer); + this.userNoAnswerTimer = undefined; + } + // If accept() is still waiting for a PRACK, make sure it rejects + this.prackNeverArrived(); + // If the final response for the initial INVITE not yet been sent, reject it + switch (this.state) { + case _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Initial: + return this.reject().then(() => super.dispose()); + case _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Establishing: + return this.reject().then(() => super.dispose()); + case _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Established: + return super.dispose(); + case _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Terminating: + return super.dispose(); + case _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Terminated: + return super.dispose(); + default: + throw new Error("Unknown state."); + } + } + /** + * 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 autoSendAnInitialProvisionalResponse() { + return this.rel100 === "required" ? false : true; + } + /** + * Initial incoming INVITE request message body. + */ + get body() { + return this.incomingInviteRequest.message.body; + } + /** + * The identity of the local user. + */ + get localIdentity() { + return this.request.to; + } + /** + * The identity of the remote user. + */ + get remoteIdentity() { + return this.request.from; + } + /** + * Initial incoming INVITE request message. + */ + get request() { + return this.incomingInviteRequest.message; + } + /** + * Accept the invitation. + * + * @remarks + * Accept the incoming INVITE request to start a Session. + * Replies to the INVITE request with a 200 Ok response. + * Resolves once the response sent, otherwise rejects. + * + * This method may reject for a variety of reasons including + * the receipt of a CANCEL request before `accept` is able + * to construct a response. + * @param options - Options bucket. + */ + accept(options = {}) { + this.logger.log("Invitation.accept"); + // validate state + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Initial) { + const error = new Error(`Invalid session state ${this.state}`); + this.logger.error(error.message); + return Promise.reject(error); + } + // Modifiers and options for initial INVITE transaction + if (options.sessionDescriptionHandlerModifiers) { + this.sessionDescriptionHandlerModifiers = options.sessionDescriptionHandlerModifiers; + } + if (options.sessionDescriptionHandlerOptions) { + this.sessionDescriptionHandlerOptions = options.sessionDescriptionHandlerOptions; + } + // transition state + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Establishing); + return (this.sendAccept() + // eslint-disable-next-line @typescript-eslint/no-unused-vars + .then(({ message, session }) => { + session.delegate = { + onAck: (ackRequest) => this.onAckRequest(ackRequest), + onAckTimeout: () => this.onAckTimeout(), + onBye: (byeRequest) => this.onByeRequest(byeRequest), + onInfo: (infoRequest) => this.onInfoRequest(infoRequest), + onInvite: (inviteRequest) => this.onInviteRequest(inviteRequest), + onMessage: (messageRequest) => this.onMessageRequest(messageRequest), + onNotify: (notifyRequest) => this.onNotifyRequest(notifyRequest), + onPrack: (prackRequest) => this.onPrackRequest(prackRequest), + onRefer: (referRequest) => this.onReferRequest(referRequest) + }; + this._dialog = session; + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Established); + // TODO: Reconsider this "automagic" send of a BYE to replacee behavior. + // This behavior has been ported forward from legacy versions. + if (this._replacee) { + this._replacee._bye(); + } + }) + .catch((error) => this.handleResponseError(error))); + } + /** + * Indicate progress processing the invitation. + * + * @remarks + * Report progress to the the caller. + * Replies to the INVITE request with a 1xx provisional response. + * Resolves once the response sent, otherwise rejects. + * @param options - Options bucket. + */ + progress(options = {}) { + this.logger.log("Invitation.progress"); + // validate state + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Initial) { + const error = new Error(`Invalid session state ${this.state}`); + this.logger.error(error.message); + return Promise.reject(error); + } + // Ported + const statusCode = options.statusCode || 180; + if (statusCode < 100 || statusCode > 199) { + throw new TypeError("Invalid statusCode: " + statusCode); + } + // Modifiers and options for initial INVITE transaction + if (options.sessionDescriptionHandlerModifiers) { + this.sessionDescriptionHandlerModifiers = options.sessionDescriptionHandlerModifiers; + } + if (options.sessionDescriptionHandlerOptions) { + this.sessionDescriptionHandlerOptions = options.sessionDescriptionHandlerOptions; + } + // 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.waitingForPrack) { + this.logger.warn("Unexpected call for progress while waiting for prack, ignoring"); + return Promise.resolve(); + } + // Trying provisional response + if (options.statusCode === 100) { + return this.sendProgressTrying() + .then(() => { + return; + }) + .catch((error) => this.handleResponseError(error)); + } + // Standard provisional response + if (!(this.rel100 === "required") && + !(this.rel100 === "supported" && options.rel100) && + !(this.rel100 === "supported" && this.userAgent.configuration.sipExtension100rel === _user_agent_options__WEBPACK_IMPORTED_MODULE_5__["SIPExtension"].Required)) { + return this.sendProgress(options) + .then(() => { + return; + }) + .catch((error) => this.handleResponseError(error)); + } + // Reliable provisional response + return this.sendProgressReliableWaitForPrack(options) + .then(() => { + return; + }) + .catch((error) => this.handleResponseError(error)); + } + /** + * Reject the invitation. + * + * @remarks + * Replies to the INVITE request with a 4xx, 5xx, or 6xx final response. + * Resolves once the response sent, otherwise rejects. + * + * The expectation is that this method is used to reject an INVITE request. + * That is indeed the case - a call to `progress` followed by `reject` is + * a typical way to "decline" an incoming INVITE request. However it may + * also be called after calling `accept` (but only before it completes) + * which will reject the call and cause `accept` to reject. + * @param options - Options bucket. + */ + reject(options = {}) { + this.logger.log("Invitation.reject"); + // validate state + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Initial && this.state !== _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Establishing) { + const error = new Error(`Invalid session state ${this.state}`); + this.logger.error(error.message); + return Promise.reject(error); + } + const statusCode = options.statusCode || 480; + const reasonPhrase = options.reasonPhrase ? options.reasonPhrase : Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["getReasonPhrase"])(statusCode); + const extraHeaders = options.extraHeaders || []; + if (statusCode < 300 || statusCode > 699) { + throw new TypeError("Invalid statusCode: " + statusCode); + } + const body = options.body ? Object(_core__WEBPACK_IMPORTED_MODULE_0__["fromBodyLegacy"])(options.body) : undefined; + // FIXME: Need to redirect to someplace + statusCode < 400 + ? this.incomingInviteRequest.redirect([], { statusCode, reasonPhrase, extraHeaders, body }) + : this.incomingInviteRequest.reject({ statusCode, reasonPhrase, extraHeaders, body }); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Terminated); + return Promise.resolve(); + } + /** + * Handle CANCEL request. + * + * @param message - CANCEL message. + * @internal + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _onCancel(message) { + this.logger.log("Invitation._onCancel"); + // validate state + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Initial && this.state !== _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Establishing) { + this.logger.error(`CANCEL received while in state ${this.state}, dropping request`); + return; + } + // flag canceled + this.isCanceled = true; + // reject INVITE with 487 status code + this.incomingInviteRequest.reject({ statusCode: 487 }); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Terminated); + } + /** + * Helper function to handle offer/answer in a PRACK. + */ + handlePrackOfferAnswer(request) { + if (!this.dialog) { + throw new Error("Dialog undefined."); + } + // If the PRACK doesn't have an offer/answer, nothing to be done. + const body = Object(_core__WEBPACK_IMPORTED_MODULE_0__["getBody"])(request.message); + if (!body || body.contentDisposition !== "session") { + return Promise.resolve(undefined); + } + const options = { + sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, + sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers + }; + // 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__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Stable: + // Receved answer. + return this.setAnswer(body, options).then(() => undefined); + case _core__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].HaveRemoteOffer: + // Received offer, generate answer. + return this.setOfferAndGetAnswer(body, options); + case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Closed: + throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`); + default: + throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`); + } + } + /** + * A handler for errors which occur while attempting to send 1xx and 2xx responses. + * In all cases, an attempt is made to reject the request if it is still outstanding. + * And while there are a variety of things which can go wrong and we log something here + * for all errors, there are a handful of common exceptions we pay some extra attention to. + * @param error - The error which occurred. + */ + handleResponseError(error) { + let statusCode = 480; // "Temporarily Unavailable" + // Log Error message + if (error instanceof Error) { + this.logger.error(error.message); + } + else { + // We don't actually know what a session description handler implementation might throw our way, + // and more generally as a last resort catch all, just assume we are getting an "unknown" and log it. + this.logger.error(error); + } + // Log Exception message + if (error instanceof _exceptions__WEBPACK_IMPORTED_MODULE_2__["ContentTypeUnsupportedError"]) { + this.logger.error("A session description handler occurred while sending response (content type unsupported"); + statusCode = 415; // "Unsupported Media Type" + } + else if (error instanceof _exceptions__WEBPACK_IMPORTED_MODULE_2__["SessionDescriptionHandlerError"]) { + this.logger.error("A session description handler occurred while sending response"); + } + else if (error instanceof _exceptions__WEBPACK_IMPORTED_MODULE_2__["SessionTerminatedError"]) { + this.logger.error("Session ended before response could be formulated and sent (while waiting for PRACK)"); + } + else if (error instanceof _core__WEBPACK_IMPORTED_MODULE_0__["TransactionStateError"]) { + this.logger.error("Session changed state before response could be formulated and sent"); + } + // Reject if still in "initial" or "establishing" state. + if (this.state === _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Initial || this.state === _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Establishing) { + try { + this.incomingInviteRequest.reject({ statusCode }); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Terminated); + } + catch (e) { + this.logger.error("An error occurred attempting to reject the request while handling another error"); + throw e; // This is not a good place to be... + } + } + // FIXME: TODO: + // Here we are squelching the throwing of errors due to an 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 + // these race errors to the caller of `accept()`, we are squelching the throwing + // of ALL errors when/if they occur after receiving a CANCEL to catch the ONE we know + // is a "normal" exceptional condition. While this is a completely reasonable approach, + // the decision should be left up to the library user. Furthermore, as we are eating + // ALL errors in this case, we are potentially (likely) hiding "real" errors which occur. + // + // Only rethrow error if the session has not been canceled. + if (this.isCanceled) { + this.logger.warn("An error occurred while attempting to formulate and send a response to an incoming INVITE." + + " However a CANCEL was received and processed while doing so which can (and often does) result" + + " in errors occurring as the session terminates in the meantime. Said error is being ignored."); + return; + } + throw error; + } + /** + * Callback for when ACK for a 2xx response is never received. + * @param session - Session the ACK never arrived for. + */ + onAckTimeout() { + 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__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Terminated); + } + /** + * A version of `accept` which resolves a session when the 200 Ok response is sent. + * @param options - Options bucket. + */ + sendAccept() { + const responseOptions = { + sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, + sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers + }; + // 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.waitingForPrack) { + return this.waitForArrivalOfPrack() + .then(() => clearTimeout(this.userNoAnswerTimer)) // Ported + .then(() => this.generateResponseOfferAnswer(this.incomingInviteRequest, responseOptions)) + .then((body) => this.incomingInviteRequest.accept({ statusCode: 200, body })); + } + clearTimeout(this.userNoAnswerTimer); // Ported + return this.generateResponseOfferAnswer(this.incomingInviteRequest, responseOptions).then((body) => this.incomingInviteRequest.accept({ statusCode: 200, body })); + } + /** + * A version of `progress` which resolves when the provisional response is sent. + * @param options - Options bucket. + */ + sendProgress(options = {}) { + const statusCode = options.statusCode || 180; + const reasonPhrase = options.reasonPhrase; + const extraHeaders = (options.extraHeaders || []).slice(); + const body = options.body ? Object(_core__WEBPACK_IMPORTED_MODULE_0__["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.sendProgressWithSDP(options); + } + try { + const progressResponse = this.incomingInviteRequest.progress({ statusCode, reasonPhrase, extraHeaders, body }); + 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. + */ + sendProgressWithSDP(options = {}) { + const responseOptions = { + sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, + sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers + }; + const statusCode = options.statusCode || 183; + const reasonPhrase = options.reasonPhrase; + const extraHeaders = (options.extraHeaders || []).slice(); + // Get an offer/answer and send a reply. + return this.generateResponseOfferAnswer(this.incomingInviteRequest, responseOptions) + .then((body) => this.incomingInviteRequest.progress({ statusCode, reasonPhrase, extraHeaders, body })) + .then((progressResponse) => { + this._dialog = progressResponse.session; + return progressResponse; + }); + } + /** + * A version of `progress` which resolves when the reliable provisional response is sent. + * @param options - Options bucket. + */ + sendProgressReliable(options = {}) { + options.extraHeaders = (options.extraHeaders || []).slice(); + options.extraHeaders.push("Require: 100rel"); + options.extraHeaders.push("RSeq: " + Math.floor(Math.random() * 10000)); + return this.sendProgressWithSDP(options); + } + /** + * A version of `progress` which resolves when the reliable provisional response is acknowledged. + * @param options - Options bucket. + */ + sendProgressReliableWaitForPrack(options = {}) { + const responseOptions = { + sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, + sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers + }; + const statusCode = options.statusCode || 183; + const reasonPhrase = options.reasonPhrase; + const extraHeaders = (options.extraHeaders || []).slice(); + extraHeaders.push("Require: 100rel"); + extraHeaders.push("RSeq: " + this.rseq++); + let body; + return new Promise((resolve, reject) => { + this.waitingForPrack = true; + this.generateResponseOfferAnswer(this.incomingInviteRequest, responseOptions) + .then((offerAnswer) => { + body = offerAnswer; + return this.incomingInviteRequest.progress({ statusCode, reasonPhrase, extraHeaders, body }); + }) + .then((progressResponse) => { + this._dialog = progressResponse.session; + let prackRequest; + let prackResponse; + progressResponse.session.delegate = { + onPrack: (request) => { + prackRequest = request; + // eslint-disable-next-line @typescript-eslint/no-use-before-define + clearTimeout(prackWaitTimeoutTimer); + // eslint-disable-next-line @typescript-eslint/no-use-before-define + clearTimeout(rel1xxRetransmissionTimer); + if (!this.waitingForPrack) { + return; + } + this.waitingForPrack = false; + this.handlePrackOfferAnswer(prackRequest) + .then((prackResponseBody) => { + try { + prackResponse = prackRequest.accept({ statusCode: 200, body: prackResponseBody }); + this.prackArrived(); + resolve({ prackRequest, prackResponse, progressResponse }); + } + catch (error) { + reject(error); + } + }) + .catch((error) => reject(error)); + } + }; + // https://tools.ietf.org/html/rfc3262#section-3 + const prackWaitTimeout = () => { + if (!this.waitingForPrack) { + return; + } + this.waitingForPrack = false; + this.logger.warn("No PRACK received, rejecting INVITE."); + // eslint-disable-next-line @typescript-eslint/no-use-before-define + clearTimeout(rel1xxRetransmissionTimer); + this.reject({ statusCode: 504 }) + .then(() => reject(new _exceptions__WEBPACK_IMPORTED_MODULE_2__["SessionTerminatedError"]())) + .catch((error) => reject(error)); + }; + const prackWaitTimeoutTimer = setTimeout(prackWaitTimeout, _core__WEBPACK_IMPORTED_MODULE_0__["Timers"].T1 * 64); + // https://tools.ietf.org/html/rfc3262#section-3 + const rel1xxRetransmission = () => { + try { + this.incomingInviteRequest.progress({ statusCode, reasonPhrase, extraHeaders, body }); + } + catch (error) { + this.waitingForPrack = false; + reject(error); + return; + } + // eslint-disable-next-line @typescript-eslint/no-use-before-define + rel1xxRetransmissionTimer = setTimeout(rel1xxRetransmission, (timeout *= 2)); + }; + let timeout = _core__WEBPACK_IMPORTED_MODULE_0__["Timers"].T1; + let rel1xxRetransmissionTimer = setTimeout(rel1xxRetransmission, timeout); + }) + .catch((error) => { + this.waitingForPrack = false; + reject(error); + }); + }); + } + /** + * A version of `progress` which resolves when a 100 Trying provisional response is sent. + */ + sendProgressTrying() { + try { + const progressResponse = this.incomingInviteRequest.trying(); + return Promise.resolve(progressResponse); + } + catch (error) { + return Promise.reject(error); + } + } + /** + * When attempting to accept the INVITE, an invitation waits + * for any outstanding PRACK to arrive before sending the 200 Ok. + * It will be waiting on this Promise to resolve which lets it know + * the PRACK has arrived and it may proceed to send the 200 Ok. + */ + waitForArrivalOfPrack() { + if (this.waitingForPrackPromise) { + throw new Error("Already waiting for PRACK"); + } + this.waitingForPrackPromise = new Promise((resolve, reject) => { + this.waitingForPrackResolve = resolve; + this.waitingForPrackReject = reject; + }); + return this.waitingForPrackPromise; + } + /** + * Here we are resolving the promise which in turn will cause + * the accept to proceed (it may still fail for other reasons, but...). + */ + prackArrived() { + if (this.waitingForPrackResolve) { + this.waitingForPrackResolve(); + } + this.waitingForPrackPromise = undefined; + this.waitingForPrackResolve = undefined; + this.waitingForPrackReject = undefined; + } + /** + * Here we are rejecting the promise which in turn will cause + * the accept to fail and the session to transition to "terminated". + */ + prackNeverArrived() { + if (this.waitingForPrackReject) { + this.waitingForPrackReject(new _exceptions__WEBPACK_IMPORTED_MODULE_2__["SessionTerminatedError"]()); + } + this.waitingForPrackPromise = undefined; + this.waitingForPrackResolve = undefined; + this.waitingForPrackReject = undefined; + } +} + + +/***/ }), +/* 114 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Session", function() { return Session; }); +/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); +/* harmony import */ var _core_messages_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(32); +/* harmony import */ var _core_user_agent_core_allowed_methods__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(82); +/* harmony import */ var _bye__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(107); +/* harmony import */ var _emitter__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(108); +/* harmony import */ var _exceptions__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(3); +/* harmony import */ var _info__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(109); +/* harmony import */ var _message__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(115); +/* harmony import */ var _notification__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(116); +/* harmony import */ var _referral__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(117); +/* harmony import */ var _session_state__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(118); + + + + + + + + + + + +/** + * A session provides real time communication between one or more participants. + * + * @remarks + * The transport behaves in a deterministic manner according to the + * the state defined in {@link SessionState}. + * @public + */ +class Session { + /** + * Constructor. + * @param userAgent - User agent. See {@link UserAgent} for details. + * @internal + */ + constructor(userAgent, options = {}) { + /** True if there is an outgoing re-INVITE request outstanding. */ + this.pendingReinvite = false; + /** True if there is an incoming re-INVITE ACK request outstanding. */ + this.pendingReinviteAck = false; + /** Session state. */ + this._state = _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Initial; + this.delegate = options.delegate; + this._stateEventEmitter = new _emitter__WEBPACK_IMPORTED_MODULE_4__["EmitterImpl"](); + this._userAgent = userAgent; + } + /** + * Destructor. + */ + dispose() { + this.logger.log(`Session ${this.id} in state ${this._state} is being disposed`); + // Remove from the user agent's session collection + delete this.userAgent._sessions[this.id]; + // Dispose of dialog media + if (this._sessionDescriptionHandler) { + this._sessionDescriptionHandler.close(); + // TODO: The SDH needs to remain defined as it will be called after it is closed in cases + // where an answer/offer arrives while the session is being torn down. There are a variety + // of circumstances where this can happen - sending a BYE during a re-INVITE for example. + // The code is currently written such that it lazily makes a new SDH when it needs one + // and one is not yet defined. Thus if we undefined it here, it will currently make a + // new one which is out of sync and then never gets cleaned up. + // + // The downside of leaving it defined are that calls this closed SDH will continue to be + // made (think setDescription) and those should/will fail. These failures are handled, but + // it would be nice to have it all coded up in a way where having an undefined SDH where + // one is expected throws an error. + // + // this._sessionDescriptionHandler = undefined; + } + switch (this.state) { + case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Initial: + break; // the Inviter/Invitation sub class dispose method handles this case + case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Establishing: + break; // the Inviter/Invitation sub class dispose method handles this case + case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established: + return new Promise((resolve) => { + this._bye({ + // wait for the response to the BYE before resolving + onAccept: () => resolve(), + onRedirect: () => resolve(), + onReject: () => resolve() + }); + }); + case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminating: + break; // nothing to be done + case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated: + break; // nothing to be done + default: + throw new Error("Unknown state."); + } + return Promise.resolve(); + } + /** + * The asserted identity of the remote user. + */ + get assertedIdentity() { + return this._assertedIdentity; + } + /** + * The confirmed session dialog. + */ + get dialog() { + return this._dialog; + } + /** + * A unique identifier for this session. + */ + get id() { + return this._id; + } + /** + * The session being replace by this one. + */ + get replacee() { + return this._replacee; + } + /** + * Session description handler. + * @remarks + * If `this` is an instance of `Invitation`, + * `sessionDescriptionHandler` will be defined when the session state changes to "established". + * If `this` is an instance of `Inviter` and an offer was sent in the INVITE, + * `sessionDescriptionHandler` will be defined when the session state changes to "establishing". + * If `this` is an instance of `Inviter` and an offer was not sent in the INVITE, + * `sessionDescriptionHandler` will be defined when the session state changes to "established". + * Otherwise `undefined`. + */ + get sessionDescriptionHandler() { + return this._sessionDescriptionHandler; + } + /** + * Session description handler factory. + */ + get sessionDescriptionHandlerFactory() { + return this.userAgent.configuration.sessionDescriptionHandlerFactory; + } + /** + * SDH modifiers for the initial INVITE transaction. + * @remarks + * Used in all cases when handling the initial INVITE transaction as either UAC or UAS. + * May be set directly at anytime. + * May optionally be set via constructor option. + * May optionally be set via options passed to Inviter.invite() or Invitation.accept(). + */ + get sessionDescriptionHandlerModifiers() { + return this._sessionDescriptionHandlerModifiers || []; + } + set sessionDescriptionHandlerModifiers(modifiers) { + this._sessionDescriptionHandlerModifiers = modifiers.slice(); + } + /** + * SDH options for the initial INVITE transaction. + * @remarks + * Used in all cases when handling the initial INVITE transaction as either UAC or UAS. + * May be set directly at anytime. + * May optionally be set via constructor option. + * May optionally be set via options passed to Inviter.invite() or Invitation.accept(). + */ + get sessionDescriptionHandlerOptions() { + return this._sessionDescriptionHandlerOptions || {}; + } + set sessionDescriptionHandlerOptions(options) { + this._sessionDescriptionHandlerOptions = Object.assign({}, options); + } + /** + * SDH modifiers for re-INVITE transactions. + * @remarks + * Used in all cases when handling a re-INVITE transaction as either UAC or UAS. + * May be set directly at anytime. + * May optionally be set via constructor option. + * May optionally be set via options passed to Session.invite(). + */ + get sessionDescriptionHandlerModifiersReInvite() { + return this._sessionDescriptionHandlerModifiersReInvite || []; + } + set sessionDescriptionHandlerModifiersReInvite(modifiers) { + this._sessionDescriptionHandlerModifiersReInvite = modifiers.slice(); + } + /** + * SDH options for re-INVITE transactions. + * @remarks + * Used in all cases when handling a re-INVITE transaction as either UAC or UAS. + * May be set directly at anytime. + * May optionally be set via constructor option. + * May optionally be set via options passed to Session.invite(). + */ + get sessionDescriptionHandlerOptionsReInvite() { + return this._sessionDescriptionHandlerOptionsReInvite || {}; + } + set sessionDescriptionHandlerOptionsReInvite(options) { + this._sessionDescriptionHandlerOptionsReInvite = Object.assign({}, options); + } + /** + * Session state. + */ + get state() { + return this._state; + } + /** + * Session state change emitter. + */ + get stateChange() { + return this._stateEventEmitter; + } + /** + * The user agent. + */ + get userAgent() { + return this._userAgent; + } + /** + * End the {@link Session}. Sends a BYE. + * @param options - Options bucket. See {@link SessionByeOptions} for details. + */ + bye(options = {}) { + let message = "Session.bye() may only be called if established session."; + switch (this.state) { + case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Initial: + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (typeof this.cancel === "function") { + message += " However Inviter.invite() has not yet been called."; + message += " Perhaps you should have called Inviter.cancel()?"; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } + else if (typeof this.reject === "function") { + message += " However Invitation.accept() has not yet been called."; + message += " Perhaps you should have called Invitation.reject()?"; + } + break; + case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Establishing: + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (typeof this.cancel === "function") { + message += " However a dialog does not yet exist."; + message += " Perhaps you should have called Inviter.cancel()?"; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } + else if (typeof this.reject === "function") { + message += " However Invitation.accept() has not yet been called (or not yet resolved)."; + message += " Perhaps you should have called Invitation.reject()?"; + } + break; + case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established: { + const requestDelegate = options.requestDelegate; + const requestOptions = this.copyRequestOptions(options.requestOptions); + return this._bye(requestDelegate, requestOptions); + } + case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminating: + message += " However this session is already terminating."; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (typeof this.cancel === "function") { + message += " Perhaps you have already called Inviter.cancel()?"; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } + else if (typeof this.reject === "function") { + message += " Perhaps you have already called Session.bye()?"; + } + break; + case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated: + message += " However this session is already terminated."; + break; + default: + throw new Error("Unknown state"); + } + this.logger.error(message); + return Promise.reject(new Error(`Invalid session state ${this.state}`)); + } + /** + * Share {@link Info} with peer. Sends an INFO. + * @param options - Options bucket. See {@link SessionInfoOptions} for details. + */ + info(options = {}) { + // guard session state + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { + const message = "Session.info() may only be called if established session."; + this.logger.error(message); + return Promise.reject(new Error(`Invalid session state ${this.state}`)); + } + const requestDelegate = options.requestDelegate; + const requestOptions = this.copyRequestOptions(options.requestOptions); + return this._info(requestDelegate, requestOptions); + } + /** + * Renegotiate the session. Sends a re-INVITE. + * @param options - Options bucket. See {@link SessionInviteOptions} for details. + */ + invite(options = {}) { + this.logger.log("Session.invite"); + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { + return Promise.reject(new Error(`Invalid session state ${this.state}`)); + } + if (this.pendingReinvite) { + return Promise.reject(new _exceptions__WEBPACK_IMPORTED_MODULE_5__["RequestPendingError"]("Reinvite in progress. Please wait until complete, then try again.")); + } + this.pendingReinvite = true; + // Modifiers and options for initial INVITE transaction + if (options.sessionDescriptionHandlerModifiers) { + this.sessionDescriptionHandlerModifiersReInvite = options.sessionDescriptionHandlerModifiers; + } + if (options.sessionDescriptionHandlerOptions) { + this.sessionDescriptionHandlerOptionsReInvite = options.sessionDescriptionHandlerOptions; + } + const delegate = { + onAccept: (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 + const body = Object(_core__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); + this.pendingReinvite = false; + return; + } + if (options.withoutSdp) { + // INVITE without SDP - set remote offer and send an answer in the ACK + const answerOptions = { + sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptionsReInvite, + sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiersReInvite + }; + this.setOfferAndGetAnswer(body, answerOptions) + .then((answerBody) => { + response.ack({ body: answerBody }); + }) + .catch((error) => { + // No way to recover, so terminate session and mark as failed. + this.logger.error("Failed to handle offer in 2xx response to re-INVITE"); + this.logger.error(error.message); + if (this.state === _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated) { + // A BYE should not be sent if already terminated. + // For example, a BYE may be sent/received while re-INVITE is outstanding. + response.ack(); + } + else { + this.ackAndBye(response, 488, "Bad Media Description"); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); + } + }) + .then(() => { + this.pendingReinvite = false; + if (options.requestDelegate && options.requestDelegate.onAccept) { + options.requestDelegate.onAccept(response); + } + }); + } + else { + // INVITE with SDP - set remote answer and send an ACK + const answerOptions = { + sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptionsReInvite, + sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiersReInvite + }; + this.setAnswer(body, answerOptions) + .then(() => { + response.ack(); + }) + .catch((error) => { + // No way to recover, so terminate session and mark as failed. + this.logger.error("Failed to handle answer in 2xx response to re-INVITE"); + this.logger.error(error.message); + // A BYE should only be sent if session is not already terminated. + // For example, a BYE may be sent/received while re-INVITE is outstanding. + // The ACK needs to be sent regardless as it was not handled by the transaction. + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated) { + this.ackAndBye(response, 488, "Bad Media Description"); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); + } + else { + response.ack(); + } + }) + .then(() => { + this.pendingReinvite = false; + if (options.requestDelegate && options.requestDelegate.onAccept) { + options.requestDelegate.onAccept(response); + } + }); + } + }, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onProgress: (response) => { + return; + }, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onRedirect: (response) => { + return; + }, + onReject: (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((error) => { + // No way to recover, so terminate session and mark as failed. + this.logger.error("Failed to rollback offer on non-2xx response to re-INVITE"); + this.logger.error(error.message); + // A BYE should only be sent if session is not already terminated. + // For example, a BYE may be sent/received while re-INVITE is outstanding. + // Note that the ACK was already sent by the transaction, so just need to send BYE. + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated) { + if (!this.dialog) { + throw new Error("Dialog undefined."); + } + const extraHeaders = []; + extraHeaders.push("Reason: " + this.getReasonHeaderValue(500, "Internal Server Error")); + this.dialog.bye(undefined, { extraHeaders }); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); + } + }) + .then(() => { + if (options.requestDelegate && options.requestDelegate.onReject) { + options.requestDelegate.onReject(response); + } + }); + } + }, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onTrying: (response) => { + return; + } + }; + const requestOptions = options.requestOptions || {}; + requestOptions.extraHeaders = (requestOptions.extraHeaders || []).slice(); + requestOptions.extraHeaders.push("Allow: " + _core_user_agent_core_allowed_methods__WEBPACK_IMPORTED_MODULE_2__["AllowedMethods"].toString()); + requestOptions.extraHeaders.push("Contact: " + this._contact); + // Just send an INVITE with no sdp... + if (options.withoutSdp) { + if (!this.dialog) { + this.pendingReinvite = false; + throw new Error("Dialog undefined."); + } + return Promise.resolve(this.dialog.invite(delegate, requestOptions)); + } + // Get an offer and send it in an INVITE + const offerOptions = { + sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptionsReInvite, + sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiersReInvite + }; + return this.getOffer(offerOptions) + .then((offerBody) => { + if (!this.dialog) { + this.pendingReinvite = false; + throw new Error("Dialog undefined."); + } + requestOptions.body = offerBody; + return this.dialog.invite(delegate, requestOptions); + }) + .catch((error) => { + this.logger.error(error.message); + this.logger.error("Failed to send re-INVITE"); + this.pendingReinvite = false; + throw error; + }); + } + /** + * Deliver a {@link Message}. Sends a MESSAGE. + * @param options - Options bucket. See {@link SessionMessageOptions} for details. + */ + message(options = {}) { + // guard session state + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { + const message = "Session.message() may only be called if established session."; + this.logger.error(message); + return Promise.reject(new Error(`Invalid session state ${this.state}`)); + } + const requestDelegate = options.requestDelegate; + const requestOptions = this.copyRequestOptions(options.requestOptions); + return this._message(requestDelegate, requestOptions); + } + /** + * Proffer a {@link Referral}. Send a REFER. + * @param referTo - The referral target. If a `Session`, a REFER w/Replaces is sent. + * @param options - Options bucket. See {@link SessionReferOptions} for details. + */ + refer(referTo, options = {}) { + // guard session state + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { + const message = "Session.refer() may only be called if established session."; + this.logger.error(message); + return Promise.reject(new Error(`Invalid session state ${this.state}`)); + } + const requestDelegate = options.requestDelegate; + const requestOptions = this.copyRequestOptions(options.requestOptions); + requestOptions.extraHeaders = requestOptions.extraHeaders + ? requestOptions.extraHeaders.concat(this.referExtraHeaders(this.referToString(referTo))) + : this.referExtraHeaders(this.referToString(referTo)); + return this._refer(options.onNotify, requestDelegate, requestOptions); + } + /** + * Send BYE. + * @param delegate - Request delegate. + * @param options - Request options bucket. + * @internal + */ + _bye(delegate, options) { + // Using core session dialog + if (!this.dialog) { + return Promise.reject(new Error("Session dialog undefined.")); + } + const 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__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Initial: + throw new Error(`Invalid dialog state ${dialog.sessionState}`); + case _core__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Early: // Implementation choice - not sending BYE for early dialogs. + throw new Error(`Invalid dialog state ${dialog.sessionState}`); + case _core__WEBPACK_IMPORTED_MODULE_0__["SessionState"].AckWait: { + // This state only occurs if we are the callee. + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminating); // We're terminating + return new Promise((resolve) => { + dialog.delegate = { + // When ACK shows up, say BYE. + onAck: () => { + const request = dialog.bye(delegate, options); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); + resolve(request); + return Promise.resolve(); + }, + // Or the server transaction times out before the ACK arrives. + onAckTimeout: () => { + const request = dialog.bye(delegate, options); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); + resolve(request); + } + }; + }); + } + case _core__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Confirmed: { + const request = dialog.bye(delegate, options); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); + return Promise.resolve(request); + } + case _core__WEBPACK_IMPORTED_MODULE_0__["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 + */ + _info(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 MESSAGE. + * @param delegate - Request delegate. + * @param options - Request options bucket. + * @internal + */ + _message(delegate, options) { + // Using core session dialog + if (!this.dialog) { + return Promise.reject(new Error("Session dialog undefined.")); + } + return Promise.resolve(this.dialog.message(delegate, options)); + } + /** + * Send REFER. + * @param onNotify - Notification callback. + * @param delegate - Request delegate. + * @param options - Request options bucket. + * @internal + */ + _refer(onNotify, delegate, options) { + // Using core session dialog + if (!this.dialog) { + return Promise.reject(new Error("Session dialog undefined.")); + } + // If set, deliver any in-dialog NOTIFY requests here... + this.onNotify = onNotify; + return Promise.resolve(this.dialog.refer(delegate, options)); + } + /** + * 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 send a BYE. + * Note that the BYE is sent in the dialog associated with the response + * which is not necessarily `this.dialog`. And, accordingly, the + * session state is not transitioned to terminated and session is not closed. + * @param inviteResponse - The response causing the error. + * @param statusCode - Status code for he reason phrase. + * @param reasonPhrase - Reason phrase for the BYE. + * @internal + */ + ackAndBye(response, statusCode, reasonPhrase) { + response.ack(); + const extraHeaders = []; + if (statusCode) { + extraHeaders.push("Reason: " + this.getReasonHeaderValue(statusCode, reasonPhrase)); + } + // Using the dialog session associate with the response (which might not be this.dialog) + response.session.bye(undefined, { extraHeaders }); + } + /** + * Handle in dialog ACK request. + * @internal + */ + onAckRequest(request) { + this.logger.log("Session.onAckRequest"); + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established && this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminating) { + this.logger.error(`ACK received while in state ${this.state}, dropping request`); + return Promise.resolve(); + } + const dialog = this.dialog; + if (!dialog) { + throw new Error("Dialog undefined."); + } + // if received answer in ACK. + const answerOptions = { + sessionDescriptionHandlerOptions: this.pendingReinviteAck + ? this.sessionDescriptionHandlerOptionsReInvite + : this.sessionDescriptionHandlerOptions, + sessionDescriptionHandlerModifiers: this.pendingReinviteAck + ? this._sessionDescriptionHandlerModifiersReInvite + : this._sessionDescriptionHandlerModifiers + }; + // reset pending ACK flag + this.pendingReinviteAck = false; + switch (dialog.signalingState) { + case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Initial: { + // State should never be reached as first reliable response must have answer/offer. + // So we must have never has sent an offer. + this.logger.error(`Invalid signaling state ${dialog.signalingState}.`); + const extraHeaders = ["Reason: " + this.getReasonHeaderValue(488, "Bad Media Description")]; + dialog.bye(undefined, { extraHeaders }); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); + return Promise.resolve(); + } + case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Stable: { + // State we should be in. + // Either the ACK has the answer that got us here, or we were in this state prior to the ACK. + const body = Object(_core__WEBPACK_IMPORTED_MODULE_0__["getBody"])(request.message); + // If the ACK doesn't have an answer, nothing to be done. + if (!body) { + return Promise.resolve(); + } + if (body.contentDisposition === "render") { + this._renderbody = body.content; + this._rendertype = body.contentType; + return Promise.resolve(); + } + if (body.contentDisposition !== "session") { + return Promise.resolve(); + } + return this.setAnswer(body, answerOptions).catch((error) => { + this.logger.error(error.message); + const extraHeaders = ["Reason: " + this.getReasonHeaderValue(488, "Bad Media Description")]; + dialog.bye(undefined, { extraHeaders }); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); + }); + } + case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].HaveLocalOffer: { + // State should never be reached as local offer would be answered by this ACK. + // So we must have received an ACK without an answer. + this.logger.error(`Invalid signaling state ${dialog.signalingState}.`); + const extraHeaders = ["Reason: " + this.getReasonHeaderValue(488, "Bad Media Description")]; + dialog.bye(undefined, { extraHeaders }); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); + return Promise.resolve(); + } + case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].HaveRemoteOffer: { + // State should never be reached as remote offer would be answered in first reliable response. + // So we must have never has sent an answer. + this.logger.error(`Invalid signaling state ${dialog.signalingState}.`); + const extraHeaders = ["Reason: " + this.getReasonHeaderValue(488, "Bad Media Description")]; + dialog.bye(undefined, { extraHeaders }); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); + return Promise.resolve(); + } + case _core__WEBPACK_IMPORTED_MODULE_0__["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 + */ + onByeRequest(request) { + this.logger.log("Session.onByeRequest"); + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { + this.logger.error(`BYE received while in state ${this.state}, dropping request`); + return; + } + if (this.delegate && this.delegate.onBye) { + const bye = new _bye__WEBPACK_IMPORTED_MODULE_3__["Bye"](request); + this.delegate.onBye(bye); + } + else { + request.accept(); + } + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); + } + /** + * Handle in dialog INFO request. + * @internal + */ + onInfoRequest(request) { + this.logger.log("Session.onInfoRequest"); + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { + this.logger.error(`INFO received while in state ${this.state}, dropping request`); + return; + } + if (this.delegate && this.delegate.onInfo) { + const info = new _info__WEBPACK_IMPORTED_MODULE_6__["Info"](request); + this.delegate.onInfo(info); + } + else { + // FIXME: TODO: We should reject request... + // + // 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. + // https://tools.ietf.org/html/rfc6086#section-4.2.2 + request.accept(); + } + } + /** + * Handle in dialog INVITE request. + * @internal + */ + onInviteRequest(request) { + this.logger.log("Session.onInviteRequest"); + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { + this.logger.error(`INVITE received while in state ${this.state}, dropping request`); + return; + } + // set pending ACK flag + this.pendingReinviteAck = true; + // 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. + const extraHeaders = ["Contact: " + this._contact]; + // Handle P-Asserted-Identity + if (request.message.hasHeader("P-Asserted-Identity")) { + const header = request.message.getHeader("P-Asserted-Identity"); + if (!header) { + throw new Error("Header undefined."); + } + this._assertedIdentity = _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].nameAddrHeaderParse(header); + } + const options = { + sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptionsReInvite, + sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiersReInvite + }; + this.generateResponseOfferAnswerInDialog(options) + .then((body) => { + const outgoingResponse = request.accept({ statusCode: 200, extraHeaders, body }); + if (this.delegate && this.delegate.onInvite) { + this.delegate.onInvite(request.message, outgoingResponse.message, 200); + } + }) + .catch((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__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Stable) { + const 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(() => { + const outgoingResponse = request.reject({ statusCode: 488 }); // Not Acceptable Here + if (this.delegate && this.delegate.onInvite) { + this.delegate.onInvite(request.message, outgoingResponse.message, 488); + } + }) + .catch((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"); + const outgoingResponse = request.reject({ statusCode: 488 }); // Not Acceptable Here + // A BYE should only be sent if session is not already terminated. + // For example, a BYE may be sent/received while re-INVITE is outstanding. + // Note that the ACK was already sent by the transaction, so just need to send BYE. + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated) { + if (!this.dialog) { + throw new Error("Dialog undefined."); + } + const extraHeadersBye = []; + extraHeadersBye.push("Reason: " + this.getReasonHeaderValue(500, "Internal Server Error")); + this.dialog.bye(undefined, { extraHeaders }); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); + } + if (this.delegate && this.delegate.onInvite) { + this.delegate.onInvite(request.message, outgoingResponse.message, 488); + } + }); + }); + } + /** + * Handle in dialog MESSAGE request. + * @internal + */ + onMessageRequest(request) { + this.logger.log("Session.onMessageRequest"); + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { + this.logger.error(`MESSAGE received while in state ${this.state}, dropping request`); + return; + } + if (this.delegate && this.delegate.onMessage) { + const message = new _message__WEBPACK_IMPORTED_MODULE_7__["Message"](request); + this.delegate.onMessage(message); + } + else { + request.accept(); + } + } + /** + * Handle in dialog NOTIFY request. + * @internal + */ + onNotifyRequest(request) { + this.logger.log("Session.onNotifyRequest"); + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { + this.logger.error(`NOTIFY received while in state ${this.state}, dropping request`); + return; + } + // If this a NOTIFY associated with the progress of a REFER, + // look to delegate handling to the associated callback. + if (this.onNotify) { + const notification = new _notification__WEBPACK_IMPORTED_MODULE_8__["Notification"](request); + this.onNotify(notification); + return; + } + // Otherwise accept the NOTIFY. + if (this.delegate && this.delegate.onNotify) { + const notification = new _notification__WEBPACK_IMPORTED_MODULE_8__["Notification"](request); + this.delegate.onNotify(notification); + } + else { + request.accept(); + } + } + /** + * Handle in dialog PRACK request. + * @internal + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onPrackRequest(request) { + this.logger.log("Session.onPrackRequest"); + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["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 + */ + onReferRequest(request) { + this.logger.log("Session.onReferRequest"); + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { + this.logger.error(`REFER received while in state ${this.state}, dropping request`); + return; + } + // 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 + if (!request.message.hasHeader("refer-to")) { + this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting."); + request.reject(); + return; + } + const referral = new _referral__WEBPACK_IMPORTED_MODULE_9__["Referral"](request, this); + if (this.delegate && this.delegate.onRefer) { + this.delegate.onRefer(referral); + } + else { + this.logger.log("No delegate available to handle REFER, automatically accepting and following."); + referral + .accept() + .then(() => referral.makeInviter(this._referralInviterOptions).invite()) + .catch((error) => { + // FIXME: logging and eating error... + this.logger.error(error.message); + }); + } + } + /** + * 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 + */ + generateResponseOfferAnswer(request, options) { + if (this.dialog) { + return this.generateResponseOfferAnswerInDialog(options); + } + const body = Object(_core__WEBPACK_IMPORTED_MODULE_0__["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 + */ + generateResponseOfferAnswerInDialog(options) { + if (!this.dialog) { + throw new Error("Dialog undefined."); + } + switch (this.dialog.signalingState) { + case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Initial: + return this.getOffer(options); + case _core__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_0__["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__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { + return Promise.resolve(undefined); + } + // In dialog INVITE without offer, get an offer for the response. + return this.getOffer(options); + case _core__WEBPACK_IMPORTED_MODULE_0__["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 + */ + getOffer(options) { + const sdh = this.setupSessionDescriptionHandler(); + const sdhOptions = options.sessionDescriptionHandlerOptions; + const sdhModifiers = options.sessionDescriptionHandlerModifiers; + // This is intentionally written very defensively. Don't trust SDH to behave. + try { + return sdh + .getDescription(sdhOptions, sdhModifiers) + .then((bodyAndContentType) => Object(_core__WEBPACK_IMPORTED_MODULE_0__["fromBodyLegacy"])(bodyAndContentType)) + .catch((error) => { + // don't trust SDH to reject with Error + this.logger.error("Session.getOffer: SDH getDescription rejected..."); + const e = error instanceof Error ? error : new Error("Session.getOffer unknown error."); + this.logger.error(e.message); + throw e; + }); + } + catch (error) { + // don't trust SDH to throw an Error + this.logger.error("Session.getOffer: SDH getDescription threw..."); + const e = error instanceof Error ? error : new Error(error); + this.logger.error(e.message); + return Promise.reject(e); + } + } + /** + * Rollback local/remote offer. + * @internal + */ + rollbackOffer() { + const sdh = this.setupSessionDescriptionHandler(); + if (sdh.rollbackDescription === undefined) { + return Promise.resolve(); + } + // This is intentionally written very defensively. Don't trust SDH to behave. + try { + return sdh.rollbackDescription().catch((error) => { + // don't trust SDH to reject with Error + this.logger.error("Session.rollbackOffer: SDH rollbackDescription rejected..."); + const e = error instanceof Error ? error : new Error("Session.rollbackOffer unknown error."); + this.logger.error(e.message); + throw e; + }); + } + catch (error) { + // don't trust SDH to throw an Error + this.logger.error("Session.rollbackOffer: SDH rollbackDescription threw..."); + const e = error instanceof Error ? error : new Error(error); + this.logger.error(e.message); + return Promise.reject(e); + } + } + /** + * Set remote answer. + * @internal + */ + setAnswer(answer, options) { + const sdh = this.setupSessionDescriptionHandler(); + const sdhOptions = options.sessionDescriptionHandlerOptions; + const sdhModifiers = options.sessionDescriptionHandlerModifiers; + // This is intentionally written very defensively. Don't trust SDH to behave. + try { + if (!sdh.hasDescription(answer.contentType)) { + return Promise.reject(new _exceptions__WEBPACK_IMPORTED_MODULE_5__["ContentTypeUnsupportedError"]()); + } + } + catch (error) { + this.logger.error("Session.setAnswer: SDH hasDescription threw..."); + const e = error instanceof Error ? error : new Error(error); + this.logger.error(e.message); + return Promise.reject(e); + } + try { + return sdh.setDescription(answer.content, sdhOptions, sdhModifiers).catch((error) => { + // don't trust SDH to reject with Error + this.logger.error("Session.setAnswer: SDH setDescription rejected..."); + const e = error instanceof Error ? error : new Error("Session.setAnswer unknown error."); + this.logger.error(e.message); + throw e; + }); + } + catch (error) { + // don't trust SDH to throw an Error + this.logger.error("Session.setAnswer: SDH setDescription threw..."); + const e = error instanceof Error ? error : new Error(error); + this.logger.error(e.message); + return Promise.reject(e); + } + } + /** + * Set remote offer and get local answer. + * @internal + */ + setOfferAndGetAnswer(offer, options) { + const sdh = this.setupSessionDescriptionHandler(); + const sdhOptions = options.sessionDescriptionHandlerOptions; + const sdhModifiers = options.sessionDescriptionHandlerModifiers; + // This is intentionally written very defensively. Don't trust SDH to behave. + try { + if (!sdh.hasDescription(offer.contentType)) { + return Promise.reject(new _exceptions__WEBPACK_IMPORTED_MODULE_5__["ContentTypeUnsupportedError"]()); + } + } + catch (error) { + this.logger.error("Session.setOfferAndGetAnswer: SDH hasDescription threw..."); + const e = error instanceof Error ? error : new Error(error); + this.logger.error(e.message); + return Promise.reject(e); + } + try { + return sdh + .setDescription(offer.content, sdhOptions, sdhModifiers) + .then(() => sdh.getDescription(sdhOptions, sdhModifiers)) + .then((bodyAndContentType) => Object(_core__WEBPACK_IMPORTED_MODULE_0__["fromBodyLegacy"])(bodyAndContentType)) + .catch((error) => { + // don't trust SDH to reject with Error + this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription rejected..."); + const e = error instanceof Error ? error : new Error("Session.setOfferAndGetAnswer unknown error."); + this.logger.error(e.message); + throw e; + }); + } + catch (error) { + // don't trust SDH to throw an Error + this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription threw..."); + const e = error instanceof Error ? error : new Error(error); + this.logger.error(e.message); + return Promise.reject(e); + } + } + /** + * SDH for confirmed dialog. + * @internal + */ + setSessionDescriptionHandler(sdh) { + if (this._sessionDescriptionHandler) { + throw new Error("Session description handler defined."); + } + this._sessionDescriptionHandler = sdh; + } + /** + * SDH for confirmed dialog. + * @internal + */ + setupSessionDescriptionHandler() { + var _a; + if (this._sessionDescriptionHandler) { + return this._sessionDescriptionHandler; + } + this._sessionDescriptionHandler = this.sessionDescriptionHandlerFactory(this, this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions); + if ((_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onSessionDescriptionHandler) { + this.delegate.onSessionDescriptionHandler(this._sessionDescriptionHandler, false); + } + return this._sessionDescriptionHandler; + } + /** + * Transition session state. + * @internal + */ + stateTransition(newState) { + const invalidTransition = () => { + throw new Error(`Invalid state transition from ${this._state} to ${newState}`); + }; + // Validate transition + switch (this._state) { + case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Initial: + if (newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Establishing && + newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established && + newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminating && + newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated) { + invalidTransition(); + } + break; + case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Establishing: + if (newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established && + newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminating && + newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated) { + invalidTransition(); + } + break; + case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established: + if (newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminating && newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated) { + invalidTransition(); + } + break; + case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminating: + if (newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated) { + invalidTransition(); + } + break; + case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated: + invalidTransition(); + break; + default: + throw new Error("Unrecognized state."); + } + // Transition + this._state = newState; + this.logger.log(`Session ${this.id} transitioned to state ${this._state}`); + this._stateEventEmitter.emit(this._state); + // Dispose + if (newState === _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated) { + this.dispose(); + } + } + copyRequestOptions(requestOptions = {}) { + const extraHeaders = requestOptions.extraHeaders ? requestOptions.extraHeaders.slice() : undefined; + const body = requestOptions.body + ? { + contentDisposition: requestOptions.body.contentDisposition || "render", + contentType: requestOptions.body.contentType || "text/plain", + content: requestOptions.body.content || "" + } + : undefined; + return { + extraHeaders, + body + }; + } + getReasonHeaderValue(code, reason) { + const cause = code; + let text = Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["getReasonPhrase"])(code); + if (!text && reason) { + text = reason; + } + return "SIP;cause=" + cause + ';text="' + text + '"'; + } + referExtraHeaders(referTo) { + const extraHeaders = []; + extraHeaders.push("Referred-By: <" + this.userAgent.configuration.uri + ">"); + extraHeaders.push("Contact: " + this._contact); + extraHeaders.push("Allow: " + ["ACK", "CANCEL", "INVITE", "MESSAGE", "BYE", "OPTIONS", "INFO", "NOTIFY", "REFER"].toString()); + extraHeaders.push("Refer-To: " + referTo); + return extraHeaders; + } + referToString(target) { + let referTo; + if (target instanceof _core__WEBPACK_IMPORTED_MODULE_0__["URI"]) { + // REFER without Replaces (Blind Transfer) + referTo = target.toString(); + } + else { + // REFER with Replaces (Attended Transfer) + if (!target.dialog) { + throw new Error("Dialog undefined."); + } + const displayName = target.remoteIdentity.friendlyName; + const remoteTarget = target.dialog.remoteTarget.toString(); + const callId = target.dialog.callId; + const remoteTag = target.dialog.remoteTag; + const localTag = target.dialog.localTag; + const replaces = encodeURIComponent(`${callId};to-tag=${remoteTag};from-tag=${localTag}`); + referTo = `"${displayName}" <${remoteTarget}?Replaces=${replaces}>`; + } + return referTo; + } +} + + +/***/ }), +/* 115 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Message", function() { return Message; }); +/** + * A received message (incoming MESSAGE). + * @public + */ +class Message { + /** @internal */ + constructor(incomingMessageRequest) { + this.incomingMessageRequest = incomingMessageRequest; + } + /** Incoming MESSAGE request message. */ + get request() { + return this.incomingMessageRequest.message; + } + /** Accept the request. */ + accept(options) { + this.incomingMessageRequest.accept(options); + return Promise.resolve(); + } + /** Reject the request. */ + reject(options) { + this.incomingMessageRequest.reject(options); + return Promise.resolve(); + } +} + + +/***/ }), +/* 116 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Notification", function() { return Notification; }); +/** + * A notification of an event (incoming NOTIFY). + * @public + */ +class Notification { + /** @internal */ + constructor(incomingNotifyRequest) { + this.incomingNotifyRequest = incomingNotifyRequest; + } + /** Incoming NOTIFY request message. */ + get request() { + return this.incomingNotifyRequest.message; + } + /** Accept the request. */ + accept(options) { + this.incomingNotifyRequest.accept(options); + return Promise.resolve(); + } + /** Reject the request. */ + reject(options) { + this.incomingNotifyRequest.reject(options); + return Promise.resolve(); + } +} + + +/***/ }), +/* 117 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Referral", function() { return Referral; }); +/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); + +/** + * A request to establish a {@link Session} elsewhere (incoming REFER). + * @public + */ +class Referral { + /** @internal */ + constructor(incomingReferRequest, session) { + this.incomingReferRequest = incomingReferRequest; + this.session = session; + } + get referTo() { + const referTo = this.incomingReferRequest.message.parseHeader("refer-to"); + if (!(referTo instanceof _core__WEBPACK_IMPORTED_MODULE_0__["NameAddrHeader"])) { + throw new Error("Failed to parse Refer-To header."); + } + return referTo; + } + get referredBy() { + return this.incomingReferRequest.message.getHeader("referred-by"); + } + get replaces() { + return this.referTo.uri.getHeader("replaces"); + } + /** Incoming REFER request message. */ + get request() { + return this.incomingReferRequest.message; + } + /** Accept the request. */ + accept(options = { statusCode: 202 }) { + this.incomingReferRequest.accept(options); + return Promise.resolve(); + } + /** Reject the request. */ + reject(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. + */ + makeInviter(options) { + if (this.inviter) { + return this.inviter; + } + const targetURI = this.referTo.uri.clone(); + targetURI.clearHeaders(); + options = options || {}; + const extraHeaders = (options.extraHeaders || []).slice(); + const replaces = this.replaces; + if (replaces) { + // decodeURIComponent is a holdover from 2c086eb4. Not sure that it is actually necessary + extraHeaders.push("Replaces: " + decodeURIComponent(replaces)); + } + const 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; + } +} + + +/***/ }), +/* 118 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SessionState", function() { return SessionState; }); +/** + * {@link Session} state. + * + * @remarks + * The {@link Session} behaves in a deterministic manner according to the following + * Finite State Machine (FSM). + * ```txt + * ___________________________________________________________ + * | ____________________________________________ | + * | | ____________________________ | | + * Session | | | v v v + * Constructed -> Initial -> Establishing -> Established -> Terminating -> Terminated + * | |___________________________^ ^ + * |_______________________________________________| + * ``` + * @public + */ +var SessionState; +(function (SessionState) { + /** + * If `Inviter`, INVITE not sent yet. + * If `Invitation`, received INVITE (but no final response sent yet). + */ + SessionState["Initial"] = "Initial"; + /** + * If `Inviter`, sent INVITE and waiting for a final response. + * If `Invitation`, received INVITE and attempting to send 200 final response (but has not sent it yet). + */ + SessionState["Establishing"] = "Establishing"; + /** + * If `Inviter`, sent INVITE and received 200 final response and sent ACK. + * If `Invitation`, received INVITE and sent 200 final response. + */ + SessionState["Established"] = "Established"; + /** + * If `Inviter`, sent INVITE, sent CANCEL and now waiting for 487 final response to ACK (or 200 to ACK & BYE). + * If `Invitation`, received INVITE, sent 200 final response and now waiting on ACK and upon receipt will attempt BYE + * (as the protocol specification requires, before sending a BYE we must receive the ACK - so we are waiting). + */ + SessionState["Terminating"] = "Terminating"; + /** + * If `Inviter`, sent INVITE and received non-200 final response (or sent/received BYE after receiving 200). + * If `Invitation`, received INVITE and sent non-200 final response (or sent/received BYE after sending 200). + */ + SessionState["Terminated"] = "Terminated"; +})(SessionState || (SessionState = {})); + + +/***/ }), +/* 119 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SIPExtension", function() { return SIPExtension; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UserAgentRegisteredOptionTags", function() { return UserAgentRegisteredOptionTags; }); +/** + * SIP extension support level. + * @public + */ +var SIPExtension; +(function (SIPExtension) { + SIPExtension["Required"] = "Required"; + SIPExtension["Supported"] = "Supported"; + SIPExtension["Unsupported"] = "Unsupported"; +})(SIPExtension || (SIPExtension = {})); +/** + * SIP Option Tags + * @remarks + * http://www.iana.org/assignments/sip-parameters/sip-parameters.xhtml#sip-parameters-4 + * @public + */ +const 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 +}; + + +/***/ }), +/* 120 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 121 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 122 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 123 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Inviter", function() { return Inviter; }); +/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); +/* harmony import */ var _core_messages_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(32); +/* harmony import */ var _session__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(114); +/* harmony import */ var _session_state__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(118); +/* harmony import */ var _user_agent_options__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(119); + + + + + +/** + * An inviter offers to establish a {@link Session} (outgoing INVITE). + * @public + */ +class Inviter extends _session__WEBPACK_IMPORTED_MODULE_2__["Session"] { + /** + * 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, targetURI, options = {}) { + super(userAgent, options); + /** True if dispose() has been called. */ + this.disposed = false; + /** True if early media use is enabled. */ + this.earlyMedia = false; + /** The early media session description handlers. */ + this.earlyMediaSessionDescriptionHandlers = new Map(); + /** True if cancel() was called. */ + this.isCanceled = false; + /** True if initial INVITE without SDP. */ + this.inviteWithoutSdp = false; + this.logger = userAgent.getLogger("sip.Inviter"); + // Early media + this.earlyMedia = options.earlyMedia !== undefined ? options.earlyMedia : this.earlyMedia; + // From tag + this.fromTag = Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["newTag"])(); + // Invite without SDP + this.inviteWithoutSdp = options.inviteWithoutSdp !== undefined ? options.inviteWithoutSdp : this.inviteWithoutSdp; + // Inviter options (could do better copying these options) + const inviterOptions = Object.assign({}, options); + inviterOptions.params = Object.assign({}, options.params); + // Anonymous call + const anonymous = options.anonymous || false; + // Contact + const contact = userAgent.contact.toString({ + anonymous, + // Do not add ;ob in initial forming dialog requests if the + // registration over the current connection got a GRUU URI. + outbound: anonymous ? !userAgent.contact.tempGruu : !userAgent.contact.pubGruu + }); + // FIXME: TODO: We should not be parsing URIs here as if it fails we have to throw an exception + // which is not something we want our constructor to do. URIs should be passed in as params. + // URIs + if (anonymous && userAgent.configuration.uri) { + inviterOptions.params.fromDisplayName = "Anonymous"; + inviterOptions.params.fromUri = "sip:anonymous@anonymous.invalid"; + } + let fromURI = userAgent.userAgentCore.configuration.aor; + if (inviterOptions.params.fromUri) { + fromURI = + typeof inviterOptions.params.fromUri === "string" + ? _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].URIParse(inviterOptions.params.fromUri) + : inviterOptions.params.fromUri; + } + if (!fromURI) { + throw new TypeError("Invalid from URI: " + inviterOptions.params.fromUri); + } + let toURI = targetURI; + if (inviterOptions.params.toUri) { + toURI = + typeof inviterOptions.params.toUri === "string" + ? _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].URIParse(inviterOptions.params.toUri) + : inviterOptions.params.toUri; + } + if (!toURI) { + throw new TypeError("Invalid to URI: " + inviterOptions.params.toUri); + } + // Params + const messageOptions = Object.assign({}, inviterOptions.params); + messageOptions.fromTag = this.fromTag; + // Extra headers + const extraHeaders = (inviterOptions.extraHeaders || []).slice(); + if (anonymous && userAgent.configuration.uri) { + extraHeaders.push("P-Preferred-Identity: " + userAgent.configuration.uri.toString()); + extraHeaders.push("Privacy: id"); + } + extraHeaders.push("Contact: " + contact); + extraHeaders.push("Allow: " + ["ACK", "CANCEL", "INVITE", "MESSAGE", "BYE", "OPTIONS", "INFO", "NOTIFY", "REFER"].toString()); + if (userAgent.configuration.sipExtension100rel === _user_agent_options__WEBPACK_IMPORTED_MODULE_4__["SIPExtension"].Required) { + extraHeaders.push("Require: 100rel"); + } + if (userAgent.configuration.sipExtensionReplaces === _user_agent_options__WEBPACK_IMPORTED_MODULE_4__["SIPExtension"].Required) { + extraHeaders.push("Require: replaces"); + } + inviterOptions.extraHeaders = extraHeaders; + // Body + const body = undefined; + // Make initial outgoing request message + this.outgoingRequestMessage = userAgent.userAgentCore.makeOutgoingRequestMessage(_core__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE, targetURI, fromURI, toURI, messageOptions, extraHeaders, body); + // Session parent properties + this._contact = contact; + this._referralInviterOptions = inviterOptions; + this._renderbody = options.renderbody; + this._rendertype = options.rendertype; + // Modifiers and options for initial INVITE transaction + if (options.sessionDescriptionHandlerModifiers) { + this.sessionDescriptionHandlerModifiers = options.sessionDescriptionHandlerModifiers; + } + if (options.sessionDescriptionHandlerOptions) { + this.sessionDescriptionHandlerOptions = options.sessionDescriptionHandlerOptions; + } + // Modifiers and options for re-INVITE transactions + if (options.sessionDescriptionHandlerModifiersReInvite) { + this.sessionDescriptionHandlerModifiersReInvite = options.sessionDescriptionHandlerModifiersReInvite; + } + if (options.sessionDescriptionHandlerOptionsReInvite) { + this.sessionDescriptionHandlerOptionsReInvite = options.sessionDescriptionHandlerOptionsReInvite; + } + // Identifier + this._id = this.outgoingRequestMessage.callId + this.fromTag; + // Add to the user agent's session collection. + this.userAgent._sessions[this._id] = this; + } + /** + * Destructor. + */ + dispose() { + // Only run through this once. It can and does get called multiple times + // depending on the what the sessions state is when first called. + // For example, if called when "establishing" it will be called again + // at least once when the session transitions to "terminated". + // Regardless, running through this more than once is pointless. + if (this.disposed) { + return Promise.resolve(); + } + this.disposed = true; + // Dispose of early dialog media + this.disposeEarlyMedia(); + // If the final response for the initial INVITE not yet been received, cancel it + switch (this.state) { + case _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Initial: + return this.cancel().then(() => super.dispose()); + case _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Establishing: + return this.cancel().then(() => super.dispose()); + case _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Established: + return super.dispose(); + case _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminating: + return super.dispose(); + case _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated: + return super.dispose(); + default: + throw new Error("Unknown state."); + } + } + /** + * Initial outgoing INVITE request message body. + */ + get body() { + return this.outgoingRequestMessage.body; + } + /** + * The identity of the local user. + */ + get localIdentity() { + return this.outgoingRequestMessage.from; + } + /** + * The identity of the remote user. + */ + get remoteIdentity() { + return this.outgoingRequestMessage.to; + } + /** + * Initial outgoing INVITE request message. + */ + get request() { + return this.outgoingRequestMessage; + } + /** + * Cancels the INVITE request. + * + * @remarks + * Sends a CANCEL request. + * Resolves once the response sent, otherwise rejects. + * + * After sending a CANCEL request the expectation is that a 487 final response + * will be received for the INVITE. However a 200 final response to the INVITE + * may nonetheless arrive (it's a race between the CANCEL reaching the UAS before + * the UAS sends a 200) in which case an ACK & BYE will be sent. The net effect + * is that this method will terminate the session regardless of the race. + * @param options - Options bucket. + */ + cancel(options = {}) { + this.logger.log("Inviter.cancel"); + // validate state + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Initial && this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Establishing) { + const error = new Error(`Invalid session state ${this.state}`); + this.logger.error(error.message); + return Promise.reject(error); + } + // flag canceled + this.isCanceled = true; + // transition state + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminating); + // helper function + function getCancelReason(code, reason) { + if ((code && code < 200) || code > 699) { + throw new TypeError("Invalid statusCode: " + code); + } + else if (code) { + const cause = code; + const text = Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["getReasonPhrase"])(code) || reason; + return "SIP;cause=" + cause + ';text="' + text + '"'; + } + } + if (this.outgoingInviteRequest) { + // the CANCEL may not be respected by peer(s), so don't transition to terminated + let cancelReason; + if (options.statusCode && options.reasonPhrase) { + cancelReason = getCancelReason(options.statusCode, options.reasonPhrase); + } + this.outgoingInviteRequest.cancel(cancelReason, options); + } + else { + this.logger.warn("Canceled session before INVITE was sent"); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["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 behavior 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 behavior of the SIP + * servers being utilized is configured to disallow forking. + */ + invite(options = {}) { + this.logger.log("Inviter.invite"); + // validate state + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Initial) { + // re-invite + return super.invite(options); + } + // Modifiers and options for initial INVITE transaction + if (options.sessionDescriptionHandlerModifiers) { + this.sessionDescriptionHandlerModifiers = options.sessionDescriptionHandlerModifiers; + } + if (options.sessionDescriptionHandlerOptions) { + this.sessionDescriptionHandlerOptions = options.sessionDescriptionHandlerOptions; + } + // just send an INVITE with no sdp... + if (options.withoutSdp || this.inviteWithoutSdp) { + if (this._renderbody && this._rendertype) { + this.outgoingRequestMessage.body = { contentType: this._rendertype, body: this._renderbody }; + } + // transition state + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Establishing); + return Promise.resolve(this.sendInvite(options)); + } + // get an offer and send it in an INVITE + const offerOptions = { + sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers, + sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions + }; + return this.getOffer(offerOptions) + .then((body) => { + this.outgoingRequestMessage.body = { body: body.content, contentType: body.contentType }; + // transition state + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Establishing); + return this.sendInvite(options); + }) + .catch((error) => { + this.logger.log(error.message); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); + 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 + */ + sendInvite(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 + // 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 environments 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.outgoingRequestMessage, { + onAccept: (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__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); + return; + } + this.notifyReferer(inviteResponse); + this.onAccept(inviteResponse) + .then(() => { + this.disposeEarlyMedia(); + }) + .catch(() => { + this.disposeEarlyMedia(); + }) + .then(() => { + if (options.requestDelegate && options.requestDelegate.onAccept) { + options.requestDelegate.onAccept(inviteResponse); + } + }); + }, + onProgress: (inviteResponse) => { + // If the user requested cancellation, ignore response. + if (this.isCanceled) { + return; + } + this.notifyReferer(inviteResponse); + this.onProgress(inviteResponse) + .catch(() => { + this.disposeEarlyMedia(); + }) + .then(() => { + if (options.requestDelegate && options.requestDelegate.onProgress) { + options.requestDelegate.onProgress(inviteResponse); + } + }); + }, + onRedirect: (inviteResponse) => { + this.notifyReferer(inviteResponse); + this.onRedirect(inviteResponse); + if (options.requestDelegate && options.requestDelegate.onRedirect) { + options.requestDelegate.onRedirect(inviteResponse); + } + }, + onReject: (inviteResponse) => { + this.notifyReferer(inviteResponse); + this.onReject(inviteResponse); + if (options.requestDelegate && options.requestDelegate.onReject) { + options.requestDelegate.onReject(inviteResponse); + } + }, + onTrying: (inviteResponse) => { + this.notifyReferer(inviteResponse); + this.onTrying(inviteResponse); + if (options.requestDelegate && options.requestDelegate.onTrying) { + options.requestDelegate.onTrying(inviteResponse); + } + } + }); + return this.outgoingInviteRequest; + } + disposeEarlyMedia() { + this.earlyMediaSessionDescriptionHandlers.forEach((sessionDescriptionHandler) => { + sessionDescriptionHandler.close(); + }); + this.earlyMediaSessionDescriptionHandlers.clear(); + } + notifyReferer(response) { + if (!this._referred) { + return; + } + if (!(this._referred instanceof _session__WEBPACK_IMPORTED_MODULE_2__["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."); + } + const statusCode = response.message.statusCode; + const reasonPhrase = response.message.reasonPhrase; + const body = `SIP/2.0 ${statusCode} ${reasonPhrase}`.trim(); + const 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: () => { + this._referred = undefined; + } + }; + } + /** + * Handle final response to initial INVITE. + * @param inviteResponse - 2xx response. + */ + onAccept(inviteResponse) { + this.logger.log("Inviter.onAccept"); + // validate state + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Establishing) { + this.logger.error(`Accept received while in state ${this.state}, dropping response`); + return Promise.reject(new Error(`Invalid session state ${this.state}`)); + } + const response = inviteResponse.message; + const session = inviteResponse.session; + // Ported behavior. + if (response.hasHeader("P-Asserted-Identity")) { + this._assertedIdentity = _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].nameAddrHeaderParse(response.getHeader("P-Asserted-Identity")); + } + // We have a confirmed dialog. + session.delegate = { + onAck: (ackRequest) => this.onAckRequest(ackRequest), + onBye: (byeRequest) => this.onByeRequest(byeRequest), + onInfo: (infoRequest) => this.onInfoRequest(infoRequest), + onInvite: (inviteRequest) => this.onInviteRequest(inviteRequest), + onMessage: (messageRequest) => this.onMessageRequest(messageRequest), + onNotify: (notifyRequest) => this.onNotifyRequest(notifyRequest), + onPrack: (prackRequest) => this.onPrackRequest(prackRequest), + onRefer: (referRequest) => this.onReferRequest(referRequest) + }; + this._dialog = session; + switch (session.signalingState) { + case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Initial: + // INVITE without offer, so MUST have offer at this point, so invalid state. + this.logger.error("Received 2xx response to INVITE without a session description"); + this.ackAndBye(inviteResponse, 400, "Missing session description"); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); + return Promise.reject(new Error("Bad Media Description")); + case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].HaveLocalOffer: + // INVITE with offer, so MUST have answer at this point, so invalid state. + this.logger.error("Received 2xx response to INVITE without a session description"); + this.ackAndBye(inviteResponse, 400, "Missing session description"); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); + return Promise.reject(new Error("Bad Media Description")); + case _core__WEBPACK_IMPORTED_MODULE_0__["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}.`); + } + const options = { + sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers, + sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions + }; + return this.setOfferAndGetAnswer(this._dialog.offer, options) + .then((body) => { + inviteResponse.ack({ body }); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Established); + }) + .catch((error) => { + this.ackAndBye(inviteResponse, 488, "Invalid session description"); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); + throw error; + }); + } + case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Stable: { + // If INVITE without offer and we have already completed the initial exchange. + if (this.earlyMediaSessionDescriptionHandlers.size > 0) { + const sdh = this.earlyMediaSessionDescriptionHandlers.get(session.id); + if (!sdh) { + throw new Error("Session description handler undefined."); + } + this.setSessionDescriptionHandler(sdh); + this.earlyMediaSessionDescriptionHandlers.delete(session.id); + inviteResponse.ack(); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["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) { + const 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 behavior 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); + } + const 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.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); + return Promise.reject(error); + } + // Otherwise we are good to go. + inviteResponse.ack(); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Established); + return Promise.resolve(); + } + // If INVITE with offer and we have been waiting till now to apply the answer. + const answer = session.answer; + if (!answer) { + throw new Error("Answer is undefined."); + } + const options = { + sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers, + sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions + }; + return this.setAnswer(answer, options) + .then(() => { + // This session has completed an initial offer/answer exchange... + let ackOptions; + if (this._renderbody && this._rendertype) { + ackOptions = { + body: { contentDisposition: "render", contentType: this._rendertype, content: this._renderbody } + }; + } + inviteResponse.ack(ackOptions); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Established); + }) + .catch((error) => { + this.logger.error(error.message); + this.ackAndBye(inviteResponse, 488, "Not Acceptable Here"); + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); + throw error; + }); + } + case _core__WEBPACK_IMPORTED_MODULE_0__["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. + */ + onProgress(inviteResponse) { + var _a; + this.logger.log("Inviter.onProgress"); + // validate state + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["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."); + } + const response = inviteResponse.message; + const session = inviteResponse.session; + // Ported - Set assertedIdentity. + if (response.hasHeader("P-Asserted-Identity")) { + this._assertedIdentity = _core__WEBPACK_IMPORTED_MODULE_0__["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 + const requireHeader = response.getHeader("require"); + const rseqHeader = response.getHeader("rseq"); + const rseq = requireHeader && requireHeader.includes("100rel") && rseqHeader ? Number(rseqHeader) : undefined; + const responseReliable = !!rseq; + const extraHeaders = []; + if (responseReliable) { + extraHeaders.push("RAck: " + response.getHeader("rseq") + " " + response.getHeader("cseq")); + } + switch (session.signalingState) { + case _core__WEBPACK_IMPORTED_MODULE_0__["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 }); + } + return Promise.resolve(); + case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].HaveLocalOffer: + // INVITE with offer and session only has that initial local offer. + if (responseReliable) { + inviteResponse.prack({ extraHeaders }); + } + return Promise.resolve(); + case _core__WEBPACK_IMPORTED_MODULE_0__["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 + const sdh = this.sessionDescriptionHandlerFactory(this, this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions || {}); + if ((_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onSessionDescriptionHandler) { + this.delegate.onSessionDescriptionHandler(sdh, true); + } + this.earlyMediaSessionDescriptionHandlers.set(session.id, sdh); + return sdh + .setDescription(response.body, this.sessionDescriptionHandlerOptions, this.sessionDescriptionHandlerModifiers) + .then(() => sdh.getDescription(this.sessionDescriptionHandlerOptions, this.sessionDescriptionHandlerModifiers)) + .then((description) => { + const body = { + contentDisposition: "session", + contentType: description.contentType, + content: description.body + }; + inviteResponse.prack({ extraHeaders, body }); + }) + .catch((error) => { + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); + throw error; + }); + } + case _core__WEBPACK_IMPORTED_MODULE_0__["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 }); + } + if (this.earlyMedia && !this.earlyMediaDialog) { + this.earlyMediaDialog = session; + const answer = session.answer; + if (!answer) { + throw new Error("Answer is undefined."); + } + const options = { + sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers, + sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions + }; + return this.setAnswer(answer, options).catch((error) => { + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); + throw error; + }); + } + return Promise.resolve(); + case _core__WEBPACK_IMPORTED_MODULE_0__["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. + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onRedirect(inviteResponse) { + this.logger.log("Inviter.onRedirect"); + // validate state + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Establishing && this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminating) { + this.logger.error(`Redirect received while in state ${this.state}, dropping response`); + return; + } + // transition state + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); + } + /** + * Handle final response to initial INVITE. + * @param inviteResponse - 4xx, 5xx, or 6xx response. + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onReject(inviteResponse) { + this.logger.log("Inviter.onReject"); + // validate state + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Establishing && this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminating) { + this.logger.error(`Reject received while in state ${this.state}, dropping response`); + return; + } + // transition state + this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); + } + /** + * Handle final response to initial INVITE. + * @param inviteResponse - 100 response. + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onTrying(inviteResponse) { + this.logger.log("Inviter.onTrying"); + // validate state + if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Establishing) { + this.logger.error(`Trying received while in state ${this.state}, dropping response`); + return; + } + } +} + + +/***/ }), +/* 124 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 125 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 126 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Messager", function() { return Messager; }); +/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); + +/** + * A messager sends a {@link Message} (outgoing MESSAGE). + * @public + */ +class Messager { + /** + * 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, targetURI, content, contentType = "text/plain", options = {}) { + // Logger + this.logger = userAgent.getLogger("sip.Messager"); + // Default options params + options.params = options.params || {}; + // URIs + let fromURI = userAgent.userAgentCore.configuration.aor; + if (options.params.fromUri) { + fromURI = + typeof options.params.fromUri === "string" ? _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].URIParse(options.params.fromUri) : options.params.fromUri; + } + if (!fromURI) { + throw new TypeError("Invalid from URI: " + options.params.fromUri); + } + let toURI = targetURI; + if (options.params.toUri) { + toURI = typeof options.params.toUri === "string" ? _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].URIParse(options.params.toUri) : options.params.toUri; + } + if (!toURI) { + throw new TypeError("Invalid to URI: " + options.params.toUri); + } + // Message params + const params = options.params ? Object.assign({}, options.params) : {}; + // Extra headers + const extraHeaders = (options.extraHeaders || []).slice(); + // Body + const contentDisposition = "render"; + const body = { + contentDisposition, + contentType, + content + }; + // Build the request + this.request = userAgent.userAgentCore.makeOutgoingRequestMessage(_core__WEBPACK_IMPORTED_MODULE_0__["C"].MESSAGE, targetURI, fromURI, toURI, params, extraHeaders, body); + // User agent + this.userAgent = userAgent; + } + /** + * Send the message. + */ + message(options = {}) { + this.userAgent.userAgentCore.request(this.request, options.requestDelegate); + return Promise.resolve(); + } +} + + +/***/ }), +/* 127 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 128 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 129 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PublisherState", function() { return PublisherState; }); +/** + * {@link Publisher} state. + * @remarks + * The {@link Publisher} behaves in a deterministic manner according to the following + * Finite State Machine (FSM). + * ```txt + * __________________________________________ + * | __________________________ | + * Publisher | | v v + * Constructed -> Initial -> Published -> Unpublished -> Terminated + * | ^____________| ^ + * |______________________________| + * ``` + * @public + */ +var PublisherState; +(function (PublisherState) { + PublisherState["Initial"] = "Initial"; + PublisherState["Published"] = "Published"; + PublisherState["Unpublished"] = "Unpublished"; + PublisherState["Terminated"] = "Terminated"; +})(PublisherState || (PublisherState = {})); + + +/***/ }), +/* 130 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 131 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Publisher", function() { return Publisher; }); +/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); +/* harmony import */ var _emitter__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(108); +/* harmony import */ var _publisher_state__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(129); + + + +/** + * A publisher publishes a publication (outgoing PUBLISH). + * @public + */ +class Publisher { + /** + * 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, targetURI, eventType, options = {}) { + this.disposed = false; + /** The publication state. */ + this._state = _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Initial; + // state emitter + this._stateEventEmitter = new _emitter__WEBPACK_IMPORTED_MODULE_1__["EmitterImpl"](); + this.userAgent = userAgent; + 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 = options.expires; + this.logger = userAgent.getLogger("sip.Publisher"); + const params = options.params || {}; + const fromURI = params.fromUri ? params.fromUri : userAgent.userAgentCore.configuration.aor; + const toURI = params.toUri ? params.toUri : targetURI; + let body; + if (options.body && options.contentType) { + const contentDisposition = "render"; + const contentType = options.contentType; + const content = options.body; + body = { + contentDisposition, + contentType, + content + }; + } + const extraHeaders = (options.extraHeaders || []).slice(); + // Build the request + this.request = userAgent.userAgentCore.makeOutgoingRequestMessage(_core__WEBPACK_IMPORTED_MODULE_0__["C"].PUBLISH, targetURI, fromURI, toURI, params, extraHeaders, body); + // Identifier + this.id = this.target.toString() + ":" + this.event; + // Add to the user agent's publisher collection. + this.userAgent._publishers[this.id] = this; + } + /** + * Destructor. + */ + dispose() { + if (this.disposed) { + return Promise.resolve(); + } + this.disposed = true; + this.logger.log(`Publisher ${this.id} in state ${this.state} is being disposed`); + // Remove from the user agent's publisher collection + delete this.userAgent._publishers[this.id]; + // Send unpublish, if requested + if (this.options.unpublishOnClose && this.state === _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Published) { + return this.unpublish(); + } + if (this.publishRefreshTimer) { + clearTimeout(this.publishRefreshTimer); + this.publishRefreshTimer = undefined; + } + this.pubRequestBody = undefined; + this.pubRequestExpires = 0; + this.pubRequestEtag = undefined; + return Promise.resolve(); + } + /** The publication state. */ + get state() { + return this._state; + } + /** Emits when the publisher state changes. */ + get stateChange() { + return this._stateEventEmitter; + } + /** + * Publish. + * @param content - Body to publish + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + publish(content, 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 + if (this.options.expires === undefined) { + throw new Error("Expires undefined."); + } + this.pubRequestExpires = this.options.expires; + this.pubRequestEtag = undefined; + } + this.sendPublishRequest(); + return Promise.resolve(); + } + /** + * Unpublish. + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + unpublish(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(); + } + return Promise.resolve(); + } + /** @internal */ + receiveResponse(response) { + const statusCode = response.statusCode || 0; + switch (true) { + case /^1[0-9]{2}$/.test(statusCode.toString()): + 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")) { + const 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(() => this.refreshRequest(), this.pubRequestExpires * 900); + this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Published); + } + else { + this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Unpublished); + } + 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; + if (this.options.body === undefined) { + throw new Error("Body undefined."); + } + this.publish(this.options.body); + } + else { + this.logger.warn("412 response to PUBLISH, recovery failed"); + this.pubRequestExpires = 0; + this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Unpublished); + this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Terminated); + } + 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")) { + const 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; + if (this.options.body === undefined) { + throw new Error("Body undefined."); + } + this.publish(this.options.body); + } + else { + this.logger.warn("Bad 423 response Min-Expires header received for PUBLISH"); + this.pubRequestExpires = 0; + this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Unpublished); + this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Terminated); + } + } + else { + this.logger.warn("423 response to PUBLISH, recovery failed"); + this.pubRequestExpires = 0; + this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Unpublished); + this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Terminated); + } + break; + default: + this.pubRequestExpires = 0; + this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Unpublished); + this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Terminated); + break; + } + // Do the cleanup + if (this.pubRequestExpires === 0) { + if (this.publishRefreshTimer) { + clearTimeout(this.publishRefreshTimer); + this.publishRefreshTimer = undefined; + } + this.pubRequestBody = undefined; + this.pubRequestEtag = undefined; + } + } + /** @internal */ + send() { + return this.userAgent.userAgentCore.publish(this.request, { + onAccept: (response) => this.receiveResponse(response.message), + onProgress: (response) => this.receiveResponse(response.message), + onRedirect: (response) => this.receiveResponse(response.message), + onReject: (response) => this.receiveResponse(response.message), + onTrying: (response) => this.receiveResponse(response.message) + }); + } + refreshRequest() { + // 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) { + throw new Error("Etag undefined"); + } + if (this.pubRequestExpires === 0) { + throw new Error("Expires zero"); + } + this.sendPublishRequest(); + } + sendPublishRequest() { + const reqOptions = Object.assign({}, this.options); + 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); + } + const ruri = this.target; + const params = this.options.params || {}; + let bodyAndContentType; + if (this.pubRequestBody !== undefined) { + if (this.options.contentType === undefined) { + throw new Error("Content type undefined."); + } + bodyAndContentType = { + body: this.pubRequestBody, + contentType: this.options.contentType + }; + } + let body; + if (bodyAndContentType) { + body = Object(_core__WEBPACK_IMPORTED_MODULE_0__["fromBodyLegacy"])(bodyAndContentType); + } + this.request = this.userAgent.userAgentCore.makeOutgoingRequestMessage(_core__WEBPACK_IMPORTED_MODULE_0__["C"].PUBLISH, ruri, params.fromUri ? params.fromUri : this.userAgent.userAgentCore.configuration.aor, params.toUri ? params.toUri : this.target, params, reqOptions.extraHeaders, body); + return this.send(); + } + /** + * Transition publication state. + */ + stateTransition(newState) { + const invalidTransition = () => { + throw new Error(`Invalid state transition from ${this._state} to ${newState}`); + }; + // Validate transition + switch (this._state) { + case _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Initial: + if (newState !== _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Published && + newState !== _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Unpublished && + newState !== _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Terminated) { + invalidTransition(); + } + break; + case _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Published: + if (newState !== _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Unpublished && newState !== _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Terminated) { + invalidTransition(); + } + break; + case _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Unpublished: + if (newState !== _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Published && newState !== _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Terminated) { + invalidTransition(); + } + break; + case _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Terminated: + invalidTransition(); + break; + default: + throw new Error("Unrecognized state."); + } + // Transition + this._state = newState; + this.logger.log(`Publication transitioned to state ${this._state}`); + this._stateEventEmitter.emit(this._state); + // Dispose + if (newState === _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Terminated) { + this.dispose(); + } + } +} + + +/***/ }), +/* 132 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 133 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 134 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RegistererState", function() { return RegistererState; }); +/** + * {@link Registerer} state. + * @remarks + * The {@link Registerer} behaves in a deterministic manner according to the following + * Finite State Machine (FSM). + * ```txt + * __________________________________________ + * | __________________________ | + * Registerer | | v v + * Constructed -> Initial -> Registered -> Unregistered -> Terminated + * | ^____________| ^ + * |______________________________| + * ``` + * @public + */ +var RegistererState; +(function (RegistererState) { + RegistererState["Initial"] = "Initial"; + RegistererState["Registered"] = "Registered"; + RegistererState["Unregistered"] = "Unregistered"; + RegistererState["Terminated"] = "Terminated"; +})(RegistererState || (RegistererState = {})); + + +/***/ }), +/* 135 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 136 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Registerer", function() { return Registerer; }); +/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); +/* harmony import */ var _emitter__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(108); +/* harmony import */ var _exceptions__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(3); +/* harmony import */ var _registerer_state__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(134); + + + + +/** + * A registerer registers a contact for an address of record (outgoing REGISTER). + * @public + */ +class Registerer { + /** + * 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, options = {}) { + this.disposed = false; + /** The contacts returned from the most recent accepted REGISTER request. */ + this._contacts = []; + /** The number of seconds to wait before retrying to register. */ + this._retryAfter = undefined; + /** The registration state. */ + this._state = _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Initial; + /** True is waiting for final response to outstanding REGISTER request. */ + this._waiting = false; + // state emitter + this._stateEventEmitter = new _emitter__WEBPACK_IMPORTED_MODULE_1__["EmitterImpl"](); + // waiting emitter + this._waitingEventEmitter = new _emitter__WEBPACK_IMPORTED_MODULE_1__["EmitterImpl"](); + // Set user agent + this.userAgent = userAgent; + // Default registrar is domain portion of user agent uri + const defaultUserAgentRegistrar = userAgent.configuration.uri.clone(); + defaultUserAgentRegistrar.user = undefined; + // Initialize configuration + this.options = Object.assign(Object.assign(Object.assign({}, Registerer.defaultOptions()), { registrar: defaultUserAgentRegistrar }), Registerer.stripUndefinedProperties(options)); + // Make sure we are not using references to array options + this.options.extraContactHeaderParams = (this.options.extraContactHeaderParams || []).slice(); + this.options.extraHeaders = (this.options.extraHeaders || []).slice(); + // Make sure we are not using references to registrar uri + if (!this.options.registrar) { + throw new Error("Registrar undefined."); + } + this.options.registrar = this.options.registrar.clone(); + // Set instanceId and regId conditional defaults and validate + if (this.options.regId && !this.options.instanceId) { + this.options.instanceId = Registerer.newUUID(); + } + else if (!this.options.regId && this.options.instanceId) { + this.options.regId = 1; + } + if (this.options.instanceId && _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].parse(this.options.instanceId, "uuid") === -1) { + throw new Error("Invalid instanceId."); + } + if (this.options.regId && this.options.regId < 0) { + throw new Error("Invalid regId."); + } + const registrar = this.options.registrar; + const fromURI = (this.options.params && this.options.params.fromUri) || userAgent.userAgentCore.configuration.aor; + const toURI = (this.options.params && this.options.params.toUri) || userAgent.configuration.uri; + const params = this.options.params || {}; + const extraHeaders = (options.extraHeaders || []).slice(); + // Build the request + this.request = userAgent.userAgentCore.makeOutgoingRequestMessage(_core__WEBPACK_IMPORTED_MODULE_0__["C"].REGISTER, registrar, fromURI, toURI, params, extraHeaders, undefined); + // Registration expires + this.expires = this.options.expires || Registerer.defaultExpires; + if (this.expires < 0) { + throw new Error("Invalid expires."); + } + // initialize logger + this.logger = userAgent.getLogger("sip.Registerer"); + if (this.options.logConfiguration) { + this.logger.log("Configuration:"); + Object.keys(this.options).forEach((key) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const value = this.options[key]; + switch (key) { + case "registrar": + this.logger.log("· " + key + ": " + value); + break; + default: + this.logger.log("· " + key + ": " + JSON.stringify(value)); + } + }); + } + // Identifier + this.id = this.request.callId + this.request.from.parameters.tag; + // Add to the user agent's session collection. + this.userAgent._registerers[this.id] = this; + } + /** Default registerer options. */ + static defaultOptions() { + return { + expires: Registerer.defaultExpires, + extraContactHeaderParams: [], + extraHeaders: [], + logConfiguration: true, + instanceId: "", + params: {}, + regId: 0, + registrar: new _core__WEBPACK_IMPORTED_MODULE_0__["URI"]("sip", "anonymous", "anonymous.invalid") + }; + } + // http://stackoverflow.com/users/109538/broofa + static newUUID() { + const UUID = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => { + const r = Math.floor(Math.random() * 16); + const v = c === "x" ? r : (r % 4) + 8; + return v.toString(16); + }); + return UUID; + } + /** + * Strip properties with undefined values from options. + * This is a work around while waiting for missing vs undefined to be addressed (or not)... + * https://github.com/Microsoft/TypeScript/issues/13195 + * @param options - Options to reduce + */ + static stripUndefinedProperties(options) { + return Object.keys(options).reduce((object, key) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (options[key] !== undefined) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + object[key] = options[key]; + } + return object; + }, {}); + } + /** The registered contacts. */ + get contacts() { + return this._contacts.slice(); + } + /** + * The number of seconds to wait before retrying to register. + * @defaultValue `undefined` + * @remarks + * When the server rejects a registration request, if it provides a suggested + * duration to wait before retrying, that value is available here when and if + * the state transitions to `Unsubscribed`. It is also available during the + * callback to `onReject` after a call to `register`. (Note that if the state + * if already `Unsubscribed`, a rejected request created by `register` will + * not cause the state to transition to `Unsubscribed`. One way to avoid this + * case is to dispose of `Registerer` when unregistered and create a new + * `Registerer` for any attempts to retry registering.) + * @example + * ```ts + * // Checking for retry after on state change + * registerer.stateChange.addListener((newState) => { + * switch (newState) { + * case RegistererState.Unregistered: + * const retryAfter = registerer.retryAfter; + * break; + * } + * }); + * + * // Checking for retry after on request rejection + * registerer.register({ + * requestDelegate: { + * onReject: () => { + * const retryAfter = registerer.retryAfter; + * } + * } + * }); + * ``` + */ + get retryAfter() { + return this._retryAfter; + } + /** The registration state. */ + get state() { + return this._state; + } + /** Emits when the registerer state changes. */ + get stateChange() { + return this._stateEventEmitter; + } + /** Destructor. */ + dispose() { + if (this.disposed) { + return Promise.resolve(); + } + this.disposed = true; + this.logger.log(`Registerer ${this.id} in state ${this.state} is being disposed`); + // Remove from the user agent's registerer collection + delete this.userAgent._registerers[this.id]; + // If registered, unregisters and resolves after final response received. + return new Promise((resolve) => { + const doClose = () => { + // If we are registered, unregister and resolve after our state changes + if (!this.waiting && this._state === _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Registered) { + this.stateChange.addListener(() => { + this.terminated(); + resolve(); + }, { once: true }); + this.unregister(); + return; + } + // Otherwise just resolve + this.terminated(); + 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.addListener(() => { + doClose(); + }, { once: true }); + } + else { + doClose(); + } + }); + } + /** + * Sends the REGISTER request. + * @remarks + * If successful, sends re-REGISTER requests prior to registration expiration until `unsubscribe()` is called. + * Rejects with `RequestPendingError` if a REGISTER request is already in progress. + */ + register(options = {}) { + if (this.state === _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated) { + this.stateError(); + throw new Error("Registerer terminated. Unable to register."); + } + if (this.disposed) { + this.stateError(); + throw new Error("Registerer disposed. Unable to register."); + } + // 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) { + this.waitingWarning(); + const error = new _exceptions__WEBPACK_IMPORTED_MODULE_2__["RequestPendingError"]("REGISTER request already in progress, waiting for final response"); + return Promise.reject(error); + } + // Options + if (options.requestOptions) { + this.options = Object.assign(Object.assign({}, this.options), options.requestOptions); + } + // Extra headers + const 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); + const outgoingRegisterRequest = this.userAgent.userAgentCore.register(this.request, { + onAccept: (response) => { + let 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"); + let 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 + let contact; + while (contacts--) { + contact = response.message.parseHeader("contact", contacts); + if (!contact) { + throw new Error("Contact undefined"); + } + if (contact.uri.user === this.userAgent.contact.uri.user && + contact.uri.host === this.userAgent.contact.uri.host && + contact.uri.port === this.userAgent.contact.uri.port) { + expires = Number(contact.getParam("expires")); + break; + } + 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")) { + const gruu = contact.getParam("temp-gruu"); + if (gruu) { + this.userAgent.contact.tempGruu = _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].URIParse(gruu.replace(/"/g, "")); + } + } + if (contact.hasParam("pub-gruu")) { + const gruu = contact.getParam("pub-gruu"); + if (gruu) { + this.userAgent.contact.pubGruu = _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].URIParse(gruu.replace(/"/g, "")); + } + } + this.registered(expires); + if (options.requestDelegate && options.requestDelegate.onAccept) { + options.requestDelegate.onAccept(response); + } + this.waitingToggle(false); + }, + onProgress: (response) => { + if (options.requestDelegate && options.requestDelegate.onProgress) { + options.requestDelegate.onProgress(response); + } + }, + onRedirect: (response) => { + this.logger.error("Redirect received. Not supported."); + this.unregistered(); + if (options.requestDelegate && options.requestDelegate.onRedirect) { + options.requestDelegate.onRedirect(response); + } + this.waitingToggle(false); + }, + onReject: (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, dropping response"); + 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}`); + // The Retry-After header field can be used with a 500 (Server Internal + // Error) or 503 (Service Unavailable) response to indicate how long the + // service is expected to be unavailable to the requesting client... + // https://tools.ietf.org/html/rfc3261#section-20.33 + let retryAfterDuration = NaN; + if (response.message.statusCode === 500 || response.message.statusCode === 503) { + const header = response.message.getHeader("retry-after"); + if (header) { + retryAfterDuration = Number.parseInt(header, undefined); + } + } + // Set for the state change (if any) and the delegate callback (if any) + this._retryAfter = isNaN(retryAfterDuration) ? undefined : retryAfterDuration; + this.unregistered(); + if (options.requestDelegate && options.requestDelegate.onReject) { + options.requestDelegate.onReject(response); + } + this._retryAfter = undefined; + this.waitingToggle(false); + }, + onTrying: (response) => { + if (options.requestDelegate && options.requestDelegate.onTrying) { + options.requestDelegate.onTrying(response); + } + } + }); + return Promise.resolve(outgoingRegisterRequest); + } + /** + * Sends the REGISTER request with expires equal to zero. + * @remarks + * Rejects with `RequestPendingError` if a REGISTER request is already in progress. + */ + unregister(options = {}) { + if (this.state === _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated) { + this.stateError(); + throw new Error("Registerer terminated. Unable to register."); + } + if (this.disposed) { + if (this.state !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Registered) { + // allows unregister while disposing and registered + this.stateError(); + throw new Error("Registerer disposed. Unable to register."); + } + } + // 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) { + this.waitingWarning(); + const error = new _exceptions__WEBPACK_IMPORTED_MODULE_2__["RequestPendingError"]("REGISTER request already in progress, waiting for final response"); + return Promise.reject(error); + } + if (this._state !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Registered && !options.all) { + this.logger.warn("Not currently registered, but sending an unregister anyway."); + } + // Extra headers + const 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-emptive 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); + const outgoingRegisterRequest = this.userAgent.userAgentCore.register(this.request, { + onAccept: (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: (response) => { + if (options.requestDelegate && options.requestDelegate.onProgress) { + options.requestDelegate.onProgress(response); + } + }, + onRedirect: (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: (response) => { + 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: (response) => { + if (options.requestDelegate && options.requestDelegate.onTrying) { + options.requestDelegate.onTrying(response); + } + } + }); + return Promise.resolve(outgoingRegisterRequest); + } + /** + * Clear registration timers. + */ + clearTimers() { + if (this.registrationTimer !== undefined) { + clearTimeout(this.registrationTimer); + this.registrationTimer = undefined; + } + if (this.registrationExpiredTimer !== undefined) { + clearTimeout(this.registrationExpiredTimer); + this.registrationExpiredTimer = undefined; + } + } + /** + * Generate Contact Header + */ + generateContactHeader(expires) { + let contact = this.userAgent.contact.toString(); + if (this.options.regId && this.options.instanceId) { + contact += ";reg-id=" + this.options.regId; + contact += ';+sip.instance=""'; + } + if (this.options.extraContactHeaderParams) { + this.options.extraContactHeaderParams.forEach((header) => { + contact += ";" + header; + }); + } + contact += ";expires=" + expires; + return contact; + } + /** + * Helper function, called when registered. + */ + registered(expires) { + this.clearTimers(); + // Re-Register before the expiration interval has elapsed. + // For that, decrease the expires value. ie: 3 seconds + this.registrationTimer = setTimeout(() => { + this.registrationTimer = undefined; + this.register(); + }, expires * 1000 - 3000); + // We are unregistered if the registration expires. + this.registrationExpiredTimer = setTimeout(() => { + this.logger.warn("Registration expired"); + this.unregistered(); + }, expires * 1000); + if (this._state !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Registered) { + this.stateTransition(_registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Registered); + } + } + /** + * Helper function, called when unregistered. + */ + unregistered() { + this.clearTimers(); + if (this._state !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Unregistered) { + this.stateTransition(_registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Unregistered); + } + } + /** + * Helper function, called when terminated. + */ + terminated() { + this.clearTimers(); + if (this._state !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated) { + this.stateTransition(_registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated); + } + } + /** + * Transition registration state. + */ + stateTransition(newState) { + const invalidTransition = () => { + throw new Error(`Invalid state transition from ${this._state} to ${newState}`); + }; + // Validate transition + switch (this._state) { + case _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Initial: + if (newState !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Registered && + newState !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Unregistered && + newState !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated) { + invalidTransition(); + } + break; + case _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Registered: + if (newState !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Unregistered && newState !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated) { + invalidTransition(); + } + break; + case _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Unregistered: + if (newState !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Registered && newState !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated) { + invalidTransition(); + } + break; + case _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated: + invalidTransition(); + break; + default: + throw new Error("Unrecognized state."); + } + // Transition + this._state = newState; + this.logger.log(`Registration transitioned to state ${this._state}`); + this._stateEventEmitter.emit(this._state); + // Dispose + if (newState === _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated) { + this.dispose(); + } + } + /** True if the registerer is currently waiting for final response to a REGISTER request. */ + get waiting() { + return this._waiting; + } + /** Emits when the registerer waiting state changes. */ + get waitingChange() { + return this._waitingEventEmitter; + } + /** + * Toggle waiting. + */ + waitingToggle(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(this._waiting); + } + /** Hopefully helpful as the standard behavior has been found to be unexpected. */ + waitingWarning() { + let message = "An attempt was made to send a REGISTER request while a prior one was still in progress."; + message += " RFC 3261 requires UAs MUST NOT send a new registration until they have received a final response"; + message += " from the registrar for the previous one or the previous REGISTER request has timed out."; + message += " Note that if the transport disconnects, you still must wait for the prior request to time out before"; + message += + " sending a new REGISTER request or alternatively dispose of the current Registerer and create a new Registerer."; + this.logger.warn(message); + } + /** Hopefully helpful as the standard behavior has been found to be unexpected. */ + stateError() { + const reason = this.state === _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated ? "is in 'Terminated' state" : "has been disposed"; + let message = `An attempt was made to send a REGISTER request when the Registerer ${reason}.`; + message += " The Registerer transitions to 'Terminated' when Registerer.dispose() is called."; + message += " Perhaps you called UserAgent.stop() which dipsoses of all Registerers?"; + this.logger.error(message); + } +} +Registerer.defaultExpires = 600; + + +/***/ }), +/* 137 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 138 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 139 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 140 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 141 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 142 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 143 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 144 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 145 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 146 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 147 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 148 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Subscriber", function() { return Subscriber; }); +/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); +/* harmony import */ var _core_user_agent_core_allowed_methods__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(82); +/* harmony import */ var _notification__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(116); +/* harmony import */ var _subscription__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(149); +/* harmony import */ var _subscription_state__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(150); + + + + + +/** + * 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.addListener((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 + */ +class Subscriber extends _subscription__WEBPACK_IMPORTED_MODULE_3__["Subscription"] { + /** + * 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, targetURI, eventType, options = {}) { + super(userAgent, options); + this.body = undefined; + this.logger = userAgent.getLogger("sip.Subscriber"); + if (options.body) { + this.body = { + body: options.body, + contentType: options.contentType ? options.contentType : "application/sdp" + }; + } + 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.subscriberRequest = this.initSubscriberRequest(); + this.outgoingRequestMessage = this.subscriberRequest.message; + // Add to UserAgent's collection + this.id = this.outgoingRequestMessage.callId + this.outgoingRequestMessage.from.parameters.tag + this.event; + this._userAgent._subscriptions[this.id] = this; + } + /** + * Destructor. + * @internal + */ + dispose() { + if (this.disposed) { + return Promise.resolve(); + } + this.logger.log(`Subscription ${this.id} in state ${this.state} is being disposed`); + // Remove from the user agent's subscription collection + delete this._userAgent._subscriptions[this.id]; + // Clear timers + if (this.retryAfterTimer) { + clearTimeout(this.retryAfterTimer); + this.retryAfterTimer = undefined; + } + // Dispose subscriber request + this.subscriberRequest.dispose(); + // Make sure to dispose of our parent, then unsubscribe the + // subscription dialog (if need be) and resolve when it has terminated. + return super.dispose().then(() => { + // If we have never subscribed there is nothing to wait on. + // If we are already transitioned to terminated there is no need to unsubscribe again. + if (this.state !== _subscription_state__WEBPACK_IMPORTED_MODULE_4__["SubscriptionState"].Subscribed) { + return; + } + if (!this._dialog) { + throw new Error("Dialog undefined."); + } + if (this._dialog.subscriptionState === _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Pending || + this._dialog.subscriptionState === _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Active) { + const dialog = this._dialog; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + return new Promise((resolve, reject) => { + dialog.delegate = { + onTerminated: () => resolve() + }; + dialog.unsubscribe(); + }); + } + }); + } + /** + * 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". + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + subscribe(options = {}) { + switch (this.subscriberRequest.state) { + case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Initial: + // we can end up here when retrying so only state transition if in SubscriptionState.Initial state + if (this.state === _subscription_state__WEBPACK_IMPORTED_MODULE_4__["SubscriptionState"].Initial) { + this.stateTransition(_subscription_state__WEBPACK_IMPORTED_MODULE_4__["SubscriptionState"].NotifyWait); + } + this.subscriberRequest.subscribe().then((result) => { + if (result.success) { + if (result.success.subscription) { + this._dialog = result.success.subscription; + this._dialog.delegate = { + onNotify: (request) => this.onNotify(request), + onRefresh: (request) => this.onRefresh(request), + onTerminated: () => { + // If a call to unsubscribe will state transition to SubscriptionState.Terminated, + // but we can end up here after that if the NOTIFY never arrives and timer N fires. + if (this.state !== _subscription_state__WEBPACK_IMPORTED_MODULE_4__["SubscriptionState"].Terminated) { + this.stateTransition(_subscription_state__WEBPACK_IMPORTED_MODULE_4__["SubscriptionState"].Terminated); + } + } + }; + } + this.onNotify(result.success.request); + } + else if (result.failure) { + this.unsubscribe(); + } + }); + break; + case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].NotifyWait: + break; + case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Pending: + break; + case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Active: + if (this._dialog) { + const request = this._dialog.refresh(); + request.delegate = { + onAccept: (response) => this.onAccepted(response), + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onRedirect: (response) => this.unsubscribe(), + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onReject: (response) => this.unsubscribe() + }; + } + break; + case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Terminated: + break; + default: + break; + } + return Promise.resolve(); + } + /** + * {@inheritDoc Subscription.unsubscribe} + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + unsubscribe(options = {}) { + if (this.disposed) { + return Promise.resolve(); + } + switch (this.subscriberRequest.state) { + case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Initial: + break; + case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].NotifyWait: + break; + case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Pending: + if (this._dialog) { + this._dialog.unsubscribe(); + // responses intentionally ignored + } + break; + case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Active: + if (this._dialog) { + this._dialog.unsubscribe(); + // responses intentionally ignored + } + break; + case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Terminated: + break; + default: + throw new Error("Unknown state."); + } + this.stateTransition(_subscription_state__WEBPACK_IMPORTED_MODULE_4__["SubscriptionState"].Terminated); + return Promise.resolve(); + } + /** + * Sends a re-SUBSCRIBE request if the subscription is "active". + * @deprecated Use `subscribe` instead. + * @internal + */ + _refresh() { + if (this.subscriberRequest.state === _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Active) { + return this.subscribe(); + } + return Promise.resolve(); + } + /** @internal */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onAccepted(response) { + // NOTE: If you think you should do something with this response, + // please make sure you understand what it is you are doing and why. + // Per the RFC, the first NOTIFY is all that actually matters. + } + /** @internal */ + onNotify(request) { + // 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__WEBPACK_IMPORTED_MODULE_4__["SubscriptionState"].Subscribed) { + this.stateTransition(_subscription_state__WEBPACK_IMPORTED_MODULE_4__["SubscriptionState"].Subscribed); + } + // Delegate notification. + if (this.delegate && this.delegate.onNotify) { + const notification = new _notification__WEBPACK_IMPORTED_MODULE_2__["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 + const 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.initSubscriberRequest(); + this.subscribe(); + return; + case "probation": + case "giveup": + this.initSubscriberRequest(); + if (subscriptionState.params && subscriptionState.params["retry-after"]) { + this.retryAfterTimer = setTimeout(() => { + this.subscribe(); + }, subscriptionState.params["retry-after"]); + } + else { + this.subscribe(); + } + return; + case "rejected": + case "noresource": + case "invariant": + break; + } + } + this.unsubscribe(); + break; + default: + break; + } + } + } + /** @internal */ + onRefresh(request) { + request.delegate = { + onAccept: (response) => this.onAccepted(response) + }; + } + initSubscriberRequest() { + const options = { + extraHeaders: this.extraHeaders, + body: this.body ? Object(_core__WEBPACK_IMPORTED_MODULE_0__["fromBodyLegacy"])(this.body) : undefined + }; + // eslint-disable-next-line @typescript-eslint/no-use-before-define + this.subscriberRequest = new SubscriberRequest(this._userAgent.userAgentCore, this.targetURI, this.event, this.expires, options); + this.subscriberRequest.delegate = { + onAccept: (response) => this.onAccepted(response) + }; + return this.subscriberRequest; + } +} +class SubscriberRequest { + constructor(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.Subscriber"); + this.delegate = delegate; + const allowHeader = "Allow: " + _core_user_agent_core_allowed_methods__WEBPACK_IMPORTED_MODULE_1__["AllowedMethods"].toString(); + const 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()); + const body = options && options.body; + this.message = core.makeOutgoingRequestMessage(_core__WEBPACK_IMPORTED_MODULE_0__["C"].SUBSCRIBE, this.target, this.core.configuration.aor, this.target, {}, extraHeaders, body); + } + /** Destructor. */ + dispose() { + if (this.request) { + this.request.waitNotifyStop(); + this.request.dispose(); + this.request = undefined; + } + } + /** Subscription state. */ + get state() { + if (this.subscription) { + return this.subscription.subscriptionState; + } + else if (this.subscribed) { + return _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].NotifyWait; + } + else { + return _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Initial; + } + } + /** + * Establish subscription. + * @param options Options bucket. + */ + subscribe() { + 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((resolve) => { + 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: (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: (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: () => { + 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: (response) => { + resolve({ failure: { 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: (response) => { + resolve({ failure: { response } }); + } + }); + }); + } +} + + +/***/ }), +/* 149 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Subscription", function() { return Subscription; }); +/* harmony import */ var _emitter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(108); +/* harmony import */ var _subscription_state__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(150); + + +/** + * A subscription provides {@link Notification} of events. + * + * @remarks + * See {@link Subscriber} for details on establishing a subscription. + * + * @public + */ +class Subscription { + /** + * Constructor. + * @param userAgent - User agent. See {@link UserAgent} for details. + * @internal + */ + constructor(userAgent, options = {}) { + this._disposed = false; + this._state = _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Initial; + this._logger = userAgent.getLogger("sip.Subscription"); + this._stateEventEmitter = new _emitter__WEBPACK_IMPORTED_MODULE_0__["EmitterImpl"](); + this._userAgent = userAgent; + this.delegate = options.delegate; + } + /** + * Destructor. + */ + dispose() { + if (this._disposed) { + return Promise.resolve(); + } + this._disposed = true; + this._stateEventEmitter.removeAllListeners(); + return Promise.resolve(); + } + /** + * The subscribed subscription dialog. + */ + get dialog() { + return this._dialog; + } + /** + * True if disposed. + * @internal + */ + get disposed() { + return this._disposed; + } + /** + * Subscription state. See {@link SubscriptionState} for details. + */ + get state() { + return this._state; + } + /** + * Emits when the subscription `state` property changes. + */ + get stateChange() { + return this._stateEventEmitter; + } + /** @internal */ + stateTransition(newState) { + const invalidTransition = () => { + throw new Error(`Invalid state transition from ${this._state} to ${newState}`); + }; + // Validate transition + switch (this._state) { + case _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Initial: + if (newState !== _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].NotifyWait && newState !== _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated) { + invalidTransition(); + } + break; + case _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].NotifyWait: + if (newState !== _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Subscribed && newState !== _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated) { + invalidTransition(); + } + break; + case _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Subscribed: + if (newState !== _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated) { + invalidTransition(); + } + break; + case _subscription_state__WEBPACK_IMPORTED_MODULE_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(this._state); + // Dispose + if (newState === _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated) { + this.dispose(); + } + } +} + + +/***/ }), +/* 150 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubscriptionState", function() { return SubscriptionState; }); +/** + * {@link Subscription} state. + * @remarks + * The {@link Subscription} behaves in a deterministic manner according to the following + * Finite State Machine (FSM). + * ```txt + * _______________________________________ + * Subscription | v + * Constructed -> Initial -> NotifyWait -> Subscribed -> Terminated + * |____________________________^ + * ``` + * @public + */ +var SubscriptionState; +(function (SubscriptionState) { + SubscriptionState["Initial"] = "Initial"; + SubscriptionState["NotifyWait"] = "NotifyWait"; + SubscriptionState["Subscribed"] = "Subscribed"; + SubscriptionState["Terminated"] = "Terminated"; +})(SubscriptionState || (SubscriptionState = {})); + + +/***/ }), +/* 151 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 152 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 153 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 154 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 155 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 156 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TransportState", function() { return TransportState; }); +/** + * {@link Transport} state. + * + * @remarks + * The {@link Transport} behaves in a deterministic manner according to the following + * Finite State Machine (FSM). + * ```txt + * ______________________________ + * | ____________ | + * Transport v v | | + * Constructed -> Disconnected -> Connecting -> Connected -> Disconnecting + * ^ ^ |_____________________^ | | + * | |_____________________________| | + * |_____________________________________________| + * ``` + * @public + */ +var TransportState; +(function (TransportState) { + /** + * The `connect()` method was called. + */ + TransportState["Connecting"] = "Connecting"; + /** + * The `connect()` method resolved. + */ + TransportState["Connected"] = "Connected"; + /** + * The `disconnect()` method was called. + */ + TransportState["Disconnecting"] = "Disconnecting"; + /** + * The `connect()` method was rejected, or + * the `disconnect()` method completed, or + * network connectivity was lost. + */ + TransportState["Disconnected"] = "Disconnected"; +})(TransportState || (TransportState = {})); + + +/***/ }), +/* 157 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 158 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UserAgentState", function() { return UserAgentState; }); +/** + * {@link UserAgent} state. + * @remarks + * Valid state transitions: + * ``` + * 1. "Started" --> "Stopped" + * 2. "Stopped" --> "Started" + * ``` + * @public + */ +var UserAgentState; +(function (UserAgentState) { + UserAgentState["Started"] = "Started"; + UserAgentState["Stopped"] = "Stopped"; +})(UserAgentState || (UserAgentState = {})); + + +/***/ }), +/* 159 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UserAgent", function() { return UserAgent; }); +/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); +/* harmony import */ var _core_messages_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(32); +/* harmony import */ var _platform_web_session_description_handler__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(160); +/* harmony import */ var _platform_web_transport__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(171); +/* harmony import */ var _version__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1); +/* harmony import */ var _emitter__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(108); +/* harmony import */ var _invitation__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(113); +/* harmony import */ var _inviter__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(123); +/* harmony import */ var _message__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(115); +/* harmony import */ var _notification__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(116); +/* harmony import */ var _user_agent_options__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(119); +/* harmony import */ var _user_agent_state__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(158); + + + + + + + + + + + + +/** + * 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 + */ +class UserAgent { + /** + * Constructs a new instance of the `UserAgent` class. + * @param options - Options bucket. See {@link UserAgentOptions} for details. + */ + constructor(options = {}) { + /** @internal */ + this._publishers = {}; + /** @internal */ + this._registerers = {}; + /** @internal */ + this._sessions = {}; + /** @internal */ + this._subscriptions = {}; + this._state = _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Stopped; + /** Unload listener. */ + this.unloadListener = () => { + this.stop(); + }; + // state emitter + this._stateEventEmitter = new _emitter__WEBPACK_IMPORTED_MODULE_5__["EmitterImpl"](); + // initialize delegate + this.delegate = options.delegate; + // initialize configuration + this.options = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, UserAgent.defaultOptions()), { sipjsId: Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["createRandomToken"])(5) }), { uri: new _core__WEBPACK_IMPORTED_MODULE_0__["URI"]("sip", "anonymous." + Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["createRandomToken"])(6), "anonymous.invalid") }), { viaHost: Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["createRandomToken"])(12) + ".invalid" }), UserAgent.stripUndefinedProperties(options)); + // viaHost is hack + if (this.options.hackIpInContact) { + if (typeof this.options.hackIpInContact === "boolean" && this.options.hackIpInContact) { + const from = 1; + const to = 254; + const 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.loggerFactory = new _core__WEBPACK_IMPORTED_MODULE_0__["LoggerFactory"](); + 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__WEBPACK_IMPORTED_MODULE_0__["Levels"].error; + break; + case "warn": + this.loggerFactory.level = _core__WEBPACK_IMPORTED_MODULE_0__["Levels"].warn; + break; + case "log": + this.loggerFactory.level = _core__WEBPACK_IMPORTED_MODULE_0__["Levels"].log; + break; + case "debug": + this.loggerFactory.level = _core__WEBPACK_IMPORTED_MODULE_0__["Levels"].debug; + break; + default: + break; + } + if (this.options.logConfiguration) { + this.logger.log("Configuration:"); + Object.keys(this.options).forEach((key) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const value = this.options[key]; + 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)); + } + }); + } + // guard deprecated transport options (remove this in version 16.x) + if (this.options.transportOptions) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const optionsDeprecated = this.options.transportOptions; + const maxReconnectionAttemptsDeprecated = optionsDeprecated.maxReconnectionAttempts; + const reconnectionTimeoutDeprecated = optionsDeprecated.reconnectionTimeout; + if (maxReconnectionAttemptsDeprecated !== undefined) { + const deprecatedMessage = `The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. ` + + "It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly."; + this.logger.warn(deprecatedMessage); + } + if (reconnectionTimeoutDeprecated !== undefined) { + const deprecatedMessage = `The transport option "reconnectionTimeout" as has apparently been specified and has been deprecated. ` + + "It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly."; + this.logger.warn(deprecatedMessage); + } + // hack + if (options.reconnectionDelay === undefined && reconnectionTimeoutDeprecated !== undefined) { + this.options.reconnectionDelay = reconnectionTimeoutDeprecated; + } + if (options.reconnectionAttempts === undefined && maxReconnectionAttemptsDeprecated !== undefined) { + this.options.reconnectionAttempts = maxReconnectionAttemptsDeprecated; + } + } + // guard deprecated user agent options (remove this in version 16.x) + if (options.reconnectionDelay !== undefined) { + const deprecatedMessage = `The user agent option "reconnectionDelay" as has apparently been specified and has been deprecated. ` + + "It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly."; + this.logger.warn(deprecatedMessage); + } + if (options.reconnectionAttempts !== undefined) { + const deprecatedMessage = `The user agent option "reconnectionAttempts" as has apparently been specified and has been deprecated. ` + + "It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly."; + this.logger.warn(deprecatedMessage); + } + // Initialize Transport + this._transport = new this.options.transportConstructor(this.getLogger("sip.Transport"), this.options.transportOptions); + this.initTransportCallbacks(); + // Initialize Contact + this._contact = this.initContact(); + // Initialize UserAgentCore + 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"); + * ``` + */ + static makeURI(uri) { + return _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].URIParse(uri); + } + /** Default user agent options. */ + static defaultOptions() { + return { + allowLegacyNotifications: false, + authorizationHa1: "", + authorizationPassword: "", + authorizationUsername: "", + autoStart: false, + autoStop: true, + delegate: {}, + contactName: "", + contactParams: { transport: "ws" }, + displayName: "", + forceRport: false, + hackAllowUnregisteredOptionTags: false, + hackIpInContact: false, + hackViaTcp: false, + logBuiltinEnabled: true, + logConfiguration: true, + logConnector: () => { + /* noop */ + }, + logLevel: "log", + noAnswerTimeout: 60, + preloadedRouteSet: [], + reconnectionAttempts: 0, + reconnectionDelay: 4, + sessionDescriptionHandlerFactory: Object(_platform_web_session_description_handler__WEBPACK_IMPORTED_MODULE_2__["defaultSessionDescriptionHandlerFactory"])(), + sessionDescriptionHandlerFactoryOptions: {}, + sipExtension100rel: _user_agent_options__WEBPACK_IMPORTED_MODULE_10__["SIPExtension"].Unsupported, + sipExtensionReplaces: _user_agent_options__WEBPACK_IMPORTED_MODULE_10__["SIPExtension"].Unsupported, + sipExtensionExtraSupported: [], + sipjsId: "", + transportConstructor: _platform_web_transport__WEBPACK_IMPORTED_MODULE_3__["Transport"], + transportOptions: {}, + uri: new _core__WEBPACK_IMPORTED_MODULE_0__["URI"]("sip", "anonymous", "anonymous.invalid"), + userAgentString: "SIP.js/" + _version__WEBPACK_IMPORTED_MODULE_4__["LIBRARY_VERSION"], + viaHost: "" + }; + } + /** + * Strip properties with undefined values from options. + * This is a work around while waiting for missing vs undefined to be addressed (or not)... + * https://github.com/Microsoft/TypeScript/issues/13195 + * @param options - Options to reduce + */ + static stripUndefinedProperties(options) { + return Object.keys(options).reduce((object, key) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (options[key] !== undefined) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + object[key] = options[key]; + } + return object; + }, {}); + } + /** + * User agent configuration. + */ + get configuration() { + return this.options; + } + /** + * User agent contact. + */ + get contact() { + return this._contact; + } + /** + * User agent state. + */ + get state() { + return this._state; + } + /** + * User agent state change emitter. + */ + get stateChange() { + return this._stateEventEmitter; + } + /** + * User agent transport. + */ + get transport() { + return this._transport; + } + /** + * User agent core. + */ + get userAgentCore() { + return this._userAgentCore; + } + /** + * The logger. + */ + getLogger(category, label) { + return this.loggerFactory.getLogger(category, label); + } + /** + * The logger factory. + */ + getLoggerFactory() { + return this.loggerFactory; + } + /** + * True if transport is connected. + */ + isConnected() { + return this.transport.isConnected(); + } + /** + * Reconnect the transport. + */ + reconnect() { + if (this.state === _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Stopped) { + return Promise.reject(new Error("User agent stopped.")); + } + // Make sure we don't call synchronously + return Promise.resolve().then(() => this.transport.connect()); + } + /** + * Start the user agent. + * + * @remarks + * Resolves if transport connects, otherwise rejects. + * + * @example + * ```ts + * userAgent.start() + * .then(() => { + * // userAgent.isConnected() === true + * }) + * .catch((error: Error) => { + * // userAgent.isConnected() === false + * }); + * ``` + */ + start() { + if (this.state === _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Started) { + this.logger.warn(`User agent already started`); + return Promise.resolve(); + } + this.logger.log(`Starting ${this.configuration.uri}`); + // Transition state + this.transitionState(_user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Started); + // TODO: Review this as it is not clear it has any benefit and at worst causes additional load the server. + // On unload it may be best to simply in most scenarios to do nothing. Furthermore and regardless, this + // kind of behavior seems more appropriate to be managed by the consumer of the API than the API itself. + // Should this perhaps be deprecated? + // + // Add window unload event listener + if (this.options.autoStop) { + // Google Chrome Packaged Apps don't allow 'unload' listeners: unload is not available in packaged apps + const 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.transport.connect(); + } + /** + * Stop the user agent. + * + * @remarks + * Resolves when the user agent has completed a graceful shutdown. + * ```txt + * 1) Sessions terminate. + * 2) Registerers unregister. + * 3) Subscribers unsubscribe. + * 4) Publishers unpublish. + * 5) Transport disconnects. + * 6) User Agent Core resets. + * ``` + * NOTE: While this is a "graceful shutdown", it can also be very slow one if you + * are waiting for the returned Promise to resolve. The disposal of the clients and + * dialogs is done serially - waiting on one to finish before moving on to the next. + * This can be slow if there are lot of subscriptions to unsubscribe for example. + * + * THE SLOW PACE IS INTENTIONAL! + * While one could spin them all down in parallel, this could slam the remote server. + * It is bad practice to denial of service attack (DoS attack) servers!!! + * Moreover, production servers will automatically blacklist clients which send too + * many requests in too short a period of time - dropping any additional requests. + * + * If a different approach to disposing is needed, one can implement whatever is + * needed and execute that prior to calling `stop()`. Alternatively one may simply + * not wait for the Promise returned by `stop()` to complete. + */ + async stop() { + if (this.state === _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Stopped) { + this.logger.warn(`User agent already stopped`); + return Promise.resolve(); + } + this.logger.log(`Stopping ${this.configuration.uri}`); + // Transition state + this.transitionState(_user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Stopped); + // TODO: See comments with associated complimentary code in start(). Should this perhaps be deprecated? + // Remove window unload event listener + if (this.options.autoStop) { + // Google Chrome Packaged Apps don't allow 'unload' listeners: unload is not available in packaged apps + const googleChromePackagedApp = typeof chrome !== "undefined" && chrome.app && chrome.app.runtime ? true : false; + if (typeof window !== "undefined" && window.removeEventListener && !googleChromePackagedApp) { + window.removeEventListener("unload", this.unloadListener); + } + } + // Be careful here to use a local references as start() can be called + // again before we complete and we don't want to touch new clients + // and we don't want to step on the new instances (or vice versa). + const publishers = Object.assign({}, this._publishers); + const registerers = Object.assign({}, this._registerers); + const sessions = Object.assign({}, this._sessions); + const subscriptions = Object.assign({}, this._subscriptions); + const transport = this.transport; + const userAgentCore = this.userAgentCore; + // + // At this point we have completed the state transition and everything + // following will effectively run async and MUST NOT cause any issues + // if UserAgent.start() is called while the following code continues. + // + // TODO: Minor optimization. + // The disposal in all cases involves, in part, sending messages which + // is not worth doing if the transport is not connected as we know attempting + // to send messages will be futile. But none of these disposal methods check + // if that's is the case and it would be easy for them to do so at this point. + // Dispose of Registerers + this.logger.log(`Dispose of registerers`); + for (const id in registerers) { + if (registerers[id]) { + await registerers[id].dispose().catch((error) => { + this.logger.error(error.message); + delete this._registerers[id]; + throw error; + }); + } + } + // Dispose of Sessions + this.logger.log(`Dispose of sessions`); + for (const id in sessions) { + if (sessions[id]) { + await sessions[id].dispose().catch((error) => { + this.logger.error(error.message); + delete this._sessions[id]; + throw error; + }); + } + } + // Dispose of Subscriptions + this.logger.log(`Dispose of subscriptions`); + for (const id in subscriptions) { + if (subscriptions[id]) { + await subscriptions[id].dispose().catch((error) => { + this.logger.error(error.message); + delete this._subscriptions[id]; + throw error; + }); + } + } + // Dispose of Publishers + this.logger.log(`Dispose of publishers`); + for (const id in publishers) { + if (publishers[id]) { + await publishers[id].dispose().catch((error) => { + this.logger.error(error.message); + delete this._publishers[id]; + throw error; + }); + } + } + // Dispose of the transport (disconnecting) + this.logger.log(`Dispose of transport`); + await transport.dispose().catch((error) => { + this.logger.error(error.message); + throw error; + }); + // Dispose of the user agent core (resetting) + this.logger.log(`Dispose of core`); + userAgentCore.dispose(); + } + /** + * Used to avoid circular references. + * @internal + */ + _makeInviter(targetURI, options) { + return new _inviter__WEBPACK_IMPORTED_MODULE_7__["Inviter"](this, targetURI, options); + } + /** + * Attempt reconnection up to `maxReconnectionAttempts` times. + * @param reconnectionAttempt - Current attempt number. + */ + attemptReconnection(reconnectionAttempt = 1) { + const reconnectionAttempts = this.options.reconnectionAttempts; + const reconnectionDelay = this.options.reconnectionDelay; + if (reconnectionAttempt > reconnectionAttempts) { + this.logger.log(`Maximum reconnection attempts reached`); + return; + } + this.logger.log(`Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - trying`); + setTimeout(() => { + this.reconnect() + .then(() => { + this.logger.log(`Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - succeeded`); + }) + .catch((error) => { + this.logger.error(error.message); + this.logger.log(`Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - failed`); + this.attemptReconnection(++reconnectionAttempt); + }); + }, reconnectionAttempt === 1 ? 0 : reconnectionDelay * 1000); + } + /** + * Initialize contact. + */ + initContact() { + const contactName = this.options.contactName != "" ? this.options.contactName : Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["createRandomToken"])(8); + const contactParams = this.options.contactParams; + const contact = { + pubGruu: undefined, + tempGruu: undefined, + uri: new _core__WEBPACK_IMPORTED_MODULE_0__["URI"]("sip", contactName, this.options.viaHost, undefined, contactParams), + toString: (contactToStringOptions = {}) => { + const anonymous = contactToStringOptions.anonymous || false; + const outbound = contactToStringOptions.outbound || false; + let contactString = "<"; + if (anonymous) { + contactString += + this.contact.tempGruu || + `sip:anonymous@anonymous.invalid;transport=${contactParams.transport ? contactParams.transport : "ws"}`; + } + else { + contactString += this.contact.pubGruu || this.contact.uri; + } + if (outbound) { + contactString += ";ob"; + } + contactString += ">"; + return contactString; + } + }; + return contact; + } + /** + * Initialize user agent core. + */ + initCore() { + // supported options + let supportedOptionTags = []; + supportedOptionTags.push("outbound"); // TODO: is this really supported? + if (this.options.sipExtension100rel === _user_agent_options__WEBPACK_IMPORTED_MODULE_10__["SIPExtension"].Supported) { + supportedOptionTags.push("100rel"); + } + if (this.options.sipExtensionReplaces === _user_agent_options__WEBPACK_IMPORTED_MODULE_10__["SIPExtension"].Supported) { + supportedOptionTags.push("replaces"); + } + if (this.options.sipExtensionExtraSupported) { + supportedOptionTags.push(...this.options.sipExtensionExtraSupported); + } + if (!this.options.hackAllowUnregisteredOptionTags) { + supportedOptionTags = supportedOptionTags.filter((optionTag) => _user_agent_options__WEBPACK_IMPORTED_MODULE_10__["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. + const supportedOptionTagsResponse = supportedOptionTags.slice(); + if (this.contact.pubGruu || this.contact.tempGruu) { + supportedOptionTagsResponse.push("gruu"); + } + // core configuration + const userAgentCoreConfiguration = { + aor: this.options.uri, + contact: this.contact, + displayName: this.options.displayName, + loggerFactory: this.loggerFactory, + hackViaTcp: this.options.hackViaTcp, + routeSet: this.options.preloadedRouteSet, + supportedOptionTags, + supportedOptionTagsResponse, + sipjsId: this.options.sipjsId, + userAgentHeaderFieldValue: this.options.userAgentString, + viaForceRport: this.options.forceRport, + viaHost: this.options.viaHost, + authenticationFactory: () => { + const username = this.options.authorizationUsername + ? this.options.authorizationUsername + : this.options.uri.user; // if authorization username not provided, use uri user as username + const password = this.options.authorizationPassword ? this.options.authorizationPassword : undefined; + const ha1 = this.options.authorizationHa1 ? this.options.authorizationHa1 : undefined; + return new _core__WEBPACK_IMPORTED_MODULE_0__["DigestAuthentication"](this.getLoggerFactory(), ha1, username, password); + }, + transportAccessor: () => this.transport + }; + const userAgentCoreDelegate = { + onInvite: (incomingInviteRequest) => { + var _a; + const invitation = new _invitation__WEBPACK_IMPORTED_MODULE_6__["Invitation"](this, incomingInviteRequest); + incomingInviteRequest.delegate = { + onCancel: (cancel) => { + invitation._onCancel(cancel); + }, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onTransportError: (error) => { + // A server transaction MUST NOT discard transaction state based only on + // encountering a non-recoverable transport error when sending a + // response. Instead, the associated INVITE server transaction state + // machine MUST remain in its current state. (Timers will eventually + // cause it to transition to the "Terminated" state). + // https://tools.ietf.org/html/rfc6026#section-7.1 + // As noted in the comment above, we are to leaving it to the transaction + // timers to eventually cause the transaction to sort itself out in the case + // of a transport failure in an invite server transaction. This delegate method + // is here simply here for completeness and to make it clear that it provides + // nothing more than informational hook into the core. That is, if you think + // you should be trying to deal with a transport error here, you are likely wrong. + this.logger.error("A transport error has occurred while handling an incoming INVITE request."); + } + }; + // 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__WEBPACK_IMPORTED_MODULE_10__["SIPExtension"].Unsupported) { + const message = incomingInviteRequest.message; + const replaces = message.parseHeader("replaces"); + if (replaces) { + const callId = replaces.call_id; + if (typeof callId !== "string") { + throw new Error("Type of call id is not string"); + } + const toTag = replaces.replaces_to_tag; + if (typeof toTag !== "string") { + throw new Error("Type of to tag is not string"); + } + const fromTag = replaces.replaces_from_tag; + if (typeof fromTag !== "string") { + throw new Error("type of from tag is not string"); + } + const targetDialogId = callId + toTag + fromTag; + const 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. + const targetSession = this._sessions[callId + fromTag] || this._sessions[callId + toTag] || undefined; + if (!targetSession) { + throw new Error("Session does not exist."); + } + invitation._replacee = targetSession; + } + } + // Delegate invitation handling. + if ((_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onInvite) { + if (invitation.autoSendAnInitialProvisionalResponse) { + invitation.progress().then(() => { + var _a; + if (((_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onInvite) === undefined) { + throw new Error("onInvite undefined."); + } + this.delegate.onInvite(invitation); + }); + return; + } + this.delegate.onInvite(invitation); + return; + } + // 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 + invitation.reject({ statusCode: 486 }); + }, + onMessage: (incomingMessageRequest) => { + if (this.delegate && this.delegate.onMessage) { + const message = new _message__WEBPACK_IMPORTED_MODULE_8__["Message"](incomingMessageRequest); + this.delegate.onMessage(message); + } + else { + // Accept the MESSAGE request, but do nothing with it. + incomingMessageRequest.accept(); + } + }, + onNotify: (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) { + const notification = new _notification__WEBPACK_IMPORTED_MODULE_9__["Notification"](incomingNotifyRequest); + this.delegate.onNotify(notification); + } + else { + // Per the above which obsoletes 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: (incomingReferRequest) => { + this.logger.warn("Received an out of dialog REFER request"); + // TOOD: this.delegate.onRefer(...) + if (this.delegate && this.delegate.onReferRequest) { + this.delegate.onReferRequest(incomingReferRequest); + } + else { + incomingReferRequest.reject({ statusCode: 405 }); + } + }, + onRegister: (incomingRegisterRequest) => { + this.logger.warn("Received an out of dialog REGISTER request"); + // TOOD: this.delegate.onRegister(...) + if (this.delegate && this.delegate.onRegisterRequest) { + this.delegate.onRegisterRequest(incomingRegisterRequest); + } + else { + incomingRegisterRequest.reject({ statusCode: 405 }); + } + }, + onSubscribe: (incomingSubscribeRequest) => { + this.logger.warn("Received an out of dialog SUBSCRIBE request"); + // TOOD: this.delegate.onSubscribe(...) + if (this.delegate && this.delegate.onSubscribeRequest) { + this.delegate.onSubscribeRequest(incomingSubscribeRequest); + } + else { + incomingSubscribeRequest.reject({ statusCode: 405 }); + } + } + }; + return new _core__WEBPACK_IMPORTED_MODULE_0__["UserAgentCore"](userAgentCoreConfiguration, userAgentCoreDelegate); + } + initTransportCallbacks() { + this.transport.onConnect = () => this.onTransportConnect(); + this.transport.onDisconnect = (error) => this.onTransportDisconnect(error); + this.transport.onMessage = (message) => this.onTransportMessage(message); + } + onTransportConnect() { + if (this.state === _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Stopped) { + return; + } + if (this.delegate && this.delegate.onConnect) { + this.delegate.onConnect(); + } + } + onTransportDisconnect(error) { + if (this.state === _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Stopped) { + return; + } + if (this.delegate && this.delegate.onDisconnect) { + this.delegate.onDisconnect(error); + } + // Only attempt to reconnect if network/server dropped the connection. + if (error && this.options.reconnectionAttempts > 0) { + this.attemptReconnection(); + } + } + onTransportMessage(messageString) { + const message = _core__WEBPACK_IMPORTED_MODULE_0__["Parser"].parseMessage(messageString, this.getLogger("sip.Parser")); + if (!message) { + this.logger.warn("Failed to parse incoming message. Dropping."); + return; + } + if (this.state === _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Stopped && message instanceof _core__WEBPACK_IMPORTED_MODULE_0__["IncomingRequestMessage"]) { + this.logger.warn(`Received ${message.method} request while stopped. 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 + const hasMinimumHeaders = () => { + const mandatoryHeaders = ["from", "to", "call_id", "cseq", "via"]; + for (const header of mandatoryHeaders) { + if (!message.hasHeader(header)) { + this.logger.warn(`Missing mandatory header field : ${header}.`); + return false; + } + } + return true; + }; + // Request Checks + if (message instanceof _core__WEBPACK_IMPORTED_MODULE_0__["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 configurable 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(). + const len = Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["utf8Length"])(message.body); + const contentLength = message.getHeader("content-length"); + if (contentLength && len < Number(contentLength)) { + this.userAgentCore.replyStateless(message, { statusCode: 400 }); + return; + } + } + // Response Checks + if (message instanceof _core__WEBPACK_IMPORTED_MODULE_0__["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(). + const len = Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["utf8Length"])(message.body); + const 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__WEBPACK_IMPORTED_MODULE_0__["IncomingRequestMessage"]) { + this.userAgentCore.receiveIncomingRequestFromTransport(message); + return; + } + // Handle Response + if (message instanceof _core__WEBPACK_IMPORTED_MODULE_0__["IncomingResponseMessage"]) { + this.userAgentCore.receiveIncomingResponseFromTransport(message); + return; + } + throw new Error("Invalid message type."); + } + /** + * Transition state. + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + transitionState(newState, error) { + const invalidTransition = () => { + throw new Error(`Invalid state transition from ${this._state} to ${newState}`); + }; + // Validate state transition + switch (this._state) { + case _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Started: + if (newState !== _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Stopped) { + invalidTransition(); + } + break; + case _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Stopped: + if (newState !== _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Started) { + invalidTransition(); + } + break; + default: + throw new Error("Unknown state."); + } + // Update state + this.logger.log(`Transitioned from ${this._state} to ${newState}`); + this._state = newState; + this._stateEventEmitter.emit(this._state); + } +} + + +/***/ }), +/* 160 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _media_stream_factory_default__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(161); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "defaultMediaStreamFactory", function() { return _media_stream_factory_default__WEBPACK_IMPORTED_MODULE_0__["defaultMediaStreamFactory"]; }); + +/* harmony import */ var _media_stream_factory__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(162); +/* empty/unused harmony star reexport *//* harmony import */ var _peer_connection_configuration_default__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(163); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "defaultPeerConnectionConfiguration", function() { return _peer_connection_configuration_default__WEBPACK_IMPORTED_MODULE_2__["defaultPeerConnectionConfiguration"]; }); + +/* harmony import */ var _peer_connection_delegate__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(164); +/* empty/unused harmony star reexport *//* harmony import */ var _session_description_handler_configuration__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(165); +/* empty/unused harmony star reexport *//* harmony import */ var _session_description_handler_factory_default__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(166); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "defaultSessionDescriptionHandlerFactory", function() { return _session_description_handler_factory_default__WEBPACK_IMPORTED_MODULE_5__["defaultSessionDescriptionHandlerFactory"]; }); + +/* harmony import */ var _session_description_handler_factory_options__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(168); +/* empty/unused harmony star reexport *//* harmony import */ var _session_description_handler_factory__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(169); +/* empty/unused harmony star reexport *//* harmony import */ var _session_description_handler_options__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(170); +/* empty/unused harmony star reexport *//* harmony import */ var _session_description_handler__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(167); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionDescriptionHandler", function() { return _session_description_handler__WEBPACK_IMPORTED_MODULE_9__["SessionDescriptionHandler"]; }); + +/** + * A SessionDescriptionHandler for web browsers. + * @packageDocumentation + */ + + + + + + + + + + + + +/***/ }), +/* 161 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaultMediaStreamFactory", function() { return defaultMediaStreamFactory; }); +/** + * Function which returns a MediaStreamFactory. + * @public + */ +function defaultMediaStreamFactory() { + return (constraints) => { + // if no audio or video, return a media stream without tracks + if (!constraints.audio && !constraints.video) { + return Promise.resolve(new MediaStream()); + } + // getUserMedia() is a powerful feature which can only be used in secure contexts; in insecure contexts, + // navigator.mediaDevices is undefined, preventing access to getUserMedia(). A secure context is, in short, + // a page loaded using HTTPS or the file:/// URL scheme, or a page loaded from localhost. + // https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia#Privacy_and_security + if (navigator.mediaDevices === undefined) { + return Promise.reject(new Error("Media devices not available in insecure contexts.")); + } + return navigator.mediaDevices.getUserMedia.call(navigator.mediaDevices, constraints); + }; +} + + +/***/ }), +/* 162 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 163 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaultPeerConnectionConfiguration", function() { return defaultPeerConnectionConfiguration; }); +/** + * Function which returns an RTCConfiguration. + * @public + */ +function defaultPeerConnectionConfiguration() { + const configuration = { + bundlePolicy: "balanced", + certificates: undefined, + iceCandidatePoolSize: 0, + iceServers: [{ urls: "stun:stun.l.google.com:19302" }], + iceTransportPolicy: "all", + peerIdentity: undefined, + rtcpMuxPolicy: "require" + }; + return configuration; +} + + +/***/ }), +/* 164 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 165 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 166 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaultSessionDescriptionHandlerFactory", function() { return defaultSessionDescriptionHandlerFactory; }); +/* harmony import */ var _media_stream_factory_default__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(161); +/* harmony import */ var _peer_connection_configuration_default__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(163); +/* harmony import */ var _session_description_handler__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(167); + + + +/** + * Function which returns a SessionDescriptionHandlerFactory. + * @remarks + * See {@link defaultPeerConnectionConfiguration} for the default peer connection configuration. + * The ICE gathering timeout defaults to 5000ms. + * @param mediaStreamFactory - MediaStream factory. + * @public + */ +function defaultSessionDescriptionHandlerFactory(mediaStreamFactory) { + return (session, options) => { + // provide a default media stream factory if need be + if (mediaStreamFactory === undefined) { + mediaStreamFactory = Object(_media_stream_factory_default__WEBPACK_IMPORTED_MODULE_0__["defaultMediaStreamFactory"])(); + } + // make sure we allow `0` to be passed in so timeout can be disabled + const iceGatheringTimeout = (options === null || options === void 0 ? void 0 : options.iceGatheringTimeout) !== undefined ? options === null || options === void 0 ? void 0 : options.iceGatheringTimeout : 5000; + // merge passed factory options into default session description configuration + const sessionDescriptionHandlerConfiguration = { + iceGatheringTimeout, + peerConnectionConfiguration: Object.assign(Object.assign({}, Object(_peer_connection_configuration_default__WEBPACK_IMPORTED_MODULE_1__["defaultPeerConnectionConfiguration"])()), options === null || options === void 0 ? void 0 : options.peerConnectionConfiguration) + }; + const logger = session.userAgent.getLogger("sip.SessionDescriptionHandler"); + return new _session_description_handler__WEBPACK_IMPORTED_MODULE_2__["SessionDescriptionHandler"](logger, mediaStreamFactory, sessionDescriptionHandlerConfiguration); + }; +} + + +/***/ }), +/* 167 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SessionDescriptionHandler", function() { return SessionDescriptionHandler; }); +/** + * A base class implementing a WebRTC session description handler for sip.js. + * @remarks + * It is expected/intended to be extended by specific WebRTC based applications. + * @privateRemarks + * So do not put application specific implementation in here. + * @public + */ +class SessionDescriptionHandler { + /** + * Constructor + * @param logger - A logger + * @param mediaStreamFactory - A factory to provide a MediaStream + * @param options - Options passed from the SessionDescriptionHandleFactory + */ + constructor(logger, mediaStreamFactory, sessionDescriptionHandlerConfiguration) { + logger.debug("SessionDescriptionHandler.constructor"); + this.logger = logger; + this.mediaStreamFactory = mediaStreamFactory; + this.sessionDescriptionHandlerConfiguration = sessionDescriptionHandlerConfiguration; + this._localMediaStream = new MediaStream(); + this._remoteMediaStream = new MediaStream(); + this._peerConnection = new RTCPeerConnection(sessionDescriptionHandlerConfiguration === null || sessionDescriptionHandlerConfiguration === void 0 ? void 0 : sessionDescriptionHandlerConfiguration.peerConnectionConfiguration); + this.initPeerConnectionEventHandlers(); + } + /** + * The local media stream currently being sent. + * + * @remarks + * The local media stream initially has no tracks, so the presence of tracks + * should not be assumed. Furthermore, tracks may be added or removed if the + * local media changes - for example, on upgrade from audio only to a video session. + * At any given time there will be at most one audio track and one video track + * (it's possible that this restriction may not apply to sub-classes). + * Use `MediaStream.onaddtrack` or add a listener for the `addtrack` event + * to detect when a new track becomes available: + * https://developer.mozilla.org/en-US/docs/Web/API/MediaStream/onaddtrack + */ + get localMediaStream() { + return this._localMediaStream; + } + /** + * The remote media stream currently being received. + * + * @remarks + * The remote media stream initially has no tracks, so the presence of tracks + * should not be assumed. Furthermore, tracks may be added or removed if the + * remote media changes - for example, on upgrade from audio only to a video session. + * At any given time there will be at most one audio track and one video track + * (it's possible that this restriction may not apply to sub-classes). + * Use `MediaStream.onaddtrack` or add a listener for the `addtrack` event + * to detect when a new track becomes available: + * https://developer.mozilla.org/en-US/docs/Web/API/MediaStream/onaddtrack + */ + get remoteMediaStream() { + return this._remoteMediaStream; + } + /** + * The data channel. Undefined before it is created. + */ + get dataChannel() { + return this._dataChannel; + } + /** + * The peer connection. Undefined if peer connection has closed. + * + * @remarks + * While access to the underlying `RTCPeerConnection` is provided, note that + * using methods with modify it may break the operation of this class. + * In particular, this class depends on exclusive access to the + * event handler properties. If you need access to the peer connection + * events, either register for events using `addEventListener()` on + * the `RTCPeerConnection` or set the `peerConnectionDelegate` on + * this `SessionDescriptionHandler`. + */ + get peerConnection() { + return this._peerConnection; + } + /** + * A delegate which provides access to the peer connection event handlers. + * + * @remarks + * Setting the peer connection event handlers directly is not supported + * and may break this class. As this class depends on exclusive access + * to them, a delegate may be set which provides alternative access to + * the event handlers in a fashion which is supported. + */ + get peerConnectionDelegate() { + return this._peerConnectionDelegate; + } + set peerConnectionDelegate(delegate) { + this._peerConnectionDelegate = delegate; + } + // The addtrack event does not get fired when JavaScript code explicitly adds tracks to the stream (by calling addTrack()). + // https://developer.mozilla.org/en-US/docs/Web/API/MediaStream/onaddtrack + static dispatchAddTrackEvent(stream, track) { + stream.dispatchEvent(new MediaStreamTrackEvent("addtrack", { track })); + } + // The removetrack event does not get fired when JavaScript code explicitly removes tracks from the stream (by calling removeTrack()). + // https://developer.mozilla.org/en-US/docs/Web/API/MediaStream/onremovetrack + static dispatchRemoveTrackEvent(stream, track) { + stream.dispatchEvent(new MediaStreamTrackEvent("removetrack", { track })); + } + /** + * Stop tracks and close peer connection. + */ + close() { + this.logger.debug("SessionDescriptionHandler.close"); + if (this._peerConnection === undefined) { + return; + } + this._peerConnection.getReceivers().forEach((receiver) => { + receiver.track && receiver.track.stop(); + }); + this._peerConnection.getSenders().forEach((sender) => { + sender.track && sender.track.stop(); + }); + if (this._dataChannel) { + this._dataChannel.close(); + } + this._peerConnection.close(); + this._peerConnection = undefined; + } + /** + * Creates an offer or answer. + * @param options - Options bucket. + * @param modifiers - Modifiers. + */ + getDescription(options, modifiers) { + var _a, _b; + this.logger.debug("SessionDescriptionHandler.getDescription"); + if (this._peerConnection === undefined) { + return Promise.reject(new Error("Peer connection closed.")); + } + // Callback on data channel creation + this.onDataChannel = options === null || options === void 0 ? void 0 : options.onDataChannel; + // ICE will restart upon applying an offer created with the iceRestart option + const iceRestart = (_a = options === null || options === void 0 ? void 0 : options.offerOptions) === null || _a === void 0 ? void 0 : _a.iceRestart; + // ICE gathering timeout may be set on a per call basis, otherwise the configured default is used + const iceTimeout = (options === null || options === void 0 ? void 0 : options.iceGatheringTimeout) === undefined + ? (_b = this.sessionDescriptionHandlerConfiguration) === null || _b === void 0 ? void 0 : _b.iceGatheringTimeout : options === null || options === void 0 ? void 0 : options.iceGatheringTimeout; + return this.getLocalMediaStream(options) + .then(() => this.createDataChannel(options)) + .then(() => this.createLocalOfferOrAnswer(options)) + .then((sessionDescription) => this.applyModifiers(sessionDescription, modifiers)) + .then((sessionDescription) => this.setLocalSessionDescription(sessionDescription)) + .then(() => this.waitForIceGatheringComplete(iceRestart, iceTimeout)) + .then(() => this.getLocalSessionDescription()) + .then((sessionDescription) => { + return { + body: sessionDescription.sdp, + contentType: "application/sdp" + }; + }) + .catch((error) => { + this.logger.error("SessionDescriptionHandler.getDescription failed - " + error); + throw error; + }); + } + /** + * Returns true if the SessionDescriptionHandler can handle the Content-Type described by a SIP message. + * @param contentType - The content type that is in the SIP Message. + */ + hasDescription(contentType) { + this.logger.debug("SessionDescriptionHandler.hasDescription"); + return contentType === "application/sdp"; + } + /** + * 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. + */ + sendDtmf(tones, options) { + this.logger.debug("SessionDescriptionHandler.sendDtmf"); + if (this._peerConnection === undefined) { + this.logger.error("SessionDescriptionHandler.sendDtmf failed - peer connection closed"); + return false; + } + const senders = this._peerConnection.getSenders(); + if (senders.length === 0) { + this.logger.error("SessionDescriptionHandler.sendDtmf failed - no senders"); + return false; + } + const dtmfSender = senders[0].dtmf; + if (!dtmfSender) { + this.logger.error("SessionDescriptionHandler.sendDtmf failed - no DTMF sender"); + return false; + } + const duration = options === null || options === void 0 ? void 0 : options.duration; + const interToneGap = options === null || options === void 0 ? void 0 : options.interToneGap; + try { + dtmfSender.insertDTMF(tones, duration, interToneGap); + } + catch (e) { + this.logger.error(e); + return false; + } + this.logger.log("SessionDescriptionHandler.sendDtmf sent via RTP: " + tones.toString()); + return true; + } + /** + * Sets an offer or answer. + * @param sdp - The session description. + * @param options - Options bucket. + * @param modifiers - Modifiers. + */ + setDescription(sdp, options, modifiers) { + this.logger.debug("SessionDescriptionHandler.setDescription"); + if (this._peerConnection === undefined) { + return Promise.reject(new Error("Peer connection closed.")); + } + // Callback on data channel creation + this.onDataChannel = options === null || options === void 0 ? void 0 : options.onDataChannel; + // SDP type + const type = this._peerConnection.signalingState === "have-local-offer" ? "answer" : "offer"; + return this.getLocalMediaStream(options) + .then(() => this.applyModifiers({ sdp, type }, modifiers)) + .then((sessionDescription) => this.setRemoteSessionDescription(sessionDescription)) + .catch((error) => { + this.logger.error("SessionDescriptionHandler.setDescription failed - " + error); + throw error; + }); + } + /** + * Applies modifiers to SDP prior to setting the local or remote description. + * @param sdp - SDP to modify. + * @param modifiers - Modifiers to apply. + */ + applyModifiers(sdp, modifiers) { + this.logger.debug("SessionDescriptionHandler.applyModifiers"); + if (!modifiers || modifiers.length === 0) { + return Promise.resolve(sdp); + } + return modifiers + .reduce((cur, next) => cur.then(next), Promise.resolve(sdp)) + .then((modified) => { + this.logger.debug("SessionDescriptionHandler.applyModifiers - modified sdp"); + if (!modified.sdp || !modified.type) { + throw new Error("Invalid SDP."); + } + return { sdp: modified.sdp, type: modified.type }; + }); + } + /** + * Create a data channel. + * @remarks + * Only creates a data channel if SessionDescriptionHandlerOptions.dataChannel is true. + * Only creates a data channel if creating a local offer. + * Only if one does not already exist. + * @param options - Session description handler options. + */ + createDataChannel(options) { + if (this._peerConnection === undefined) { + return Promise.reject(new Error("Peer connection closed.")); + } + // only create a data channel if requested + if ((options === null || options === void 0 ? void 0 : options.dataChannel) !== true) { + return Promise.resolve(); + } + // do not create a data channel if we already have one + if (this._dataChannel) { + return Promise.resolve(); + } + switch (this._peerConnection.signalingState) { + case "stable": + // if we are stable, assume we are creating a local offer so create a data channel + this.logger.debug("SessionDescriptionHandler.createDataChannel - creating data channel"); + try { + this._dataChannel = this._peerConnection.createDataChannel((options === null || options === void 0 ? void 0 : options.dataChannelLabel) || "", options === null || options === void 0 ? void 0 : options.dataChannelOptions); + if (this.onDataChannel) { + this.onDataChannel(this._dataChannel); + } + return Promise.resolve(); + } + catch (error) { + return Promise.reject(error); + } + case "have-remote-offer": + return Promise.resolve(); + case "have-local-offer": + case "have-local-pranswer": + case "have-remote-pranswer": + case "closed": + default: + return Promise.reject(new Error("Invalid signaling state " + this._peerConnection.signalingState)); + } + } + /** + * Depending on current signaling state, create a local offer or answer. + * @param options - Session description handler options. + */ + createLocalOfferOrAnswer(options) { + if (this._peerConnection === undefined) { + return Promise.reject(new Error("Peer connection closed.")); + } + switch (this._peerConnection.signalingState) { + case "stable": + // if we are stable, assume we are creating a local offer + this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP offer"); + return this._peerConnection.createOffer(options === null || options === void 0 ? void 0 : options.offerOptions); + case "have-remote-offer": + // if we have a remote offer, assume we are creating a local answer + this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP answer"); + return this._peerConnection.createAnswer(options === null || options === void 0 ? void 0 : options.answerOptions); + case "have-local-offer": + case "have-local-pranswer": + case "have-remote-pranswer": + case "closed": + default: + return Promise.reject(new Error("Invalid signaling state " + this._peerConnection.signalingState)); + } + } + /** + * Get a media stream from the media stream factory and set the local media stream. + * @param options - Session description handler options. + */ + getLocalMediaStream(options) { + this.logger.debug("SessionDescriptionHandler.getLocalMediaStream"); + if (this._peerConnection === undefined) { + return Promise.reject(new Error("Peer connection closed.")); + } + let constraints = Object.assign({}, options === null || options === void 0 ? void 0 : options.constraints); + // if we already have a local media stream... + if (this.localMediaStreamConstraints) { + // ignore constraint "downgrades" + constraints.audio = constraints.audio || this.localMediaStreamConstraints.audio; + constraints.video = constraints.video || this.localMediaStreamConstraints.video; + // if constraints have not changed, do not get a new media stream + if (JSON.stringify(this.localMediaStreamConstraints.audio) === JSON.stringify(constraints.audio) && + JSON.stringify(this.localMediaStreamConstraints.video) === JSON.stringify(constraints.video)) { + return Promise.resolve(); + } + } + else { + // if no constraints have been specified, default to audio for initial media stream + if (constraints.audio === undefined && constraints.video === undefined) { + constraints = { audio: true }; + } + } + this.localMediaStreamConstraints = constraints; + return this.mediaStreamFactory(constraints, this).then((mediaStream) => this.setLocalMediaStream(mediaStream)); + } + /** + * Sets the peer connection's sender tracks and local media stream tracks. + * + * @remarks + * Only the first audio and video tracks of the provided MediaStream are utilized. + * Adds tracks if audio and/or video tracks are not already present, otherwise replaces tracks. + * + * @param stream - Media stream containing tracks to be utilized. + */ + setLocalMediaStream(stream) { + this.logger.debug("SessionDescriptionHandler.setLocalMediaStream"); + if (!this._peerConnection) { + throw new Error("Peer connection undefined."); + } + const pc = this._peerConnection; + const localStream = this._localMediaStream; + const trackUpdates = []; + const updateTrack = (newTrack) => { + const kind = newTrack.kind; + if (kind !== "audio" && kind !== "video") { + throw new Error(`Unknown new track kind ${kind}.`); + } + const sender = pc.getSenders().find((sender) => sender.track && sender.track.kind === kind); + if (sender) { + trackUpdates.push(new Promise((resolve) => { + this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - replacing sender ${kind} track`); + resolve(); + }).then(() => sender + .replaceTrack(newTrack) + .then(() => { + const oldTrack = localStream.getTracks().find((localTrack) => localTrack.kind === kind); + if (oldTrack) { + oldTrack.stop(); + localStream.removeTrack(oldTrack); + SessionDescriptionHandler.dispatchRemoveTrackEvent(localStream, oldTrack); + } + localStream.addTrack(newTrack); + SessionDescriptionHandler.dispatchAddTrackEvent(localStream, newTrack); + }) + .catch((error) => { + this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to replace sender ${kind} track`); + throw error; + }))); + } + else { + trackUpdates.push(new Promise((resolve) => { + this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - adding sender ${kind} track`); + resolve(); + }).then(() => { + // Review: could make streamless tracks a configurable option? + // https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/addTrack#Usage_notes + try { + pc.addTrack(newTrack, localStream); + } + catch (error) { + this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to add sender ${kind} track`); + throw error; + } + localStream.addTrack(newTrack); + SessionDescriptionHandler.dispatchAddTrackEvent(localStream, newTrack); + })); + } + }; + // update peer connection audio tracks + const audioTracks = stream.getAudioTracks(); + if (audioTracks.length) { + updateTrack(audioTracks[0]); + } + // update peer connection video tracks + const videoTracks = stream.getVideoTracks(); + if (videoTracks.length) { + updateTrack(videoTracks[0]); + } + return trackUpdates.reduce((p, x) => p.then(() => x), Promise.resolve()); + } + /** + * Gets the peer connection's local session description. + */ + getLocalSessionDescription() { + this.logger.debug("SessionDescriptionHandler.getLocalSessionDescription"); + if (this._peerConnection === undefined) { + return Promise.reject(new Error("Peer connection closed.")); + } + const sdp = this._peerConnection.localDescription; + if (!sdp) { + return Promise.reject(new Error("Failed to get local session description")); + } + return Promise.resolve(sdp); + } + /** + * Sets the peer connection's local session description. + * @param sessionDescription - sessionDescription The session description. + */ + setLocalSessionDescription(sessionDescription) { + this.logger.debug("SessionDescriptionHandler.setLocalSessionDescription"); + if (this._peerConnection === undefined) { + return Promise.reject(new Error("Peer connection closed.")); + } + return this._peerConnection.setLocalDescription(sessionDescription); + } + /** + * Sets the peer connection's remote session description. + * @param sessionDescription - The session description. + */ + setRemoteSessionDescription(sessionDescription) { + this.logger.debug("SessionDescriptionHandler.setRemoteSessionDescription"); + if (this._peerConnection === undefined) { + return Promise.reject(new Error("Peer connection closed.")); + } + const sdp = sessionDescription.sdp; + let type; + switch (this._peerConnection.signalingState) { + case "stable": + // if we are stable assume this is a remote offer + type = "offer"; + break; + case "have-local-offer": + // if we made an offer, assume this is a remote answer + type = "answer"; + break; + case "have-local-pranswer": + case "have-remote-offer": + case "have-remote-pranswer": + case "closed": + default: + return Promise.reject(new Error("Invalid signaling state " + this._peerConnection.signalingState)); + } + if (!sdp) { + this.logger.error("SessionDescriptionHandler.setRemoteSessionDescription failed - cannot set null sdp"); + return Promise.reject(new Error("SDP is undefined")); + } + return this._peerConnection.setRemoteDescription({ sdp, type }); + } + /** + * Sets a remote media stream track. + * + * @remarks + * Adds tracks if audio and/or video tracks are not already present, otherwise replaces tracks. + * + * @param track - Media stream track to be utilized. + */ + setRemoteTrack(track) { + this.logger.debug("SessionDescriptionHandler.setRemoteTrack"); + const remoteStream = this._remoteMediaStream; + if (remoteStream.getTrackById(track.id)) { + this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - have remote ${track.kind} track`); + } + else if (track.kind === "audio") { + this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${track.kind} track`); + remoteStream.getAudioTracks().forEach((track) => { + track.stop(); + remoteStream.removeTrack(track); + SessionDescriptionHandler.dispatchRemoveTrackEvent(remoteStream, track); + }); + remoteStream.addTrack(track); + SessionDescriptionHandler.dispatchAddTrackEvent(remoteStream, track); + } + else if (track.kind === "video") { + this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${track.kind} track`); + remoteStream.getVideoTracks().forEach((track) => { + track.stop(); + remoteStream.removeTrack(track); + SessionDescriptionHandler.dispatchRemoveTrackEvent(remoteStream, track); + }); + remoteStream.addTrack(track); + SessionDescriptionHandler.dispatchAddTrackEvent(remoteStream, track); + } + } + /** + * Called when ICE gathering completes and resolves any waiting promise. + */ + iceGatheringComplete() { + this.logger.debug("SessionDescriptionHandler.iceGatheringComplete"); + // clear timer if need be + if (this.iceGatheringCompleteTimeoutId !== undefined) { + this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - clearing timeout"); + clearTimeout(this.iceGatheringCompleteTimeoutId); + this.iceGatheringCompleteTimeoutId = undefined; + } + // resolve and cleanup promise if need be + if (this.iceGatheringCompletePromise !== undefined) { + this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - resolving promise"); + this.iceGatheringCompleteResolve && this.iceGatheringCompleteResolve(); + this.iceGatheringCompletePromise = undefined; + this.iceGatheringCompleteResolve = undefined; + this.iceGatheringCompleteReject = undefined; + } + } + /** + * Wait for ICE gathering to complete. + * @param restart - If true, waits if current state is "complete" (waits for transition to "complete"). + * @param timeout - Milliseconds after which waiting times out. No timeout if 0. + */ + waitForIceGatheringComplete(restart = false, timeout = 0) { + this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete"); + if (this._peerConnection === undefined) { + return Promise.reject("Peer connection closed."); + } + // guard already complete + if (!restart && this._peerConnection.iceGatheringState === "complete") { + this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - already complete"); + return Promise.resolve(); + } + // only one may be waiting, reject any prior + if (this.iceGatheringCompletePromise !== undefined) { + this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - rejecting prior waiting promise"); + this.iceGatheringCompleteReject && this.iceGatheringCompleteReject(new Error("Promise superseded.")); + this.iceGatheringCompletePromise = undefined; + this.iceGatheringCompleteResolve = undefined; + this.iceGatheringCompleteReject = undefined; + } + this.iceGatheringCompletePromise = new Promise((resolve, reject) => { + this.iceGatheringCompleteResolve = resolve; + this.iceGatheringCompleteReject = reject; + if (timeout > 0) { + this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout in " + timeout); + this.iceGatheringCompleteTimeoutId = setTimeout(() => { + this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout"); + this.iceGatheringComplete(); + }, timeout); + } + }); + return this.iceGatheringCompletePromise; + } + /** + * Initializes the peer connection event handlers + */ + initPeerConnectionEventHandlers() { + this.logger.debug("SessionDescriptionHandler.initPeerConnectionEventHandlers"); + if (!this._peerConnection) + throw new Error("Peer connection undefined."); + const peerConnection = this._peerConnection; + peerConnection.onconnectionstatechange = (event) => { + var _a; + const newState = peerConnection.connectionState; + this.logger.debug(`SessionDescriptionHandler.onconnectionstatechange ${newState}`); + if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onconnectionstatechange) { + this._peerConnectionDelegate.onconnectionstatechange(event); + } + }; + peerConnection.ondatachannel = (event) => { + var _a; + this.logger.debug(`SessionDescriptionHandler.ondatachannel`); + this._dataChannel = event.channel; + if (this.onDataChannel) { + this.onDataChannel(this._dataChannel); + } + if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.ondatachannel) { + this._peerConnectionDelegate.ondatachannel(event); + } + }; + peerConnection.onicecandidate = (event) => { + var _a; + this.logger.debug(`SessionDescriptionHandler.onicecandidate`); + if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onicecandidate) { + this._peerConnectionDelegate.onicecandidate(event); + } + }; + peerConnection.onicecandidateerror = (event) => { + var _a; + this.logger.debug(`SessionDescriptionHandler.onicecandidateerror`); + if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onicecandidateerror) { + this._peerConnectionDelegate.onicecandidateerror(event); + } + }; + peerConnection.oniceconnectionstatechange = (event) => { + var _a; + const newState = peerConnection.iceConnectionState; + this.logger.debug(`SessionDescriptionHandler.oniceconnectionstatechange ${newState}`); + if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.oniceconnectionstatechange) { + this._peerConnectionDelegate.oniceconnectionstatechange(event); + } + }; + peerConnection.onicegatheringstatechange = (event) => { + var _a; + const newState = peerConnection.iceGatheringState; + this.logger.debug(`SessionDescriptionHandler.onicegatheringstatechange ${newState}`); + if (newState === "complete") { + this.iceGatheringComplete(); // complete waiting for ICE gathering to complete + } + if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onicegatheringstatechange) { + this._peerConnectionDelegate.onicegatheringstatechange(event); + } + }; + peerConnection.onnegotiationneeded = (event) => { + var _a; + this.logger.debug(`SessionDescriptionHandler.onnegotiationneeded`); + if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onnegotiationneeded) { + this._peerConnectionDelegate.onnegotiationneeded(event); + } + }; + peerConnection.onsignalingstatechange = (event) => { + var _a; + const newState = peerConnection.signalingState; + this.logger.debug(`SessionDescriptionHandler.onsignalingstatechange ${newState}`); + if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onsignalingstatechange) { + this._peerConnectionDelegate.onsignalingstatechange(event); + } + }; + peerConnection.onstatsended = (event) => { + var _a; + this.logger.debug(`SessionDescriptionHandler.onstatsended`); + if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onstatsended) { + this._peerConnectionDelegate.onstatsended(event); + } + }; + peerConnection.ontrack = (event) => { + var _a; + const kind = event.track.kind; + const enabled = event.track.enabled ? "enabled" : "disabled"; + this.logger.debug(`SessionDescriptionHandler.ontrack ${kind} ${enabled}`); + this.setRemoteTrack(event.track); + if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.ontrack) { + this._peerConnectionDelegate.ontrack(event); + } + }; + } +} + + +/***/ }), +/* 168 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 169 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 170 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 171 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _transport__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(172); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Transport", function() { return _transport__WEBPACK_IMPORTED_MODULE_0__["Transport"]; }); + +/* harmony import */ var _transport_options__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(173); +/* empty/unused harmony star reexport *//** + * A Transport implementation for web browsers. + * @packageDocumentation + */ + + + + +/***/ }), +/* 172 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Transport", function() { return Transport; }); +/* harmony import */ var _api_emitter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(108); +/* harmony import */ var _api_exceptions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3); +/* harmony import */ var _api_transport_state__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(156); +/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(5); + + + + +/** + * Transport for SIP over secure WebSocket (WSS). + * @public + */ +class Transport { + constructor(logger, options) { + this._state = _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected; + this.transitioningState = false; + // state emitter + this._stateEventEmitter = new _api_emitter__WEBPACK_IMPORTED_MODULE_0__["EmitterImpl"](); + // logger + this.logger = logger; + // guard deprecated options (remove this in version 16.x) + if (options) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const optionsDeprecated = options; + const wsServersDeprecated = optionsDeprecated === null || optionsDeprecated === void 0 ? void 0 : optionsDeprecated.wsServers; + const maxReconnectionAttemptsDeprecated = optionsDeprecated === null || optionsDeprecated === void 0 ? void 0 : optionsDeprecated.maxReconnectionAttempts; + if (wsServersDeprecated !== undefined) { + const deprecatedMessage = `The transport option "wsServers" as has apparently been specified and has been deprecated. ` + + "It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly."; + this.logger.warn(deprecatedMessage); + } + if (maxReconnectionAttemptsDeprecated !== undefined) { + const deprecatedMessage = `The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. ` + + "It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly."; + this.logger.warn(deprecatedMessage); + } + // hack + if (wsServersDeprecated && !options.server) { + if (typeof wsServersDeprecated === "string") { + options.server = wsServersDeprecated; + } + if (wsServersDeprecated instanceof Array) { + options.server = wsServersDeprecated[0]; + } + } + } + // initialize configuration + this.configuration = Object.assign(Object.assign({}, Transport.defaultOptions), options); + // validate server URL + const url = this.configuration.server; + const parsed = _core__WEBPACK_IMPORTED_MODULE_3__["Grammar"].parse(url, "absoluteURI"); + if (parsed === -1) { + this.logger.error(`Invalid WebSocket Server URL "${url}"`); + throw new Error("Invalid WebSocket Server URL"); + } + if (!["wss", "ws", "udp"].includes(parsed.scheme)) { + this.logger.error(`Invalid scheme in WebSocket Server URL "${url}"`); + throw new Error("Invalid scheme in WebSocket Server URL"); + } + this._protocol = parsed.scheme.toUpperCase(); + } + dispose() { + return this.disconnect(); + } + /** + * The protocol. + * + * @remarks + * Formatted as defined for the Via header sent-protocol transport. + * https://tools.ietf.org/html/rfc3261#section-20.42 + */ + get protocol() { + return this._protocol; + } + /** + * The URL of the WebSocket Server. + */ + get server() { + return this.configuration.server; + } + /** + * Transport state. + */ + get state() { + return this._state; + } + /** + * Transport state change emitter. + */ + get stateChange() { + return this._stateEventEmitter; + } + /** + * The WebSocket. + */ + get ws() { + return this._ws; + } + /** + * Connect to network. + * Resolves once connected. Otherwise rejects with an Error. + */ + connect() { + return this._connect(); + } + /** + * Disconnect from network. + * Resolves once disconnected. Otherwise rejects with an Error. + */ + disconnect() { + return this._disconnect(); + } + /** + * Returns true if the `state` equals "Connected". + * @remarks + * This is equivalent to `state === TransportState.Connected`. + */ + isConnected() { + return this.state === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected; + } + /** + * Sends a message. + * Resolves once message is sent. Otherwise rejects with an Error. + * @param message - Message to send. + */ + send(message) { + // Error handling is independent of whether the message was a request or + // response. + // + // If the transport user asks for a message to be sent over an + // unreliable transport, and the result is an ICMP error, the behavior + // depends on the type of ICMP error. Host, network, port or protocol + // unreachable errors, or parameter problem errors SHOULD cause the + // transport layer to inform the transport user of a failure in sending. + // Source quench and TTL exceeded ICMP errors SHOULD be ignored. + // + // If the transport user asks for a request to be sent over a reliable + // transport, and the result is a connection failure, the transport + // layer SHOULD inform the transport user of a failure in sending. + // https://tools.ietf.org/html/rfc3261#section-18.4 + return this._send(message); + } + _connect() { + this.logger.log(`Connecting ${this.server}`); + switch (this.state) { + case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting: + // If `state` is "Connecting", `state` MUST NOT transition before returning. + if (this.transitioningState) { + return Promise.reject(this.transitionLoopDetectedError(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting)); + } + if (!this.connectPromise) { + throw new Error("Connect promise must be defined."); + } + return this.connectPromise; // Already connecting + case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected: + // If `state` is "Connected", `state` MUST NOT transition before returning. + if (this.transitioningState) { + return Promise.reject(this.transitionLoopDetectedError(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting)); + } + if (this.connectPromise) { + throw new Error("Connect promise must not be defined."); + } + return Promise.resolve(); // Already connected + case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting: + // If `state` is "Disconnecting", `state` MUST transition to "Connecting" before returning + if (this.connectPromise) { + throw new Error("Connect promise must not be defined."); + } + try { + this.transitionState(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting); + } + catch (e) { + if (e instanceof _api_exceptions__WEBPACK_IMPORTED_MODULE_1__["StateTransitionError"]) { + return Promise.reject(e); // Loop detected + } + throw e; + } + break; + case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected: + // If `state` is "Disconnected" `state` MUST transition to "Connecting" before returning + if (this.connectPromise) { + throw new Error("Connect promise must not be defined."); + } + try { + this.transitionState(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting); + } + catch (e) { + if (e instanceof _api_exceptions__WEBPACK_IMPORTED_MODULE_1__["StateTransitionError"]) { + return Promise.reject(e); // Loop detected + } + throw e; + } + break; + default: + throw new Error("Unknown state"); + } + let ws; + try { + // WebSocket() + // https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/WebSocket + ws = new WebSocket(this.server, "sip"); + ws.binaryType = "arraybuffer"; // set data type of received binary messages + ws.addEventListener("close", (ev) => this.onWebSocketClose(ev, ws)); + ws.addEventListener("error", (ev) => this.onWebSocketError(ev, ws)); + ws.addEventListener("open", (ev) => this.onWebSocketOpen(ev, ws)); + ws.addEventListener("message", (ev) => this.onWebSocketMessage(ev, ws)); + this._ws = ws; + } + catch (error) { + this._ws = undefined; + this.logger.error("WebSocket construction failed."); + this.logger.error(error); + return new Promise((resolve, reject) => { + this.connectResolve = resolve; + this.connectReject = reject; + // The `state` MUST transition to "Disconnecting" or "Disconnected" before rejecting + this.transitionState(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected, error); + }); + } + this.connectPromise = new Promise((resolve, reject) => { + this.connectResolve = resolve; + this.connectReject = reject; + this.connectTimeout = setTimeout(() => { + this.logger.warn("Connect timed out. " + + "Exceeded time set in configuration.connectionTimeout: " + + this.configuration.connectionTimeout + + "s."); + ws.close(1000); // careful here to use a local reference instead of this._ws + }, this.configuration.connectionTimeout * 1000); + }); + return this.connectPromise; + } + _disconnect() { + this.logger.log(`Disconnecting ${this.server}`); + switch (this.state) { + case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting: + // If `state` is "Connecting", `state` MUST transition to "Disconnecting" before returning. + if (this.disconnectPromise) { + throw new Error("Disconnect promise must not be defined."); + } + try { + this.transitionState(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting); + } + catch (e) { + if (e instanceof _api_exceptions__WEBPACK_IMPORTED_MODULE_1__["StateTransitionError"]) { + return Promise.reject(e); // Loop detected + } + throw e; + } + break; + case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected: + // If `state` is "Connected", `state` MUST transition to "Disconnecting" before returning. + if (this.disconnectPromise) { + throw new Error("Disconnect promise must not be defined."); + } + try { + this.transitionState(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting); + } + catch (e) { + if (e instanceof _api_exceptions__WEBPACK_IMPORTED_MODULE_1__["StateTransitionError"]) { + return Promise.reject(e); // Loop detected + } + throw e; + } + break; + case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting: + // If `state` is "Disconnecting", `state` MUST NOT transition before returning. + if (this.transitioningState) { + return Promise.reject(this.transitionLoopDetectedError(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting)); + } + if (!this.disconnectPromise) { + throw new Error("Disconnect promise must be defined."); + } + return this.disconnectPromise; // Already disconnecting + case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected: + // If `state` is "Disconnected", `state` MUST NOT transition before returning. + if (this.transitioningState) { + return Promise.reject(this.transitionLoopDetectedError(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting)); + } + if (this.disconnectPromise) { + throw new Error("Disconnect promise must not be defined."); + } + return Promise.resolve(); // Already disconnected + default: + throw new Error("Unknown state"); + } + if (!this._ws) { + throw new Error("WebSocket must be defined."); + } + const ws = this._ws; + this.disconnectPromise = new Promise((resolve, reject) => { + this.disconnectResolve = resolve; + this.disconnectReject = reject; + try { + // WebSocket.close() + // https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close + ws.close(1000); // careful here to use a local reference instead of this._ws + } + catch (error) { + // Treating this as a coding error as it apparently can only happen + // if you pass close() invalid parameters (so it should never happen) + this.logger.error("WebSocket close failed."); + this.logger.error(error); + throw error; + } + }); + return this.disconnectPromise; + } + _send(message) { + if (this.configuration.traceSip === true) { + this.logger.log("Sending WebSocket message:\n\n" + message + "\n"); + } + if (this._state !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected) { + return Promise.reject(new Error("Not connected.")); + } + if (!this._ws) { + throw new Error("WebSocket undefined."); + } + try { + // WebSocket.send() + // https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send + this._ws.send(message); + } + catch (error) { + if (error instanceof Error) { + return Promise.reject(error); + } + return Promise.reject(new Error("WebSocket send failed.")); + } + return Promise.resolve(); + } + /** + * WebSocket "onclose" event handler. + * @param ev - Event. + */ + onWebSocketClose(ev, ws) { + if (ws !== this._ws) { + return; + } + const message = `WebSocket closed ${this.server} (code: ${ev.code})`; + const error = !this.disconnectPromise ? new Error(message) : undefined; + if (error) { + this.logger.warn("WebSocket closed unexpectedly"); + } + this.logger.log(message); + // We are about to transition to disconnected, so clear our web socket + this._ws = undefined; + // The `state` MUST transition to "Disconnected" before resolving (assuming `state` is not already "Disconnected"). + this.transitionState(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected, error); + } + /** + * WebSocket "onerror" event handler. + * @param ev - Event. + */ + onWebSocketError(ev, ws) { + if (ws !== this._ws) { + return; + } + this.logger.error("WebSocket error occurred."); + } + /** + * WebSocket "onmessage" event handler. + * @param ev - Event. + */ + onWebSocketMessage(ev, ws) { + if (ws !== this._ws) { + return; + } + const data = ev.data; + let 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; + } + if (!data) { + this.logger.warn("Received empty message, discarding..."); + return; + } + if (typeof data !== "string") { + // WebSocket binary message. + try { + finishedData = new TextDecoder().decode(new Uint8Array(data)); + // TextDecoder (above) is not supported by old browsers, but it correctly decodes UTF-8. + // The line below is an ISO 8859-1 (Latin 1) decoder, so just UTF-8 code points that are 1 byte. + // It's old code and works in old browsers (IE), so leaving it here in a comment in case someone needs it. + // finishedData = String.fromCharCode.apply(null, (new Uint8Array(data) as unknown as Array)); + } + catch (err) { + this.logger.error(err); + this.logger.error("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" + finishedData + "\n"); + } + } + else { + // WebSocket text message. + finishedData = data; + if (this.configuration.traceSip === true) { + this.logger.log("Received WebSocket text message:\n\n" + finishedData + "\n"); + } + } + if (this.state !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected) { + this.logger.warn("Received message while not connected, discarding..."); + return; + } + if (this.onMessage) { + try { + this.onMessage(finishedData); + } + catch (e) { + this.logger.error(e); + this.logger.error("Exception thrown by onMessage callback"); + throw e; // rethrow unhandled exception + } + } + } + /** + * WebSocket "onopen" event handler. + * @param ev - Event. + */ + onWebSocketOpen(ev, ws) { + if (ws !== this._ws) { + return; + } + if (this._state === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting) { + this.logger.log(`WebSocket opened ${this.server}`); + this.transitionState(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected); + } + } + /** + * Helper function to generate an Error. + * @param state - State transitioning to. + */ + transitionLoopDetectedError(state) { + let message = `A state transition loop has been detected.`; + message += ` An attempt to transition from ${this._state} to ${state} before the prior transition completed.`; + message += ` Perhaps you are synchronously calling connect() or disconnect() from a callback or state change handler?`; + this.logger.error(message); + return new _api_exceptions__WEBPACK_IMPORTED_MODULE_1__["StateTransitionError"]("Loop detected."); + } + /** + * Transition transport state. + * @internal + */ + transitionState(newState, error) { + const invalidTransition = () => { + throw new Error(`Invalid state transition from ${this._state} to ${newState}`); + }; + if (this.transitioningState) { + throw this.transitionLoopDetectedError(newState); + } + this.transitioningState = true; + // Validate state transition + switch (this._state) { + case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting: + if (newState !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected && + newState !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting && + newState !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected) { + invalidTransition(); + } + break; + case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected: + if (newState !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting && newState !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected) { + invalidTransition(); + } + break; + case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting: + if (newState !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting && newState !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected) { + invalidTransition(); + } + break; + case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected: + if (newState !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting) { + invalidTransition(); + } + break; + default: + throw new Error("Unknown state."); + } + // Update state + const oldState = this._state; + this._state = newState; + // Local copies of connect promises (guarding against callbacks changing them indirectly) + // const connectPromise = this.connectPromise; + const connectResolve = this.connectResolve; + const connectReject = this.connectReject; + // Reset connect promises if no longer connecting + if (oldState === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting) { + this.connectPromise = undefined; + this.connectResolve = undefined; + this.connectReject = undefined; + } + // Local copies of disconnect promises (guarding against callbacks changing them indirectly) + // const disconnectPromise = this.disconnectPromise; + const disconnectResolve = this.disconnectResolve; + const disconnectReject = this.disconnectReject; + // Reset disconnect promises if no longer disconnecting + if (oldState === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting) { + this.disconnectPromise = undefined; + this.disconnectResolve = undefined; + this.disconnectReject = undefined; + } + // Clear any outstanding connect timeout + if (this.connectTimeout) { + clearTimeout(this.connectTimeout); + this.connectTimeout = undefined; + } + this.logger.log(`Transitioned from ${oldState} to ${this._state}`); + this._stateEventEmitter.emit(this._state); + // Transition to Connected + if (newState === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected) { + this.startSendingKeepAlives(); + if (this.onConnect) { + try { + this.onConnect(); + } + catch (e) { + this.logger.error(e); + this.logger.error("Exception thrown by onConnect callback"); + throw e; // rethrow unhandled exception + } + } + } + // Transition from Connected + if (oldState === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected) { + this.stopSendingKeepAlives(); + if (this.onDisconnect) { + try { + if (error) { + this.onDisconnect(error); + } + else { + this.onDisconnect(); + } + } + catch (e) { + this.logger.error(e); + this.logger.error("Exception thrown by onDisconnect callback"); + throw e; // rethrow unhandled exception + } + } + } + // Complete connect promise + if (oldState === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting) { + if (!connectResolve) { + throw new Error("Connect resolve undefined."); + } + if (!connectReject) { + throw new Error("Connect reject undefined."); + } + newState === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected ? connectResolve() : connectReject(error || new Error("Connect aborted.")); + } + // Complete disconnect promise + if (oldState === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting) { + if (!disconnectResolve) { + throw new Error("Disconnect resolve undefined."); + } + if (!disconnectReject) { + throw new Error("Disconnect reject undefined."); + } + newState === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected + ? disconnectResolve() + : disconnectReject(error || new Error("Disconnect aborted.")); + } + this.transitioningState = false; + } + // TODO: Review "KeepAlive Stuff". + // It is not clear if it works and there are no tests for it. + // It was blindly lifted the keep alive code unchanged from earlier transport code. + // + // From the RFC... + // + // SIP WebSocket Clients and Servers may keep their WebSocket + // connections open by sending periodic WebSocket "Ping" frames as + // described in [RFC6455], Section 5.5.2. + // ... + // The indication and use of the CRLF NAT keep-alive mechanism defined + // for SIP connection-oriented transports in [RFC5626], Section 3.5.1 or + // [RFC6223] are, of course, usable over the transport defined in this + // specification. + // https://tools.ietf.org/html/rfc7118#section-6 + // + // and... + // + // The Ping frame contains an opcode of 0x9. + // https://tools.ietf.org/html/rfc6455#section-5.5.2 + // + // ============================== + // KeepAlive Stuff + // ============================== + clearKeepAliveTimeout() { + if (this.keepAliveDebounceTimeout) { + clearTimeout(this.keepAliveDebounceTimeout); + } + this.keepAliveDebounceTimeout = undefined; + } + /** + * Send a keep-alive (a double-CRLF sequence). + */ + sendKeepAlive() { + if (this.keepAliveDebounceTimeout) { + // We already have an outstanding keep alive, do not send another. + return Promise.resolve(); + } + this.keepAliveDebounceTimeout = setTimeout(() => { + this.clearKeepAliveTimeout(); + }, this.configuration.keepAliveDebounce * 1000); + return this.send("\r\n\r\n"); + } + /** + * Start sending keep-alives. + */ + startSendingKeepAlives() { + // Compute an amount of time in seconds to wait before sending another keep-alive. + const computeKeepAliveTimeout = (upperBound) => { + const lowerBound = upperBound * 0.8; + return 1000 * (Math.random() * (upperBound - lowerBound) + lowerBound); + }; + if (this.configuration.keepAliveInterval && !this.keepAliveInterval) { + this.keepAliveInterval = setInterval(() => { + this.sendKeepAlive(); + this.startSendingKeepAlives(); + }, computeKeepAliveTimeout(this.configuration.keepAliveInterval)); + } + } + /** + * Stop sending keep-alives. + */ + stopSendingKeepAlives() { + if (this.keepAliveInterval) { + clearInterval(this.keepAliveInterval); + } + if (this.keepAliveDebounceTimeout) { + clearTimeout(this.keepAliveDebounceTimeout); + } + this.keepAliveInterval = undefined; + this.keepAliveDebounceTimeout = undefined; + } +} +Transport.defaultOptions = { + server: "", + connectionTimeout: 5, + keepAliveInterval: 0, + keepAliveDebounce: 10, + traceSip: true +}; + + +/***/ }), +/* 173 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 174 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _modifiers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(175); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripTcpCandidates", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripTcpCandidates"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripTelephoneEvent", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripTelephoneEvent"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "cleanJitsiSdpImageattr", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["cleanJitsiSdpImageattr"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripG722", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripG722"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripRtpPayload", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripRtpPayload"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripVideo", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripVideo"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "addMidLines", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["addMidLines"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "holdModifier", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["holdModifier"]; }); + +/* harmony import */ var _session_description_handler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(160); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "defaultMediaStreamFactory", function() { return _session_description_handler__WEBPACK_IMPORTED_MODULE_1__["defaultMediaStreamFactory"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "defaultPeerConnectionConfiguration", function() { return _session_description_handler__WEBPACK_IMPORTED_MODULE_1__["defaultPeerConnectionConfiguration"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "defaultSessionDescriptionHandlerFactory", function() { return _session_description_handler__WEBPACK_IMPORTED_MODULE_1__["defaultSessionDescriptionHandlerFactory"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionDescriptionHandler", function() { return _session_description_handler__WEBPACK_IMPORTED_MODULE_1__["SessionDescriptionHandler"]; }); + +/* harmony import */ var _simple_user__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(177); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SimpleUser", function() { return _simple_user__WEBPACK_IMPORTED_MODULE_2__["SimpleUser"]; }); + +/* harmony import */ var _transport__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(171); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Transport", function() { return _transport__WEBPACK_IMPORTED_MODULE_3__["Transport"]; }); + + + + + + + +/***/ }), +/* 175 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _modifiers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(176); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripTcpCandidates", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripTcpCandidates"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripTelephoneEvent", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripTelephoneEvent"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "cleanJitsiSdpImageattr", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["cleanJitsiSdpImageattr"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripG722", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripG722"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripRtpPayload", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripRtpPayload"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripVideo", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripVideo"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "addMidLines", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["addMidLines"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "holdModifier", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["holdModifier"]; }); + +/** + * SessionDescriptionHandlerModifer functions for web browsers. + * @packageDocumentation + */ + + + +/***/ }), +/* 176 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stripTcpCandidates", function() { return stripTcpCandidates; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stripTelephoneEvent", function() { return stripTelephoneEvent; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "cleanJitsiSdpImageattr", function() { return cleanJitsiSdpImageattr; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stripG722", function() { return stripG722; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stripRtpPayload", function() { return stripRtpPayload; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stripVideo", function() { return stripVideo; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addMidLines", function() { return addMidLines; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "holdModifier", function() { return holdModifier; }); +const stripPayload = (sdp, payload) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const mediaDescs = []; + const lines = sdp.split(/\r\n/); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let currentMediaDesc; + for (let i = 0; i < lines.length;) { + const line = lines[i]; + if (/^m=(?:audio|video)/.test(line)) { + currentMediaDesc = { + index: i, + stripped: [] + }; + mediaDescs.push(currentMediaDesc); + } + else if (currentMediaDesc) { + const 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 (const mediaDesc of mediaDescs) { + const mline = lines[mediaDesc.index].split(" "); + // Ignore the first 3 parameters of the mline. The codec information is after that + for (let 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"); +}; +const stripMediaDescription = (sdp, description) => { + const descriptionRegExp = new RegExp("m=" + description + ".*$", "gm"); + const groupRegExp = new RegExp("^a=group:.*$", "gm"); + if (descriptionRegExp.test(sdp)) { + let midLineToRemove; + sdp = sdp.split(/^m=/gm).filter((section) => { + if (section.substr(0, description.length) === description) { + midLineToRemove = section.match(/^a=mid:.*$/gm); + if (midLineToRemove) { + const step = midLineToRemove[0].match(/:.+$/g); + if (step) { + midLineToRemove = step[0].substr(1); + } + } + return false; + } + return true; + }).join("m="); + const groupLine = sdp.match(groupRegExp); + if (groupLine && groupLine.length === 1) { + let groupLinePortion = groupLine[0]; + // eslint-disable-next-line no-useless-escape + const groupRegExpReplace = new RegExp("\ *" + midLineToRemove + "[^\ ]*", "g"); + groupLinePortion = groupLinePortion.replace(groupRegExpReplace, ""); + sdp = sdp.split(groupRegExp).join(groupLinePortion); + } + } + return sdp; +}; +/** + * Modifier. + * @public + */ +function stripTcpCandidates(description) { + description.sdp = (description.sdp || "").replace(/^a=candidate:\d+ \d+ tcp .*?\r\n/img, ""); + return Promise.resolve(description); +} +/** + * Modifier. + * @public + */ +function stripTelephoneEvent(description) { + description.sdp = stripPayload(description.sdp || "", "telephone-event"); + return Promise.resolve(description); +} +/** + * Modifier. + * @public + */ +function cleanJitsiSdpImageattr(description) { + description.sdp = (description.sdp || "").replace(/^(a=imageattr:.*?)(x|y)=\[0-/gm, "$1$2=[1:"); + return Promise.resolve(description); +} +/** + * Modifier. + * @public + */ +function stripG722(description) { + description.sdp = stripPayload(description.sdp || "", "G722"); + return Promise.resolve(description); +} +/** + * Modifier. + * @public + */ +function stripRtpPayload(payload) { + return (description) => { + description.sdp = stripPayload(description.sdp || "", payload); + return Promise.resolve(description); + }; +} +/** + * Modifier. + * @public + */ +function stripVideo(description) { + description.sdp = stripMediaDescription(description.sdp || "", "video"); + return Promise.resolve(description); +} +/** + * Modifier. + * @public + */ +function addMidLines(description) { + let sdp = description.sdp || ""; + if (sdp.search(/^a=mid.*$/gm) === -1) { + const mlines = sdp.match(/^m=.*$/gm); + const sdpArray = sdp.split(/^m=.*$/gm); + if (mlines) { + mlines.forEach((elem, idx) => { + mlines[idx] = elem + "\na=mid:" + idx; + }); + } + sdpArray.forEach((elem, idx) => { + if (mlines && mlines[idx]) { + sdpArray[idx] = elem + mlines[idx]; + } + }); + sdp = sdpArray.join(""); + description.sdp = sdp; + } + return Promise.resolve(description); +} +/** + * The modifier that should be used when the session would like to place the call on hold. + * @param description - The description that will be modified. + */ +function holdModifier(description) { + if (!description.sdp || !description.type) { + throw new Error("Invalid SDP"); + } + let sdp = description.sdp; + const type = description.type; + if (sdp) { + if (!/a=(sendrecv|sendonly|recvonly|inactive)/.test(sdp)) { + sdp = sdp.replace(/(m=[^\r]*\r\n)/g, "$1a=sendonly\r\n"); + } + else { + sdp = sdp.replace(/a=sendrecv\r\n/g, "a=sendonly\r\n"); + sdp = sdp.replace(/a=recvonly\r\n/g, "a=inactive\r\n"); + } + } + return Promise.resolve({ sdp, type }); +} + + +/***/ }), +/* 177 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _simple_user__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(178); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SimpleUser", function() { return _simple_user__WEBPACK_IMPORTED_MODULE_0__["SimpleUser"]; }); + +/* harmony import */ var _simple_user_delegate__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(179); +/* empty/unused harmony star reexport *//* harmony import */ var _simple_user_options__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(180); +/* empty/unused harmony star reexport *//** + * A simple SIP user implementation for web browsers. + * @packageDocumentation + */ + + + + + +/***/ }), +/* 178 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SimpleUser", function() { return SimpleUser; }); +/* harmony import */ var _api__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); +/* harmony import */ var _modifiers__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(175); +/* harmony import */ var _session_description_handler__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(160); +/* harmony import */ var _transport__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(171); + + + + +/** + * A simple SIP user class. + * @remarks + * While this class is completely functional for simple use cases, it is not intended + * to provide an interface which is suitable for most (must less all) applications. + * While this class has many limitations (for example, it only handles a single concurrent session), + * it is, however, intended to serve as a simple example of using the SIP.js API. + * @public + */ +class SimpleUser { + /** + * Constructs a new instance of the `SimpleUser` class. + * @param server - SIP WebSocket Server URL. + * @param options - Options bucket. See {@link SimpleUserOptions} for details. + */ + constructor(server, options = {}) { + this.attemptingReconnection = false; + this.connectRequested = false; + this.held = false; + this.registerer = undefined; + this.registerRequested = false; + this.session = undefined; + // Delegate + this.delegate = options.delegate; + // Copy options + this.options = Object.assign({}, options); + // UserAgentOptions + const userAgentOptions = Object.assign({}, options.userAgentOptions); + // Transport + if (!userAgentOptions.transportConstructor) { + userAgentOptions.transportConstructor = _transport__WEBPACK_IMPORTED_MODULE_3__["Transport"]; + } + // TransportOptions + if (!userAgentOptions.transportOptions) { + userAgentOptions.transportOptions = { + server + }; + } + // URI + if (!userAgentOptions.uri) { + // If an AOR was provided, convert it to a URI + if (options.aor) { + const uri = _api__WEBPACK_IMPORTED_MODULE_0__["UserAgent"].makeURI(options.aor); + if (!uri) { + throw new Error(`Failed to create valid URI from ${options.aor}`); + } + userAgentOptions.uri = uri; + } + } + // UserAgent + this.userAgent = new _api__WEBPACK_IMPORTED_MODULE_0__["UserAgent"](userAgentOptions); + // UserAgent's delegate + this.userAgent.delegate = { + // Handle connection with server established + onConnect: () => { + this.logger.log(`[${this.id}] Connected`); + if (this.delegate && this.delegate.onServerConnect) { + this.delegate.onServerConnect(); + } + if (this.registerer && this.registerRequested) { + this.logger.log(`[${this.id}] Registering...`); + this.registerer.register().catch((e) => { + this.logger.error(`[${this.id}] Error occurred registering after connection with server was obtained.`); + this.logger.error(e.toString()); + }); + } + }, + // Handle connection with server lost + onDisconnect: (error) => { + this.logger.log(`[${this.id}] Disconnected`); + if (this.delegate && this.delegate.onServerDisconnect) { + this.delegate.onServerDisconnect(error); + } + if (this.session) { + this.logger.log(`[${this.id}] Hanging up...`); + this.hangup() // cleanup hung calls + .catch((e) => { + this.logger.error(`[${this.id}] Error occurred hanging up call after connection with server was lost.`); + this.logger.error(e.toString()); + }); + } + if (this.registerer) { + this.logger.log(`[${this.id}] Unregistering...`); + this.registerer + .unregister() // cleanup invalid registrations + .catch((e) => { + this.logger.error(`[${this.id}] Error occurred unregistering after connection with server was lost.`); + this.logger.error(e.toString()); + }); + } + // Only attempt to reconnect if network/server dropped the connection. + if (error) { + this.attemptReconnection(); + } + }, + // Handle incoming invitations + onInvite: (invitation) => { + this.logger.log(`[${this.id}] Received INVITE`); + // Guard against a pre-existing session. This implementation only supports one session at a time. + // However an incoming INVITE request may be received at any time and/or while in the process + // of sending an outgoing INVITE request. So we reject any incoming INVITE in those cases. + if (this.session) { + this.logger.warn(`[${this.id}] Session already in progress, rejecting INVITE...`); + invitation + .reject() + .then(() => { + this.logger.log(`[${this.id}] Rejected INVITE`); + }) + .catch((error) => { + this.logger.error(`[${this.id}] Failed to reject INVITE`); + this.logger.error(error.toString()); + }); + return; + } + // Use our configured constraints as options for any Inviter created as result of a REFER + const referralInviterOptions = { + sessionDescriptionHandlerOptions: { constraints: this.constraints } + }; + // Initialize our session + this.initSession(invitation, referralInviterOptions); + // Delegate + if (this.delegate && this.delegate.onCallReceived) { + this.delegate.onCallReceived(); + } + else { + this.logger.warn(`[${this.id}] No handler available, rejecting INVITE...`); + invitation + .reject() + .then(() => { + this.logger.log(`[${this.id}] Rejected INVITE`); + }) + .catch((error) => { + this.logger.error(`[${this.id}] Failed to reject INVITE`); + this.logger.error(error.toString()); + }); + } + }, + // Handle incoming messages + onMessage: (message) => { + message.accept().then(() => { + if (this.delegate && this.delegate.onMessageReceived) { + this.delegate.onMessageReceived(message.request.body); + } + }); + } + }; + // Use the SIP.js logger + this.logger = this.userAgent.getLogger("sip.SimpleUser"); + // Monitor network connectivity and attempt reconnection when we come online + window.addEventListener("online", () => { + this.logger.log(`[${this.id}] Online`); + this.attemptReconnection(); + }); + } + /** + * Instance identifier. + * @internal + */ + get id() { + return (this.options.userAgentOptions && this.options.userAgentOptions.displayName) || "Anonymous"; + } + /** The local media stream. Undefined if call not answered. */ + get localMediaStream() { + var _a; + const sdh = (_a = this.session) === null || _a === void 0 ? void 0 : _a.sessionDescriptionHandler; + if (!sdh) { + return undefined; + } + if (!(sdh instanceof _session_description_handler__WEBPACK_IMPORTED_MODULE_2__["SessionDescriptionHandler"])) { + throw new Error("Session description handler not instance of web SessionDescriptionHandler"); + } + return sdh.localMediaStream; + } + /** The remote media stream. Undefined if call not answered. */ + get remoteMediaStream() { + var _a; + const sdh = (_a = this.session) === null || _a === void 0 ? void 0 : _a.sessionDescriptionHandler; + if (!sdh) { + return undefined; + } + if (!(sdh instanceof _session_description_handler__WEBPACK_IMPORTED_MODULE_2__["SessionDescriptionHandler"])) { + throw new Error("Session description handler not instance of web SessionDescriptionHandler"); + } + return sdh.remoteMediaStream; + } + /** + * The local audio track, if available. + * @deprecated Use localMediaStream and get track from the stream. + */ + get localAudioTrack() { + var _a; + return (_a = this.localMediaStream) === null || _a === void 0 ? void 0 : _a.getTracks().find((track) => track.kind === "audio"); + } + /** + * The local video track, if available. + * @deprecated Use localMediaStream and get track from the stream. + */ + get localVideoTrack() { + var _a; + return (_a = this.localMediaStream) === null || _a === void 0 ? void 0 : _a.getTracks().find((track) => track.kind === "video"); + } + /** + * The remote audio track, if available. + * @deprecated Use remoteMediaStream and get track from the stream. + */ + get remoteAudioTrack() { + var _a; + return (_a = this.remoteMediaStream) === null || _a === void 0 ? void 0 : _a.getTracks().find((track) => track.kind === "audio"); + } + /** + * The remote video track, if available. + * @deprecated Use remoteMediaStream and get track from the stream. + */ + get remoteVideoTrack() { + var _a; + return (_a = this.remoteMediaStream) === null || _a === void 0 ? void 0 : _a.getTracks().find((track) => track.kind === "video"); + } + /** + * Connect. + * @remarks + * Start the UserAgent's WebSocket Transport. + */ + connect() { + this.logger.log(`[${this.id}] Connecting UserAgent...`); + this.connectRequested = true; + if (this.userAgent.state !== _api__WEBPACK_IMPORTED_MODULE_0__["UserAgentState"].Started) { + return this.userAgent.start(); + } + return this.userAgent.reconnect(); + } + /** + * Disconnect. + * @remarks + * Stop the UserAgent's WebSocket Transport. + */ + disconnect() { + this.logger.log(`[${this.id}] Disconnecting UserAgent...`); + this.connectRequested = false; + return this.userAgent.stop(); + } + /** + * Return true if connected. + */ + isConnected() { + return this.userAgent.isConnected(); + } + /** + * Start receiving incoming calls. + * @remarks + * Send a REGISTER request for the UserAgent's AOR. + * Resolves when the REGISTER request is sent, otherwise rejects. + */ + register(registererOptions, registererRegisterOptions) { + this.logger.log(`[${this.id}] Registering UserAgent...`); + this.registerRequested = true; + if (!this.registerer) { + this.registerer = new _api__WEBPACK_IMPORTED_MODULE_0__["Registerer"](this.userAgent, registererOptions); + this.registerer.stateChange.addListener((state) => { + switch (state) { + case _api__WEBPACK_IMPORTED_MODULE_0__["RegistererState"].Initial: + break; + case _api__WEBPACK_IMPORTED_MODULE_0__["RegistererState"].Registered: + if (this.delegate && this.delegate.onRegistered) { + this.delegate.onRegistered(); + } + break; + case _api__WEBPACK_IMPORTED_MODULE_0__["RegistererState"].Unregistered: + if (this.delegate && this.delegate.onUnregistered) { + this.delegate.onUnregistered(); + } + break; + case _api__WEBPACK_IMPORTED_MODULE_0__["RegistererState"].Terminated: + this.registerer = undefined; + break; + default: + throw new Error("Unknown registerer state."); + } + }); + } + return this.registerer.register(registererRegisterOptions).then(() => { + return; + }); + } + /** + * Stop receiving incoming calls. + * @remarks + * Send an un-REGISTER request for the UserAgent's AOR. + * Resolves when the un-REGISTER request is sent, otherwise rejects. + */ + unregister(registererUnregisterOptions) { + this.logger.log(`[${this.id}] Unregistering UserAgent...`); + this.registerRequested = false; + if (!this.registerer) { + return Promise.resolve(); + } + return this.registerer.unregister(registererUnregisterOptions).then(() => { + return; + }); + } + /** + * Make an outgoing call. + * @remarks + * Send an INVITE request to create a new Session. + * Resolves when the INVITE request is sent, otherwise rejects. + * Use `onCallAnswered` delegate method to determine if Session is established. + * @param destination - The target destination to call. A SIP address to send the INVITE to. + * @param inviterOptions - Optional options for Inviter constructor. + * @param inviterInviteOptions - Optional options for Inviter.invite(). + */ + call(destination, inviterOptions, inviterInviteOptions) { + this.logger.log(`[${this.id}] Beginning Session...`); + if (this.session) { + return Promise.reject(new Error("Session already exists.")); + } + const target = _api__WEBPACK_IMPORTED_MODULE_0__["UserAgent"].makeURI(destination); + if (!target) { + return Promise.reject(new Error(`Failed to create a valid URI from "${destination}"`)); + } + // Use our configured constraints as InviterOptions if none provided + if (!inviterOptions) { + inviterOptions = {}; + } + if (!inviterOptions.sessionDescriptionHandlerOptions) { + inviterOptions.sessionDescriptionHandlerOptions = {}; + } + if (!inviterOptions.sessionDescriptionHandlerOptions.constraints) { + inviterOptions.sessionDescriptionHandlerOptions.constraints = this.constraints; + } + // Create a new Inviter for the outgoing Session + const inviter = new _api__WEBPACK_IMPORTED_MODULE_0__["Inviter"](this.userAgent, target, inviterOptions); + // Send INVITE + return this.sendInvite(inviter, inviterOptions, inviterInviteOptions).then(() => { + return; + }); + } + /** + * Hangup a call. + * @remarks + * Send a BYE request, CANCEL request or reject response to end the current Session. + * Resolves when the request/response is sent, otherwise rejects. + * Use `onCallTerminated` delegate method to determine if and when call is ended. + */ + hangup() { + this.logger.log(`[${this.id}] Hangup...`); + return this.terminate(); + } + /** + * Answer an incoming call. + * @remarks + * Accept an incoming INVITE request creating a new Session. + * Resolves with the response is sent, otherwise rejects. + * Use `onCallAnswered` delegate method to determine if and when call is established. + * @param invitationAcceptOptions - Optional options for Inviter.accept(). + */ + answer(invitationAcceptOptions) { + this.logger.log(`[${this.id}] Accepting Invitation...`); + if (!this.session) { + return Promise.reject(new Error("Session does not exist.")); + } + if (!(this.session instanceof _api__WEBPACK_IMPORTED_MODULE_0__["Invitation"])) { + return Promise.reject(new Error("Session not instance of Invitation.")); + } + // Use our configured constraints as InvitationAcceptOptions if none provided + if (!invitationAcceptOptions) { + invitationAcceptOptions = {}; + } + if (!invitationAcceptOptions.sessionDescriptionHandlerOptions) { + invitationAcceptOptions.sessionDescriptionHandlerOptions = {}; + } + if (!invitationAcceptOptions.sessionDescriptionHandlerOptions.constraints) { + invitationAcceptOptions.sessionDescriptionHandlerOptions.constraints = this.constraints; + } + return this.session.accept(invitationAcceptOptions); + } + /** + * Decline an incoming call. + * @remarks + * Reject an incoming INVITE request. + * Resolves with the response is sent, otherwise rejects. + * Use `onCallTerminated` delegate method to determine if and when call is ended. + */ + decline() { + this.logger.log(`[${this.id}] rejecting Invitation...`); + if (!this.session) { + return Promise.reject(new Error("Session does not exist.")); + } + if (!(this.session instanceof _api__WEBPACK_IMPORTED_MODULE_0__["Invitation"])) { + return Promise.reject(new Error("Session not instance of Invitation.")); + } + return this.session.reject(); + } + /** + * Hold call + * @remarks + * Send a re-INVITE with new offer indicating "hold". + * Resolves when the re-INVITE request is sent, otherwise rejects. + * Use `onCallHold` delegate method to determine if request is accepted or rejected. + * See: https://tools.ietf.org/html/rfc6337 + */ + hold() { + this.logger.log(`[${this.id}] holding session...`); + return this.setHold(true); + } + /** + * Unhold call. + * @remarks + * Send a re-INVITE with new offer indicating "unhold". + * Resolves when the re-INVITE request is sent, otherwise rejects. + * Use `onCallHold` delegate method to determine if request is accepted or rejected. + * See: https://tools.ietf.org/html/rfc6337 + */ + unhold() { + this.logger.log(`[${this.id}] unholding session...`); + return this.setHold(false); + } + /** + * Hold state. + * @remarks + * True if session media is on hold. + */ + isHeld() { + return this.held; + } + /** + * Mute call. + * @remarks + * Disable sender's media tracks. + */ + mute() { + this.logger.log(`[${this.id}] disabling media tracks...`); + this.setMute(true); + } + /** + * Unmute call. + * @remarks + * Enable sender's media tracks. + */ + unmute() { + this.logger.log(`[${this.id}] enabling media tracks...`); + this.setMute(false); + } + /** + * Mute state. + * @remarks + * True if sender's media track is disabled. + */ + isMuted() { + const track = this.localAudioTrack || this.localVideoTrack; + return track ? !track.enabled : false; + } + /** + * Send DTMF. + * @remarks + * Send an INFO request with content type application/dtmf-relay. + * @param tone - Tone to send. + */ + sendDTMF(tone) { + this.logger.log(`[${this.id}] sending DTMF...`); + // As RFC 6086 states, sending DTMF via INFO is not standardized... + // + // Companies have been using INFO messages in order to transport + // Dual-Tone Multi-Frequency (DTMF) tones. All mechanisms are + // proprietary and have not been standardized. + // https://tools.ietf.org/html/rfc6086#section-2 + // + // It is however widely supported based on this draft: + // https://tools.ietf.org/html/draft-kaplan-dispatch-info-dtmf-package-00 + // Validate tone + if (!/^[0-9A-D#*,]$/.exec(tone)) { + return Promise.reject(new Error("Invalid DTMF tone.")); + } + if (!this.session) { + return Promise.reject(new Error("Session does not exist.")); + } + // The UA MUST populate the "application/dtmf-relay" body, as defined + // earlier, with the button pressed and the duration it was pressed + // for. Technically, this actually requires the INFO to be generated + // when the user *releases* the button, however if the user has still + // not released a button after 5 seconds, which is the maximum duration + // supported by this mechanism, the UA should generate the INFO at that + // time. + // https://tools.ietf.org/html/draft-kaplan-dispatch-info-dtmf-package-00#section-5.3 + this.logger.log(`[${this.id}] Sending DTMF tone: ${tone}`); + const dtmf = tone; + const duration = 2000; + const body = { + contentDisposition: "render", + contentType: "application/dtmf-relay", + content: "Signal=" + dtmf + "\r\nDuration=" + duration + }; + const requestOptions = { body }; + return this.session.info({ requestOptions }).then(() => { + return; + }); + } + /** + * Send a message. + * @remarks + * Send a MESSAGE request. + * @param destination - The target destination for the message. A SIP address to send the MESSAGE to. + */ + message(destination, message) { + this.logger.log(`[${this.id}] sending message...`); + const target = _api__WEBPACK_IMPORTED_MODULE_0__["UserAgent"].makeURI(destination); + if (!target) { + return Promise.reject(new Error(`Failed to create a valid URI from "${destination}"`)); + } + return new _api__WEBPACK_IMPORTED_MODULE_0__["Messager"](this.userAgent, target, message).message(); + } + /** Media constraints. */ + get constraints() { + var _a; + let constraints = { audio: true, video: false }; // default to audio only calls + if ((_a = this.options.media) === null || _a === void 0 ? void 0 : _a.constraints) { + constraints = Object.assign({}, this.options.media.constraints); + } + return constraints; + } + /** + * Attempt reconnection up to `maxReconnectionAttempts` times. + * @param reconnectionAttempt - Current attempt number. + */ + attemptReconnection(reconnectionAttempt = 1) { + const reconnectionAttempts = this.options.reconnectionAttempts || 3; + const reconnectionDelay = this.options.reconnectionDelay || 4; + if (!this.connectRequested) { + this.logger.log(`[${this.id}] Reconnection not currently desired`); + return; // If intentionally disconnected, don't reconnect. + } + if (this.attemptingReconnection) { + this.logger.log(`[${this.id}] Reconnection attempt already in progress`); + } + if (reconnectionAttempt > reconnectionAttempts) { + this.logger.log(`[${this.id}] Reconnection maximum attempts reached`); + return; + } + if (reconnectionAttempt === 1) { + this.logger.log(`[${this.id}] Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - trying`); + } + else { + this.logger.log(`[${this.id}] Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - trying in ${reconnectionDelay} seconds`); + } + this.attemptingReconnection = true; + setTimeout(() => { + if (!this.connectRequested) { + this.logger.log(`[${this.id}] Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - aborted`); + this.attemptingReconnection = false; + return; // If intentionally disconnected, don't reconnect. + } + this.userAgent + .reconnect() + .then(() => { + this.logger.log(`[${this.id}] Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - succeeded`); + this.attemptingReconnection = false; + }) + .catch((error) => { + this.logger.log(`[${this.id}] Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - failed`); + this.logger.error(error.message); + this.attemptingReconnection = false; + this.attemptReconnection(++reconnectionAttempt); + }); + }, reconnectionAttempt === 1 ? 0 : reconnectionDelay * 1000); + } + /** Helper function to remove media from html elements. */ + cleanupMedia() { + if (this.options.media) { + if (this.options.media.local) { + if (this.options.media.local.video) { + this.options.media.local.video.srcObject = null; + this.options.media.local.video.pause(); + } + } + if (this.options.media.remote) { + if (this.options.media.remote.audio) { + this.options.media.remote.audio.srcObject = null; + this.options.media.remote.audio.pause(); + } + if (this.options.media.remote.video) { + this.options.media.remote.video.srcObject = null; + this.options.media.remote.video.pause(); + } + } + } + } + /** Helper function to enable/disable media tracks. */ + enableSenderTracks(enable) { + if (!this.session) { + throw new Error("Session does not exist."); + } + const sessionDescriptionHandler = this.session.sessionDescriptionHandler; + if (!(sessionDescriptionHandler instanceof _session_description_handler__WEBPACK_IMPORTED_MODULE_2__["SessionDescriptionHandler"])) { + throw new Error("Session's session description handler not instance of SessionDescriptionHandler."); + } + const peerConnection = sessionDescriptionHandler.peerConnection; + if (!peerConnection) { + throw new Error("Peer connection closed."); + } + peerConnection.getSenders().forEach((sender) => { + if (sender.track) { + sender.track.enabled = enable; + } + }); + } + /** + * Setup session delegate and state change handler. + * @param session - Session to setup + * @param referralInviterOptions - Options for any Inviter created as result of a REFER. + */ + initSession(session, referralInviterOptions) { + // Set session + this.session = session; + // Call session created callback + if (this.delegate && this.delegate.onCallCreated) { + this.delegate.onCallCreated(); + } + // Setup session state change handler + this.session.stateChange.addListener((state) => { + if (this.session !== session) { + return; // if our session has changed, just return + } + this.logger.log(`[${this.id}] session state changed to ${state}`); + switch (state) { + case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Initial: + break; + case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Establishing: + break; + case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Established: + this.setupLocalMedia(); + this.setupRemoteMedia(); + if (this.delegate && this.delegate.onCallAnswered) { + this.delegate.onCallAnswered(); + } + break; + case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Terminating: + // fall through + case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Terminated: + this.session = undefined; + this.cleanupMedia(); + if (this.delegate && this.delegate.onCallHangup) { + this.delegate.onCallHangup(); + } + break; + default: + throw new Error("Unknown session state."); + } + }); + // Setup delegate + this.session.delegate = { + onInfo: (info) => { + // As RFC 6086 states, sending DTMF via INFO is not standardized... + // + // Companies have been using INFO messages in order to transport + // Dual-Tone Multi-Frequency (DTMF) tones. All mechanisms are + // proprietary and have not been standardized. + // https://tools.ietf.org/html/rfc6086#section-2 + // + // It is however widely supported based on this draft: + // https://tools.ietf.org/html/draft-kaplan-dispatch-info-dtmf-package-00 + var _a; + // FIXME: TODO: We should reject correctly... + // + // 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. + // https://tools.ietf.org/html/rfc6086#section-4.2.2 + // No delegate + if (((_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onCallDTMFReceived) === undefined) { + info.reject(); + return; + } + // Invalid content type + const contentType = info.request.getHeader("content-type"); + if (!contentType || !/^application\/dtmf-relay/i.exec(contentType)) { + info.reject(); + return; + } + // Invalid body + const body = info.request.body.split("\r\n", 2); + if (body.length !== 2) { + info.reject(); + return; + } + // Invalid tone + let tone; + const toneRegExp = /^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/; + if (toneRegExp.test(body[0])) { + tone = body[0].replace(toneRegExp, "$2"); + } + if (!tone) { + info.reject(); + return; + } + // Invalid duration + let duration; + const durationRegExp = /^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/; + if (durationRegExp.test(body[1])) { + duration = parseInt(body[1].replace(durationRegExp, "$2"), 10); + } + if (!duration) { + info.reject(); + return; + } + info + .accept() + .then(() => { + if (this.delegate && this.delegate.onCallDTMFReceived) { + if (!tone || !duration) { + throw new Error("Tone or duration undefined."); + } + this.delegate.onCallDTMFReceived(tone, duration); + } + }) + .catch((error) => { + this.logger.error(error.message); + }); + }, + onRefer: (referral) => { + referral + .accept() + .then(() => this.sendInvite(referral.makeInviter(referralInviterOptions), referralInviterOptions)) + .catch((error) => { + this.logger.error(error.message); + }); + } + }; + } + /** Helper function to init send then send invite. */ + sendInvite(inviter, inviterOptions, inviterInviteOptions) { + // Initialize our session + this.initSession(inviter, inviterOptions); + // Send the INVITE + return inviter.invite(inviterInviteOptions).then(() => { + this.logger.log(`[${this.id}] sent INVITE`); + }); + } + /** + * Puts Session on hold. + * @param hold - Hold on if true, off if false. + */ + setHold(hold) { + if (!this.session) { + return Promise.reject(new Error("Session does not exist.")); + } + const session = this.session; + // Just resolve if we are already in correct state + if (this.held === hold) { + return Promise.resolve(); + } + const sessionDescriptionHandler = this.session.sessionDescriptionHandler; + if (!(sessionDescriptionHandler instanceof _session_description_handler__WEBPACK_IMPORTED_MODULE_2__["SessionDescriptionHandler"])) { + throw new Error("Session's session description handler not instance of SessionDescriptionHandler."); + } + const options = { + requestDelegate: { + onAccept: () => { + this.held = hold; + if (this.delegate && this.delegate.onCallHold) { + this.delegate.onCallHold(this.held); + } + }, + onReject: () => { + this.logger.warn(`[${this.id}] re-invite request was rejected`); + if (this.delegate && this.delegate.onCallHold) { + this.delegate.onCallHold(this.held); + } + } + } + }; + // Session properties used to pass modifiers to the SessionDescriptionHandler: + // + // 1) Session.sessionDescriptionHandlerModifiers + // - used in all cases when handling the initial INVITE transaction as either UAC or UAS + // - may be set directly at anytime + // - may optionally be set via constructor option + // - may optionally be set via options passed to Inviter.invite() or Invitation.accept() + // + // 2) Session.sessionDescriptionHandlerModifiersReInvite + // - used in all cases when handling a re-INVITE transaction as either UAC or UAS + // - may be set directly at anytime + // - may optionally be set via constructor option + // - may optionally be set via options passed to Session.invite() + // Set the session's SDH re-INVITE modifiers to produce the appropriate SDP offer to place call on hold + session.sessionDescriptionHandlerModifiersReInvite = hold ? [_modifiers__WEBPACK_IMPORTED_MODULE_1__["holdModifier"]] : []; + // Send re-INVITE + return this.session + .invite(options) + .then(() => { + // Reset the session's SDH re-INVITE modifiers. + // Note that if the modifiers are not reset, they will be applied + // to the SDP answer as well (which we do not want in this case). + session.sessionDescriptionHandlerModifiersReInvite = []; + this.enableSenderTracks(!hold); // mute/unmute + }) + .catch((error) => { + if (error instanceof _api__WEBPACK_IMPORTED_MODULE_0__["RequestPendingError"]) { + this.logger.error(`[${this.id}] A hold request is already in progress.`); + } + throw error; + }); + } + /** + * Puts Session on mute. + * @param mute - Mute on if true, off if false. + */ + setMute(mute) { + if (!this.session) { + this.logger.warn(`[${this.id}] A session is required to enabled/disable media tracks`); + return; + } + if (this.session.state !== _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Established) { + this.logger.warn(`[${this.id}] An established session is required to enable/disable media tracks`); + return; + } + this.enableSenderTracks(!mute); + } + /** Helper function to attach local media to html elements. */ + setupLocalMedia() { + var _a, _b; + if (!this.session) { + throw new Error("Session does not exist."); + } + const mediaElement = (_b = (_a = this.options.media) === null || _a === void 0 ? void 0 : _a.local) === null || _b === void 0 ? void 0 : _b.video; + if (mediaElement) { + const localStream = this.localMediaStream; + if (!localStream) { + throw new Error("Local media stream undefiend."); + } + mediaElement.srcObject = localStream; + mediaElement.volume = 0; + mediaElement.play().catch((error) => { + this.logger.error(`[${this.id}] Failed to play local media`); + this.logger.error(error.message); + }); + } + } + /** Helper function to attach remote media to html elements. */ + setupRemoteMedia() { + var _a, _b, _c, _d; + if (!this.session) { + throw new Error("Session does not exist."); + } + const mediaElement = ((_b = (_a = this.options.media) === null || _a === void 0 ? void 0 : _a.remote) === null || _b === void 0 ? void 0 : _b.video) || ((_d = (_c = this.options.media) === null || _c === void 0 ? void 0 : _c.remote) === null || _d === void 0 ? void 0 : _d.audio); + if (mediaElement) { + const remoteStream = this.remoteMediaStream; + if (!remoteStream) { + throw new Error("Remote media stream undefiend."); + } + mediaElement.autoplay = true; // Safari hack, because you cannot call .play() from a non user action + mediaElement.srcObject = remoteStream; + mediaElement.play().catch((error) => { + this.logger.error(`[${this.id}] Failed to play remote media`); + this.logger.error(error.message); + }); + remoteStream.onaddtrack = () => { + this.logger.log(`[${this.id}] Remote media onaddtrack`); + mediaElement.load(); // Safari hack, as it doesn't work otheriwse + mediaElement.play().catch((error) => { + this.logger.error(`[${this.id}] Failed to play remote media`); + this.logger.error(error.message); + }); + }; + } + } + /** + * End a session. + * @remarks + * Send a BYE request, CANCEL request or reject response to end the current Session. + * Resolves when the request/response is sent, otherwise rejects. + * Use `onCallTerminated` delegate method to determine if and when Session is terminated. + */ + terminate() { + this.logger.log(`[${this.id}] Terminating...`); + if (!this.session) { + return Promise.reject(new Error("Session does not exist.")); + } + switch (this.session.state) { + case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Initial: + if (this.session instanceof _api__WEBPACK_IMPORTED_MODULE_0__["Inviter"]) { + return this.session.cancel().then(() => { + this.logger.log(`[${this.id}] Inviter never sent INVITE (canceled)`); + }); + } + else if (this.session instanceof _api__WEBPACK_IMPORTED_MODULE_0__["Invitation"]) { + return this.session.reject().then(() => { + this.logger.log(`[${this.id}] Invitation rejected (sent 480)`); + }); + } + else { + throw new Error("Unknown session type."); + } + case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Establishing: + if (this.session instanceof _api__WEBPACK_IMPORTED_MODULE_0__["Inviter"]) { + return this.session.cancel().then(() => { + this.logger.log(`[${this.id}] Inviter canceled (sent CANCEL)`); + }); + } + else if (this.session instanceof _api__WEBPACK_IMPORTED_MODULE_0__["Invitation"]) { + return this.session.reject().then(() => { + this.logger.log(`[${this.id}] Invitation rejected (sent 480)`); + }); + } + else { + throw new Error("Unknown session type."); + } + case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Established: + return this.session.bye().then(() => { + this.logger.log(`[${this.id}] Session ended (sent BYE)`); + }); + case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Terminating: + break; + case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Terminated: + break; + default: + throw new Error("Unknown state"); + } + this.logger.log(`[${this.id}] Terminating in state ${this.session.state}, no action taken`); + return Promise.resolve(); + } +} + + +/***/ }), +/* 179 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }), +/* 180 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + + + +/***/ }) +/******/ ]); +}); \ No newline at end of file diff --git a/dist/sip.min.js b/dist/sip.min.js new file mode 100644 index 000000000..1c78309aa --- /dev/null +++ b/dist/sip.min.js @@ -0,0 +1 @@ +!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 s(i){if(t[i])return t[i].exports;var r=t[i]={i:i,l:!1,exports:{}};return e[i].call(r.exports,r,r.exports,s),r.l=!0,r.exports}return s.m=e,s.c=t,s.d=function(e,t,i){s.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:i})},s.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},s.t=function(e,t){if(1&t&&(e=s(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var i=Object.create(null);if(s.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)s.d(i,r,function(t){return e[t]}.bind(null,r));return i},s.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return s.d(t,"a",t),t},s.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},s.p="",s(s.s=62)}({62:function(e,t,s){"use strict";s.r(t),s.d(t,"name",(function(){return Tt})),s.d(t,"version",(function(){return bt})),s.d(t,"ContentTypeUnsupportedError",(function(){return o})),s.d(t,"RequestPendingError",(function(){return a})),s.d(t,"SessionDescriptionHandlerError",(function(){return c})),s.d(t,"SessionTerminatedError",(function(){return h})),s.d(t,"StateTransitionError",(function(){return d})),s.d(t,"Bye",(function(){return l})),s.d(t,"EmitterImpl",(function(){return g})),s.d(t,"Info",(function(){return u})),s.d(t,"Invitation",(function(){return Z})),s.d(t,"Inviter",(function(){return J})),s.d(t,"Message",(function(){return L})),s.d(t,"Messager",(function(){return z})),s.d(t,"Notification",(function(){return B})),s.d(t,"PublisherState",(function(){return X})),s.d(t,"Publisher",(function(){return oe})),s.d(t,"Referral",(function(){return V})),s.d(t,"RegistererState",(function(){return Q})),s.d(t,"Registerer",(function(){return ae})),s.d(t,"SessionState",(function(){return G})),s.d(t,"Session",(function(){return W})),s.d(t,"Subscriber",(function(){return he})),s.d(t,"SubscriptionState",(function(){return te})),s.d(t,"Subscription",(function(){return ce})),s.d(t,"TransportState",(function(){return se})),s.d(t,"SIPExtension",(function(){return K})),s.d(t,"UserAgentRegisteredOptionTags",(function(){return Y})),s.d(t,"UserAgentState",(function(){return ie})),s.d(t,"UserAgent",(function(){return ot})),s.d(t,"Grammar",(function(){return b})),s.d(t,"NameAddrHeader",(function(){return f})),s.d(t,"Parameters",(function(){return p})),s.d(t,"URI",(function(){return m})),s.d(t,"Core",(function(){return i})),s.d(t,"Web",(function(){return r}));var i={};s.r(i),s.d(i,"Dialog",(function(){return ye})),s.d(i,"SessionDialog",(function(){return Le})),s.d(i,"SubscriptionDialog",(function(){return We})),s.d(i,"Exception",(function(){return n})),s.d(i,"TransactionStateError",(function(){return M})),s.d(i,"TransportError",(function(){return ve})),s.d(i,"Levels",(function(){return re})),s.d(i,"LoggerFactory",(function(){return ge})),s.d(i,"Logger",(function(){return le})),s.d(i,"Grammar",(function(){return b})),s.d(i,"NameAddrHeader",(function(){return f})),s.d(i,"Parameters",(function(){return p})),s.d(i,"URI",(function(){return m})),s.d(i,"C",(function(){return j})),s.d(i,"fromBodyLegacy",(function(){return k})),s.d(i,"isBody",(function(){return x})),s.d(i,"getBody",(function(){return q})),s.d(i,"DigestAuthentication",(function(){return fe})),s.d(i,"IncomingMessage",(function(){return C})),s.d(i,"IncomingRequestMessage",(function(){return A})),s.d(i,"IncomingResponseMessage",(function(){return D})),s.d(i,"OutgoingRequestMessage",(function(){return H})),s.d(i,"constructOutgoingResponse",(function(){return me})),s.d(i,"Parser",(function(){return et})),s.d(i,"SessionState",(function(){return P})),s.d(i,"SignalingState",(function(){return N})),s.d(i,"SubscriptionState",(function(){return ee})),s.d(i,"ClientTransaction",(function(){return be})),s.d(i,"InviteClientTransaction",(function(){return Ee})),s.d(i,"InviteServerTransaction",(function(){return Re})),s.d(i,"NonInviteClientTransaction",(function(){return Te})),s.d(i,"NonInviteServerTransaction",(function(){return Ce})),s.d(i,"ServerTransaction",(function(){return Se})),s.d(i,"TransactionState",(function(){return ne})),s.d(i,"Transaction",(function(){return we})),s.d(i,"UserAgentCore",(function(){return Qe})),s.d(i,"ByeUserAgentClient",(function(){return Ie})),s.d(i,"ByeUserAgentServer",(function(){return De})),s.d(i,"CancelUserAgentClient",(function(){return at})),s.d(i,"InfoUserAgentClient",(function(){return He})),s.d(i,"InfoUserAgentServer",(function(){return _e})),s.d(i,"InviteUserAgentClient",(function(){return Be})),s.d(i,"InviteUserAgentServer",(function(){return Ze})),s.d(i,"MessageUserAgentClient",(function(){return ke})),s.d(i,"MessageUserAgentServer",(function(){return xe})),s.d(i,"NotifyUserAgentClient",(function(){return qe})),s.d(i,"NotifyUserAgentServer",(function(){return Pe})),s.d(i,"PublishUserAgentClient",(function(){return Ve})),s.d(i,"PrackUserAgentClient",(function(){return Ne})),s.d(i,"PrackUserAgentServer",(function(){return Me})),s.d(i,"ReInviteUserAgentClient",(function(){return Oe})),s.d(i,"ReInviteUserAgentServer",(function(){return Ue})),s.d(i,"ReSubscribeUserAgentClient",(function(){return Ke})),s.d(i,"ReSubscribeUserAgentServer",(function(){return ct})),s.d(i,"ReferUserAgentClient",(function(){return je})),s.d(i,"ReferUserAgentServer",(function(){return Fe})),s.d(i,"RegisterUserAgentClient",(function(){return Ge})),s.d(i,"RegisterUserAgentServer",(function(){return Je})),s.d(i,"SubscribeUserAgentClient",(function(){return Ye})),s.d(i,"SubscribeUserAgentServer",(function(){return ze})),s.d(i,"UserAgentClient",(function(){return $e})),s.d(i,"UserAgentServer",(function(){return Ae})),s.d(i,"Timers",(function(){return U}));var r={};s.r(r),s.d(r,"stripTcpCandidates",(function(){return dt})),s.d(r,"stripTelephoneEvent",(function(){return lt})),s.d(r,"cleanJitsiSdpImageattr",(function(){return gt})),s.d(r,"stripG722",(function(){return ut})),s.d(r,"stripRtpPayload",(function(){return pt})),s.d(r,"stripVideo",(function(){return ft})),s.d(r,"addMidLines",(function(){return mt})),s.d(r,"holdModifier",(function(){return vt})),s.d(r,"defaultMediaStreamFactory",(function(){return tt})),s.d(r,"defaultPeerConnectionConfiguration",(function(){return st})),s.d(r,"defaultSessionDescriptionHandlerFactory",(function(){return rt})),s.d(r,"SessionDescriptionHandler",(function(){return it})),s.d(r,"SimpleUser",(function(){return wt})),s.d(r,"Transport",(function(){return nt}));class n extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}class o extends n{constructor(e){super(e||"Unsupported content type.")}}class a extends n{constructor(e){super(e||"Request pending.")}}class c extends n{constructor(e){super(e||"Unspecified session description handler error.")}}class h extends n{constructor(){super("The session has terminated.")}}class d extends n{constructor(e){super(e||"An error occurred during state transition.")}}class l{constructor(e){this.incomingByeRequest=e}get request(){return this.incomingByeRequest.message}accept(e){return this.incomingByeRequest.accept(e),Promise.resolve()}reject(e){return this.incomingByeRequest.reject(e),Promise.resolve()}}class g{constructor(){this.listeners=new Array}addListener(e,t){const s=t=>{this.removeListener(s),e(t)};!0===(null==t?void 0:t.once)?this.listeners.push(s):this.listeners.push(e)}emit(e){this.listeners.slice().forEach(t=>t(e))}removeAllListeners(){this.listeners=[]}removeListener(e){this.listeners=this.listeners.filter(t=>t!==e)}on(e){return this.addListener(e)}off(e){return this.removeListener(e)}once(e){return this.addListener(e,{once:!0})}}class u{constructor(e){this.incomingInfoRequest=e}get request(){return this.incomingInfoRequest.message}accept(e){return this.incomingInfoRequest.accept(e),Promise.resolve()}reject(e){return this.incomingInfoRequest.reject(e),Promise.resolve()}}class p{constructor(e){this.parameters={};for(const t in e)e.hasOwnProperty(t)&&this.setParam(t,e[t])}setParam(e,t){e&&(this.parameters[e.toLowerCase()]=null==t?null:t.toString())}getParam(e){if(e)return this.parameters[e.toLowerCase()]}hasParam(e){return!(!e||void 0===this.parameters[e.toLowerCase()])}deleteParam(e){if(e=e.toLowerCase(),this.hasParam(e)){const t=this.parameters[e];return delete this.parameters[e],t}}clearParams(){this.parameters={}}}class f extends p{constructor(e,t,s){super(s),this.uri=e,this._displayName=t}get friendlyName(){return this.displayName||this.uri.aor}get displayName(){return this._displayName}set displayName(e){this._displayName=e}clone(){return new f(this.uri.clone(),this._displayName,JSON.parse(JSON.stringify(this.parameters)))}toString(){let e=this.displayName||"0"===this.displayName?'"'+this.displayName+'" ':"";e+="<"+this.uri.toString()+">";for(const t in this.parameters)this.parameters.hasOwnProperty(t)&&(e+=";"+t,null!==this.parameters[t]&&(e+="="+this.parameters[t]));return e}}class m extends p{constructor(e="sip",t,s,i,r,n){if(super(r||{}),this.headers={},!s)throw new TypeError('missing or invalid "host" parameter');for(const e in n)n.hasOwnProperty(e)&&this.setHeader(e,n[e]);this.raw={scheme:e,user:t,host:s,port:i},this.normal={scheme:e.toLowerCase(),user:t,host:s.toLowerCase(),port:i}}get scheme(){return this.normal.scheme}set scheme(e){this.raw.scheme=e,this.normal.scheme=e.toLowerCase()}get user(){return this.normal.user}set user(e){this.normal.user=this.raw.user=e}get host(){return this.normal.host}set host(e){this.raw.host=e,this.normal.host=e.toLowerCase()}get aor(){return this.normal.user+"@"+this.normal.host}get port(){return this.normal.port}set port(e){this.normal.port=this.raw.port=e}setHeader(e,t){this.headers[this.headerize(e)]=t instanceof Array?t:[t]}getHeader(e){if(e)return this.headers[this.headerize(e)]}hasHeader(e){return!!e&&!!this.headers.hasOwnProperty(this.headerize(e))}deleteHeader(e){if(e=this.headerize(e),this.headers.hasOwnProperty(e)){const t=this.headers[e];return delete this.headers[e],t}}clearHeaders(){this.headers={}}clone(){return new m(this._raw.scheme,this._raw.user||"",this._raw.host,this._raw.port,JSON.parse(JSON.stringify(this.parameters)),JSON.parse(JSON.stringify(this.headers)))}toRaw(){return this._toString(this._raw)}toString(){return this._toString(this._normal)}get _normal(){return this.normal}get _raw(){return this.raw}_toString(e){let t=e.scheme+":";e.scheme.toLowerCase().match("^sips?$")||(t+="//"),e.user&&(t+=this.escapeUser(e.user)+"@"),t+=e.host,(e.port||0===e.port)&&(t+=":"+e.port);for(const e in this.parameters)this.parameters.hasOwnProperty(e)&&(t+=";"+e,null!==this.parameters[e]&&(t+="="+this.parameters[e]));const s=[];for(const e in this.headers)if(this.headers.hasOwnProperty(e))for(const t in this.headers[e])this.headers[e].hasOwnProperty(t)&&s.push(e+"="+this.headers[e][t]);return s.length>0&&(t+="?"+s.join("&")),t}escapeUser(e){let t;try{t=decodeURIComponent(e)}catch(e){throw e}return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%2B/gi,"+").replace(/%3F/gi,"?").replace(/%2F/gi,"/")}headerize(e){const t={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},s=e.toLowerCase().replace(/_/g,"-").split("-"),i=s.length;let r="";for(let e=0;e"\\x0"+s(e)).replace(/[\x10-\x1F\x7F-\x9F]/g,e=>"\\x"+s(e))}function r(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,e=>"\\x0"+s(e)).replace(/[\x10-\x1F\x7F-\x9F]/g,e=>"\\x"+s(e))}function n(e){switch(e.type){case"literal":return'"'+i(e.text)+'"';case"class":const t=e.parts.map(e=>Array.isArray(e)?r(e[0])+"-"+r(e[1]):r(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){const t=e.map(n);let s,i;if(t.sort(),t.length>0){for(s=1,i=1;s",b(">",!1),"\\",b("\\",!1),"[",b("[",!1),"]",b("]",!1),"{",b("{",!1),"}",b("}",!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 m(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 m(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",b("sips",!0),"sip",b("sip",!0),function(e){(t=t||{data:{}}).data.scheme=e},function(){(t=t||{data:{}}).data.user=decodeURIComponent(p().slice(0,-1))},function(){(t=t||{data:{}}).data.password=p()},function(){return(t=t||{data:{}}).data.host=p(),t.data.host},function(){return(t=t||{data:{}}).data.host_type="domain",p()},/^[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",p()},"::",b("::",!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",p()},function(){return(t=t||{data:{}}).data.host_type="IPv4",p()},"25",b("25",!1),/^[0-5]/,T([["0","5"]],!1,!1),"2",b("2",!1),/^[0-4]/,T([["0","4"]],!1,!1),"1",b("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=",b("transport=",!0),"udp",b("udp",!0),"tcp",b("tcp",!0),"sctp",b("sctp",!0),"tls",b("tls",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.transport=e.toLowerCase()},"user=",b("user=",!0),"phone",b("phone",!0),"ip",b("ip",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.user=e.toLowerCase()},"method=",b("method=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.method=e},"ttl=",b("ttl=",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.ttl=e},"maddr=",b("maddr=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.maddr=e},"lr",b("lr",!0),function(){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.lr=void 0},function(e,s){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),s=null===s?void 0:s[1],t.data.uri_params[e.toLowerCase()]=s},function(e,s){e=e.join("").toLowerCase(),s=s.join(""),(t=t||{data:{}}).data.uri_headers||(t.data.uri_headers={}),t.data.uri_headers[e]?t.data.uri_headers[e].push(s):t.data.uri_headers[e]=[s]},function(){"Refer_To"===(t=t||{data:{}}).startRule&&(t.data.uri=new m(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)},"//",b("//",!1),function(){(t=t||{data:{}}).data.scheme=p()},b("SIP",!0),function(){(t=t||{data:{}}).data.sip_version=p()},"INVITE",b("INVITE",!1),"ACK",b("ACK",!1),"VXACH",b("VXACH",!1),"OPTIONS",b("OPTIONS",!1),"BYE",b("BYE",!1),"CANCEL",b("CANCEL",!1),"REGISTER",b("REGISTER",!1),"SUBSCRIBE",b("SUBSCRIBE",!1),"NOTIFY",b("NOTIFY",!1),"REFER",b("REFER",!1),"PUBLISH",b("PUBLISH",!1),function(){return(t=t||{data:{}}).data.method=p(),t.data.method},function(e){(t=t||{data:{}}).data.status_code=parseInt(e.join(""))},function(){(t=t||{data:{}}).data.reason_phrase=p()},function(){(t=t||{data:{}}).data=p()},function(){var e,s;for(s=(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#;l&&(l=a,g=[]),g.push(e))}function E(e,t,s){return new v(v.buildMessage(e,t),e,t,s)}function $(e){return e.split("").map(e=>e.charCodeAt(0)-32)}if(t.data={},d=function t(i){const r=o[i];let h=0;const d=[];let l=r.length;const g=[],p=[];let f;for(;;){for(;ha?(l=h+3+r[h+1],h+=3):(l=h+3+r[h+1]+r[h+2],h+=3+r[h+1]);break;case 18:g.push(l),d.push(h+4+r[h+2]+r[h+3]),e.substr(a,n[r[h+1]].length)===n[r[h+1]]?(l=h+4+r[h+2],h+=4):(l=h+4+r[h+2]+r[h+3],h+=4+r[h+2]);break;case 19:g.push(l),d.push(h+4+r[h+2]+r[h+3]),e.substr(a,n[r[h+1]].length).toLowerCase()===n[r[h+1]]?(l=h+4+r[h+2],h+=4):(l=h+4+r[h+2]+r[h+3],h+=4+r[h+2]);break;case 20:g.push(l),d.push(h+4+r[h+2]+r[h+3]),n[r[h+1]].test(e.charAt(a))?(l=h+4+r[h+2],h+=4):(l=h+4+r[h+2]+r[h+3],h+=4+r[h+2]);break;case 21:p.push(e.substr(a,r[h+1])),a+=r[h+1],h+=2;break;case 22:p.push(n[r[h+1]]),a+=n[r[h+1]].length,h+=2;break;case 23:p.push(s),0===u&&y(n[r[h+1]]),h+=2;break;case 24:c=p[p.length-1-r[h+1]],h+=2;break;case 25:c=a,h++;break;case 26:f=r.slice(h+4,h+4+r[h+3]).map((function(e){return p[p.length-1-e]})),p.splice(p.length-r[h+2],r[h+2],n[r[h+1]].apply(null,f)),h+=4+r[h+3];break;case 27:p.push(t(r[h+1])),h+=2;break;case 28:u++,h++;break;case 29:u--,h++;break;default:throw new Error("Invalid opcode: "+r[h]+".")}if(!(g.length>0))break;l=g.pop(),h=d.pop()}return p[0]}(r),d!==s&&a===e.length)return d;throw d!==s&&a=this.headers[e].length)return;const s=this.headers[e][t],i=s.raw;if(s.parsed)return s.parsed;const r=b.parse(i,e.replace(/-/g,"_"));return-1===r?void this.headers[e].splice(t,1):(s.parsed=r,r)}s(e,t=0){return this.parseHeader(e,t)}setHeader(e,t){this.headers[$(e)]=[{raw:t}]}toString(){return this.data}}class A extends C{constructor(){super()}}class D extends C{constructor(){super()}}class H{constructor(e,t,s,i,r,n,o){this.headers={},this.extraHeaders=[],this.options=H.getDefaultOptions(),r&&(this.options=Object.assign(Object.assign({},this.options),r),this.options.optionTags&&this.options.optionTags.length&&(this.options.optionTags=this.options.optionTags.slice()),this.options.routeSet&&this.options.routeSet.length&&(this.options.routeSet=this.options.routeSet.slice())),n&&n.length&&(this.extraHeaders=n.slice()),o&&(this.body={body:o.content,contentType:o.contentType}),this.method=e,this.ruri=t.clone(),this.fromURI=s.clone(),this.fromTag=this.options.fromTag?this.options.fromTag:E(),this.from=H.makeNameAddrHeader(this.fromURI,this.options.fromDisplayName,this.fromTag),this.toURI=i.clone(),this.toTag=this.options.toTag,this.to=H.makeNameAddrHeader(this.toURI,this.options.toDisplayName,this.toTag),this.callId=this.options.callId?this.options.callId:this.options.callIdPrefix+R(15),this.cseq=this.options.cseq,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")}static getDefaultOptions(){return{callId:"",callIdPrefix:"",cseq:1,toDisplayName:"",toTag:"",fromDisplayName:"",fromTag:"",forceRport:!1,hackViaTcp:!1,optionTags:["outbound"],routeSet:[],userAgentString:"sip.js",viaHost:""}}static makeNameAddrHeader(e,t,s){const i={};return s&&(i.tag=s),new f(e,t,i)}getHeader(e){const t=this.headers[$(e)];if(t){if(t[0])return t[0]}else{const t=new RegExp("^\\s*"+e+"\\s*:","i");for(const e of this.extraHeaders)if(t.test(e))return e.substring(e.indexOf(":")+1).trim()}}getHeaders(e){const t=[],s=this.headers[$(e)];if(s)for(const e of s)t.push(e);else{const s=new RegExp("^\\s*"+e+"\\s*:","i");for(const e of this.extraHeaders)s.test(e)&&t.push(e.substring(e.indexOf(":")+1).trim())}return t}hasHeader(e){if(this.headers[$(e)])return!0;{const t=new RegExp("^\\s*"+e+"\\s*:","i");for(const e of this.extraHeaders)if(t.test(e))return!0}return!1}setHeader(e,t){this.headers[$(e)]=t instanceof Array?t:[t]}setViaHeader(e,t){this.options.hackViaTcp&&(t="TCP");let s="SIP/2.0/"+t;s+=" "+this.options.viaHost+";branch="+e,this.options.forceRport&&(s+=";rport"),this.setHeader("via",s),this.branch=e}toString(){let e="";e+=this.method+" "+this.ruri.toRaw()+" SIP/2.0\r\n";for(const t in this.headers)if(this.headers[t])for(const s of this.headers[t])e+=t+": "+s+"\r\n";for(const t of this.extraHeaders)e+=t.trim()+"\r\n";return e+="Supported: "+this.options.optionTags.join(", ")+"\r\n",e+="User-Agent: "+this.options.userAgentString+"\r\n",this.body?"string"==typeof this.body?(e+="Content-Length: "+I(this.body)+"\r\n\r\n",e+=this.body):this.body.body&&this.body.contentType?(e+="Content-Type: "+this.body.contentType+"\r\n",e+="Content-Length: "+I(this.body.body)+"\r\n\r\n",e+=this.body.body):e+="Content-Length: 0\r\n\r\n":e+="Content-Length: 0\r\n\r\n",e}}function _(e){return"application/sdp"===e?"session":"render"}function k(e){const t="string"==typeof e?e:e.body,s="string"==typeof e?"application/sdp":e.contentType;return{contentDisposition:_(s),contentType:s,content:t}}function x(e){return!(!e||"string"!=typeof e.content||"string"!=typeof e.contentType||void 0!==e.contentDisposition)||"string"==typeof e.contentDisposition}function q(e){let t,s,i;if(e instanceof A&&e.body){const r=e.parseHeader("Content-Disposition");t=r?r.type:void 0,s=e.parseHeader("Content-Type"),i=e.body}if(e instanceof D&&e.body){const r=e.parseHeader("Content-Disposition");t=r?r.type:void 0,s=e.parseHeader("Content-Type"),i=e.body}if(e instanceof H&&e.body)if(t=e.getHeader("Content-Disposition"),s=e.getHeader("Content-Type"),"string"==typeof e.body){if(!s)throw new Error("Header content type header does not equal body content type.");i=e.body}else{if(s&&s!==e.body.contentType)throw new Error("Header content type header does not equal body content type.");s=e.body.contentType,i=e.body.body}if(x(e)&&(t=e.contentDisposition,s=e.contentType,i=e.content),i){if(s&&!t&&(t=_(s)),!t)throw new Error("Content disposition undefined.");if(!s)throw new Error("Content type undefined.");return{contentDisposition:t,contentType:s,content:i}}}var P,N;!function(e){e.Initial="Initial",e.Early="Early",e.AckWait="AckWait",e.Confirmed="Confirmed",e.Terminated="Terminated"}(P||(P={})),function(e){e.Initial="Initial",e.HaveLocalOffer="HaveLocalOffer",e.HaveRemoteOffer="HaveRemoteOffer",e.Stable="Stable",e.Closed="Closed"}(N||(N={}));class M extends n{constructor(e){super(e||"Transaction state error.")}}const O=500,U={T1:O,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};var j;!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"}(j||(j={}));const F=[j.ACK,j.BYE,j.CANCEL,j.INFO,j.INVITE,j.MESSAGE,j.NOTIFY,j.OPTIONS,j.PRACK,j.REFER,j.REGISTER,j.SUBSCRIBE];class L{constructor(e){this.incomingMessageRequest=e}get request(){return this.incomingMessageRequest.message}accept(e){return this.incomingMessageRequest.accept(e),Promise.resolve()}reject(e){return this.incomingMessageRequest.reject(e),Promise.resolve()}}class B{constructor(e){this.incomingNotifyRequest=e}get request(){return this.incomingNotifyRequest.message}accept(e){return this.incomingNotifyRequest.accept(e),Promise.resolve()}reject(e){return this.incomingNotifyRequest.reject(e),Promise.resolve()}}class V{constructor(e,t){this.incomingReferRequest=e,this.session=t}get referTo(){const e=this.incomingReferRequest.message.parseHeader("refer-to");if(!(e instanceof f))throw new Error("Failed to parse Refer-To header.");return e}get referredBy(){return this.incomingReferRequest.message.getHeader("referred-by")}get replaces(){return this.referTo.uri.getHeader("replaces")}get request(){return this.incomingReferRequest.message}accept(e={statusCode:202}){return this.incomingReferRequest.accept(e),Promise.resolve()}reject(e){return this.incomingReferRequest.reject(e),Promise.resolve()}makeInviter(e){if(this.inviter)return this.inviter;const t=this.referTo.uri.clone();t.clearHeaders();const s=((e=e||{}).extraHeaders||[]).slice(),i=this.replaces;i&&s.push("Replaces: "+decodeURIComponent(i));const r=this.referredBy;return r&&s.push("Referred-By: "+r),e.extraHeaders=s,this.inviter=this.session.userAgent._makeInviter(t,e),this.inviter._referred=this.session,this.session._referral=this.inviter,this.inviter}}var G,K;!function(e){e.Initial="Initial",e.Establishing="Establishing",e.Established="Established",e.Terminating="Terminating",e.Terminated="Terminated"}(G||(G={}));class W{constructor(e,t={}){this.pendingReinvite=!1,this.pendingReinviteAck=!1,this._state=G.Initial,this.delegate=t.delegate,this._stateEventEmitter=new g,this._userAgent=e}dispose(){switch(this.logger.log(`Session ${this.id} in state ${this._state} is being disposed`),delete this.userAgent._sessions[this.id],this._sessionDescriptionHandler&&this._sessionDescriptionHandler.close(),this.state){case G.Initial:case G.Establishing:break;case G.Established:return new Promise(e=>{this._bye({onAccept:()=>e(),onRedirect:()=>e(),onReject:()=>e()})});case G.Terminating:case G.Terminated:break;default:throw new Error("Unknown state.")}return Promise.resolve()}get assertedIdentity(){return this._assertedIdentity}get dialog(){return this._dialog}get id(){return this._id}get replacee(){return this._replacee}get sessionDescriptionHandler(){return this._sessionDescriptionHandler}get sessionDescriptionHandlerFactory(){return this.userAgent.configuration.sessionDescriptionHandlerFactory}get sessionDescriptionHandlerModifiers(){return this._sessionDescriptionHandlerModifiers||[]}set sessionDescriptionHandlerModifiers(e){this._sessionDescriptionHandlerModifiers=e.slice()}get sessionDescriptionHandlerOptions(){return this._sessionDescriptionHandlerOptions||{}}set sessionDescriptionHandlerOptions(e){this._sessionDescriptionHandlerOptions=Object.assign({},e)}get sessionDescriptionHandlerModifiersReInvite(){return this._sessionDescriptionHandlerModifiersReInvite||[]}set sessionDescriptionHandlerModifiersReInvite(e){this._sessionDescriptionHandlerModifiersReInvite=e.slice()}get sessionDescriptionHandlerOptionsReInvite(){return this._sessionDescriptionHandlerOptionsReInvite||{}}set sessionDescriptionHandlerOptionsReInvite(e){this._sessionDescriptionHandlerOptionsReInvite=Object.assign({},e)}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get userAgent(){return this._userAgent}bye(e={}){let t="Session.bye() may only be called if established session.";switch(this.state){case G.Initial:"function"==typeof this.cancel?(t+=" However Inviter.invite() has not yet been called.",t+=" Perhaps you should have called Inviter.cancel()?"):"function"==typeof this.reject&&(t+=" However Invitation.accept() has not yet been called.",t+=" Perhaps you should have called Invitation.reject()?");break;case G.Establishing:"function"==typeof this.cancel?(t+=" However a dialog does not yet exist.",t+=" Perhaps you should have called Inviter.cancel()?"):"function"==typeof this.reject&&(t+=" However Invitation.accept() has not yet been called (or not yet resolved).",t+=" Perhaps you should have called Invitation.reject()?");break;case G.Established:{const t=e.requestDelegate,s=this.copyRequestOptions(e.requestOptions);return this._bye(t,s)}case G.Terminating:t+=" However this session is already terminating.","function"==typeof this.cancel?t+=" Perhaps you have already called Inviter.cancel()?":"function"==typeof this.reject&&(t+=" Perhaps you have already called Session.bye()?");break;case G.Terminated:t+=" However this session is already terminated.";break;default:throw new Error("Unknown state")}return this.logger.error(t),Promise.reject(new Error("Invalid session state "+this.state))}info(e={}){if(this.state!==G.Established){const e="Session.info() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error("Invalid session state "+this.state))}const t=e.requestDelegate,s=this.copyRequestOptions(e.requestOptions);return this._info(t,s)}invite(e={}){if(this.logger.log("Session.invite"),this.state!==G.Established)return Promise.reject(new Error("Invalid session state "+this.state));if(this.pendingReinvite)return Promise.reject(new a("Reinvite in progress. Please wait until complete, then try again."));this.pendingReinvite=!0,e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiersReInvite=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptionsReInvite=e.sessionDescriptionHandlerOptions);const t={onAccept:t=>{const s=q(t.message);if(!s)return this.logger.error("Received 2xx response to re-INVITE without a session description"),this.ackAndBye(t,400,"Missing session description"),this.stateTransition(G.Terminated),void(this.pendingReinvite=!1);if(e.withoutSdp){const i={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.setOfferAndGetAnswer(s,i).then(e=>{t.ack({body:e})}).catch(e=>{this.logger.error("Failed to handle offer in 2xx response to re-INVITE"),this.logger.error(e.message),this.state===G.Terminated?t.ack():(this.ackAndBye(t,488,"Bad Media Description"),this.stateTransition(G.Terminated))}).then(()=>{this.pendingReinvite=!1,e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t)})}else{const i={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.setAnswer(s,i).then(()=>{t.ack()}).catch(e=>{this.logger.error("Failed to handle answer in 2xx response to re-INVITE"),this.logger.error(e.message),this.state!==G.Terminated?(this.ackAndBye(t,488,"Bad Media Description"),this.stateTransition(G.Terminated)):t.ack()}).then(()=>{this.pendingReinvite=!1,e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t)})}},onProgress:e=>{},onRedirect:e=>{},onReject:t=>{this.logger.warn("Received a non-2xx response to re-INVITE"),this.pendingReinvite=!1,e.withoutSdp?e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t):this.rollbackOffer().catch(e=>{if(this.logger.error("Failed to rollback offer on non-2xx response to re-INVITE"),this.logger.error(e.message),this.state!==G.Terminated){if(!this.dialog)throw new Error("Dialog undefined.");const e=[];e.push("Reason: "+this.getReasonHeaderValue(500,"Internal Server Error")),this.dialog.bye(void 0,{extraHeaders:e}),this.stateTransition(G.Terminated)}}).then(()=>{e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t)})},onTrying:e=>{}},s=e.requestOptions||{};if(s.extraHeaders=(s.extraHeaders||[]).slice(),s.extraHeaders.push("Allow: "+F.toString()),s.extraHeaders.push("Contact: "+this._contact),e.withoutSdp){if(!this.dialog)throw this.pendingReinvite=!1,new Error("Dialog undefined.");return Promise.resolve(this.dialog.invite(t,s))}const i={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};return this.getOffer(i).then(e=>{if(!this.dialog)throw this.pendingReinvite=!1,new Error("Dialog undefined.");return s.body=e,this.dialog.invite(t,s)}).catch(e=>{throw this.logger.error(e.message),this.logger.error("Failed to send re-INVITE"),this.pendingReinvite=!1,e})}message(e={}){if(this.state!==G.Established){const e="Session.message() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error("Invalid session state "+this.state))}const t=e.requestDelegate,s=this.copyRequestOptions(e.requestOptions);return this._message(t,s)}refer(e,t={}){if(this.state!==G.Established){const e="Session.refer() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error("Invalid session state "+this.state))}const s=t.requestDelegate,i=this.copyRequestOptions(t.requestOptions);return i.extraHeaders=i.extraHeaders?i.extraHeaders.concat(this.referExtraHeaders(this.referToString(e))):this.referExtraHeaders(this.referToString(e)),this._refer(t.onNotify,s,i)}_bye(e,t){if(!this.dialog)return Promise.reject(new Error("Session dialog undefined."));const s=this.dialog;switch(s.sessionState){case P.Initial:case P.Early:throw new Error("Invalid dialog state "+s.sessionState);case P.AckWait:return this.stateTransition(G.Terminating),new Promise(i=>{s.delegate={onAck:()=>{const r=s.bye(e,t);return this.stateTransition(G.Terminated),i(r),Promise.resolve()},onAckTimeout:()=>{const r=s.bye(e,t);this.stateTransition(G.Terminated),i(r)}}});case P.Confirmed:{const i=s.bye(e,t);return this.stateTransition(G.Terminated),Promise.resolve(i)}case P.Terminated:throw new Error("Invalid dialog state "+s.sessionState);default:throw new Error("Unrecognized state.")}}_info(e,t){return this.dialog?Promise.resolve(this.dialog.info(e,t)):Promise.reject(new Error("Session dialog undefined."))}_message(e,t){return this.dialog?Promise.resolve(this.dialog.message(e,t)):Promise.reject(new Error("Session dialog undefined."))}_refer(e,t,s){return this.dialog?(this.onNotify=e,Promise.resolve(this.dialog.refer(t,s))):Promise.reject(new Error("Session dialog undefined."))}ackAndBye(e,t,s){e.ack();const i=[];t&&i.push("Reason: "+this.getReasonHeaderValue(t,s)),e.session.bye(void 0,{extraHeaders:i})}onAckRequest(e){if(this.logger.log("Session.onAckRequest"),this.state!==G.Established&&this.state!==G.Terminating)return this.logger.error(`ACK received while in state ${this.state}, dropping request`),Promise.resolve();const t=this.dialog;if(!t)throw new Error("Dialog undefined.");const s={sessionDescriptionHandlerOptions:this.pendingReinviteAck?this.sessionDescriptionHandlerOptionsReInvite:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.pendingReinviteAck?this._sessionDescriptionHandlerModifiersReInvite:this._sessionDescriptionHandlerModifiers};switch(this.pendingReinviteAck=!1,t.signalingState){case N.Initial:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const e=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:e}),this.stateTransition(G.Terminated),Promise.resolve()}case N.Stable:{const i=q(e.message);return i?"render"===i.contentDisposition?(this._renderbody=i.content,this._rendertype=i.contentType,Promise.resolve()):"session"!==i.contentDisposition?Promise.resolve():this.setAnswer(i,s).catch(e=>{this.logger.error(e.message);const s=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];t.bye(void 0,{extraHeaders:s}),this.stateTransition(G.Terminated)}):Promise.resolve()}case N.HaveLocalOffer:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const e=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:e}),this.stateTransition(G.Terminated),Promise.resolve()}case N.HaveRemoteOffer:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const e=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:e}),this.stateTransition(G.Terminated),Promise.resolve()}case N.Closed:default:throw new Error(`Invalid signaling state ${t.signalingState}.`)}}onByeRequest(e){if(this.logger.log("Session.onByeRequest"),this.state===G.Established){if(this.delegate&&this.delegate.onBye){const t=new l(e);this.delegate.onBye(t)}else e.accept();this.stateTransition(G.Terminated)}else this.logger.error(`BYE received while in state ${this.state}, dropping request`)}onInfoRequest(e){if(this.logger.log("Session.onInfoRequest"),this.state===G.Established)if(this.delegate&&this.delegate.onInfo){const t=new u(e);this.delegate.onInfo(t)}else e.accept();else this.logger.error(`INFO received while in state ${this.state}, dropping request`)}onInviteRequest(e){if(this.logger.log("Session.onInviteRequest"),this.state!==G.Established)return void this.logger.error(`INVITE received while in state ${this.state}, dropping request`);this.pendingReinviteAck=!0;const t=["Contact: "+this._contact];if(e.message.hasHeader("P-Asserted-Identity")){const t=e.message.getHeader("P-Asserted-Identity");if(!t)throw new Error("Header undefined.");this._assertedIdentity=b.nameAddrHeaderParse(t)}const s={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.generateResponseOfferAnswerInDialog(s).then(s=>{const i=e.accept({statusCode:200,extraHeaders:t,body:s});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,i.message,200)}).catch(s=>{if(this.logger.error(s.message),this.logger.error("Failed to handle to re-INVITE request"),!this.dialog)throw new Error("Dialog undefined.");if(this.logger.error(this.dialog.signalingState),this.dialog.signalingState!==N.Stable)this.rollbackOffer().then(()=>{const t=e.reject({statusCode:488});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,t.message,488)}).catch(s=>{this.logger.error(s.message),this.logger.error("Failed to rollback offer on re-INVITE request");const i=e.reject({statusCode:488});if(this.state!==G.Terminated){if(!this.dialog)throw new Error("Dialog undefined.");[].push("Reason: "+this.getReasonHeaderValue(500,"Internal Server Error")),this.dialog.bye(void 0,{extraHeaders:t}),this.stateTransition(G.Terminated)}this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,i.message,488)});else{const t=e.reject({statusCode:488});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,t.message,488)}})}onMessageRequest(e){if(this.logger.log("Session.onMessageRequest"),this.state===G.Established)if(this.delegate&&this.delegate.onMessage){const t=new L(e);this.delegate.onMessage(t)}else e.accept();else this.logger.error(`MESSAGE received while in state ${this.state}, dropping request`)}onNotifyRequest(e){if(this.logger.log("Session.onNotifyRequest"),this.state===G.Established)if(this.onNotify){const t=new B(e);this.onNotify(t)}else if(this.delegate&&this.delegate.onNotify){const t=new B(e);this.delegate.onNotify(t)}else e.accept();else this.logger.error(`NOTIFY received while in state ${this.state}, dropping request`)}onPrackRequest(e){if(this.logger.log("Session.onPrackRequest"),this.state===G.Established)throw new Error("Unimplemented.");this.logger.error(`PRACK received while in state ${this.state}, dropping request`)}onReferRequest(e){if(this.logger.log("Session.onReferRequest"),this.state!==G.Established)return void this.logger.error(`REFER received while in state ${this.state}, dropping request`);if(!e.message.hasHeader("refer-to"))return this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting."),void e.reject();const t=new V(e,this);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(t):(this.logger.log("No delegate available to handle REFER, automatically accepting and following."),t.accept().then(()=>t.makeInviter(this._referralInviterOptions).invite()).catch(e=>{this.logger.error(e.message)}))}generateResponseOfferAnswer(e,t){if(this.dialog)return this.generateResponseOfferAnswerInDialog(t);const s=q(e.message);return s&&"session"===s.contentDisposition?this.setOfferAndGetAnswer(s,t):this.getOffer(t)}generateResponseOfferAnswerInDialog(e){if(!this.dialog)throw new Error("Dialog undefined.");switch(this.dialog.signalingState){case N.Initial:return this.getOffer(e);case N.HaveLocalOffer:return Promise.resolve(void 0);case N.HaveRemoteOffer:if(!this.dialog.offer)throw new Error(`Session offer undefined in signaling state ${this.dialog.signalingState}.`);return this.setOfferAndGetAnswer(this.dialog.offer,e);case N.Stable:return this.state!==G.Established?Promise.resolve(void 0):this.getOffer(e);case N.Closed:default:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`)}}getOffer(e){const t=this.setupSessionDescriptionHandler(),s=e.sessionDescriptionHandlerOptions,i=e.sessionDescriptionHandlerModifiers;try{return t.getDescription(s,i).then(e=>k(e)).catch(e=>{this.logger.error("Session.getOffer: SDH getDescription rejected...");const t=e instanceof Error?e:new Error("Session.getOffer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.getOffer: SDH getDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}rollbackOffer(){const e=this.setupSessionDescriptionHandler();if(void 0===e.rollbackDescription)return Promise.resolve();try{return e.rollbackDescription().catch(e=>{this.logger.error("Session.rollbackOffer: SDH rollbackDescription rejected...");const t=e instanceof Error?e:new Error("Session.rollbackOffer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.rollbackOffer: SDH rollbackDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}setAnswer(e,t){const s=this.setupSessionDescriptionHandler(),i=t.sessionDescriptionHandlerOptions,r=t.sessionDescriptionHandlerModifiers;try{if(!s.hasDescription(e.contentType))return Promise.reject(new o)}catch(e){this.logger.error("Session.setAnswer: SDH hasDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}try{return s.setDescription(e.content,i,r).catch(e=>{this.logger.error("Session.setAnswer: SDH setDescription rejected...");const t=e instanceof Error?e:new Error("Session.setAnswer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.setAnswer: SDH setDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}setOfferAndGetAnswer(e,t){const s=this.setupSessionDescriptionHandler(),i=t.sessionDescriptionHandlerOptions,r=t.sessionDescriptionHandlerModifiers;try{if(!s.hasDescription(e.contentType))return Promise.reject(new o)}catch(e){this.logger.error("Session.setOfferAndGetAnswer: SDH hasDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}try{return s.setDescription(e.content,i,r).then(()=>s.getDescription(i,r)).then(e=>k(e)).catch(e=>{this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription rejected...");const t=e instanceof Error?e:new Error("Session.setOfferAndGetAnswer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}setSessionDescriptionHandler(e){if(this._sessionDescriptionHandler)throw new Error("Session description handler defined.");this._sessionDescriptionHandler=e}setupSessionDescriptionHandler(){var e;return this._sessionDescriptionHandler||(this._sessionDescriptionHandler=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions),(null===(e=this.delegate)||void 0===e?void 0:e.onSessionDescriptionHandler)&&this.delegate.onSessionDescriptionHandler(this._sessionDescriptionHandler,!1)),this._sessionDescriptionHandler}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case G.Initial:e!==G.Establishing&&e!==G.Established&&e!==G.Terminating&&e!==G.Terminated&&t();break;case G.Establishing:e!==G.Established&&e!==G.Terminating&&e!==G.Terminated&&t();break;case G.Established:e!==G.Terminating&&e!==G.Terminated&&t();break;case G.Terminating:e!==G.Terminated&&t();break;case G.Terminated:t();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log(`Session ${this.id} transitioned to state ${this._state}`),this._stateEventEmitter.emit(this._state),e===G.Terminated&&this.dispose()}copyRequestOptions(e={}){return{extraHeaders:e.extraHeaders?e.extraHeaders.slice():void 0,body:e.body?{contentDisposition:e.body.contentDisposition||"render",contentType:e.body.contentType||"text/plain",content:e.body.content||""}:void 0}}getReasonHeaderValue(e,t){const s=e;let i=y(e);return!i&&t&&(i=t),"SIP;cause="+s+';text="'+i+'"'}referExtraHeaders(e){const t=[];return t.push("Referred-By: <"+this.userAgent.configuration.uri+">"),t.push("Contact: "+this._contact),t.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),t.push("Refer-To: "+e),t}referToString(e){let t;if(e instanceof m)t=e.toString();else{if(!e.dialog)throw new Error("Dialog undefined.");const s=e.remoteIdentity.friendlyName,i=e.dialog.remoteTarget.toString(),r=e.dialog.callId,n=e.dialog.remoteTag,o=e.dialog.localTag;t=`"${s}" <${i}?Replaces=${encodeURIComponent(`${r};to-tag=${n};from-tag=${o}`)}>`}return t}}!function(e){e.Required="Required",e.Supported="Supported",e.Unsupported="Unsupported"}(K||(K={}));const Y={"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};class Z extends W{constructor(e,t){super(e),this.incomingInviteRequest=t,this.disposed=!1,this.expiresTimer=void 0,this.isCanceled=!1,this.rel100="none",this.rseq=Math.floor(1e4*Math.random()),this.userNoAnswerTimer=void 0,this.waitingForPrack=!1,this.logger=e.getLogger("sip.Invitation");const s=this.incomingInviteRequest.message,i=s.getHeader("require");i&&i.toLowerCase().includes("100rel")&&(this.rel100="required");const r=s.getHeader("supported");if(r&&r.toLowerCase().includes("100rel")&&(this.rel100="supported"),s.toTag=t.toTag,"string"!=typeof s.toTag)throw new TypeError("toTag should have been a string.");if(this.userNoAnswerTimer=setTimeout(()=>{t.reject({statusCode:480}),this.stateTransition(G.Terminated)},this.userAgent.configuration.noAnswerTimeout?1e3*this.userAgent.configuration.noAnswerTimeout:6e4),s.hasHeader("expires")){const e=1e3*Number(s.getHeader("expires")||0);this.expiresTimer=setTimeout(()=>{this.state===G.Initial&&(t.reject({statusCode:487}),this.stateTransition(G.Terminated))},e)}const n=this.request.getHeader("P-Asserted-Identity");n&&(this._assertedIdentity=b.nameAddrHeaderParse(n)),this._contact=this.userAgent.contact.toString();const o=s.parseHeader("Content-Disposition");o&&"render"===o.type&&(this._renderbody=s.body,this._rendertype=s.getHeader("Content-Type")),this._id=s.callId+s.fromTag,this.userAgent._sessions[this._id]=this}dispose(){if(this.disposed)return Promise.resolve();switch(this.disposed=!0,this.expiresTimer&&(clearTimeout(this.expiresTimer),this.expiresTimer=void 0),this.userNoAnswerTimer&&(clearTimeout(this.userNoAnswerTimer),this.userNoAnswerTimer=void 0),this.prackNeverArrived(),this.state){case G.Initial:case G.Establishing:return this.reject().then(()=>super.dispose());case G.Established:case G.Terminating:case G.Terminated:return super.dispose();default:throw new Error("Unknown state.")}}get autoSendAnInitialProvisionalResponse(){return"required"!==this.rel100}get body(){return this.incomingInviteRequest.message.body}get localIdentity(){return this.request.to}get remoteIdentity(){return this.request.from}get request(){return this.incomingInviteRequest.message}accept(e={}){if(this.logger.log("Invitation.accept"),this.state!==G.Initial){const e=new Error("Invalid session state "+this.state);return this.logger.error(e.message),Promise.reject(e)}return e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),this.stateTransition(G.Establishing),this.sendAccept().then(({message:e,session:t})=>{t.delegate={onAck:e=>this.onAckRequest(e),onAckTimeout:()=>this.onAckTimeout(),onBye:e=>this.onByeRequest(e),onInfo:e=>this.onInfoRequest(e),onInvite:e=>this.onInviteRequest(e),onMessage:e=>this.onMessageRequest(e),onNotify:e=>this.onNotifyRequest(e),onPrack:e=>this.onPrackRequest(e),onRefer:e=>this.onReferRequest(e)},this._dialog=t,this.stateTransition(G.Established),this._replacee&&this._replacee._bye()}).catch(e=>this.handleResponseError(e))}progress(e={}){if(this.logger.log("Invitation.progress"),this.state!==G.Initial){const e=new Error("Invalid session state "+this.state);return this.logger.error(e.message),Promise.reject(e)}const t=e.statusCode||180;if(t<100||t>199)throw new TypeError("Invalid statusCode: "+t);return e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),this.waitingForPrack?(this.logger.warn("Unexpected call for progress while waiting for prack, ignoring"),Promise.resolve()):100===e.statusCode?this.sendProgressTrying().then(()=>{}).catch(e=>this.handleResponseError(e)):"required"===this.rel100||"supported"===this.rel100&&e.rel100||"supported"===this.rel100&&this.userAgent.configuration.sipExtension100rel===K.Required?this.sendProgressReliableWaitForPrack(e).then(()=>{}).catch(e=>this.handleResponseError(e)):this.sendProgress(e).then(()=>{}).catch(e=>this.handleResponseError(e))}reject(e={}){if(this.logger.log("Invitation.reject"),this.state!==G.Initial&&this.state!==G.Establishing){const e=new Error("Invalid session state "+this.state);return this.logger.error(e.message),Promise.reject(e)}const t=e.statusCode||480,s=e.reasonPhrase?e.reasonPhrase:y(t),i=e.extraHeaders||[];if(t<300||t>699)throw new TypeError("Invalid statusCode: "+t);const r=e.body?k(e.body):void 0;return t<400?this.incomingInviteRequest.redirect([],{statusCode:t,reasonPhrase:s,extraHeaders:i,body:r}):this.incomingInviteRequest.reject({statusCode:t,reasonPhrase:s,extraHeaders:i,body:r}),this.stateTransition(G.Terminated),Promise.resolve()}_onCancel(e){this.logger.log("Invitation._onCancel"),this.state===G.Initial||this.state===G.Establishing?(this.isCanceled=!0,this.incomingInviteRequest.reject({statusCode:487}),this.stateTransition(G.Terminated)):this.logger.error(`CANCEL received while in state ${this.state}, dropping request`)}handlePrackOfferAnswer(e){if(!this.dialog)throw new Error("Dialog undefined.");const t=q(e.message);if(!t||"session"!==t.contentDisposition)return Promise.resolve(void 0);const s={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers};switch(this.dialog.signalingState){case N.Initial:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case N.Stable:return this.setAnswer(t,s).then(()=>{});case N.HaveLocalOffer:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case N.HaveRemoteOffer:return this.setOfferAndGetAnswer(t,s);case N.Closed:default:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`)}}handleResponseError(e){let t=480;if(e instanceof Error?this.logger.error(e.message):this.logger.error(e),e instanceof o?(this.logger.error("A session description handler occurred while sending response (content type unsupported"),t=415):e instanceof c?this.logger.error("A session description handler occurred while sending response"):e instanceof h?this.logger.error("Session ended before response could be formulated and sent (while waiting for PRACK)"):e instanceof M&&this.logger.error("Session changed state before response could be formulated and sent"),this.state===G.Initial||this.state===G.Establishing)try{this.incomingInviteRequest.reject({statusCode:t}),this.stateTransition(G.Terminated)}catch(e){throw this.logger.error("An error occurred attempting to reject the request while handling another error"),e}if(!this.isCanceled)throw e;this.logger.warn("An error occurred while attempting to formulate and send a response to an incoming INVITE. However a CANCEL was received and processed while doing so which can (and often does) result in errors occurring as the session terminates in the meantime. Said error is being ignored.")}onAckTimeout(){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(G.Terminated)}sendAccept(){const e={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers};return this.waitingForPrack?this.waitForArrivalOfPrack().then(()=>clearTimeout(this.userNoAnswerTimer)).then(()=>this.generateResponseOfferAnswer(this.incomingInviteRequest,e)).then(e=>this.incomingInviteRequest.accept({statusCode:200,body:e})):(clearTimeout(this.userNoAnswerTimer),this.generateResponseOfferAnswer(this.incomingInviteRequest,e).then(e=>this.incomingInviteRequest.accept({statusCode:200,body:e})))}sendProgress(e={}){const t=e.statusCode||180,s=e.reasonPhrase,i=(e.extraHeaders||[]).slice(),r=e.body?k(e.body):void 0;if(183===t&&!r)return this.sendProgressWithSDP(e);try{const e=this.incomingInviteRequest.progress({statusCode:t,reasonPhrase:s,extraHeaders:i,body:r});return this._dialog=e.session,Promise.resolve(e)}catch(e){return Promise.reject(e)}}sendProgressWithSDP(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},s=e.statusCode||183,i=e.reasonPhrase,r=(e.extraHeaders||[]).slice();return this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then(e=>this.incomingInviteRequest.progress({statusCode:s,reasonPhrase:i,extraHeaders:r,body:e})).then(e=>(this._dialog=e.session,e))}sendProgressReliable(e={}){return e.extraHeaders=(e.extraHeaders||[]).slice(),e.extraHeaders.push("Require: 100rel"),e.extraHeaders.push("RSeq: "+Math.floor(1e4*Math.random())),this.sendProgressWithSDP(e)}sendProgressReliableWaitForPrack(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},s=e.statusCode||183,i=e.reasonPhrase,r=(e.extraHeaders||[]).slice();let n;return r.push("Require: 100rel"),r.push("RSeq: "+this.rseq++),new Promise((e,o)=>{this.waitingForPrack=!0,this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then(e=>(n=e,this.incomingInviteRequest.progress({statusCode:s,reasonPhrase:i,extraHeaders:r,body:n}))).then(t=>{let a,c;this._dialog=t.session,t.session.delegate={onPrack:s=>{a=s,clearTimeout(d),clearTimeout(u),this.waitingForPrack&&(this.waitingForPrack=!1,this.handlePrackOfferAnswer(a).then(s=>{try{c=a.accept({statusCode:200,body:s}),this.prackArrived(),e({prackRequest:a,prackResponse:c,progressResponse:t})}catch(e){o(e)}}).catch(e=>o(e)))}};const d=setTimeout(()=>{this.waitingForPrack&&(this.waitingForPrack=!1,this.logger.warn("No PRACK received, rejecting INVITE."),clearTimeout(u),this.reject({statusCode:504}).then(()=>o(new h)).catch(e=>o(e)))},64*U.T1),l=()=>{try{this.incomingInviteRequest.progress({statusCode:s,reasonPhrase:i,extraHeaders:r,body:n})}catch(e){return this.waitingForPrack=!1,void o(e)}u=setTimeout(l,g*=2)};let g=U.T1,u=setTimeout(l,g)}).catch(e=>{this.waitingForPrack=!1,o(e)})})}sendProgressTrying(){try{const e=this.incomingInviteRequest.trying();return Promise.resolve(e)}catch(e){return Promise.reject(e)}}waitForArrivalOfPrack(){if(this.waitingForPrackPromise)throw new Error("Already waiting for PRACK");return this.waitingForPrackPromise=new Promise((e,t)=>{this.waitingForPrackResolve=e,this.waitingForPrackReject=t}),this.waitingForPrackPromise}prackArrived(){this.waitingForPrackResolve&&this.waitingForPrackResolve(),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0}prackNeverArrived(){this.waitingForPrackReject&&this.waitingForPrackReject(new h),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0}}class J extends W{constructor(e,t,s={}){super(e,s),this.disposed=!1,this.earlyMedia=!1,this.earlyMediaSessionDescriptionHandlers=new Map,this.isCanceled=!1,this.inviteWithoutSdp=!1,this.logger=e.getLogger("sip.Inviter"),this.earlyMedia=void 0!==s.earlyMedia?s.earlyMedia:this.earlyMedia,this.fromTag=E(),this.inviteWithoutSdp=void 0!==s.inviteWithoutSdp?s.inviteWithoutSdp:this.inviteWithoutSdp;const i=Object.assign({},s);i.params=Object.assign({},s.params);const r=s.anonymous||!1,n=e.contact.toString({anonymous:r,outbound:r?!e.contact.tempGruu:!e.contact.pubGruu});r&&e.configuration.uri&&(i.params.fromDisplayName="Anonymous",i.params.fromUri="sip:anonymous@anonymous.invalid");let o=e.userAgentCore.configuration.aor;if(i.params.fromUri&&(o="string"==typeof i.params.fromUri?b.URIParse(i.params.fromUri):i.params.fromUri),!o)throw new TypeError("Invalid from URI: "+i.params.fromUri);let a=t;if(i.params.toUri&&(a="string"==typeof i.params.toUri?b.URIParse(i.params.toUri):i.params.toUri),!a)throw new TypeError("Invalid to URI: "+i.params.toUri);const c=Object.assign({},i.params);c.fromTag=this.fromTag;const h=(i.extraHeaders||[]).slice();r&&e.configuration.uri&&(h.push("P-Preferred-Identity: "+e.configuration.uri.toString()),h.push("Privacy: id")),h.push("Contact: "+n),h.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),e.configuration.sipExtension100rel===K.Required&&h.push("Require: 100rel"),e.configuration.sipExtensionReplaces===K.Required&&h.push("Require: replaces"),i.extraHeaders=h;this.outgoingRequestMessage=e.userAgentCore.makeOutgoingRequestMessage(j.INVITE,t,o,a,c,h,void 0),this._contact=n,this._referralInviterOptions=i,this._renderbody=s.renderbody,this._rendertype=s.rendertype,s.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=s.sessionDescriptionHandlerModifiers),s.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=s.sessionDescriptionHandlerOptions),s.sessionDescriptionHandlerModifiersReInvite&&(this.sessionDescriptionHandlerModifiersReInvite=s.sessionDescriptionHandlerModifiersReInvite),s.sessionDescriptionHandlerOptionsReInvite&&(this.sessionDescriptionHandlerOptionsReInvite=s.sessionDescriptionHandlerOptionsReInvite),this._id=this.outgoingRequestMessage.callId+this.fromTag,this.userAgent._sessions[this._id]=this}dispose(){if(this.disposed)return Promise.resolve();switch(this.disposed=!0,this.disposeEarlyMedia(),this.state){case G.Initial:case G.Establishing:return this.cancel().then(()=>super.dispose());case G.Established:case G.Terminating:case G.Terminated:return super.dispose();default:throw new Error("Unknown state.")}}get body(){return this.outgoingRequestMessage.body}get localIdentity(){return this.outgoingRequestMessage.from}get remoteIdentity(){return this.outgoingRequestMessage.to}get request(){return this.outgoingRequestMessage}cancel(e={}){if(this.logger.log("Inviter.cancel"),this.state!==G.Initial&&this.state!==G.Establishing){const e=new Error("Invalid session state "+this.state);return this.logger.error(e.message),Promise.reject(e)}if(this.isCanceled=!0,this.stateTransition(G.Terminating),this.outgoingInviteRequest){let t;e.statusCode&&e.reasonPhrase&&(t=function(e,t){if(e&&e<200||e>699)throw new TypeError("Invalid statusCode: "+e);if(e){return"SIP;cause="+e+';text="'+(y(e)||t)+'"'}}(e.statusCode,e.reasonPhrase)),this.outgoingInviteRequest.cancel(t,e)}else this.logger.warn("Canceled session before INVITE was sent"),this.stateTransition(G.Terminated);return Promise.resolve()}invite(e={}){if(this.logger.log("Inviter.invite"),this.state!==G.Initial)return super.invite(e);if(e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),e.withoutSdp||this.inviteWithoutSdp)return this._renderbody&&this._rendertype&&(this.outgoingRequestMessage.body={contentType:this._rendertype,body:this._renderbody}),this.stateTransition(G.Establishing),Promise.resolve(this.sendInvite(e));const t={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.getOffer(t).then(t=>(this.outgoingRequestMessage.body={body:t.content,contentType:t.contentType},this.stateTransition(G.Establishing),this.sendInvite(e))).catch(e=>{throw this.logger.log(e.message),this.stateTransition(G.Terminated),e})}sendInvite(e={}){return this.outgoingInviteRequest=this.userAgent.userAgentCore.invite(this.outgoingRequestMessage,{onAccept:t=>this.dialog?(this.logger.log("Additional confirmed dialog, sending ACK and BYE"),void this.ackAndBye(t)):this.isCanceled?(this.logger.log("Canceled session accepted, sending ACK and BYE"),this.ackAndBye(t),void this.stateTransition(G.Terminated)):(this.notifyReferer(t),void this.onAccept(t).then(()=>{this.disposeEarlyMedia()}).catch(()=>{this.disposeEarlyMedia()}).then(()=>{e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t)})),onProgress:t=>{this.isCanceled||(this.notifyReferer(t),this.onProgress(t).catch(()=>{this.disposeEarlyMedia()}).then(()=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)}))},onRedirect:t=>{this.notifyReferer(t),this.onRedirect(t),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t)},onReject:t=>{this.notifyReferer(t),this.onReject(t),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t)},onTrying:t=>{this.notifyReferer(t),this.onTrying(t),e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}}),this.outgoingInviteRequest}disposeEarlyMedia(){this.earlyMediaSessionDescriptionHandlers.forEach(e=>{e.close()}),this.earlyMediaSessionDescriptionHandlers.clear()}notifyReferer(e){if(!this._referred)return;if(!(this._referred instanceof W))throw new Error("Referred session not instance of session");if(!this._referred.dialog)return;if(!e.message.statusCode)throw new Error("Status code undefined.");if(!e.message.reasonPhrase)throw new Error("Reason phrase undefined.");const t=`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:t}}).delegate={onReject:()=>{this._referred=void 0}}}onAccept(e){if(this.logger.log("Inviter.onAccept"),this.state!==G.Establishing)return this.logger.error(`Accept received while in state ${this.state}, dropping response`),Promise.reject(new Error("Invalid session state "+this.state));const t=e.message,s=e.session;switch(t.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=b.nameAddrHeaderParse(t.getHeader("P-Asserted-Identity"))),s.delegate={onAck:e=>this.onAckRequest(e),onBye:e=>this.onByeRequest(e),onInfo:e=>this.onInfoRequest(e),onInvite:e=>this.onInviteRequest(e),onMessage:e=>this.onMessageRequest(e),onNotify:e=>this.onNotifyRequest(e),onPrack:e=>this.onPrackRequest(e),onRefer:e=>this.onReferRequest(e)},this._dialog=s,s.signalingState){case N.Initial:case N.HaveLocalOffer:return this.logger.error("Received 2xx response to INVITE without a session description"),this.ackAndBye(e,400,"Missing session description"),this.stateTransition(G.Terminated),Promise.reject(new Error("Bad Media Description"));case N.HaveRemoteOffer:{if(!this._dialog.offer)throw new Error(`Session offer undefined in signaling state ${this._dialog.signalingState}.`);const t={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setOfferAndGetAnswer(this._dialog.offer,t).then(t=>{e.ack({body:t}),this.stateTransition(G.Established)}).catch(t=>{throw this.ackAndBye(e,488,"Invalid session description"),this.stateTransition(G.Terminated),t})}case N.Stable:{if(this.earlyMediaSessionDescriptionHandlers.size>0){const t=this.earlyMediaSessionDescriptionHandlers.get(s.id);if(!t)throw new Error("Session description handler undefined.");return this.setSessionDescriptionHandler(t),this.earlyMediaSessionDescriptionHandlers.delete(s.id),e.ack(),this.stateTransition(G.Established),Promise.resolve()}if(this.earlyMediaDialog){if(this.earlyMediaDialog!==s){if(this.earlyMedia){const e="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 behavior 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(e)}const t=new Error("Early media dialog does not equal confirmed dialog, terminating session");return this.logger.error(t.message),this.ackAndBye(e,488,"Not Acceptable Here"),this.stateTransition(G.Terminated),Promise.reject(t)}return e.ack(),this.stateTransition(G.Established),Promise.resolve()}const t=s.answer;if(!t)throw new Error("Answer is undefined.");const i={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(t,i).then(()=>{let t;this._renderbody&&this._rendertype&&(t={body:{contentDisposition:"render",contentType:this._rendertype,content:this._renderbody}}),e.ack(t),this.stateTransition(G.Established)}).catch(t=>{throw this.logger.error(t.message),this.ackAndBye(e,488,"Not Acceptable Here"),this.stateTransition(G.Terminated),t})}case N.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onProgress(e){var t;if(this.logger.log("Inviter.onProgress"),this.state!==G.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.");const s=e.message,i=e.session;s.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=b.nameAddrHeaderParse(s.getHeader("P-Asserted-Identity")));const r=s.getHeader("require"),n=s.getHeader("rseq"),o=!!(r&&r.includes("100rel")&&n?Number(n):void 0),a=[];switch(o&&a.push("RAck: "+s.getHeader("rseq")+" "+s.getHeader("cseq")),i.signalingState){case N.Initial:return o&&(this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."),e.prack({extraHeaders:a})),Promise.resolve();case N.HaveLocalOffer:return o&&e.prack({extraHeaders:a}),Promise.resolve();case N.HaveRemoteOffer:if(!o)return this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response."),Promise.resolve();{const r=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions||{});return(null===(t=this.delegate)||void 0===t?void 0:t.onSessionDescriptionHandler)&&this.delegate.onSessionDescriptionHandler(r,!0),this.earlyMediaSessionDescriptionHandlers.set(i.id,r),r.setDescription(s.body,this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers).then(()=>r.getDescription(this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers)).then(t=>{const s={contentDisposition:"session",contentType:t.contentType,content:t.body};e.prack({extraHeaders:a,body:s})}).catch(e=>{throw this.stateTransition(G.Terminated),e})}case N.Stable:if(o&&e.prack({extraHeaders:a}),this.earlyMedia&&!this.earlyMediaDialog){this.earlyMediaDialog=i;const e=i.answer;if(!e)throw new Error("Answer is undefined.");const t={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(e,t).catch(e=>{throw this.stateTransition(G.Terminated),e})}return Promise.resolve();case N.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onRedirect(e){this.logger.log("Inviter.onRedirect"),this.state===G.Establishing||this.state===G.Terminating?this.stateTransition(G.Terminated):this.logger.error(`Redirect received while in state ${this.state}, dropping response`)}onReject(e){this.logger.log("Inviter.onReject"),this.state===G.Establishing||this.state===G.Terminating?this.stateTransition(G.Terminated):this.logger.error(`Reject received while in state ${this.state}, dropping response`)}onTrying(e){this.logger.log("Inviter.onTrying"),this.state===G.Establishing||this.logger.error(`Trying received while in state ${this.state}, dropping response`)}}class z{constructor(e,t,s,i="text/plain",r={}){this.logger=e.getLogger("sip.Messager"),r.params=r.params||{};let n=e.userAgentCore.configuration.aor;if(r.params.fromUri&&(n="string"==typeof r.params.fromUri?b.URIParse(r.params.fromUri):r.params.fromUri),!n)throw new TypeError("Invalid from URI: "+r.params.fromUri);let o=t;if(r.params.toUri&&(o="string"==typeof r.params.toUri?b.URIParse(r.params.toUri):r.params.toUri),!o)throw new TypeError("Invalid to URI: "+r.params.toUri);const a=r.params?Object.assign({},r.params):{},c=(r.extraHeaders||[]).slice(),h={contentDisposition:"render",contentType:i,content:s};this.request=e.userAgentCore.makeOutgoingRequestMessage(j.MESSAGE,t,n,o,a,c,h),this.userAgent=e}message(e={}){return this.userAgent.userAgentCore.request(this.request,e.requestDelegate),Promise.resolve()}}var X,Q,ee,te,se,ie,re,ne;!function(e){e.Initial="Initial",e.Published="Published",e.Unpublished="Unpublished",e.Terminated="Terminated"}(X||(X={}));class oe{constructor(e,t,s,i={}){this.disposed=!1,this._state=X.Initial,this._stateEventEmitter=new g,this.userAgent=e,i.extraHeaders=(i.extraHeaders||[]).slice(),i.contentType=i.contentType||"text/plain","number"!=typeof i.expires||i.expires%1!=0?i.expires=3600:i.expires=Number(i.expires),"boolean"!=typeof i.unpublishOnClose&&(i.unpublishOnClose=!0),this.target=t,this.event=s,this.options=i,this.pubRequestExpires=i.expires,this.logger=e.getLogger("sip.Publisher");const r=i.params||{},n=r.fromUri?r.fromUri:e.userAgentCore.configuration.aor,o=r.toUri?r.toUri:t;let a;if(i.body&&i.contentType){a={contentDisposition:"render",contentType:i.contentType,content:i.body}}const c=(i.extraHeaders||[]).slice();this.request=e.userAgentCore.makeOutgoingRequestMessage(j.PUBLISH,t,n,o,r,c,a),this.id=this.target.toString()+":"+this.event,this.userAgent._publishers[this.id]=this}dispose(){return this.disposed?Promise.resolve():(this.disposed=!0,this.logger.log(`Publisher ${this.id} in state ${this.state} is being disposed`),delete this.userAgent._publishers[this.id],this.options.unpublishOnClose&&this.state===X.Published?this.unpublish():(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,this.pubRequestExpires=0,this.pubRequestEtag=void 0,Promise.resolve()))}get state(){return this._state}get stateChange(){return this._stateEventEmitter}publish(e,t={}){if(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.options.body=e,this.pubRequestBody=this.options.body,0===this.pubRequestExpires){if(void 0===this.options.expires)throw new Error("Expires undefined.");this.pubRequestExpires=this.options.expires,this.pubRequestEtag=void 0}return this.sendPublishRequest(),Promise.resolve()}unpublish(e={}){return this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,this.pubRequestExpires=0,void 0!==this.pubRequestEtag&&this.sendPublishRequest(),Promise.resolve()}receiveResponse(e){const t=e.statusCode||0;switch(!0){case/^1[0-9]{2}$/.test(t.toString()):break;case/^2[0-9]{2}$/.test(t.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")){const t=Number(e.getHeader("Expires"));"number"==typeof t&&t>=0&&t<=this.pubRequestExpires?this.pubRequestExpires=t: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(()=>this.refreshRequest(),900*this.pubRequestExpires),this.stateTransition(X.Published)):this.stateTransition(X.Unpublished);break;case/^412$/.test(t.toString()):if(void 0!==this.pubRequestEtag&&0!==this.pubRequestExpires){if(this.logger.warn("412 response to PUBLISH, recovering"),this.pubRequestEtag=void 0,void 0===this.options.body)throw new Error("Body undefined.");this.publish(this.options.body)}else this.logger.warn("412 response to PUBLISH, recovery failed"),this.pubRequestExpires=0,this.stateTransition(X.Unpublished),this.stateTransition(X.Terminated);break;case/^423$/.test(t.toString()):if(0!==this.pubRequestExpires&&e.hasHeader("Min-Expires")){const t=Number(e.getHeader("Min-Expires"));if("number"==typeof t||t>this.pubRequestExpires){if(this.logger.warn("423 code in response to PUBLISH, adjusting the Expires value and trying to recover"),this.pubRequestExpires=t,void 0===this.options.body)throw new Error("Body undefined.");this.publish(this.options.body)}else this.logger.warn("Bad 423 response Min-Expires header received for PUBLISH"),this.pubRequestExpires=0,this.stateTransition(X.Unpublished),this.stateTransition(X.Terminated)}else this.logger.warn("423 response to PUBLISH, recovery failed"),this.pubRequestExpires=0,this.stateTransition(X.Unpublished),this.stateTransition(X.Terminated);break;default:this.pubRequestExpires=0,this.stateTransition(X.Unpublished),this.stateTransition(X.Terminated)}0===this.pubRequestExpires&&(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,this.pubRequestEtag=void 0)}send(){return this.userAgent.userAgentCore.publish(this.request,{onAccept:e=>this.receiveResponse(e.message),onProgress:e=>this.receiveResponse(e.message),onRedirect:e=>this.receiveResponse(e.message),onReject:e=>this.receiveResponse(e.message),onTrying:e=>this.receiveResponse(e.message)})}refreshRequest(){if(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,void 0===this.pubRequestEtag)throw new Error("Etag undefined");if(0===this.pubRequestExpires)throw new Error("Expires zero");this.sendPublishRequest()}sendPublishRequest(){const e=Object.assign({},this.options);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);const t=this.target,s=this.options.params||{};let i,r;if(void 0!==this.pubRequestBody){if(void 0===this.options.contentType)throw new Error("Content type undefined.");i={body:this.pubRequestBody,contentType:this.options.contentType}}return i&&(r=k(i)),this.request=this.userAgent.userAgentCore.makeOutgoingRequestMessage(j.PUBLISH,t,s.fromUri?s.fromUri:this.userAgent.userAgentCore.configuration.aor,s.toUri?s.toUri:this.target,s,e.extraHeaders,r),this.send()}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case X.Initial:e!==X.Published&&e!==X.Unpublished&&e!==X.Terminated&&t();break;case X.Published:e!==X.Unpublished&&e!==X.Terminated&&t();break;case X.Unpublished:e!==X.Published&&e!==X.Terminated&&t();break;case X.Terminated:t();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log("Publication transitioned to state "+this._state),this._stateEventEmitter.emit(this._state),e===X.Terminated&&this.dispose()}}!function(e){e.Initial="Initial",e.Registered="Registered",e.Unregistered="Unregistered",e.Terminated="Terminated"}(Q||(Q={}));class ae{constructor(e,t={}){this.disposed=!1,this._contacts=[],this._retryAfter=void 0,this._state=Q.Initial,this._waiting=!1,this._stateEventEmitter=new g,this._waitingEventEmitter=new g,this.userAgent=e;const s=e.configuration.uri.clone();if(s.user=void 0,this.options=Object.assign(Object.assign(Object.assign({},ae.defaultOptions()),{registrar:s}),ae.stripUndefinedProperties(t)),this.options.extraContactHeaderParams=(this.options.extraContactHeaderParams||[]).slice(),this.options.extraHeaders=(this.options.extraHeaders||[]).slice(),!this.options.registrar)throw new Error("Registrar undefined.");if(this.options.registrar=this.options.registrar.clone(),this.options.regId&&!this.options.instanceId?this.options.instanceId=ae.newUUID():!this.options.regId&&this.options.instanceId&&(this.options.regId=1),this.options.instanceId&&-1===b.parse(this.options.instanceId,"uuid"))throw new Error("Invalid instanceId.");if(this.options.regId&&this.options.regId<0)throw new Error("Invalid regId.");const i=this.options.registrar,r=this.options.params&&this.options.params.fromUri||e.userAgentCore.configuration.aor,n=this.options.params&&this.options.params.toUri||e.configuration.uri,o=this.options.params||{},a=(t.extraHeaders||[]).slice();if(this.request=e.userAgentCore.makeOutgoingRequestMessage(j.REGISTER,i,r,n,o,a,void 0),this.expires=this.options.expires||ae.defaultExpires,this.expires<0)throw new Error("Invalid expires.");this.logger=e.getLogger("sip.Registerer"),this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach(e=>{const t=this.options[e];switch(e){case"registrar":this.logger.log("\xb7 "+e+": "+t);break;default:this.logger.log("\xb7 "+e+": "+JSON.stringify(t))}})),this.id=this.request.callId+this.request.from.parameters.tag,this.userAgent._registerers[this.id]=this}static defaultOptions(){return{expires:ae.defaultExpires,extraContactHeaderParams:[],extraHeaders:[],logConfiguration:!0,instanceId:"",params:{},regId:0,registrar:new m("sip","anonymous","anonymous.invalid")}}static newUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.floor(16*Math.random());return("x"===e?t:t%4+8).toString(16)})}static stripUndefinedProperties(e){return Object.keys(e).reduce((t,s)=>(void 0!==e[s]&&(t[s]=e[s]),t),{})}get contacts(){return this._contacts.slice()}get retryAfter(){return this._retryAfter}get state(){return this._state}get stateChange(){return this._stateEventEmitter}dispose(){return this.disposed?Promise.resolve():(this.disposed=!0,this.logger.log(`Registerer ${this.id} in state ${this.state} is being disposed`),delete this.userAgent._registerers[this.id],new Promise(e=>{const t=()=>{if(!this.waiting&&this._state===Q.Registered)return this.stateChange.addListener(()=>{this.terminated(),e()},{once:!0}),void this.unregister();this.terminated(),e()};this.waiting?this.waitingChange.addListener(()=>{t()},{once:!0}):t()}))}register(e={}){if(this.state===Q.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();const e=new a("REGISTER request already in progress, waiting for final response");return Promise.reject(e)}e.requestOptions&&(this.options=Object.assign(Object.assign({},this.options),e.requestOptions));const t=(this.options.extraHeaders||[]).slice();t.push("Contact: "+this.generateContactHeader(this.expires)),t.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=t,this.waitingToggle(!0);const s=this.userAgent.userAgentCore.register(this.request,{onAccept:t=>{let s;t.message.hasHeader("expires")&&(s=Number(t.message.getHeader("expires"))),this._contacts=t.message.getHeaders("contact");let i,r=this._contacts.length;if(!r)return this.logger.error("No Contact header in response to REGISTER, dropping response."),void this.unregistered();for(;r--;){if(i=t.message.parseHeader("contact",r),!i)throw new Error("Contact undefined");if(i.uri.user===this.userAgent.contact.uri.user&&i.uri.host===this.userAgent.contact.uri.host&&i.uri.port===this.userAgent.contact.uri.port){s=Number(i.getParam("expires"));break}i=void 0}if(void 0===i)return this.logger.error("No Contact header pointing to us, dropping response"),this.unregistered(),void this.waitingToggle(!1);if(void 0===s)return this.logger.error("Contact pointing to us is missing expires parameter, dropping response"),this.unregistered(),void this.waitingToggle(!1);if(i.hasParam("temp-gruu")){const e=i.getParam("temp-gruu");e&&(this.userAgent.contact.tempGruu=b.URIParse(e.replace(/"/g,"")))}if(i.hasParam("pub-gruu")){const e=i.getParam("pub-gruu");e&&(this.userAgent.contact.pubGruu=b.URIParse(e.replace(/"/g,"")))}this.registered(s),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t),this.waitingToggle(!1)},onProgress:t=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)},onRedirect:t=>{this.logger.error("Redirect received. Not supported."),this.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t),this.waitingToggle(!1)},onReject:t=>{if(423===t.message.statusCode)return t.message.hasHeader("min-expires")?(this.expires=Number(t.message.getHeader("min-expires")),this.waitingToggle(!1),void this.register()):(this.logger.error("423 response received for REGISTER without Min-Expires, dropping response"),this.unregistered(),void this.waitingToggle(!1));this.logger.warn("Failed to register, status code "+t.message.statusCode);let s=NaN;if(500===t.message.statusCode||503===t.message.statusCode){const e=t.message.getHeader("retry-after");e&&(s=Number.parseInt(e,void 0))}this._retryAfter=isNaN(s)?void 0:s,this.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t),this._retryAfter=void 0,this.waitingToggle(!1)},onTrying:t=>{e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}});return Promise.resolve(s)}unregister(e={}){if(this.state===Q.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed&&this.state!==Q.Registered)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();const e=new a("REGISTER request already in progress, waiting for final response");return Promise.reject(e)}this._state===Q.Registered||e.all||this.logger.warn("Not currently registered, but sending an unregister anyway.");const t=(e.requestOptions&&e.requestOptions.extraHeaders||[]).slice();this.request.extraHeaders=t,e.all?(t.push("Contact: *"),t.push("Expires: 0")):t.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);const s=this.userAgent.userAgentCore.register(this.request,{onAccept:t=>{this._contacts=t.message.getHeaders("contact"),this.unregistered(),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t),this.waitingToggle(!1)},onProgress:t=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)},onRedirect:t=>{this.logger.error("Unregister redirected. Not currently supported."),this.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t),this.waitingToggle(!1)},onReject:t=>{this.logger.error("Unregister rejected with status code "+t.message.statusCode),this.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t),this.waitingToggle(!1)},onTrying:t=>{e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}});return Promise.resolve(s)}clearTimers(){void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),void 0!==this.registrationExpiredTimer&&(clearTimeout(this.registrationExpiredTimer),this.registrationExpiredTimer=void 0)}generateContactHeader(e){let t=this.userAgent.contact.toString();return this.options.regId&&this.options.instanceId&&(t+=";reg-id="+this.options.regId,t+=';+sip.instance=""'),this.options.extraContactHeaderParams&&this.options.extraContactHeaderParams.forEach(e=>{t+=";"+e}),t+=";expires="+e,t}registered(e){this.clearTimers(),this.registrationTimer=setTimeout(()=>{this.registrationTimer=void 0,this.register()},1e3*e-3e3),this.registrationExpiredTimer=setTimeout(()=>{this.logger.warn("Registration expired"),this.unregistered()},1e3*e),this._state!==Q.Registered&&this.stateTransition(Q.Registered)}unregistered(){this.clearTimers(),this._state!==Q.Unregistered&&this.stateTransition(Q.Unregistered)}terminated(){this.clearTimers(),this._state!==Q.Terminated&&this.stateTransition(Q.Terminated)}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case Q.Initial:e!==Q.Registered&&e!==Q.Unregistered&&e!==Q.Terminated&&t();break;case Q.Registered:e!==Q.Unregistered&&e!==Q.Terminated&&t();break;case Q.Unregistered:e!==Q.Registered&&e!==Q.Terminated&&t();break;case Q.Terminated:t();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log("Registration transitioned to state "+this._state),this._stateEventEmitter.emit(this._state),e===Q.Terminated&&this.dispose()}get waiting(){return this._waiting}get waitingChange(){return this._waitingEventEmitter}waitingToggle(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(this._waiting)}waitingWarning(){let e="An attempt was made to send a REGISTER request while a prior one was still in progress.";e+=" RFC 3261 requires UAs MUST NOT send a new registration until they have received a final response",e+=" from the registrar for the previous one or the previous REGISTER request has timed out.",e+=" Note that if the transport disconnects, you still must wait for the prior request to time out before",e+=" sending a new REGISTER request or alternatively dispose of the current Registerer and create a new Registerer.",this.logger.warn("An attempt was made to send a REGISTER request while a prior one was still in progress. RFC 3261 requires UAs MUST NOT send a new registration until they have received a final response from the registrar for the previous one or the previous REGISTER request has timed out. Note that if the transport disconnects, you still must wait for the prior request to time out before sending a new REGISTER request or alternatively dispose of the current Registerer and create a new Registerer.")}stateError(){let e=`An attempt was made to send a REGISTER request when the Registerer ${this.state===Q.Terminated?"is in 'Terminated' state":"has been disposed"}.`;e+=" The Registerer transitions to 'Terminated' when Registerer.dispose() is called.",e+=" Perhaps you called UserAgent.stop() which dipsoses of all Registerers?",this.logger.error(e)}}ae.defaultExpires=600,function(e){e.Initial="Initial",e.NotifyWait="NotifyWait",e.Pending="Pending",e.Active="Active",e.Terminated="Terminated"}(ee||(ee={})),function(e){e.Initial="Initial",e.NotifyWait="NotifyWait",e.Subscribed="Subscribed",e.Terminated="Terminated"}(te||(te={}));class ce{constructor(e,t={}){this._disposed=!1,this._state=te.Initial,this._logger=e.getLogger("sip.Subscription"),this._stateEventEmitter=new g,this._userAgent=e,this.delegate=t.delegate}dispose(){return this._disposed||(this._disposed=!0,this._stateEventEmitter.removeAllListeners()),Promise.resolve()}get dialog(){return this._dialog}get disposed(){return this._disposed}get state(){return this._state}get stateChange(){return this._stateEventEmitter}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case te.Initial:e!==te.NotifyWait&&e!==te.Terminated&&t();break;case te.NotifyWait:e!==te.Subscribed&&e!==te.Terminated&&t();break;case te.Subscribed:e!==te.Terminated&&t();break;case te.Terminated:t();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(this._state),e===te.Terminated&&this.dispose())}}class he extends ce{constructor(e,t,s,i={}){super(e,i),this.body=void 0,this.logger=e.getLogger("sip.Subscriber"),i.body&&(this.body={body:i.body,contentType:i.contentType?i.contentType:"application/sdp"}),this.targetURI=t,this.event=s,void 0===i.expires?this.expires=3600:"number"!=typeof i.expires?(this.logger.warn('Option "expires" must be a number. Using default of 3600.'),this.expires=3600):this.expires=i.expires,this.extraHeaders=(i.extraHeaders||[]).slice(),this.subscriberRequest=this.initSubscriberRequest(),this.outgoingRequestMessage=this.subscriberRequest.message,this.id=this.outgoingRequestMessage.callId+this.outgoingRequestMessage.from.parameters.tag+this.event,this._userAgent._subscriptions[this.id]=this}dispose(){return this.disposed?Promise.resolve():(this.logger.log(`Subscription ${this.id} in state ${this.state} is being disposed`),delete this._userAgent._subscriptions[this.id],this.retryAfterTimer&&(clearTimeout(this.retryAfterTimer),this.retryAfterTimer=void 0),this.subscriberRequest.dispose(),super.dispose().then(()=>{if(this.state===te.Subscribed){if(!this._dialog)throw new Error("Dialog undefined.");if(this._dialog.subscriptionState===ee.Pending||this._dialog.subscriptionState===ee.Active){const e=this._dialog;return new Promise((t,s)=>{e.delegate={onTerminated:()=>t()},e.unsubscribe()})}}}))}subscribe(e={}){switch(this.subscriberRequest.state){case ee.Initial:this.state===te.Initial&&this.stateTransition(te.NotifyWait),this.subscriberRequest.subscribe().then(e=>{e.success?(e.success.subscription&&(this._dialog=e.success.subscription,this._dialog.delegate={onNotify:e=>this.onNotify(e),onRefresh:e=>this.onRefresh(e),onTerminated:()=>{this.state!==te.Terminated&&this.stateTransition(te.Terminated)}}),this.onNotify(e.success.request)):e.failure&&this.unsubscribe()});break;case ee.NotifyWait:case ee.Pending:break;case ee.Active:if(this._dialog){this._dialog.refresh().delegate={onAccept:e=>this.onAccepted(e),onRedirect:e=>this.unsubscribe(),onReject:e=>this.unsubscribe()}}break;case ee.Terminated:}return Promise.resolve()}unsubscribe(e={}){if(this.disposed)return Promise.resolve();switch(this.subscriberRequest.state){case ee.Initial:case ee.NotifyWait:break;case ee.Pending:case ee.Active:this._dialog&&this._dialog.unsubscribe();break;case ee.Terminated:break;default:throw new Error("Unknown state.")}return this.stateTransition(te.Terminated),Promise.resolve()}_refresh(){return this.subscriberRequest.state===ee.Active?this.subscribe():Promise.resolve()}onAccepted(e){}onNotify(e){if(this.disposed)return void e.accept();if(this.state!==te.Subscribed&&this.stateTransition(te.Subscribed),this.delegate&&this.delegate.onNotify){const t=new B(e);this.delegate.onNotify(t)}else e.accept();const t=e.message.parseHeader("Subscription-State");if(t&&t.state)switch(t.state){case"terminated":if(t.reason)switch(this.logger.log("Terminated subscription with reason "+t.reason),t.reason){case"deactivated":case"timeout":return this.initSubscriberRequest(),void this.subscribe();case"probation":case"giveup":return this.initSubscriberRequest(),void(t.params&&t.params["retry-after"]?this.retryAfterTimer=setTimeout(()=>{this.subscribe()},t.params["retry-after"]):this.subscribe())}this.unsubscribe()}}onRefresh(e){e.delegate={onAccept:e=>this.onAccepted(e)}}initSubscriberRequest(){const e={extraHeaders:this.extraHeaders,body:this.body?k(this.body):void 0};return this.subscriberRequest=new de(this._userAgent.userAgentCore,this.targetURI,this.event,this.expires,e),this.subscriberRequest.delegate={onAccept:e=>this.onAccepted(e)},this.subscriberRequest}}class de{constructor(e,t,s,i,r,n){this.core=e,this.target=t,this.event=s,this.expires=i,this.subscribed=!1,this.logger=e.loggerFactory.getLogger("sip.Subscriber"),this.delegate=n;const o="Allow: "+F.toString(),a=(r&&r.extraHeaders||[]).slice();a.push(o),a.push("Event: "+this.event),a.push("Expires: "+this.expires),a.push("Contact: "+this.core.configuration.contact.toString());const c=r&&r.body;this.message=e.makeOutgoingRequestMessage(j.SUBSCRIBE,this.target,this.core.configuration.aor,this.target,{},a,c)}dispose(){this.request&&(this.request.waitNotifyStop(),this.request.dispose(),this.request=void 0)}get state(){return this.subscription?this.subscription.subscriptionState:this.subscribed?ee.NotifyWait:ee.Initial}subscribe(){return this.subscribed?Promise.reject(new Error("Not in initial state. Did you call subscribe more than once?")):(this.subscribed=!0,new Promise(e=>{if(!this.message)throw new Error("Message undefined.");this.request=this.core.subscribe(this.message,{onAccept:e=>{this.delegate&&this.delegate.onAccept&&this.delegate.onAccept(e)},onNotify:t=>{this.subscription=t.subscription,this.subscription&&(this.subscription.autoRefresh=!0),e({success:t})},onNotifyTimeout:()=>{e({failure:{}})},onRedirect:t=>{e({failure:{response:t}})},onReject:t=>{e({failure:{response:t}})}})}))}}!function(e){e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Disconnected="Disconnected"}(se||(se={})),function(e){e.Started="Started",e.Stopped="Stopped"}(ie||(ie={})),function(e){e[e.error=0]="error",e[e.warn=1]="warn",e[e.log=2]="log",e[e.debug=3]="debug"}(re||(re={}));class le{constructor(e,t,s){this.logger=e,this.category=t,this.label=s}error(e){this.genericLog(re.error,e)}warn(e){this.genericLog(re.warn,e)}log(e){this.genericLog(re.log,e)}debug(e){this.genericLog(re.debug,e)}genericLog(e,t){this.logger.genericLog(e,this.category,this.label,t)}get level(){return this.logger.level}set level(e){this.logger.level=e}}class ge{constructor(){this.builtinEnabled=!0,this._level=re.log,this.loggers={},this.logger=this.getLogger("sip:loggerfactory")}get level(){return this._level}set level(e){e>=0&&e<=3?this._level=e:e>3?this._level=3:re.hasOwnProperty(e)?this._level=e:this.logger.error("invalid 'level' parameter value: "+JSON.stringify(e))}get connector(){return this._connector}set connector(e){e?"function"==typeof e?this._connector=e:this.logger.error("invalid 'connector' parameter value: "+JSON.stringify(e)):this._connector=void 0}getLogger(e,t){if(t&&3===this.level)return new le(this,e,t);if(this.loggers[e])return this.loggers[e];{const t=new le(this,e);return this.loggers[e]=t,t}}genericLog(e,t,s,i){this.level>=e&&this.builtinEnabled&&this.print(e,t,s,i),this.connector&&this.connector(re[e],t,s,i)}print(e,t,s,i){if("string"==typeof i){const e=[new Date,t];s&&e.push(s),i=e.concat(i).join(" | ")}switch(e){case re.error:console.error(i);break;case re.warn:console.warn(i);break;case re.log:console.log(i);break;case re.debug:console.debug(i)}}}class ue{constructor(){this._dataLength=0,this._bufferLength=0,this._state=new Int32Array(4),this._buffer=new ArrayBuffer(68),this._buffer8=new Uint8Array(this._buffer,0,68),this._buffer32=new Uint32Array(this._buffer,0,17),this.start()}static hashStr(e,t=!1){return this.onePassHasher.start().appendStr(e).end(t)}static hashAsciiStr(e,t=!1){return this.onePassHasher.start().appendAsciiStr(e).end(t)}static _hex(e){const t=ue.hexChars,s=ue.hexOut;let i,r,n,o;for(o=0;o<4;o+=1)for(r=8*o,i=e[o],n=0;n<8;n+=2)s[r+1+n]=t.charAt(15&i),i>>>=4,s[r+0+n]=t.charAt(15&i),i>>>=4;return s.join("")}static _md5cycle(e,t){let s=e[0],i=e[1],r=e[2],n=e[3];s+=(i&r|~i&n)+t[0]-680876936|0,s=(s<<7|s>>>25)+i|0,n+=(s&i|~s&r)+t[1]-389564586|0,n=(n<<12|n>>>20)+s|0,r+=(n&s|~n&i)+t[2]+606105819|0,r=(r<<17|r>>>15)+n|0,i+=(r&n|~r&s)+t[3]-1044525330|0,i=(i<<22|i>>>10)+r|0,s+=(i&r|~i&n)+t[4]-176418897|0,s=(s<<7|s>>>25)+i|0,n+=(s&i|~s&r)+t[5]+1200080426|0,n=(n<<12|n>>>20)+s|0,r+=(n&s|~n&i)+t[6]-1473231341|0,r=(r<<17|r>>>15)+n|0,i+=(r&n|~r&s)+t[7]-45705983|0,i=(i<<22|i>>>10)+r|0,s+=(i&r|~i&n)+t[8]+1770035416|0,s=(s<<7|s>>>25)+i|0,n+=(s&i|~s&r)+t[9]-1958414417|0,n=(n<<12|n>>>20)+s|0,r+=(n&s|~n&i)+t[10]-42063|0,r=(r<<17|r>>>15)+n|0,i+=(r&n|~r&s)+t[11]-1990404162|0,i=(i<<22|i>>>10)+r|0,s+=(i&r|~i&n)+t[12]+1804603682|0,s=(s<<7|s>>>25)+i|0,n+=(s&i|~s&r)+t[13]-40341101|0,n=(n<<12|n>>>20)+s|0,r+=(n&s|~n&i)+t[14]-1502002290|0,r=(r<<17|r>>>15)+n|0,i+=(r&n|~r&s)+t[15]+1236535329|0,i=(i<<22|i>>>10)+r|0,s+=(i&n|r&~n)+t[1]-165796510|0,s=(s<<5|s>>>27)+i|0,n+=(s&r|i&~r)+t[6]-1069501632|0,n=(n<<9|n>>>23)+s|0,r+=(n&i|s&~i)+t[11]+643717713|0,r=(r<<14|r>>>18)+n|0,i+=(r&s|n&~s)+t[0]-373897302|0,i=(i<<20|i>>>12)+r|0,s+=(i&n|r&~n)+t[5]-701558691|0,s=(s<<5|s>>>27)+i|0,n+=(s&r|i&~r)+t[10]+38016083|0,n=(n<<9|n>>>23)+s|0,r+=(n&i|s&~i)+t[15]-660478335|0,r=(r<<14|r>>>18)+n|0,i+=(r&s|n&~s)+t[4]-405537848|0,i=(i<<20|i>>>12)+r|0,s+=(i&n|r&~n)+t[9]+568446438|0,s=(s<<5|s>>>27)+i|0,n+=(s&r|i&~r)+t[14]-1019803690|0,n=(n<<9|n>>>23)+s|0,r+=(n&i|s&~i)+t[3]-187363961|0,r=(r<<14|r>>>18)+n|0,i+=(r&s|n&~s)+t[8]+1163531501|0,i=(i<<20|i>>>12)+r|0,s+=(i&n|r&~n)+t[13]-1444681467|0,s=(s<<5|s>>>27)+i|0,n+=(s&r|i&~r)+t[2]-51403784|0,n=(n<<9|n>>>23)+s|0,r+=(n&i|s&~i)+t[7]+1735328473|0,r=(r<<14|r>>>18)+n|0,i+=(r&s|n&~s)+t[12]-1926607734|0,i=(i<<20|i>>>12)+r|0,s+=(i^r^n)+t[5]-378558|0,s=(s<<4|s>>>28)+i|0,n+=(s^i^r)+t[8]-2022574463|0,n=(n<<11|n>>>21)+s|0,r+=(n^s^i)+t[11]+1839030562|0,r=(r<<16|r>>>16)+n|0,i+=(r^n^s)+t[14]-35309556|0,i=(i<<23|i>>>9)+r|0,s+=(i^r^n)+t[1]-1530992060|0,s=(s<<4|s>>>28)+i|0,n+=(s^i^r)+t[4]+1272893353|0,n=(n<<11|n>>>21)+s|0,r+=(n^s^i)+t[7]-155497632|0,r=(r<<16|r>>>16)+n|0,i+=(r^n^s)+t[10]-1094730640|0,i=(i<<23|i>>>9)+r|0,s+=(i^r^n)+t[13]+681279174|0,s=(s<<4|s>>>28)+i|0,n+=(s^i^r)+t[0]-358537222|0,n=(n<<11|n>>>21)+s|0,r+=(n^s^i)+t[3]-722521979|0,r=(r<<16|r>>>16)+n|0,i+=(r^n^s)+t[6]+76029189|0,i=(i<<23|i>>>9)+r|0,s+=(i^r^n)+t[9]-640364487|0,s=(s<<4|s>>>28)+i|0,n+=(s^i^r)+t[12]-421815835|0,n=(n<<11|n>>>21)+s|0,r+=(n^s^i)+t[15]+530742520|0,r=(r<<16|r>>>16)+n|0,i+=(r^n^s)+t[2]-995338651|0,i=(i<<23|i>>>9)+r|0,s+=(r^(i|~n))+t[0]-198630844|0,s=(s<<6|s>>>26)+i|0,n+=(i^(s|~r))+t[7]+1126891415|0,n=(n<<10|n>>>22)+s|0,r+=(s^(n|~i))+t[14]-1416354905|0,r=(r<<15|r>>>17)+n|0,i+=(n^(r|~s))+t[5]-57434055|0,i=(i<<21|i>>>11)+r|0,s+=(r^(i|~n))+t[12]+1700485571|0,s=(s<<6|s>>>26)+i|0,n+=(i^(s|~r))+t[3]-1894986606|0,n=(n<<10|n>>>22)+s|0,r+=(s^(n|~i))+t[10]-1051523|0,r=(r<<15|r>>>17)+n|0,i+=(n^(r|~s))+t[1]-2054922799|0,i=(i<<21|i>>>11)+r|0,s+=(r^(i|~n))+t[8]+1873313359|0,s=(s<<6|s>>>26)+i|0,n+=(i^(s|~r))+t[15]-30611744|0,n=(n<<10|n>>>22)+s|0,r+=(s^(n|~i))+t[6]-1560198380|0,r=(r<<15|r>>>17)+n|0,i+=(n^(r|~s))+t[13]+1309151649|0,i=(i<<21|i>>>11)+r|0,s+=(r^(i|~n))+t[4]-145523070|0,s=(s<<6|s>>>26)+i|0,n+=(i^(s|~r))+t[11]-1120210379|0,n=(n<<10|n>>>22)+s|0,r+=(s^(n|~i))+t[2]+718787259|0,r=(r<<15|r>>>17)+n|0,i+=(n^(r|~s))+t[9]-343485551|0,i=(i<<21|i>>>11)+r|0,e[0]=s+e[0]|0,e[1]=i+e[1]|0,e[2]=r+e[2]|0,e[3]=n+e[3]|0}start(){return this._dataLength=0,this._bufferLength=0,this._state.set(ue.stateIdentity),this}appendStr(e){const t=this._buffer8,s=this._buffer32;let i,r,n=this._bufferLength;for(r=0;r>>6),t[n++]=63&i|128;else if(i<55296||i>56319)t[n++]=224+(i>>>12),t[n++]=i>>>6&63|128,t[n++]=63&i|128;else{if(i=1024*(i-55296)+(e.charCodeAt(++r)-56320)+65536,i>1114111)throw new Error("Unicode standard supports code points up to U+10FFFF");t[n++]=240+(i>>>18),t[n++]=i>>>12&63|128,t[n++]=i>>>6&63|128,t[n++]=63&i|128}n>=64&&(this._dataLength+=64,ue._md5cycle(this._state,s),n-=64,s[0]=s[16])}return this._bufferLength=n,this}appendAsciiStr(e){const t=this._buffer8,s=this._buffer32;let i,r=this._bufferLength,n=0;for(;;){for(i=Math.min(e.length-n,64-r);i--;)t[r++]=e.charCodeAt(n++);if(r<64)break;this._dataLength+=64,ue._md5cycle(this._state,s),r=0}return this._bufferLength=r,this}appendByteArray(e){const t=this._buffer8,s=this._buffer32;let i,r=this._bufferLength,n=0;for(;;){for(i=Math.min(e.length-n,64-r);i--;)t[r++]=e[n++];if(r<64)break;this._dataLength+=64,ue._md5cycle(this._state,s),r=0}return this._bufferLength=r,this}getState(){const e=this._state;return{buffer:String.fromCharCode.apply(null,this._buffer8),buflen:this._bufferLength,length:this._dataLength,state:[e[0],e[1],e[2],e[3]]}}setState(e){const t=e.buffer,s=e.state,i=this._state;let r;for(this._dataLength=e.length,this._bufferLength=e.buflen,i[0]=s[0],i[1]=s[1],i[2]=s[2],i[3]=s[3],r=0;r>2);let n;if(this._dataLength+=t,s[t]=128,s[t+1]=s[t+2]=s[t+3]=0,i.set(ue.buffer32Identity.subarray(r),r),t>55&&(ue._md5cycle(this._state,i),i.set(ue.buffer32Identity)),n=8*this._dataLength,n<=4294967295)i[14]=n;else{const e=n.toString(16).match(/(.*?)(.{0,8})$/);if(null===e)return;const t=parseInt(e[2],16),s=parseInt(e[1],16)||0;i[14]=t,i[15]=s}return ue._md5cycle(this._state,i),e?this._state:ue._hex(this._state)}}function pe(e){return ue.hashStr(e)}ue.stateIdentity=new Int32Array([1732584193,-271733879,-1732584194,271733878]),ue.buffer32Identity=new Int32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),ue.hexChars="0123456789abcdef",ue.hexOut=[],ue.onePassHasher=new ue,"5d41402abc4b2a76b9719d911017c592"!==ue.hashStr("hello")&&console.error("Md5 self test failed.");class fe{constructor(e,t,s,i){this.logger=e.getLogger("sipjs.digestauthentication"),this.username=s,this.password=i,this.ha1=t,this.nc=0,this.ncHex="00000000"}authenticate(e,t,s){if(this.algorithm=t.algorithm,this.realm=t.realm,this.nonce=t.nonce,this.opaque=t.opaque,this.stale=t.stale,this.algorithm){if("MD5"!==this.algorithm)return this.logger.warn("challenge with Digest algorithm different than 'MD5', authentication aborted"),!1}else this.algorithm="MD5";if(!this.realm)return this.logger.warn("challenge without Digest realm, authentication aborted"),!1;if(!this.nonce)return this.logger.warn("challenge without Digest nonce, authentication aborted"),!1;if(t.qop)if(t.qop.indexOf("auth")>-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=R(12),this.nc+=1,this.updateNcHex(),4294967296===this.nc&&(this.nc=1,this.ncHex="00000001"),this.calculateResponse(s),!0}toString(){const 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(", ")}updateNcHex(){const e=Number(this.nc).toString(16);this.ncHex="00000000".substr(0,8-e.length)+e}calculateResponse(e){let t,s;t=this.ha1,""!==t&&void 0!==t||(t=pe(this.username+":"+this.realm+":"+this.password)),"auth"===this.qop?(s=pe(this.method+":"+this.uri),this.response=pe(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth:"+s)):"auth-int"===this.qop?(s=pe(this.method+":"+this.uri+":"+pe(e||"")),this.response=pe(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth-int:"+s)):void 0===this.qop&&(s=pe(this.method+":"+this.uri),this.response=pe(t+":"+this.nonce+":"+s))}}function me(e,t){if(t.statusCode<100||t.statusCode>699)throw new TypeError("Invalid statusCode: "+t.statusCode);const s=t.reasonPhrase?t.reasonPhrase:y(t.statusCode);let i="SIP/2.0 "+t.statusCode+" "+s+"\r\n";t.statusCode>=100&&t.statusCode,t.statusCode;const r="From: "+e.getHeader("From")+"\r\n",n="Call-ID: "+e.callId+"\r\n",o="CSeq: "+e.cseq+" "+e.method+"\r\n",a=e.getHeaders("via").reduce((e,t)=>e+"Via: "+t+"\r\n","");let c="To: "+e.getHeader("to");if(t.statusCode>100&&!e.parseHeader("to").hasParam("tag")){let e=t.toTag;e||(e=E()),c+=";tag="+e}c+="\r\n";let h="";t.supported&&(h="Supported: "+t.supported.join(", ")+"\r\n");let d="";t.userAgent&&(d="User-Agent: "+t.userAgent+"\r\n");let l="";return t.extraHeaders&&(l=t.extraHeaders.reduce((e,t)=>e+t.trim()+"\r\n","")),i+=a,i+=r,i+=c,i+=o,i+=n,i+=h,i+=d,i+=l,t.body?(i+="Content-Type: "+t.body.contentType+"\r\n",i+="Content-Length: "+I(t.body.content)+"\r\n\r\n",i+=t.body.content):i+="Content-Length: 0\r\n\r\n",{message:i}}class ve extends n{constructor(e){super(e||"Unspecified transport error.")}}class we{constructor(e,t,s,i,r){this._transport=e,this._user=t,this._id=s,this._state=i,this.listeners=new Array,this.logger=t.loggerFactory.getLogger(r,s),this.logger.debug(`Constructing ${this.typeToString()} with id ${this.id}.`)}dispose(){this.logger.debug(`Destroyed ${this.typeToString()} with id ${this.id}.`)}get id(){return this._id}get kind(){throw new Error("Invalid kind.")}get state(){return this._state}get transport(){return this._transport}addStateChangeListener(e,t){const s=()=>{this.removeStateChangeListener(s),e()};!0===(null==t?void 0:t.once)?this.listeners.push(s):this.listeners.push(e)}notifyStateChangeListeners(){this.listeners.slice().forEach(e=>e())}removeStateChangeListener(e){this.listeners=this.listeners.filter(t=>t!==e)}logTransportError(e,t){this.logger.error(e.message),this.logger.error(`Transport error occurred in ${this.typeToString()} with id ${this.id}.`),this.logger.error(t)}send(e){return this.transport.send(e).catch(e=>{if(e instanceof ve)throw this.onTransportError(e),e;let t;throw t=e&&"string"==typeof e.message?new ve(e.message):new ve,this.onTransportError(t),t})}setState(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.notifyStateChangeListeners()}typeToString(){return"UnknownType"}}class be extends we{constructor(e,t,s,i,r){super(t,s,be.makeId(e),i,r),this._request=e,this.user=s,e.setViaHeader(this.id,t.protocol)}static makeId(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())}get request(){return this._request}onRequestTimeout(){this.user.onRequestTimeout&&this.user.onRequestTimeout()}}!function(e){e.Accepted="Accepted",e.Calling="Calling",e.Completed="Completed",e.Confirmed="Confirmed",e.Proceeding="Proceeding",e.Terminated="Terminated",e.Trying="Trying"}(ne||(ne={}));class Te extends be{constructor(e,t,s){super(e,t,s,ne.Trying,"sip.transaction.nict"),this.F=setTimeout(()=>this.timerF(),U.TIMER_F),this.send(e.toString()).catch(e=>{this.logTransportError(e,"Failed to send initial outgoing request.")})}dispose(){this.F&&(clearTimeout(this.F),this.F=void 0),this.K&&(clearTimeout(this.K),this.K=void 0),super.dispose()}get kind(){return"nict"}receiveResponse(e){const t=e.statusCode;if(!t||t<100||t>699)throw new Error("Invalid status code "+t);switch(this.state){case ne.Trying:if(t>=100&&t<=199)return this.stateTransition(ne.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=699)return this.stateTransition(ne.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case ne.Proceeding:if(t>=100&&t<=199&&this.user.receiveResponse)return this.user.receiveResponse(e);if(t>=200&&t<=699)return this.stateTransition(ne.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case ne.Completed:case ne.Terminated:return;default:throw new Error("Invalid state "+this.state)}const s=`Non-INVITE client transaction received unexpected ${t} response while in state ${this.state}.`;this.logger.warn(s)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(ne.Terminated,!0)}typeToString(){return"non-INVITE client transaction"}stateTransition(e,t=!1){const s=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case ne.Trying:s();break;case ne.Proceeding:this.state!==ne.Trying&&s();break;case ne.Completed:this.state!==ne.Trying&&this.state!==ne.Proceeding&&s();break;case ne.Terminated:this.state!==ne.Trying&&this.state!==ne.Proceeding&&this.state!==ne.Completed&&(t||s());break;default:s()}e===ne.Completed&&(this.F&&(clearTimeout(this.F),this.F=void 0),this.K=setTimeout(()=>this.timerK(),U.TIMER_K)),e===ne.Terminated&&this.dispose(),this.setState(e)}timerF(){this.logger.debug(`Timer F expired for non-INVITE client transaction ${this.id}.`),this.state!==ne.Trying&&this.state!==ne.Proceeding||(this.onRequestTimeout(),this.stateTransition(ne.Terminated))}timerK(){this.state===ne.Completed&&this.stateTransition(ne.Terminated)}}class Se extends we{constructor(e,t,s,i,r){super(t,s,e.viaBranch,i,r),this._request=e,this.user=s}get request(){return this._request}}class Re extends Se{constructor(e,t,s){super(e,t,s,ne.Proceeding,"sip.transaction.ist")}dispose(){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),super.dispose()}get kind(){return"ist"}receiveRequest(e){switch(this.state){case ne.Proceeding:if(e.method===j.INVITE)return void(this.lastProvisionalResponse&&this.send(this.lastProvisionalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")}));break;case ne.Accepted:if(e.method===j.INVITE)return;break;case ne.Completed:if(e.method===j.INVITE){if(!this.lastFinalResponse)throw new Error("Last final response undefined.");return void this.send(this.lastFinalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of final response.")})}if(e.method===j.ACK)return void this.stateTransition(ne.Confirmed);break;case ne.Confirmed:case ne.Terminated:if(e.method===j.INVITE||e.method===j.ACK)return;break;default:throw new Error("Invalid state "+this.state)}const t=`INVITE server transaction received unexpected ${e.method} request while in state ${this.state}.`;this.logger.warn(t)}receiveResponse(e,t){if(e<100||e>699)throw new Error("Invalid status code "+e);switch(this.state){case ne.Proceeding:if(e>=100&&e<=199)return this.lastProvisionalResponse=t,e>100&&this.startProgressExtensionTimer(),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 1xx response.")});if(e>=200&&e<=299)return this.lastFinalResponse=t,this.stateTransition(ne.Accepted),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")});if(e>=300&&e<=699)return this.lastFinalResponse=t,this.stateTransition(ne.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send non-2xx final response.")});break;case ne.Accepted:if(e>=200&&e<=299)return void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")});break;case ne.Completed:case ne.Confirmed:case ne.Terminated:break;default:throw new Error("Invalid state "+this.state)}const s=`INVITE server transaction received unexpected ${e} response from TU while in state ${this.state}.`;throw this.logger.error(s),new Error(s)}retransmitAcceptedResponse(){this.state===ne.Accepted&&this.lastFinalResponse&&this.send(this.lastFinalResponse).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")})}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e)}typeToString(){return"INVITE server transaction"}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case ne.Proceeding:t();break;case ne.Accepted:case ne.Completed:this.state!==ne.Proceeding&&t();break;case ne.Confirmed:this.state!==ne.Completed&&t();break;case ne.Terminated:this.state!==ne.Accepted&&this.state!==ne.Completed&&this.state!==ne.Confirmed&&t();break;default:t()}this.stopProgressExtensionTimer(),e===ne.Accepted&&(this.L=setTimeout(()=>this.timerL(),U.TIMER_L)),e===ne.Completed&&(this.H=setTimeout(()=>this.timerH(),U.TIMER_H)),e===ne.Confirmed&&(this.I=setTimeout(()=>this.timerI(),U.TIMER_I)),e===ne.Terminated&&this.dispose(),this.setState(e)}startProgressExtensionTimer(){void 0===this.progressExtensionTimer&&(this.progressExtensionTimer=setInterval(()=>{if(this.logger.debug(`Progress extension timer expired for INVITE server transaction ${this.id}.`),!this.lastProvisionalResponse)throw new Error("Last provisional response undefined.");this.send(this.lastProvisionalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")})},U.PROVISIONAL_RESPONSE_INTERVAL))}stopProgressExtensionTimer(){void 0!==this.progressExtensionTimer&&(clearInterval(this.progressExtensionTimer),this.progressExtensionTimer=void 0)}timerG(){}timerH(){this.logger.debug(`Timer H expired for INVITE server transaction ${this.id}.`),this.state===ne.Completed&&(this.logger.warn("ACK to negative final response was never received, terminating transaction."),this.stateTransition(ne.Terminated))}timerI(){this.logger.debug(`Timer I expired for INVITE server transaction ${this.id}.`),this.stateTransition(ne.Terminated)}timerL(){this.logger.debug(`Timer L expired for INVITE server transaction ${this.id}.`),this.state===ne.Accepted&&this.stateTransition(ne.Terminated)}}class ye{constructor(e,t){this.core=e,this.dialogState=t,this.core.dialogs.set(this.id,this)}static initialDialogStateForUserAgentClient(e,t){const s=t.getHeaders("record-route").reverse(),i=t.parseHeader("contact");if(!i)throw new Error("Contact undefined.");if(!(i instanceof f))throw new Error("Contact not instance of NameAddrHeader.");const r=i.uri,n=e.cseq,o=e.callId,a=e.fromTag,c=t.toTag;if(!o)throw new Error("Call id undefined.");if(!a)throw new Error("From tag undefined.");if(!c)throw new Error("To tag undefined.");if(!e.from)throw new Error("From undefined.");if(!e.to)throw new Error("To undefined.");const h=e.from.uri,d=e.to.uri;if(!t.statusCode)throw new Error("Incoming response status code undefined.");return{id:o+a+c,early:t.statusCode<200,callId:o,localTag:a,remoteTag:c,localSequenceNumber:n,remoteSequenceNumber:void 0,localURI:h,remoteURI:d,remoteTarget:r,routeSet:s,secure:!1}}static initialDialogStateForUserAgentServer(e,t,s=!1){const i=e.getHeaders("record-route"),r=e.parseHeader("contact");if(!r)throw new Error("Contact undefined.");if(!(r instanceof f))throw new Error("Contact not instance of NameAddrHeader.");const n=r.uri,o=e.cseq,a=e.callId,c=t,h=e.fromTag,d=e.from.uri;return{id:a+c+h,early:s,callId:a,localTag:c,remoteTag:h,localSequenceNumber:void 0,remoteSequenceNumber:o,localURI:e.to.uri,remoteURI:d,remoteTarget:n,routeSet:i,secure:!1}}dispose(){this.core.dialogs.delete(this.id)}get id(){return this.dialogState.id}get early(){return this.dialogState.early}get callId(){return this.dialogState.callId}get localTag(){return this.dialogState.localTag}get remoteTag(){return this.dialogState.remoteTag}get localSequenceNumber(){return this.dialogState.localSequenceNumber}get remoteSequenceNumber(){return this.dialogState.remoteSequenceNumber}get localURI(){return this.dialogState.localURI}get remoteURI(){return this.dialogState.remoteURI}get remoteTarget(){return this.dialogState.remoteTarget}get routeSet(){return this.dialogState.routeSet}get secure(){return this.dialogState.secure}get userAgentCore(){return this.core}confirm(){this.dialogState.early=!1}receiveRequest(e){if(e.method!==j.ACK){if(this.remoteSequenceNumber){if(e.cseq<=this.remoteSequenceNumber)throw new Error("Out of sequence in dialog request. Did you forget to call sequenceGuard()?");this.dialogState.remoteSequenceNumber=e.cseq}this.remoteSequenceNumber||(this.dialogState.remoteSequenceNumber=e.cseq)}}recomputeRouteSet(e){this.dialogState.routeSet=e.getHeaders("record-route").reverse()}createOutgoingRequestMessage(e,t){const s=this.remoteURI,i=this.remoteTag,r=this.localURI,n=this.localTag,o=this.callId;let a;a=t&&t.cseq?t.cseq:this.dialogState.localSequenceNumber?this.dialogState.localSequenceNumber+=1:this.dialogState.localSequenceNumber=1;const c=this.remoteTarget,h=this.routeSet,d=t&&t.extraHeaders,l=t&&t.body;return this.userAgentCore.makeOutgoingRequestMessage(e,c,r,s,{callId:o,cseq:a,fromTag:n,toTag:i,routeSet:h},d,l)}incrementLocalSequenceNumber(){if(!this.dialogState.localSequenceNumber)throw new Error("Local sequence number undefined.");this.dialogState.localSequenceNumber+=1}sequenceGuard(e){return e.method===j.ACK||(!(this.remoteSequenceNumber&&e.cseq<=this.remoteSequenceNumber)||(this.core.replyStateless(e,{statusCode:500}),!1))}}class Ee extends be{constructor(e,t,s){super(e,t,s,ne.Calling,"sip.transaction.ict"),this.ackRetransmissionCache=new Map,this.B=setTimeout(()=>this.timerB(),U.TIMER_B),this.send(e.toString()).catch(e=>{this.logTransportError(e,"Failed to send initial outgoing request.")})}dispose(){this.B&&(clearTimeout(this.B),this.B=void 0),this.D&&(clearTimeout(this.D),this.D=void 0),this.M&&(clearTimeout(this.M),this.M=void 0),super.dispose()}get kind(){return"ict"}ackResponse(e){const t=e.toTag;if(!t)throw new Error("To tag undefined.");const s="z9hG4bK"+Math.floor(1e7*Math.random());e.setViaHeader(s,this.transport.protocol),this.ackRetransmissionCache.set(t,e),this.send(e.toString()).catch(e=>{this.logTransportError(e,"Failed to send ACK to 2xx response.")})}receiveResponse(e){const t=e.statusCode;if(!t||t<100||t>699)throw new Error("Invalid status code "+t);switch(this.state){case ne.Calling:if(t>=100&&t<=199)return this.stateTransition(ne.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(ne.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(ne.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case ne.Proceeding:if(t>=100&&t<=199)return void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(ne.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(ne.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case ne.Accepted:if(t>=200&&t<=299){if(!this.ackRetransmissionCache.has(e.toTag))return this.ackRetransmissionCache.set(e.toTag,void 0),void(this.user.receiveResponse&&this.user.receiveResponse(e));const t=this.ackRetransmissionCache.get(e.toTag);return t?void this.send(t.toString()).catch(e=>{this.logTransportError(e,"Failed to send retransmission of ACK to 2xx response.")}):void 0}break;case ne.Completed:if(t>=300&&t<=699)return void this.ack(e);break;case ne.Terminated:break;default:throw new Error("Invalid state "+this.state)}const s=`Received unexpected ${t} response while in state ${this.state}.`;this.logger.warn(s)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(ne.Terminated,!0)}typeToString(){return"INVITE client transaction"}ack(e){const t=this.request.ruri,s=this.request.callId,i=this.request.cseq,r=this.request.getHeader("from"),n=e.getHeader("to"),o=this.request.getHeader("via"),a=this.request.getHeader("route");if(!r)throw new Error("From undefined.");if(!n)throw new Error("To undefined.");if(!o)throw new Error("Via undefined.");let c=`ACK ${t} SIP/2.0\r\n`;a&&(c+=`Route: ${a}\r\n`),c+=`Via: ${o}\r\n`,c+=`To: ${n}\r\n`,c+=`From: ${r}\r\n`,c+=`Call-ID: ${s}\r\n`,c+=`CSeq: ${i} ACK\r\n`,c+="Max-Forwards: 70\r\n",c+="Content-Length: 0\r\n\r\n",this.send(c).catch(e=>{this.logTransportError(e,"Failed to send ACK to non-2xx response.")})}stateTransition(e,t=!1){const s=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case ne.Calling:s();break;case ne.Proceeding:this.state!==ne.Calling&&s();break;case ne.Accepted:case ne.Completed:this.state!==ne.Calling&&this.state!==ne.Proceeding&&s();break;case ne.Terminated:this.state!==ne.Calling&&this.state!==ne.Accepted&&this.state!==ne.Completed&&(t||s());break;default:s()}this.B&&(clearTimeout(this.B),this.B=void 0),ne.Proceeding,e===ne.Completed&&(this.D=setTimeout(()=>this.timerD(),U.TIMER_D)),e===ne.Accepted&&(this.M=setTimeout(()=>this.timerM(),U.TIMER_M)),e===ne.Terminated&&this.dispose(),this.setState(e)}timerA(){}timerB(){this.logger.debug(`Timer B expired for INVITE client transaction ${this.id}.`),this.state===ne.Calling&&(this.onRequestTimeout(),this.stateTransition(ne.Terminated))}timerD(){this.logger.debug(`Timer D expired for INVITE client transaction ${this.id}.`),this.state===ne.Completed&&this.stateTransition(ne.Terminated)}timerM(){this.logger.debug(`Timer M expired for INVITE client transaction ${this.id}.`),this.state===ne.Accepted&&this.stateTransition(ne.Terminated)}}class $e{constructor(e,t,s,i){this.transactionConstructor=e,this.core=t,this.message=s,this.delegate=i,this.challenged=!1,this.stale=!1,this.logger=this.loggerFactory.getLogger("sip.user-agent-client"),this.init()}dispose(){this.transaction.dispose()}get loggerFactory(){return this.core.loggerFactory}get transaction(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction}cancel(e,t={}){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.");const s=this.core.makeOutgoingRequestMessage(j.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},t.extraHeaders);return s.branch=this.message.branch,this.message.headers.Route&&(s.headers.Route=this.message.headers.Route),e&&s.setHeader("Reason",e),this.transaction.state===ne.Proceeding?new $e(Te,this.core,s):this.transaction.addStateChangeListener(()=>{this.transaction&&this.transaction.state===ne.Proceeding&&new $e(Te,this.core,s)},{once:!0}),s}authenticationGuard(e,t){const s=e.statusCode;if(!s)throw new Error("Response status code undefined.");if(401!==s&&407!==s)return!0;let i,r;if(401===s?(i=e.parseHeader("www-authenticate"),r="authorization"):(i=e.parseHeader("proxy-authenticate"),r="proxy-authorization"),!i)return this.logger.warn(s+" with wrong or missing challenge, cannot authenticate"),!0;if(this.challenged&&(this.stale||!0!==i.stale))return this.logger.warn(s+" 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,i))return!0;this.challenged=!0,i.stale&&(this.stale=!0);let n=this.message.cseq+=1;return t&&t.localSequenceNumber&&(t.incrementLocalSequenceNumber(),n=this.message.cseq=t.localSequenceNumber),this.message.setHeader("cseq",n+" "+this.message.method),this.message.setHeader(r,this.credentials.toString()),this.init(),!1}onRequestTimeout(){this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout.");const e=new D;e.statusCode=408,e.reasonPhrase="Request Timeout",this.receiveResponse(e)}onTransportError(e){this.logger.error(e.message),this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable.");const t=new D;t.statusCode=503,t.reasonPhrase="Service Unavailable",this.receiveResponse(t)}receiveResponse(e){if(!this.authenticationGuard(e))return;const 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)}}init(){const e={loggerFactory:this.loggerFactory,onRequestTimeout:()=>this.onRequestTimeout(),onStateChange:e=>{e===ne.Terminated&&(this.core.userAgentClients.delete(s),t===this._transaction&&this.dispose())},onTransportError:e=>this.onTransportError(e),receiveResponse:e=>this.receiveResponse(e)},t=new this.transactionConstructor(this.message,this.core.transport,e);this._transaction=t;const s=t.id+t.request.method;this.core.userAgentClients.set(s,this)}}class Ie extends $e{constructor(e,t,s){const i=e.createOutgoingRequestMessage(j.BYE,s);super(Te,e.userAgentCore,i,t),e.dispose()}}class Ce extends Se{constructor(e,t,s){super(e,t,s,ne.Trying,"sip.transaction.nist")}dispose(){this.J&&(clearTimeout(this.J),this.J=void 0),super.dispose()}get kind(){return"nist"}receiveRequest(e){switch(this.state){case ne.Trying:break;case ne.Proceeding:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")});break;case ne.Completed:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of final response.")});break;case ne.Terminated:break;default:throw new Error("Invalid state "+this.state)}}receiveResponse(e,t){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 ne.Trying:if(this.lastResponse=t,e>=100&&e<200)return this.stateTransition(ne.Proceeding),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send provisional response.")});if(e>=200&&e<=699)return this.stateTransition(ne.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send final response.")});break;case ne.Proceeding:if(this.lastResponse=t,e>=200&&e<=699)return this.stateTransition(ne.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send final response.")});break;case ne.Completed:return;case ne.Terminated:break;default:throw new Error("Invalid state "+this.state)}const s=`Non-INVITE server transaction received unexpected ${e} response from TU while in state ${this.state}.`;throw this.logger.error(s),new Error(s)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(ne.Terminated,!0)}typeToString(){return"non-INVITE server transaction"}stateTransition(e,t=!1){const s=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case ne.Trying:s();break;case ne.Proceeding:this.state!==ne.Trying&&s();break;case ne.Completed:this.state!==ne.Trying&&this.state!==ne.Proceeding&&s();break;case ne.Terminated:this.state!==ne.Proceeding&&this.state!==ne.Completed&&(t||s());break;default:s()}e===ne.Completed&&(this.J=setTimeout(()=>this.timerJ(),U.TIMER_J)),e===ne.Terminated&&this.dispose(),this.setState(e)}timerJ(){this.logger.debug(`Timer J expired for NON-INVITE server transaction ${this.id}.`),this.state===ne.Completed&&this.stateTransition(ne.Terminated)}}class Ae{constructor(e,t,s,i){this.transactionConstructor=e,this.core=t,this.message=s,this.delegate=i,this.logger=this.loggerFactory.getLogger("sip.user-agent-server"),this.toTag=s.toTag?s.toTag:E(),this.init()}dispose(){this.transaction.dispose()}get loggerFactory(){return this.core.loggerFactory}get transaction(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction}accept(e={statusCode:200}){if(!this.acceptable)throw new M(`${this.message.method} not acceptable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<200||t>299)throw new TypeError("Invalid statusCode: "+t);return this.reply(e)}progress(e={statusCode:180}){if(!this.progressable)throw new M(`${this.message.method} not progressable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<101||t>199)throw new TypeError("Invalid statusCode: "+t);return this.reply(e)}redirect(e,t={statusCode:302}){if(!this.redirectable)throw new M(`${this.message.method} not redirectable in state ${this.transaction.state}.`);const s=t.statusCode;if(s<300||s>399)throw new TypeError("Invalid statusCode: "+s);const i=new Array;e.forEach(e=>i.push("Contact: "+e.toString())),t.extraHeaders=(t.extraHeaders||[]).concat(i);return this.reply(t)}reject(e={statusCode:480}){if(!this.rejectable)throw new M(`${this.message.method} not rejectable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<400||t>699)throw new TypeError("Invalid statusCode: "+t);return this.reply(e)}trying(e){if(!this.tryingable)throw new M(`${this.message.method} not tryingable in state ${this.transaction.state}.`);return this.reply({statusCode:100})}receiveCancel(e){this.delegate&&this.delegate.onCancel&&this.delegate.onCancel(e)}get acceptable(){if(this.transaction instanceof Re)return this.transaction.state===ne.Proceeding||this.transaction.state===ne.Accepted;if(this.transaction instanceof Ce)return this.transaction.state===ne.Trying||this.transaction.state===ne.Proceeding;throw new Error("Unknown transaction type.")}get progressable(){if(this.transaction instanceof Re)return this.transaction.state===ne.Proceeding;if(this.transaction instanceof Ce)return!1;throw new Error("Unknown transaction type.")}get redirectable(){if(this.transaction instanceof Re)return this.transaction.state===ne.Proceeding;if(this.transaction instanceof Ce)return this.transaction.state===ne.Trying||this.transaction.state===ne.Proceeding;throw new Error("Unknown transaction type.")}get rejectable(){if(this.transaction instanceof Re)return this.transaction.state===ne.Proceeding;if(this.transaction instanceof Ce)return this.transaction.state===ne.Trying||this.transaction.state===ne.Proceeding;throw new Error("Unknown transaction type.")}get tryingable(){if(this.transaction instanceof Re)return this.transaction.state===ne.Proceeding;if(this.transaction instanceof Ce)return this.transaction.state===ne.Trying;throw new Error("Unknown transaction type.")}reply(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;const t=me(this.message,e);return this.transaction.receiveResponse(e.statusCode,t.message),t}init(){const e={loggerFactory:this.loggerFactory,onStateChange:e=>{e===ne.Terminated&&(this.core.userAgentServers.delete(s),this.dispose())},onTransportError:e=>{this.logger.error(e.message),this.delegate&&this.delegate.onTransportError?this.delegate.onTransportError(e):this.logger.error("User agent server response transport error.")}},t=new this.transactionConstructor(this.message,this.core.transport,e);this._transaction=t;const s=t.id;this.core.userAgentServers.set(t.id,this)}}class De extends Ae{constructor(e,t,s){super(Ce,e.userAgentCore,t,s)}}class He extends $e{constructor(e,t,s){const i=e.createOutgoingRequestMessage(j.INFO,s);super(Te,e.userAgentCore,i,t)}}class _e extends Ae{constructor(e,t,s){super(Ce,e.userAgentCore,t,s)}}class ke extends $e{constructor(e,t,s){super(Te,e,t,s)}}class xe extends Ae{constructor(e,t,s){super(Ce,e,t,s)}}class qe extends $e{constructor(e,t,s){const i=e.createOutgoingRequestMessage(j.NOTIFY,s);super(Te,e.userAgentCore,i,t)}}class Pe extends Ae{constructor(e,t,s){const i=void 0!==e.userAgentCore?e.userAgentCore:e;super(Ce,i,t,s)}}class Ne extends $e{constructor(e,t,s){const i=e.createOutgoingRequestMessage(j.PRACK,s);super(Te,e.userAgentCore,i,t),e.signalingStateTransition(i)}}class Me extends Ae{constructor(e,t,s){super(Ce,e.userAgentCore,t,s),e.signalingStateTransition(t),this.dialog=e}accept(e={statusCode:200}){return e.body&&this.dialog.signalingStateTransition(e.body),super.accept(e)}}class Oe extends $e{constructor(e,t,s){const i=e.createOutgoingRequestMessage(j.INVITE,s);super(Ee,e.userAgentCore,i,t),this.delegate=t,e.signalingStateTransition(i),e.reinviteUserAgentClient=this,this.dialog=e}receiveResponse(e){if(!this.authenticationGuard(e,this.dialog))return;const 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,session:this.dialog,prack:e=>{throw new Error("Unimplemented.")}});break;case/^2[0-9]{2}$/.test(t):this.dialog.signalingStateTransition(e),this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e,session:this.dialog,ack:e=>this.dialog.ack(e)});break;case/^3[0-9]{2}$/.test(t):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(t):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 "+t)}}}class Ue extends Ae{constructor(e,t,s){super(Re,e.userAgentCore,t,s),e.reinviteUserAgentServer=this,this.dialog=e}accept(e={statusCode:200}){e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(this.dialog.routeSet.map(e=>"Record-Route: "+e));const t=super.accept(e),s=this.dialog,i=Object.assign(Object.assign({},t),{session:s});return e.body&&this.dialog.signalingStateTransition(e.body),this.dialog.reConfirm(),i}progress(e={statusCode:180}){const t=super.progress(e),s=this.dialog,i=Object.assign(Object.assign({},t),{session:s});return e.body&&this.dialog.signalingStateTransition(e.body),i}redirect(e,t={statusCode:302}){throw this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,new Error("Unimplemented.")}reject(e={statusCode:488}){return this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,super.reject(e)}}class je extends $e{constructor(e,t,s){const i=e.createOutgoingRequestMessage(j.REFER,s);super(Te,e.userAgentCore,i,t)}}class Fe extends Ae{constructor(e,t,s){const i=void 0!==e.userAgentCore?e.userAgentCore:e;super(Ce,i,t,s)}}class Le extends ye{constructor(e,t,s,i){super(t,s),this.initialTransaction=e,this._signalingState=N.Initial,this.ackWait=!1,this.ackProcessing=!1,this.delegate=i,e instanceof Re&&(this.ackWait=!0),this.early||this.start2xxRetransmissionTimer(),this.signalingStateTransition(e.request),this.logger=t.loggerFactory.getLogger("sip.invite-dialog"),this.logger.log(`INVITE dialog ${this.id} constructed`)}dispose(){super.dispose(),this._signalingState=N.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`)}get sessionState(){return this.early?P.Early:this.ackWait?P.AckWait:this._signalingState===N.Closed?P.Terminated:P.Confirmed}get signalingState(){return this._signalingState}get offer(){return this._offer}get answer(){return this._answer}confirm(){this.early&&this.start2xxRetransmissionTimer(),super.confirm()}reConfirm(){this.reinviteUserAgentServer&&this.startReInvite2xxRetransmissionTimer()}ack(e={}){let t;if(this.logger.log(`INVITE dialog ${this.id} sending ACK request`),this.reinviteUserAgentClient){if(!(this.reinviteUserAgentClient.transaction instanceof Ee))throw new Error("Transaction not instance of InviteClientTransaction.");t=this.reinviteUserAgentClient.transaction,this.reinviteUserAgentClient=void 0}else{if(!(this.initialTransaction instanceof Ee))throw new Error("Initial transaction not instance of InviteClientTransaction.");t=this.initialTransaction}const s=this.createOutgoingRequestMessage(j.ACK,{cseq:t.request.cseq,extraHeaders:e.extraHeaders,body:e.body});return t.ackResponse(s),this.signalingStateTransition(s),{message:s}}bye(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending BYE request`),this.initialTransaction instanceof Re){if(this.early)throw new Error("UAS MUST NOT send a BYE on early dialogs.");if(this.ackWait&&this.initialTransaction.state!==ne.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 Ie(this,e,t)}info(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending INFO request`),this.early)throw new Error("Dialog not confirmed.");return new He(this,e,t)}invite(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 Oe(this,e,t)}message(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending MESSAGE request`),this.early)throw new Error("Dialog not confirmed.");const s=this.createOutgoingRequestMessage(j.MESSAGE,t);return new ke(this.core,s,e)}notify(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending NOTIFY request`),this.early)throw new Error("Dialog not confirmed.");return new qe(this,e,t)}prack(e,t){return this.logger.log(`INVITE dialog ${this.id} sending PRACK request`),new Ne(this,e,t)}refer(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending REFER request`),this.early)throw new Error("Dialog not confirmed.");return new je(this,e,t)}receiveRequest(e){if(this.logger.log(`INVITE dialog ${this.id} received ${e.method} request`),e.method!==j.ACK)if(this.sequenceGuard(e)){if(super.receiveRequest(e),e.method===j.INVITE){const t=()=>{const e=this.ackWait?"waiting for initial ACK":"processing initial ACK";this.logger.warn(`INVITE dialog ${this.id} received re-INVITE while ${e}`);let t="RFC 5407 suggests the following to avoid this race condition... ";t+=" Note: Implementation issues are outside the scope of this document,",t+=" but the following tip is provided for avoiding race conditions of",t+=" this type. The caller can delay sending re-INVITE F6 for some period",t+=" of time (2 seconds, perhaps), after which the caller can reasonably",t+=" assume that its ACK has been received. Implementors can decouple the",t+=" actions of the user (e.g., pressing the hold button) from the actions",t+=" of the protocol (the sending of re-INVITE F6), so that the UA can",t+=" behave like this. In this case, it is the implementor's choice as to",t+=" how long to wait. In most cases, such an implementation may be",t+=" useful to prevent the type of race condition shown in this section.",t+=" This document expresses no preference about whether or not they",t+=" should wait for an ACK to be delivered. After considering the impact",t+=" on user experience, implementors should decide whether or not to wait",t+=" for a while, because the user experience depends on the",t+=" implementation and has no direct bearing on protocol behavior.",this.logger.warn("RFC 5407 suggests the following to avoid this race condition... Note: Implementation issues are outside the scope of this document, but the following tip is provided for avoiding race conditions of this type. The caller can delay sending re-INVITE F6 for some period of time (2 seconds, perhaps), after which the caller can reasonably assume that its ACK has been received. Implementors can decouple the actions of the user (e.g., pressing the hold button) from the actions of the protocol (the sending of re-INVITE F6), so that the UA can behave like this. In this case, it is the implementor's choice as to how long to wait. In most cases, such an implementation may be useful to prevent the type of race condition shown in this section. This document expresses no preference about whether or not they should wait for an ACK to be delivered. After considering the impact on user experience, implementors should decide whether or not to wait for a while, because the user experience depends on the implementation and has no direct bearing on protocol behavior.")},s=["Retry-After: "+(Math.floor(10*Math.random())+1)];if(this.ackProcessing)return this.core.replyStateless(e,{statusCode:500,extraHeaders:s}),void t();if(this.ackWait&&this.signalingState!==N.Stable)return this.core.replyStateless(e,{statusCode:500,extraHeaders:s}),void t();if(this.reinviteUserAgentServer)return void this.core.replyStateless(e,{statusCode:500,extraHeaders:s});if(this.reinviteUserAgentClient)return void this.core.replyStateless(e,{statusCode:491})}if(e.method===j.INVITE){const t=e.parseHeader("contact");if(!t)throw new Error("Contact undefined.");if(!(t instanceof f))throw new Error("Contact not instance of NameAddrHeader.");this.dialogState.remoteTarget=t.uri}switch(e.method){case j.BYE:{const t=new De(this,e);this.delegate&&this.delegate.onBye?this.delegate.onBye(t):t.accept(),this.dispose()}break;case j.INFO:{const t=new _e(this,e);this.delegate&&this.delegate.onInfo?this.delegate.onInfo(t):t.reject({statusCode:469,extraHeaders:["Recv-Info :"]})}break;case j.INVITE:{const t=new Ue(this,e);this.signalingStateTransition(e),this.delegate&&this.delegate.onInvite?this.delegate.onInvite(t):t.reject({statusCode:488})}break;case j.MESSAGE:{const t=new xe(this.core,e);this.delegate&&this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case j.NOTIFY:{const t=new Pe(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(t):t.accept()}break;case j.PRACK:{const t=new Me(this,e);this.delegate&&this.delegate.onPrack?this.delegate.onPrack(t):t.accept()}break;case j.REFER:{const t=new Fe(this,e);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(t):t.reject()}break;default:this.logger.log(`INVITE dialog ${this.id} received unimplemented ${e.method} request`),this.core.replyStateless(e,{statusCode:501})}}else this.logger.log(`INVITE dialog ${this.id} rejected out of order ${e.method} request.`);else{if(this.ackWait){if(this.initialTransaction instanceof Ee)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);if(this.initialTransaction.request.cseq!==e.cseq)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);this.ackWait=!1}else{if(!this.reinviteUserAgentServer)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);if(this.reinviteUserAgentServer.transaction.request.cseq!==e.cseq)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);this.reinviteUserAgentServer=void 0}if(this.signalingStateTransition(e),this.delegate&&this.delegate.onAck){const t=this.delegate.onAck({message:e});t instanceof Promise&&(this.ackProcessing=!0,t.then(()=>this.ackProcessing=!1).catch(()=>this.ackProcessing=!1))}}}reliableSequenceGuard(e){const t=e.statusCode;if(!t)throw new Error("Status code undefined");if(t>100&&t<200){const t=e.getHeader("require"),s=e.getHeader("rseq"),i=t&&t.includes("100rel")&&s?Number(s):void 0;if(i){if(this.rseq&&this.rseq+1!==i)return!1;this.rseq=this.rseq?this.rseq+1:i}}return!0}signalingStateRollback(){this._signalingState!==N.HaveLocalOffer&&this.signalingState!==N.HaveRemoteOffer||this._rollbackOffer&&this._rollbackAnswer&&(this._signalingState=N.Stable,this._offer=this._rollbackOffer,this._answer=this._rollbackAnswer)}signalingStateTransition(e){const t=q(e);if(t&&"session"===t.contentDisposition){if(this._signalingState===N.Stable&&(this._rollbackOffer=this._offer,this._rollbackAnswer=this._answer),e instanceof A)switch(this._signalingState){case N.Initial:case N.Stable:this._signalingState=N.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case N.HaveLocalOffer:this._signalingState=N.Stable,this._answer=t;break;case N.HaveRemoteOffer:case N.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof D)switch(this._signalingState){case N.Initial:case N.Stable:this._signalingState=N.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case N.HaveLocalOffer:this._signalingState=N.Stable,this._answer=t;break;case N.HaveRemoteOffer:case N.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof H)switch(this._signalingState){case N.Initial:case N.Stable:this._signalingState=N.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case N.HaveLocalOffer:break;case N.HaveRemoteOffer:this._signalingState=N.Stable,this._answer=t;break;case N.Closed:break;default:throw new Error("Unexpected signaling state.")}if(x(e))switch(this._signalingState){case N.Initial:case N.Stable:this._signalingState=N.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case N.HaveLocalOffer:break;case N.HaveRemoteOffer:this._signalingState=N.Stable,this._answer=t;break;case N.Closed:break;default:throw new Error("Unexpected signaling state.")}}}start2xxRetransmissionTimer(){if(this.initialTransaction instanceof Re){const e=this.initialTransaction;let t=U.T1;const s=()=>{this.ackWait?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,U.T2),this.invite2xxTimer=setTimeout(s,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(s,t);const i=()=>{e.state===ne.Terminated&&(e.removeStateChangeListener(i),this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.ackWait&&(this.delegate&&this.delegate.onAckTimeout?this.delegate.onAckTimeout():this.bye()))};e.addStateChangeListener(i)}}startReInvite2xxRetransmissionTimer(){if(this.reinviteUserAgentServer&&this.reinviteUserAgentServer.transaction instanceof Re){const e=this.reinviteUserAgentServer.transaction;let t=U.T1;const s=()=>{this.reinviteUserAgentServer?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,U.T2),this.invite2xxTimer=setTimeout(s,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(s,t);const i=()=>{e.state===ne.Terminated&&(e.removeStateChangeListener(i),this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.reinviteUserAgentServer)};e.addStateChangeListener(i)}}}class Be extends $e{constructor(e,t,s){super(Ee,e,t,s),this.confirmedDialogAcks=new Map,this.confirmedDialogs=new Map,this.earlyDialogs=new Map,this.delegate=s}dispose(){this.earlyDialogs.forEach(e=>e.dispose()),this.earlyDialogs.clear(),super.dispose()}onTransportError(e){if(this.transaction.state===ne.Calling)return super.onTransportError(e);this.logger.error(e.message),this.logger.error("User agent client request transport error while sending ACK.")}receiveResponse(e){if(!this.authenticationGuard(e))return;const t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):return void(this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e}));case/^1[0-9]{2}$/.test(t):{if(!e.toTag)return void this.logger.warn("Non-100 1xx INVITE response received without a to tag, dropping.");if(!e.parseHeader("contact"))return void this.logger.error("Non-100 1xx INVITE response received without a Contact header field, dropping.");const t=ye.initialDialogStateForUserAgentClient(this.message,e);let s=this.earlyDialogs.get(t.id);if(!s){const e=this.transaction;if(!(e instanceof Ee))throw new Error("Transaction not instance of InviteClientTransaction.");s=new Le(e,this.core,t),this.earlyDialogs.set(s.id,s)}if(!s.reliableSequenceGuard(e))return void this.logger.warn("1xx INVITE reliable response received out of order or is a retransmission, dropping.");s.signalingState!==N.Initial&&s.signalingState!==N.HaveLocalOffer||s.signalingStateTransition(e);const i=s;this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:i,prack:e=>i.prack(void 0,e)})}return;case/^2[0-9]{2}$/.test(t):{if(!e.toTag)return void this.logger.error("2xx INVITE response received without a to tag, dropping.");if(!e.parseHeader("contact"))return void this.logger.error("2xx INVITE response received without a Contact header field, dropping.");const t=ye.initialDialogStateForUserAgentClient(this.message,e);let s=this.confirmedDialogs.get(t.id);if(s){const e=this.confirmedDialogAcks.get(t.id);if(e){const t=this.transaction;if(!(t instanceof Ee))throw new Error("Client transaction not instance of InviteClientTransaction.");t.ackResponse(e.message)}return}if(s=this.earlyDialogs.get(t.id),s)s.confirm(),s.recomputeRouteSet(e),this.earlyDialogs.delete(s.id),this.confirmedDialogs.set(s.id,s);else{const e=this.transaction;if(!(e instanceof Ee))throw new Error("Transaction not instance of InviteClientTransaction.");s=new Le(e,this.core,t),this.confirmedDialogs.set(s.id,s)}s.signalingState!==N.Initial&&s.signalingState!==N.HaveLocalOffer||s.signalingStateTransition(e);const i=s;if(this.delegate&&this.delegate.onAccept)this.delegate.onAccept({message:e,session:i,ack:e=>{const t=i.ack(e);return this.confirmedDialogAcks.set(i.id,t),t}});else{const e=i.ack();this.confirmedDialogAcks.set(i.id,e)}}return;case/^3[0-9]{2}$/.test(t):return this.earlyDialogs.forEach(e=>e.dispose()),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e}));case/^[4-6][0-9]{2}$/.test(t):return this.earlyDialogs.forEach(e=>e.dispose()),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e}));default:throw new Error("Invalid status code "+t)}throw new Error(`Executing what should be an unreachable code path receiving ${t} response.`)}}class Ve extends $e{constructor(e,t,s){super(Te,e,t,s)}}class Ge extends $e{constructor(e,t,s){super(Te,e,t,s)}}class Ke extends $e{constructor(e,t,s){const i=e.createOutgoingRequestMessage(j.SUBSCRIBE,s);super(Te,e.userAgentCore,i,t),this.dialog=e}waitNotifyStop(){}receiveResponse(e){if(e.statusCode&&e.statusCode>=200&&e.statusCode<300){const t=e.getHeader("Expires");if(t){const e=Number(t);this.dialog.subscriptionExpires>e&&(this.dialog.subscriptionExpires=e)}else this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE")}if(e.statusCode&&e.statusCode>=400&&e.statusCode<700){[404,405,410,416,480,481,482,483,484,485,489,501,604].includes(e.statusCode)&&this.dialog.terminate()}super.receiveResponse(e)}}class We extends ye{constructor(e,t,s,i,r,n){super(i,r),this.delegate=n,this._autoRefresh=!1,this._subscriptionEvent=e,this._subscriptionExpires=t,this._subscriptionExpiresInitial=t,this._subscriptionExpiresLastSet=Math.floor(Date.now()/1e3),this._subscriptionRefresh=void 0,this._subscriptionRefreshLastSet=void 0,this._subscriptionState=s,this.logger=i.loggerFactory.getLogger("sip.subscribe-dialog"),this.logger.log(`SUBSCRIBE dialog ${this.id} constructed`)}static initialDialogStateForSubscription(e,t){const s=t.getHeaders("record-route"),i=t.parseHeader("contact");if(!i)throw new Error("Contact undefined.");if(!(i instanceof f))throw new Error("Contact not instance of NameAddrHeader.");const r=i.uri,n=e.cseq,o=e.callId,a=e.fromTag,c=t.fromTag;if(!o)throw new Error("Call id undefined.");if(!a)throw new Error("From tag undefined.");if(!c)throw new Error("To tag undefined.");if(!e.from)throw new Error("From undefined.");if(!e.to)throw new Error("To undefined.");return{id:o+a+c,early:!1,callId:o,localTag:a,remoteTag:c,localSequenceNumber:n,remoteSequenceNumber:void 0,localURI:e.from.uri,remoteURI:e.to.uri,remoteTarget:r,routeSet:s,secure:!1}}dispose(){super.dispose(),this.N&&(clearTimeout(this.N),this.N=void 0),this.refreshTimerClear(),this.logger.log(`SUBSCRIBE dialog ${this.id} destroyed`)}get autoRefresh(){return this._autoRefresh}set autoRefresh(e){this._autoRefresh=!0,this.refreshTimerSet()}get subscriptionEvent(){return this._subscriptionEvent}get subscriptionExpires(){const e=Math.floor(Date.now()/1e3)-this._subscriptionExpiresLastSet,t=this._subscriptionExpires-e;return Math.max(t,0)}set subscriptionExpires(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){const t=this.subscriptionRefresh;(void 0===t||t>=e)&&this.refreshTimerSet()}}get subscriptionExpiresInitial(){return this._subscriptionExpiresInitial}get subscriptionRefresh(){if(void 0===this._subscriptionRefresh||void 0===this._subscriptionRefreshLastSet)return;const e=Math.floor(Date.now()/1e3)-this._subscriptionRefreshLastSet,t=this._subscriptionRefresh-e;return Math.max(t,0)}get subscriptionState(){return this._subscriptionState}receiveRequest(e){if(this.logger.log(`SUBSCRIBE dialog ${this.id} received ${e.method} request`),this.sequenceGuard(e))switch(super.receiveRequest(e),e.method){case j.NOTIFY:this.onNotify(e);break;default:this.logger.log(`SUBSCRIBE dialog ${this.id} received unimplemented ${e.method} request`),this.core.replyStateless(e,{statusCode:501})}else this.logger.log(`SUBSCRIBE dialog ${this.id} rejected out of order ${e.method} request.`)}refresh(){const e="Allow: "+F.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)}subscribe(e,t={}){if(this.subscriptionState!==ee.Pending&&this.subscriptionState!==ee.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`);const s=new Ke(this,e,t);return this.N&&(clearTimeout(this.N),this.N=void 0),this.N=setTimeout(()=>this.timerN(),U.TIMER_N),s}terminate(){this.stateTransition(ee.Terminated),this.onTerminated()}unsubscribe(){const e="Allow: "+F.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)}onNotify(e){const t=e.parseHeader("Event").event;if(!t||t!==this.subscriptionEvent)return void this.core.replyStateless(e,{statusCode:489});this.N&&(clearTimeout(this.N),this.N=void 0);const s=e.parseHeader("Subscription-State");if(!s||!s.state)return void this.core.replyStateless(e,{statusCode:489});const i=s.state,r=s.expires?Math.max(s.expires,0):void 0;switch(i){case"pending":this.stateTransition(ee.Pending,r);break;case"active":this.stateTransition(ee.Active,r);break;case"terminated":this.stateTransition(ee.Terminated,r);break;default:this.logger.warn("Unrecognized subscription state.")}const n=new Pe(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(n):n.accept()}onRefresh(e){this.delegate&&this.delegate.onRefresh&&this.delegate.onRefresh(e)}onTerminated(){this.delegate&&this.delegate.onTerminated&&this.delegate.onTerminated()}refreshTimerClear(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=void 0)}refreshTimerSet(){if(this.refreshTimerClear(),this.autoRefresh&&this.subscriptionExpires>0){const e=900*this.subscriptionExpires;this._subscriptionRefresh=Math.floor(e/1e3),this._subscriptionRefreshLastSet=Math.floor(Date.now()/1e3),this.refreshTimer=setTimeout(()=>{this.refreshTimer=void 0,this._subscriptionRefresh=void 0,this._subscriptionRefreshLastSet=void 0,this.onRefresh(this.refresh())},e)}}stateTransition(e,t){const s=()=>{this.logger.warn(`Invalid subscription state transition from ${this.subscriptionState} to ${e}`)};switch(e){case ee.Initial:case ee.NotifyWait:return void s();case ee.Pending:if(this.subscriptionState!==ee.NotifyWait&&this.subscriptionState!==ee.Pending)return void s();break;case ee.Active:case ee.Terminated:if(this.subscriptionState!==ee.NotifyWait&&this.subscriptionState!==ee.Pending&&this.subscriptionState!==ee.Active)return void s();break;default:return void s()}e===ee.Pending&&t&&(this.subscriptionExpires=t),e===ee.Active&&t&&(this.subscriptionExpires=t),e===ee.Terminated&&this.dispose(),this._subscriptionState=e}timerN(){this.logger.warn("Timer N expired for SUBSCRIBE dialog. Timed out waiting for NOTIFY."),this.subscriptionState!==ee.Terminated&&(this.stateTransition(ee.Terminated),this.onTerminated())}}class Ye extends $e{constructor(e,t,s){const i=t.getHeader("Event");if(!i)throw new Error("Event undefined");const r=t.getHeader("Expires");if(!r)throw new Error("Expires undefined");super(Te,e,t,s),this.delegate=s,this.subscriberId=t.callId+t.fromTag+i,this.subscriptionExpiresRequested=this.subscriptionExpires=Number(r),this.subscriptionEvent=i,this.subscriptionState=ee.NotifyWait,this.waitNotifyStart()}dispose(){super.dispose()}onNotify(e){const t=e.message.parseHeader("Event").event;if(!t||t!==this.subscriptionEvent)return this.logger.warn("Failed to parse event."),void e.reject({statusCode:489});const s=e.message.parseHeader("Subscription-State");if(!s||!s.state)return this.logger.warn("Failed to parse subscription state."),void e.reject({statusCode:489});const i=s.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){if(!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=s.expires?Math.min(this.subscriptionExpires,Math.max(s.expires,0)):this.subscriptionExpires,i){case"pending":this.subscriptionState=ee.Pending;break;case"active":this.subscriptionState=ee.Active;break;case"terminated":this.subscriptionState=ee.Terminated;break;default:throw new Error(`Unrecognized state ${i}.`)}if(this.subscriptionState!==ee.Terminated){const t=We.initialDialogStateForSubscription(this.message,e.message);this.dialog=new We(this.subscriptionEvent,this.subscriptionExpires,this.subscriptionState,this.core,t)}if(this.delegate&&this.delegate.onNotify){const t=e,s=this.dialog;this.delegate.onNotify({request:t,subscription:s})}else e.accept()}waitNotifyStart(){this.N||(this.core.subscribers.set(this.subscriberId,this),this.N=setTimeout(()=>this.timerN(),U.TIMER_N))}waitNotifyStop(){this.N&&(this.core.subscribers.delete(this.subscriberId),clearTimeout(this.N),this.N=void 0)}receiveResponse(e){if(this.authenticationGuard(e)){if(e.statusCode&&e.statusCode>=200&&e.statusCode<300){const t=e.getHeader("Expires");if(t){const e=Number(t);e>this.subscriptionExpiresRequested&&this.logger.warn("Expires header in a 200-class response to SUBSCRIBE with a higher value than the one in the request"),ethis.subscriptionExpires&&(this.dialog.subscriptionExpires=this.subscriptionExpires)}e.statusCode&&e.statusCode>=300&&e.statusCode<700&&this.waitNotifyStop(),super.receiveResponse(e)}}timerN(){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()}}class Ze extends Ae{constructor(e,t,s){super(Re,e,t,s),this.core=e}dispose(){this.earlyDialog&&this.earlyDialog.dispose(),super.dispose()}accept(e={statusCode:200}){if(!this.acceptable)throw new M(`${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{const e=this.transaction;if(!(e instanceof Re))throw new Error("Transaction not instance of InviteClientTransaction.");const t=ye.initialDialogStateForUserAgentServer(this.message,this.toTag);this.confirmedDialog=new Le(e,this.core,t)}const t=this.message.getHeaders("record-route").map(e=>"Record-Route: "+e),s="Contact: "+this.core.configuration.contact.toString(),i="Allow: "+F.toString();if(!e.body)if(this.confirmedDialog.signalingState===N.Stable)e.body=this.confirmedDialog.answer;else if(this.confirmedDialog.signalingState===N.Initial||this.confirmedDialog.signalingState===N.HaveRemoteOffer)throw new Error("Response must have a body.");e.statusCode=e.statusCode||200,e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(t),e.extraHeaders.push(i),e.extraHeaders.push(s);const r=super.accept(e),n=this.confirmedDialog,o=Object.assign(Object.assign({},r),{session:n});return e.body&&this.confirmedDialog.signalingState!==N.Stable&&this.confirmedDialog.signalingStateTransition(e.body),o}progress(e={statusCode:180}){if(!this.progressable)throw new M(`${this.message.method} not progressable in state ${this.transaction.state}.`);if(!this.earlyDialog){const e=this.transaction;if(!(e instanceof Re))throw new Error("Transaction not instance of InviteClientTransaction.");const t=ye.initialDialogStateForUserAgentServer(this.message,this.toTag,!0);this.earlyDialog=new Le(e,this.core,t)}const t=this.message.getHeaders("record-route").map(e=>"Record-Route: "+e),s="Contact: "+this.core.configuration.contact;e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(t),e.extraHeaders.push(s);const i=super.progress(e),r=this.earlyDialog,n=Object.assign(Object.assign({},i),{session:r});return e.body&&this.earlyDialog.signalingState!==N.Stable&&this.earlyDialog.signalingStateTransition(e.body),n}redirect(e,t={statusCode:302}){return super.redirect(e,t)}reject(e={statusCode:486}){return super.reject(e)}}class Je extends Ae{constructor(e,t,s){super(Ce,e,t,s),this.core=e}}class ze extends Ae{constructor(e,t,s){super(Ce,e,t,s),this.core=e}}const Xe=["application/sdp","application/dtmf-relay"];class Qe{constructor(e,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")}dispose(){this.reset()}reset(){this.dialogs.forEach(e=>e.dispose()),this.dialogs.clear(),this.subscribers.forEach(e=>e.dispose()),this.subscribers.clear(),this.userAgentClients.forEach(e=>e.dispose()),this.userAgentClients.clear(),this.userAgentServers.forEach(e=>e.dispose()),this.userAgentServers.clear()}get loggerFactory(){return this.configuration.loggerFactory}get transport(){const e=this.configuration.transportAccessor();if(!e)throw new Error("Transport undefined.");return e}invite(e,t){return new Be(this,e,t)}message(e,t){return new ke(this,e,t)}publish(e,t){return new Ve(this,e,t)}register(e,t){return new Ge(this,e,t)}subscribe(e,t){return new Ye(this,e,t)}request(e,t){return new $e(Te,this,e,t)}makeOutgoingRequestMessage(e,t,s,i,r,n,o){const a=this.configuration.sipjsId,c=this.configuration.displayName,h=this.configuration.viaForceRport,d=this.configuration.hackViaTcp,l=this.configuration.supportedOptionTags.slice();e===j.REGISTER&&l.push("path","gruu"),e===j.INVITE&&(this.configuration.contact.pubGruu||this.configuration.contact.tempGruu)&&l.push("gruu");const g={callIdPrefix:a,forceRport:h,fromDisplayName:c,hackViaTcp:d,optionTags:l,routeSet:this.configuration.routeSet,userAgentString:this.configuration.userAgentHeaderFieldValue,viaHost:this.configuration.viaHost},u=Object.assign(Object.assign({},g),r);return new H(e,t,s,i,u,n,o)}receiveIncomingRequestFromTransport(e){this.receiveRequestFromTransport(e)}receiveIncomingResponseFromTransport(e){this.receiveResponseFromTransport(e)}replyStateless(e,t){const s=this.configuration.userAgentHeaderFieldValue,i=this.configuration.supportedOptionTagsResponse;t=Object.assign(Object.assign({},t),{userAgent:s,supported:i});const r=me(e,t);return this.transport.send(r.message).catch(t=>{t instanceof Error&&this.logger.error(t.message),this.logger.error(`Transport error occurred sending stateless reply to ${e.method} request.`)}),r}receiveRequestFromTransport(e){const t=e.viaBranch,s=this.userAgentServers.get(t);e.method===j.ACK&&s&&s.transaction.state===ne.Accepted&&s instanceof Ze?this.logger.warn(`Discarding out of dialog ACK after 2xx response sent on transaction ${t}.`):e.method!==j.CANCEL?s?s.transaction.receiveRequest(e):this.receiveRequest(e):s?(this.replyStateless(e,{statusCode:200}),s.transaction instanceof Re&&s.transaction.state===ne.Proceeding&&s instanceof Ze&&s.receiveCancel(e)):this.replyStateless(e,{statusCode:481})}receiveRequest(e){if(!F.includes(e.method)){const t="Allow: "+F.toString();return void this.replyStateless(e,{statusCode:405,extraHeaders:[t]})}if(!e.ruri)throw new Error("Request-URI undefined.");if("sip"!==e.ruri.scheme)return void this.replyStateless(e,{statusCode:416});const t=e.ruri,s=e=>!!e&&e.user===t.user;if(!s(this.configuration.aor)&&!(s(this.configuration.contact.uri)||s(this.configuration.contact.pubGruu)||s(this.configuration.contact.tempGruu)))return this.logger.warn("Request-URI does not point to us."),void(e.method!==j.ACK&&this.replyStateless(e,{statusCode:404}));if(e.method!==j.INVITE||e.hasHeader("Contact")){if(!e.toTag){const t=e.viaBranch;if(!this.userAgentServers.has(t)){if(Array.from(this.userAgentServers.values()).some(t=>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"})}receiveInsideDialogRequest(e){if(e.method===j.NOTIFY){const t=e.parseHeader("Event");if(!t||!t.event)return void this.replyStateless(e,{statusCode:489});const s=e.callId+e.toTag+t.event,i=this.subscribers.get(s);if(i){const t=new Pe(this,e);return void i.onNotify(t)}}const t=e.callId+e.toTag+e.fromTag,s=this.dialogs.get(t);if(s){if(e.method===j.OPTIONS){const t="Allow: "+F.toString(),s="Accept: "+Xe.toString();return void this.replyStateless(e,{statusCode:200,extraHeaders:[t,s]})}s.receiveRequest(e)}else e.method!==j.ACK&&this.replyStateless(e,{statusCode:481})}receiveOutsideDialogRequest(e){switch(e.method){case j.ACK:break;case j.BYE:this.replyStateless(e,{statusCode:481});break;case j.CANCEL:throw new Error(`Unexpected out of dialog request method ${e.method}.`);case j.INFO:this.replyStateless(e,{statusCode:405});break;case j.INVITE:{const t=new Ze(this,e);this.delegate.onInvite?this.delegate.onInvite(t):t.reject()}break;case j.MESSAGE:{const t=new xe(this,e);this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case j.NOTIFY:{const t=new Pe(this,e);this.delegate.onNotify?this.delegate.onNotify(t):t.reject({statusCode:405})}break;case j.OPTIONS:{const t="Allow: "+F.toString(),s="Accept: "+Xe.toString();this.replyStateless(e,{statusCode:200,extraHeaders:[t,s]})}break;case j.REFER:{const t=new Fe(this,e);this.delegate.onRefer?this.delegate.onRefer(t):t.reject({statusCode:405})}break;case j.REGISTER:{const t=new Je(this,e);this.delegate.onRegister?this.delegate.onRegister(t):t.reject({statusCode:405})}break;case j.SUBSCRIBE:{const t=new ze(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}.`)}}receiveResponseFromTransport(e){if(e.getHeaders("via").length>1)return void this.logger.warn("More than one Via header field present in the response, dropping");const t=e.viaBranch+e.method,s=this.userAgentClients.get(t);s?s.transaction.receiveResponse(e):this.logger.warn(`Discarding unmatched ${e.statusCode} response to ${e.method} ${t}.`)}}var et;function tt(){return e=>e.audio||e.video?void 0===navigator.mediaDevices?Promise.reject(new Error("Media devices not available in insecure contexts.")):navigator.mediaDevices.getUserMedia.call(navigator.mediaDevices,e):Promise.resolve(new MediaStream)}function st(){return{bundlePolicy:"balanced",certificates:void 0,iceCandidatePoolSize:0,iceServers:[{urls:"stun:stun.l.google.com:19302"}],iceTransportPolicy:"all",peerIdentity:void 0,rtcpMuxPolicy:"require"}}!function(e){function t(e,t){let s=t,i=0,r=0;if(e.substring(s,s+2).match(/(^\r\n)/))return-2;for(;0===i;){if(r=e.indexOf("\r\n",s),-1===r)return r;!e.substring(r+2,r+4).match(/(^\r\n)/)&&e.charAt(r+2).match(/(^\s+)/)?s=r+2:i=r}return i}function s(e,t,s,i){const r=t.indexOf(":",s),n=t.substring(s,r).trim(),o=t.substring(r+1,i).trim();let a;switch(n.toLowerCase()){case"via":case"v":e.addHeader("via",o),1===e.getHeaders("via").length?(a=e.parseHeader("Via"),a&&(e.via=a,e.viaBranch=a.branch)):a=0;break;case"from":case"f":e.setHeader("from",o),a=e.parseHeader("from"),a&&(e.from=a,e.fromTag=a.getParam("tag"));break;case"to":case"t":e.setHeader("to",o),a=e.parseHeader("to"),a&&(e.to=a,e.toTag=a.getParam("tag"));break;case"record-route":if(a=b.parse(o,"Record_Route"),-1===a){a=void 0;break}if(!(a instanceof Array)){a=void 0;break}a.forEach(t=>{e.addHeader("record-route",o.substring(t.position,t.offset)),e.headers["Record-Route"][e.getHeaders("record-route").length-1].parsed=t.parsed});break;case"call-id":case"i":e.setHeader("call-id",o),a=e.parseHeader("call-id"),a&&(e.callId=o);break;case"contact":case"m":if(a=b.parse(o,"Contact"),-1===a){a=void 0;break}if(!(a instanceof Array)){a=void 0;break}a.forEach(t=>{e.addHeader("contact",o.substring(t.position,t.offset)),e.headers.Contact[e.getHeaders("contact").length-1].parsed=t.parsed});break;case"content-length":case"l":e.setHeader("content-length",o),a=e.parseHeader("content-length");break;case"content-type":case"c":e.setHeader("content-type",o),a=e.parseHeader("content-type");break;case"cseq":e.setHeader("cseq",o),a=e.parseHeader("cseq"),a&&(e.cseq=a.value),e instanceof D&&(e.method=a.method);break;case"max-forwards":e.setHeader("max-forwards",o),a=e.parseHeader("max-forwards");break;case"www-authenticate":e.setHeader("www-authenticate",o),a=e.parseHeader("www-authenticate");break;case"proxy-authenticate":e.setHeader("proxy-authenticate",o),a=e.parseHeader("proxy-authenticate");break;case"refer-to":case"r":e.setHeader("refer-to",o),a=e.parseHeader("refer-to"),a&&(e.referTo=a);break;default:e.addHeader(n.toLowerCase(),o),a=0}return void 0!==a||{error:"error parsing header '"+n+"'"}}e.getHeader=t,e.parseHeader=s,e.parseMessage=function(e,i){let r=0,n=e.indexOf("\r\n");if(-1===n)return void i.warn("no CRLF found, not a SIP message, discarded");const o=e.substring(0,n),a=b.parse(o,"Request_Response");let c,h;if(-1!==a){for(a.status_code?(c=new D,c.statusCode=a.status_code,c.reasonPhrase=a.reason_phrase):(c=new A,c.method=a.method,c.ruri=a.uri),c.data=e,r=n+2;;){if(n=t(e,r),-2===n){h=r+2;break}if(-1===n)return void i.error("malformed message");const o=s(c,e,r,n);if(o&&!0!==o)return void i.error(o.error);r=n+2}return c.hasHeader("content-length")?c.body=e.substr(h,Number(c.getHeader("content-length"))):c.body=e.substring(h),c}i.warn('error parsing first line of SIP message: "'+o+'"')}}(et||(et={}));class it{constructor(e,t,s){e.debug("SessionDescriptionHandler.constructor"),this.logger=e,this.mediaStreamFactory=t,this.sessionDescriptionHandlerConfiguration=s,this._localMediaStream=new MediaStream,this._remoteMediaStream=new MediaStream,this._peerConnection=new RTCPeerConnection(null==s?void 0:s.peerConnectionConfiguration),this.initPeerConnectionEventHandlers()}get localMediaStream(){return this._localMediaStream}get remoteMediaStream(){return this._remoteMediaStream}get dataChannel(){return this._dataChannel}get peerConnection(){return this._peerConnection}get peerConnectionDelegate(){return this._peerConnectionDelegate}set peerConnectionDelegate(e){this._peerConnectionDelegate=e}static dispatchAddTrackEvent(e,t){e.dispatchEvent(new MediaStreamTrackEvent("addtrack",{track:t}))}static dispatchRemoveTrackEvent(e,t){e.dispatchEvent(new MediaStreamTrackEvent("removetrack",{track:t}))}close(){this.logger.debug("SessionDescriptionHandler.close"),void 0!==this._peerConnection&&(this._peerConnection.getReceivers().forEach(e=>{e.track&&e.track.stop()}),this._peerConnection.getSenders().forEach(e=>{e.track&&e.track.stop()}),this._dataChannel&&this._dataChannel.close(),this._peerConnection.close(),this._peerConnection=void 0)}getDescription(e,t){var s,i;if(this.logger.debug("SessionDescriptionHandler.getDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));this.onDataChannel=null==e?void 0:e.onDataChannel;const r=null===(s=null==e?void 0:e.offerOptions)||void 0===s?void 0:s.iceRestart,n=void 0===(null==e?void 0:e.iceGatheringTimeout)?null===(i=this.sessionDescriptionHandlerConfiguration)||void 0===i?void 0:i.iceGatheringTimeout:null==e?void 0:e.iceGatheringTimeout;return this.getLocalMediaStream(e).then(()=>this.createDataChannel(e)).then(()=>this.createLocalOfferOrAnswer(e)).then(e=>this.applyModifiers(e,t)).then(e=>this.setLocalSessionDescription(e)).then(()=>this.waitForIceGatheringComplete(r,n)).then(()=>this.getLocalSessionDescription()).then(e=>({body:e.sdp,contentType:"application/sdp"})).catch(e=>{throw this.logger.error("SessionDescriptionHandler.getDescription failed - "+e),e})}hasDescription(e){return this.logger.debug("SessionDescriptionHandler.hasDescription"),"application/sdp"===e}sendDtmf(e,t){if(this.logger.debug("SessionDescriptionHandler.sendDtmf"),void 0===this._peerConnection)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - peer connection closed"),!1;const s=this._peerConnection.getSenders();if(0===s.length)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no senders"),!1;const i=s[0].dtmf;if(!i)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no DTMF sender"),!1;const r=null==t?void 0:t.duration,n=null==t?void 0:t.interToneGap;try{i.insertDTMF(e,r,n)}catch(e){return this.logger.error(e),!1}return this.logger.log("SessionDescriptionHandler.sendDtmf sent via RTP: "+e.toString()),!0}setDescription(e,t,s){if(this.logger.debug("SessionDescriptionHandler.setDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));this.onDataChannel=null==t?void 0:t.onDataChannel;const i="have-local-offer"===this._peerConnection.signalingState?"answer":"offer";return this.getLocalMediaStream(t).then(()=>this.applyModifiers({sdp:e,type:i},s)).then(e=>this.setRemoteSessionDescription(e)).catch(e=>{throw this.logger.error("SessionDescriptionHandler.setDescription failed - "+e),e})}applyModifiers(e,t){return this.logger.debug("SessionDescriptionHandler.applyModifiers"),t&&0!==t.length?t.reduce((e,t)=>e.then(t),Promise.resolve(e)).then(e=>{if(this.logger.debug("SessionDescriptionHandler.applyModifiers - modified sdp"),!e.sdp||!e.type)throw new Error("Invalid SDP.");return{sdp:e.sdp,type:e.type}}):Promise.resolve(e)}createDataChannel(e){if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));if(!0!==(null==e?void 0:e.dataChannel))return Promise.resolve();if(this._dataChannel)return Promise.resolve();switch(this._peerConnection.signalingState){case"stable":this.logger.debug("SessionDescriptionHandler.createDataChannel - creating data channel");try{return this._dataChannel=this._peerConnection.createDataChannel((null==e?void 0:e.dataChannelLabel)||"",null==e?void 0:e.dataChannelOptions),this.onDataChannel&&this.onDataChannel(this._dataChannel),Promise.resolve()}catch(e){return Promise.reject(e)}case"have-remote-offer":return Promise.resolve();case"have-local-offer":case"have-local-pranswer":case"have-remote-pranswer":case"closed":default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}}createLocalOfferOrAnswer(e){if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));switch(this._peerConnection.signalingState){case"stable":return this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP offer"),this._peerConnection.createOffer(null==e?void 0:e.offerOptions);case"have-remote-offer":return this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP answer"),this._peerConnection.createAnswer(null==e?void 0:e.answerOptions);case"have-local-offer":case"have-local-pranswer":case"have-remote-pranswer":case"closed":default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}}getLocalMediaStream(e){if(this.logger.debug("SessionDescriptionHandler.getLocalMediaStream"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));let t=Object.assign({},null==e?void 0:e.constraints);if(this.localMediaStreamConstraints){if(t.audio=t.audio||this.localMediaStreamConstraints.audio,t.video=t.video||this.localMediaStreamConstraints.video,JSON.stringify(this.localMediaStreamConstraints.audio)===JSON.stringify(t.audio)&&JSON.stringify(this.localMediaStreamConstraints.video)===JSON.stringify(t.video))return Promise.resolve()}else void 0===t.audio&&void 0===t.video&&(t={audio:!0});return this.localMediaStreamConstraints=t,this.mediaStreamFactory(t,this).then(e=>this.setLocalMediaStream(e))}setLocalMediaStream(e){if(this.logger.debug("SessionDescriptionHandler.setLocalMediaStream"),!this._peerConnection)throw new Error("Peer connection undefined.");const t=this._peerConnection,s=this._localMediaStream,i=[],r=e=>{const r=e.kind;if("audio"!==r&&"video"!==r)throw new Error(`Unknown new track kind ${r}.`);const n=t.getSenders().find(e=>e.track&&e.track.kind===r);n?i.push(new Promise(e=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - replacing sender ${r} track`),e()}).then(()=>n.replaceTrack(e).then(()=>{const t=s.getTracks().find(e=>e.kind===r);t&&(t.stop(),s.removeTrack(t),it.dispatchRemoveTrackEvent(s,t)),s.addTrack(e),it.dispatchAddTrackEvent(s,e)}).catch(e=>{throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to replace sender ${r} track`),e}))):i.push(new Promise(e=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - adding sender ${r} track`),e()}).then(()=>{try{t.addTrack(e,s)}catch(e){throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to add sender ${r} track`),e}s.addTrack(e),it.dispatchAddTrackEvent(s,e)}))},n=e.getAudioTracks();n.length&&r(n[0]);const o=e.getVideoTracks();return o.length&&r(o[0]),i.reduce((e,t)=>e.then(()=>t),Promise.resolve())}getLocalSessionDescription(){if(this.logger.debug("SessionDescriptionHandler.getLocalSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));const e=this._peerConnection.localDescription;return e?Promise.resolve(e):Promise.reject(new Error("Failed to get local session description"))}setLocalSessionDescription(e){return this.logger.debug("SessionDescriptionHandler.setLocalSessionDescription"),void 0===this._peerConnection?Promise.reject(new Error("Peer connection closed.")):this._peerConnection.setLocalDescription(e)}setRemoteSessionDescription(e){if(this.logger.debug("SessionDescriptionHandler.setRemoteSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));const t=e.sdp;let s;switch(this._peerConnection.signalingState){case"stable":s="offer";break;case"have-local-offer":s="answer";break;case"have-local-pranswer":case"have-remote-offer":case"have-remote-pranswer":case"closed":default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}return t?this._peerConnection.setRemoteDescription({sdp:t,type:s}):(this.logger.error("SessionDescriptionHandler.setRemoteSessionDescription failed - cannot set null sdp"),Promise.reject(new Error("SDP is undefined")))}setRemoteTrack(e){this.logger.debug("SessionDescriptionHandler.setRemoteTrack");const t=this._remoteMediaStream;t.getTrackById(e.id)?this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - have remote ${e.kind} track`):"audio"===e.kind?(this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${e.kind} track`),t.getAudioTracks().forEach(e=>{e.stop(),t.removeTrack(e),it.dispatchRemoveTrackEvent(t,e)}),t.addTrack(e),it.dispatchAddTrackEvent(t,e)):"video"===e.kind&&(this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${e.kind} track`),t.getVideoTracks().forEach(e=>{e.stop(),t.removeTrack(e),it.dispatchRemoveTrackEvent(t,e)}),t.addTrack(e),it.dispatchAddTrackEvent(t,e))}iceGatheringComplete(){this.logger.debug("SessionDescriptionHandler.iceGatheringComplete"),void 0!==this.iceGatheringCompleteTimeoutId&&(this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - clearing timeout"),clearTimeout(this.iceGatheringCompleteTimeoutId),this.iceGatheringCompleteTimeoutId=void 0),void 0!==this.iceGatheringCompletePromise&&(this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - resolving promise"),this.iceGatheringCompleteResolve&&this.iceGatheringCompleteResolve(),this.iceGatheringCompletePromise=void 0,this.iceGatheringCompleteResolve=void 0,this.iceGatheringCompleteReject=void 0)}waitForIceGatheringComplete(e=!1,t=0){return this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete"),void 0===this._peerConnection?Promise.reject("Peer connection closed."):e||"complete"!==this._peerConnection.iceGatheringState?(void 0!==this.iceGatheringCompletePromise&&(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - rejecting prior waiting promise"),this.iceGatheringCompleteReject&&this.iceGatheringCompleteReject(new Error("Promise superseded.")),this.iceGatheringCompletePromise=void 0,this.iceGatheringCompleteResolve=void 0,this.iceGatheringCompleteReject=void 0),this.iceGatheringCompletePromise=new Promise((e,s)=>{this.iceGatheringCompleteResolve=e,this.iceGatheringCompleteReject=s,t>0&&(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout in "+t),this.iceGatheringCompleteTimeoutId=setTimeout(()=>{this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout"),this.iceGatheringComplete()},t))}),this.iceGatheringCompletePromise):(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - already complete"),Promise.resolve())}initPeerConnectionEventHandlers(){if(this.logger.debug("SessionDescriptionHandler.initPeerConnectionEventHandlers"),!this._peerConnection)throw new Error("Peer connection undefined.");const e=this._peerConnection;e.onconnectionstatechange=t=>{var s;const i=e.connectionState;this.logger.debug("SessionDescriptionHandler.onconnectionstatechange "+i),(null===(s=this._peerConnectionDelegate)||void 0===s?void 0:s.onconnectionstatechange)&&this._peerConnectionDelegate.onconnectionstatechange(t)},e.ondatachannel=e=>{var t;this.logger.debug("SessionDescriptionHandler.ondatachannel"),this._dataChannel=e.channel,this.onDataChannel&&this.onDataChannel(this._dataChannel),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.ondatachannel)&&this._peerConnectionDelegate.ondatachannel(e)},e.onicecandidate=e=>{var t;this.logger.debug("SessionDescriptionHandler.onicecandidate"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onicecandidate)&&this._peerConnectionDelegate.onicecandidate(e)},e.onicecandidateerror=e=>{var t;this.logger.debug("SessionDescriptionHandler.onicecandidateerror"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onicecandidateerror)&&this._peerConnectionDelegate.onicecandidateerror(e)},e.oniceconnectionstatechange=t=>{var s;const i=e.iceConnectionState;this.logger.debug("SessionDescriptionHandler.oniceconnectionstatechange "+i),(null===(s=this._peerConnectionDelegate)||void 0===s?void 0:s.oniceconnectionstatechange)&&this._peerConnectionDelegate.oniceconnectionstatechange(t)},e.onicegatheringstatechange=t=>{var s;const i=e.iceGatheringState;this.logger.debug("SessionDescriptionHandler.onicegatheringstatechange "+i),"complete"===i&&this.iceGatheringComplete(),(null===(s=this._peerConnectionDelegate)||void 0===s?void 0:s.onicegatheringstatechange)&&this._peerConnectionDelegate.onicegatheringstatechange(t)},e.onnegotiationneeded=e=>{var t;this.logger.debug("SessionDescriptionHandler.onnegotiationneeded"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onnegotiationneeded)&&this._peerConnectionDelegate.onnegotiationneeded(e)},e.onsignalingstatechange=t=>{var s;const i=e.signalingState;this.logger.debug("SessionDescriptionHandler.onsignalingstatechange "+i),(null===(s=this._peerConnectionDelegate)||void 0===s?void 0:s.onsignalingstatechange)&&this._peerConnectionDelegate.onsignalingstatechange(t)},e.onstatsended=e=>{var t;this.logger.debug("SessionDescriptionHandler.onstatsended"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onstatsended)&&this._peerConnectionDelegate.onstatsended(e)},e.ontrack=e=>{var t;const s=e.track.kind,i=e.track.enabled?"enabled":"disabled";this.logger.debug(`SessionDescriptionHandler.ontrack ${s} ${i}`),this.setRemoteTrack(e.track),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.ontrack)&&this._peerConnectionDelegate.ontrack(e)}}}function rt(e){return(t,s)=>{void 0===e&&(e=tt());const i={iceGatheringTimeout:void 0!==(null==s?void 0:s.iceGatheringTimeout)?null==s?void 0:s.iceGatheringTimeout:5e3,peerConnectionConfiguration:Object.assign(Object.assign({},{bundlePolicy:"balanced",certificates:void 0,iceCandidatePoolSize:0,iceServers:[{urls:"stun:stun.l.google.com:19302"}],iceTransportPolicy:"all",peerIdentity:void 0,rtcpMuxPolicy:"require"}),null==s?void 0:s.peerConnectionConfiguration)},r=t.userAgent.getLogger("sip.SessionDescriptionHandler");return new it(r,e,i)}}class nt{constructor(e,t){if(this._state=se.Disconnected,this.transitioningState=!1,this._stateEventEmitter=new g,this.logger=e,t){const e=t,s=null==e?void 0:e.wsServers,i=null==e?void 0:e.maxReconnectionAttempts;if(void 0!==s){const e='The transport option "wsServers" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(void 0!==i){const e='The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}s&&!t.server&&("string"==typeof s&&(t.server=s),s instanceof Array&&(t.server=s[0]))}this.configuration=Object.assign(Object.assign({},nt.defaultOptions),t);const s=this.configuration.server,i=b.parse(s,"absoluteURI");if(-1===i)throw this.logger.error(`Invalid WebSocket Server URL "${s}"`),new Error("Invalid WebSocket Server URL");if(!["wss","ws","udp"].includes(i.scheme))throw this.logger.error(`Invalid scheme in WebSocket Server URL "${s}"`),new Error("Invalid scheme in WebSocket Server URL");this._protocol=i.scheme.toUpperCase()}dispose(){return this.disconnect()}get protocol(){return this._protocol}get server(){return this.configuration.server}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get ws(){return this._ws}connect(){return this._connect()}disconnect(){return this._disconnect()}isConnected(){return this.state===se.Connected}send(e){return this._send(e)}_connect(){switch(this.logger.log("Connecting "+this.server),this.state){case se.Connecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(se.Connecting));if(!this.connectPromise)throw new Error("Connect promise must be defined.");return this.connectPromise;case se.Connected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(se.Connecting));if(this.connectPromise)throw new Error("Connect promise must not be defined.");return Promise.resolve();case se.Disconnecting:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(se.Connecting)}catch(e){if(e instanceof d)return Promise.reject(e);throw e}break;case se.Disconnected:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(se.Connecting)}catch(e){if(e instanceof d)return Promise.reject(e);throw e}break;default:throw new Error("Unknown state")}let e;try{e=new WebSocket(this.server,"sip"),e.binaryType="arraybuffer",e.addEventListener("close",t=>this.onWebSocketClose(t,e)),e.addEventListener("error",t=>this.onWebSocketError(t,e)),e.addEventListener("open",t=>this.onWebSocketOpen(t,e)),e.addEventListener("message",t=>this.onWebSocketMessage(t,e)),this._ws=e}catch(e){return this._ws=void 0,this.logger.error("WebSocket construction failed."),this.logger.error(e),new Promise((t,s)=>{this.connectResolve=t,this.connectReject=s,this.transitionState(se.Disconnected,e)})}return this.connectPromise=new Promise((t,s)=>{this.connectResolve=t,this.connectReject=s,this.connectTimeout=setTimeout(()=>{this.logger.warn("Connect timed out. Exceeded time set in configuration.connectionTimeout: "+this.configuration.connectionTimeout+"s."),e.close(1e3)},1e3*this.configuration.connectionTimeout)}),this.connectPromise}_disconnect(){switch(this.logger.log("Disconnecting "+this.server),this.state){case se.Connecting:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(se.Disconnecting)}catch(e){if(e instanceof d)return Promise.reject(e);throw e}break;case se.Connected:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(se.Disconnecting)}catch(e){if(e instanceof d)return Promise.reject(e);throw e}break;case se.Disconnecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(se.Disconnecting));if(!this.disconnectPromise)throw new Error("Disconnect promise must be defined.");return this.disconnectPromise;case se.Disconnected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(se.Disconnecting));if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");return Promise.resolve();default:throw new Error("Unknown state")}if(!this._ws)throw new Error("WebSocket must be defined.");const e=this._ws;return this.disconnectPromise=new Promise((t,s)=>{this.disconnectResolve=t,this.disconnectReject=s;try{e.close(1e3)}catch(e){throw this.logger.error("WebSocket close failed."),this.logger.error(e),e}}),this.disconnectPromise}_send(e){if(!0===this.configuration.traceSip&&this.logger.log("Sending WebSocket message:\n\n"+e+"\n"),this._state!==se.Connected)return Promise.reject(new Error("Not connected."));if(!this._ws)throw new Error("WebSocket undefined.");try{this._ws.send(e)}catch(e){return e instanceof Error?Promise.reject(e):Promise.reject(new Error("WebSocket send failed."))}return Promise.resolve()}onWebSocketClose(e,t){if(t!==this._ws)return;const s=`WebSocket closed ${this.server} (code: ${e.code})`,i=this.disconnectPromise?void 0:new Error(s);i&&this.logger.warn("WebSocket closed unexpectedly"),this.logger.log(s),this._ws=void 0,this.transitionState(se.Disconnected,i)}onWebSocketError(e,t){t===this._ws&&this.logger.error("WebSocket error occurred.")}onWebSocketMessage(e,t){if(t!==this._ws)return;const s=e.data;let i;if(/^(\r\n)+$/.test(s))return this.clearKeepAliveTimeout(),void(!0===this.configuration.traceSip&&this.logger.log("Received WebSocket message with CRLF Keep Alive response"));if(s){if("string"!=typeof s){try{i=(new TextDecoder).decode(new Uint8Array(s))}catch(e){return this.logger.error(e),void this.logger.error("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"+i+"\n")}else i=s,!0===this.configuration.traceSip&&this.logger.log("Received WebSocket text message:\n\n"+i+"\n");if(this.state===se.Connected){if(this.onMessage)try{this.onMessage(i)}catch(e){throw this.logger.error(e),this.logger.error("Exception thrown by onMessage callback"),e}}else this.logger.warn("Received message while not connected, discarding...")}else this.logger.warn("Received empty message, discarding...")}onWebSocketOpen(e,t){t===this._ws&&this._state===se.Connecting&&(this.logger.log("WebSocket opened "+this.server),this.transitionState(se.Connected))}transitionLoopDetectedError(e){let t="A state transition loop has been detected.";return t+=` An attempt to transition from ${this._state} to ${e} before the prior transition completed.`,t+=" Perhaps you are synchronously calling connect() or disconnect() from a callback or state change handler?",this.logger.error(t),new d("Loop detected.")}transitionState(e,t){const s=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};if(this.transitioningState)throw this.transitionLoopDetectedError(e);switch(this.transitioningState=!0,this._state){case se.Connecting:e!==se.Connected&&e!==se.Disconnecting&&e!==se.Disconnected&&s();break;case se.Connected:e!==se.Disconnecting&&e!==se.Disconnected&&s();break;case se.Disconnecting:e!==se.Connecting&&e!==se.Disconnected&&s();break;case se.Disconnected:e!==se.Connecting&&s();break;default:throw new Error("Unknown state.")}const i=this._state;this._state=e;const r=this.connectResolve,n=this.connectReject;i===se.Connecting&&(this.connectPromise=void 0,this.connectResolve=void 0,this.connectReject=void 0);const o=this.disconnectResolve,a=this.disconnectReject;if(i===se.Disconnecting&&(this.disconnectPromise=void 0,this.disconnectResolve=void 0,this.disconnectReject=void 0),this.connectTimeout&&(clearTimeout(this.connectTimeout),this.connectTimeout=void 0),this.logger.log(`Transitioned from ${i} to ${this._state}`),this._stateEventEmitter.emit(this._state),e===se.Connected&&(this.startSendingKeepAlives(),this.onConnect))try{this.onConnect()}catch(e){throw this.logger.error(e),this.logger.error("Exception thrown by onConnect callback"),e}if(i===se.Connected&&(this.stopSendingKeepAlives(),this.onDisconnect))try{t?this.onDisconnect(t):this.onDisconnect()}catch(e){throw this.logger.error(e),this.logger.error("Exception thrown by onDisconnect callback"),e}if(i===se.Connecting){if(!r)throw new Error("Connect resolve undefined.");if(!n)throw new Error("Connect reject undefined.");e===se.Connected?r():n(t||new Error("Connect aborted."))}if(i===se.Disconnecting){if(!o)throw new Error("Disconnect resolve undefined.");if(!a)throw new Error("Disconnect reject undefined.");e===se.Disconnected?o():a(t||new Error("Disconnect aborted."))}this.transitioningState=!1}clearKeepAliveTimeout(){this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveDebounceTimeout=void 0}sendKeepAlive(){return this.keepAliveDebounceTimeout?Promise.resolve():(this.keepAliveDebounceTimeout=setTimeout(()=>{this.clearKeepAliveTimeout()},1e3*this.configuration.keepAliveDebounce),this.send("\r\n\r\n"))}startSendingKeepAlives(){this.configuration.keepAliveInterval&&!this.keepAliveInterval&&(this.keepAliveInterval=setInterval(()=>{this.sendKeepAlive(),this.startSendingKeepAlives()},(e=>{const t=.8*e;return 1e3*(Math.random()*(e-t)+t)})(this.configuration.keepAliveInterval)))}stopSendingKeepAlives(){this.keepAliveInterval&&clearInterval(this.keepAliveInterval),this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveInterval=void 0,this.keepAliveDebounceTimeout=void 0}}nt.defaultOptions={server:"",connectionTimeout:5,keepAliveInterval:0,keepAliveDebounce:10,traceSip:!0};class ot{constructor(e={}){if(this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this._state=ie.Stopped,this.unloadListener=()=>{this.stop()},this._stateEventEmitter=new g,this.delegate=e.delegate,this.options=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},ot.defaultOptions()),{sipjsId:R(5)}),{uri:new m("sip","anonymous."+R(6),"anonymous.invalid")}),{viaHost:R(12)+".invalid"}),ot.stripUndefinedProperties(e)),this.options.hackIpInContact)if("boolean"==typeof this.options.hackIpInContact&&this.options.hackIpInContact){const e=1,t=254,s=Math.floor(Math.random()*(t-e+1)+e);this.options.viaHost="192.0.2."+s}else this.options.hackIpInContact&&(this.options.viaHost=this.options.hackIpInContact);switch(this.loggerFactory=new ge,this.logger=this.loggerFactory.getLogger("sip.UserAgent"),this.loggerFactory.builtinEnabled=this.options.logBuiltinEnabled,this.loggerFactory.connector=this.options.logConnector,this.options.logLevel){case"error":this.loggerFactory.level=re.error;break;case"warn":this.loggerFactory.level=re.warn;break;case"log":this.loggerFactory.level=re.log;break;case"debug":this.loggerFactory.level=re.debug}if(this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach(e=>{const t=this.options[e];switch(e){case"uri":case"sessionDescriptionHandlerFactory":this.logger.log("\xb7 "+e+": "+t);break;case"authorizationPassword":this.logger.log("\xb7 "+e+": NOT SHOWN");break;case"transportConstructor":this.logger.log("\xb7 "+e+": "+t.name);break;default:this.logger.log("\xb7 "+e+": "+JSON.stringify(t))}})),this.options.transportOptions){const t=this.options.transportOptions,s=t.maxReconnectionAttempts,i=t.reconnectionTimeout;if(void 0!==s){const e='The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(void 0!==i){const e='The transport option "reconnectionTimeout" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}void 0===e.reconnectionDelay&&void 0!==i&&(this.options.reconnectionDelay=i),void 0===e.reconnectionAttempts&&void 0!==s&&(this.options.reconnectionAttempts=s)}if(void 0!==e.reconnectionDelay){const e='The user agent option "reconnectionDelay" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(void 0!==e.reconnectionAttempts){const e='The user agent option "reconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}this._transport=new this.options.transportConstructor(this.getLogger("sip.Transport"),this.options.transportOptions),this.initTransportCallbacks(),this._contact=this.initContact(),this._userAgentCore=this.initCore(),this.options.autoStart&&this.start()}static makeURI(e){return b.URIParse(e)}static defaultOptions(){return{allowLegacyNotifications:!1,authorizationHa1:"",authorizationPassword:"",authorizationUsername:"",autoStart:!1,autoStop:!0,delegate:{},contactName:"",contactParams:{transport:"ws"},displayName:"",forceRport:!1,hackAllowUnregisteredOptionTags:!1,hackIpInContact:!1,hackViaTcp:!1,logBuiltinEnabled:!0,logConfiguration:!0,logConnector:()=>{},logLevel:"log",noAnswerTimeout:60,preloadedRouteSet:[],reconnectionAttempts:0,reconnectionDelay:4,sessionDescriptionHandlerFactory:rt(),sessionDescriptionHandlerFactoryOptions:{},sipExtension100rel:K.Unsupported,sipExtensionReplaces:K.Unsupported,sipExtensionExtraSupported:[],sipjsId:"",transportConstructor:nt,transportOptions:{},uri:new m("sip","anonymous","anonymous.invalid"),userAgentString:"SIP.js/0.18.0",viaHost:""}}static stripUndefinedProperties(e){return Object.keys(e).reduce((t,s)=>(void 0!==e[s]&&(t[s]=e[s]),t),{})}get configuration(){return this.options}get contact(){return this._contact}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get transport(){return this._transport}get userAgentCore(){return this._userAgentCore}getLogger(e,t){return this.loggerFactory.getLogger(e,t)}getLoggerFactory(){return this.loggerFactory}isConnected(){return this.transport.isConnected()}reconnect(){return this.state===ie.Stopped?Promise.reject(new Error("User agent stopped.")):Promise.resolve().then(()=>this.transport.connect())}start(){if(this.state===ie.Started)return this.logger.warn("User agent already started"),Promise.resolve();if(this.logger.log("Starting "+this.configuration.uri),this.transitionState(ie.Started),this.options.autoStop){const e=!("undefined"==typeof chrome||!chrome.app||!chrome.app.runtime);"undefined"==typeof window||"function"!=typeof window.addEventListener||e||window.addEventListener("unload",this.unloadListener)}return this.transport.connect()}async stop(){if(this.state===ie.Stopped)return this.logger.warn("User agent already stopped"),Promise.resolve();if(this.logger.log("Stopping "+this.configuration.uri),this.transitionState(ie.Stopped),this.options.autoStop){const e=!("undefined"==typeof chrome||!chrome.app||!chrome.app.runtime);"undefined"!=typeof window&&window.removeEventListener&&!e&&window.removeEventListener("unload",this.unloadListener)}const e=Object.assign({},this._publishers),t=Object.assign({},this._registerers),s=Object.assign({},this._sessions),i=Object.assign({},this._subscriptions),r=this.transport,n=this.userAgentCore;this.logger.log("Dispose of registerers");for(const e in t)t[e]&&await t[e].dispose().catch(t=>{throw this.logger.error(t.message),delete this._registerers[e],t});this.logger.log("Dispose of sessions");for(const e in s)s[e]&&await s[e].dispose().catch(t=>{throw this.logger.error(t.message),delete this._sessions[e],t});this.logger.log("Dispose of subscriptions");for(const e in i)i[e]&&await i[e].dispose().catch(t=>{throw this.logger.error(t.message),delete this._subscriptions[e],t});this.logger.log("Dispose of publishers");for(const t in e)e[t]&&await e[t].dispose().catch(e=>{throw this.logger.error(e.message),delete this._publishers[t],e});this.logger.log("Dispose of transport"),await r.dispose().catch(e=>{throw this.logger.error(e.message),e}),this.logger.log("Dispose of core"),n.dispose()}_makeInviter(e,t){return new J(this,e,t)}attemptReconnection(e=1){const t=this.options.reconnectionAttempts,s=this.options.reconnectionDelay;e>t?this.logger.log("Maximum reconnection attempts reached"):(this.logger.log(`Reconnection attempt ${e} of ${t} - trying`),setTimeout(()=>{this.reconnect().then(()=>{this.logger.log(`Reconnection attempt ${e} of ${t} - succeeded`)}).catch(s=>{this.logger.error(s.message),this.logger.log(`Reconnection attempt ${e} of ${t} - failed`),this.attemptReconnection(++e)})},1===e?0:1e3*s))}initContact(){const e=""!=this.options.contactName?this.options.contactName:R(8),t=this.options.contactParams;return{pubGruu:void 0,tempGruu:void 0,uri:new m("sip",e,this.options.viaHost,void 0,t),toString:(e={})=>{const s=e.anonymous||!1,i=e.outbound||!1;let r="<";return r+=s?this.contact.tempGruu||"sip:anonymous@anonymous.invalid;transport="+(t.transport?t.transport:"ws"):this.contact.pubGruu||this.contact.uri,i&&(r+=";ob"),r+=">",r}}}initCore(){let e=[];e.push("outbound"),this.options.sipExtension100rel===K.Supported&&e.push("100rel"),this.options.sipExtensionReplaces===K.Supported&&e.push("replaces"),this.options.sipExtensionExtraSupported&&e.push(...this.options.sipExtensionExtraSupported),this.options.hackAllowUnregisteredOptionTags||(e=e.filter(e=>Y[e])),e=Array.from(new Set(e));const t=e.slice();(this.contact.pubGruu||this.contact.tempGruu)&&t.push("gruu");const s={aor:this.options.uri,contact:this.contact,displayName:this.options.displayName,loggerFactory:this.loggerFactory,hackViaTcp:this.options.hackViaTcp,routeSet:this.options.preloadedRouteSet,supportedOptionTags:e,supportedOptionTagsResponse:t,sipjsId:this.options.sipjsId,userAgentHeaderFieldValue:this.options.userAgentString,viaForceRport:this.options.forceRport,viaHost:this.options.viaHost,authenticationFactory:()=>{const e=this.options.authorizationUsername?this.options.authorizationUsername:this.options.uri.user,t=this.options.authorizationPassword?this.options.authorizationPassword:void 0,s=this.options.authorizationHa1?this.options.authorizationHa1:void 0;return new fe(this.getLoggerFactory(),s,e,t)},transportAccessor:()=>this.transport};return new Qe(s,{onInvite:e=>{var t;const s=new Z(this,e);if(e.delegate={onCancel:e=>{s._onCancel(e)},onTransportError:e=>{this.logger.error("A transport error has occurred while handling an incoming INVITE request.")}},e.trying(),this.options.sipExtensionReplaces!==K.Unsupported){const t=e.message.parseHeader("replaces");if(t){const e=t.call_id;if("string"!=typeof e)throw new Error("Type of call id is not string");const i=t.replaces_to_tag;if("string"!=typeof i)throw new Error("Type of to tag is not string");const r=t.replaces_from_tag;if("string"!=typeof r)throw new Error("type of from tag is not string");const n=e+i+r,o=this.userAgentCore.dialogs.get(n);if(!o)return void s.reject({statusCode:481});if(!o.early&&!0===t.early_only)return void s.reject({statusCode:486});const a=this._sessions[e+r]||this._sessions[e+i]||void 0;if(!a)throw new Error("Session does not exist.");s._replacee=a}}if(null===(t=this.delegate)||void 0===t?void 0:t.onInvite)return s.autoSendAnInitialProvisionalResponse?void s.progress().then(()=>{var e;if(void 0===(null===(e=this.delegate)||void 0===e?void 0:e.onInvite))throw new Error("onInvite undefined.");this.delegate.onInvite(s)}):void this.delegate.onInvite(s);s.reject({statusCode:486})},onMessage:e=>{if(this.delegate&&this.delegate.onMessage){const t=new L(e);this.delegate.onMessage(t)}else e.accept()},onNotify:e=>{if(this.delegate&&this.delegate.onNotify){const t=new B(e);this.delegate.onNotify(t)}else this.options.allowLegacyNotifications?e.accept():e.reject({statusCode:481})},onRefer:e=>{this.logger.warn("Received an out of dialog REFER request"),this.delegate&&this.delegate.onReferRequest?this.delegate.onReferRequest(e):e.reject({statusCode:405})},onRegister:e=>{this.logger.warn("Received an out of dialog REGISTER request"),this.delegate&&this.delegate.onRegisterRequest?this.delegate.onRegisterRequest(e):e.reject({statusCode:405})},onSubscribe:e=>{this.logger.warn("Received an out of dialog SUBSCRIBE request"),this.delegate&&this.delegate.onSubscribeRequest?this.delegate.onSubscribeRequest(e):e.reject({statusCode:405})}})}initTransportCallbacks(){this.transport.onConnect=()=>this.onTransportConnect(),this.transport.onDisconnect=e=>this.onTransportDisconnect(e),this.transport.onMessage=e=>this.onTransportMessage(e)}onTransportConnect(){this.state!==ie.Stopped&&this.delegate&&this.delegate.onConnect&&this.delegate.onConnect()}onTransportDisconnect(e){this.state!==ie.Stopped&&(this.delegate&&this.delegate.onDisconnect&&this.delegate.onDisconnect(e),e&&this.options.reconnectionAttempts>0&&this.attemptReconnection())}onTransportMessage(e){const t=et.parseMessage(e,this.getLogger("sip.Parser"));if(!t)return void this.logger.warn("Failed to parse incoming message. Dropping.");if(this.state===ie.Stopped&&t instanceof A)return void this.logger.warn(`Received ${t.method} request while stopped. Dropping.`);const s=()=>{const e=["from","to","call_id","cseq","via"];for(const s of e)if(!t.hasHeader(s))return this.logger.warn(`Missing mandatory header field : ${s}.`),!1;return!0};if(t instanceof A){if(!s())return void this.logger.warn("Request missing mandatory header field. Dropping.");if(!t.toTag&&t.callId.substr(0,5)===this.options.sipjsId)return void this.userAgentCore.replyStateless(t,{statusCode:482});const e=I(t.body),i=t.getHeader("content-length");if(i&&e1)return void this.logger.warn("More than one Via header field present in the response. Dropping.");if(t.via.host!==this.options.viaHost||void 0!==t.via.port)return void this.logger.warn("Via sent-by in the response does not match UA Via host value. Dropping.");const e=I(t.body),i=t.getHeader("content-length");if(i&&e{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case ie.Started:e!==ie.Stopped&&s();break;case ie.Stopped:e!==ie.Started&&s();break;default:throw new Error("Unknown state.")}this.logger.log(`Transitioned from ${this._state} to ${e}`),this._state=e,this._stateEventEmitter.emit(this._state)}}class at extends $e{constructor(e,t,s){super(Te,e,t,s)}}class ct extends Ae{constructor(e,t,s){super(Ce,e.userAgentCore,t,s)}}const ht=(e,t)=>{const s=[],i=e.split(/\r\n/);let r;for(let e=0;e(t.sdp=ht(t.sdp||"",e),Promise.resolve(t))}function ft(e){return e.sdp=((e,t)=>{const s=new RegExp("m="+t+".*$","gm"),i=new RegExp("^a=group:.*$","gm");if(s.test(e)){let s;const r=(e=e.split(/^m=/gm).filter(e=>{if(e.substr(0,t.length)===t){if(s=e.match(/^a=mid:.*$/gm),s){const e=s[0].match(/:.+$/g);e&&(s=e[0].substr(1))}return!1}return!0}).join("m=")).match(i);if(r&&1===r.length){let t=r[0];const n=new RegExp(" *"+s+"[^ ]*","g");t=t.replace(n,""),e=e.split(i).join(t)}}return e})(e.sdp||"","video"),Promise.resolve(e)}function mt(e){let t=e.sdp||"";if(-1===t.search(/^a=mid.*$/gm)){const s=t.match(/^m=.*$/gm),i=t.split(/^m=.*$/gm);s&&s.forEach((e,t)=>{s[t]=e+"\na=mid:"+t}),i.forEach((e,t)=>{s&&s[t]&&(i[t]=e+s[t])}),t=i.join(""),e.sdp=t}return Promise.resolve(e)}function vt(e){if(!e.sdp||!e.type)throw new Error("Invalid SDP");let t=e.sdp;const s=e.type;return t&&(/a=(sendrecv|sendonly|recvonly|inactive)/.test(t)?(t=t.replace(/a=sendrecv\r\n/g,"a=sendonly\r\n"),t=t.replace(/a=recvonly\r\n/g,"a=inactive\r\n")):t=t.replace(/(m=[^\r]*\r\n)/g,"$1a=sendonly\r\n")),Promise.resolve({sdp:t,type:s})}class wt{constructor(e,t={}){this.attemptingReconnection=!1,this.connectRequested=!1,this.held=!1,this.registerer=void 0,this.registerRequested=!1,this.session=void 0,this.delegate=t.delegate,this.options=Object.assign({},t);const s=Object.assign({},t.userAgentOptions);if(s.transportConstructor||(s.transportConstructor=nt),s.transportOptions||(s.transportOptions={server:e}),!s.uri&&t.aor){const e=ot.makeURI(t.aor);if(!e)throw new Error("Failed to create valid URI from "+t.aor);s.uri=e}this.userAgent=new ot(s),this.userAgent.delegate={onConnect:()=>{this.logger.log(`[${this.id}] Connected`),this.delegate&&this.delegate.onServerConnect&&this.delegate.onServerConnect(),this.registerer&&this.registerRequested&&(this.logger.log(`[${this.id}] Registering...`),this.registerer.register().catch(e=>{this.logger.error(`[${this.id}] Error occurred registering after connection with server was obtained.`),this.logger.error(e.toString())}))},onDisconnect:e=>{this.logger.log(`[${this.id}] Disconnected`),this.delegate&&this.delegate.onServerDisconnect&&this.delegate.onServerDisconnect(e),this.session&&(this.logger.log(`[${this.id}] Hanging up...`),this.hangup().catch(e=>{this.logger.error(`[${this.id}] Error occurred hanging up call after connection with server was lost.`),this.logger.error(e.toString())})),this.registerer&&(this.logger.log(`[${this.id}] Unregistering...`),this.registerer.unregister().catch(e=>{this.logger.error(`[${this.id}] Error occurred unregistering after connection with server was lost.`),this.logger.error(e.toString())})),e&&this.attemptReconnection()},onInvite:e=>{if(this.logger.log(`[${this.id}] Received INVITE`),this.session)return this.logger.warn(`[${this.id}] Session already in progress, rejecting INVITE...`),void e.reject().then(()=>{this.logger.log(`[${this.id}] Rejected INVITE`)}).catch(e=>{this.logger.error(`[${this.id}] Failed to reject INVITE`),this.logger.error(e.toString())});const t={sessionDescriptionHandlerOptions:{constraints:this.constraints}};this.initSession(e,t),this.delegate&&this.delegate.onCallReceived?this.delegate.onCallReceived():(this.logger.warn(`[${this.id}] No handler available, rejecting INVITE...`),e.reject().then(()=>{this.logger.log(`[${this.id}] Rejected INVITE`)}).catch(e=>{this.logger.error(`[${this.id}] Failed to reject INVITE`),this.logger.error(e.toString())}))},onMessage:e=>{e.accept().then(()=>{this.delegate&&this.delegate.onMessageReceived&&this.delegate.onMessageReceived(e.request.body)})}},this.logger=this.userAgent.getLogger("sip.SimpleUser"),window.addEventListener("online",()=>{this.logger.log(`[${this.id}] Online`),this.attemptReconnection()})}get id(){return this.options.userAgentOptions&&this.options.userAgentOptions.displayName||"Anonymous"}get localMediaStream(){var e;const t=null===(e=this.session)||void 0===e?void 0:e.sessionDescriptionHandler;if(t){if(!(t instanceof it))throw new Error("Session description handler not instance of web SessionDescriptionHandler");return t.localMediaStream}}get remoteMediaStream(){var e;const t=null===(e=this.session)||void 0===e?void 0:e.sessionDescriptionHandler;if(t){if(!(t instanceof it))throw new Error("Session description handler not instance of web SessionDescriptionHandler");return t.remoteMediaStream}}get localAudioTrack(){var e;return null===(e=this.localMediaStream)||void 0===e?void 0:e.getTracks().find(e=>"audio"===e.kind)}get localVideoTrack(){var e;return null===(e=this.localMediaStream)||void 0===e?void 0:e.getTracks().find(e=>"video"===e.kind)}get remoteAudioTrack(){var e;return null===(e=this.remoteMediaStream)||void 0===e?void 0:e.getTracks().find(e=>"audio"===e.kind)}get remoteVideoTrack(){var e;return null===(e=this.remoteMediaStream)||void 0===e?void 0:e.getTracks().find(e=>"video"===e.kind)}connect(){return this.logger.log(`[${this.id}] Connecting UserAgent...`),this.connectRequested=!0,this.userAgent.state!==ie.Started?this.userAgent.start():this.userAgent.reconnect()}disconnect(){return this.logger.log(`[${this.id}] Disconnecting UserAgent...`),this.connectRequested=!1,this.userAgent.stop()}isConnected(){return this.userAgent.isConnected()}register(e,t){return this.logger.log(`[${this.id}] Registering UserAgent...`),this.registerRequested=!0,this.registerer||(this.registerer=new ae(this.userAgent,e),this.registerer.stateChange.addListener(e=>{switch(e){case Q.Initial:break;case Q.Registered:this.delegate&&this.delegate.onRegistered&&this.delegate.onRegistered();break;case Q.Unregistered:this.delegate&&this.delegate.onUnregistered&&this.delegate.onUnregistered();break;case Q.Terminated:this.registerer=void 0;break;default:throw new Error("Unknown registerer state.")}})),this.registerer.register(t).then(()=>{})}unregister(e){return this.logger.log(`[${this.id}] Unregistering UserAgent...`),this.registerRequested=!1,this.registerer?this.registerer.unregister(e).then(()=>{}):Promise.resolve()}call(e,t,s){if(this.logger.log(`[${this.id}] Beginning Session...`),this.session)return Promise.reject(new Error("Session already exists."));const i=ot.makeURI(e);if(!i)return Promise.reject(new Error(`Failed to create a valid URI from "${e}"`));t||(t={}),t.sessionDescriptionHandlerOptions||(t.sessionDescriptionHandlerOptions={}),t.sessionDescriptionHandlerOptions.constraints||(t.sessionDescriptionHandlerOptions.constraints=this.constraints);const r=new J(this.userAgent,i,t);return this.sendInvite(r,t,s).then(()=>{})}hangup(){return this.logger.log(`[${this.id}] Hangup...`),this.terminate()}answer(e){return this.logger.log(`[${this.id}] Accepting Invitation...`),this.session?this.session instanceof Z?(e||(e={}),e.sessionDescriptionHandlerOptions||(e.sessionDescriptionHandlerOptions={}),e.sessionDescriptionHandlerOptions.constraints||(e.sessionDescriptionHandlerOptions.constraints=this.constraints),this.session.accept(e)):Promise.reject(new Error("Session not instance of Invitation.")):Promise.reject(new Error("Session does not exist."))}decline(){return this.logger.log(`[${this.id}] rejecting Invitation...`),this.session?this.session instanceof Z?this.session.reject():Promise.reject(new Error("Session not instance of Invitation.")):Promise.reject(new Error("Session does not exist."))}hold(){return this.logger.log(`[${this.id}] holding session...`),this.setHold(!0)}unhold(){return this.logger.log(`[${this.id}] unholding session...`),this.setHold(!1)}isHeld(){return this.held}mute(){this.logger.log(`[${this.id}] disabling media tracks...`),this.setMute(!0)}unmute(){this.logger.log(`[${this.id}] enabling media tracks...`),this.setMute(!1)}isMuted(){const e=this.localAudioTrack||this.localVideoTrack;return!!e&&!e.enabled}sendDTMF(e){if(this.logger.log(`[${this.id}] sending DTMF...`),!/^[0-9A-D#*,]$/.exec(e))return Promise.reject(new Error("Invalid DTMF tone."));if(!this.session)return Promise.reject(new Error("Session does not exist."));this.logger.log(`[${this.id}] Sending DTMF tone: ${e}`);const t={body:{contentDisposition:"render",contentType:"application/dtmf-relay",content:"Signal="+e+"\r\nDuration=2000"}};return this.session.info({requestOptions:t}).then(()=>{})}message(e,t){this.logger.log(`[${this.id}] sending message...`);const s=ot.makeURI(e);return s?new z(this.userAgent,s,t).message():Promise.reject(new Error(`Failed to create a valid URI from "${e}"`))}get constraints(){var e;let t={audio:!0,video:!1};return(null===(e=this.options.media)||void 0===e?void 0:e.constraints)&&(t=Object.assign({},this.options.media.constraints)),t}attemptReconnection(e=1){const t=this.options.reconnectionAttempts||3,s=this.options.reconnectionDelay||4;this.connectRequested?(this.attemptingReconnection&&this.logger.log(`[${this.id}] Reconnection attempt already in progress`),e>t?this.logger.log(`[${this.id}] Reconnection maximum attempts reached`):(1===e?this.logger.log(`[${this.id}] Reconnection attempt ${e} of ${t} - trying`):this.logger.log(`[${this.id}] Reconnection attempt ${e} of ${t} - trying in ${s} seconds`),this.attemptingReconnection=!0,setTimeout(()=>{if(!this.connectRequested)return this.logger.log(`[${this.id}] Reconnection attempt ${e} of ${t} - aborted`),void(this.attemptingReconnection=!1);this.userAgent.reconnect().then(()=>{this.logger.log(`[${this.id}] Reconnection attempt ${e} of ${t} - succeeded`),this.attemptingReconnection=!1}).catch(s=>{this.logger.log(`[${this.id}] Reconnection attempt ${e} of ${t} - failed`),this.logger.error(s.message),this.attemptingReconnection=!1,this.attemptReconnection(++e)})},1===e?0:1e3*s))):this.logger.log(`[${this.id}] Reconnection not currently desired`)}cleanupMedia(){this.options.media&&(this.options.media.local&&this.options.media.local.video&&(this.options.media.local.video.srcObject=null,this.options.media.local.video.pause()),this.options.media.remote&&(this.options.media.remote.audio&&(this.options.media.remote.audio.srcObject=null,this.options.media.remote.audio.pause()),this.options.media.remote.video&&(this.options.media.remote.video.srcObject=null,this.options.media.remote.video.pause())))}enableSenderTracks(e){if(!this.session)throw new Error("Session does not exist.");const t=this.session.sessionDescriptionHandler;if(!(t instanceof it))throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");const s=t.peerConnection;if(!s)throw new Error("Peer connection closed.");s.getSenders().forEach(t=>{t.track&&(t.track.enabled=e)})}initSession(e,t){this.session=e,this.delegate&&this.delegate.onCallCreated&&this.delegate.onCallCreated(),this.session.stateChange.addListener(t=>{if(this.session===e)switch(this.logger.log(`[${this.id}] session state changed to ${t}`),t){case G.Initial:case G.Establishing:break;case G.Established:this.setupLocalMedia(),this.setupRemoteMedia(),this.delegate&&this.delegate.onCallAnswered&&this.delegate.onCallAnswered();break;case G.Terminating:case G.Terminated:this.session=void 0,this.cleanupMedia(),this.delegate&&this.delegate.onCallHangup&&this.delegate.onCallHangup();break;default:throw new Error("Unknown session state.")}}),this.session.delegate={onInfo:e=>{var t;if(void 0===(null===(t=this.delegate)||void 0===t?void 0:t.onCallDTMFReceived))return void e.reject();const s=e.request.getHeader("content-type");if(!s||!/^application\/dtmf-relay/i.exec(s))return void e.reject();const i=e.request.body.split("\r\n",2);if(2!==i.length)return void e.reject();let r;const n=/^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/;if(n.test(i[0])&&(r=i[0].replace(n,"$2")),!r)return void e.reject();let o;const a=/^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/;a.test(i[1])&&(o=parseInt(i[1].replace(a,"$2"),10)),o?e.accept().then(()=>{if(this.delegate&&this.delegate.onCallDTMFReceived){if(!r||!o)throw new Error("Tone or duration undefined.");this.delegate.onCallDTMFReceived(r,o)}}).catch(e=>{this.logger.error(e.message)}):e.reject()},onRefer:e=>{e.accept().then(()=>this.sendInvite(e.makeInviter(t),t)).catch(e=>{this.logger.error(e.message)})}}}sendInvite(e,t,s){return this.initSession(e,t),e.invite(s).then(()=>{this.logger.log(`[${this.id}] sent INVITE`)})}setHold(e){if(!this.session)return Promise.reject(new Error("Session does not exist."));const t=this.session;if(this.held===e)return Promise.resolve();if(!(this.session.sessionDescriptionHandler instanceof it))throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");const s={requestDelegate:{onAccept:()=>{this.held=e,this.delegate&&this.delegate.onCallHold&&this.delegate.onCallHold(this.held)},onReject:()=>{this.logger.warn(`[${this.id}] re-invite request was rejected`),this.delegate&&this.delegate.onCallHold&&this.delegate.onCallHold(this.held)}}};return t.sessionDescriptionHandlerModifiersReInvite=e?[vt]:[],this.session.invite(s).then(()=>{t.sessionDescriptionHandlerModifiersReInvite=[],this.enableSenderTracks(!e)}).catch(e=>{throw e instanceof a&&this.logger.error(`[${this.id}] A hold request is already in progress.`),e})}setMute(e){this.session?this.session.state===G.Established?this.enableSenderTracks(!e):this.logger.warn(`[${this.id}] An established session is required to enable/disable media tracks`):this.logger.warn(`[${this.id}] A session is required to enabled/disable media tracks`)}setupLocalMedia(){var e,t;if(!this.session)throw new Error("Session does not exist.");const s=null===(t=null===(e=this.options.media)||void 0===e?void 0:e.local)||void 0===t?void 0:t.video;if(s){const e=this.localMediaStream;if(!e)throw new Error("Local media stream undefiend.");s.srcObject=e,s.volume=0,s.play().catch(e=>{this.logger.error(`[${this.id}] Failed to play local media`),this.logger.error(e.message)})}}setupRemoteMedia(){var e,t,s,i;if(!this.session)throw new Error("Session does not exist.");const r=(null===(t=null===(e=this.options.media)||void 0===e?void 0:e.remote)||void 0===t?void 0:t.video)||(null===(i=null===(s=this.options.media)||void 0===s?void 0:s.remote)||void 0===i?void 0:i.audio);if(r){const e=this.remoteMediaStream;if(!e)throw new Error("Remote media stream undefiend.");r.autoplay=!0,r.srcObject=e,r.play().catch(e=>{this.logger.error(`[${this.id}] Failed to play remote media`),this.logger.error(e.message)}),e.onaddtrack=()=>{this.logger.log(`[${this.id}] Remote media onaddtrack`),r.load(),r.play().catch(e=>{this.logger.error(`[${this.id}] Failed to play remote media`),this.logger.error(e.message)})}}}terminate(){if(this.logger.log(`[${this.id}] Terminating...`),!this.session)return Promise.reject(new Error("Session does not exist."));switch(this.session.state){case G.Initial:if(this.session instanceof J)return this.session.cancel().then(()=>{this.logger.log(`[${this.id}] Inviter never sent INVITE (canceled)`)});if(this.session instanceof Z)return this.session.reject().then(()=>{this.logger.log(`[${this.id}] Invitation rejected (sent 480)`)});throw new Error("Unknown session type.");case G.Establishing:if(this.session instanceof J)return this.session.cancel().then(()=>{this.logger.log(`[${this.id}] Inviter canceled (sent CANCEL)`)});if(this.session instanceof Z)return this.session.reject().then(()=>{this.logger.log(`[${this.id}] Invitation rejected (sent 480)`)});throw new Error("Unknown session type.");case G.Established:return this.session.bye().then(()=>{this.logger.log(`[${this.id}] Session ended (sent BYE)`)});case G.Terminating:case G.Terminated:break;default:throw new Error("Unknown state")}return this.logger.log(`[${this.id}] Terminating in state ${this.session.state}, no action taken`),Promise.resolve()}}const bt="0.18.0",Tt="sip.js"}})})); \ No newline at end of file diff --git a/lib/api/bye.d.ts b/lib/api/bye.d.ts new file mode 100644 index 000000000..3ab581000 --- /dev/null +++ b/lib/api/bye.d.ts @@ -0,0 +1,17 @@ +import { IncomingByeRequest, IncomingRequestMessage, ResponseOptions } from "../core"; +/** + * A request to end a {@link Session} (incoming BYE). + * @public + */ +export declare class Bye { + private incomingByeRequest; + /** @internal */ + constructor(incomingByeRequest: IncomingByeRequest); + /** Incoming BYE request message. */ + get request(): IncomingRequestMessage; + /** Accept the request. */ + accept(options?: ResponseOptions): Promise; + /** Reject the request. */ + reject(options?: ResponseOptions): Promise; +} +//# sourceMappingURL=bye.d.ts.map \ No newline at end of file diff --git a/lib/api/bye.d.ts.map b/lib/api/bye.d.ts.map new file mode 100644 index 000000000..121d3414e --- /dev/null +++ b/lib/api/bye.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"bye.d.ts","sourceRoot":"","sources":["../../src/api/bye.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,sBAAsB,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAEtF;;;GAGG;AACH,qBAAa,GAAG;IAEK,OAAO,CAAC,kBAAkB;IAD7C,gBAAgB;gBACW,kBAAkB,EAAE,kBAAkB;IAEjE,oCAAoC;IACpC,IAAW,OAAO,IAAI,sBAAsB,CAE3C;IAED,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/bye.js b/lib/api/bye.js new file mode 100644 index 000000000..87b919f7c --- /dev/null +++ b/lib/api/bye.js @@ -0,0 +1,24 @@ +/** + * A request to end a {@link Session} (incoming BYE). + * @public + */ +export class Bye { + /** @internal */ + constructor(incomingByeRequest) { + this.incomingByeRequest = incomingByeRequest; + } + /** Incoming BYE request message. */ + get request() { + return this.incomingByeRequest.message; + } + /** Accept the request. */ + accept(options) { + this.incomingByeRequest.accept(options); + return Promise.resolve(); + } + /** Reject the request. */ + reject(options) { + this.incomingByeRequest.reject(options); + return Promise.resolve(); + } +} diff --git a/lib/api/dtmf.d.ts b/lib/api/dtmf.d.ts new file mode 100644 index 000000000..ae952ab34 --- /dev/null +++ b/lib/api/dtmf.d.ts @@ -0,0 +1,16 @@ +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); + get tone(): string; + get 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 new file mode 100644 index 000000000..fd9a3e2c0 --- /dev/null +++ b/lib/api/dtmf.d.ts.map @@ -0,0 +1 @@ +{"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;IAC5B,OAAO,CAAC,KAAK,CAAS;IACtB,OAAO,CAAC,SAAS,CAAS;IAE1B,gBAAgB;gBACG,mBAAmB,EAAE,mBAAmB,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM;IAM3F,IAAW,IAAI,IAAI,MAAM,CAExB;IAED,IAAW,QAAQ,IAAI,MAAM,CAE5B;CACF"} \ No newline at end of file diff --git a/lib/api/dtmf.js b/lib/api/dtmf.js new file mode 100644 index 000000000..28b161d7f --- /dev/null +++ b/lib/api/dtmf.js @@ -0,0 +1,20 @@ +import { Info } from "./info"; +/** + * A DTMF signal (incoming INFO). + * @deprecated Use `Info`. + * @internal + */ +export class DTMF extends Info { + /** @internal */ + constructor(incomingInfoRequest, tone, duration) { + super(incomingInfoRequest); + this._tone = tone; + this._duration = duration; + } + get tone() { + return this._tone; + } + get duration() { + return this._duration; + } +} diff --git a/lib/api/emitter.d.ts b/lib/api/emitter.d.ts new file mode 100644 index 000000000..97968c2e3 --- /dev/null +++ b/lib/api/emitter.d.ts @@ -0,0 +1,89 @@ +/** + * Generic observable. + * @public + */ +export interface Emitter { + /** + * Sets up a function that will be called whenever the target changes. + * @param listener - Callback function. + * @param options - An options object that specifies characteristics about the listener. + * If once true, indicates that the listener should be invoked at most once after being added. + * If once true, the listener would be automatically removed when invoked. + */ + addListener(listener: (data: T) => void, options?: { + once?: boolean; + }): void; + /** + * Removes from the listener previously registered with addListener. + * @param listener - Callback function. + */ + removeListener(listener: (data: T) => void): void; + /** + * Registers a listener. + * @param listener - Callback function. + * @deprecated Use addListener. + */ + on(listener: (data: T) => void): void; + /** + * Unregisters a listener. + * @param listener - Callback function. + * @deprecated Use removeListener. + */ + off(listener: (data: T) => void): void; + /** + * Registers a listener then unregisters the listener after one event emission. + * @param listener - Callback function. + * @deprecated Use addListener. + */ + once(listener: (data: T) => void): void; +} +/** + * An {@link Emitter} implementation. + * @internal + */ +export declare class EmitterImpl implements Emitter { + private listeners; + /** + * Sets up a function that will be called whenever the target changes. + * @param listener - Callback function. + * @param options - An options object that specifies characteristics about the listener. + * If once true, indicates that the listener should be invoked at most once after being added. + * If once true, the listener would be automatically removed when invoked. + */ + addListener(listener: (data: T) => void, options?: { + once?: boolean; + }): void; + /** + * Emit change. + * @param data - Data to emit. + */ + emit(data: T): void; + /** + * Removes all listeners previously registered with addListener. + */ + removeAllListeners(): void; + /** + * Removes a listener previously registered with addListener. + * @param listener - Callback function. + */ + removeListener(listener: (data: T) => void): void; + /** + * Registers a listener. + * @param listener - Callback function. + * @deprecated Use addListener. + */ + on(listener: (data: T) => void): void; + /** + * Unregisters a listener. + * @param listener - Callback function. + * @deprecated Use removeListener. + */ + off(listener: (data: T) => void): void; + /** + * Registers a listener then unregisters the listener after one event emission. + * @param listener - Callback function. + * @deprecated Use addListener. + */ + once(listener: (data: T) => void): void; +} +//# 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 new file mode 100644 index 000000000..75bed8d6f --- /dev/null +++ b/lib/api/emitter.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"emitter.d.ts","sourceRoot":"","sources":["../../src/api/emitter.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,WAAW,OAAO,CAAC,CAAC;IACxB;;;;;;OAMG;IACH,WAAW,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,IAAI,EAAE,OAAO,CAAC,EAAE;QAAE,IAAI,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG,IAAI,CAAC;IAC7E;;;OAGG;IACH,cAAc,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,IAAI,GAAG,IAAI,CAAC;IAClD;;;;OAIG;IACH,EAAE,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,IAAI,GAAG,IAAI,CAAC;IACtC;;;;OAIG;IACH,GAAG,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,IAAI,GAAG,IAAI,CAAC;IACvC;;;;OAIG;IACH,IAAI,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,IAAI,GAAG,IAAI,CAAC;CACzC;AAED;;;GAGG;AACH,qBAAa,WAAW,CAAC,CAAC,CAAE,YAAW,OAAO,CAAC,CAAC,CAAC;IAC/C,OAAO,CAAC,SAAS,CAAkC;IAEnD;;;;;;OAMG;IACI,WAAW,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,IAAI,EAAE,OAAO,CAAC,EAAE;QAAE,IAAI,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG,IAAI;IAQnF;;;OAGG;IACI,IAAI,CAAC,IAAI,EAAE,CAAC,GAAG,IAAI;IAI1B;;OAEG;IACI,kBAAkB,IAAI,IAAI;IAIjC;;;OAGG;IACI,cAAc,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,IAAI,GAAG,IAAI;IAIxD;;;;OAIG;IACI,EAAE,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,IAAI,GAAG,IAAI;IAI5C;;;;OAIG;IACI,GAAG,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,IAAI,GAAG,IAAI;IAI7C;;;;OAIG;IACI,IAAI,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,IAAI,GAAG,IAAI;CAG/C"} \ No newline at end of file diff --git a/lib/api/emitter.js b/lib/api/emitter.js new file mode 100644 index 000000000..c3470c4ec --- /dev/null +++ b/lib/api/emitter.js @@ -0,0 +1,67 @@ +/** + * An {@link Emitter} implementation. + * @internal + */ +export class EmitterImpl { + constructor() { + this.listeners = new Array(); + } + /** + * Sets up a function that will be called whenever the target changes. + * @param listener - Callback function. + * @param options - An options object that specifies characteristics about the listener. + * If once true, indicates that the listener should be invoked at most once after being added. + * If once true, the listener would be automatically removed when invoked. + */ + addListener(listener, options) { + const onceWrapper = (data) => { + this.removeListener(onceWrapper); + listener(data); + }; + (options === null || options === void 0 ? void 0 : options.once) === true ? this.listeners.push(onceWrapper) : this.listeners.push(listener); + } + /** + * Emit change. + * @param data - Data to emit. + */ + emit(data) { + this.listeners.slice().forEach((listener) => listener(data)); + } + /** + * Removes all listeners previously registered with addListener. + */ + removeAllListeners() { + this.listeners = []; + } + /** + * Removes a listener previously registered with addListener. + * @param listener - Callback function. + */ + removeListener(listener) { + this.listeners = this.listeners.filter((l) => l !== listener); + } + /** + * Registers a listener. + * @param listener - Callback function. + * @deprecated Use addListener. + */ + on(listener) { + return this.addListener(listener); + } + /** + * Unregisters a listener. + * @param listener - Callback function. + * @deprecated Use removeListener. + */ + off(listener) { + return this.removeListener(listener); + } + /** + * Registers a listener then unregisters the listener after one event emission. + * @param listener - Callback function. + * @deprecated Use addListener. + */ + once(listener) { + return this.addListener(listener, { once: true }); + } +} diff --git a/lib/api/exceptions/content-type-unsupported.d.ts b/lib/api/exceptions/content-type-unsupported.d.ts new file mode 100644 index 000000000..386826e0c --- /dev/null +++ b/lib/api/exceptions/content-type-unsupported.d.ts @@ -0,0 +1,9 @@ +import { Exception } from "../../core"; +/** + * An exception indicating an unsupported content type prevented execution. + * @public + */ +export declare class ContentTypeUnsupportedError extends Exception { + constructor(message?: string); +} +//# sourceMappingURL=content-type-unsupported.d.ts.map \ No newline at end of file diff --git a/lib/api/exceptions/content-type-unsupported.d.ts.map b/lib/api/exceptions/content-type-unsupported.d.ts.map new file mode 100644 index 000000000..0d3bfbb8d --- /dev/null +++ b/lib/api/exceptions/content-type-unsupported.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"content-type-unsupported.d.ts","sourceRoot":"","sources":["../../../src/api/exceptions/content-type-unsupported.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAEvC;;;GAGG;AACH,qBAAa,2BAA4B,SAAQ,SAAS;gBACrC,OAAO,CAAC,EAAE,MAAM;CAGpC"} \ No newline at end of file diff --git a/lib/api/exceptions/content-type-unsupported.js b/lib/api/exceptions/content-type-unsupported.js new file mode 100644 index 000000000..705325bb4 --- /dev/null +++ b/lib/api/exceptions/content-type-unsupported.js @@ -0,0 +1,10 @@ +import { Exception } from "../../core"; +/** + * An exception indicating an unsupported content type prevented execution. + * @public + */ +export class ContentTypeUnsupportedError extends Exception { + constructor(message) { + super(message ? message : "Unsupported content type."); + } +} diff --git a/lib/api/exceptions/index.d.ts b/lib/api/exceptions/index.d.ts new file mode 100644 index 000000000..658d1660e --- /dev/null +++ b/lib/api/exceptions/index.d.ts @@ -0,0 +1,6 @@ +export * from "./content-type-unsupported"; +export * from "./request-pending"; +export * from "./session-description-handler"; +export * from "./session-terminated"; +export * from "./state-transition"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/api/exceptions/index.d.ts.map b/lib/api/exceptions/index.d.ts.map new file mode 100644 index 000000000..93e3ddca1 --- /dev/null +++ b/lib/api/exceptions/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/api/exceptions/index.ts"],"names":[],"mappings":"AAAA,cAAc,4BAA4B,CAAC;AAC3C,cAAc,mBAAmB,CAAC;AAClC,cAAc,+BAA+B,CAAC;AAC9C,cAAc,sBAAsB,CAAC;AACrC,cAAc,oBAAoB,CAAC"} \ No newline at end of file diff --git a/lib/api/exceptions/index.js b/lib/api/exceptions/index.js new file mode 100644 index 000000000..aea43f163 --- /dev/null +++ b/lib/api/exceptions/index.js @@ -0,0 +1,5 @@ +export * from "./content-type-unsupported"; +export * from "./request-pending"; +export * from "./session-description-handler"; +export * from "./session-terminated"; +export * from "./state-transition"; diff --git a/lib/api/exceptions/request-pending.d.ts b/lib/api/exceptions/request-pending.d.ts new file mode 100644 index 000000000..ce12eb574 --- /dev/null +++ b/lib/api/exceptions/request-pending.d.ts @@ -0,0 +1,10 @@ +import { Exception } from "../../core"; +/** + * An exception indicating an outstanding prior request prevented execution. + * @public + */ +export declare class RequestPendingError extends Exception { + /** @internal */ + constructor(message?: string); +} +//# sourceMappingURL=request-pending.d.ts.map \ No newline at end of file diff --git a/lib/api/exceptions/request-pending.d.ts.map b/lib/api/exceptions/request-pending.d.ts.map new file mode 100644 index 000000000..503a9dcff --- /dev/null +++ b/lib/api/exceptions/request-pending.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"request-pending.d.ts","sourceRoot":"","sources":["../../../src/api/exceptions/request-pending.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAEvC;;;GAGG;AACH,qBAAa,mBAAoB,SAAQ,SAAS;IAChD,gBAAgB;gBACG,OAAO,CAAC,EAAE,MAAM;CAGpC"} \ No newline at end of file diff --git a/lib/api/exceptions/request-pending.js b/lib/api/exceptions/request-pending.js new file mode 100644 index 000000000..415fd6985 --- /dev/null +++ b/lib/api/exceptions/request-pending.js @@ -0,0 +1,11 @@ +import { Exception } from "../../core"; +/** + * An exception indicating an outstanding prior request prevented execution. + * @public + */ +export class RequestPendingError extends Exception { + /** @internal */ + constructor(message) { + super(message ? message : "Request pending."); + } +} diff --git a/lib/api/exceptions/session-description-handler.d.ts b/lib/api/exceptions/session-description-handler.d.ts new file mode 100644 index 000000000..8bb15d10e --- /dev/null +++ b/lib/api/exceptions/session-description-handler.d.ts @@ -0,0 +1,9 @@ +import { Exception } from "../../core"; +/** + * An exception indicating a session description handler error occured. + * @public + */ +export declare class SessionDescriptionHandlerError extends Exception { + constructor(message?: string); +} +//# sourceMappingURL=session-description-handler.d.ts.map \ No newline at end of file diff --git a/lib/api/exceptions/session-description-handler.d.ts.map b/lib/api/exceptions/session-description-handler.d.ts.map new file mode 100644 index 000000000..185c078c6 --- /dev/null +++ b/lib/api/exceptions/session-description-handler.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"session-description-handler.d.ts","sourceRoot":"","sources":["../../../src/api/exceptions/session-description-handler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAEvC;;;GAGG;AACH,qBAAa,8BAA+B,SAAQ,SAAS;gBACxC,OAAO,CAAC,EAAE,MAAM;CAGpC"} \ No newline at end of file diff --git a/lib/api/exceptions/session-description-handler.js b/lib/api/exceptions/session-description-handler.js new file mode 100644 index 000000000..2f62ac9ea --- /dev/null +++ b/lib/api/exceptions/session-description-handler.js @@ -0,0 +1,10 @@ +import { Exception } from "../../core"; +/** + * An exception indicating a session description handler error occured. + * @public + */ +export class SessionDescriptionHandlerError extends Exception { + constructor(message) { + super(message ? message : "Unspecified session description handler error."); + } +} diff --git a/lib/api/exceptions/session-terminated.d.ts b/lib/api/exceptions/session-terminated.d.ts new file mode 100644 index 000000000..fc76671bf --- /dev/null +++ b/lib/api/exceptions/session-terminated.d.ts @@ -0,0 +1,9 @@ +import { Exception } from "../../core"; +/** + * An exception indicating the session terminated before the action completed. + * @public + */ +export declare class SessionTerminatedError extends Exception { + constructor(); +} +//# sourceMappingURL=session-terminated.d.ts.map \ No newline at end of file diff --git a/lib/api/exceptions/session-terminated.d.ts.map b/lib/api/exceptions/session-terminated.d.ts.map new file mode 100644 index 000000000..e8b222bbe --- /dev/null +++ b/lib/api/exceptions/session-terminated.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"session-terminated.d.ts","sourceRoot":"","sources":["../../../src/api/exceptions/session-terminated.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAEvC;;;GAGG;AACH,qBAAa,sBAAuB,SAAQ,SAAS;;CAIpD"} \ No newline at end of file diff --git a/lib/api/exceptions/session-terminated.js b/lib/api/exceptions/session-terminated.js new file mode 100644 index 000000000..1dc9d862d --- /dev/null +++ b/lib/api/exceptions/session-terminated.js @@ -0,0 +1,10 @@ +import { Exception } from "../../core"; +/** + * An exception indicating the session terminated before the action completed. + * @public + */ +export class SessionTerminatedError extends Exception { + constructor() { + super("The session has terminated."); + } +} diff --git a/lib/api/exceptions/state-transition.d.ts b/lib/api/exceptions/state-transition.d.ts new file mode 100644 index 000000000..b60bdb000 --- /dev/null +++ b/lib/api/exceptions/state-transition.d.ts @@ -0,0 +1,9 @@ +import { Exception } from "../../core"; +/** + * An exception indicating an invalid state transition error occured. + * @public + */ +export declare class StateTransitionError extends Exception { + constructor(message?: string); +} +//# sourceMappingURL=state-transition.d.ts.map \ No newline at end of file diff --git a/lib/api/exceptions/state-transition.d.ts.map b/lib/api/exceptions/state-transition.d.ts.map new file mode 100644 index 000000000..a75b1a256 --- /dev/null +++ b/lib/api/exceptions/state-transition.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"state-transition.d.ts","sourceRoot":"","sources":["../../../src/api/exceptions/state-transition.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAEvC;;;GAGG;AACH,qBAAa,oBAAqB,SAAQ,SAAS;gBAC9B,OAAO,CAAC,EAAE,MAAM;CAGpC"} \ No newline at end of file diff --git a/lib/api/exceptions/state-transition.js b/lib/api/exceptions/state-transition.js new file mode 100644 index 000000000..3ba45265c --- /dev/null +++ b/lib/api/exceptions/state-transition.js @@ -0,0 +1,10 @@ +import { Exception } from "../../core"; +/** + * An exception indicating an invalid state transition error occured. + * @public + */ +export class StateTransitionError extends Exception { + constructor(message) { + super(message ? message : "An error occurred during state transition."); + } +} diff --git a/lib/api/index.d.ts b/lib/api/index.d.ts new file mode 100644 index 000000000..c312ee698 --- /dev/null +++ b/lib/api/index.d.ts @@ -0,0 +1,59 @@ +/** + * A simple yet powerful API which takes care of SIP signaling and WebRTC media sessions for you. + * @packageDocumentation + */ +export * from "./exceptions"; +export * from "./bye"; +export * from "./emitter"; +export * from "./info"; +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-message-options"; +export * from "./messager-options"; +export * from "./messager"; +export * from "./notification"; +export * from "./publisher-options"; +export * from "./publisher-publish-options"; +export * from "./publisher-state"; +export * from "./publisher-unpublish-options"; +export * from "./publisher"; +export * from "./referral"; +export * from "./registerer-options"; +export * from "./registerer-register-options"; +export * from "./registerer-state"; +export * from "./registerer-unregister-options"; +export * from "./registerer"; +export * from "./session-bye-options"; +export * from "./session-delegate"; +export * from "./session-description-handler-factory"; +export * from "./session-description-handler"; +export * from "./session-info-options"; +export * from "./session-invite-options"; +export * from "./session-message-options"; +export * from "./session-options"; +export * from "./session-refer-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 "./transport"; +export * from "./transport-state"; +export * from "./user-agent-delegate"; +export * from "./user-agent-options"; +export * from "./user-agent-state"; +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 new file mode 100644 index 000000000..323f79b18 --- /dev/null +++ b/lib/api/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/api/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,cAAc,cAAc,CAAC;AAC7B,cAAc,OAAO,CAAC;AACtB,cAAc,WAAW,CAAC;AAC1B,cAAc,QAAQ,CAAC;AACvB,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,4BAA4B,CAAC;AAC3C,cAAc,oBAAoB,CAAC;AACnC,cAAc,YAAY,CAAC;AAC3B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,qBAAqB,CAAC;AACpC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,mBAAmB,CAAC;AAClC,cAAc,+BAA+B,CAAC;AAC9C,cAAc,aAAa,CAAC;AAC5B,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,uBAAuB,CAAC;AACtC,cAAc,oBAAoB,CAAC;AACnC,cAAc,uCAAuC,CAAC;AACtD,cAAc,+BAA+B,CAAC;AAC9C,cAAc,wBAAwB,CAAC;AACvC,cAAc,0BAA0B,CAAC;AACzC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,mBAAmB,CAAC;AAClC,cAAc,yBAAyB,CAAC;AACxC,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,aAAa,CAAC;AAC5B,cAAc,mBAAmB,CAAC;AAClC,cAAc,uBAAuB,CAAC;AACtC,cAAc,sBAAsB,CAAC;AACrC,cAAc,oBAAoB,CAAC;AACnC,cAAc,cAAc,CAAC"} \ No newline at end of file diff --git a/lib/api/index.js b/lib/api/index.js new file mode 100644 index 000000000..88daf1474 --- /dev/null +++ b/lib/api/index.js @@ -0,0 +1,58 @@ +/** + * A simple yet powerful API which takes care of SIP signaling and WebRTC media sessions for you. + * @packageDocumentation + */ +export * from "./exceptions"; +export * from "./bye"; +export * from "./emitter"; +export * from "./info"; +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-message-options"; +export * from "./messager-options"; +export * from "./messager"; +export * from "./notification"; +export * from "./publisher-options"; +export * from "./publisher-publish-options"; +export * from "./publisher-state"; +export * from "./publisher-unpublish-options"; +export * from "./publisher"; +export * from "./referral"; +export * from "./registerer-options"; +export * from "./registerer-register-options"; +export * from "./registerer-state"; +export * from "./registerer-unregister-options"; +export * from "./registerer"; +export * from "./session-bye-options"; +export * from "./session-delegate"; +export * from "./session-description-handler-factory"; +export * from "./session-description-handler"; +export * from "./session-info-options"; +export * from "./session-invite-options"; +export * from "./session-message-options"; +export * from "./session-options"; +export * from "./session-refer-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 "./transport"; +export * from "./transport-state"; +export * from "./user-agent-delegate"; +export * from "./user-agent-options"; +export * from "./user-agent-state"; +export * from "./user-agent"; diff --git a/lib/api/info.d.ts b/lib/api/info.d.ts new file mode 100644 index 000000000..9305dbe6e --- /dev/null +++ b/lib/api/info.d.ts @@ -0,0 +1,17 @@ +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. */ + get 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 new file mode 100644 index 000000000..6f6c26905 --- /dev/null +++ b/lib/api/info.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"info.d.ts","sourceRoot":"","sources":["../../src/api/info.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,sBAAsB,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAEvF;;;GAGG;AACH,qBAAa,IAAI;IAEI,OAAO,CAAC,mBAAmB;IAD9C,gBAAgB;gBACW,mBAAmB,EAAE,mBAAmB;IAEnE,wCAAwC;IACxC,IAAW,OAAO,IAAI,sBAAsB,CAE3C;IAED,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 new file mode 100644 index 000000000..1929cc08d --- /dev/null +++ b/lib/api/info.js @@ -0,0 +1,24 @@ +/** + * An exchange of information (incoming INFO). + * @public + */ +export class Info { + /** @internal */ + constructor(incomingInfoRequest) { + this.incomingInfoRequest = incomingInfoRequest; + } + /** Incoming MESSAGE request message. */ + get request() { + return this.incomingInfoRequest.message; + } + /** Accept the request. */ + accept(options) { + this.incomingInfoRequest.accept(options); + return Promise.resolve(); + } + /** Reject the request. */ + reject(options) { + this.incomingInfoRequest.reject(options); + return Promise.resolve(); + } +} diff --git a/lib/api/invitation-accept-options.d.ts b/lib/api/invitation-accept-options.d.ts new file mode 100644 index 000000000..341908975 --- /dev/null +++ b/lib/api/invitation-accept-options.d.ts @@ -0,0 +1,16 @@ +import { SessionDescriptionHandlerModifier, SessionDescriptionHandlerOptions } from "./session-description-handler"; +/** + * Options for {@link Invitation.accept}. + * @public + */ +export interface InvitationAcceptOptions { + /** + * Modifiers to pass to SessionDescriptionHandler during the initial INVITE transaction. + */ + sessionDescriptionHandlerModifiers?: Array; + /** + * Options to pass to SessionDescriptionHandler during the initial INVITE transaction. + */ + sessionDescriptionHandlerOptions?: SessionDescriptionHandlerOptions; +} +//# 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 new file mode 100644 index 000000000..4a690a2f3 --- /dev/null +++ b/lib/api/invitation-accept-options.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"invitation-accept-options.d.ts","sourceRoot":"","sources":["../../src/api/invitation-accept-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iCAAiC,EAAE,gCAAgC,EAAE,MAAM,+BAA+B,CAAC;AAEpH;;;GAGG;AACH,MAAM,WAAW,uBAAuB;IACtC;;OAEG;IACH,kCAAkC,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,CAAC;IAC9E;;OAEG;IACH,gCAAgC,CAAC,EAAE,gCAAgC,CAAC;CACrE"} \ No newline at end of file diff --git a/lib/api/invitation-accept-options.js b/lib/api/invitation-accept-options.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/api/invitation-accept-options.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/api/invitation-progress-options.d.ts b/lib/api/invitation-progress-options.d.ts new file mode 100644 index 000000000..67d19dbc6 --- /dev/null +++ b/lib/api/invitation-progress-options.d.ts @@ -0,0 +1,39 @@ +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; + /** + * Modifiers to pass to SessionDescriptionHandler during the initial INVITE transaction. + */ + sessionDescriptionHandlerModifiers?: Array; + /** + * Options to pass to SessionDescriptionHandler during the initial INVITE transaction. + */ + sessionDescriptionHandlerOptions?: SessionDescriptionHandlerOptions; + /** + * 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 new file mode 100644 index 000000000..f18712a02 --- /dev/null +++ b/lib/api/invitation-progress-options.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"invitation-progress-options.d.ts","sourceRoot":"","sources":["../../src/api/invitation-progress-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iCAAiC,EAAE,gCAAgC,EAAE,MAAM,+BAA+B,CAAC;AAEpH;;;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,kCAAkC,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,CAAC;IAC9E;;OAEG;IACH,gCAAgC,CAAC,EAAE,gCAAgC,CAAC;IACpE;;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 new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/api/invitation-progress-options.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/api/invitation-reject-options.d.ts b/lib/api/invitation-reject-options.d.ts new file mode 100644 index 000000000..98221ac8c --- /dev/null +++ b/lib/api/invitation-reject-options.d.ts @@ -0,0 +1,26 @@ +/** + * 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 new file mode 100644 index 000000000..69c351da8 --- /dev/null +++ b/lib/api/invitation-reject-options.d.ts.map @@ -0,0 +1 @@ +{"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 new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/api/invitation-reject-options.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/api/invitation.d.ts b/lib/api/invitation.d.ts new file mode 100644 index 000000000..2a93a2eb4 --- /dev/null +++ b/lib/api/invitation.d.ts @@ -0,0 +1,196 @@ +import { IncomingInviteRequest, IncomingRequestMessage, Logger, NameAddrHeader } 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; + /** + * Logger. + */ + protected logger: Logger; + /** @internal */ + protected _id: string; + /** True if dispose() has been called. */ + private disposed; + /** INVITE will be rejected if not accepted within a certain period time. */ + private expiresTimer; + /** True if this Session has been Terminated due to a CANCEL request. */ + private isCanceled; + /** Are reliable provisional responses required or supported. */ + private rel100; + /** The current RSeq header value. */ + private rseq; + /** INVITE will be rejected if final response not sent in a certain period time. */ + private userNoAnswerTimer; + /** True if waiting for a PRACK before sending a 200 Ok. */ + private waitingForPrack; + /** A Promise providing a defer when waiting for a PRACK. */ + private waitingForPrackPromise; + /** Function to resolve when PRACK arrives. */ + private waitingForPrackResolve; + /** Function to reject when PRACK never arrives. */ + private waitingForPrackReject; + /** @internal */ + constructor(userAgent: UserAgent, incomingInviteRequest: IncomingInviteRequest); + /** + * Destructor. + */ + dispose(): Promise; + /** + * 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 autoSendAnInitialProvisionalResponse(): boolean; + /** + * Initial incoming INVITE request message body. + */ + get body(): string | undefined; + /** + * The identity of the local user. + */ + get localIdentity(): NameAddrHeader; + /** + * The identity of the remote user. + */ + get remoteIdentity(): NameAddrHeader; + /** + * Initial incoming INVITE request message. + */ + get 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. + * Resolves once the response sent, otherwise rejects. + * + * This method may reject for a variety of reasons including + * the receipt of a CANCEL request before `accept` is able + * to construct a 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. + * Resolves once the response sent, otherwise rejects. + * @param options - Options bucket. + */ + progress(options?: InvitationProgressOptions): Promise; + /** + * Reject the invitation. + * + * @remarks + * Replies to the INVITE request with a 4xx, 5xx, or 6xx final response. + * Resolves once the response sent, otherwise rejects. + * + * The expectation is that this method is used to reject an INVITE request. + * That is indeed the case - a call to `progress` followed by `reject` is + * a typical way to "decline" an incoming INVITE request. However it may + * also be called after calling `accept` (but only before it completes) + * which will reject the call and cause `accept` to reject. + * @param options - Options bucket. + */ + reject(options?: InvitationRejectOptions): Promise; + /** + * Handle CANCEL request. + * + * @param message - CANCEL message. + * @internal + */ + _onCancel(message: IncomingRequestMessage): void; + /** + * Helper function to handle offer/answer in a PRACK. + */ + private handlePrackOfferAnswer; + /** + * A handler for errors which occur while attempting to send 1xx and 2xx responses. + * In all cases, an attempt is made to reject the request if it is still outstanding. + * And while there are a variety of things which can go wrong and we log something here + * for all errors, there are a handful of common exceptions we pay some extra attention to. + * @param error - The error which occurred. + */ + private handleResponseError; + /** + * Callback for when ACK for a 2xx response is never received. + * @param session - Session the ACK never arrived for. + */ + private onAckTimeout; + /** + * A version of `accept` which resolves a session when the 200 Ok response is sent. + * @param options - Options bucket. + */ + private sendAccept; + /** + * A version of `progress` which resolves when the provisional response is sent. + * @param options - Options bucket. + */ + private sendProgress; + /** + * A version of `progress` which resolves when the provisional response with sdp is sent. + * @param options - Options bucket. + */ + private sendProgressWithSDP; + /** + * A version of `progress` which resolves when the reliable provisional response is sent. + * @param options - Options bucket. + */ + private sendProgressReliable; + /** + * A version of `progress` which resolves when the reliable provisional response is acknowledged. + * @param options - Options bucket. + */ + private sendProgressReliableWaitForPrack; + /** + * A version of `progress` which resolves when a 100 Trying provisional response is sent. + */ + private sendProgressTrying; + /** + * When attempting to accept the INVITE, an invitation waits + * for any outstanding PRACK to arrive before sending the 200 Ok. + * It will be waiting on this Promise to resolve which lets it know + * the PRACK has arrived and it may proceed to send the 200 Ok. + */ + private waitForArrivalOfPrack; + /** + * Here we are resolving the promise which in turn will cause + * the accept to proceed (it may still fail for other reasons, but...). + */ + private prackArrived; + /** + * Here we are rejecting the promise which in turn will cause + * the accept to fail and the session to transition to "terminated". + */ + private prackNeverArrived; +} +//# 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 new file mode 100644 index 000000000..5f5c269c3 --- /dev/null +++ b/lib/api/invitation.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"invitation.d.ts","sourceRoot":"","sources":["../../src/api/invitation.ts"],"names":[],"mappings":"AAAA,OAAO,EAKL,qBAAqB,EAErB,sBAAsB,EAEtB,MAAM,EACN,cAAc,EAMf,MAAM,SAAS,CAAC;AAGjB,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;AAEpC,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAMzC;;;GAGG;AACH,qBAAa,UAAW,SAAQ,OAAO;IA+BI,OAAO,CAAC,qBAAqB;IA9BtE;;OAEG;IACH,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC;IAEzB,gBAAgB;IAChB,SAAS,CAAC,GAAG,EAAE,MAAM,CAAC;IAEtB,yCAAyC;IACzC,OAAO,CAAC,QAAQ,CAAS;IACzB,4EAA4E;IAC5E,OAAO,CAAC,YAAY,CAAiC;IACrD,wEAAwE;IACxE,OAAO,CAAC,UAAU,CAAS;IAC3B,gEAAgE;IAChE,OAAO,CAAC,MAAM,CAA6C;IAC3D,qCAAqC;IACrC,OAAO,CAAC,IAAI,CAAqC;IACjD,mFAAmF;IACnF,OAAO,CAAC,iBAAiB,CAAiC;IAC1D,2DAA2D;IAC3D,OAAO,CAAC,eAAe,CAAS;IAChC,4DAA4D;IAC5D,OAAO,CAAC,sBAAsB,CAA4B;IAC1D,8CAA8C;IAC9C,OAAO,CAAC,sBAAsB,CAA8B;IAC5D,mDAAmD;IACnD,OAAO,CAAC,qBAAqB,CAA6B;IAE1D,gBAAgB;gBACG,SAAS,EAAE,SAAS,EAAU,qBAAqB,EAAE,qBAAqB;IA6E7F;;OAEG;IACI,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAyC/B;;;;;;;;;;;;;;;;;;;;;;;OAuBG;IACH,IAAW,oCAAoC,IAAI,OAAO,CAEzD;IAED;;OAEG;IACH,IAAW,IAAI,IAAI,MAAM,GAAG,SAAS,CAEpC;IAED;;OAEG;IACH,IAAW,aAAa,IAAI,cAAc,CAEzC;IAED;;OAEG;IACH,IAAW,cAAc,IAAI,cAAc,CAE1C;IAED;;OAEG;IACH,IAAW,OAAO,IAAI,sBAAsB,CAE3C;IAED;;;;;;;;;;;;OAYG;IACI,MAAM,CAAC,OAAO,GAAE,uBAA4B,GAAG,OAAO,CAAC,IAAI,CAAC;IAiDnE;;;;;;;;OAQG;IACI,QAAQ,CAAC,OAAO,GAAE,yBAA8B,GAAG,OAAO,CAAC,IAAI,CAAC;IAsEvE;;;;;;;;;;;;;OAaG;IACI,MAAM,CAAC,OAAO,GAAE,uBAA4B,GAAG,OAAO,CAAC,IAAI,CAAC;IA+BnE;;;;;OAKG;IAEI,SAAS,CAAC,OAAO,EAAE,sBAAsB,GAAG,IAAI;IAkBvD;;OAEG;IACH,OAAO,CAAC,sBAAsB;IA4C9B;;;;;;OAMG;IACH,OAAO,CAAC,mBAAmB;IA0D3B;;;OAGG;IACH,OAAO,CAAC,YAAY;IAUpB;;;OAGG;IACH,OAAO,CAAC,UAAU;IAgClB;;;OAGG;IACH,OAAO,CAAC,YAAY;IA2BpB;;;OAGG;IACH,OAAO,CAAC,mBAAmB;IAkB3B;;;OAGG;IACH,OAAO,CAAC,oBAAoB;IAO5B;;;OAGG;IACH,OAAO,CAAC,gCAAgC;IA4FxC;;OAEG;IACH,OAAO,CAAC,kBAAkB;IAS1B;;;;;OAKG;IACH,OAAO,CAAC,qBAAqB;IAW7B;;;OAGG;IACH,OAAO,CAAC,YAAY;IASpB;;;OAGG;IACH,OAAO,CAAC,iBAAiB;CAQ1B"} \ No newline at end of file diff --git a/lib/api/invitation.js b/lib/api/invitation.js new file mode 100644 index 000000000..3b5741354 --- /dev/null +++ b/lib/api/invitation.js @@ -0,0 +1,708 @@ +import { fromBodyLegacy, getBody, Grammar, SignalingState, Timers, TransactionStateError } from "../core"; +import { getReasonPhrase } from "../core/messages/utils"; +import { ContentTypeUnsupportedError, SessionDescriptionHandlerError, SessionTerminatedError } from "./exceptions"; +import { Session } from "./session"; +import { SessionState } from "./session-state"; +import { SIPExtension } from "./user-agent-options"; +/** + * An invitation is an offer to establish a {@link Session} (incoming INVITE). + * @public + */ +export class Invitation extends Session { + /** @internal */ + constructor(userAgent, incomingInviteRequest) { + super(userAgent); + this.incomingInviteRequest = incomingInviteRequest; + /** True if dispose() has been called. */ + this.disposed = false; + /** INVITE will be rejected if not accepted within a certain period time. */ + this.expiresTimer = undefined; + /** True if this Session has been Terminated due to a CANCEL request. */ + this.isCanceled = false; + /** Are reliable provisional responses required or supported. */ + this.rel100 = "none"; + /** The current RSeq header value. */ + this.rseq = Math.floor(Math.random() * 10000); + /** INVITE will be rejected if final response not sent in a certain period time. */ + this.userNoAnswerTimer = undefined; + /** True if waiting for a PRACK before sending a 200 Ok. */ + this.waitingForPrack = false; + this.logger = userAgent.getLogger("sip.Invitation"); + const incomingRequestMessage = this.incomingInviteRequest.message; + // Set 100rel if necessary + const requireHeader = incomingRequestMessage.getHeader("require"); + if (requireHeader && requireHeader.toLowerCase().includes("100rel")) { + this.rel100 = "required"; + } + const supportedHeader = incomingRequestMessage.getHeader("supported"); + if (supportedHeader && supportedHeader.toLowerCase().includes("100rel")) { + this.rel100 = "supported"; + } + // FIXME: HACK: This is a hack to port an existing behavior. + // Set the toTag on the incoming request message to the toTag which + // will be used in the response to the incoming request!!! + // 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). + // eslint-disable-next-line @typescript-eslint/no-explicit-any + incomingRequestMessage.toTag = incomingInviteRequest.toTag; + if (typeof incomingRequestMessage.toTag !== "string") { + throw new TypeError("toTag should have been a string."); + } + // The following mapping values are RECOMMENDED: + // ... + // 19 no answer from the user 480 Temporarily unavailable + // https://tools.ietf.org/html/rfc3398#section-7.2.4.1 + this.userNoAnswerTimer = setTimeout(() => { + incomingInviteRequest.reject({ statusCode: 480 }); + this.stateTransition(SessionState.Terminated); + }, this.userAgent.configuration.noAnswerTimeout ? this.userAgent.configuration.noAnswerTimeout * 1000 : 60000); + // 1. If the request is an INVITE that contains an Expires header + // field, the UAS core sets a timer for the number of seconds + // indicated in the header field value. When the timer fires, the + // invitation is considered to be expired. If the invitation + // expires before the UAS has generated a final response, a 487 + // (Request Terminated) response SHOULD be generated. + // https://tools.ietf.org/html/rfc3261#section-13.3.1 + if (incomingRequestMessage.hasHeader("expires")) { + const expires = Number(incomingRequestMessage.getHeader("expires") || 0) * 1000; + this.expiresTimer = setTimeout(() => { + if (this.state === SessionState.Initial) { + incomingInviteRequest.reject({ statusCode: 487 }); + this.stateTransition(SessionState.Terminated); + } + }, expires); + } + // Session parent properties + const assertedIdentity = this.request.getHeader("P-Asserted-Identity"); + if (assertedIdentity) { + this._assertedIdentity = Grammar.nameAddrHeaderParse(assertedIdentity); + } + this._contact = this.userAgent.contact.toString(); + const contentDisposition = incomingRequestMessage.parseHeader("Content-Disposition"); + if (contentDisposition && contentDisposition.type === "render") { + this._renderbody = incomingRequestMessage.body; + this._rendertype = incomingRequestMessage.getHeader("Content-Type"); + } + // Identifier + this._id = incomingRequestMessage.callId + incomingRequestMessage.fromTag; + // Add to the user agent's session collection. + this.userAgent._sessions[this._id] = this; + } + /** + * Destructor. + */ + dispose() { + // Only run through this once. It can and does get called multiple times + // depending on the what the sessions state is when first called. + // For example, if called when "establishing" it will be called again + // at least once when the session transitions to "terminated". + // Regardless, running through this more than once is pointless. + if (this.disposed) { + return Promise.resolve(); + } + this.disposed = true; + // Clear timers + if (this.expiresTimer) { + clearTimeout(this.expiresTimer); + this.expiresTimer = undefined; + } + if (this.userNoAnswerTimer) { + clearTimeout(this.userNoAnswerTimer); + this.userNoAnswerTimer = undefined; + } + // If accept() is still waiting for a PRACK, make sure it rejects + this.prackNeverArrived(); + // If the final response for the initial INVITE not yet been sent, reject it + switch (this.state) { + case SessionState.Initial: + return this.reject().then(() => super.dispose()); + case SessionState.Establishing: + return this.reject().then(() => super.dispose()); + case SessionState.Established: + return super.dispose(); + case SessionState.Terminating: + return super.dispose(); + case SessionState.Terminated: + return super.dispose(); + default: + throw new Error("Unknown state."); + } + } + /** + * 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 autoSendAnInitialProvisionalResponse() { + return this.rel100 === "required" ? false : true; + } + /** + * Initial incoming INVITE request message body. + */ + get body() { + return this.incomingInviteRequest.message.body; + } + /** + * The identity of the local user. + */ + get localIdentity() { + return this.request.to; + } + /** + * The identity of the remote user. + */ + get remoteIdentity() { + return this.request.from; + } + /** + * Initial incoming INVITE request message. + */ + get request() { + return this.incomingInviteRequest.message; + } + /** + * Accept the invitation. + * + * @remarks + * Accept the incoming INVITE request to start a Session. + * Replies to the INVITE request with a 200 Ok response. + * Resolves once the response sent, otherwise rejects. + * + * This method may reject for a variety of reasons including + * the receipt of a CANCEL request before `accept` is able + * to construct a response. + * @param options - Options bucket. + */ + accept(options = {}) { + this.logger.log("Invitation.accept"); + // validate state + if (this.state !== SessionState.Initial) { + const error = new Error(`Invalid session state ${this.state}`); + this.logger.error(error.message); + return Promise.reject(error); + } + // Modifiers and options for initial INVITE transaction + if (options.sessionDescriptionHandlerModifiers) { + this.sessionDescriptionHandlerModifiers = options.sessionDescriptionHandlerModifiers; + } + if (options.sessionDescriptionHandlerOptions) { + this.sessionDescriptionHandlerOptions = options.sessionDescriptionHandlerOptions; + } + // transition state + this.stateTransition(SessionState.Establishing); + return (this.sendAccept() + // eslint-disable-next-line @typescript-eslint/no-unused-vars + .then(({ message, session }) => { + session.delegate = { + onAck: (ackRequest) => this.onAckRequest(ackRequest), + onAckTimeout: () => this.onAckTimeout(), + onBye: (byeRequest) => this.onByeRequest(byeRequest), + onInfo: (infoRequest) => this.onInfoRequest(infoRequest), + onInvite: (inviteRequest) => this.onInviteRequest(inviteRequest), + onMessage: (messageRequest) => this.onMessageRequest(messageRequest), + onNotify: (notifyRequest) => this.onNotifyRequest(notifyRequest), + onPrack: (prackRequest) => this.onPrackRequest(prackRequest), + onRefer: (referRequest) => this.onReferRequest(referRequest) + }; + this._dialog = session; + this.stateTransition(SessionState.Established); + // TODO: Reconsider this "automagic" send of a BYE to replacee behavior. + // This behavior has been ported forward from legacy versions. + if (this._replacee) { + this._replacee._bye(); + } + }) + .catch((error) => this.handleResponseError(error))); + } + /** + * Indicate progress processing the invitation. + * + * @remarks + * Report progress to the the caller. + * Replies to the INVITE request with a 1xx provisional response. + * Resolves once the response sent, otherwise rejects. + * @param options - Options bucket. + */ + progress(options = {}) { + this.logger.log("Invitation.progress"); + // validate state + if (this.state !== SessionState.Initial) { + const error = new Error(`Invalid session state ${this.state}`); + this.logger.error(error.message); + return Promise.reject(error); + } + // Ported + const statusCode = options.statusCode || 180; + if (statusCode < 100 || statusCode > 199) { + throw new TypeError("Invalid statusCode: " + statusCode); + } + // Modifiers and options for initial INVITE transaction + if (options.sessionDescriptionHandlerModifiers) { + this.sessionDescriptionHandlerModifiers = options.sessionDescriptionHandlerModifiers; + } + if (options.sessionDescriptionHandlerOptions) { + this.sessionDescriptionHandlerOptions = options.sessionDescriptionHandlerOptions; + } + // 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.waitingForPrack) { + this.logger.warn("Unexpected call for progress while waiting for prack, ignoring"); + return Promise.resolve(); + } + // Trying provisional response + if (options.statusCode === 100) { + return this.sendProgressTrying() + .then(() => { + return; + }) + .catch((error) => this.handleResponseError(error)); + } + // Standard provisional response + if (!(this.rel100 === "required") && + !(this.rel100 === "supported" && options.rel100) && + !(this.rel100 === "supported" && this.userAgent.configuration.sipExtension100rel === SIPExtension.Required)) { + return this.sendProgress(options) + .then(() => { + return; + }) + .catch((error) => this.handleResponseError(error)); + } + // Reliable provisional response + return this.sendProgressReliableWaitForPrack(options) + .then(() => { + return; + }) + .catch((error) => this.handleResponseError(error)); + } + /** + * Reject the invitation. + * + * @remarks + * Replies to the INVITE request with a 4xx, 5xx, or 6xx final response. + * Resolves once the response sent, otherwise rejects. + * + * The expectation is that this method is used to reject an INVITE request. + * That is indeed the case - a call to `progress` followed by `reject` is + * a typical way to "decline" an incoming INVITE request. However it may + * also be called after calling `accept` (but only before it completes) + * which will reject the call and cause `accept` to reject. + * @param options - Options bucket. + */ + reject(options = {}) { + this.logger.log("Invitation.reject"); + // validate state + if (this.state !== SessionState.Initial && this.state !== SessionState.Establishing) { + const error = new Error(`Invalid session state ${this.state}`); + this.logger.error(error.message); + return Promise.reject(error); + } + const statusCode = options.statusCode || 480; + const reasonPhrase = options.reasonPhrase ? options.reasonPhrase : getReasonPhrase(statusCode); + const extraHeaders = options.extraHeaders || []; + if (statusCode < 300 || statusCode > 699) { + throw new TypeError("Invalid statusCode: " + statusCode); + } + const body = options.body ? fromBodyLegacy(options.body) : undefined; + // FIXME: Need to redirect to someplace + statusCode < 400 + ? this.incomingInviteRequest.redirect([], { statusCode, reasonPhrase, extraHeaders, body }) + : this.incomingInviteRequest.reject({ statusCode, reasonPhrase, extraHeaders, body }); + this.stateTransition(SessionState.Terminated); + return Promise.resolve(); + } + /** + * Handle CANCEL request. + * + * @param message - CANCEL message. + * @internal + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _onCancel(message) { + this.logger.log("Invitation._onCancel"); + // validate state + if (this.state !== SessionState.Initial && this.state !== SessionState.Establishing) { + this.logger.error(`CANCEL received while in state ${this.state}, dropping request`); + return; + } + // flag canceled + this.isCanceled = true; + // reject INVITE with 487 status code + this.incomingInviteRequest.reject({ statusCode: 487 }); + this.stateTransition(SessionState.Terminated); + } + /** + * Helper function to handle offer/answer in a PRACK. + */ + handlePrackOfferAnswer(request) { + if (!this.dialog) { + throw new Error("Dialog undefined."); + } + // If the PRACK doesn't have an offer/answer, nothing to be done. + const body = getBody(request.message); + if (!body || body.contentDisposition !== "session") { + return Promise.resolve(undefined); + } + const options = { + sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, + sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers + }; + // 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 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 SignalingState.Stable: + // Receved answer. + return this.setAnswer(body, options).then(() => undefined); + case 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 SignalingState.HaveRemoteOffer: + // Received offer, generate answer. + return this.setOfferAndGetAnswer(body, options); + case SignalingState.Closed: + throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`); + default: + throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`); + } + } + /** + * A handler for errors which occur while attempting to send 1xx and 2xx responses. + * In all cases, an attempt is made to reject the request if it is still outstanding. + * And while there are a variety of things which can go wrong and we log something here + * for all errors, there are a handful of common exceptions we pay some extra attention to. + * @param error - The error which occurred. + */ + handleResponseError(error) { + let statusCode = 480; // "Temporarily Unavailable" + // Log Error message + if (error instanceof Error) { + this.logger.error(error.message); + } + else { + // We don't actually know what a session description handler implementation might throw our way, + // and more generally as a last resort catch all, just assume we are getting an "unknown" and log it. + this.logger.error(error); + } + // Log Exception message + if (error instanceof ContentTypeUnsupportedError) { + this.logger.error("A session description handler occurred while sending response (content type unsupported"); + statusCode = 415; // "Unsupported Media Type" + } + else if (error instanceof SessionDescriptionHandlerError) { + this.logger.error("A session description handler occurred while sending response"); + } + else if (error instanceof SessionTerminatedError) { + this.logger.error("Session ended before response could be formulated and sent (while waiting for PRACK)"); + } + else if (error instanceof TransactionStateError) { + this.logger.error("Session changed state before response could be formulated and sent"); + } + // Reject if still in "initial" or "establishing" state. + if (this.state === SessionState.Initial || this.state === SessionState.Establishing) { + try { + this.incomingInviteRequest.reject({ statusCode }); + this.stateTransition(SessionState.Terminated); + } + catch (e) { + this.logger.error("An error occurred attempting to reject the request while handling another error"); + throw e; // This is not a good place to be... + } + } + // FIXME: TODO: + // Here we are squelching the throwing of errors due to an 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 + // these race errors to the caller of `accept()`, we are squelching the throwing + // of ALL errors when/if they occur after receiving a CANCEL to catch the ONE we know + // is a "normal" exceptional condition. While this is a completely reasonable approach, + // the decision should be left up to the library user. Furthermore, as we are eating + // ALL errors in this case, we are potentially (likely) hiding "real" errors which occur. + // + // Only rethrow error if the session has not been canceled. + if (this.isCanceled) { + this.logger.warn("An error occurred while attempting to formulate and send a response to an incoming INVITE." + + " However a CANCEL was received and processed while doing so which can (and often does) result" + + " in errors occurring as the session terminates in the meantime. Said error is being ignored."); + return; + } + throw error; + } + /** + * Callback for when ACK for a 2xx response is never received. + * @param session - Session the ACK never arrived for. + */ + onAckTimeout() { + 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(SessionState.Terminated); + } + /** + * A version of `accept` which resolves a session when the 200 Ok response is sent. + * @param options - Options bucket. + */ + sendAccept() { + const responseOptions = { + sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, + sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers + }; + // 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.waitingForPrack) { + return this.waitForArrivalOfPrack() + .then(() => clearTimeout(this.userNoAnswerTimer)) // Ported + .then(() => this.generateResponseOfferAnswer(this.incomingInviteRequest, responseOptions)) + .then((body) => this.incomingInviteRequest.accept({ statusCode: 200, body })); + } + clearTimeout(this.userNoAnswerTimer); // Ported + return this.generateResponseOfferAnswer(this.incomingInviteRequest, responseOptions).then((body) => this.incomingInviteRequest.accept({ statusCode: 200, body })); + } + /** + * A version of `progress` which resolves when the provisional response is sent. + * @param options - Options bucket. + */ + sendProgress(options = {}) { + const statusCode = options.statusCode || 180; + const reasonPhrase = options.reasonPhrase; + const extraHeaders = (options.extraHeaders || []).slice(); + const body = options.body ? 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.sendProgressWithSDP(options); + } + try { + const progressResponse = this.incomingInviteRequest.progress({ statusCode, reasonPhrase, extraHeaders, body }); + 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. + */ + sendProgressWithSDP(options = {}) { + const responseOptions = { + sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, + sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers + }; + const statusCode = options.statusCode || 183; + const reasonPhrase = options.reasonPhrase; + const extraHeaders = (options.extraHeaders || []).slice(); + // Get an offer/answer and send a reply. + return this.generateResponseOfferAnswer(this.incomingInviteRequest, responseOptions) + .then((body) => this.incomingInviteRequest.progress({ statusCode, reasonPhrase, extraHeaders, body })) + .then((progressResponse) => { + this._dialog = progressResponse.session; + return progressResponse; + }); + } + /** + * A version of `progress` which resolves when the reliable provisional response is sent. + * @param options - Options bucket. + */ + sendProgressReliable(options = {}) { + options.extraHeaders = (options.extraHeaders || []).slice(); + options.extraHeaders.push("Require: 100rel"); + options.extraHeaders.push("RSeq: " + Math.floor(Math.random() * 10000)); + return this.sendProgressWithSDP(options); + } + /** + * A version of `progress` which resolves when the reliable provisional response is acknowledged. + * @param options - Options bucket. + */ + sendProgressReliableWaitForPrack(options = {}) { + const responseOptions = { + sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, + sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers + }; + const statusCode = options.statusCode || 183; + const reasonPhrase = options.reasonPhrase; + const extraHeaders = (options.extraHeaders || []).slice(); + extraHeaders.push("Require: 100rel"); + extraHeaders.push("RSeq: " + this.rseq++); + let body; + return new Promise((resolve, reject) => { + this.waitingForPrack = true; + this.generateResponseOfferAnswer(this.incomingInviteRequest, responseOptions) + .then((offerAnswer) => { + body = offerAnswer; + return this.incomingInviteRequest.progress({ statusCode, reasonPhrase, extraHeaders, body }); + }) + .then((progressResponse) => { + this._dialog = progressResponse.session; + let prackRequest; + let prackResponse; + progressResponse.session.delegate = { + onPrack: (request) => { + prackRequest = request; + // eslint-disable-next-line @typescript-eslint/no-use-before-define + clearTimeout(prackWaitTimeoutTimer); + // eslint-disable-next-line @typescript-eslint/no-use-before-define + clearTimeout(rel1xxRetransmissionTimer); + if (!this.waitingForPrack) { + return; + } + this.waitingForPrack = false; + this.handlePrackOfferAnswer(prackRequest) + .then((prackResponseBody) => { + try { + prackResponse = prackRequest.accept({ statusCode: 200, body: prackResponseBody }); + this.prackArrived(); + resolve({ prackRequest, prackResponse, progressResponse }); + } + catch (error) { + reject(error); + } + }) + .catch((error) => reject(error)); + } + }; + // https://tools.ietf.org/html/rfc3262#section-3 + const prackWaitTimeout = () => { + if (!this.waitingForPrack) { + return; + } + this.waitingForPrack = false; + this.logger.warn("No PRACK received, rejecting INVITE."); + // eslint-disable-next-line @typescript-eslint/no-use-before-define + clearTimeout(rel1xxRetransmissionTimer); + this.reject({ statusCode: 504 }) + .then(() => reject(new SessionTerminatedError())) + .catch((error) => reject(error)); + }; + const prackWaitTimeoutTimer = setTimeout(prackWaitTimeout, Timers.T1 * 64); + // https://tools.ietf.org/html/rfc3262#section-3 + const rel1xxRetransmission = () => { + try { + this.incomingInviteRequest.progress({ statusCode, reasonPhrase, extraHeaders, body }); + } + catch (error) { + this.waitingForPrack = false; + reject(error); + return; + } + // eslint-disable-next-line @typescript-eslint/no-use-before-define + rel1xxRetransmissionTimer = setTimeout(rel1xxRetransmission, (timeout *= 2)); + }; + let timeout = Timers.T1; + let rel1xxRetransmissionTimer = setTimeout(rel1xxRetransmission, timeout); + }) + .catch((error) => { + this.waitingForPrack = false; + reject(error); + }); + }); + } + /** + * A version of `progress` which resolves when a 100 Trying provisional response is sent. + */ + sendProgressTrying() { + try { + const progressResponse = this.incomingInviteRequest.trying(); + return Promise.resolve(progressResponse); + } + catch (error) { + return Promise.reject(error); + } + } + /** + * When attempting to accept the INVITE, an invitation waits + * for any outstanding PRACK to arrive before sending the 200 Ok. + * It will be waiting on this Promise to resolve which lets it know + * the PRACK has arrived and it may proceed to send the 200 Ok. + */ + waitForArrivalOfPrack() { + if (this.waitingForPrackPromise) { + throw new Error("Already waiting for PRACK"); + } + this.waitingForPrackPromise = new Promise((resolve, reject) => { + this.waitingForPrackResolve = resolve; + this.waitingForPrackReject = reject; + }); + return this.waitingForPrackPromise; + } + /** + * Here we are resolving the promise which in turn will cause + * the accept to proceed (it may still fail for other reasons, but...). + */ + prackArrived() { + if (this.waitingForPrackResolve) { + this.waitingForPrackResolve(); + } + this.waitingForPrackPromise = undefined; + this.waitingForPrackResolve = undefined; + this.waitingForPrackReject = undefined; + } + /** + * Here we are rejecting the promise which in turn will cause + * the accept to fail and the session to transition to "terminated". + */ + prackNeverArrived() { + if (this.waitingForPrackReject) { + this.waitingForPrackReject(new SessionTerminatedError()); + } + this.waitingForPrackPromise = undefined; + this.waitingForPrackResolve = undefined; + this.waitingForPrackReject = undefined; + } +} diff --git a/lib/api/inviter-cancel-options.d.ts b/lib/api/inviter-cancel-options.d.ts new file mode 100644 index 000000000..1eee02922 --- /dev/null +++ b/lib/api/inviter-cancel-options.d.ts @@ -0,0 +1,10 @@ +/** + * 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 new file mode 100644 index 000000000..720656225 --- /dev/null +++ b/lib/api/inviter-cancel-options.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"inviter-cancel-options.d.ts","sourceRoot":"","sources":["../../src/api/inviter-cancel-options.ts"],"names":[],"mappings":"AAAA;;;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 new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/api/inviter-cancel-options.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/api/inviter-invite-options.d.ts b/lib/api/inviter-invite-options.d.ts new file mode 100644 index 000000000..0fab0afa4 --- /dev/null +++ b/lib/api/inviter-invite-options.d.ts @@ -0,0 +1,29 @@ +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; + /** + * Modifiers to pass to SessionDescriptionHandler during the initial INVITE transaction. + */ + sessionDescriptionHandlerModifiers?: Array; + /** + * Options to pass to SessionDescriptionHandler during the initial INVITE transaction. + */ + 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 new file mode 100644 index 000000000..7f153f7e3 --- /dev/null +++ b/lib/api/inviter-invite-options.d.ts.map @@ -0,0 +1 @@ +{"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,EAAE,iCAAiC,EAAE,gCAAgC,EAAE,MAAM,+BAA+B,CAAC;AAEpH;;;GAGG;AACH,MAAM,WAAW,oBAAoB;IACnC;;OAEG;IACH,eAAe,CAAC,EAAE,uBAAuB,CAAC;IAC1C;;OAEG;IACH,cAAc,CAAC,EAAE,cAAc,CAAC;IAChC;;OAEG;IACH,kCAAkC,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,CAAC;IAC9E;;OAEG;IACH,gCAAgC,CAAC,EAAE,gCAAgC,CAAC;IACpE;;OAEG;IACH,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 new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/api/inviter-invite-options.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/api/inviter-options.d.ts b/lib/api/inviter-options.d.ts new file mode 100644 index 000000000..4cda297bd --- /dev/null +++ b/lib/api/inviter-options.d.ts @@ -0,0 +1,44 @@ +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; + /** + * 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 `inviteWithoutSdp` 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. */ + 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 during the initial INVITE transaction. */ + sessionDescriptionHandlerModifiers?: Array; + /** Options to pass to SessionDescriptionHandler during the initial INVITE transaction. */ + sessionDescriptionHandlerOptions?: SessionDescriptionHandlerOptions; + /** Modifiers to pass to SessionDescriptionHandler during re-INVITE transactions. */ + sessionDescriptionHandlerModifiersReInvite?: Array; + /** Options to pass to SessionDescriptionHandler during re-INVITE transactions. */ + sessionDescriptionHandlerOptionsReInvite?: 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 new file mode 100644 index 000000000..9d3d205f8 --- /dev/null +++ b/lib/api/inviter-options.d.ts.map @@ -0,0 +1 @@ +{"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;;;;;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;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,4FAA4F;IAC5F,kCAAkC,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,CAAC;IAC9E,0FAA0F;IAC1F,gCAAgC,CAAC,EAAE,gCAAgC,CAAC;IACpE,oFAAoF;IACpF,0CAA0C,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,CAAC;IACtF,kFAAkF;IAClF,wCAAwC,CAAC,EAAE,gCAAgC,CAAC;CAC7E"} \ No newline at end of file diff --git a/lib/api/inviter-options.js b/lib/api/inviter-options.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/api/inviter-options.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/api/inviter.d.ts b/lib/api/inviter.d.ts new file mode 100644 index 000000000..14d7fa100 --- /dev/null +++ b/lib/api/inviter.d.ts @@ -0,0 +1,237 @@ +import { Logger, 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 { + /** + * If this Inviter was created as a result of a REFER, the referred Session. Otherwise undefined. + * @internal + */ + _referred: Session | undefined; + /** + * Logger. + */ + protected logger: Logger; + /** @internal */ + protected _id: string; + /** True if dispose() has been called. */ + private disposed; + /** True if early media use is enabled. */ + private earlyMedia; + /** The early media session. */ + private earlyMediaDialog; + /** The early media session description handlers. */ + private earlyMediaSessionDescriptionHandlers; + /** Our From tag. */ + private fromTag; + /** True if cancel() was called. */ + private isCanceled; + /** True if initial INVITE without SDP. */ + private inviteWithoutSdp; + /** Initial INVITE request sent by core. Undefined until sent. */ + private outgoingInviteRequest; + /** Initial INVITE message provided to core to send. */ + private outgoingRequestMessage; + /** + * 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); + /** + * Destructor. + */ + dispose(): Promise; + /** + * Initial outgoing INVITE request message body. + */ + get body(): BodyAndContentType | undefined; + /** + * The identity of the local user. + */ + get localIdentity(): NameAddrHeader; + /** + * The identity of the remote user. + */ + get remoteIdentity(): NameAddrHeader; + /** + * Initial outgoing INVITE request message. + */ + get request(): OutgoingRequestMessage; + /** + * Cancels the INVITE request. + * + * @remarks + * Sends a CANCEL request. + * Resolves once the response sent, otherwise rejects. + * + * After sending a CANCEL request the expectation is that a 487 final response + * will be received for the INVITE. However a 200 final response to the INVITE + * may nonetheless arrive (it's a race between the CANCEL reaching the UAS before + * the UAS sends a 200) in which case an ACK & BYE will be sent. The net effect + * is that this method will terminate the session regardless of the race. + * @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 behavior 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 behavior 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 new file mode 100644 index 000000000..5bcdb3084 --- /dev/null +++ b/lib/api/inviter.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"inviter.d.ts","sourceRoot":"","sources":["../../src/api/inviter.ts"],"names":[],"mappings":"AAAA,OAAO,EAML,MAAM,EACN,cAAc,EACd,qBAAqB,EACrB,sBAAsB,EAMtB,GAAG,EACJ,MAAM,SAAS,CAAC;AAEjB,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,EAAE,kBAAkB,EAA6B,MAAM,+BAA+B,CAAC;AAE9F,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAGzC;;;GAGG;AACH,qBAAa,OAAQ,SAAQ,OAAO;IAClC;;;OAGG;IACI,SAAS,EAAE,OAAO,GAAG,SAAS,CAAC;IAEtC;;OAEG;IACH,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC;IAEzB,gBAAgB;IAChB,SAAS,CAAC,GAAG,EAAE,MAAM,CAAC;IAEtB,yCAAyC;IACzC,OAAO,CAAC,QAAQ,CAAS;IACzB,0CAA0C;IAC1C,OAAO,CAAC,UAAU,CAAS;IAC3B,+BAA+B;IAC/B,OAAO,CAAC,gBAAgB,CAA4B;IACpD,oDAAoD;IACpD,OAAO,CAAC,oCAAoC,CAAgD;IAC5F,oBAAoB;IACpB,OAAO,CAAC,OAAO,CAAS;IACxB,mCAAmC;IACnC,OAAO,CAAC,UAAU,CAAS;IAC3B,0CAA0C;IAC1C,OAAO,CAAC,gBAAgB,CAAS;IACjC,iEAAiE;IACjE,OAAO,CAAC,qBAAqB,CAAoC;IACjE,uDAAuD;IACvD,OAAO,CAAC,sBAAsB,CAAyB;IAEvD;;;;;OAKG;gBACgB,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,GAAG,EAAE,OAAO,GAAE,cAAmB;IA0HrF;;OAEG;IACI,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IA+B/B;;OAEG;IACH,IAAW,IAAI,IAAI,kBAAkB,GAAG,SAAS,CAEhD;IAED;;OAEG;IACH,IAAW,aAAa,IAAI,cAAc,CAEzC;IAED;;OAEG;IACH,IAAW,cAAc,IAAI,cAAc,CAE1C;IAED;;OAEG;IACH,IAAW,OAAO,IAAI,sBAAsB,CAE3C;IAED;;;;;;;;;;;;;OAaG;IACI,MAAM,CAAC,OAAO,GAAE,oBAAyB,GAAG,OAAO,CAAC,IAAI,CAAC;IA0ChE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAmFG;IACI,MAAM,CAAC,OAAO,GAAE,oBAAyB,GAAG,OAAO,CAAC,qBAAqB,CAAC;IAkDjF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAsCG;IACH,OAAO,CAAC,UAAU;IAkPlB,OAAO,CAAC,iBAAiB;IAOzB,OAAO,CAAC,aAAa;IA+CrB;;;OAGG;IACH,OAAO,CAAC,QAAQ;IAgJhB;;;OAGG;IACH,OAAO,CAAC,UAAU;IA+IlB;;;OAGG;IAEH,OAAO,CAAC,UAAU;IAalB;;;OAGG;IAEH,OAAO,CAAC,QAAQ;IAahB;;;OAGG;IAEH,OAAO,CAAC,QAAQ;CASjB"} \ No newline at end of file diff --git a/lib/api/inviter.js b/lib/api/inviter.js new file mode 100644 index 000000000..39669bcdb --- /dev/null +++ b/lib/api/inviter.js @@ -0,0 +1,977 @@ +import { C, Grammar, SignalingState } from "../core"; +import { getReasonPhrase, newTag } from "../core/messages/utils"; +import { Session } from "./session"; +import { SessionState } from "./session-state"; +import { SIPExtension } from "./user-agent-options"; +/** + * An inviter offers to establish a {@link Session} (outgoing INVITE). + * @public + */ +export class Inviter extends Session { + /** + * 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, targetURI, options = {}) { + super(userAgent, options); + /** True if dispose() has been called. */ + this.disposed = false; + /** True if early media use is enabled. */ + this.earlyMedia = false; + /** The early media session description handlers. */ + this.earlyMediaSessionDescriptionHandlers = new Map(); + /** True if cancel() was called. */ + this.isCanceled = false; + /** True if initial INVITE without SDP. */ + this.inviteWithoutSdp = false; + this.logger = userAgent.getLogger("sip.Inviter"); + // Early media + this.earlyMedia = options.earlyMedia !== undefined ? options.earlyMedia : this.earlyMedia; + // From tag + this.fromTag = newTag(); + // Invite without SDP + this.inviteWithoutSdp = options.inviteWithoutSdp !== undefined ? options.inviteWithoutSdp : this.inviteWithoutSdp; + // Inviter options (could do better copying these options) + const inviterOptions = Object.assign({}, options); + inviterOptions.params = Object.assign({}, options.params); + // Anonymous call + const anonymous = options.anonymous || false; + // Contact + const contact = userAgent.contact.toString({ + anonymous, + // Do not add ;ob in initial forming dialog requests if the + // registration over the current connection got a GRUU URI. + outbound: anonymous ? !userAgent.contact.tempGruu : !userAgent.contact.pubGruu + }); + // FIXME: TODO: We should not be parsing URIs here as if it fails we have to throw an exception + // which is not something we want our constructor to do. URIs should be passed in as params. + // URIs + if (anonymous && userAgent.configuration.uri) { + inviterOptions.params.fromDisplayName = "Anonymous"; + inviterOptions.params.fromUri = "sip:anonymous@anonymous.invalid"; + } + let fromURI = userAgent.userAgentCore.configuration.aor; + if (inviterOptions.params.fromUri) { + fromURI = + typeof inviterOptions.params.fromUri === "string" + ? Grammar.URIParse(inviterOptions.params.fromUri) + : inviterOptions.params.fromUri; + } + if (!fromURI) { + throw new TypeError("Invalid from URI: " + inviterOptions.params.fromUri); + } + let toURI = targetURI; + if (inviterOptions.params.toUri) { + toURI = + typeof inviterOptions.params.toUri === "string" + ? Grammar.URIParse(inviterOptions.params.toUri) + : inviterOptions.params.toUri; + } + if (!toURI) { + throw new TypeError("Invalid to URI: " + inviterOptions.params.toUri); + } + // Params + const messageOptions = Object.assign({}, inviterOptions.params); + messageOptions.fromTag = this.fromTag; + // Extra headers + const extraHeaders = (inviterOptions.extraHeaders || []).slice(); + if (anonymous && userAgent.configuration.uri) { + extraHeaders.push("P-Preferred-Identity: " + userAgent.configuration.uri.toString()); + extraHeaders.push("Privacy: id"); + } + extraHeaders.push("Contact: " + contact); + extraHeaders.push("Allow: " + ["ACK", "CANCEL", "INVITE", "MESSAGE", "BYE", "OPTIONS", "INFO", "NOTIFY", "REFER"].toString()); + if (userAgent.configuration.sipExtension100rel === SIPExtension.Required) { + extraHeaders.push("Require: 100rel"); + } + if (userAgent.configuration.sipExtensionReplaces === SIPExtension.Required) { + extraHeaders.push("Require: replaces"); + } + inviterOptions.extraHeaders = extraHeaders; + // Body + const body = undefined; + // Make initial outgoing request message + this.outgoingRequestMessage = userAgent.userAgentCore.makeOutgoingRequestMessage(C.INVITE, targetURI, fromURI, toURI, messageOptions, extraHeaders, body); + // Session parent properties + this._contact = contact; + this._referralInviterOptions = inviterOptions; + this._renderbody = options.renderbody; + this._rendertype = options.rendertype; + // Modifiers and options for initial INVITE transaction + if (options.sessionDescriptionHandlerModifiers) { + this.sessionDescriptionHandlerModifiers = options.sessionDescriptionHandlerModifiers; + } + if (options.sessionDescriptionHandlerOptions) { + this.sessionDescriptionHandlerOptions = options.sessionDescriptionHandlerOptions; + } + // Modifiers and options for re-INVITE transactions + if (options.sessionDescriptionHandlerModifiersReInvite) { + this.sessionDescriptionHandlerModifiersReInvite = options.sessionDescriptionHandlerModifiersReInvite; + } + if (options.sessionDescriptionHandlerOptionsReInvite) { + this.sessionDescriptionHandlerOptionsReInvite = options.sessionDescriptionHandlerOptionsReInvite; + } + // Identifier + this._id = this.outgoingRequestMessage.callId + this.fromTag; + // Add to the user agent's session collection. + this.userAgent._sessions[this._id] = this; + } + /** + * Destructor. + */ + dispose() { + // Only run through this once. It can and does get called multiple times + // depending on the what the sessions state is when first called. + // For example, if called when "establishing" it will be called again + // at least once when the session transitions to "terminated". + // Regardless, running through this more than once is pointless. + if (this.disposed) { + return Promise.resolve(); + } + this.disposed = true; + // Dispose of early dialog media + this.disposeEarlyMedia(); + // If the final response for the initial INVITE not yet been received, cancel it + switch (this.state) { + case SessionState.Initial: + return this.cancel().then(() => super.dispose()); + case SessionState.Establishing: + return this.cancel().then(() => super.dispose()); + case SessionState.Established: + return super.dispose(); + case SessionState.Terminating: + return super.dispose(); + case SessionState.Terminated: + return super.dispose(); + default: + throw new Error("Unknown state."); + } + } + /** + * Initial outgoing INVITE request message body. + */ + get body() { + return this.outgoingRequestMessage.body; + } + /** + * The identity of the local user. + */ + get localIdentity() { + return this.outgoingRequestMessage.from; + } + /** + * The identity of the remote user. + */ + get remoteIdentity() { + return this.outgoingRequestMessage.to; + } + /** + * Initial outgoing INVITE request message. + */ + get request() { + return this.outgoingRequestMessage; + } + /** + * Cancels the INVITE request. + * + * @remarks + * Sends a CANCEL request. + * Resolves once the response sent, otherwise rejects. + * + * After sending a CANCEL request the expectation is that a 487 final response + * will be received for the INVITE. However a 200 final response to the INVITE + * may nonetheless arrive (it's a race between the CANCEL reaching the UAS before + * the UAS sends a 200) in which case an ACK & BYE will be sent. The net effect + * is that this method will terminate the session regardless of the race. + * @param options - Options bucket. + */ + cancel(options = {}) { + this.logger.log("Inviter.cancel"); + // validate state + if (this.state !== SessionState.Initial && this.state !== SessionState.Establishing) { + const error = new Error(`Invalid session state ${this.state}`); + this.logger.error(error.message); + return Promise.reject(error); + } + // flag canceled + this.isCanceled = true; + // transition state + this.stateTransition(SessionState.Terminating); + // helper function + function getCancelReason(code, reason) { + if ((code && code < 200) || code > 699) { + throw new TypeError("Invalid statusCode: " + code); + } + else if (code) { + const cause = code; + const text = getReasonPhrase(code) || reason; + return "SIP;cause=" + cause + ';text="' + text + '"'; + } + } + if (this.outgoingInviteRequest) { + // the CANCEL may not be respected by peer(s), so don't transition to terminated + let cancelReason; + if (options.statusCode && options.reasonPhrase) { + cancelReason = getCancelReason(options.statusCode, options.reasonPhrase); + } + this.outgoingInviteRequest.cancel(cancelReason, options); + } + else { + this.logger.warn("Canceled session before INVITE was sent"); + this.stateTransition(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 behavior 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 behavior of the SIP + * servers being utilized is configured to disallow forking. + */ + invite(options = {}) { + this.logger.log("Inviter.invite"); + // validate state + if (this.state !== SessionState.Initial) { + // re-invite + return super.invite(options); + } + // Modifiers and options for initial INVITE transaction + if (options.sessionDescriptionHandlerModifiers) { + this.sessionDescriptionHandlerModifiers = options.sessionDescriptionHandlerModifiers; + } + if (options.sessionDescriptionHandlerOptions) { + this.sessionDescriptionHandlerOptions = options.sessionDescriptionHandlerOptions; + } + // just send an INVITE with no sdp... + if (options.withoutSdp || this.inviteWithoutSdp) { + if (this._renderbody && this._rendertype) { + this.outgoingRequestMessage.body = { contentType: this._rendertype, body: this._renderbody }; + } + // transition state + this.stateTransition(SessionState.Establishing); + return Promise.resolve(this.sendInvite(options)); + } + // get an offer and send it in an INVITE + const offerOptions = { + sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers, + sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions + }; + return this.getOffer(offerOptions) + .then((body) => { + this.outgoingRequestMessage.body = { body: body.content, contentType: body.contentType }; + // transition state + this.stateTransition(SessionState.Establishing); + return this.sendInvite(options); + }) + .catch((error) => { + this.logger.log(error.message); + this.stateTransition(SessionState.Terminated); + 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 + */ + sendInvite(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 + // 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 environments 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.outgoingRequestMessage, { + onAccept: (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(SessionState.Terminated); + return; + } + this.notifyReferer(inviteResponse); + this.onAccept(inviteResponse) + .then(() => { + this.disposeEarlyMedia(); + }) + .catch(() => { + this.disposeEarlyMedia(); + }) + .then(() => { + if (options.requestDelegate && options.requestDelegate.onAccept) { + options.requestDelegate.onAccept(inviteResponse); + } + }); + }, + onProgress: (inviteResponse) => { + // If the user requested cancellation, ignore response. + if (this.isCanceled) { + return; + } + this.notifyReferer(inviteResponse); + this.onProgress(inviteResponse) + .catch(() => { + this.disposeEarlyMedia(); + }) + .then(() => { + if (options.requestDelegate && options.requestDelegate.onProgress) { + options.requestDelegate.onProgress(inviteResponse); + } + }); + }, + onRedirect: (inviteResponse) => { + this.notifyReferer(inviteResponse); + this.onRedirect(inviteResponse); + if (options.requestDelegate && options.requestDelegate.onRedirect) { + options.requestDelegate.onRedirect(inviteResponse); + } + }, + onReject: (inviteResponse) => { + this.notifyReferer(inviteResponse); + this.onReject(inviteResponse); + if (options.requestDelegate && options.requestDelegate.onReject) { + options.requestDelegate.onReject(inviteResponse); + } + }, + onTrying: (inviteResponse) => { + this.notifyReferer(inviteResponse); + this.onTrying(inviteResponse); + if (options.requestDelegate && options.requestDelegate.onTrying) { + options.requestDelegate.onTrying(inviteResponse); + } + } + }); + return this.outgoingInviteRequest; + } + disposeEarlyMedia() { + this.earlyMediaSessionDescriptionHandlers.forEach((sessionDescriptionHandler) => { + sessionDescriptionHandler.close(); + }); + this.earlyMediaSessionDescriptionHandlers.clear(); + } + notifyReferer(response) { + if (!this._referred) { + return; + } + if (!(this._referred instanceof 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."); + } + const statusCode = response.message.statusCode; + const reasonPhrase = response.message.reasonPhrase; + const body = `SIP/2.0 ${statusCode} ${reasonPhrase}`.trim(); + const 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: () => { + this._referred = undefined; + } + }; + } + /** + * Handle final response to initial INVITE. + * @param inviteResponse - 2xx response. + */ + onAccept(inviteResponse) { + this.logger.log("Inviter.onAccept"); + // validate state + if (this.state !== SessionState.Establishing) { + this.logger.error(`Accept received while in state ${this.state}, dropping response`); + return Promise.reject(new Error(`Invalid session state ${this.state}`)); + } + const response = inviteResponse.message; + const session = inviteResponse.session; + // Ported behavior. + if (response.hasHeader("P-Asserted-Identity")) { + this._assertedIdentity = Grammar.nameAddrHeaderParse(response.getHeader("P-Asserted-Identity")); + } + // We have a confirmed dialog. + session.delegate = { + onAck: (ackRequest) => this.onAckRequest(ackRequest), + onBye: (byeRequest) => this.onByeRequest(byeRequest), + onInfo: (infoRequest) => this.onInfoRequest(infoRequest), + onInvite: (inviteRequest) => this.onInviteRequest(inviteRequest), + onMessage: (messageRequest) => this.onMessageRequest(messageRequest), + onNotify: (notifyRequest) => this.onNotifyRequest(notifyRequest), + onPrack: (prackRequest) => this.onPrackRequest(prackRequest), + onRefer: (referRequest) => this.onReferRequest(referRequest) + }; + this._dialog = session; + switch (session.signalingState) { + case SignalingState.Initial: + // INVITE without offer, so MUST have offer at this point, so invalid state. + this.logger.error("Received 2xx response to INVITE without a session description"); + this.ackAndBye(inviteResponse, 400, "Missing session description"); + this.stateTransition(SessionState.Terminated); + return Promise.reject(new Error("Bad Media Description")); + case SignalingState.HaveLocalOffer: + // INVITE with offer, so MUST have answer at this point, so invalid state. + this.logger.error("Received 2xx response to INVITE without a session description"); + this.ackAndBye(inviteResponse, 400, "Missing session description"); + this.stateTransition(SessionState.Terminated); + return Promise.reject(new Error("Bad Media Description")); + case 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}.`); + } + const options = { + sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers, + sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions + }; + return this.setOfferAndGetAnswer(this._dialog.offer, options) + .then((body) => { + inviteResponse.ack({ body }); + this.stateTransition(SessionState.Established); + }) + .catch((error) => { + this.ackAndBye(inviteResponse, 488, "Invalid session description"); + this.stateTransition(SessionState.Terminated); + throw error; + }); + } + case SignalingState.Stable: { + // If INVITE without offer and we have already completed the initial exchange. + if (this.earlyMediaSessionDescriptionHandlers.size > 0) { + const sdh = this.earlyMediaSessionDescriptionHandlers.get(session.id); + if (!sdh) { + throw new Error("Session description handler undefined."); + } + this.setSessionDescriptionHandler(sdh); + this.earlyMediaSessionDescriptionHandlers.delete(session.id); + inviteResponse.ack(); + this.stateTransition(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) { + const 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 behavior 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); + } + const 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.stateTransition(SessionState.Terminated); + return Promise.reject(error); + } + // Otherwise we are good to go. + inviteResponse.ack(); + this.stateTransition(SessionState.Established); + return Promise.resolve(); + } + // If INVITE with offer and we have been waiting till now to apply the answer. + const answer = session.answer; + if (!answer) { + throw new Error("Answer is undefined."); + } + const options = { + sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers, + sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions + }; + return this.setAnswer(answer, options) + .then(() => { + // This session has completed an initial offer/answer exchange... + let ackOptions; + if (this._renderbody && this._rendertype) { + ackOptions = { + body: { contentDisposition: "render", contentType: this._rendertype, content: this._renderbody } + }; + } + inviteResponse.ack(ackOptions); + this.stateTransition(SessionState.Established); + }) + .catch((error) => { + this.logger.error(error.message); + this.ackAndBye(inviteResponse, 488, "Not Acceptable Here"); + this.stateTransition(SessionState.Terminated); + throw error; + }); + } + case 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. + */ + onProgress(inviteResponse) { + var _a; + this.logger.log("Inviter.onProgress"); + // validate state + if (this.state !== 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."); + } + const response = inviteResponse.message; + const session = inviteResponse.session; + // Ported - Set assertedIdentity. + if (response.hasHeader("P-Asserted-Identity")) { + this._assertedIdentity = 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 + const requireHeader = response.getHeader("require"); + const rseqHeader = response.getHeader("rseq"); + const rseq = requireHeader && requireHeader.includes("100rel") && rseqHeader ? Number(rseqHeader) : undefined; + const responseReliable = !!rseq; + const extraHeaders = []; + if (responseReliable) { + extraHeaders.push("RAck: " + response.getHeader("rseq") + " " + response.getHeader("cseq")); + } + switch (session.signalingState) { + case 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 }); + } + return Promise.resolve(); + case SignalingState.HaveLocalOffer: + // INVITE with offer and session only has that initial local offer. + if (responseReliable) { + inviteResponse.prack({ extraHeaders }); + } + return Promise.resolve(); + case 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 + const sdh = this.sessionDescriptionHandlerFactory(this, this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions || {}); + if ((_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onSessionDescriptionHandler) { + this.delegate.onSessionDescriptionHandler(sdh, true); + } + this.earlyMediaSessionDescriptionHandlers.set(session.id, sdh); + return sdh + .setDescription(response.body, this.sessionDescriptionHandlerOptions, this.sessionDescriptionHandlerModifiers) + .then(() => sdh.getDescription(this.sessionDescriptionHandlerOptions, this.sessionDescriptionHandlerModifiers)) + .then((description) => { + const body = { + contentDisposition: "session", + contentType: description.contentType, + content: description.body + }; + inviteResponse.prack({ extraHeaders, body }); + }) + .catch((error) => { + this.stateTransition(SessionState.Terminated); + throw error; + }); + } + case 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 }); + } + if (this.earlyMedia && !this.earlyMediaDialog) { + this.earlyMediaDialog = session; + const answer = session.answer; + if (!answer) { + throw new Error("Answer is undefined."); + } + const options = { + sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers, + sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions + }; + return this.setAnswer(answer, options).catch((error) => { + this.stateTransition(SessionState.Terminated); + throw error; + }); + } + return Promise.resolve(); + case 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. + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onRedirect(inviteResponse) { + this.logger.log("Inviter.onRedirect"); + // validate state + if (this.state !== SessionState.Establishing && this.state !== SessionState.Terminating) { + this.logger.error(`Redirect received while in state ${this.state}, dropping response`); + return; + } + // transition state + this.stateTransition(SessionState.Terminated); + } + /** + * Handle final response to initial INVITE. + * @param inviteResponse - 4xx, 5xx, or 6xx response. + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onReject(inviteResponse) { + this.logger.log("Inviter.onReject"); + // validate state + if (this.state !== SessionState.Establishing && this.state !== SessionState.Terminating) { + this.logger.error(`Reject received while in state ${this.state}, dropping response`); + return; + } + // transition state + this.stateTransition(SessionState.Terminated); + } + /** + * Handle final response to initial INVITE. + * @param inviteResponse - 100 response. + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onTrying(inviteResponse) { + this.logger.log("Inviter.onTrying"); + // validate state + if (this.state !== SessionState.Establishing) { + this.logger.error(`Trying received while in state ${this.state}, dropping response`); + return; + } + } +} diff --git a/lib/api/message.d.ts b/lib/api/message.d.ts new file mode 100644 index 000000000..1ceb4b121 --- /dev/null +++ b/lib/api/message.d.ts @@ -0,0 +1,17 @@ +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. */ + get 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 new file mode 100644 index 000000000..156007f5d --- /dev/null +++ b/lib/api/message.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"message.d.ts","sourceRoot":"","sources":["../../src/api/message.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,sBAAsB,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAE1F;;;GAGG;AACH,qBAAa,OAAO;IAEC,OAAO,CAAC,sBAAsB;IADjD,gBAAgB;gBACW,sBAAsB,EAAE,sBAAsB;IAEzE,wCAAwC;IACxC,IAAW,OAAO,IAAI,sBAAsB,CAE3C;IAED,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 new file mode 100644 index 000000000..d65d1d0ed --- /dev/null +++ b/lib/api/message.js @@ -0,0 +1,24 @@ +/** + * A received message (incoming MESSAGE). + * @public + */ +export class Message { + /** @internal */ + constructor(incomingMessageRequest) { + this.incomingMessageRequest = incomingMessageRequest; + } + /** Incoming MESSAGE request message. */ + get request() { + return this.incomingMessageRequest.message; + } + /** Accept the request. */ + accept(options) { + this.incomingMessageRequest.accept(options); + return Promise.resolve(); + } + /** Reject the request. */ + reject(options) { + this.incomingMessageRequest.reject(options); + return Promise.resolve(); + } +} diff --git a/lib/api/messager-message-options.d.ts b/lib/api/messager-message-options.d.ts new file mode 100644 index 000000000..7a83a61b8 --- /dev/null +++ b/lib/api/messager-message-options.d.ts @@ -0,0 +1,12 @@ +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 new file mode 100644 index 000000000..5806244a8 --- /dev/null +++ b/lib/api/messager-message-options.d.ts.map @@ -0,0 +1 @@ +{"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 new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/api/messager-message-options.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/api/messager-options.d.ts b/lib/api/messager-options.d.ts new file mode 100644 index 000000000..2d2251208 --- /dev/null +++ b/lib/api/messager-options.d.ts @@ -0,0 +1,18 @@ +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 new file mode 100644 index 000000000..48d8e72b9 --- /dev/null +++ b/lib/api/messager-options.d.ts.map @@ -0,0 +1 @@ +{"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 new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/api/messager-options.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/api/messager.d.ts b/lib/api/messager.d.ts new file mode 100644 index 000000000..2cf076e2e --- /dev/null +++ b/lib/api/messager.d.ts @@ -0,0 +1,27 @@ +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 { + private logger; + private request; + private userAgent; + /** + * 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); + /** + * 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 new file mode 100644 index 000000000..34d2136ca --- /dev/null +++ b/lib/api/messager.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"messager.d.ts","sourceRoot":"","sources":["../../src/api/messager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAoD,GAAG,EAAE,MAAM,SAAS,CAAC;AAChF,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,QAAQ;IACnB,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,OAAO,CAAyB;IACxC,OAAO,CAAC,SAAS,CAAY;IAE7B;;;;;;;OAOG;gBAED,SAAS,EAAE,SAAS,EACpB,SAAS,EAAE,GAAG,EACd,OAAO,EAAE,MAAM,EACf,WAAW,SAAe,EAC1B,OAAO,GAAE,eAAoB;IAsD/B;;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 new file mode 100644 index 000000000..72f55690c --- /dev/null +++ b/lib/api/messager.js @@ -0,0 +1,59 @@ +import { C, Grammar } from "../core"; +/** + * A messager sends a {@link Message} (outgoing MESSAGE). + * @public + */ +export class Messager { + /** + * 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, targetURI, content, contentType = "text/plain", options = {}) { + // Logger + this.logger = userAgent.getLogger("sip.Messager"); + // Default options params + options.params = options.params || {}; + // URIs + let fromURI = userAgent.userAgentCore.configuration.aor; + if (options.params.fromUri) { + fromURI = + typeof options.params.fromUri === "string" ? Grammar.URIParse(options.params.fromUri) : options.params.fromUri; + } + if (!fromURI) { + throw new TypeError("Invalid from URI: " + options.params.fromUri); + } + let toURI = targetURI; + if (options.params.toUri) { + toURI = typeof options.params.toUri === "string" ? Grammar.URIParse(options.params.toUri) : options.params.toUri; + } + if (!toURI) { + throw new TypeError("Invalid to URI: " + options.params.toUri); + } + // Message params + const params = options.params ? Object.assign({}, options.params) : {}; + // Extra headers + const extraHeaders = (options.extraHeaders || []).slice(); + // Body + const contentDisposition = "render"; + const body = { + contentDisposition, + contentType, + content + }; + // Build the request + this.request = userAgent.userAgentCore.makeOutgoingRequestMessage(C.MESSAGE, targetURI, fromURI, toURI, params, extraHeaders, body); + // User agent + this.userAgent = userAgent; + } + /** + * Send the message. + */ + message(options = {}) { + this.userAgent.userAgentCore.request(this.request, options.requestDelegate); + return Promise.resolve(); + } +} diff --git a/lib/api/notification.d.ts b/lib/api/notification.d.ts new file mode 100644 index 000000000..3290d6f60 --- /dev/null +++ b/lib/api/notification.d.ts @@ -0,0 +1,17 @@ +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. */ + get 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 new file mode 100644 index 000000000..823e6118a --- /dev/null +++ b/lib/api/notification.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"notification.d.ts","sourceRoot":"","sources":["../../src/api/notification.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,sBAAsB,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAEzF;;;GAGG;AACH,qBAAa,YAAY;IAEJ,OAAO,CAAC,qBAAqB;IADhD,gBAAgB;gBACW,qBAAqB,EAAE,qBAAqB;IAEvE,uCAAuC;IACvC,IAAW,OAAO,IAAI,sBAAsB,CAE3C;IAED,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 new file mode 100644 index 000000000..a86924254 --- /dev/null +++ b/lib/api/notification.js @@ -0,0 +1,24 @@ +/** + * A notification of an event (incoming NOTIFY). + * @public + */ +export class Notification { + /** @internal */ + constructor(incomingNotifyRequest) { + this.incomingNotifyRequest = incomingNotifyRequest; + } + /** Incoming NOTIFY request message. */ + get request() { + return this.incomingNotifyRequest.message; + } + /** Accept the request. */ + accept(options) { + this.incomingNotifyRequest.accept(options); + return Promise.resolve(); + } + /** Reject the request. */ + reject(options) { + this.incomingNotifyRequest.reject(options); + return Promise.resolve(); + } +} diff --git a/lib/api/notifier.d.ts b/lib/api/notifier.d.ts new file mode 100644 index 000000000..feb606737 --- /dev/null +++ b/lib/api/notifier.d.ts @@ -0,0 +1,9 @@ +/** + * 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 new file mode 100644 index 000000000..f65c5e841 --- /dev/null +++ b/lib/api/notifier.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"notifier.d.ts","sourceRoot":"","sources":["../../src/api/notifier.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,qBAAa,QAAQ;CAAG"} \ No newline at end of file diff --git a/lib/api/notifier.js b/lib/api/notifier.js new file mode 100644 index 000000000..e64883a8b --- /dev/null +++ b/lib/api/notifier.js @@ -0,0 +1,8 @@ +/** + * TODO: This is currently just a placeholder. + * Notifier is the peer of a Subscriber. + * That is, a Notifier sends NOTIFY requests. + * @internal + */ +export class Notifier { +} diff --git a/lib/api/publisher-options.d.ts b/lib/api/publisher-options.d.ts new file mode 100644 index 000000000..137223835 --- /dev/null +++ b/lib/api/publisher-options.d.ts @@ -0,0 +1,34 @@ +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 new file mode 100644 index 000000000..01fdfda1a --- /dev/null +++ b/lib/api/publisher-options.d.ts.map @@ -0,0 +1 @@ +{"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 new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/api/publisher-options.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/api/publisher-publish-options.d.ts b/lib/api/publisher-publish-options.d.ts new file mode 100644 index 000000000..e849f0773 --- /dev/null +++ b/lib/api/publisher-publish-options.d.ts @@ -0,0 +1,7 @@ +/** + * 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 new file mode 100644 index 000000000..d43326216 --- /dev/null +++ b/lib/api/publisher-publish-options.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"publisher-publish-options.d.ts","sourceRoot":"","sources":["../../src/api/publisher-publish-options.ts"],"names":[],"mappings":"AACA;;;GAGG;AACH,MAAM,WAAW,uBAAuB;CAAG"} \ No newline at end of file diff --git a/lib/api/publisher-publish-options.js b/lib/api/publisher-publish-options.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/api/publisher-publish-options.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/api/publisher-state.d.ts b/lib/api/publisher-state.d.ts new file mode 100644 index 000000000..facc5009e --- /dev/null +++ b/lib/api/publisher-state.d.ts @@ -0,0 +1,22 @@ +/** + * {@link Publisher} state. + * @remarks + * The {@link Publisher} behaves in a deterministic manner according to the following + * Finite State Machine (FSM). + * ```txt + * __________________________________________ + * | __________________________ | + * Publisher | | v v + * Constructed -> Initial -> Published -> Unpublished -> Terminated + * | ^____________| ^ + * |______________________________| + * ``` + * @public + */ +export declare enum PublisherState { + Initial = "Initial", + Published = "Published", + Unpublished = "Unpublished", + Terminated = "Terminated" +} +//# sourceMappingURL=publisher-state.d.ts.map \ No newline at end of file diff --git a/lib/api/publisher-state.d.ts.map b/lib/api/publisher-state.d.ts.map new file mode 100644 index 000000000..dd3f6b0b6 --- /dev/null +++ b/lib/api/publisher-state.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"publisher-state.d.ts","sourceRoot":"","sources":["../../src/api/publisher-state.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,oBAAY,cAAc;IACxB,OAAO,YAAY;IACnB,SAAS,cAAc;IACvB,WAAW,gBAAgB;IAC3B,UAAU,eAAe;CAC1B"} \ No newline at end of file diff --git a/lib/api/publisher-state.js b/lib/api/publisher-state.js new file mode 100644 index 000000000..28a86a28c --- /dev/null +++ b/lib/api/publisher-state.js @@ -0,0 +1,22 @@ +/** + * {@link Publisher} state. + * @remarks + * The {@link Publisher} behaves in a deterministic manner according to the following + * Finite State Machine (FSM). + * ```txt + * __________________________________________ + * | __________________________ | + * Publisher | | v v + * Constructed -> Initial -> Published -> Unpublished -> Terminated + * | ^____________| ^ + * |______________________________| + * ``` + * @public + */ +export var PublisherState; +(function (PublisherState) { + PublisherState["Initial"] = "Initial"; + PublisherState["Published"] = "Published"; + PublisherState["Unpublished"] = "Unpublished"; + PublisherState["Terminated"] = "Terminated"; +})(PublisherState || (PublisherState = {})); diff --git a/lib/api/publisher-unpublish-options.d.ts b/lib/api/publisher-unpublish-options.d.ts new file mode 100644 index 000000000..09d3c157a --- /dev/null +++ b/lib/api/publisher-unpublish-options.d.ts @@ -0,0 +1,7 @@ +/** + * 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 new file mode 100644 index 000000000..99a1f229c --- /dev/null +++ b/lib/api/publisher-unpublish-options.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"publisher-unpublish-options.d.ts","sourceRoot":"","sources":["../../src/api/publisher-unpublish-options.ts"],"names":[],"mappings":"AACA;;;GAGG;AACH,MAAM,WAAW,yBAAyB;CAAG"} \ No newline at end of file diff --git a/lib/api/publisher-unpublish-options.js b/lib/api/publisher-unpublish-options.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/api/publisher-unpublish-options.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/api/publisher.d.ts b/lib/api/publisher.d.ts new file mode 100644 index 000000000..e62f5ac78 --- /dev/null +++ b/lib/api/publisher.d.ts @@ -0,0 +1,66 @@ +import { IncomingResponseMessage, OutgoingPublishRequest, URI } from "../core"; +import { Emitter } from "./emitter"; +import { PublisherOptions } from "./publisher-options"; +import { PublisherPublishOptions } from "./publisher-publish-options"; +import { PublisherState } from "./publisher-state"; +import { PublisherUnpublishOptions } from "./publisher-unpublish-options"; +import { UserAgent } from "./user-agent"; +/** + * A publisher publishes a publication (outgoing PUBLISH). + * @public + */ +export declare class Publisher { + private event; + private options; + private target; + private pubRequestBody; + private pubRequestExpires; + private pubRequestEtag; + private publishRefreshTimer; + private disposed; + private id; + private logger; + private request; + private userAgent; + /** The publication state. */ + private _state; + /** Emits when the registration state changes. */ + private _stateEventEmitter; + /** + * 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); + /** + * Destructor. + */ + dispose(): Promise; + /** The publication state. */ + get state(): PublisherState; + /** Emits when the publisher state changes. */ + get stateChange(): Emitter; + /** + * Publish. + * @param content - Body to publish + */ + publish(content: string, options?: PublisherPublishOptions): Promise; + /** + * Unpublish. + */ + unpublish(options?: PublisherUnpublishOptions): Promise; + /** @internal */ + protected receiveResponse(response: IncomingResponseMessage): void; + /** @internal */ + protected send(): OutgoingPublishRequest; + private refreshRequest; + private sendPublishRequest; + /** + * Transition publication state. + */ + private stateTransition; +} +//# 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 new file mode 100644 index 000000000..4e37de760 --- /dev/null +++ b/lib/api/publisher.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"publisher.d.ts","sourceRoot":"","sources":["../../src/api/publisher.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,uBAAuB,EAEvB,sBAAsB,EAEtB,GAAG,EACJ,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,OAAO,EAAe,MAAM,WAAW,CAAC;AACjD,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,uBAAuB,EAAE,MAAM,6BAA6B,CAAC;AACtE,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,EAAE,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAE1E,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC;;;GAGG;AACH,qBAAa,SAAS;IACpB,OAAO,CAAC,KAAK,CAAS;IACtB,OAAO,CAAC,OAAO,CAAmB;IAClC,OAAO,CAAC,MAAM,CAAM;IACpB,OAAO,CAAC,cAAc,CAAqB;IAC3C,OAAO,CAAC,iBAAiB,CAAS;IAClC,OAAO,CAAC,cAAc,CAAqB;IAC3C,OAAO,CAAC,mBAAmB,CAAqB;IAEhD,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,EAAE,CAAS;IACnB,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,OAAO,CAAyB;IACxC,OAAO,CAAC,SAAS,CAAY;IAE7B,6BAA6B;IAC7B,OAAO,CAAC,MAAM,CAA0C;IACxD,iDAAiD;IACjD,OAAO,CAAC,kBAAkB,CAA8B;IAExD;;;;;;;OAOG;gBACgB,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,GAAG,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,GAAE,gBAAqB;IA4D1G;;OAEG;IACI,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IA2B/B,6BAA6B;IAC7B,IAAW,KAAK,IAAI,cAAc,CAEjC;IAED,8CAA8C;IAC9C,IAAW,WAAW,IAAI,OAAO,CAAC,cAAc,CAAC,CAEhD;IAED;;;OAGG;IAEI,OAAO,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE,uBAA4B,GAAG,OAAO,CAAC,IAAI,CAAC;IAyBrF;;OAEG;IAEI,SAAS,CAAC,OAAO,GAAE,yBAA8B,GAAG,OAAO,CAAC,IAAI,CAAC;IAiBxE,gBAAgB;IAChB,SAAS,CAAC,eAAe,CAAC,QAAQ,EAAE,uBAAuB,GAAG,IAAI;IA+FlE,gBAAgB;IAChB,SAAS,CAAC,IAAI,IAAI,sBAAsB;IAUxC,OAAO,CAAC,cAAc;IAqBtB,OAAO,CAAC,kBAAkB;IA0C1B;;OAEG;IACH,OAAO,CAAC,eAAe;CA2CxB"} \ No newline at end of file diff --git a/lib/api/publisher.js b/lib/api/publisher.js new file mode 100644 index 000000000..256ec2d7f --- /dev/null +++ b/lib/api/publisher.js @@ -0,0 +1,326 @@ +import { C, fromBodyLegacy } from "../core"; +import { EmitterImpl } from "./emitter"; +import { PublisherState } from "./publisher-state"; +/** + * A publisher publishes a publication (outgoing PUBLISH). + * @public + */ +export class Publisher { + /** + * 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, targetURI, eventType, options = {}) { + this.disposed = false; + /** The publication state. */ + this._state = PublisherState.Initial; + // state emitter + this._stateEventEmitter = new EmitterImpl(); + this.userAgent = userAgent; + 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 = options.expires; + this.logger = userAgent.getLogger("sip.Publisher"); + const params = options.params || {}; + const fromURI = params.fromUri ? params.fromUri : userAgent.userAgentCore.configuration.aor; + const toURI = params.toUri ? params.toUri : targetURI; + let body; + if (options.body && options.contentType) { + const contentDisposition = "render"; + const contentType = options.contentType; + const content = options.body; + body = { + contentDisposition, + contentType, + content + }; + } + const extraHeaders = (options.extraHeaders || []).slice(); + // Build the request + this.request = userAgent.userAgentCore.makeOutgoingRequestMessage(C.PUBLISH, targetURI, fromURI, toURI, params, extraHeaders, body); + // Identifier + this.id = this.target.toString() + ":" + this.event; + // Add to the user agent's publisher collection. + this.userAgent._publishers[this.id] = this; + } + /** + * Destructor. + */ + dispose() { + if (this.disposed) { + return Promise.resolve(); + } + this.disposed = true; + this.logger.log(`Publisher ${this.id} in state ${this.state} is being disposed`); + // Remove from the user agent's publisher collection + delete this.userAgent._publishers[this.id]; + // Send unpublish, if requested + if (this.options.unpublishOnClose && this.state === PublisherState.Published) { + return this.unpublish(); + } + if (this.publishRefreshTimer) { + clearTimeout(this.publishRefreshTimer); + this.publishRefreshTimer = undefined; + } + this.pubRequestBody = undefined; + this.pubRequestExpires = 0; + this.pubRequestEtag = undefined; + return Promise.resolve(); + } + /** The publication state. */ + get state() { + return this._state; + } + /** Emits when the publisher state changes. */ + get stateChange() { + return this._stateEventEmitter; + } + /** + * Publish. + * @param content - Body to publish + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + publish(content, 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 + if (this.options.expires === undefined) { + throw new Error("Expires undefined."); + } + this.pubRequestExpires = this.options.expires; + this.pubRequestEtag = undefined; + } + this.sendPublishRequest(); + return Promise.resolve(); + } + /** + * Unpublish. + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + unpublish(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(); + } + return Promise.resolve(); + } + /** @internal */ + receiveResponse(response) { + const statusCode = response.statusCode || 0; + switch (true) { + case /^1[0-9]{2}$/.test(statusCode.toString()): + 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")) { + const 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(() => this.refreshRequest(), this.pubRequestExpires * 900); + this.stateTransition(PublisherState.Published); + } + else { + this.stateTransition(PublisherState.Unpublished); + } + 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; + if (this.options.body === undefined) { + throw new Error("Body undefined."); + } + this.publish(this.options.body); + } + else { + this.logger.warn("412 response to PUBLISH, recovery failed"); + this.pubRequestExpires = 0; + this.stateTransition(PublisherState.Unpublished); + this.stateTransition(PublisherState.Terminated); + } + 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")) { + const 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; + if (this.options.body === undefined) { + throw new Error("Body undefined."); + } + this.publish(this.options.body); + } + else { + this.logger.warn("Bad 423 response Min-Expires header received for PUBLISH"); + this.pubRequestExpires = 0; + this.stateTransition(PublisherState.Unpublished); + this.stateTransition(PublisherState.Terminated); + } + } + else { + this.logger.warn("423 response to PUBLISH, recovery failed"); + this.pubRequestExpires = 0; + this.stateTransition(PublisherState.Unpublished); + this.stateTransition(PublisherState.Terminated); + } + break; + default: + this.pubRequestExpires = 0; + this.stateTransition(PublisherState.Unpublished); + this.stateTransition(PublisherState.Terminated); + break; + } + // Do the cleanup + if (this.pubRequestExpires === 0) { + if (this.publishRefreshTimer) { + clearTimeout(this.publishRefreshTimer); + this.publishRefreshTimer = undefined; + } + this.pubRequestBody = undefined; + this.pubRequestEtag = undefined; + } + } + /** @internal */ + send() { + return this.userAgent.userAgentCore.publish(this.request, { + onAccept: (response) => this.receiveResponse(response.message), + onProgress: (response) => this.receiveResponse(response.message), + onRedirect: (response) => this.receiveResponse(response.message), + onReject: (response) => this.receiveResponse(response.message), + onTrying: (response) => this.receiveResponse(response.message) + }); + } + refreshRequest() { + // 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) { + throw new Error("Etag undefined"); + } + if (this.pubRequestExpires === 0) { + throw new Error("Expires zero"); + } + this.sendPublishRequest(); + } + sendPublishRequest() { + const reqOptions = Object.assign({}, this.options); + 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); + } + const ruri = this.target; + const params = this.options.params || {}; + let bodyAndContentType; + if (this.pubRequestBody !== undefined) { + if (this.options.contentType === undefined) { + throw new Error("Content type undefined."); + } + bodyAndContentType = { + body: this.pubRequestBody, + contentType: this.options.contentType + }; + } + let body; + if (bodyAndContentType) { + body = fromBodyLegacy(bodyAndContentType); + } + this.request = this.userAgent.userAgentCore.makeOutgoingRequestMessage(C.PUBLISH, ruri, params.fromUri ? params.fromUri : this.userAgent.userAgentCore.configuration.aor, params.toUri ? params.toUri : this.target, params, reqOptions.extraHeaders, body); + return this.send(); + } + /** + * Transition publication state. + */ + stateTransition(newState) { + const invalidTransition = () => { + throw new Error(`Invalid state transition from ${this._state} to ${newState}`); + }; + // Validate transition + switch (this._state) { + case PublisherState.Initial: + if (newState !== PublisherState.Published && + newState !== PublisherState.Unpublished && + newState !== PublisherState.Terminated) { + invalidTransition(); + } + break; + case PublisherState.Published: + if (newState !== PublisherState.Unpublished && newState !== PublisherState.Terminated) { + invalidTransition(); + } + break; + case PublisherState.Unpublished: + if (newState !== PublisherState.Published && newState !== PublisherState.Terminated) { + invalidTransition(); + } + break; + case PublisherState.Terminated: + invalidTransition(); + break; + default: + throw new Error("Unrecognized state."); + } + // Transition + this._state = newState; + this.logger.log(`Publication transitioned to state ${this._state}`); + this._stateEventEmitter.emit(this._state); + // Dispose + if (newState === PublisherState.Terminated) { + this.dispose(); + } + } +} diff --git a/lib/api/referral.d.ts b/lib/api/referral.d.ts new file mode 100644 index 000000000..f107b7ccd --- /dev/null +++ b/lib/api/referral.d.ts @@ -0,0 +1,39 @@ +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); + get referTo(): NameAddrHeader; + get referredBy(): string | undefined; + get replaces(): string | undefined; + /** Incoming REFER request message. */ + get 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 new file mode 100644 index 000000000..14bdd1143 --- /dev/null +++ b/lib/api/referral.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"referral.d.ts","sourceRoot":"","sources":["../../src/api/referral.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,sBAAsB,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AACxG,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;IAIA,OAAO,CAAC,oBAAoB;IAAwB,OAAO,CAAC,OAAO;IAHtF,OAAO,CAAC,OAAO,CAAsB;IAErC,gBAAgB;gBACW,oBAAoB,EAAE,oBAAoB,EAAU,OAAO,EAAE,OAAO;IAE/F,IAAW,OAAO,IAAI,cAAc,CAMnC;IAED,IAAW,UAAU,IAAI,MAAM,GAAG,SAAS,CAE1C;IAED,IAAW,QAAQ,IAAI,MAAM,GAAG,SAAS,CAExC;IAED,sCAAsC;IACtC,IAAW,OAAO,IAAI,sBAAsB,CAE3C;IAED,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,CAAC,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO;CAuBtD"} \ No newline at end of file diff --git a/lib/api/referral.js b/lib/api/referral.js new file mode 100644 index 000000000..9f21b653e --- /dev/null +++ b/lib/api/referral.js @@ -0,0 +1,75 @@ +import { NameAddrHeader } from "../core"; +/** + * A request to establish a {@link Session} elsewhere (incoming REFER). + * @public + */ +export class Referral { + /** @internal */ + constructor(incomingReferRequest, session) { + this.incomingReferRequest = incomingReferRequest; + this.session = session; + } + get referTo() { + const referTo = this.incomingReferRequest.message.parseHeader("refer-to"); + if (!(referTo instanceof NameAddrHeader)) { + throw new Error("Failed to parse Refer-To header."); + } + return referTo; + } + get referredBy() { + return this.incomingReferRequest.message.getHeader("referred-by"); + } + get replaces() { + return this.referTo.uri.getHeader("replaces"); + } + /** Incoming REFER request message. */ + get request() { + return this.incomingReferRequest.message; + } + /** Accept the request. */ + accept(options = { statusCode: 202 }) { + this.incomingReferRequest.accept(options); + return Promise.resolve(); + } + /** Reject the request. */ + reject(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. + */ + makeInviter(options) { + if (this.inviter) { + return this.inviter; + } + const targetURI = this.referTo.uri.clone(); + targetURI.clearHeaders(); + options = options || {}; + const extraHeaders = (options.extraHeaders || []).slice(); + const replaces = this.replaces; + if (replaces) { + // decodeURIComponent is a holdover from 2c086eb4. Not sure that it is actually necessary + extraHeaders.push("Replaces: " + decodeURIComponent(replaces)); + } + const 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; + } +} diff --git a/lib/api/registerer-options.d.ts b/lib/api/registerer-options.d.ts new file mode 100644 index 000000000..3657de030 --- /dev/null +++ b/lib/api/registerer-options.d.ts @@ -0,0 +1,42 @@ +import { URI } from "../core"; +/** + * Options for {@link Registerer} constructor. + * @public + */ +export interface RegistererOptions { + /** Registration expiration time in seconds. */ + expires?: number; + /** Array of extra Contact header parameters. */ + extraContactHeaderParams?: Array; + /** Array of extra headers added to the REGISTER. */ + extraHeaders?: Array; + /** + * UUID to provide with "+sip.instance" Contact parameter. + * @defaultValue a randomly generated uuid + */ + instanceId?: string; + /** + * If true, constructor logs the registerer configuration. + * @defaultValue `true` + */ + logConfiguration?: boolean; + /** @deprecated TODO: provide alternative. */ + params?: { + fromDisplayName?: string; + fromTag?: string; + fromUri?: URI; + toDisplayName?: string; + toUri?: URI; + }; + /** + * Value to provide with "reg-id" Contact parameter. + * @defaultValue 1 + */ + regId?: number; + /** + * The URI of the registrar to send the REGISTER requests. + * @defaultValue domain portion of the user agent's uri + */ + registrar?: URI; +} +//# 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 new file mode 100644 index 000000000..b77f84b43 --- /dev/null +++ b/lib/api/registerer-options.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"registerer-options.d.ts","sourceRoot":"","sources":["../../src/api/registerer-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AAE9B;;;GAGG;AACH,MAAM,WAAW,iBAAiB;IAChC,+CAA+C;IAC/C,OAAO,CAAC,EAAE,MAAM,CAAC;IAEjB,gDAAgD;IAChD,wBAAwB,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAEzC,oDAAoD;IACpD,YAAY,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAE7B;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IAEpB;;;OAGG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAE3B,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;IAEF;;;OAGG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;IAEf;;;OAGG;IACH,SAAS,CAAC,EAAE,GAAG,CAAC;CACjB"} \ No newline at end of file diff --git a/lib/api/registerer-options.js b/lib/api/registerer-options.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/api/registerer-options.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/api/registerer-register-options.d.ts b/lib/api/registerer-register-options.d.ts new file mode 100644 index 000000000..22140aa66 --- /dev/null +++ b/lib/api/registerer-register-options.d.ts @@ -0,0 +1,12 @@ +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 new file mode 100644 index 000000000..77c1747b4 --- /dev/null +++ b/lib/api/registerer-register-options.d.ts.map @@ -0,0 +1 @@ +{"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;AAElE;;;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 new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/api/registerer-register-options.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/api/registerer-state.d.ts b/lib/api/registerer-state.d.ts new file mode 100644 index 000000000..de9c318ff --- /dev/null +++ b/lib/api/registerer-state.d.ts @@ -0,0 +1,22 @@ +/** + * {@link Registerer} state. + * @remarks + * The {@link Registerer} behaves in a deterministic manner according to the following + * Finite State Machine (FSM). + * ```txt + * __________________________________________ + * | __________________________ | + * Registerer | | v v + * Constructed -> Initial -> Registered -> Unregistered -> Terminated + * | ^____________| ^ + * |______________________________| + * ``` + * @public + */ +export declare enum RegistererState { + Initial = "Initial", + Registered = "Registered", + Unregistered = "Unregistered", + Terminated = "Terminated" +} +//# 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 new file mode 100644 index 000000000..b14cf5168 --- /dev/null +++ b/lib/api/registerer-state.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"registerer-state.d.ts","sourceRoot":"","sources":["../../src/api/registerer-state.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,oBAAY,eAAe;IACzB,OAAO,YAAY;IACnB,UAAU,eAAe;IACzB,YAAY,iBAAiB;IAC7B,UAAU,eAAe;CAC1B"} \ No newline at end of file diff --git a/lib/api/registerer-state.js b/lib/api/registerer-state.js new file mode 100644 index 000000000..3ae97e339 --- /dev/null +++ b/lib/api/registerer-state.js @@ -0,0 +1,22 @@ +/** + * {@link Registerer} state. + * @remarks + * The {@link Registerer} behaves in a deterministic manner according to the following + * Finite State Machine (FSM). + * ```txt + * __________________________________________ + * | __________________________ | + * Registerer | | v v + * Constructed -> Initial -> Registered -> Unregistered -> Terminated + * | ^____________| ^ + * |______________________________| + * ``` + * @public + */ +export var RegistererState; +(function (RegistererState) { + RegistererState["Initial"] = "Initial"; + RegistererState["Registered"] = "Registered"; + RegistererState["Unregistered"] = "Unregistered"; + RegistererState["Terminated"] = "Terminated"; +})(RegistererState || (RegistererState = {})); diff --git a/lib/api/registerer-unregister-options.d.ts b/lib/api/registerer-unregister-options.d.ts new file mode 100644 index 000000000..d2673f86d --- /dev/null +++ b/lib/api/registerer-unregister-options.d.ts @@ -0,0 +1,17 @@ +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 new file mode 100644 index 000000000..3f30ee432 --- /dev/null +++ b/lib/api/registerer-unregister-options.d.ts.map @@ -0,0 +1 @@ +{"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 new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/api/registerer-unregister-options.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/api/registerer.d.ts b/lib/api/registerer.d.ts new file mode 100644 index 000000000..2df7146e7 --- /dev/null +++ b/lib/api/registerer.d.ts @@ -0,0 +1,143 @@ +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 static readonly defaultExpires; + private disposed; + private id; + 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 number of seconds to wait before retrying to register. */ + private _retryAfter; + /** 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); + /** Default registerer options. */ + private static defaultOptions; + private static newUUID; + /** + * Strip properties with undefined values from options. + * This is a work around while waiting for missing vs undefined to be addressed (or not)... + * https://github.com/Microsoft/TypeScript/issues/13195 + * @param options - Options to reduce + */ + private static stripUndefinedProperties; + /** The registered contacts. */ + get contacts(): Array; + /** + * The number of seconds to wait before retrying to register. + * @defaultValue `undefined` + * @remarks + * When the server rejects a registration request, if it provides a suggested + * duration to wait before retrying, that value is available here when and if + * the state transitions to `Unsubscribed`. It is also available during the + * callback to `onReject` after a call to `register`. (Note that if the state + * if already `Unsubscribed`, a rejected request created by `register` will + * not cause the state to transition to `Unsubscribed`. One way to avoid this + * case is to dispose of `Registerer` when unregistered and create a new + * `Registerer` for any attempts to retry registering.) + * @example + * ```ts + * // Checking for retry after on state change + * registerer.stateChange.addListener((newState) => { + * switch (newState) { + * case RegistererState.Unregistered: + * const retryAfter = registerer.retryAfter; + * break; + * } + * }); + * + * // Checking for retry after on request rejection + * registerer.register({ + * requestDelegate: { + * onReject: () => { + * const retryAfter = registerer.retryAfter; + * } + * } + * }); + * ``` + */ + get retryAfter(): number | undefined; + /** The registration state. */ + get state(): RegistererState; + /** Emits when the registerer state changes. */ + get stateChange(): Emitter; + /** Destructor. */ + dispose(): Promise; + /** + * Sends the REGISTER request. + * @remarks + * If successful, sends re-REGISTER requests prior to registration expiration until `unsubscribe()` is called. + * Rejects with `RequestPendingError` if a REGISTER request is already in progress. + */ + register(options?: RegistererRegisterOptions): Promise; + /** + * Sends the REGISTER request with expires equal to zero. + * @remarks + * Rejects with `RequestPendingError` if a REGISTER request is already in progress. + */ + unregister(options?: RegistererUnregisterOptions): Promise; + /** + * Clear registration timers. + */ + private clearTimers; + /** + * Generate Contact Header + */ + private generateContactHeader; + /** + * Helper function, called when registered. + */ + private registered; + /** + * Helper function, called when unregistered. + */ + private unregistered; + /** + * Helper function, called when terminated. + */ + private terminated; + /** + * Transition registration state. + */ + private stateTransition; + /** True if the registerer is currently waiting for final response to a REGISTER request. */ + private get waiting(); + /** Emits when the registerer waiting state changes. */ + private get waitingChange(); + /** + * Toggle waiting. + */ + private waitingToggle; + /** Hopefully helpful as the standard behavior has been found to be unexpected. */ + private waitingWarning; + /** Hopefully helpful as the standard behavior has been found to be unexpected. */ + private stateError; +} +//# 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 new file mode 100644 index 000000000..eb3766161 --- /dev/null +++ b/lib/api/registerer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"registerer.d.ts","sourceRoot":"","sources":["../../src/api/registerer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAsB,uBAAuB,EAA+C,MAAM,SAAS,CAAC;AACnH,OAAO,EAAE,OAAO,EAAe,MAAM,WAAW,CAAC;AAEjD,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;AAEzC;;;GAGG;AACH,qBAAa,UAAU;IACrB,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,cAAc,CAAO;IAE7C,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,EAAE,CAAS;IACnB,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,CAAqB;IACrD,OAAO,CAAC,iBAAiB,CAAqB;IAE9C,4EAA4E;IAC5E,OAAO,CAAC,SAAS,CAAqB;IAEtC,iEAAiE;IACjE,OAAO,CAAC,WAAW,CAAiC;IAEpD,8BAA8B;IAC9B,OAAO,CAAC,MAAM,CAA4C;IAC1D,iDAAiD;IACjD,OAAO,CAAC,kBAAkB,CAA+B;IAEzD,0EAA0E;IAC1E,OAAO,CAAC,QAAQ,CAAS;IACzB,kCAAkC;IAClC,OAAO,CAAC,oBAAoB,CAAuB;IAEnD;;;;OAIG;gBACgB,SAAS,EAAE,SAAS,EAAE,OAAO,GAAE,iBAAsB;IA+FxE,kCAAkC;IAClC,OAAO,CAAC,MAAM,CAAC,cAAc;IAc7B,OAAO,CAAC,MAAM,CAAC,OAAO;IAStB;;;;;OAKG;IACH,OAAO,CAAC,MAAM,CAAC,wBAAwB;IAWvC,+BAA+B;IAC/B,IAAW,QAAQ,IAAI,KAAK,CAAC,MAAM,CAAC,CAEnC;IAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAgCG;IACH,IAAW,UAAU,IAAI,MAAM,GAAG,SAAS,CAE1C;IAED,8BAA8B;IAC9B,IAAW,KAAK,IAAI,eAAe,CAElC;IAED,+CAA+C;IAC/C,IAAW,WAAW,IAAI,OAAO,CAAC,eAAe,CAAC,CAEjD;IAED,kBAAkB;IACX,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IA6C/B;;;;;OAKG;IACI,QAAQ,CAAC,OAAO,GAAE,yBAA8B,GAAG,OAAO,CAAC,uBAAuB,CAAC;IAkN1F;;;;OAIG;IACI,UAAU,CAAC,OAAO,GAAE,2BAAgC,GAAG,OAAO,CAAC,uBAAuB,CAAC;IAgH9F;;OAEG;IACH,OAAO,CAAC,WAAW;IAYnB;;OAEG;IACH,OAAO,CAAC,qBAAqB;IAkB7B;;OAEG;IACH,OAAO,CAAC,UAAU;IAqBlB;;OAEG;IACH,OAAO,CAAC,YAAY;IAQpB;;OAEG;IACH,OAAO,CAAC,UAAU;IAQlB;;OAEG;IACH,OAAO,CAAC,eAAe;IA4CvB,4FAA4F;IAC5F,OAAO,KAAK,OAAO,GAElB;IAED,uDAAuD;IACvD,OAAO,KAAK,aAAa,GAExB;IAED;;OAEG;IACH,OAAO,CAAC,aAAa;IASrB,kFAAkF;IAClF,OAAO,CAAC,cAAc;IAUtB,kFAAkF;IAClF,OAAO,CAAC,UAAU;CAOnB"} \ No newline at end of file diff --git a/lib/api/registerer.js b/lib/api/registerer.js new file mode 100644 index 000000000..cc984f515 --- /dev/null +++ b/lib/api/registerer.js @@ -0,0 +1,663 @@ +import { C, Grammar, URI } from "../core"; +import { EmitterImpl } from "./emitter"; +import { RequestPendingError } from "./exceptions"; +import { RegistererState } from "./registerer-state"; +/** + * A registerer registers a contact for an address of record (outgoing REGISTER). + * @public + */ +export class Registerer { + /** + * 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, options = {}) { + this.disposed = false; + /** The contacts returned from the most recent accepted REGISTER request. */ + this._contacts = []; + /** The number of seconds to wait before retrying to register. */ + this._retryAfter = undefined; + /** The registration state. */ + this._state = RegistererState.Initial; + /** True is waiting for final response to outstanding REGISTER request. */ + this._waiting = false; + // state emitter + this._stateEventEmitter = new EmitterImpl(); + // waiting emitter + this._waitingEventEmitter = new EmitterImpl(); + // Set user agent + this.userAgent = userAgent; + // Default registrar is domain portion of user agent uri + const defaultUserAgentRegistrar = userAgent.configuration.uri.clone(); + defaultUserAgentRegistrar.user = undefined; + // Initialize configuration + this.options = Object.assign(Object.assign(Object.assign({}, Registerer.defaultOptions()), { registrar: defaultUserAgentRegistrar }), Registerer.stripUndefinedProperties(options)); + // Make sure we are not using references to array options + this.options.extraContactHeaderParams = (this.options.extraContactHeaderParams || []).slice(); + this.options.extraHeaders = (this.options.extraHeaders || []).slice(); + // Make sure we are not using references to registrar uri + if (!this.options.registrar) { + throw new Error("Registrar undefined."); + } + this.options.registrar = this.options.registrar.clone(); + // Set instanceId and regId conditional defaults and validate + if (this.options.regId && !this.options.instanceId) { + this.options.instanceId = Registerer.newUUID(); + } + else if (!this.options.regId && this.options.instanceId) { + this.options.regId = 1; + } + if (this.options.instanceId && Grammar.parse(this.options.instanceId, "uuid") === -1) { + throw new Error("Invalid instanceId."); + } + if (this.options.regId && this.options.regId < 0) { + throw new Error("Invalid regId."); + } + const registrar = this.options.registrar; + const fromURI = (this.options.params && this.options.params.fromUri) || userAgent.userAgentCore.configuration.aor; + const toURI = (this.options.params && this.options.params.toUri) || userAgent.configuration.uri; + const params = this.options.params || {}; + const extraHeaders = (options.extraHeaders || []).slice(); + // Build the request + this.request = userAgent.userAgentCore.makeOutgoingRequestMessage(C.REGISTER, registrar, fromURI, toURI, params, extraHeaders, undefined); + // Registration expires + this.expires = this.options.expires || Registerer.defaultExpires; + if (this.expires < 0) { + throw new Error("Invalid expires."); + } + // initialize logger + this.logger = userAgent.getLogger("sip.Registerer"); + if (this.options.logConfiguration) { + this.logger.log("Configuration:"); + Object.keys(this.options).forEach((key) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const value = this.options[key]; + switch (key) { + case "registrar": + this.logger.log("· " + key + ": " + value); + break; + default: + this.logger.log("· " + key + ": " + JSON.stringify(value)); + } + }); + } + // Identifier + this.id = this.request.callId + this.request.from.parameters.tag; + // Add to the user agent's session collection. + this.userAgent._registerers[this.id] = this; + } + /** Default registerer options. */ + static defaultOptions() { + return { + expires: Registerer.defaultExpires, + extraContactHeaderParams: [], + extraHeaders: [], + logConfiguration: true, + instanceId: "", + params: {}, + regId: 0, + registrar: new URI("sip", "anonymous", "anonymous.invalid") + }; + } + // http://stackoverflow.com/users/109538/broofa + static newUUID() { + const UUID = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => { + const r = Math.floor(Math.random() * 16); + const v = c === "x" ? r : (r % 4) + 8; + return v.toString(16); + }); + return UUID; + } + /** + * Strip properties with undefined values from options. + * This is a work around while waiting for missing vs undefined to be addressed (or not)... + * https://github.com/Microsoft/TypeScript/issues/13195 + * @param options - Options to reduce + */ + static stripUndefinedProperties(options) { + return Object.keys(options).reduce((object, key) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (options[key] !== undefined) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + object[key] = options[key]; + } + return object; + }, {}); + } + /** The registered contacts. */ + get contacts() { + return this._contacts.slice(); + } + /** + * The number of seconds to wait before retrying to register. + * @defaultValue `undefined` + * @remarks + * When the server rejects a registration request, if it provides a suggested + * duration to wait before retrying, that value is available here when and if + * the state transitions to `Unsubscribed`. It is also available during the + * callback to `onReject` after a call to `register`. (Note that if the state + * if already `Unsubscribed`, a rejected request created by `register` will + * not cause the state to transition to `Unsubscribed`. One way to avoid this + * case is to dispose of `Registerer` when unregistered and create a new + * `Registerer` for any attempts to retry registering.) + * @example + * ```ts + * // Checking for retry after on state change + * registerer.stateChange.addListener((newState) => { + * switch (newState) { + * case RegistererState.Unregistered: + * const retryAfter = registerer.retryAfter; + * break; + * } + * }); + * + * // Checking for retry after on request rejection + * registerer.register({ + * requestDelegate: { + * onReject: () => { + * const retryAfter = registerer.retryAfter; + * } + * } + * }); + * ``` + */ + get retryAfter() { + return this._retryAfter; + } + /** The registration state. */ + get state() { + return this._state; + } + /** Emits when the registerer state changes. */ + get stateChange() { + return this._stateEventEmitter; + } + /** Destructor. */ + dispose() { + if (this.disposed) { + return Promise.resolve(); + } + this.disposed = true; + this.logger.log(`Registerer ${this.id} in state ${this.state} is being disposed`); + // Remove from the user agent's registerer collection + delete this.userAgent._registerers[this.id]; + // If registered, unregisters and resolves after final response received. + return new Promise((resolve) => { + const doClose = () => { + // If we are registered, unregister and resolve after our state changes + if (!this.waiting && this._state === RegistererState.Registered) { + this.stateChange.addListener(() => { + this.terminated(); + resolve(); + }, { once: true }); + this.unregister(); + return; + } + // Otherwise just resolve + this.terminated(); + 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.addListener(() => { + doClose(); + }, { once: true }); + } + else { + doClose(); + } + }); + } + /** + * Sends the REGISTER request. + * @remarks + * If successful, sends re-REGISTER requests prior to registration expiration until `unsubscribe()` is called. + * Rejects with `RequestPendingError` if a REGISTER request is already in progress. + */ + register(options = {}) { + if (this.state === RegistererState.Terminated) { + this.stateError(); + throw new Error("Registerer terminated. Unable to register."); + } + if (this.disposed) { + this.stateError(); + throw new Error("Registerer disposed. Unable to register."); + } + // 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) { + this.waitingWarning(); + const error = new RequestPendingError("REGISTER request already in progress, waiting for final response"); + return Promise.reject(error); + } + // Options + if (options.requestOptions) { + this.options = Object.assign(Object.assign({}, this.options), options.requestOptions); + } + // Extra headers + const 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); + const outgoingRegisterRequest = this.userAgent.userAgentCore.register(this.request, { + onAccept: (response) => { + let 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"); + let 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 + let contact; + while (contacts--) { + contact = response.message.parseHeader("contact", contacts); + if (!contact) { + throw new Error("Contact undefined"); + } + if (contact.uri.user === this.userAgent.contact.uri.user && + contact.uri.host === this.userAgent.contact.uri.host && + contact.uri.port === this.userAgent.contact.uri.port) { + expires = Number(contact.getParam("expires")); + break; + } + 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")) { + const gruu = contact.getParam("temp-gruu"); + if (gruu) { + this.userAgent.contact.tempGruu = Grammar.URIParse(gruu.replace(/"/g, "")); + } + } + if (contact.hasParam("pub-gruu")) { + const gruu = contact.getParam("pub-gruu"); + if (gruu) { + this.userAgent.contact.pubGruu = Grammar.URIParse(gruu.replace(/"/g, "")); + } + } + this.registered(expires); + if (options.requestDelegate && options.requestDelegate.onAccept) { + options.requestDelegate.onAccept(response); + } + this.waitingToggle(false); + }, + onProgress: (response) => { + if (options.requestDelegate && options.requestDelegate.onProgress) { + options.requestDelegate.onProgress(response); + } + }, + onRedirect: (response) => { + this.logger.error("Redirect received. Not supported."); + this.unregistered(); + if (options.requestDelegate && options.requestDelegate.onRedirect) { + options.requestDelegate.onRedirect(response); + } + this.waitingToggle(false); + }, + onReject: (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, dropping response"); + 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}`); + // The Retry-After header field can be used with a 500 (Server Internal + // Error) or 503 (Service Unavailable) response to indicate how long the + // service is expected to be unavailable to the requesting client... + // https://tools.ietf.org/html/rfc3261#section-20.33 + let retryAfterDuration = NaN; + if (response.message.statusCode === 500 || response.message.statusCode === 503) { + const header = response.message.getHeader("retry-after"); + if (header) { + retryAfterDuration = Number.parseInt(header, undefined); + } + } + // Set for the state change (if any) and the delegate callback (if any) + this._retryAfter = isNaN(retryAfterDuration) ? undefined : retryAfterDuration; + this.unregistered(); + if (options.requestDelegate && options.requestDelegate.onReject) { + options.requestDelegate.onReject(response); + } + this._retryAfter = undefined; + this.waitingToggle(false); + }, + onTrying: (response) => { + if (options.requestDelegate && options.requestDelegate.onTrying) { + options.requestDelegate.onTrying(response); + } + } + }); + return Promise.resolve(outgoingRegisterRequest); + } + /** + * Sends the REGISTER request with expires equal to zero. + * @remarks + * Rejects with `RequestPendingError` if a REGISTER request is already in progress. + */ + unregister(options = {}) { + if (this.state === RegistererState.Terminated) { + this.stateError(); + throw new Error("Registerer terminated. Unable to register."); + } + if (this.disposed) { + if (this.state !== RegistererState.Registered) { + // allows unregister while disposing and registered + this.stateError(); + throw new Error("Registerer disposed. Unable to register."); + } + } + // 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) { + this.waitingWarning(); + const error = new RequestPendingError("REGISTER request already in progress, waiting for final response"); + return Promise.reject(error); + } + if (this._state !== RegistererState.Registered && !options.all) { + this.logger.warn("Not currently registered, but sending an unregister anyway."); + } + // Extra headers + const 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-emptive 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); + const outgoingRegisterRequest = this.userAgent.userAgentCore.register(this.request, { + onAccept: (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: (response) => { + if (options.requestDelegate && options.requestDelegate.onProgress) { + options.requestDelegate.onProgress(response); + } + }, + onRedirect: (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: (response) => { + 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: (response) => { + if (options.requestDelegate && options.requestDelegate.onTrying) { + options.requestDelegate.onTrying(response); + } + } + }); + return Promise.resolve(outgoingRegisterRequest); + } + /** + * Clear registration timers. + */ + clearTimers() { + if (this.registrationTimer !== undefined) { + clearTimeout(this.registrationTimer); + this.registrationTimer = undefined; + } + if (this.registrationExpiredTimer !== undefined) { + clearTimeout(this.registrationExpiredTimer); + this.registrationExpiredTimer = undefined; + } + } + /** + * Generate Contact Header + */ + generateContactHeader(expires) { + let contact = this.userAgent.contact.toString(); + if (this.options.regId && this.options.instanceId) { + contact += ";reg-id=" + this.options.regId; + contact += ';+sip.instance=""'; + } + if (this.options.extraContactHeaderParams) { + this.options.extraContactHeaderParams.forEach((header) => { + contact += ";" + header; + }); + } + contact += ";expires=" + expires; + return contact; + } + /** + * Helper function, called when registered. + */ + registered(expires) { + this.clearTimers(); + // Re-Register before the expiration interval has elapsed. + // For that, decrease the expires value. ie: 3 seconds + this.registrationTimer = setTimeout(() => { + this.registrationTimer = undefined; + this.register(); + }, expires * 1000 - 3000); + // We are unregistered if the registration expires. + this.registrationExpiredTimer = setTimeout(() => { + this.logger.warn("Registration expired"); + this.unregistered(); + }, expires * 1000); + if (this._state !== RegistererState.Registered) { + this.stateTransition(RegistererState.Registered); + } + } + /** + * Helper function, called when unregistered. + */ + unregistered() { + this.clearTimers(); + if (this._state !== RegistererState.Unregistered) { + this.stateTransition(RegistererState.Unregistered); + } + } + /** + * Helper function, called when terminated. + */ + terminated() { + this.clearTimers(); + if (this._state !== RegistererState.Terminated) { + this.stateTransition(RegistererState.Terminated); + } + } + /** + * Transition registration state. + */ + stateTransition(newState) { + const invalidTransition = () => { + throw new Error(`Invalid state transition from ${this._state} to ${newState}`); + }; + // Validate transition + switch (this._state) { + case RegistererState.Initial: + if (newState !== RegistererState.Registered && + newState !== RegistererState.Unregistered && + newState !== RegistererState.Terminated) { + invalidTransition(); + } + break; + case RegistererState.Registered: + if (newState !== RegistererState.Unregistered && newState !== RegistererState.Terminated) { + invalidTransition(); + } + break; + case RegistererState.Unregistered: + if (newState !== RegistererState.Registered && newState !== RegistererState.Terminated) { + invalidTransition(); + } + break; + case RegistererState.Terminated: + invalidTransition(); + break; + default: + throw new Error("Unrecognized state."); + } + // Transition + this._state = newState; + this.logger.log(`Registration transitioned to state ${this._state}`); + this._stateEventEmitter.emit(this._state); + // Dispose + if (newState === RegistererState.Terminated) { + this.dispose(); + } + } + /** True if the registerer is currently waiting for final response to a REGISTER request. */ + get waiting() { + return this._waiting; + } + /** Emits when the registerer waiting state changes. */ + get waitingChange() { + return this._waitingEventEmitter; + } + /** + * Toggle waiting. + */ + waitingToggle(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(this._waiting); + } + /** Hopefully helpful as the standard behavior has been found to be unexpected. */ + waitingWarning() { + let message = "An attempt was made to send a REGISTER request while a prior one was still in progress."; + message += " RFC 3261 requires UAs MUST NOT send a new registration until they have received a final response"; + message += " from the registrar for the previous one or the previous REGISTER request has timed out."; + message += " Note that if the transport disconnects, you still must wait for the prior request to time out before"; + message += + " sending a new REGISTER request or alternatively dispose of the current Registerer and create a new Registerer."; + this.logger.warn(message); + } + /** Hopefully helpful as the standard behavior has been found to be unexpected. */ + stateError() { + const reason = this.state === RegistererState.Terminated ? "is in 'Terminated' state" : "has been disposed"; + let message = `An attempt was made to send a REGISTER request when the Registerer ${reason}.`; + message += " The Registerer transitions to 'Terminated' when Registerer.dispose() is called."; + message += " Perhaps you called UserAgent.stop() which dipsoses of all Registerers?"; + this.logger.error(message); + } +} +Registerer.defaultExpires = 600; diff --git a/lib/api/session-bye-options.d.ts b/lib/api/session-bye-options.d.ts new file mode 100644 index 000000000..dd51797cd --- /dev/null +++ b/lib/api/session-bye-options.d.ts @@ -0,0 +1,12 @@ +import { OutgoingRequestDelegate, RequestOptions } from "../core"; +/** + * Options for {@link Session.bye}. + * @public + */ +export interface SessionByeOptions { + /** See `core` API. */ + requestDelegate?: OutgoingRequestDelegate; + /** See `core` API. */ + requestOptions?: RequestOptions; +} +//# sourceMappingURL=session-bye-options.d.ts.map \ No newline at end of file diff --git a/lib/api/session-bye-options.d.ts.map b/lib/api/session-bye-options.d.ts.map new file mode 100644 index 000000000..065612db2 --- /dev/null +++ b/lib/api/session-bye-options.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"session-bye-options.d.ts","sourceRoot":"","sources":["../../src/api/session-bye-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/session-bye-options.js b/lib/api/session-bye-options.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/api/session-bye-options.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/api/session-delegate.d.ts b/lib/api/session-delegate.d.ts new file mode 100644 index 000000000..ceb0e42b3 --- /dev/null +++ b/lib/api/session-delegate.d.ts @@ -0,0 +1,74 @@ +import { IncomingRequestMessage } from "../core"; +import { Bye } from "./bye"; +import { Info } from "./info"; +import { Message } from "./message"; +import { Notification } from "./notification"; +import { Referral } from "./referral"; +import { SessionDescriptionHandler } from "./session-description-handler"; +/** + * Delegate for {@link Session}. + * @public + */ +export interface SessionDelegate { + /** + * Called upon receiving an incoming in dialog BYE request. + * @param bye - The bye. + */ + onBye?(bye: Bye): void; + /** + * 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 MESSAGE request. + * @param message - The message. + */ + onMessage?(message: Message): 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; + /** + * Called upon creating a SessionDescriptionHandler. + * + * @remarks + * It's recommended that the SessionDescriptionHandler be accessed via the `Session.sessionDescriptionHandler` property. + * However there are use cases where one needs access immediately after it is constructed and before it is utilized. + * Thus this callback. + * + * In most scenarios a single SessionDescriptionHandler will be created per Session + * in which case this callback will be called at most once and `provisional` will be `false`. + * + * However if reliable provisional responses are being supported and an INVITE is sent without SDP, + * one or more session description handlers will be created if remote offers are received in reliable provisional responses. + * When remote offers are received in reliable provisional responses, the `provisional` parameter will be `true`. + * When the `provisional` paramter is `true`, this callback may (or may not) be called again. + * If the session is ultimately established using a SessionDescriptionHandler which was not created provisionally, + * this callback will be called again and the `provisional` parameter will be `false`. + * If the session is ultimately established using a SessionDescriptionHandler which was created provisionally, + * this callback will not be called again. + * Note that if the session is ultimately established using a SessionDescriptionHandler which was created provisionally, + * the provisional SessionDescriptionHandler being utilized will be available via the `Session.sessionDescriptionHandler` property. + * + * @param sessionDescriptionHandler - The handler. + * @param provisional - True if created provisionally. + */ + onSessionDescriptionHandler?(sessionDescriptionHandler: SessionDescriptionHandler, provisional: boolean): void; +} +//# 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 new file mode 100644 index 000000000..6ffd2058e --- /dev/null +++ b/lib/api/session-delegate.d.ts.map @@ -0,0 +1 @@ +{"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,GAAG,EAAE,MAAM,OAAO,CAAC;AAC5B,OAAO,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AAC9B,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,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAE1E;;;GAGG;AACH,MAAM,WAAW,eAAe;IAC9B;;;OAGG;IACH,KAAK,CAAC,CAAC,GAAG,EAAE,GAAG,GAAG,IAAI,CAAC;IAEvB;;;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;;;OAGG;IACH,SAAS,CAAC,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAAC;IAEnC;;;;;;;OAOG;IACH,QAAQ,CAAC,CAAC,YAAY,EAAE,YAAY,GAAG,IAAI,CAAC;IAE5C;;;OAGG;IACH,OAAO,CAAC,CAAC,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAAC;IAEnC;;;;;;;;;;;;;;;;;;;;;;;;OAwBG;IACH,2BAA2B,CAAC,CAAC,yBAAyB,EAAE,yBAAyB,EAAE,WAAW,EAAE,OAAO,GAAG,IAAI,CAAC;CAChH"} \ No newline at end of file diff --git a/lib/api/session-delegate.js b/lib/api/session-delegate.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/api/session-delegate.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/api/session-description-handler-factory.d.ts b/lib/api/session-description-handler-factory.d.ts new file mode 100644 index 000000000..276d48824 --- /dev/null +++ b/lib/api/session-description-handler-factory.d.ts @@ -0,0 +1,16 @@ +import { Session } from "./session"; +import { SessionDescriptionHandler } from "./session-description-handler"; +/** + * Factory for {@link SessionDescriptionHandler}. + * @public + */ +export interface SessionDescriptionHandlerFactory { + /** + * SessionDescriptionHandler factory function. + * @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 new file mode 100644 index 000000000..ac2624e8d --- /dev/null +++ b/lib/api/session-description-handler-factory.d.ts.map @@ -0,0 +1 @@ +{"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;AAE1E;;;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 new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/api/session-description-handler-factory.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/api/session-description-handler.d.ts b/lib/api/session-description-handler.d.ts new file mode 100644 index 000000000..7a44b4435 --- /dev/null +++ b/lib/api/session-description-handler.d.ts @@ -0,0 +1,75 @@ +/** + * 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; + /** + * 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?: unknown): 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 new file mode 100644 index 000000000..36facd9ec --- /dev/null +++ b/lib/api/session-description-handler.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"session-description-handler.d.ts","sourceRoot":"","sources":["../../src/api/session-description-handler.ts"],"names":[],"mappings":"AAAA;;;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;;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,OAAO,GAAG,OAAO,CAAC;CACrD;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 new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/api/session-description-handler.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/api/session-info-options.d.ts b/lib/api/session-info-options.d.ts new file mode 100644 index 000000000..25b01e787 --- /dev/null +++ b/lib/api/session-info-options.d.ts @@ -0,0 +1,12 @@ +import { OutgoingRequestDelegate, RequestOptions } from "../core"; +/** + * Options for {@link Session.info}. + * @public + */ +export interface SessionInfoOptions { + /** See `core` API. */ + requestDelegate?: OutgoingRequestDelegate; + /** See `core` API. */ + requestOptions?: RequestOptions; +} +//# sourceMappingURL=session-info-options.d.ts.map \ No newline at end of file diff --git a/lib/api/session-info-options.d.ts.map b/lib/api/session-info-options.d.ts.map new file mode 100644 index 000000000..76455fbdc --- /dev/null +++ b/lib/api/session-info-options.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"session-info-options.d.ts","sourceRoot":"","sources":["../../src/api/session-info-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAElE;;;GAGG;AACH,MAAM,WAAW,kBAAkB;IACjC,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/session-info-options.js b/lib/api/session-info-options.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/api/session-info-options.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/api/session-invite-options.d.ts b/lib/api/session-invite-options.d.ts new file mode 100644 index 000000000..bcd3cf7e8 --- /dev/null +++ b/lib/api/session-invite-options.d.ts @@ -0,0 +1,29 @@ +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; + /** + * Modifiers to pass to SessionDescriptionHandler during re-INVITE transaction. + */ + sessionDescriptionHandlerModifiers?: Array; + /** + * Options to pass to SessionDescriptionHandler during re-INVITE transaction. + */ + 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 new file mode 100644 index 000000000..f33e68e18 --- /dev/null +++ b/lib/api/session-invite-options.d.ts.map @@ -0,0 +1 @@ +{"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,EAAE,iCAAiC,EAAE,gCAAgC,EAAE,MAAM,+BAA+B,CAAC;AAEpH;;;GAGG;AACH,MAAM,WAAW,oBAAoB;IACnC;;OAEG;IACH,eAAe,CAAC,EAAE,uBAAuB,CAAC;IAC1C;;OAEG;IACH,cAAc,CAAC,EAAE,cAAc,CAAC;IAChC;;OAEG;IACH,kCAAkC,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,CAAC;IAC9E;;OAEG;IACH,gCAAgC,CAAC,EAAE,gCAAgC,CAAC;IACpE;;OAEG;IACH,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 new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/api/session-invite-options.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/api/session-message-options.d.ts b/lib/api/session-message-options.d.ts new file mode 100644 index 000000000..0d528d345 --- /dev/null +++ b/lib/api/session-message-options.d.ts @@ -0,0 +1,12 @@ +import { OutgoingRequestDelegate, RequestOptions } from "../core"; +/** + * Options for {@link Session.message}. + * @public + */ +export interface SessionMessageOptions { + /** See `core` API. */ + requestDelegate?: OutgoingRequestDelegate; + /** See `core` API. */ + requestOptions?: RequestOptions; +} +//# sourceMappingURL=session-message-options.d.ts.map \ No newline at end of file diff --git a/lib/api/session-message-options.d.ts.map b/lib/api/session-message-options.d.ts.map new file mode 100644 index 000000000..ca21f8b56 --- /dev/null +++ b/lib/api/session-message-options.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"session-message-options.d.ts","sourceRoot":"","sources":["../../src/api/session-message-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAElE;;;GAGG;AACH,MAAM,WAAW,qBAAqB;IACpC,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/session-message-options.js b/lib/api/session-message-options.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/api/session-message-options.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/api/session-options.d.ts b/lib/api/session-options.d.ts new file mode 100644 index 000000000..ea5e9b0fc --- /dev/null +++ b/lib/api/session-options.d.ts @@ -0,0 +1,9 @@ +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 new file mode 100644 index 000000000..fd9033393 --- /dev/null +++ b/lib/api/session-options.d.ts.map @@ -0,0 +1 @@ +{"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 new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/api/session-options.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/api/session-refer-options.d.ts b/lib/api/session-refer-options.d.ts new file mode 100644 index 000000000..dc9c15a00 --- /dev/null +++ b/lib/api/session-refer-options.d.ts @@ -0,0 +1,15 @@ +import { OutgoingRequestDelegate, RequestOptions } from "../core"; +import { Notification } from "./notification"; +/** + * Options for {@link Session.refer}. + * @public + */ +export interface SessionReferOptions { + /** Called upon receiving an incoming NOTIFY associated with a REFER. */ + onNotify?: (notification: Notification) => void; + /** See `core` API. */ + requestDelegate?: OutgoingRequestDelegate; + /** See `core` API. */ + requestOptions?: RequestOptions; +} +//# sourceMappingURL=session-refer-options.d.ts.map \ No newline at end of file diff --git a/lib/api/session-refer-options.d.ts.map b/lib/api/session-refer-options.d.ts.map new file mode 100644 index 000000000..5e4627256 --- /dev/null +++ b/lib/api/session-refer-options.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"session-refer-options.d.ts","sourceRoot":"","sources":["../../src/api/session-refer-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAClE,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAE9C;;;GAGG;AACH,MAAM,WAAW,mBAAmB;IAClC,wEAAwE;IACxE,QAAQ,CAAC,EAAE,CAAC,YAAY,EAAE,YAAY,KAAK,IAAI,CAAC;IAChD,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/session-refer-options.js b/lib/api/session-refer-options.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/api/session-refer-options.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/api/session-state.d.ts b/lib/api/session-state.d.ts new file mode 100644 index 000000000..6706732a4 --- /dev/null +++ b/lib/api/session-state.d.ts @@ -0,0 +1,46 @@ +/** + * {@link Session} state. + * + * @remarks + * The {@link Session} behaves in a deterministic manner according to the following + * Finite State Machine (FSM). + * ```txt + * ___________________________________________________________ + * | ____________________________________________ | + * | | ____________________________ | | + * Session | | | v v v + * Constructed -> Initial -> Establishing -> Established -> Terminating -> Terminated + * | |___________________________^ ^ + * |_______________________________________________| + * ``` + * @public + */ +export declare enum SessionState { + /** + * If `Inviter`, INVITE not sent yet. + * If `Invitation`, received INVITE (but no final response sent yet). + */ + Initial = "Initial", + /** + * If `Inviter`, sent INVITE and waiting for a final response. + * If `Invitation`, received INVITE and attempting to send 200 final response (but has not sent it yet). + */ + Establishing = "Establishing", + /** + * If `Inviter`, sent INVITE and received 200 final response and sent ACK. + * If `Invitation`, received INVITE and sent 200 final response. + */ + Established = "Established", + /** + * If `Inviter`, sent INVITE, sent CANCEL and now waiting for 487 final response to ACK (or 200 to ACK & BYE). + * If `Invitation`, received INVITE, sent 200 final response and now waiting on ACK and upon receipt will attempt BYE + * (as the protocol specification requires, before sending a BYE we must receive the ACK - so we are waiting). + */ + Terminating = "Terminating", + /** + * If `Inviter`, sent INVITE and received non-200 final response (or sent/received BYE after receiving 200). + * If `Invitation`, received INVITE and sent non-200 final response (or sent/received BYE after sending 200). + */ + 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 new file mode 100644 index 000000000..8427a136d --- /dev/null +++ b/lib/api/session-state.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"session-state.d.ts","sourceRoot":"","sources":["../../src/api/session-state.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,oBAAY,YAAY;IACtB;;;OAGG;IACH,OAAO,YAAY;IACnB;;;OAGG;IACH,YAAY,iBAAiB;IAC7B;;;OAGG;IACH,WAAW,gBAAgB;IAC3B;;;;OAIG;IACH,WAAW,gBAAgB;IAC3B;;;OAGG;IACH,UAAU,eAAe;CAC1B"} \ No newline at end of file diff --git a/lib/api/session-state.js b/lib/api/session-state.js new file mode 100644 index 000000000..693137b2a --- /dev/null +++ b/lib/api/session-state.js @@ -0,0 +1,46 @@ +/** + * {@link Session} state. + * + * @remarks + * The {@link Session} behaves in a deterministic manner according to the following + * Finite State Machine (FSM). + * ```txt + * ___________________________________________________________ + * | ____________________________________________ | + * | | ____________________________ | | + * Session | | | v v v + * Constructed -> Initial -> Establishing -> Established -> Terminating -> Terminated + * | |___________________________^ ^ + * |_______________________________________________| + * ``` + * @public + */ +export var SessionState; +(function (SessionState) { + /** + * If `Inviter`, INVITE not sent yet. + * If `Invitation`, received INVITE (but no final response sent yet). + */ + SessionState["Initial"] = "Initial"; + /** + * If `Inviter`, sent INVITE and waiting for a final response. + * If `Invitation`, received INVITE and attempting to send 200 final response (but has not sent it yet). + */ + SessionState["Establishing"] = "Establishing"; + /** + * If `Inviter`, sent INVITE and received 200 final response and sent ACK. + * If `Invitation`, received INVITE and sent 200 final response. + */ + SessionState["Established"] = "Established"; + /** + * If `Inviter`, sent INVITE, sent CANCEL and now waiting for 487 final response to ACK (or 200 to ACK & BYE). + * If `Invitation`, received INVITE, sent 200 final response and now waiting on ACK and upon receipt will attempt BYE + * (as the protocol specification requires, before sending a BYE we must receive the ACK - so we are waiting). + */ + SessionState["Terminating"] = "Terminating"; + /** + * If `Inviter`, sent INVITE and received non-200 final response (or sent/received BYE after receiving 200). + * If `Invitation`, received INVITE and sent non-200 final response (or sent/received BYE after sending 200). + */ + SessionState["Terminated"] = "Terminated"; +})(SessionState || (SessionState = {})); diff --git a/lib/api/session.d.ts b/lib/api/session.d.ts new file mode 100644 index 000000000..421151e74 --- /dev/null +++ b/lib/api/session.d.ts @@ -0,0 +1,360 @@ +import { AckableIncomingResponseWithSession, Body, IncomingAckRequest, IncomingByeRequest, IncomingInfoRequest, IncomingInviteRequest, IncomingMessageRequest, IncomingNotifyRequest, IncomingPrackRequest, IncomingReferRequest, Logger, NameAddrHeader, OutgoingByeRequest, OutgoingInfoRequest, OutgoingInviteRequest, OutgoingMessageRequest, OutgoingReferRequest, OutgoingRequestDelegate, RequestOptions, Session as SessionDialog, URI } from "../core"; +import { Emitter } from "./emitter"; +import { Inviter } from "./inviter"; +import { InviterOptions } from "./inviter-options"; +import { Notification } from "./notification"; +import { SessionByeOptions } from "./session-bye-options"; +import { SessionDelegate } from "./session-delegate"; +import { SessionDescriptionHandler, SessionDescriptionHandlerModifier, SessionDescriptionHandlerOptions } from "./session-description-handler"; +import { SessionDescriptionHandlerFactory } from "./session-description-handler-factory"; +import { SessionInfoOptions } from "./session-info-options"; +import { SessionInviteOptions } from "./session-invite-options"; +import { SessionMessageOptions } from "./session-message-options"; +import { SessionOptions } from "./session-options"; +import { SessionReferOptions } from "./session-refer-options"; +import { SessionState } from "./session-state"; +import { UserAgent } from "./user-agent"; +/** + * A session provides real time communication between one or more participants. + * + * @remarks + * The transport behaves in a deterministic manner according to the + * the state defined in {@link SessionState}. + * @public + */ +export declare abstract class Session { + /** + * Property reserved for use by instance owner. + * @defaultValue `undefined` + */ + data: unknown; + /** + * The session delegate. + * @defaultValue `undefined` + */ + delegate: SessionDelegate | undefined; + /** @internal */ + _contact: string | undefined; + /** @internal */ + _referral: Inviter | undefined; + /** @internal */ + _replacee: Session | undefined; + /** @internal */ + protected _assertedIdentity: NameAddrHeader | undefined; + /** @internal */ + protected _dialog: SessionDialog | undefined; + /** @internal */ + protected _referralInviterOptions: InviterOptions | undefined; + /** @internal */ + protected _renderbody: string | undefined; + /** @internal */ + protected _rendertype: string | undefined; + /** If defined, NOTIFYs associated with a REFER subscription are delivered here. */ + private onNotify; + /** True if there is an outgoing re-INVITE request outstanding. */ + private pendingReinvite; + /** True if there is an incoming re-INVITE ACK request outstanding. */ + private pendingReinviteAck; + /** Dialogs session description handler. */ + private _sessionDescriptionHandler; + /** SDH modifiers for the initial INVITE transaction. */ + private _sessionDescriptionHandlerModifiers; + /** SDH options for the initial INVITE transaction. */ + private _sessionDescriptionHandlerOptions; + /** SDH modifiers for re-INVITE transactions. */ + private _sessionDescriptionHandlerModifiersReInvite; + /** SDH options for re-NVITE transactions.*/ + private _sessionDescriptionHandlerOptionsReInvite; + /** Session state. */ + private _state; + /** Session state emitter. */ + private _stateEventEmitter; + /** User agent. */ + private _userAgent; + /** + * The identity of the local user. + */ + abstract readonly localIdentity: NameAddrHeader; + /** + * The identity of the remote user. + */ + abstract readonly remoteIdentity: NameAddrHeader; + /** + * Logger. + */ + protected abstract logger: Logger; + /** @internal */ + protected abstract _id: string; + /** + * Constructor. + * @param userAgent - User agent. See {@link UserAgent} for details. + * @internal + */ + protected constructor(userAgent: UserAgent, options?: SessionOptions); + /** + * Destructor. + */ + dispose(): Promise; + /** + * The asserted identity of the remote user. + */ + get assertedIdentity(): NameAddrHeader | undefined; + /** + * The confirmed session dialog. + */ + get dialog(): SessionDialog | undefined; + /** + * A unique identifier for this session. + */ + get id(): string; + /** + * The session being replace by this one. + */ + get replacee(): Session | undefined; + /** + * Session description handler. + * @remarks + * If `this` is an instance of `Invitation`, + * `sessionDescriptionHandler` will be defined when the session state changes to "established". + * If `this` is an instance of `Inviter` and an offer was sent in the INVITE, + * `sessionDescriptionHandler` will be defined when the session state changes to "establishing". + * If `this` is an instance of `Inviter` and an offer was not sent in the INVITE, + * `sessionDescriptionHandler` will be defined when the session state changes to "established". + * Otherwise `undefined`. + */ + get sessionDescriptionHandler(): SessionDescriptionHandler | undefined; + /** + * Session description handler factory. + */ + get sessionDescriptionHandlerFactory(): SessionDescriptionHandlerFactory; + /** + * SDH modifiers for the initial INVITE transaction. + * @remarks + * Used in all cases when handling the initial INVITE transaction as either UAC or UAS. + * May be set directly at anytime. + * May optionally be set via constructor option. + * May optionally be set via options passed to Inviter.invite() or Invitation.accept(). + */ + get sessionDescriptionHandlerModifiers(): Array; + set sessionDescriptionHandlerModifiers(modifiers: Array); + /** + * SDH options for the initial INVITE transaction. + * @remarks + * Used in all cases when handling the initial INVITE transaction as either UAC or UAS. + * May be set directly at anytime. + * May optionally be set via constructor option. + * May optionally be set via options passed to Inviter.invite() or Invitation.accept(). + */ + get sessionDescriptionHandlerOptions(): SessionDescriptionHandlerOptions; + set sessionDescriptionHandlerOptions(options: SessionDescriptionHandlerOptions); + /** + * SDH modifiers for re-INVITE transactions. + * @remarks + * Used in all cases when handling a re-INVITE transaction as either UAC or UAS. + * May be set directly at anytime. + * May optionally be set via constructor option. + * May optionally be set via options passed to Session.invite(). + */ + get sessionDescriptionHandlerModifiersReInvite(): Array; + set sessionDescriptionHandlerModifiersReInvite(modifiers: Array); + /** + * SDH options for re-INVITE transactions. + * @remarks + * Used in all cases when handling a re-INVITE transaction as either UAC or UAS. + * May be set directly at anytime. + * May optionally be set via constructor option. + * May optionally be set via options passed to Session.invite(). + */ + get sessionDescriptionHandlerOptionsReInvite(): SessionDescriptionHandlerOptions; + set sessionDescriptionHandlerOptionsReInvite(options: SessionDescriptionHandlerOptions); + /** + * Session state. + */ + get state(): SessionState; + /** + * Session state change emitter. + */ + get stateChange(): Emitter; + /** + * The user agent. + */ + get userAgent(): UserAgent; + /** + * End the {@link Session}. Sends a BYE. + * @param options - Options bucket. See {@link SessionByeOptions} for details. + */ + bye(options?: SessionByeOptions): Promise; + /** + * Share {@link Info} with peer. Sends an INFO. + * @param options - Options bucket. See {@link SessionInfoOptions} for details. + */ + info(options?: SessionInfoOptions): Promise; + /** + * Renegotiate the session. Sends a re-INVITE. + * @param options - Options bucket. See {@link SessionInviteOptions} for details. + */ + invite(options?: SessionInviteOptions): Promise; + /** + * Deliver a {@link Message}. Sends a MESSAGE. + * @param options - Options bucket. See {@link SessionMessageOptions} for details. + */ + message(options?: SessionMessageOptions): Promise; + /** + * Proffer a {@link Referral}. Send a REFER. + * @param referTo - The referral target. If a `Session`, a REFER w/Replaces is sent. + * @param options - Options bucket. See {@link SessionReferOptions} for details. + */ + refer(referTo: URI | Session, options?: SessionReferOptions): Promise; + /** + * 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 MESSAGE. + * @param delegate - Request delegate. + * @param options - Request options bucket. + * @internal + */ + _message(delegate?: OutgoingRequestDelegate, options?: RequestOptions): Promise; + /** + * Send REFER. + * @param onNotify - Notification callback. + * @param delegate - Request delegate. + * @param options - Request options bucket. + * @internal + */ + _refer(onNotify?: (notification: Notification) => void, delegate?: OutgoingRequestDelegate, options?: RequestOptions): Promise; + /** + * 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 send a BYE. + * Note that the BYE is sent in the dialog associated with the response + * which is not necessarily `this.dialog`. And, accordingly, the + * session state is not transitioned to terminated and session is not closed. + * @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): Promise; + /** + * 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 MESSAGE request. + * @internal + */ + protected onMessageRequest(request: IncomingMessageRequest): 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; + /** + * 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; + private copyRequestOptions; + private getReasonHeaderValue; + private referExtraHeaders; + private referToString; +} +//# 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 new file mode 100644 index 000000000..968531dcb --- /dev/null +++ b/lib/api/session.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../../src/api/session.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kCAAkC,EAClC,IAAI,EAIJ,kBAAkB,EAClB,kBAAkB,EAClB,mBAAmB,EACnB,qBAAqB,EACrB,sBAAsB,EACtB,qBAAqB,EACrB,oBAAoB,EACpB,oBAAoB,EACpB,MAAM,EACN,cAAc,EACd,kBAAkB,EAClB,mBAAmB,EACnB,qBAAqB,EAErB,sBAAsB,EACtB,oBAAoB,EACpB,uBAAuB,EACvB,cAAc,EACd,OAAO,IAAI,aAAa,EAGxB,GAAG,EACJ,MAAM,SAAS,CAAC;AAIjB,OAAO,EAAE,OAAO,EAAe,MAAM,WAAW,CAAC;AAGjD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAEnD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAE9C,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAC1D,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,EACL,yBAAyB,EACzB,iCAAiC,EACjC,gCAAgC,EACjC,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,gCAAgC,EAAE,MAAM,uCAAuC,CAAC;AACzF,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAC5D,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAChE,OAAO,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AAClE,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAC9D,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC;;;;;;;GAOG;AACH,8BAAsB,OAAO;IAC3B;;;OAGG;IACI,IAAI,EAAE,OAAO,CAAC;IAErB;;;OAGG;IACI,QAAQ,EAAE,eAAe,GAAG,SAAS,CAAC;IAK7C,gBAAgB;IACT,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IACpC,gBAAgB;IACT,SAAS,EAAE,OAAO,GAAG,SAAS,CAAC;IACtC,gBAAgB;IACT,SAAS,EAAE,OAAO,GAAG,SAAS,CAAC;IAKtC,gBAAgB;IAChB,SAAS,CAAC,iBAAiB,EAAE,cAAc,GAAG,SAAS,CAAC;IACxD,gBAAgB;IAChB,SAAS,CAAC,OAAO,EAAE,aAAa,GAAG,SAAS,CAAC;IAC7C,gBAAgB;IAChB,SAAS,CAAC,uBAAuB,EAAE,cAAc,GAAG,SAAS,CAAC;IAC9D,gBAAgB;IAChB,SAAS,CAAC,WAAW,EAAE,MAAM,GAAG,SAAS,CAAC;IAC1C,gBAAgB;IAChB,SAAS,CAAC,WAAW,EAAE,MAAM,GAAG,SAAS,CAAC;IAE1C,mFAAmF;IACnF,OAAO,CAAC,QAAQ,CAAqD;IACrE,kEAAkE;IAClE,OAAO,CAAC,eAAe,CAAS;IAChC,sEAAsE;IACtE,OAAO,CAAC,kBAAkB,CAAS;IACnC,2CAA2C;IAC3C,OAAO,CAAC,0BAA0B,CAAwC;IAC1E,wDAAwD;IACxD,OAAO,CAAC,mCAAmC,CAAuD;IAClG,sDAAsD;IACtD,OAAO,CAAC,iCAAiC,CAA+C;IACxF,gDAAgD;IAChD,OAAO,CAAC,2CAA2C,CAAuD;IAC1G,4CAA4C;IAC5C,OAAO,CAAC,yCAAyC,CAA+C;IAChG,qBAAqB;IACrB,OAAO,CAAC,MAAM,CAAsC;IACpD,6BAA6B;IAC7B,OAAO,CAAC,kBAAkB,CAA4B;IACtD,kBAAkB;IAClB,OAAO,CAAC,UAAU,CAAY;IAE9B;;OAEG;IACH,kBAAyB,aAAa,EAAE,cAAc,CAAC;IAEvD;;OAEG;IACH,kBAAyB,cAAc,EAAE,cAAc,CAAC;IAExD;;OAEG;IACH,SAAS,CAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IAElC,gBAAgB;IAChB,SAAS,CAAC,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IAE/B;;;;OAIG;IACH,SAAS,aAAa,SAAS,EAAE,SAAS,EAAE,OAAO,GAAE,cAAmB;IAMxE;;OAEG;IACI,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAkD/B;;OAEG;IACH,IAAW,gBAAgB,IAAI,cAAc,GAAG,SAAS,CAExD;IAED;;OAEG;IACH,IAAW,MAAM,IAAI,aAAa,GAAG,SAAS,CAE7C;IAED;;OAEG;IACH,IAAW,EAAE,IAAI,MAAM,CAEtB;IAED;;OAEG;IACH,IAAW,QAAQ,IAAI,OAAO,GAAG,SAAS,CAEzC;IAED;;;;;;;;;;OAUG;IACH,IAAW,yBAAyB,IAAI,yBAAyB,GAAG,SAAS,CAE5E;IAED;;OAEG;IACH,IAAW,gCAAgC,IAAI,gCAAgC,CAE9E;IAED;;;;;;;OAOG;IACH,IAAW,kCAAkC,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAExF;IAED,IAAW,kCAAkC,CAAC,SAAS,EAAE,KAAK,CAAC,iCAAiC,CAAC,EAEhG;IAED;;;;;;;OAOG;IACH,IAAW,gCAAgC,IAAI,gCAAgC,CAE9E;IAED,IAAW,gCAAgC,CAAC,OAAO,EAAE,gCAAgC,EAEpF;IAED;;;;;;;OAOG;IACH,IAAW,0CAA0C,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAEhG;IAED,IAAW,0CAA0C,CAAC,SAAS,EAAE,KAAK,CAAC,iCAAiC,CAAC,EAExG;IAED;;;;;;;OAOG;IACH,IAAW,wCAAwC,IAAI,gCAAgC,CAEtF;IAED,IAAW,wCAAwC,CAAC,OAAO,EAAE,gCAAgC,EAE5F;IAED;;OAEG;IACH,IAAW,KAAK,IAAI,YAAY,CAE/B;IAED;;OAEG;IACH,IAAW,WAAW,IAAI,OAAO,CAAC,YAAY,CAAC,CAE9C;IAED;;OAEG;IACH,IAAW,SAAS,IAAI,SAAS,CAEhC;IAED;;;OAGG;IACI,GAAG,CAAC,OAAO,GAAE,iBAAsB,GAAG,OAAO,CAAC,kBAAkB,CAAC;IAoDxE;;;OAGG;IACI,IAAI,CAAC,OAAO,GAAE,kBAAuB,GAAG,OAAO,CAAC,mBAAmB,CAAC;IAa3E;;;OAGG;IACI,MAAM,CAAC,OAAO,GAAE,oBAAyB,GAAG,OAAO,CAAC,qBAAqB,CAAC;IAyLjF;;;OAGG;IACI,OAAO,CAAC,OAAO,GAAE,qBAA0B,GAAG,OAAO,CAAC,sBAAsB,CAAC;IAapF;;;;OAIG;IACI,KAAK,CAAC,OAAO,EAAE,GAAG,GAAG,OAAO,EAAE,OAAO,GAAE,mBAAwB,GAAG,OAAO,CAAC,oBAAoB,CAAC;IAgBtG;;;;;OAKG;IACI,IAAI,CAAC,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,kBAAkB,CAAC;IAmDtG;;;;;OAKG;IACI,KAAK,CAAC,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,mBAAmB,CAAC;IAQxG;;;;;OAKG;IACI,QAAQ,CAAC,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,sBAAsB,CAAC;IAQ9G;;;;;;OAMG;IACI,MAAM,CACX,QAAQ,CAAC,EAAE,CAAC,YAAY,EAAE,YAAY,KAAK,IAAI,EAC/C,QAAQ,CAAC,EAAE,uBAAuB,EAClC,OAAO,CAAC,EAAE,cAAc,GACvB,OAAO,CAAC,kBAAkB,CAAC;IAU9B;;;;;;;;;;;OAWG;IACH,SAAS,CAAC,SAAS,CAAC,QAAQ,EAAE,kCAAkC,EAAE,UAAU,CAAC,EAAE,MAAM,EAAE,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI;IAUnH;;;OAGG;IACH,SAAS,CAAC,YAAY,CAAC,OAAO,EAAE,kBAAkB,GAAG,OAAO,CAAC,IAAI,CAAC;IAmFlE;;;OAGG;IACH,SAAS,CAAC,YAAY,CAAC,OAAO,EAAE,kBAAkB,GAAG,IAAI;IAezD;;;OAGG;IACH,SAAS,CAAC,aAAa,CAAC,OAAO,EAAE,mBAAmB,GAAG,IAAI;IAuB3D;;;OAGG;IACH,SAAS,CAAC,eAAe,CAAC,OAAO,EAAE,qBAAqB,GAAG,IAAI;IAiF/D;;;OAGG;IACH,SAAS,CAAC,gBAAgB,CAAC,OAAO,EAAE,sBAAsB,GAAG,IAAI;IAejE;;;OAGG;IACH,SAAS,CAAC,eAAe,CAAC,OAAO,EAAE,qBAAqB,GAAG,IAAI;IAwB/D;;;OAGG;IAEH,SAAS,CAAC,cAAc,CAAC,OAAO,EAAE,oBAAoB,GAAG,IAAI;IAU7D;;;OAGG;IACH,SAAS,CAAC,cAAc,CAAC,OAAO,EAAE,oBAAoB,GAAG,IAAI;IAgC7D;;;;;;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,CAAC;KAC/E,GACA,OAAO,CAAC,IAAI,GAAG,SAAS,CAAC;IAY5B;;;;;OAKG;IACH,SAAS,CAAC,mCAAmC,CAAC,OAAO,EAAE;QACrD,gCAAgC,CAAC,EAAE,gCAAgC,CAAC;QACpE,kCAAkC,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,CAAC;KAC/E,GAAG,OAAO,CAAC,IAAI,GAAG,SAAS,CAAC;IAuC7B;;;OAGG;IACH,SAAS,CAAC,QAAQ,CAAC,OAAO,EAAE;QAC1B,gCAAgC,CAAC,EAAE,gCAAgC,CAAC;QACpE,kCAAkC,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,CAAC;KAC/E,GAAG,OAAO,CAAC,IAAI,CAAC;IAyBjB;;;OAGG;IACH,SAAS,CAAC,aAAa,IAAI,OAAO,CAAC,IAAI,CAAC;IAuBxC;;;OAGG;IACH,SAAS,CAAC,SAAS,CACjB,MAAM,EAAE,IAAI,EACZ,OAAO,EAAE;QACP,gCAAgC,CAAC,EAAE,gCAAgC,CAAC;QACpE,kCAAkC,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,CAAC;KAC/E,GACA,OAAO,CAAC,IAAI,CAAC;IAgChB;;;OAGG;IACH,SAAS,CAAC,oBAAoB,CAC5B,KAAK,EAAE,IAAI,EACX,OAAO,EAAE;QACP,gCAAgC,CAAC,EAAE,gCAAgC,CAAC;QACpE,kCAAkC,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,CAAC;KAC/E,GACA,OAAO,CAAC,IAAI,CAAC;IAoChB;;;OAGG;IACH,SAAS,CAAC,4BAA4B,CAAC,GAAG,EAAE,yBAAyB,GAAG,IAAI;IAO5E;;;OAGG;IACH,SAAS,CAAC,8BAA8B,IAAI,yBAAyB;IAcrE;;;OAGG;IACH,SAAS,CAAC,eAAe,CAAC,QAAQ,EAAE,YAAY,GAAG,IAAI;IAsDvD,OAAO,CAAC,kBAAkB;IAe1B,OAAO,CAAC,oBAAoB;IAS5B,OAAO,CAAC,iBAAiB;IAWzB,OAAO,CAAC,aAAa;CAoBtB"} \ No newline at end of file diff --git a/lib/api/session.js b/lib/api/session.js new file mode 100644 index 000000000..8a908f467 --- /dev/null +++ b/lib/api/session.js @@ -0,0 +1,1229 @@ +import { fromBodyLegacy, getBody, Grammar, SessionState as SessionDialogState, SignalingState, URI } from "../core"; +import { getReasonPhrase } from "../core/messages/utils"; +import { AllowedMethods } from "../core/user-agent-core/allowed-methods"; +import { Bye } from "./bye"; +import { EmitterImpl } from "./emitter"; +import { ContentTypeUnsupportedError, RequestPendingError } from "./exceptions"; +import { Info } from "./info"; +import { Message } from "./message"; +import { Notification } from "./notification"; +import { Referral } from "./referral"; +import { SessionState } from "./session-state"; +/** + * A session provides real time communication between one or more participants. + * + * @remarks + * The transport behaves in a deterministic manner according to the + * the state defined in {@link SessionState}. + * @public + */ +export class Session { + /** + * Constructor. + * @param userAgent - User agent. See {@link UserAgent} for details. + * @internal + */ + constructor(userAgent, options = {}) { + /** True if there is an outgoing re-INVITE request outstanding. */ + this.pendingReinvite = false; + /** True if there is an incoming re-INVITE ACK request outstanding. */ + this.pendingReinviteAck = false; + /** Session state. */ + this._state = SessionState.Initial; + this.delegate = options.delegate; + this._stateEventEmitter = new EmitterImpl(); + this._userAgent = userAgent; + } + /** + * Destructor. + */ + dispose() { + this.logger.log(`Session ${this.id} in state ${this._state} is being disposed`); + // Remove from the user agent's session collection + delete this.userAgent._sessions[this.id]; + // Dispose of dialog media + if (this._sessionDescriptionHandler) { + this._sessionDescriptionHandler.close(); + // TODO: The SDH needs to remain defined as it will be called after it is closed in cases + // where an answer/offer arrives while the session is being torn down. There are a variety + // of circumstances where this can happen - sending a BYE during a re-INVITE for example. + // The code is currently written such that it lazily makes a new SDH when it needs one + // and one is not yet defined. Thus if we undefined it here, it will currently make a + // new one which is out of sync and then never gets cleaned up. + // + // The downside of leaving it defined are that calls this closed SDH will continue to be + // made (think setDescription) and those should/will fail. These failures are handled, but + // it would be nice to have it all coded up in a way where having an undefined SDH where + // one is expected throws an error. + // + // this._sessionDescriptionHandler = undefined; + } + switch (this.state) { + case SessionState.Initial: + break; // the Inviter/Invitation sub class dispose method handles this case + case SessionState.Establishing: + break; // the Inviter/Invitation sub class dispose method handles this case + case SessionState.Established: + return new Promise((resolve) => { + this._bye({ + // wait for the response to the BYE before resolving + onAccept: () => resolve(), + onRedirect: () => resolve(), + onReject: () => resolve() + }); + }); + case SessionState.Terminating: + break; // nothing to be done + case SessionState.Terminated: + break; // nothing to be done + default: + throw new Error("Unknown state."); + } + return Promise.resolve(); + } + /** + * The asserted identity of the remote user. + */ + get assertedIdentity() { + return this._assertedIdentity; + } + /** + * The confirmed session dialog. + */ + get dialog() { + return this._dialog; + } + /** + * A unique identifier for this session. + */ + get id() { + return this._id; + } + /** + * The session being replace by this one. + */ + get replacee() { + return this._replacee; + } + /** + * Session description handler. + * @remarks + * If `this` is an instance of `Invitation`, + * `sessionDescriptionHandler` will be defined when the session state changes to "established". + * If `this` is an instance of `Inviter` and an offer was sent in the INVITE, + * `sessionDescriptionHandler` will be defined when the session state changes to "establishing". + * If `this` is an instance of `Inviter` and an offer was not sent in the INVITE, + * `sessionDescriptionHandler` will be defined when the session state changes to "established". + * Otherwise `undefined`. + */ + get sessionDescriptionHandler() { + return this._sessionDescriptionHandler; + } + /** + * Session description handler factory. + */ + get sessionDescriptionHandlerFactory() { + return this.userAgent.configuration.sessionDescriptionHandlerFactory; + } + /** + * SDH modifiers for the initial INVITE transaction. + * @remarks + * Used in all cases when handling the initial INVITE transaction as either UAC or UAS. + * May be set directly at anytime. + * May optionally be set via constructor option. + * May optionally be set via options passed to Inviter.invite() or Invitation.accept(). + */ + get sessionDescriptionHandlerModifiers() { + return this._sessionDescriptionHandlerModifiers || []; + } + set sessionDescriptionHandlerModifiers(modifiers) { + this._sessionDescriptionHandlerModifiers = modifiers.slice(); + } + /** + * SDH options for the initial INVITE transaction. + * @remarks + * Used in all cases when handling the initial INVITE transaction as either UAC or UAS. + * May be set directly at anytime. + * May optionally be set via constructor option. + * May optionally be set via options passed to Inviter.invite() or Invitation.accept(). + */ + get sessionDescriptionHandlerOptions() { + return this._sessionDescriptionHandlerOptions || {}; + } + set sessionDescriptionHandlerOptions(options) { + this._sessionDescriptionHandlerOptions = Object.assign({}, options); + } + /** + * SDH modifiers for re-INVITE transactions. + * @remarks + * Used in all cases when handling a re-INVITE transaction as either UAC or UAS. + * May be set directly at anytime. + * May optionally be set via constructor option. + * May optionally be set via options passed to Session.invite(). + */ + get sessionDescriptionHandlerModifiersReInvite() { + return this._sessionDescriptionHandlerModifiersReInvite || []; + } + set sessionDescriptionHandlerModifiersReInvite(modifiers) { + this._sessionDescriptionHandlerModifiersReInvite = modifiers.slice(); + } + /** + * SDH options for re-INVITE transactions. + * @remarks + * Used in all cases when handling a re-INVITE transaction as either UAC or UAS. + * May be set directly at anytime. + * May optionally be set via constructor option. + * May optionally be set via options passed to Session.invite(). + */ + get sessionDescriptionHandlerOptionsReInvite() { + return this._sessionDescriptionHandlerOptionsReInvite || {}; + } + set sessionDescriptionHandlerOptionsReInvite(options) { + this._sessionDescriptionHandlerOptionsReInvite = Object.assign({}, options); + } + /** + * Session state. + */ + get state() { + return this._state; + } + /** + * Session state change emitter. + */ + get stateChange() { + return this._stateEventEmitter; + } + /** + * The user agent. + */ + get userAgent() { + return this._userAgent; + } + /** + * End the {@link Session}. Sends a BYE. + * @param options - Options bucket. See {@link SessionByeOptions} for details. + */ + bye(options = {}) { + let message = "Session.bye() may only be called if established session."; + switch (this.state) { + case SessionState.Initial: + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (typeof this.cancel === "function") { + message += " However Inviter.invite() has not yet been called."; + message += " Perhaps you should have called Inviter.cancel()?"; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } + else if (typeof this.reject === "function") { + message += " However Invitation.accept() has not yet been called."; + message += " Perhaps you should have called Invitation.reject()?"; + } + break; + case SessionState.Establishing: + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (typeof this.cancel === "function") { + message += " However a dialog does not yet exist."; + message += " Perhaps you should have called Inviter.cancel()?"; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } + else if (typeof this.reject === "function") { + message += " However Invitation.accept() has not yet been called (or not yet resolved)."; + message += " Perhaps you should have called Invitation.reject()?"; + } + break; + case SessionState.Established: { + const requestDelegate = options.requestDelegate; + const requestOptions = this.copyRequestOptions(options.requestOptions); + return this._bye(requestDelegate, requestOptions); + } + case SessionState.Terminating: + message += " However this session is already terminating."; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (typeof this.cancel === "function") { + message += " Perhaps you have already called Inviter.cancel()?"; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } + else if (typeof this.reject === "function") { + message += " Perhaps you have already called Session.bye()?"; + } + break; + case SessionState.Terminated: + message += " However this session is already terminated."; + break; + default: + throw new Error("Unknown state"); + } + this.logger.error(message); + return Promise.reject(new Error(`Invalid session state ${this.state}`)); + } + /** + * Share {@link Info} with peer. Sends an INFO. + * @param options - Options bucket. See {@link SessionInfoOptions} for details. + */ + info(options = {}) { + // guard session state + if (this.state !== SessionState.Established) { + const message = "Session.info() may only be called if established session."; + this.logger.error(message); + return Promise.reject(new Error(`Invalid session state ${this.state}`)); + } + const requestDelegate = options.requestDelegate; + const requestOptions = this.copyRequestOptions(options.requestOptions); + return this._info(requestDelegate, requestOptions); + } + /** + * Renegotiate the session. Sends a re-INVITE. + * @param options - Options bucket. See {@link SessionInviteOptions} for details. + */ + invite(options = {}) { + this.logger.log("Session.invite"); + if (this.state !== SessionState.Established) { + return Promise.reject(new Error(`Invalid session state ${this.state}`)); + } + if (this.pendingReinvite) { + return Promise.reject(new RequestPendingError("Reinvite in progress. Please wait until complete, then try again.")); + } + this.pendingReinvite = true; + // Modifiers and options for initial INVITE transaction + if (options.sessionDescriptionHandlerModifiers) { + this.sessionDescriptionHandlerModifiersReInvite = options.sessionDescriptionHandlerModifiers; + } + if (options.sessionDescriptionHandlerOptions) { + this.sessionDescriptionHandlerOptionsReInvite = options.sessionDescriptionHandlerOptions; + } + const delegate = { + onAccept: (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 + const body = 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(SessionState.Terminated); + this.pendingReinvite = false; + return; + } + if (options.withoutSdp) { + // INVITE without SDP - set remote offer and send an answer in the ACK + const answerOptions = { + sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptionsReInvite, + sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiersReInvite + }; + this.setOfferAndGetAnswer(body, answerOptions) + .then((answerBody) => { + response.ack({ body: answerBody }); + }) + .catch((error) => { + // No way to recover, so terminate session and mark as failed. + this.logger.error("Failed to handle offer in 2xx response to re-INVITE"); + this.logger.error(error.message); + if (this.state === SessionState.Terminated) { + // A BYE should not be sent if already terminated. + // For example, a BYE may be sent/received while re-INVITE is outstanding. + response.ack(); + } + else { + this.ackAndBye(response, 488, "Bad Media Description"); + this.stateTransition(SessionState.Terminated); + } + }) + .then(() => { + this.pendingReinvite = false; + if (options.requestDelegate && options.requestDelegate.onAccept) { + options.requestDelegate.onAccept(response); + } + }); + } + else { + // INVITE with SDP - set remote answer and send an ACK + const answerOptions = { + sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptionsReInvite, + sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiersReInvite + }; + this.setAnswer(body, answerOptions) + .then(() => { + response.ack(); + }) + .catch((error) => { + // No way to recover, so terminate session and mark as failed. + this.logger.error("Failed to handle answer in 2xx response to re-INVITE"); + this.logger.error(error.message); + // A BYE should only be sent if session is not already terminated. + // For example, a BYE may be sent/received while re-INVITE is outstanding. + // The ACK needs to be sent regardless as it was not handled by the transaction. + if (this.state !== SessionState.Terminated) { + this.ackAndBye(response, 488, "Bad Media Description"); + this.stateTransition(SessionState.Terminated); + } + else { + response.ack(); + } + }) + .then(() => { + this.pendingReinvite = false; + if (options.requestDelegate && options.requestDelegate.onAccept) { + options.requestDelegate.onAccept(response); + } + }); + } + }, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onProgress: (response) => { + return; + }, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onRedirect: (response) => { + return; + }, + onReject: (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((error) => { + // No way to recover, so terminate session and mark as failed. + this.logger.error("Failed to rollback offer on non-2xx response to re-INVITE"); + this.logger.error(error.message); + // A BYE should only be sent if session is not already terminated. + // For example, a BYE may be sent/received while re-INVITE is outstanding. + // Note that the ACK was already sent by the transaction, so just need to send BYE. + if (this.state !== SessionState.Terminated) { + if (!this.dialog) { + throw new Error("Dialog undefined."); + } + const extraHeaders = []; + extraHeaders.push("Reason: " + this.getReasonHeaderValue(500, "Internal Server Error")); + this.dialog.bye(undefined, { extraHeaders }); + this.stateTransition(SessionState.Terminated); + } + }) + .then(() => { + if (options.requestDelegate && options.requestDelegate.onReject) { + options.requestDelegate.onReject(response); + } + }); + } + }, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onTrying: (response) => { + return; + } + }; + const requestOptions = options.requestOptions || {}; + requestOptions.extraHeaders = (requestOptions.extraHeaders || []).slice(); + requestOptions.extraHeaders.push("Allow: " + AllowedMethods.toString()); + requestOptions.extraHeaders.push("Contact: " + this._contact); + // Just send an INVITE with no sdp... + if (options.withoutSdp) { + if (!this.dialog) { + this.pendingReinvite = false; + throw new Error("Dialog undefined."); + } + return Promise.resolve(this.dialog.invite(delegate, requestOptions)); + } + // Get an offer and send it in an INVITE + const offerOptions = { + sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptionsReInvite, + sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiersReInvite + }; + return this.getOffer(offerOptions) + .then((offerBody) => { + if (!this.dialog) { + this.pendingReinvite = false; + throw new Error("Dialog undefined."); + } + requestOptions.body = offerBody; + return this.dialog.invite(delegate, requestOptions); + }) + .catch((error) => { + this.logger.error(error.message); + this.logger.error("Failed to send re-INVITE"); + this.pendingReinvite = false; + throw error; + }); + } + /** + * Deliver a {@link Message}. Sends a MESSAGE. + * @param options - Options bucket. See {@link SessionMessageOptions} for details. + */ + message(options = {}) { + // guard session state + if (this.state !== SessionState.Established) { + const message = "Session.message() may only be called if established session."; + this.logger.error(message); + return Promise.reject(new Error(`Invalid session state ${this.state}`)); + } + const requestDelegate = options.requestDelegate; + const requestOptions = this.copyRequestOptions(options.requestOptions); + return this._message(requestDelegate, requestOptions); + } + /** + * Proffer a {@link Referral}. Send a REFER. + * @param referTo - The referral target. If a `Session`, a REFER w/Replaces is sent. + * @param options - Options bucket. See {@link SessionReferOptions} for details. + */ + refer(referTo, options = {}) { + // guard session state + if (this.state !== SessionState.Established) { + const message = "Session.refer() may only be called if established session."; + this.logger.error(message); + return Promise.reject(new Error(`Invalid session state ${this.state}`)); + } + const requestDelegate = options.requestDelegate; + const requestOptions = this.copyRequestOptions(options.requestOptions); + requestOptions.extraHeaders = requestOptions.extraHeaders + ? requestOptions.extraHeaders.concat(this.referExtraHeaders(this.referToString(referTo))) + : this.referExtraHeaders(this.referToString(referTo)); + return this._refer(options.onNotify, requestDelegate, requestOptions); + } + /** + * Send BYE. + * @param delegate - Request delegate. + * @param options - Request options bucket. + * @internal + */ + _bye(delegate, options) { + // Using core session dialog + if (!this.dialog) { + return Promise.reject(new Error("Session dialog undefined.")); + } + const 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 SessionDialogState.Initial: + throw new Error(`Invalid dialog state ${dialog.sessionState}`); + case SessionDialogState.Early: // Implementation choice - not sending BYE for early dialogs. + throw new Error(`Invalid dialog state ${dialog.sessionState}`); + case SessionDialogState.AckWait: { + // This state only occurs if we are the callee. + this.stateTransition(SessionState.Terminating); // We're terminating + return new Promise((resolve) => { + dialog.delegate = { + // When ACK shows up, say BYE. + onAck: () => { + const request = dialog.bye(delegate, options); + this.stateTransition(SessionState.Terminated); + resolve(request); + return Promise.resolve(); + }, + // Or the server transaction times out before the ACK arrives. + onAckTimeout: () => { + const request = dialog.bye(delegate, options); + this.stateTransition(SessionState.Terminated); + resolve(request); + } + }; + }); + } + case SessionDialogState.Confirmed: { + const request = dialog.bye(delegate, options); + this.stateTransition(SessionState.Terminated); + return Promise.resolve(request); + } + case SessionDialogState.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 + */ + _info(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 MESSAGE. + * @param delegate - Request delegate. + * @param options - Request options bucket. + * @internal + */ + _message(delegate, options) { + // Using core session dialog + if (!this.dialog) { + return Promise.reject(new Error("Session dialog undefined.")); + } + return Promise.resolve(this.dialog.message(delegate, options)); + } + /** + * Send REFER. + * @param onNotify - Notification callback. + * @param delegate - Request delegate. + * @param options - Request options bucket. + * @internal + */ + _refer(onNotify, delegate, options) { + // Using core session dialog + if (!this.dialog) { + return Promise.reject(new Error("Session dialog undefined.")); + } + // If set, deliver any in-dialog NOTIFY requests here... + this.onNotify = onNotify; + return Promise.resolve(this.dialog.refer(delegate, options)); + } + /** + * 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 send a BYE. + * Note that the BYE is sent in the dialog associated with the response + * which is not necessarily `this.dialog`. And, accordingly, the + * session state is not transitioned to terminated and session is not closed. + * @param inviteResponse - The response causing the error. + * @param statusCode - Status code for he reason phrase. + * @param reasonPhrase - Reason phrase for the BYE. + * @internal + */ + ackAndBye(response, statusCode, reasonPhrase) { + response.ack(); + const extraHeaders = []; + if (statusCode) { + extraHeaders.push("Reason: " + this.getReasonHeaderValue(statusCode, reasonPhrase)); + } + // Using the dialog session associate with the response (which might not be this.dialog) + response.session.bye(undefined, { extraHeaders }); + } + /** + * Handle in dialog ACK request. + * @internal + */ + onAckRequest(request) { + this.logger.log("Session.onAckRequest"); + if (this.state !== SessionState.Established && this.state !== SessionState.Terminating) { + this.logger.error(`ACK received while in state ${this.state}, dropping request`); + return Promise.resolve(); + } + const dialog = this.dialog; + if (!dialog) { + throw new Error("Dialog undefined."); + } + // if received answer in ACK. + const answerOptions = { + sessionDescriptionHandlerOptions: this.pendingReinviteAck + ? this.sessionDescriptionHandlerOptionsReInvite + : this.sessionDescriptionHandlerOptions, + sessionDescriptionHandlerModifiers: this.pendingReinviteAck + ? this._sessionDescriptionHandlerModifiersReInvite + : this._sessionDescriptionHandlerModifiers + }; + // reset pending ACK flag + this.pendingReinviteAck = false; + switch (dialog.signalingState) { + case SignalingState.Initial: { + // State should never be reached as first reliable response must have answer/offer. + // So we must have never has sent an offer. + this.logger.error(`Invalid signaling state ${dialog.signalingState}.`); + const extraHeaders = ["Reason: " + this.getReasonHeaderValue(488, "Bad Media Description")]; + dialog.bye(undefined, { extraHeaders }); + this.stateTransition(SessionState.Terminated); + return Promise.resolve(); + } + case SignalingState.Stable: { + // State we should be in. + // Either the ACK has the answer that got us here, or we were in this state prior to the ACK. + const body = getBody(request.message); + // If the ACK doesn't have an answer, nothing to be done. + if (!body) { + return Promise.resolve(); + } + if (body.contentDisposition === "render") { + this._renderbody = body.content; + this._rendertype = body.contentType; + return Promise.resolve(); + } + if (body.contentDisposition !== "session") { + return Promise.resolve(); + } + return this.setAnswer(body, answerOptions).catch((error) => { + this.logger.error(error.message); + const extraHeaders = ["Reason: " + this.getReasonHeaderValue(488, "Bad Media Description")]; + dialog.bye(undefined, { extraHeaders }); + this.stateTransition(SessionState.Terminated); + }); + } + case SignalingState.HaveLocalOffer: { + // State should never be reached as local offer would be answered by this ACK. + // So we must have received an ACK without an answer. + this.logger.error(`Invalid signaling state ${dialog.signalingState}.`); + const extraHeaders = ["Reason: " + this.getReasonHeaderValue(488, "Bad Media Description")]; + dialog.bye(undefined, { extraHeaders }); + this.stateTransition(SessionState.Terminated); + return Promise.resolve(); + } + case SignalingState.HaveRemoteOffer: { + // State should never be reached as remote offer would be answered in first reliable response. + // So we must have never has sent an answer. + this.logger.error(`Invalid signaling state ${dialog.signalingState}.`); + const extraHeaders = ["Reason: " + this.getReasonHeaderValue(488, "Bad Media Description")]; + dialog.bye(undefined, { extraHeaders }); + this.stateTransition(SessionState.Terminated); + return Promise.resolve(); + } + case 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 + */ + onByeRequest(request) { + this.logger.log("Session.onByeRequest"); + if (this.state !== SessionState.Established) { + this.logger.error(`BYE received while in state ${this.state}, dropping request`); + return; + } + if (this.delegate && this.delegate.onBye) { + const bye = new Bye(request); + this.delegate.onBye(bye); + } + else { + request.accept(); + } + this.stateTransition(SessionState.Terminated); + } + /** + * Handle in dialog INFO request. + * @internal + */ + onInfoRequest(request) { + this.logger.log("Session.onInfoRequest"); + if (this.state !== SessionState.Established) { + this.logger.error(`INFO received while in state ${this.state}, dropping request`); + return; + } + if (this.delegate && this.delegate.onInfo) { + const info = new Info(request); + this.delegate.onInfo(info); + } + else { + // FIXME: TODO: We should reject request... + // + // 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. + // https://tools.ietf.org/html/rfc6086#section-4.2.2 + request.accept(); + } + } + /** + * Handle in dialog INVITE request. + * @internal + */ + onInviteRequest(request) { + this.logger.log("Session.onInviteRequest"); + if (this.state !== SessionState.Established) { + this.logger.error(`INVITE received while in state ${this.state}, dropping request`); + return; + } + // set pending ACK flag + this.pendingReinviteAck = true; + // 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. + const extraHeaders = ["Contact: " + this._contact]; + // Handle P-Asserted-Identity + if (request.message.hasHeader("P-Asserted-Identity")) { + const header = request.message.getHeader("P-Asserted-Identity"); + if (!header) { + throw new Error("Header undefined."); + } + this._assertedIdentity = Grammar.nameAddrHeaderParse(header); + } + const options = { + sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptionsReInvite, + sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiersReInvite + }; + this.generateResponseOfferAnswerInDialog(options) + .then((body) => { + const outgoingResponse = request.accept({ statusCode: 200, extraHeaders, body }); + if (this.delegate && this.delegate.onInvite) { + this.delegate.onInvite(request.message, outgoingResponse.message, 200); + } + }) + .catch((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 === SignalingState.Stable) { + const 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(() => { + const outgoingResponse = request.reject({ statusCode: 488 }); // Not Acceptable Here + if (this.delegate && this.delegate.onInvite) { + this.delegate.onInvite(request.message, outgoingResponse.message, 488); + } + }) + .catch((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"); + const outgoingResponse = request.reject({ statusCode: 488 }); // Not Acceptable Here + // A BYE should only be sent if session is not already terminated. + // For example, a BYE may be sent/received while re-INVITE is outstanding. + // Note that the ACK was already sent by the transaction, so just need to send BYE. + if (this.state !== SessionState.Terminated) { + if (!this.dialog) { + throw new Error("Dialog undefined."); + } + const extraHeadersBye = []; + extraHeadersBye.push("Reason: " + this.getReasonHeaderValue(500, "Internal Server Error")); + this.dialog.bye(undefined, { extraHeaders }); + this.stateTransition(SessionState.Terminated); + } + if (this.delegate && this.delegate.onInvite) { + this.delegate.onInvite(request.message, outgoingResponse.message, 488); + } + }); + }); + } + /** + * Handle in dialog MESSAGE request. + * @internal + */ + onMessageRequest(request) { + this.logger.log("Session.onMessageRequest"); + if (this.state !== SessionState.Established) { + this.logger.error(`MESSAGE received while in state ${this.state}, dropping request`); + return; + } + if (this.delegate && this.delegate.onMessage) { + const message = new Message(request); + this.delegate.onMessage(message); + } + else { + request.accept(); + } + } + /** + * Handle in dialog NOTIFY request. + * @internal + */ + onNotifyRequest(request) { + this.logger.log("Session.onNotifyRequest"); + if (this.state !== SessionState.Established) { + this.logger.error(`NOTIFY received while in state ${this.state}, dropping request`); + return; + } + // If this a NOTIFY associated with the progress of a REFER, + // look to delegate handling to the associated callback. + if (this.onNotify) { + const notification = new Notification(request); + this.onNotify(notification); + return; + } + // Otherwise accept the NOTIFY. + if (this.delegate && this.delegate.onNotify) { + const notification = new Notification(request); + this.delegate.onNotify(notification); + } + else { + request.accept(); + } + } + /** + * Handle in dialog PRACK request. + * @internal + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onPrackRequest(request) { + this.logger.log("Session.onPrackRequest"); + if (this.state !== 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 + */ + onReferRequest(request) { + this.logger.log("Session.onReferRequest"); + if (this.state !== SessionState.Established) { + this.logger.error(`REFER received while in state ${this.state}, dropping request`); + return; + } + // 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 + if (!request.message.hasHeader("refer-to")) { + this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting."); + request.reject(); + return; + } + const referral = new Referral(request, this); + if (this.delegate && this.delegate.onRefer) { + this.delegate.onRefer(referral); + } + else { + this.logger.log("No delegate available to handle REFER, automatically accepting and following."); + referral + .accept() + .then(() => referral.makeInviter(this._referralInviterOptions).invite()) + .catch((error) => { + // FIXME: logging and eating error... + this.logger.error(error.message); + }); + } + } + /** + * 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 + */ + generateResponseOfferAnswer(request, options) { + if (this.dialog) { + return this.generateResponseOfferAnswerInDialog(options); + } + const body = 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 + */ + generateResponseOfferAnswerInDialog(options) { + if (!this.dialog) { + throw new Error("Dialog undefined."); + } + switch (this.dialog.signalingState) { + case SignalingState.Initial: + return this.getOffer(options); + case 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 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 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 !== SessionState.Established) { + return Promise.resolve(undefined); + } + // In dialog INVITE without offer, get an offer for the response. + return this.getOffer(options); + case 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 + */ + getOffer(options) { + const sdh = this.setupSessionDescriptionHandler(); + const sdhOptions = options.sessionDescriptionHandlerOptions; + const sdhModifiers = options.sessionDescriptionHandlerModifiers; + // This is intentionally written very defensively. Don't trust SDH to behave. + try { + return sdh + .getDescription(sdhOptions, sdhModifiers) + .then((bodyAndContentType) => fromBodyLegacy(bodyAndContentType)) + .catch((error) => { + // don't trust SDH to reject with Error + this.logger.error("Session.getOffer: SDH getDescription rejected..."); + const e = error instanceof Error ? error : new Error("Session.getOffer unknown error."); + this.logger.error(e.message); + throw e; + }); + } + catch (error) { + // don't trust SDH to throw an Error + this.logger.error("Session.getOffer: SDH getDescription threw..."); + const e = error instanceof Error ? error : new Error(error); + this.logger.error(e.message); + return Promise.reject(e); + } + } + /** + * Rollback local/remote offer. + * @internal + */ + rollbackOffer() { + const sdh = this.setupSessionDescriptionHandler(); + if (sdh.rollbackDescription === undefined) { + return Promise.resolve(); + } + // This is intentionally written very defensively. Don't trust SDH to behave. + try { + return sdh.rollbackDescription().catch((error) => { + // don't trust SDH to reject with Error + this.logger.error("Session.rollbackOffer: SDH rollbackDescription rejected..."); + const e = error instanceof Error ? error : new Error("Session.rollbackOffer unknown error."); + this.logger.error(e.message); + throw e; + }); + } + catch (error) { + // don't trust SDH to throw an Error + this.logger.error("Session.rollbackOffer: SDH rollbackDescription threw..."); + const e = error instanceof Error ? error : new Error(error); + this.logger.error(e.message); + return Promise.reject(e); + } + } + /** + * Set remote answer. + * @internal + */ + setAnswer(answer, options) { + const sdh = this.setupSessionDescriptionHandler(); + const sdhOptions = options.sessionDescriptionHandlerOptions; + const sdhModifiers = options.sessionDescriptionHandlerModifiers; + // This is intentionally written very defensively. Don't trust SDH to behave. + try { + if (!sdh.hasDescription(answer.contentType)) { + return Promise.reject(new ContentTypeUnsupportedError()); + } + } + catch (error) { + this.logger.error("Session.setAnswer: SDH hasDescription threw..."); + const e = error instanceof Error ? error : new Error(error); + this.logger.error(e.message); + return Promise.reject(e); + } + try { + return sdh.setDescription(answer.content, sdhOptions, sdhModifiers).catch((error) => { + // don't trust SDH to reject with Error + this.logger.error("Session.setAnswer: SDH setDescription rejected..."); + const e = error instanceof Error ? error : new Error("Session.setAnswer unknown error."); + this.logger.error(e.message); + throw e; + }); + } + catch (error) { + // don't trust SDH to throw an Error + this.logger.error("Session.setAnswer: SDH setDescription threw..."); + const e = error instanceof Error ? error : new Error(error); + this.logger.error(e.message); + return Promise.reject(e); + } + } + /** + * Set remote offer and get local answer. + * @internal + */ + setOfferAndGetAnswer(offer, options) { + const sdh = this.setupSessionDescriptionHandler(); + const sdhOptions = options.sessionDescriptionHandlerOptions; + const sdhModifiers = options.sessionDescriptionHandlerModifiers; + // This is intentionally written very defensively. Don't trust SDH to behave. + try { + if (!sdh.hasDescription(offer.contentType)) { + return Promise.reject(new ContentTypeUnsupportedError()); + } + } + catch (error) { + this.logger.error("Session.setOfferAndGetAnswer: SDH hasDescription threw..."); + const e = error instanceof Error ? error : new Error(error); + this.logger.error(e.message); + return Promise.reject(e); + } + try { + return sdh + .setDescription(offer.content, sdhOptions, sdhModifiers) + .then(() => sdh.getDescription(sdhOptions, sdhModifiers)) + .then((bodyAndContentType) => fromBodyLegacy(bodyAndContentType)) + .catch((error) => { + // don't trust SDH to reject with Error + this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription rejected..."); + const e = error instanceof Error ? error : new Error("Session.setOfferAndGetAnswer unknown error."); + this.logger.error(e.message); + throw e; + }); + } + catch (error) { + // don't trust SDH to throw an Error + this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription threw..."); + const e = error instanceof Error ? error : new Error(error); + this.logger.error(e.message); + return Promise.reject(e); + } + } + /** + * SDH for confirmed dialog. + * @internal + */ + setSessionDescriptionHandler(sdh) { + if (this._sessionDescriptionHandler) { + throw new Error("Session description handler defined."); + } + this._sessionDescriptionHandler = sdh; + } + /** + * SDH for confirmed dialog. + * @internal + */ + setupSessionDescriptionHandler() { + var _a; + if (this._sessionDescriptionHandler) { + return this._sessionDescriptionHandler; + } + this._sessionDescriptionHandler = this.sessionDescriptionHandlerFactory(this, this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions); + if ((_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onSessionDescriptionHandler) { + this.delegate.onSessionDescriptionHandler(this._sessionDescriptionHandler, false); + } + return this._sessionDescriptionHandler; + } + /** + * Transition session state. + * @internal + */ + stateTransition(newState) { + const invalidTransition = () => { + throw new Error(`Invalid state transition from ${this._state} to ${newState}`); + }; + // Validate transition + switch (this._state) { + case SessionState.Initial: + if (newState !== SessionState.Establishing && + newState !== SessionState.Established && + newState !== SessionState.Terminating && + newState !== SessionState.Terminated) { + invalidTransition(); + } + break; + case SessionState.Establishing: + if (newState !== SessionState.Established && + newState !== SessionState.Terminating && + newState !== SessionState.Terminated) { + invalidTransition(); + } + break; + case SessionState.Established: + if (newState !== SessionState.Terminating && newState !== SessionState.Terminated) { + invalidTransition(); + } + break; + case SessionState.Terminating: + if (newState !== SessionState.Terminated) { + invalidTransition(); + } + break; + case SessionState.Terminated: + invalidTransition(); + break; + default: + throw new Error("Unrecognized state."); + } + // Transition + this._state = newState; + this.logger.log(`Session ${this.id} transitioned to state ${this._state}`); + this._stateEventEmitter.emit(this._state); + // Dispose + if (newState === SessionState.Terminated) { + this.dispose(); + } + } + copyRequestOptions(requestOptions = {}) { + const extraHeaders = requestOptions.extraHeaders ? requestOptions.extraHeaders.slice() : undefined; + const body = requestOptions.body + ? { + contentDisposition: requestOptions.body.contentDisposition || "render", + contentType: requestOptions.body.contentType || "text/plain", + content: requestOptions.body.content || "" + } + : undefined; + return { + extraHeaders, + body + }; + } + getReasonHeaderValue(code, reason) { + const cause = code; + let text = getReasonPhrase(code); + if (!text && reason) { + text = reason; + } + return "SIP;cause=" + cause + ';text="' + text + '"'; + } + referExtraHeaders(referTo) { + const extraHeaders = []; + extraHeaders.push("Referred-By: <" + this.userAgent.configuration.uri + ">"); + extraHeaders.push("Contact: " + this._contact); + extraHeaders.push("Allow: " + ["ACK", "CANCEL", "INVITE", "MESSAGE", "BYE", "OPTIONS", "INFO", "NOTIFY", "REFER"].toString()); + extraHeaders.push("Refer-To: " + referTo); + return extraHeaders; + } + referToString(target) { + let referTo; + if (target instanceof URI) { + // REFER without Replaces (Blind Transfer) + referTo = target.toString(); + } + else { + // REFER with Replaces (Attended Transfer) + if (!target.dialog) { + throw new Error("Dialog undefined."); + } + const displayName = target.remoteIdentity.friendlyName; + const remoteTarget = target.dialog.remoteTarget.toString(); + const callId = target.dialog.callId; + const remoteTag = target.dialog.remoteTag; + const localTag = target.dialog.localTag; + const replaces = encodeURIComponent(`${callId};to-tag=${remoteTag};from-tag=${localTag}`); + referTo = `"${displayName}" <${remoteTarget}?Replaces=${replaces}>`; + } + return referTo; + } +} diff --git a/lib/api/subscriber-options.d.ts b/lib/api/subscriber-options.d.ts new file mode 100644 index 000000000..61cfed12b --- /dev/null +++ b/lib/api/subscriber-options.d.ts @@ -0,0 +1,12 @@ +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 new file mode 100644 index 000000000..0bebbff69 --- /dev/null +++ b/lib/api/subscriber-options.d.ts.map @@ -0,0 +1 @@ +{"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 new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/api/subscriber-options.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/api/subscriber-subscribe-options.d.ts b/lib/api/subscriber-subscribe-options.d.ts new file mode 100644 index 000000000..53ffaa836 --- /dev/null +++ b/lib/api/subscriber-subscribe-options.d.ts @@ -0,0 +1,7 @@ +/** + * 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 new file mode 100644 index 000000000..4e315065c --- /dev/null +++ b/lib/api/subscriber-subscribe-options.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"subscriber-subscribe-options.d.ts","sourceRoot":"","sources":["../../src/api/subscriber-subscribe-options.ts"],"names":[],"mappings":"AACA;;;GAGG;AACH,MAAM,WAAW,0BAA0B;CAAG"} \ No newline at end of file diff --git a/lib/api/subscriber-subscribe-options.js b/lib/api/subscriber-subscribe-options.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/api/subscriber-subscribe-options.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/api/subscriber.d.ts b/lib/api/subscriber.d.ts new file mode 100644 index 000000000..4481a27c0 --- /dev/null +++ b/lib/api/subscriber.d.ts @@ -0,0 +1,95 @@ +import { IncomingNotifyRequest, IncomingResponse, 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.addListener((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 event; + private expires; + private extraHeaders; + private logger; + private outgoingRequestMessage; + private retryAfterTimer; + private subscriberRequest; + 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(): Promise; + /** + * 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; + /** + * {@inheritDoc Subscription.unsubscribe} + */ + unsubscribe(options?: SubscriptionUnsubscribeOptions): Promise; + /** + * Sends a re-SUBSCRIBE request if the subscription is "active". + * @deprecated Use `subscribe` instead. + * @internal + */ + _refresh(): Promise; + /** @internal */ + protected onAccepted(response: IncomingResponse): void; + /** @internal */ + protected onNotify(request: IncomingNotifyRequest): void; + /** @internal */ + protected onRefresh(request: OutgoingSubscribeRequest): void; + private initSubscriberRequest; +} +//# 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 new file mode 100644 index 000000000..24f09359d --- /dev/null +++ b/lib/api/subscriber.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"subscriber.d.ts","sourceRoot":"","sources":["../../src/api/subscriber.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,qBAAqB,EAErB,gBAAgB,EAGhB,wBAAwB,EAIxB,GAAG,EAEJ,MAAM,SAAS,CAAC;AAIjB,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;IAE1C,OAAO,CAAC,EAAE,CAAS;IACnB,OAAO,CAAC,IAAI,CAA6C;IACzD,OAAO,CAAC,KAAK,CAAS;IACtB,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,YAAY,CAAgB;IACpC,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,sBAAsB,CAAyB;IACvD,OAAO,CAAC,eAAe,CAAqB;IAC5C,OAAO,CAAC,iBAAiB,CAAoB;IAC7C,OAAO,CAAC,SAAS,CAAM;IAEvB;;;;;;OAMG;gBACgB,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,GAAG,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,GAAE,iBAAsB;IAwC3G;;;OAGG;IACI,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IA6C/B;;;;;;OAMG;IAEI,SAAS,CAAC,OAAO,GAAE,0BAA+B,GAAG,OAAO,CAAC,IAAI,CAAC;IAqDzE;;OAEG;IAEI,WAAW,CAAC,OAAO,GAAE,8BAAmC,GAAG,OAAO,CAAC,IAAI,CAAC;IA+B/E;;;;OAIG;IACI,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;IAOhC,gBAAgB;IAEhB,SAAS,CAAC,UAAU,CAAC,QAAQ,EAAE,gBAAgB,GAAG,IAAI;IAMtD,gBAAgB;IAChB,SAAS,CAAC,QAAQ,CAAC,OAAO,EAAE,qBAAqB,GAAG,IAAI;IAuExD,gBAAgB;IAChB,SAAS,CAAC,SAAS,CAAC,OAAO,EAAE,wBAAwB,GAAG,IAAI;IAM5D,OAAO,CAAC,qBAAqB;CAkB9B"} \ No newline at end of file diff --git a/lib/api/subscriber.js b/lib/api/subscriber.js new file mode 100644 index 000000000..63b8099f1 --- /dev/null +++ b/lib/api/subscriber.js @@ -0,0 +1,427 @@ +import { C, fromBodyLegacy, SubscriptionState as SubscriptionDialogState } from "../core"; +import { AllowedMethods } from "../core/user-agent-core/allowed-methods"; +import { Notification } from "./notification"; +import { Subscription } from "./subscription"; +import { SubscriptionState } from "./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.addListener((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 class Subscriber extends Subscription { + /** + * 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, targetURI, eventType, options = {}) { + super(userAgent, options); + this.body = undefined; + this.logger = userAgent.getLogger("sip.Subscriber"); + if (options.body) { + this.body = { + body: options.body, + contentType: options.contentType ? options.contentType : "application/sdp" + }; + } + 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.subscriberRequest = this.initSubscriberRequest(); + this.outgoingRequestMessage = this.subscriberRequest.message; + // Add to UserAgent's collection + this.id = this.outgoingRequestMessage.callId + this.outgoingRequestMessage.from.parameters.tag + this.event; + this._userAgent._subscriptions[this.id] = this; + } + /** + * Destructor. + * @internal + */ + dispose() { + if (this.disposed) { + return Promise.resolve(); + } + this.logger.log(`Subscription ${this.id} in state ${this.state} is being disposed`); + // Remove from the user agent's subscription collection + delete this._userAgent._subscriptions[this.id]; + // Clear timers + if (this.retryAfterTimer) { + clearTimeout(this.retryAfterTimer); + this.retryAfterTimer = undefined; + } + // Dispose subscriber request + this.subscriberRequest.dispose(); + // Make sure to dispose of our parent, then unsubscribe the + // subscription dialog (if need be) and resolve when it has terminated. + return super.dispose().then(() => { + // If we have never subscribed there is nothing to wait on. + // If we are already transitioned to terminated there is no need to unsubscribe again. + if (this.state !== SubscriptionState.Subscribed) { + return; + } + if (!this._dialog) { + throw new Error("Dialog undefined."); + } + if (this._dialog.subscriptionState === SubscriptionDialogState.Pending || + this._dialog.subscriptionState === SubscriptionDialogState.Active) { + const dialog = this._dialog; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + return new Promise((resolve, reject) => { + dialog.delegate = { + onTerminated: () => resolve() + }; + dialog.unsubscribe(); + }); + } + }); + } + /** + * 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". + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + subscribe(options = {}) { + switch (this.subscriberRequest.state) { + case SubscriptionDialogState.Initial: + // we can end up here when retrying so only state transition if in SubscriptionState.Initial state + if (this.state === SubscriptionState.Initial) { + this.stateTransition(SubscriptionState.NotifyWait); + } + this.subscriberRequest.subscribe().then((result) => { + if (result.success) { + if (result.success.subscription) { + this._dialog = result.success.subscription; + this._dialog.delegate = { + onNotify: (request) => this.onNotify(request), + onRefresh: (request) => this.onRefresh(request), + onTerminated: () => { + // If a call to unsubscribe will state transition to SubscriptionState.Terminated, + // but we can end up here after that if the NOTIFY never arrives and timer N fires. + if (this.state !== SubscriptionState.Terminated) { + this.stateTransition(SubscriptionState.Terminated); + } + } + }; + } + this.onNotify(result.success.request); + } + else if (result.failure) { + this.unsubscribe(); + } + }); + break; + case SubscriptionDialogState.NotifyWait: + break; + case SubscriptionDialogState.Pending: + break; + case SubscriptionDialogState.Active: + if (this._dialog) { + const request = this._dialog.refresh(); + request.delegate = { + onAccept: (response) => this.onAccepted(response), + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onRedirect: (response) => this.unsubscribe(), + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onReject: (response) => this.unsubscribe() + }; + } + break; + case SubscriptionDialogState.Terminated: + break; + default: + break; + } + return Promise.resolve(); + } + /** + * {@inheritDoc Subscription.unsubscribe} + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + unsubscribe(options = {}) { + if (this.disposed) { + return Promise.resolve(); + } + switch (this.subscriberRequest.state) { + case SubscriptionDialogState.Initial: + break; + case SubscriptionDialogState.NotifyWait: + break; + case SubscriptionDialogState.Pending: + if (this._dialog) { + this._dialog.unsubscribe(); + // responses intentionally ignored + } + break; + case SubscriptionDialogState.Active: + if (this._dialog) { + this._dialog.unsubscribe(); + // responses intentionally ignored + } + break; + case SubscriptionDialogState.Terminated: + break; + default: + throw new Error("Unknown state."); + } + this.stateTransition(SubscriptionState.Terminated); + return Promise.resolve(); + } + /** + * Sends a re-SUBSCRIBE request if the subscription is "active". + * @deprecated Use `subscribe` instead. + * @internal + */ + _refresh() { + if (this.subscriberRequest.state === SubscriptionDialogState.Active) { + return this.subscribe(); + } + return Promise.resolve(); + } + /** @internal */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onAccepted(response) { + // NOTE: If you think you should do something with this response, + // please make sure you understand what it is you are doing and why. + // Per the RFC, the first NOTIFY is all that actually matters. + } + /** @internal */ + onNotify(request) { + // 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 !== SubscriptionState.Subscribed) { + this.stateTransition(SubscriptionState.Subscribed); + } + // Delegate notification. + if (this.delegate && this.delegate.onNotify) { + const notification = new 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 + const 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.initSubscriberRequest(); + this.subscribe(); + return; + case "probation": + case "giveup": + this.initSubscriberRequest(); + if (subscriptionState.params && subscriptionState.params["retry-after"]) { + this.retryAfterTimer = setTimeout(() => { + this.subscribe(); + }, subscriptionState.params["retry-after"]); + } + else { + this.subscribe(); + } + return; + case "rejected": + case "noresource": + case "invariant": + break; + } + } + this.unsubscribe(); + break; + default: + break; + } + } + } + /** @internal */ + onRefresh(request) { + request.delegate = { + onAccept: (response) => this.onAccepted(response) + }; + } + initSubscriberRequest() { + const options = { + extraHeaders: this.extraHeaders, + body: this.body ? fromBodyLegacy(this.body) : undefined + }; + // eslint-disable-next-line @typescript-eslint/no-use-before-define + this.subscriberRequest = new SubscriberRequest(this._userAgent.userAgentCore, this.targetURI, this.event, this.expires, options); + this.subscriberRequest.delegate = { + onAccept: (response) => this.onAccepted(response) + }; + return this.subscriberRequest; + } +} +class SubscriberRequest { + constructor(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.Subscriber"); + this.delegate = delegate; + const allowHeader = "Allow: " + AllowedMethods.toString(); + const 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()); + const body = options && options.body; + this.message = core.makeOutgoingRequestMessage(C.SUBSCRIBE, this.target, this.core.configuration.aor, this.target, {}, extraHeaders, body); + } + /** Destructor. */ + dispose() { + if (this.request) { + this.request.waitNotifyStop(); + this.request.dispose(); + this.request = undefined; + } + } + /** Subscription state. */ + get state() { + if (this.subscription) { + return this.subscription.subscriptionState; + } + else if (this.subscribed) { + return SubscriptionDialogState.NotifyWait; + } + else { + return SubscriptionDialogState.Initial; + } + } + /** + * Establish subscription. + * @param options Options bucket. + */ + subscribe() { + 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((resolve) => { + 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: (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: (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: () => { + 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: (response) => { + resolve({ failure: { 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: (response) => { + resolve({ failure: { response } }); + } + }); + }); + } +} diff --git a/lib/api/subscription-delegate.d.ts b/lib/api/subscription-delegate.d.ts new file mode 100644 index 000000000..2059c8b59 --- /dev/null +++ b/lib/api/subscription-delegate.d.ts @@ -0,0 +1,13 @@ +import { Notification } from "./notification"; +/** + * Delegate for {@link Subscription}. + * @public + */ +export interface SubscriptionDelegate { + /** + * Called upon receiving an incoming 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 new file mode 100644 index 000000000..7f5133b59 --- /dev/null +++ b/lib/api/subscription-delegate.d.ts.map @@ -0,0 +1 @@ +{"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 new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/api/subscription-delegate.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/api/subscription-options.d.ts b/lib/api/subscription-options.d.ts new file mode 100644 index 000000000..70e65308d --- /dev/null +++ b/lib/api/subscription-options.d.ts @@ -0,0 +1,9 @@ +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 new file mode 100644 index 000000000..abd24343b --- /dev/null +++ b/lib/api/subscription-options.d.ts.map @@ -0,0 +1 @@ +{"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 new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/api/subscription-options.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/api/subscription-state.d.ts b/lib/api/subscription-state.d.ts new file mode 100644 index 000000000..df46a7d8b --- /dev/null +++ b/lib/api/subscription-state.d.ts @@ -0,0 +1,20 @@ +/** + * {@link Subscription} state. + * @remarks + * The {@link Subscription} behaves in a deterministic manner according to the following + * Finite State Machine (FSM). + * ```txt + * _______________________________________ + * Subscription | v + * Constructed -> Initial -> NotifyWait -> Subscribed -> 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 new file mode 100644 index 000000000..629f5dc35 --- /dev/null +++ b/lib/api/subscription-state.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"subscription-state.d.ts","sourceRoot":"","sources":["../../src/api/subscription-state.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,oBAAY,iBAAiB;IAC3B,OAAO,YAAY;IACnB,UAAU,eAAe;IACzB,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 new file mode 100644 index 000000000..ad2c149ca --- /dev/null +++ b/lib/api/subscription-state.js @@ -0,0 +1,20 @@ +/** + * {@link Subscription} state. + * @remarks + * The {@link Subscription} behaves in a deterministic manner according to the following + * Finite State Machine (FSM). + * ```txt + * _______________________________________ + * Subscription | v + * Constructed -> Initial -> NotifyWait -> Subscribed -> Terminated + * |____________________________^ + * ``` + * @public + */ +export var SubscriptionState; +(function (SubscriptionState) { + SubscriptionState["Initial"] = "Initial"; + SubscriptionState["NotifyWait"] = "NotifyWait"; + SubscriptionState["Subscribed"] = "Subscribed"; + SubscriptionState["Terminated"] = "Terminated"; +})(SubscriptionState || (SubscriptionState = {})); diff --git a/lib/api/subscription-subscribe-options.d.ts b/lib/api/subscription-subscribe-options.d.ts new file mode 100644 index 000000000..38fc11d53 --- /dev/null +++ b/lib/api/subscription-subscribe-options.d.ts @@ -0,0 +1,7 @@ +/** + * 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 new file mode 100644 index 000000000..bb7847866 --- /dev/null +++ b/lib/api/subscription-subscribe-options.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"subscription-subscribe-options.d.ts","sourceRoot":"","sources":["../../src/api/subscription-subscribe-options.ts"],"names":[],"mappings":"AACA;;;GAGG;AACH,MAAM,WAAW,4BAA4B;CAAG"} \ No newline at end of file diff --git a/lib/api/subscription-subscribe-options.js b/lib/api/subscription-subscribe-options.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/api/subscription-subscribe-options.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/api/subscription-unsubscribe-options.d.ts b/lib/api/subscription-unsubscribe-options.d.ts new file mode 100644 index 000000000..0130c59f3 --- /dev/null +++ b/lib/api/subscription-unsubscribe-options.d.ts @@ -0,0 +1,7 @@ +/** + * 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 new file mode 100644 index 000000000..6714e6c50 --- /dev/null +++ b/lib/api/subscription-unsubscribe-options.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"subscription-unsubscribe-options.d.ts","sourceRoot":"","sources":["../../src/api/subscription-unsubscribe-options.ts"],"names":[],"mappings":"AACA;;;GAGG;AACH,MAAM,WAAW,8BAA8B;CAAG"} \ No newline at end of file diff --git a/lib/api/subscription-unsubscribe-options.js b/lib/api/subscription-unsubscribe-options.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/api/subscription-unsubscribe-options.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/api/subscription.d.ts b/lib/api/subscription.d.ts new file mode 100644 index 000000000..d3e4b8885 --- /dev/null +++ b/lib/api/subscription.d.ts @@ -0,0 +1,85 @@ +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 {@link Notification} of events. + * + * @remarks + * See {@link Subscriber} for details on establishing a subscription. + * + * @public + */ +export declare abstract class Subscription { + /** + * Property reserved for use by instance owner. + * @defaultValue `undefined` + */ + data: unknown; + /** + * 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 + */ + protected _dialog: SubscriptionDialog | undefined; + /** + * Our user agent. + * @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. + */ + dispose(): Promise; + /** + * The subscribed subscription dialog. + */ + get dialog(): SubscriptionDialog | undefined; + /** + * True if disposed. + * @internal + */ + get disposed(): boolean; + /** + * Subscription state. See {@link SubscriptionState} for details. + */ + get state(): SubscriptionState; + /** + * Emits when the subscription `state` property changes. + */ + get stateChange(): Emitter; + /** @internal */ + protected stateTransition(newState: SubscriptionState): void; + /** + * 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; +} +//# 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 new file mode 100644 index 000000000..33c9f8b22 --- /dev/null +++ b/lib/api/subscription.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"subscription.d.ts","sourceRoot":"","sources":["../../src/api/subscription.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,YAAY,IAAI,kBAAkB,EAAE,MAAM,SAAS,CAAC;AACrE,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,YAAY;IAChC;;;OAGG;IACI,IAAI,EAAE,OAAO,CAAC;IAErB;;;OAGG;IACI,QAAQ,EAAE,oBAAoB,GAAG,SAAS,CAAC;IAElD;;;OAGG;IACH,SAAS,CAAC,OAAO,EAAE,kBAAkB,GAAG,SAAS,CAAC;IAElD;;;OAGG;IACH,SAAS,CAAC,UAAU,EAAE,SAAS,CAAC;IAEhC,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,MAAM,CAAgD;IAC9D,OAAO,CAAC,kBAAkB,CAAiC;IAE3D;;;;OAIG;IACH,SAAS,aAAa,SAAS,EAAE,SAAS,EAAE,OAAO,GAAE,mBAAwB;IAO7E;;OAEG;IACI,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAS/B;;OAEG;IACH,IAAW,MAAM,IAAI,kBAAkB,GAAG,SAAS,CAElD;IAED;;;OAGG;IACH,IAAW,QAAQ,IAAI,OAAO,CAE7B;IAED;;OAEG;IACH,IAAW,KAAK,IAAI,iBAAiB,CAEpC;IAED;;OAEG;IACH,IAAW,WAAW,IAAI,OAAO,CAAC,iBAAiB,CAAC,CAEnD;IAED,gBAAgB;IAChB,SAAS,CAAC,eAAe,CAAC,QAAQ,EAAE,iBAAiB,GAAG,IAAI;IA6C5D;;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;CACrF"} \ No newline at end of file diff --git a/lib/api/subscription.js b/lib/api/subscription.js new file mode 100644 index 000000000..35fada66d --- /dev/null +++ b/lib/api/subscription.js @@ -0,0 +1,102 @@ +import { EmitterImpl } from "./emitter"; +import { SubscriptionState } from "./subscription-state"; +/** + * A subscription provides {@link Notification} of events. + * + * @remarks + * See {@link Subscriber} for details on establishing a subscription. + * + * @public + */ +export class Subscription { + /** + * Constructor. + * @param userAgent - User agent. See {@link UserAgent} for details. + * @internal + */ + constructor(userAgent, options = {}) { + this._disposed = false; + this._state = SubscriptionState.Initial; + this._logger = userAgent.getLogger("sip.Subscription"); + this._stateEventEmitter = new EmitterImpl(); + this._userAgent = userAgent; + this.delegate = options.delegate; + } + /** + * Destructor. + */ + dispose() { + if (this._disposed) { + return Promise.resolve(); + } + this._disposed = true; + this._stateEventEmitter.removeAllListeners(); + return Promise.resolve(); + } + /** + * The subscribed subscription dialog. + */ + get dialog() { + return this._dialog; + } + /** + * True if disposed. + * @internal + */ + get disposed() { + return this._disposed; + } + /** + * Subscription state. See {@link SubscriptionState} for details. + */ + get state() { + return this._state; + } + /** + * Emits when the subscription `state` property changes. + */ + get stateChange() { + return this._stateEventEmitter; + } + /** @internal */ + stateTransition(newState) { + const invalidTransition = () => { + throw new Error(`Invalid state transition from ${this._state} to ${newState}`); + }; + // Validate transition + switch (this._state) { + case SubscriptionState.Initial: + if (newState !== SubscriptionState.NotifyWait && newState !== SubscriptionState.Terminated) { + invalidTransition(); + } + break; + case SubscriptionState.NotifyWait: + if (newState !== SubscriptionState.Subscribed && newState !== SubscriptionState.Terminated) { + invalidTransition(); + } + break; + case SubscriptionState.Subscribed: + if (newState !== SubscriptionState.Terminated) { + invalidTransition(); + } + break; + case 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(this._state); + // Dispose + if (newState === SubscriptionState.Terminated) { + this.dispose(); + } + } +} diff --git a/lib/api/transport-state.d.ts b/lib/api/transport-state.d.ts new file mode 100644 index 000000000..d3319fcd6 --- /dev/null +++ b/lib/api/transport-state.d.ts @@ -0,0 +1,38 @@ +/** + * {@link Transport} state. + * + * @remarks + * The {@link Transport} behaves in a deterministic manner according to the following + * Finite State Machine (FSM). + * ```txt + * ______________________________ + * | ____________ | + * Transport v v | | + * Constructed -> Disconnected -> Connecting -> Connected -> Disconnecting + * ^ ^ |_____________________^ | | + * | |_____________________________| | + * |_____________________________________________| + * ``` + * @public + */ +export declare enum TransportState { + /** + * The `connect()` method was called. + */ + Connecting = "Connecting", + /** + * The `connect()` method resolved. + */ + Connected = "Connected", + /** + * The `disconnect()` method was called. + */ + Disconnecting = "Disconnecting", + /** + * The `connect()` method was rejected, or + * the `disconnect()` method completed, or + * network connectivity was lost. + */ + Disconnected = "Disconnected" +} +//# sourceMappingURL=transport-state.d.ts.map \ No newline at end of file diff --git a/lib/api/transport-state.d.ts.map b/lib/api/transport-state.d.ts.map new file mode 100644 index 000000000..c8f3524d0 --- /dev/null +++ b/lib/api/transport-state.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"transport-state.d.ts","sourceRoot":"","sources":["../../src/api/transport-state.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,oBAAY,cAAc;IACxB;;OAEG;IACH,UAAU,eAAe;IACzB;;OAEG;IACH,SAAS,cAAc;IACvB;;OAEG;IACH,aAAa,kBAAkB;IAC/B;;;;OAIG;IACH,YAAY,iBAAiB;CAC9B"} \ No newline at end of file diff --git a/lib/api/transport-state.js b/lib/api/transport-state.js new file mode 100644 index 000000000..b38c563f5 --- /dev/null +++ b/lib/api/transport-state.js @@ -0,0 +1,38 @@ +/** + * {@link Transport} state. + * + * @remarks + * The {@link Transport} behaves in a deterministic manner according to the following + * Finite State Machine (FSM). + * ```txt + * ______________________________ + * | ____________ | + * Transport v v | | + * Constructed -> Disconnected -> Connecting -> Connected -> Disconnecting + * ^ ^ |_____________________^ | | + * | |_____________________________| | + * |_____________________________________________| + * ``` + * @public + */ +export var TransportState; +(function (TransportState) { + /** + * The `connect()` method was called. + */ + TransportState["Connecting"] = "Connecting"; + /** + * The `connect()` method resolved. + */ + TransportState["Connected"] = "Connected"; + /** + * The `disconnect()` method was called. + */ + TransportState["Disconnecting"] = "Disconnecting"; + /** + * The `connect()` method was rejected, or + * the `disconnect()` method completed, or + * network connectivity was lost. + */ + TransportState["Disconnected"] = "Disconnected"; +})(TransportState || (TransportState = {})); diff --git a/lib/api/transport.d.ts b/lib/api/transport.d.ts new file mode 100644 index 000000000..3f40d84d3 --- /dev/null +++ b/lib/api/transport.d.ts @@ -0,0 +1,160 @@ +import { Transport as CoreTransport } from "../core"; +import { Emitter } from "./emitter"; +import { TransportState } from "./transport-state"; +/** + * Transport layer interface expected by the `UserAgent`. + * + * @remarks + * The transport behaves in a deterministic manner according to the + * the state defined in {@link TransportState}. + * + * The "Connecting" state is ONLY entered in response to the user calling `connect()`. + * The "Disconnecting" state is ONLY entered in response to the user calling `disconnect()`. + * The `onConnect` callback is ALWAYS called upon transitioning to the "Connected" state. + * The `onDisconnect` callback is ALWAYS called upon transitioning from the "Connected" state. + * + * Adherence to the state machine by the transport implementation is critical as the + * UserAgent depends on this behavior. Furthermore it is critical that the transport + * transition to the "Disconnected" state in all instances where network connectivity + * is lost as the UserAgent, API, and application layer more generally depend on knowing + * network was lost. For example, from a practical standpoint registrations and subscriptions are invalidated + * when network is lost - particularly in the case of connection oriented transport + * protocols such as a secure WebSocket transport. + * + * Proper handling the application level protocol recovery must be left to the application layer, + * thus the transport MUST NOT attempt to "auto-recover" from or otherwise hide loss of network. + * Note that callbacks and emitters such as `onConnect` and `onDisconnect` MUST NOT call methods + * `connect()` and `direct()` synchronously (state change handlers must not loop back). They may + * however do so asynchronously using a Promise resolution, `setTimeout`, or some other method. + * For example... + * ```ts + * transport.onDisconnect = () => { + * Promise.resolve().then(() => transport.connect()); + * } + * ``` + * @public + */ +export interface Transport extends CoreTransport { + /** + * Transport state. + * + * @remarks + * The initial Transport state MUST be "disconnected" (after calling constructor). + */ + readonly state: TransportState; + /** + * Transport state change emitter. + */ + readonly stateChange: Emitter; + /** + * Callback on state transition to "Connected". + * + * @remarks + * When the `UserAgent` is constructed, this property is set. + * ```txt + * - The `state` MUST be "Connected" when called. + * ``` + */ + onConnect: (() => void) | undefined; + /** + * Callback on state transition from "Connected". + * + * @remarks + * When the `UserAgent` is constructed, this property is set. + * ```txt + * - The `state` MUST NOT "Connected" when called. + * - If prior `state` is "Connecting" or "Connected", `error` MUST be defined. + * - If prior `state` is "Disconnecting", `error` MUST NOT be undefined. + * ``` + * If the transition from "Connected" occurs because the transport + * user requested it by calling `disconnect`, then `error` will be undefined. + * Otherwise `error` will be defined to provide an indication that the + * transport initiated the transition from "Connected" - for example, + * perhaps network connectivity was lost. + */ + onDisconnect: ((error?: Error) => void) | undefined; + /** + * Callback on receipt of a message. + * + * @remarks + * When the `UserAgent` is constructed, this property is set. + * The `state` MUST be "Connected" when this is called. + */ + onMessage: ((message: string) => void) | undefined; + /** + * Connect to network. + * + * @remarks + * ```txt + * - If `state` is "Connecting", `state` MUST NOT transition before returning. + * - If `state` is "Connected", `state` MUST NOT transition before returning. + * - If `state` is "Disconnecting", `state` MUST transition to "Connecting" before returning. + * - If `state` is "Disconnected" `state` MUST transition to "Connecting" before returning. + * - The `state` MUST transition to "Connected" before resolving (assuming `state` is not already "Connected"). + * - The `state` MUST transition to "Disconnecting" or "Disconnected" before rejecting and MUST reject with an Error. + * ``` + * Resolves when the transport connects. Rejects if transport fails to connect. + * Rejects with {@link StateTransitionError} if a loop is detected. + * In particular, callbacks and emitters MUST NOT call this method synchronously. + */ + connect(): Promise; + /** + * Disconnect from network. + * + * @remarks + * ```txt + * - If `state` is "Connecting", `state` MUST transition to "Disconnecting" before returning. + * - If `state` is "Connected", `state` MUST transition to "Disconnecting" before returning. + * - If `state` is "Disconnecting", `state` MUST NOT transition before returning. + * - If `state` is "Disconnected", `state` MUST NOT transition before returning. + * - The `state` MUST transition to "Disconnected" before resolving (assuming `state` is not already "Disconnected"). + * - The `state` MUST transition to "Connecting" or "Connected" before rejecting and MUST reject with an Error. + * ``` + * Resolves when the transport disconnects. Rejects if transport fails to disconnect. + * Rejects with {@link StateTransitionError} if a loop is detected. + * In particular, callbacks and emitters MUST NOT call this method synchronously. + */ + disconnect(): Promise; + /** + * Dispose. + * + * @remarks + * When the `UserAgent` is disposed or stopped, this method is called. + * The `UserAgent` MUST NOT continue to utilize the instance after calling this method. + */ + dispose(): Promise; + /** + * Returns true if the `state` equals "Connected". + * + * @remarks + * This is equivalent to `state === TransportState.Connected`. + * It is convenient. A common paradigm is, for example... + * + * @example + * ```ts + * // Monitor transport connectivity + * userAgent.transport.stateChange.addListener(() => { + * if (userAgent.transport.isConnected()) { + * // handle transport connect + * } else { + * // handle transport disconnect + * } + * }); + * ``` + */ + isConnected(): boolean; + /** + * Send a message. + * + * @remarks + * ```txt + * - If `state` is "Connecting", rejects with an Error. + * - If `state` is "Connected", resolves when the message is sent otherwise rejects with an Error. + * - If `state` is "Disconnecting", rejects with an Error. + * - If `state` is "Disconnected", rejects with an Error. + * ``` + * @param message - Message to send. + */ + send(message: string): Promise; +} +//# sourceMappingURL=transport.d.ts.map \ No newline at end of file diff --git a/lib/api/transport.d.ts.map b/lib/api/transport.d.ts.map new file mode 100644 index 000000000..2c68274b5 --- /dev/null +++ b/lib/api/transport.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"transport.d.ts","sourceRoot":"","sources":["../../src/api/transport.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,IAAI,aAAa,EAAE,MAAM,SAAS,CAAC;AACrD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAEnD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,MAAM,WAAW,SAAU,SAAQ,aAAa;IAC9C;;;;;OAKG;IACH,QAAQ,CAAC,KAAK,EAAE,cAAc,CAAC;IAE/B;;OAEG;IACH,QAAQ,CAAC,WAAW,EAAE,OAAO,CAAC,cAAc,CAAC,CAAC;IAE9C;;;;;;;;OAQG;IACH,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,GAAG,SAAS,CAAC;IAEpC;;;;;;;;;;;;;;;OAeG;IACH,YAAY,EAAE,CAAC,CAAC,KAAK,CAAC,EAAE,KAAK,KAAK,IAAI,CAAC,GAAG,SAAS,CAAC;IAEpD;;;;;;OAMG;IACH,SAAS,EAAE,CAAC,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC,GAAG,SAAS,CAAC;IAEnD;;;;;;;;;;;;;;;OAeG;IACH,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAEzB;;;;;;;;;;;;;;;OAeG;IACH,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAE5B;;;;;;OAMG;IACH,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAEzB;;;;;;;;;;;;;;;;;;OAkBG;IACH,WAAW,IAAI,OAAO,CAAC;IAEvB;;;;;;;;;;;OAWG;IACH,IAAI,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACtC"} \ No newline at end of file diff --git a/lib/api/transport.js b/lib/api/transport.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/api/transport.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/api/user-agent-delegate.d.ts b/lib/api/user-agent-delegate.d.ts new file mode 100644 index 000000000..1213b62fc --- /dev/null +++ b/lib/api/user-agent-delegate.d.ts @@ -0,0 +1,85 @@ +import { IncomingReferRequest, 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 transport transitioning to connected state. + */ + onConnect?(): void; + /** + * Called upon transport transitioning from connected state. + * @param error - An error if disconnect triggered by transport. Otherwise undefined. + */ + onDisconnect?(error?: Error): void; + /** + * 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; + /** + * @alpha + * Called upon receipt of a referral. + * @remarks + * Handler for incoming out of dialog REFER requests. + * @param referral - The referral. + */ + onRefer?(referral: Referral): void; + /** + * @alpha + * Called upon receipt of a registration. + * @remarks + * Handler for incoming out of dialog REGISTER requests. + * @param registration - The registration. + */ + onRegister?(registration: unknown): void; + /** + * @alpha + * 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 an out of dialog REFER. Used by test suite. + * @param request - The request. + */ + onReferRequest?(request: IncomingReferRequest): void; + /** + * @internal + * Called upon receipt of a REGISTER request. Used by test suite. + * @param request - The request. + */ + onRegisterRequest?(request: IncomingRegisterRequest): void; + /** + * @internal + * Called upon receipt of an out of dialog SUBSCRIBE 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 new file mode 100644 index 000000000..c4a0c15bb --- /dev/null +++ b/lib/api/user-agent-delegate.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"user-agent-delegate.d.ts","sourceRoot":"","sources":["../../src/api/user-agent-delegate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,uBAAuB,EAAE,wBAAwB,EAAE,MAAM,SAAS,CAAC;AAClG,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;;OAEG;IACH,SAAS,CAAC,IAAI,IAAI,CAAC;IAEnB;;;OAGG;IACH,YAAY,CAAC,CAAC,KAAK,CAAC,EAAE,KAAK,GAAG,IAAI,CAAC;IAEnC;;;;;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;;;;;;OAMG;IACH,OAAO,CAAC,CAAC,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAAC;IAEnC;;;;;;OAMG;IACH,UAAU,CAAC,CAAC,YAAY,EAAE,OAAO,GAA4B,IAAI,CAAC;IAElE;;;;;;OAMG;IACH,WAAW,CAAC,CAAC,YAAY,EAAE,YAAY,GAAG,IAAI,CAAC;IAE/C;;;;OAIG;IACH,cAAc,CAAC,CAAC,OAAO,EAAE,oBAAoB,GAAG,IAAI,CAAC;IAErD;;;;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 new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/api/user-agent-delegate.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/api/user-agent-options.d.ts b/lib/api/user-agent-options.d.ts new file mode 100644 index 000000000..de13b15a6 --- /dev/null +++ b/lib/api/user-agent-options.d.ts @@ -0,0 +1,250 @@ +import { Logger, URI } from "../core"; +import { SessionDescriptionHandlerFactory } from "./session-description-handler-factory"; +import { Transport } from "./transport"; +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; + /** + * Authorization ha1. + * @defaultValue `""` + */ + authorizationHa1?: string; + /** + * 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() resolves 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; + /** + * The contact name associated with the user agent. + * @remarks + * User specified contact name, if not specifed random string will be generated + * @defaultValue `""` + */ + contactName?: string; + /** + * The URI parameters associated with the user agent. + * @remarks + * User specified contact parameters + * @defaultValue `{ transport: "ws" }` + */ + contactParams?: { + [name: string]: string; + }; + /** + * 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; + /** + * 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 every time a log is generated. + * @defaultValue A noop + */ + 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; + /** + * Adds a Route header(s) to outgoing requests. + * @defaultValue `[]` + */ + preloadedRouteSet?: Array; + /** + * @deprecated + * Maximum number of times to attempt to reconnect when the transport connection drops. + * @defaultValue 0 + */ + reconnectionAttempts?: number; + /** + * @deprecated + * Seconds to wait between reconnection attempts when the transport connection drops. + * @defaultValue 4 + */ + reconnectionDelay?: 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.SessionDescriptionHandler.defaultFactory` + */ + sessionDescriptionHandlerFactory?: SessionDescriptionHandlerFactory; + /** + * Options to passed to `sessionDescriptionHandlerFactory`. + * @remarks + * See `Web.SessionDescriptionHandlerOptions` 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: Logger, 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?: unknown; + /** + * 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; + /** + * 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 new file mode 100644 index 000000000..e36d806ae --- /dev/null +++ b/lib/api/user-agent-options.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"user-agent-options.d.ts","sourceRoot":"","sources":["../../src/api/user-agent-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AACtC,OAAO,EAAE,gCAAgC,EAAE,MAAM,uCAAuC,CAAC;AACzF,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAE1D;;;GAGG;AACH,oBAAY,QAAQ,GAAG,OAAO,GAAG,KAAK,GAAG,MAAM,GAAG,OAAO,CAAC;AAE1D;;;GAGG;AACH,oBAAY,YAAY,GAAG,CAAC,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,SAAS,EAAE,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;AAEnH;;;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,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAE1B;;;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;;;;;OAKG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IAErB;;;;;OAKG;IACH,aAAa,CAAC,EAAE;QAAE,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE,CAAC;IAE3C;;;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,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAE5B;;;OAGG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAE3B;;;OAGG;IACH,YAAY,CAAC,EAAE,YAAY,CAAC;IAE5B;;;OAGG;IACH,QAAQ,CAAC,EAAE,QAAQ,CAAC;IAEpB;;;OAGG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IAEzB;;;OAGG;IACH,iBAAiB,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAElC;;;;OAIG;IACH,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAE9B;;;;OAIG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAE3B;;;;;;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;IAEH,oBAAoB,CAAC,EAAE,KAAK,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,KAAK,SAAS,CAAC;IAEvE;;;;;OAKG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAE3B;;;;;;;;;;;OAWG;IACH,GAAG,CAAC,EAAE,GAAG,CAAC;IAEV;;;;OAIG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IAEzB;;;;OAIG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED;;;;;GAKG;AACH,eAAO,MAAM,6BAA6B,EAAE;IAAE,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAA;CAkCtE,CAAC"} \ No newline at end of file diff --git a/lib/api/user-agent-options.js b/lib/api/user-agent-options.js new file mode 100644 index 000000000..8e38df1ab --- /dev/null +++ b/lib/api/user-agent-options.js @@ -0,0 +1,51 @@ +/** + * SIP extension support level. + * @public + */ +export var SIPExtension; +(function (SIPExtension) { + SIPExtension["Required"] = "Required"; + SIPExtension["Supported"] = "Supported"; + SIPExtension["Unsupported"] = "Unsupported"; +})(SIPExtension || (SIPExtension = {})); +/** + * SIP Option Tags + * @remarks + * http://www.iana.org/assignments/sip-parameters/sip-parameters.xhtml#sip-parameters-4 + * @public + */ +export const 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 new file mode 100644 index 000000000..c0a48616a --- /dev/null +++ b/lib/api/user-agent-state.d.ts @@ -0,0 +1,15 @@ +/** + * {@link UserAgent} state. + * @remarks + * Valid state transitions: + * ``` + * 1. "Started" --> "Stopped" + * 2. "Stopped" --> "Started" + * ``` + * @public + */ +export declare enum UserAgentState { + Started = "Started", + 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 new file mode 100644 index 000000000..b3ec610be --- /dev/null +++ b/lib/api/user-agent-state.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"user-agent-state.d.ts","sourceRoot":"","sources":["../../src/api/user-agent-state.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,oBAAY,cAAc;IACxB,OAAO,YAAY;IACnB,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 new file mode 100644 index 000000000..09065910e --- /dev/null +++ b/lib/api/user-agent-state.js @@ -0,0 +1,15 @@ +/** + * {@link UserAgent} state. + * @remarks + * Valid state transitions: + * ``` + * 1. "Started" --> "Stopped" + * 2. "Stopped" --> "Started" + * ``` + * @public + */ +export var UserAgentState; +(function (UserAgentState) { + UserAgentState["Started"] = "Started"; + UserAgentState["Stopped"] = "Stopped"; +})(UserAgentState || (UserAgentState = {})); diff --git a/lib/api/user-agent.d.ts b/lib/api/user-agent.d.ts new file mode 100644 index 000000000..9e82d5f12 --- /dev/null +++ b/lib/api/user-agent.d.ts @@ -0,0 +1,201 @@ +import { Contact, Logger, LoggerFactory, URI, UserAgentCore } from "../core"; +import { Emitter } from "./emitter"; +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 { Transport } from "./transport"; +import { UserAgentDelegate } from "./user-agent-delegate"; +import { UserAgentOptions } from "./user-agent-options"; +import { UserAgentState } from "./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 + */ +export declare class UserAgent { + /** + * Property reserved for use by instance owner. + * @defaultValue `undefined` + */ + data: unknown; + /** + * Delegate. + */ + delegate: UserAgentDelegate | undefined; + /** @internal */ + _publishers: { + [id: string]: Publisher; + }; + /** @internal */ + _registerers: { + [id: string]: Registerer; + }; + /** @internal */ + _sessions: { + [id: string]: Session; + }; + /** @internal */ + _subscriptions: { + [id: string]: Subscription; + }; + private _contact; + private _state; + private _stateEventEmitter; + private _transport; + private _userAgentCore; + /** Logger. */ + private logger; + /** LoggerFactory. */ + private loggerFactory; + /** Options. */ + private options; + /** + * Constructs a new instance of the `UserAgent` class. + * @param options - Options bucket. See {@link UserAgentOptions} for details. + */ + constructor(options?: Partial); + /** + * 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 defaultOptions; + /** + * Strip properties with undefined values from options. + * This is a work around while waiting for missing vs undefined to be addressed (or not)... + * https://github.com/Microsoft/TypeScript/issues/13195 + * @param options - Options to reduce + */ + private static stripUndefinedProperties; + /** + * User agent configuration. + */ + get configuration(): Required; + /** + * User agent contact. + */ + get contact(): Contact; + /** + * User agent state. + */ + get state(): UserAgentState; + /** + * User agent state change emitter. + */ + get stateChange(): Emitter; + /** + * User agent transport. + */ + get transport(): Transport; + /** + * User agent core. + */ + get userAgentCore(): UserAgentCore; + /** + * The logger. + */ + getLogger(category: string, label?: string): Logger; + /** + * The logger factory. + */ + getLoggerFactory(): LoggerFactory; + /** + * True if transport is connected. + */ + isConnected(): boolean; + /** + * Reconnect the transport. + */ + reconnect(): Promise; + /** + * Start the user agent. + * + * @remarks + * Resolves if transport connects, otherwise rejects. + * + * @example + * ```ts + * userAgent.start() + * .then(() => { + * // userAgent.isConnected() === true + * }) + * .catch((error: Error) => { + * // userAgent.isConnected() === false + * }); + * ``` + */ + start(): Promise; + /** + * Stop the user agent. + * + * @remarks + * Resolves when the user agent has completed a graceful shutdown. + * ```txt + * 1) Sessions terminate. + * 2) Registerers unregister. + * 3) Subscribers unsubscribe. + * 4) Publishers unpublish. + * 5) Transport disconnects. + * 6) User Agent Core resets. + * ``` + * NOTE: While this is a "graceful shutdown", it can also be very slow one if you + * are waiting for the returned Promise to resolve. The disposal of the clients and + * dialogs is done serially - waiting on one to finish before moving on to the next. + * This can be slow if there are lot of subscriptions to unsubscribe for example. + * + * THE SLOW PACE IS INTENTIONAL! + * While one could spin them all down in parallel, this could slam the remote server. + * It is bad practice to denial of service attack (DoS attack) servers!!! + * Moreover, production servers will automatically blacklist clients which send too + * many requests in too short a period of time - dropping any additional requests. + * + * If a different approach to disposing is needed, one can implement whatever is + * needed and execute that prior to calling `stop()`. Alternatively one may simply + * not wait for the Promise returned by `stop()` to complete. + */ + stop(): Promise; + /** + * Used to avoid circular references. + * @internal + */ + _makeInviter(targetURI: URI, options?: InviterOptions): Inviter; + /** + * Attempt reconnection up to `maxReconnectionAttempts` times. + * @param reconnectionAttempt - Current attempt number. + */ + private attemptReconnection; + /** + * Initialize contact. + */ + private initContact; + /** + * Initialize user agent core. + */ + private initCore; + private initTransportCallbacks; + private onTransportConnect; + private onTransportDisconnect; + private onTransportMessage; + /** + * Transition state. + */ + private transitionState; + /** Unload listener. */ + private unloadListener; +} +//# 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 new file mode 100644 index 000000000..bd2c74c60 --- /dev/null +++ b/lib/api/user-agent.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"user-agent.d.ts","sourceRoot":"","sources":["../../src/api/user-agent.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,OAAO,EAYP,MAAM,EACN,aAAa,EAGb,GAAG,EACH,aAAa,EAGd,MAAM,SAAS,CAAC;AAKjB,OAAO,EAAE,OAAO,EAAe,MAAM,WAAW,CAAC;AAEjD,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;AACpC,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAC1D,OAAO,EAAgB,gBAAgB,EAAiC,MAAM,sBAAsB,CAAC;AACrG,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAKpD;;;;;;;;;;GAUG;AACH,qBAAa,SAAS;IACpB;;;OAGG;IACI,IAAI,EAAE,OAAO,CAAC;IAErB;;OAEG;IACI,QAAQ,EAAE,iBAAiB,GAAG,SAAS,CAAC;IAE/C,gBAAgB;IACT,WAAW,EAAE;QAAE,CAAC,EAAE,EAAE,MAAM,GAAG,SAAS,CAAA;KAAE,CAAM;IACrD,gBAAgB;IACT,YAAY,EAAE;QAAE,CAAC,EAAE,EAAE,MAAM,GAAG,UAAU,CAAA;KAAE,CAAM;IACvD,gBAAgB;IACT,SAAS,EAAE;QAAE,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAA;KAAE,CAAM;IACjD,gBAAgB;IACT,cAAc,EAAE;QAAE,CAAC,EAAE,EAAE,MAAM,GAAG,YAAY,CAAA;KAAE,CAAM;IAE3D,OAAO,CAAC,QAAQ,CAAU;IAC1B,OAAO,CAAC,MAAM,CAA0C;IACxD,OAAO,CAAC,kBAAkB,CAA8B;IACxD,OAAO,CAAC,UAAU,CAAY;IAC9B,OAAO,CAAC,cAAc,CAAgB;IAEtC,cAAc;IACd,OAAO,CAAC,MAAM,CAAS;IACvB,qBAAqB;IACrB,OAAO,CAAC,aAAa,CAAgB;IACrC,eAAe;IACf,OAAO,CAAC,OAAO,CAA6B;IAE5C;;;OAGG;gBACgB,OAAO,GAAE,OAAO,CAAC,gBAAgB,CAAM;IA+I1D;;;;;;;;OAQG;WACW,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,GAAG,SAAS;IAInD,kCAAkC;IAClC,OAAO,CAAC,MAAM,CAAC,cAAc;IAwC7B;;;;;OAKG;IACH,OAAO,CAAC,MAAM,CAAC,wBAAwB;IAWvC;;OAEG;IACH,IAAW,aAAa,IAAI,QAAQ,CAAC,gBAAgB,CAAC,CAErD;IAED;;OAEG;IACH,IAAW,OAAO,IAAI,OAAO,CAE5B;IAED;;OAEG;IACH,IAAW,KAAK,IAAI,cAAc,CAEjC;IAED;;OAEG;IACH,IAAW,WAAW,IAAI,OAAO,CAAC,cAAc,CAAC,CAEhD;IAED;;OAEG;IACH,IAAW,SAAS,IAAI,SAAS,CAEhC;IAED;;OAEG;IACH,IAAW,aAAa,IAAI,aAAa,CAExC;IAED;;OAEG;IACI,SAAS,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM;IAI1D;;OAEG;IACI,gBAAgB,IAAI,aAAa;IAIxC;;OAEG;IACI,WAAW,IAAI,OAAO;IAI7B;;OAEG;IACI,SAAS,IAAI,OAAO,CAAC,IAAI,CAAC;IAQjC;;;;;;;;;;;;;;;;OAgBG;IACI,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IA2B7B;;;;;;;;;;;;;;;;;;;;;;;;;;;OA2BG;IACU,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAqGlC;;;OAGG;IACI,YAAY,CAAC,SAAS,EAAE,GAAG,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO;IAItE;;;OAGG;IACH,OAAO,CAAC,mBAAmB;IA0B3B;;OAEG;IACH,OAAO,CAAC,WAAW;IA4BnB;;OAEG;IACH,OAAO,CAAC,QAAQ;IA2NhB,OAAO,CAAC,sBAAsB;IAM9B,OAAO,CAAC,kBAAkB;IAS1B,OAAO,CAAC,qBAAqB;IAa7B,OAAO,CAAC,kBAAkB;IAwG1B;;OAEG;IAEH,OAAO,CAAC,eAAe;IA2BvB,uBAAuB;IACvB,OAAO,CAAC,cAAc,CAEpB;CACH"} \ No newline at end of file diff --git a/lib/api/user-agent.js b/lib/api/user-agent.js new file mode 100644 index 000000000..08efc899c --- /dev/null +++ b/lib/api/user-agent.js @@ -0,0 +1,862 @@ +import { DigestAuthentication, Grammar, IncomingRequestMessage, IncomingResponseMessage, Levels, LoggerFactory, Parser, URI, UserAgentCore } from "../core"; +import { createRandomToken, utf8Length } from "../core/messages/utils"; +import { defaultSessionDescriptionHandlerFactory } from "../platform/web/session-description-handler"; +import { Transport as WebTransport } from "../platform/web/transport"; +import { LIBRARY_VERSION } from "../version"; +import { EmitterImpl } from "./emitter"; +import { Invitation } from "./invitation"; +import { Inviter } from "./inviter"; +import { Message } from "./message"; +import { Notification } from "./notification"; +import { SIPExtension, UserAgentRegisteredOptionTags } from "./user-agent-options"; +import { UserAgentState } from "./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 + */ +export class UserAgent { + /** + * Constructs a new instance of the `UserAgent` class. + * @param options - Options bucket. See {@link UserAgentOptions} for details. + */ + constructor(options = {}) { + /** @internal */ + this._publishers = {}; + /** @internal */ + this._registerers = {}; + /** @internal */ + this._sessions = {}; + /** @internal */ + this._subscriptions = {}; + this._state = UserAgentState.Stopped; + /** Unload listener. */ + this.unloadListener = () => { + this.stop(); + }; + // state emitter + this._stateEventEmitter = new EmitterImpl(); + // initialize delegate + this.delegate = options.delegate; + // initialize configuration + this.options = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, UserAgent.defaultOptions()), { sipjsId: createRandomToken(5) }), { uri: new URI("sip", "anonymous." + createRandomToken(6), "anonymous.invalid") }), { viaHost: createRandomToken(12) + ".invalid" }), UserAgent.stripUndefinedProperties(options)); + // viaHost is hack + if (this.options.hackIpInContact) { + if (typeof this.options.hackIpInContact === "boolean" && this.options.hackIpInContact) { + const from = 1; + const to = 254; + const 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.loggerFactory = new LoggerFactory(); + 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 = Levels.error; + break; + case "warn": + this.loggerFactory.level = Levels.warn; + break; + case "log": + this.loggerFactory.level = Levels.log; + break; + case "debug": + this.loggerFactory.level = Levels.debug; + break; + default: + break; + } + if (this.options.logConfiguration) { + this.logger.log("Configuration:"); + Object.keys(this.options).forEach((key) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const value = this.options[key]; + 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)); + } + }); + } + // guard deprecated transport options (remove this in version 16.x) + if (this.options.transportOptions) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const optionsDeprecated = this.options.transportOptions; + const maxReconnectionAttemptsDeprecated = optionsDeprecated.maxReconnectionAttempts; + const reconnectionTimeoutDeprecated = optionsDeprecated.reconnectionTimeout; + if (maxReconnectionAttemptsDeprecated !== undefined) { + const deprecatedMessage = `The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. ` + + "It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly."; + this.logger.warn(deprecatedMessage); + } + if (reconnectionTimeoutDeprecated !== undefined) { + const deprecatedMessage = `The transport option "reconnectionTimeout" as has apparently been specified and has been deprecated. ` + + "It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly."; + this.logger.warn(deprecatedMessage); + } + // hack + if (options.reconnectionDelay === undefined && reconnectionTimeoutDeprecated !== undefined) { + this.options.reconnectionDelay = reconnectionTimeoutDeprecated; + } + if (options.reconnectionAttempts === undefined && maxReconnectionAttemptsDeprecated !== undefined) { + this.options.reconnectionAttempts = maxReconnectionAttemptsDeprecated; + } + } + // guard deprecated user agent options (remove this in version 16.x) + if (options.reconnectionDelay !== undefined) { + const deprecatedMessage = `The user agent option "reconnectionDelay" as has apparently been specified and has been deprecated. ` + + "It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly."; + this.logger.warn(deprecatedMessage); + } + if (options.reconnectionAttempts !== undefined) { + const deprecatedMessage = `The user agent option "reconnectionAttempts" as has apparently been specified and has been deprecated. ` + + "It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly."; + this.logger.warn(deprecatedMessage); + } + // Initialize Transport + this._transport = new this.options.transportConstructor(this.getLogger("sip.Transport"), this.options.transportOptions); + this.initTransportCallbacks(); + // Initialize Contact + this._contact = this.initContact(); + // Initialize UserAgentCore + 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"); + * ``` + */ + static makeURI(uri) { + return Grammar.URIParse(uri); + } + /** Default user agent options. */ + static defaultOptions() { + return { + allowLegacyNotifications: false, + authorizationHa1: "", + authorizationPassword: "", + authorizationUsername: "", + autoStart: false, + autoStop: true, + delegate: {}, + contactName: "", + contactParams: { transport: "ws" }, + displayName: "", + forceRport: false, + hackAllowUnregisteredOptionTags: false, + hackIpInContact: false, + hackViaTcp: false, + logBuiltinEnabled: true, + logConfiguration: true, + logConnector: () => { + /* noop */ + }, + logLevel: "log", + noAnswerTimeout: 60, + preloadedRouteSet: [], + reconnectionAttempts: 0, + reconnectionDelay: 4, + sessionDescriptionHandlerFactory: defaultSessionDescriptionHandlerFactory(), + sessionDescriptionHandlerFactoryOptions: {}, + sipExtension100rel: SIPExtension.Unsupported, + sipExtensionReplaces: SIPExtension.Unsupported, + sipExtensionExtraSupported: [], + sipjsId: "", + transportConstructor: WebTransport, + transportOptions: {}, + uri: new URI("sip", "anonymous", "anonymous.invalid"), + userAgentString: "SIP.js/" + LIBRARY_VERSION, + viaHost: "" + }; + } + /** + * Strip properties with undefined values from options. + * This is a work around while waiting for missing vs undefined to be addressed (or not)... + * https://github.com/Microsoft/TypeScript/issues/13195 + * @param options - Options to reduce + */ + static stripUndefinedProperties(options) { + return Object.keys(options).reduce((object, key) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (options[key] !== undefined) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + object[key] = options[key]; + } + return object; + }, {}); + } + /** + * User agent configuration. + */ + get configuration() { + return this.options; + } + /** + * User agent contact. + */ + get contact() { + return this._contact; + } + /** + * User agent state. + */ + get state() { + return this._state; + } + /** + * User agent state change emitter. + */ + get stateChange() { + return this._stateEventEmitter; + } + /** + * User agent transport. + */ + get transport() { + return this._transport; + } + /** + * User agent core. + */ + get userAgentCore() { + return this._userAgentCore; + } + /** + * The logger. + */ + getLogger(category, label) { + return this.loggerFactory.getLogger(category, label); + } + /** + * The logger factory. + */ + getLoggerFactory() { + return this.loggerFactory; + } + /** + * True if transport is connected. + */ + isConnected() { + return this.transport.isConnected(); + } + /** + * Reconnect the transport. + */ + reconnect() { + if (this.state === UserAgentState.Stopped) { + return Promise.reject(new Error("User agent stopped.")); + } + // Make sure we don't call synchronously + return Promise.resolve().then(() => this.transport.connect()); + } + /** + * Start the user agent. + * + * @remarks + * Resolves if transport connects, otherwise rejects. + * + * @example + * ```ts + * userAgent.start() + * .then(() => { + * // userAgent.isConnected() === true + * }) + * .catch((error: Error) => { + * // userAgent.isConnected() === false + * }); + * ``` + */ + start() { + if (this.state === UserAgentState.Started) { + this.logger.warn(`User agent already started`); + return Promise.resolve(); + } + this.logger.log(`Starting ${this.configuration.uri}`); + // Transition state + this.transitionState(UserAgentState.Started); + // TODO: Review this as it is not clear it has any benefit and at worst causes additional load the server. + // On unload it may be best to simply in most scenarios to do nothing. Furthermore and regardless, this + // kind of behavior seems more appropriate to be managed by the consumer of the API than the API itself. + // Should this perhaps be deprecated? + // + // Add window unload event listener + if (this.options.autoStop) { + // Google Chrome Packaged Apps don't allow 'unload' listeners: unload is not available in packaged apps + const 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.transport.connect(); + } + /** + * Stop the user agent. + * + * @remarks + * Resolves when the user agent has completed a graceful shutdown. + * ```txt + * 1) Sessions terminate. + * 2) Registerers unregister. + * 3) Subscribers unsubscribe. + * 4) Publishers unpublish. + * 5) Transport disconnects. + * 6) User Agent Core resets. + * ``` + * NOTE: While this is a "graceful shutdown", it can also be very slow one if you + * are waiting for the returned Promise to resolve. The disposal of the clients and + * dialogs is done serially - waiting on one to finish before moving on to the next. + * This can be slow if there are lot of subscriptions to unsubscribe for example. + * + * THE SLOW PACE IS INTENTIONAL! + * While one could spin them all down in parallel, this could slam the remote server. + * It is bad practice to denial of service attack (DoS attack) servers!!! + * Moreover, production servers will automatically blacklist clients which send too + * many requests in too short a period of time - dropping any additional requests. + * + * If a different approach to disposing is needed, one can implement whatever is + * needed and execute that prior to calling `stop()`. Alternatively one may simply + * not wait for the Promise returned by `stop()` to complete. + */ + async stop() { + if (this.state === UserAgentState.Stopped) { + this.logger.warn(`User agent already stopped`); + return Promise.resolve(); + } + this.logger.log(`Stopping ${this.configuration.uri}`); + // Transition state + this.transitionState(UserAgentState.Stopped); + // TODO: See comments with associated complimentary code in start(). Should this perhaps be deprecated? + // Remove window unload event listener + if (this.options.autoStop) { + // Google Chrome Packaged Apps don't allow 'unload' listeners: unload is not available in packaged apps + const googleChromePackagedApp = typeof chrome !== "undefined" && chrome.app && chrome.app.runtime ? true : false; + if (typeof window !== "undefined" && window.removeEventListener && !googleChromePackagedApp) { + window.removeEventListener("unload", this.unloadListener); + } + } + // Be careful here to use a local references as start() can be called + // again before we complete and we don't want to touch new clients + // and we don't want to step on the new instances (or vice versa). + const publishers = Object.assign({}, this._publishers); + const registerers = Object.assign({}, this._registerers); + const sessions = Object.assign({}, this._sessions); + const subscriptions = Object.assign({}, this._subscriptions); + const transport = this.transport; + const userAgentCore = this.userAgentCore; + // + // At this point we have completed the state transition and everything + // following will effectively run async and MUST NOT cause any issues + // if UserAgent.start() is called while the following code continues. + // + // TODO: Minor optimization. + // The disposal in all cases involves, in part, sending messages which + // is not worth doing if the transport is not connected as we know attempting + // to send messages will be futile. But none of these disposal methods check + // if that's is the case and it would be easy for them to do so at this point. + // Dispose of Registerers + this.logger.log(`Dispose of registerers`); + for (const id in registerers) { + if (registerers[id]) { + await registerers[id].dispose().catch((error) => { + this.logger.error(error.message); + delete this._registerers[id]; + throw error; + }); + } + } + // Dispose of Sessions + this.logger.log(`Dispose of sessions`); + for (const id in sessions) { + if (sessions[id]) { + await sessions[id].dispose().catch((error) => { + this.logger.error(error.message); + delete this._sessions[id]; + throw error; + }); + } + } + // Dispose of Subscriptions + this.logger.log(`Dispose of subscriptions`); + for (const id in subscriptions) { + if (subscriptions[id]) { + await subscriptions[id].dispose().catch((error) => { + this.logger.error(error.message); + delete this._subscriptions[id]; + throw error; + }); + } + } + // Dispose of Publishers + this.logger.log(`Dispose of publishers`); + for (const id in publishers) { + if (publishers[id]) { + await publishers[id].dispose().catch((error) => { + this.logger.error(error.message); + delete this._publishers[id]; + throw error; + }); + } + } + // Dispose of the transport (disconnecting) + this.logger.log(`Dispose of transport`); + await transport.dispose().catch((error) => { + this.logger.error(error.message); + throw error; + }); + // Dispose of the user agent core (resetting) + this.logger.log(`Dispose of core`); + userAgentCore.dispose(); + } + /** + * Used to avoid circular references. + * @internal + */ + _makeInviter(targetURI, options) { + return new Inviter(this, targetURI, options); + } + /** + * Attempt reconnection up to `maxReconnectionAttempts` times. + * @param reconnectionAttempt - Current attempt number. + */ + attemptReconnection(reconnectionAttempt = 1) { + const reconnectionAttempts = this.options.reconnectionAttempts; + const reconnectionDelay = this.options.reconnectionDelay; + if (reconnectionAttempt > reconnectionAttempts) { + this.logger.log(`Maximum reconnection attempts reached`); + return; + } + this.logger.log(`Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - trying`); + setTimeout(() => { + this.reconnect() + .then(() => { + this.logger.log(`Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - succeeded`); + }) + .catch((error) => { + this.logger.error(error.message); + this.logger.log(`Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - failed`); + this.attemptReconnection(++reconnectionAttempt); + }); + }, reconnectionAttempt === 1 ? 0 : reconnectionDelay * 1000); + } + /** + * Initialize contact. + */ + initContact() { + const contactName = this.options.contactName != "" ? this.options.contactName : createRandomToken(8); + const contactParams = this.options.contactParams; + const contact = { + pubGruu: undefined, + tempGruu: undefined, + uri: new URI("sip", contactName, this.options.viaHost, undefined, contactParams), + toString: (contactToStringOptions = {}) => { + const anonymous = contactToStringOptions.anonymous || false; + const outbound = contactToStringOptions.outbound || false; + let contactString = "<"; + if (anonymous) { + contactString += + this.contact.tempGruu || + `sip:anonymous@anonymous.invalid;transport=${contactParams.transport ? contactParams.transport : "ws"}`; + } + else { + contactString += this.contact.pubGruu || this.contact.uri; + } + if (outbound) { + contactString += ";ob"; + } + contactString += ">"; + return contactString; + } + }; + return contact; + } + /** + * Initialize user agent core. + */ + initCore() { + // supported options + let supportedOptionTags = []; + supportedOptionTags.push("outbound"); // TODO: is this really supported? + if (this.options.sipExtension100rel === SIPExtension.Supported) { + supportedOptionTags.push("100rel"); + } + if (this.options.sipExtensionReplaces === SIPExtension.Supported) { + supportedOptionTags.push("replaces"); + } + if (this.options.sipExtensionExtraSupported) { + supportedOptionTags.push(...this.options.sipExtensionExtraSupported); + } + if (!this.options.hackAllowUnregisteredOptionTags) { + supportedOptionTags = supportedOptionTags.filter((optionTag) => 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. + const supportedOptionTagsResponse = supportedOptionTags.slice(); + if (this.contact.pubGruu || this.contact.tempGruu) { + supportedOptionTagsResponse.push("gruu"); + } + // core configuration + const userAgentCoreConfiguration = { + aor: this.options.uri, + contact: this.contact, + displayName: this.options.displayName, + loggerFactory: this.loggerFactory, + hackViaTcp: this.options.hackViaTcp, + routeSet: this.options.preloadedRouteSet, + supportedOptionTags, + supportedOptionTagsResponse, + sipjsId: this.options.sipjsId, + userAgentHeaderFieldValue: this.options.userAgentString, + viaForceRport: this.options.forceRport, + viaHost: this.options.viaHost, + authenticationFactory: () => { + const username = this.options.authorizationUsername + ? this.options.authorizationUsername + : this.options.uri.user; // if authorization username not provided, use uri user as username + const password = this.options.authorizationPassword ? this.options.authorizationPassword : undefined; + const ha1 = this.options.authorizationHa1 ? this.options.authorizationHa1 : undefined; + return new DigestAuthentication(this.getLoggerFactory(), ha1, username, password); + }, + transportAccessor: () => this.transport + }; + const userAgentCoreDelegate = { + onInvite: (incomingInviteRequest) => { + var _a; + const invitation = new Invitation(this, incomingInviteRequest); + incomingInviteRequest.delegate = { + onCancel: (cancel) => { + invitation._onCancel(cancel); + }, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onTransportError: (error) => { + // A server transaction MUST NOT discard transaction state based only on + // encountering a non-recoverable transport error when sending a + // response. Instead, the associated INVITE server transaction state + // machine MUST remain in its current state. (Timers will eventually + // cause it to transition to the "Terminated" state). + // https://tools.ietf.org/html/rfc6026#section-7.1 + // As noted in the comment above, we are to leaving it to the transaction + // timers to eventually cause the transaction to sort itself out in the case + // of a transport failure in an invite server transaction. This delegate method + // is here simply here for completeness and to make it clear that it provides + // nothing more than informational hook into the core. That is, if you think + // you should be trying to deal with a transport error here, you are likely wrong. + this.logger.error("A transport error has occurred while handling an incoming INVITE request."); + } + }; + // 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 !== SIPExtension.Unsupported) { + const message = incomingInviteRequest.message; + const replaces = message.parseHeader("replaces"); + if (replaces) { + const callId = replaces.call_id; + if (typeof callId !== "string") { + throw new Error("Type of call id is not string"); + } + const toTag = replaces.replaces_to_tag; + if (typeof toTag !== "string") { + throw new Error("Type of to tag is not string"); + } + const fromTag = replaces.replaces_from_tag; + if (typeof fromTag !== "string") { + throw new Error("type of from tag is not string"); + } + const targetDialogId = callId + toTag + fromTag; + const 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. + const targetSession = this._sessions[callId + fromTag] || this._sessions[callId + toTag] || undefined; + if (!targetSession) { + throw new Error("Session does not exist."); + } + invitation._replacee = targetSession; + } + } + // Delegate invitation handling. + if ((_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onInvite) { + if (invitation.autoSendAnInitialProvisionalResponse) { + invitation.progress().then(() => { + var _a; + if (((_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onInvite) === undefined) { + throw new Error("onInvite undefined."); + } + this.delegate.onInvite(invitation); + }); + return; + } + this.delegate.onInvite(invitation); + return; + } + // 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 + invitation.reject({ statusCode: 486 }); + }, + onMessage: (incomingMessageRequest) => { + if (this.delegate && this.delegate.onMessage) { + const message = new Message(incomingMessageRequest); + this.delegate.onMessage(message); + } + else { + // Accept the MESSAGE request, but do nothing with it. + incomingMessageRequest.accept(); + } + }, + onNotify: (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) { + const notification = new Notification(incomingNotifyRequest); + this.delegate.onNotify(notification); + } + else { + // Per the above which obsoletes 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: (incomingReferRequest) => { + this.logger.warn("Received an out of dialog REFER request"); + // TOOD: this.delegate.onRefer(...) + if (this.delegate && this.delegate.onReferRequest) { + this.delegate.onReferRequest(incomingReferRequest); + } + else { + incomingReferRequest.reject({ statusCode: 405 }); + } + }, + onRegister: (incomingRegisterRequest) => { + this.logger.warn("Received an out of dialog REGISTER request"); + // TOOD: this.delegate.onRegister(...) + if (this.delegate && this.delegate.onRegisterRequest) { + this.delegate.onRegisterRequest(incomingRegisterRequest); + } + else { + incomingRegisterRequest.reject({ statusCode: 405 }); + } + }, + onSubscribe: (incomingSubscribeRequest) => { + this.logger.warn("Received an out of dialog SUBSCRIBE request"); + // TOOD: this.delegate.onSubscribe(...) + if (this.delegate && this.delegate.onSubscribeRequest) { + this.delegate.onSubscribeRequest(incomingSubscribeRequest); + } + else { + incomingSubscribeRequest.reject({ statusCode: 405 }); + } + } + }; + return new UserAgentCore(userAgentCoreConfiguration, userAgentCoreDelegate); + } + initTransportCallbacks() { + this.transport.onConnect = () => this.onTransportConnect(); + this.transport.onDisconnect = (error) => this.onTransportDisconnect(error); + this.transport.onMessage = (message) => this.onTransportMessage(message); + } + onTransportConnect() { + if (this.state === UserAgentState.Stopped) { + return; + } + if (this.delegate && this.delegate.onConnect) { + this.delegate.onConnect(); + } + } + onTransportDisconnect(error) { + if (this.state === UserAgentState.Stopped) { + return; + } + if (this.delegate && this.delegate.onDisconnect) { + this.delegate.onDisconnect(error); + } + // Only attempt to reconnect if network/server dropped the connection. + if (error && this.options.reconnectionAttempts > 0) { + this.attemptReconnection(); + } + } + onTransportMessage(messageString) { + const message = Parser.parseMessage(messageString, this.getLogger("sip.Parser")); + if (!message) { + this.logger.warn("Failed to parse incoming message. Dropping."); + return; + } + if (this.state === UserAgentState.Stopped && message instanceof IncomingRequestMessage) { + this.logger.warn(`Received ${message.method} request while stopped. 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 + const hasMinimumHeaders = () => { + const mandatoryHeaders = ["from", "to", "call_id", "cseq", "via"]; + for (const header of mandatoryHeaders) { + if (!message.hasHeader(header)) { + this.logger.warn(`Missing mandatory header field : ${header}.`); + return false; + } + } + return true; + }; + // Request Checks + if (message instanceof 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 configurable 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(). + const len = utf8Length(message.body); + const contentLength = message.getHeader("content-length"); + if (contentLength && len < Number(contentLength)) { + this.userAgentCore.replyStateless(message, { statusCode: 400 }); + return; + } + } + // Response Checks + if (message instanceof 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(). + const len = utf8Length(message.body); + const 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 IncomingRequestMessage) { + this.userAgentCore.receiveIncomingRequestFromTransport(message); + return; + } + // Handle Response + if (message instanceof IncomingResponseMessage) { + this.userAgentCore.receiveIncomingResponseFromTransport(message); + return; + } + throw new Error("Invalid message type."); + } + /** + * Transition state. + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + transitionState(newState, error) { + const invalidTransition = () => { + throw new Error(`Invalid state transition from ${this._state} to ${newState}`); + }; + // Validate state transition + switch (this._state) { + case UserAgentState.Started: + if (newState !== UserAgentState.Stopped) { + invalidTransition(); + } + break; + case UserAgentState.Stopped: + if (newState !== UserAgentState.Started) { + invalidTransition(); + } + break; + default: + throw new Error("Unknown state."); + } + // Update state + this.logger.log(`Transitioned from ${this._state} to ${newState}`); + this._state = newState; + this._stateEventEmitter.emit(this._state); + } +} diff --git a/lib/core/dialogs/dialog-state.d.ts b/lib/core/dialogs/dialog-state.d.ts new file mode 100644 index 000000000..1d97f8759 --- /dev/null +++ b/lib/core/dialogs/dialog-state.d.ts @@ -0,0 +1,35 @@ +import { URI } from "../../grammar"; +/** + * 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 new file mode 100644 index 000000000..e9eebc558 --- /dev/null +++ b/lib/core/dialogs/dialog-state.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"dialog-state.d.ts","sourceRoot":"","sources":["../../../src/core/dialogs/dialog-state.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,eAAe,CAAC;AAEpC;;;;;;;;;;;;;;;;;;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 new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/core/dialogs/dialog-state.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/core/dialogs/dialog.d.ts b/lib/core/dialogs/dialog.d.ts new file mode 100644 index 000000000..1c33af893 --- /dev/null +++ b/lib/core/dialogs/dialog.d.ts @@ -0,0 +1,162 @@ +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; + /** + * Dialog constructor. + * @param core - User agent core. + * @param dialogState - Initial dialog state. + */ + protected constructor(core: UserAgentCore, 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; + /** 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 + */ + get 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). + */ + get early(): boolean; + /** Call identifier component of the dialog id. */ + get callId(): string; + /** Local tag component of the dialog id. */ + get localTag(): string; + /** Remote tag component of the dialog id. */ + get remoteTag(): string; + /** Local sequence number (used to order requests from the UA to its peer). */ + get localSequenceNumber(): number | undefined; + /** Remote sequence number (used to order requests from its peer to the UA). */ + get remoteSequenceNumber(): number | undefined; + /** Local URI. */ + get localURI(): URI; + /** Remote URI. */ + get remoteURI(): URI; + /** Remote target. */ + get 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. + */ + get 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* + */ + get secure(): boolean; + /** The user agent core servicing this dialog. */ + get 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; + /** + * Increment the local sequence number by one. + * It feels like this should be protected, but the current authentication handling currently + * needs this to keep the dialog in sync when "auto re-sends" request messages. + * @internal + */ + incrementLocalSequenceNumber(): void; + /** + * 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 new file mode 100644 index 000000000..119237ac3 --- /dev/null +++ b/lib/core/dialogs/dialog.d.ts.map @@ -0,0 +1 @@ +{"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;IAMK,SAAS,CAAC,IAAI,EAAE,aAAa;IAAE,SAAS,CAAC,WAAW,EAAE,WAAW;IALvF;;;;OAIG;IACH,SAAS,aAAuB,IAAI,EAAE,aAAa,EAAY,WAAW,EAAE,WAAW;IAIvF;;;;;;;OAOG;WACW,oCAAoC,CAChD,sBAAsB,EAAE,sBAAsB,EAC9C,uBAAuB,EAAE,uBAAuB,GAC/C,WAAW;IA2Gd;;;;;;OAMG;WACW,oCAAoC,CAChD,sBAAsB,EAAE,sBAAsB,EAC9C,KAAK,EAAE,MAAM,EACb,KAAK,UAAQ,GACZ,WAAW;IAqEd,kBAAkB;IACX,OAAO,IAAI,IAAI;IAItB;;;;;;;;OAQG;IACH,IAAW,EAAE,IAAI,MAAM,CAEtB;IAED;;;;;;;;;;;;;OAaG;IACH,IAAW,KAAK,IAAI,OAAO,CAE1B;IAED,kDAAkD;IAClD,IAAW,MAAM,IAAI,MAAM,CAE1B;IAED,4CAA4C;IAC5C,IAAW,QAAQ,IAAI,MAAM,CAE5B;IAED,6CAA6C;IAC7C,IAAW,SAAS,IAAI,MAAM,CAE7B;IAED,8EAA8E;IAC9E,IAAW,mBAAmB,IAAI,MAAM,GAAG,SAAS,CAEnD;IAED,+EAA+E;IAC/E,IAAW,oBAAoB,IAAI,MAAM,GAAG,SAAS,CAEpD;IAED,iBAAiB;IACjB,IAAW,QAAQ,IAAI,GAAG,CAEzB;IAED,kBAAkB;IAClB,IAAW,SAAS,IAAI,GAAG,CAE1B;IAED,qBAAqB;IACrB,IAAW,YAAY,IAAI,GAAG,CAE7B;IAED;;;OAGG;IACH,IAAW,QAAQ,IAAI,KAAK,CAAC,MAAM,CAAC,CAEnC;IAED;;;OAGG;IACH,IAAW,MAAM,IAAI,OAAO,CAE3B;IAED,iDAAiD;IACjD,IAAW,aAAa,IAAI,aAAa,CAExC;IAED,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;;;;;OAKG;IACI,4BAA4B,IAAI,IAAI;IAO3C;;;;;;;;;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 new file mode 100644 index 000000000..5b5c5d130 --- /dev/null +++ b/lib/core/dialogs/dialog.js @@ -0,0 +1,532 @@ +import { C, NameAddrHeader } from "../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 + */ +export class Dialog { + /** + * Dialog constructor. + * @param core - User agent core. + * @param dialogState - Initial dialog state. + */ + constructor(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. + */ + static initialDialogStateForUserAgentClient(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 + const 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 + const routeSet = incomingResponseMessage.getHeaders("record-route").reverse(); + // 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. + // https://tools.ietf.org/html/rfc3261#section-12.1.1 + const contact = incomingResponseMessage.parseHeader("contact"); + if (!contact) { + // TODO: Review to make sure this will never happen + throw new Error("Contact undefined."); + } + if (!(contact instanceof NameAddrHeader)) { + throw new Error("Contact not instance of NameAddrHeader."); + } + const 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 + const localSequenceNumber = outgoingRequestMessage.cseq; + const remoteSequenceNumber = undefined; + const callId = outgoingRequestMessage.callId; + const localTag = outgoingRequestMessage.fromTag; + const 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."); + } + const localURI = outgoingRequestMessage.from.uri; + const 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."); + } + const early = incomingResponseMessage.statusCode < 200 ? true : false; + const dialogState = { + id: callId + localTag + remoteTag, + early, + callId, + localTag, + remoteTag, + localSequenceNumber, + remoteSequenceNumber, + localURI, + remoteURI, + remoteTarget, + routeSet, + 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. + */ + static initialDialogStateForUserAgentServer(incomingRequestMessage, toTag, 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 + const 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 + const routeSet = incomingRequestMessage.getHeaders("record-route"); + const contact = incomingRequestMessage.parseHeader("contact"); + if (!contact) { + // TODO: Review to make sure this will never happen + throw new Error("Contact undefined."); + } + if (!(contact instanceof NameAddrHeader)) { + throw new Error("Contact not instance of NameAddrHeader."); + } + const 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 + const remoteSequenceNumber = incomingRequestMessage.cseq; + const localSequenceNumber = undefined; + const callId = incomingRequestMessage.callId; + const localTag = toTag; + const 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 + const remoteURI = incomingRequestMessage.from.uri; + const localURI = incomingRequestMessage.to.uri; + const dialogState = { + id: callId + localTag + remoteTag, + early, + callId, + localTag, + remoteTag, + localSequenceNumber, + remoteSequenceNumber, + localURI, + remoteURI, + remoteTarget, + routeSet, + secure + }; + return dialogState; + } + /** Destructor. */ + dispose() { + this.core.dialogs.delete(this.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 id() { + return this.dialogState.id; + } + /** + * 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 early() { + return this.dialogState.early; + } + /** Call identifier component of the dialog id. */ + get callId() { + return this.dialogState.callId; + } + /** Local tag component of the dialog id. */ + get localTag() { + return this.dialogState.localTag; + } + /** Remote tag component of the dialog id. */ + get remoteTag() { + return this.dialogState.remoteTag; + } + /** Local sequence number (used to order requests from the UA to its peer). */ + get localSequenceNumber() { + return this.dialogState.localSequenceNumber; + } + /** Remote sequence number (used to order requests from its peer to the UA). */ + get remoteSequenceNumber() { + return this.dialogState.remoteSequenceNumber; + } + /** Local URI. */ + get localURI() { + return this.dialogState.localURI; + } + /** Remote URI. */ + get remoteURI() { + return this.dialogState.remoteURI; + } + /** Remote target. */ + get remoteTarget() { + return this.dialogState.remoteTarget; + } + /** + * 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 routeSet() { + return this.dialogState.routeSet; + } + /** + * 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 secure() { + return this.dialogState.secure; + } + /** The user agent core servicing this dialog. */ + get userAgentCore() { + return this.core; + } + /** Confirm the dialog. Only matters if dialog is currently early. */ + confirm() { + 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. + */ + receiveRequest(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 === 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 + */ + recomputeRouteSet(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. + */ + createOutgoingRequestMessage(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 + const toUri = this.remoteURI; + const toTag = this.remoteTag; + const fromUri = this.localURI; + const 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 + const callId = this.callId; + let 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). + const ruri = this.remoteTarget; + const routeSet = this.routeSet; + const extraHeaders = options && options.extraHeaders; + const 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 + const message = this.userAgentCore.makeOutgoingRequestMessage(method, ruri, fromUri, toUri, { + callId, + cseq, + fromTag, + toTag, + routeSet + }, extraHeaders, body); + return message; + } + /** + * Increment the local sequence number by one. + * It feels like this should be protected, but the current authentication handling currently + * needs this to keep the dialog in sync when "auto re-sends" request messages. + * @internal + */ + incrementLocalSequenceNumber() { + if (!this.dialogState.localSequenceNumber) { + throw new Error("Local sequence number undefined."); + } + this.dialogState.localSequenceNumber += 1; + } + /** + * 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. + */ + sequenceGuard(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 === 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; + } +} diff --git a/lib/core/dialogs/index.d.ts b/lib/core/dialogs/index.d.ts new file mode 100644 index 000000000..c09e33400 --- /dev/null +++ b/lib/core/dialogs/index.d.ts @@ -0,0 +1,5 @@ +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 new file mode 100644 index 000000000..12c5dbfac --- /dev/null +++ b/lib/core/dialogs/index.d.ts.map @@ -0,0 +1 @@ +{"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 new file mode 100644 index 000000000..7cacf07f2 --- /dev/null +++ b/lib/core/dialogs/index.js @@ -0,0 +1,4 @@ +export * from "./dialog"; +export * from "./dialog-state"; +export * from "./session-dialog"; +export * from "./subscription-dialog"; diff --git a/lib/core/dialogs/session-dialog.d.ts b/lib/core/dialogs/session-dialog.d.ts new file mode 100644 index 000000000..2388594d2 --- /dev/null +++ b/lib/core/dialogs/session-dialog.d.ts @@ -0,0 +1,197 @@ +import { Body, IncomingRequestMessage, IncomingResponseMessage, OutgoingAckRequest, OutgoingByeRequest, OutgoingInfoRequest, OutgoingInviteRequest, OutgoingInviteRequestDelegate, OutgoingMessageRequest, 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; + /** True if processing an ACK to the initial transaction 2xx (UAS only). */ + private ackProcessing; + /** 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; + get sessionState(): SessionState; + /** The state of the offer/answer exchange. */ + get signalingState(): SignalingState; + /** The current offer. Undefined unless signaling state HaveLocalOffer, HaveRemoteOffer, of Stable. */ + get offer(): Body | undefined; + /** The current answer. Undefined unless signaling state Stable. */ + get 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; + /** + * A UAC MAY associate a MESSAGE request with an existing dialog. If a + * MESSAGE request is sent within a dialog, it is "associated" with any + * media session or sessions associated with that dialog. + * https://tools.ietf.org/html/rfc3428#section-4 + * @param options - Options bucket. + */ + message(delegate: OutgoingRequestDelegate, options?: RequestOptions): OutgoingMessageRequest; + /** + * 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; + /** + * Guard against out of order reliable provisional responses and retransmissions. + * Returns false if the response should be discarded, otherwise true. + * @param message - Incoming response message within this dialog. + */ + 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 new file mode 100644 index 000000000..bd291f5d8 --- /dev/null +++ b/lib/core/dialogs/session-dialog.d.ts.map @@ -0,0 +1 @@ +{"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,sBAAsB,EACtB,qBAAqB,EACrB,oBAAoB,EACpB,oBAAoB,EACpB,uBAAuB,EACvB,sBAAsB,EACtB,cAAc,EACf,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,OAAO,EAAE,eAAe,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEpF,OAAO,EAAE,uBAAuB,EAAE,uBAAuB,EAAoB,MAAM,iBAAiB,CAAC;AACrG,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAWnD,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;IA6BxD,OAAO,CAAC,kBAAkB;IA5BrB,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,2EAA2E;IAC3E,OAAO,CAAC,aAAa,CAAS;IAC9B,wEAAwE;IACxE,OAAO,CAAC,cAAc,CAAqB;IAC3C,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;IAsBtB,IAAI,YAAY,IAAI,YAAY,CAU/B;IAED,8CAA8C;IAC9C,IAAI,cAAc,IAAI,cAAc,CAEnC;IAED,sGAAsG;IACtG,IAAI,KAAK,IAAI,IAAI,GAAG,SAAS,CAE5B;IAED,mEAAmE;IACnE,IAAI,MAAM,IAAI,IAAI,GAAG,SAAS,CAE7B;IAED,qEAAqE;IAC9D,OAAO,IAAI,IAAI;IAStB,yEAAyE;IAClE,SAAS,IAAI,IAAI;IAQxB;;;;;;;;;;;;;;OAcG;IACI,GAAG,CAAC,OAAO,GAAE,cAAmB,GAAG,kBAAkB;IA2B5D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;;;;;;OAMG;IACI,OAAO,CAAC,QAAQ,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,sBAAsB;IAUnG;;;;;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;IAiR5D;;;;OAIG;IACI,qBAAqB,CAAC,OAAO,EAAE,uBAAuB,GAAG,OAAO;IAgDvE;;OAEG;IACI,sBAAsB,IAAI,IAAI;IAarC;;;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 new file mode 100644 index 000000000..dda12375c --- /dev/null +++ b/lib/core/dialogs/session-dialog.js @@ -0,0 +1,895 @@ +import { C, getBody, IncomingRequestMessage, IncomingResponseMessage, isBody, NameAddrHeader, OutgoingRequestMessage } from "../messages"; +import { SessionState, SignalingState } from "../session"; +import { Timers } from "../timers"; +import { InviteClientTransaction, InviteServerTransaction, TransactionState } from "../transactions"; +import { ByeUserAgentClient } from "../user-agents/bye-user-agent-client"; +import { ByeUserAgentServer } from "../user-agents/bye-user-agent-server"; +import { InfoUserAgentClient } from "../user-agents/info-user-agent-client"; +import { InfoUserAgentServer } from "../user-agents/info-user-agent-server"; +import { MessageUserAgentClient } from "../user-agents/message-user-agent-client"; +import { MessageUserAgentServer } from "../user-agents/message-user-agent-server"; +import { NotifyUserAgentClient } from "../user-agents/notify-user-agent-client"; +import { NotifyUserAgentServer } from "../user-agents/notify-user-agent-server"; +import { PrackUserAgentClient } from "../user-agents/prack-user-agent-client"; +import { PrackUserAgentServer } from "../user-agents/prack-user-agent-server"; +import { ReInviteUserAgentClient } from "../user-agents/re-invite-user-agent-client"; +import { ReInviteUserAgentServer } from "../user-agents/re-invite-user-agent-server"; +import { ReferUserAgentClient } from "../user-agents/refer-user-agent-client"; +import { ReferUserAgentServer } from "../user-agents/refer-user-agent-server"; +import { Dialog } from "./dialog"; +/** + * Session Dialog. + * @public + */ +export class SessionDialog extends Dialog { + constructor(initialTransaction, core, state, delegate) { + super(core, state); + this.initialTransaction = initialTransaction; + /** The state of the offer/answer exchange. */ + this._signalingState = SignalingState.Initial; + /** True if waiting for an ACK to the initial transaction 2xx (UAS only). */ + this.ackWait = false; + /** True if processing an ACK to the initial transaction 2xx (UAS only). */ + this.ackProcessing = false; + this.delegate = delegate; + if (initialTransaction instanceof 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`); + } + dispose() { + super.dispose(); + this._signalingState = 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`); + } + // FIXME: Need real state machine + get sessionState() { + if (this.early) { + return SessionState.Early; + } + else if (this.ackWait) { + return SessionState.AckWait; + } + else if (this._signalingState === SignalingState.Closed) { + return SessionState.Terminated; + } + else { + return SessionState.Confirmed; + } + } + /** The state of the offer/answer exchange. */ + get signalingState() { + return this._signalingState; + } + /** The current offer. Undefined unless signaling state HaveLocalOffer, HaveRemoteOffer, of Stable. */ + get offer() { + return this._offer; + } + /** The current answer. Undefined unless signaling state Stable. */ + get answer() { + return this._answer; + } + /** Confirm the dialog. Only matters if dialog is currently early. */ + confirm() { + // When we're confirmed start the retransmitting whatever + // the 2xx final response that may have confirmed us. + if (this.early) { + this.start2xxRetransmissionTimer(); + } + super.confirm(); + } + /** Re-confirm the dialog. Only matters if handling re-INVITE request. */ + reConfirm() { + // 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. + */ + ack(options = {}) { + this.logger.log(`INVITE dialog ${this.id} sending ACK request`); + let transaction; + if (this.reinviteUserAgentClient) { + // We're sending ACK for a re-INVITE + if (!(this.reinviteUserAgentClient.transaction instanceof 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 InviteClientTransaction)) { + throw new Error("Initial transaction not instance of InviteClientTransaction."); + } + transaction = this.initialTransaction; + } + const message = this.createOutgoingRequestMessage(C.ACK, { + cseq: transaction.request.cseq, + extraHeaders: options.extraHeaders, + body: options.body + }); + transaction.ackResponse(message); // See InviteClientTransaction for details. + this.signalingStateTransition(message); + return { 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. + */ + bye(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 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 !== 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 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. + */ + info(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 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 + */ + invite(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 ReInviteUserAgentClient(this, delegate, options); + } + /** + * A UAC MAY associate a MESSAGE request with an existing dialog. If a + * MESSAGE request is sent within a dialog, it is "associated" with any + * media session or sessions associated with that dialog. + * https://tools.ietf.org/html/rfc3428#section-4 + * @param options - Options bucket. + */ + message(delegate, options) { + this.logger.log(`INVITE dialog ${this.id} sending MESSAGE request`); + if (this.early) { + // FIXME: TODO: This should throw a proper exception. + throw new Error("Dialog not confirmed."); + } + const message = this.createOutgoingRequestMessage(C.MESSAGE, options); + return new MessageUserAgentClient(this.core, message, delegate); + } + /** + * 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, 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 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. + */ + prack(delegate, options) { + this.logger.log(`INVITE dialog ${this.id} sending PRACK request`); + return new 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. + */ + refer(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 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. + */ + receiveRequest(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 === 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 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) { + const promiseOrVoid = this.delegate.onAck({ message }); + if (promiseOrVoid instanceof Promise) { + this.ackProcessing = true; // make sure this is always reset to false + promiseOrVoid.then(() => (this.ackProcessing = false)).catch(() => (this.ackProcessing = false)); + } + } + 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; + } + // Request within a dialog common processing. + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + super.receiveRequest(message); + // Handle various INVITE related cross-over, glare and race conditions + if (message.method === C.INVITE) { + // Hopefully this message is helpful... + const warning = () => { + const reason = this.ackWait ? "waiting for initial ACK" : "processing initial ACK"; + this.logger.warn(`INVITE dialog ${this.id} received re-INVITE while ${reason}`); + let msg = "RFC 5407 suggests the following to avoid this race condition... "; + msg += " Note: Implementation issues are outside the scope of this document,"; + msg += " but the following tip is provided for avoiding race conditions of"; + msg += " this type. The caller can delay sending re-INVITE F6 for some period"; + msg += " of time (2 seconds, perhaps), after which the caller can reasonably"; + msg += " assume that its ACK has been received. Implementors can decouple the"; + msg += " actions of the user (e.g., pressing the hold button) from the actions"; + msg += " of the protocol (the sending of re-INVITE F6), so that the UA can"; + msg += " behave like this. In this case, it is the implementor's choice as to"; + msg += " how long to wait. In most cases, such an implementation may be"; + msg += " useful to prevent the type of race condition shown in this section."; + msg += " This document expresses no preference about whether or not they"; + msg += " should wait for an ACK to be delivered. After considering the impact"; + msg += " on user experience, implementors should decide whether or not to wait"; + msg += " for a while, because the user experience depends on the"; + msg += " implementation and has no direct bearing on protocol behavior."; + this.logger.warn(msg); + return; // drop re-INVITE request message + }; + // 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 + const retryAfter = Math.floor(Math.random() * 10) + 1; + const extraHeaders = [`Retry-After: ${retryAfter}`]; + // There may be ONLY ONE offer/answer negotiation in progress for a + // single dialog at any point in time. Section 4 explains how to ensure + // this. + // https://tools.ietf.org/html/rfc6337#section-2.2 + if (this.ackProcessing) { + // UAS-IsI: While an INVITE server transaction is incomplete or ACK + // transaction associated with an offer/answer is incomplete, + // a UA must reject another INVITE request with a 500 + // response. + // https://tools.ietf.org/html/rfc6337#section-4.3 + this.core.replyStateless(message, { statusCode: 500, extraHeaders }); + warning(); + return; + } + // 3.1.4. Callee Receives re-INVITE (Established State) While in the + // Moratorium State (Case 1) + // https://tools.ietf.org/html/rfc5407#section-3.1.4 + // 3.1.5. Callee Receives re-INVITE (Established State) While in the + // Moratorium State (Case 2) + // https://tools.ietf.org/html/rfc5407#section-3.1.5 + if (this.ackWait && this.signalingState !== SignalingState.Stable) { + // This scenario is basically the same as that of Section 3.1.4, but + // differs in sending an offer in the 200 and an answer in the ACK. In + // contrast to the previous case, the offer in the 200 (F3) and the + // offer in the re-INVITE (F6) collide with each other. + // + // Bob sends a 491 to the re-INVITE (F6) since he is not able to + // properly handle a new request until he receives an answer. (Note: + // 500 with a Retry-After header may be returned if the 491 response is + // understood to indicate request collision. However, 491 is + // recommended here because 500 applies to so many cases that it is + // difficult to determine what the real problem was.) + // https://tools.ietf.org/html/rfc5407#section-3.1.5 + // UAS-IsI: While an INVITE server transaction is incomplete or ACK + // transaction associated with an offer/answer is incomplete, + // a UA must reject another INVITE request with a 500 + // response. + // https://tools.ietf.org/html/rfc6337#section-4.3 + this.core.replyStateless(message, { statusCode: 500, extraHeaders }); + warning(); + return; + } + // 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) { + this.core.replyStateless(message, { statusCode: 500, 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; + } + } + // 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 === C.INVITE) { + // FIXME: parser needs to be typed... + const contact = message.parseHeader("contact"); + if (!contact) { + // TODO: Review to make sure this will never happen + throw new Error("Contact undefined."); + } + if (!(contact instanceof NameAddrHeader)) { + throw new Error("Contact not instance of NameAddrHeader."); + } + this.dialogState.remoteTarget = contact.uri; + } + // Switch on method and then delegate. + switch (message.method) { + case 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 + { + const uas = new ByeUserAgentServer(this, message); + this.delegate && this.delegate.onBye ? this.delegate.onBye(uas) : uas.accept(); + this.dispose(); + } + break; + case 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. + { + const uas = new InfoUserAgentServer(this, message); + this.delegate && this.delegate.onInfo + ? this.delegate.onInfo(uas) + : uas.reject({ + statusCode: 469, + extraHeaders: ["Recv-Info :"] + }); + } + break; + case 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 + { + const uas = new 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 C.MESSAGE: + { + const uas = new MessageUserAgentServer(this.core, message); + this.delegate && this.delegate.onMessage ? this.delegate.onMessage(uas) : uas.accept(); + } + break; + case C.NOTIFY: + // https://tools.ietf.org/html/rfc3515#section-2.4.4 + { + const uas = new NotifyUserAgentServer(this, message); + this.delegate && this.delegate.onNotify ? this.delegate.onNotify(uas) : uas.accept(); + } + break; + case C.PRACK: + // https://tools.ietf.org/html/rfc3262#section-4 + { + const uas = new PrackUserAgentServer(this, message); + this.delegate && this.delegate.onPrack ? this.delegate.onPrack(uas) : uas.accept(); + } + break; + case C.REFER: + // https://tools.ietf.org/html/rfc3515#section-2.4.2 + { + const uas = new 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; + } + } + /** + * Guard against out of order reliable provisional responses and retransmissions. + * Returns false if the response should be discarded, otherwise true. + * @param message - Incoming response message within this dialog. + */ + reliableSequenceGuard(message) { + const 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 + const requireHeader = message.getHeader("require"); + const rseqHeader = message.getHeader("rseq"); + const 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 + this.rseq = this.rseq ? this.rseq + 1 : rseq; + } + } + return true; + } + /** + * If not in a stable signaling state, rollback to prior stable signaling state. + */ + signalingStateRollback() { + if (this._signalingState === SignalingState.HaveLocalOffer || + this.signalingState === SignalingState.HaveRemoteOffer) { + if (this._rollbackOffer && this._rollbackAnswer) { + this._signalingState = 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. + */ + signalingStateTransition(message) { + const body = 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 === SignalingState.Stable) { + this._rollbackOffer = this._offer; + this._rollbackAnswer = this._answer; + } + // We're in UAS role, receiving incoming request with session description + if (message instanceof IncomingRequestMessage) { + switch (this._signalingState) { + case SignalingState.Initial: + case SignalingState.Stable: + this._signalingState = SignalingState.HaveRemoteOffer; + this._offer = body; + this._answer = undefined; + break; + case SignalingState.HaveLocalOffer: + this._signalingState = SignalingState.Stable; + this._answer = body; + break; + case 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 SignalingState.Closed: + break; + default: + throw new Error("Unexpected signaling state."); + } + } + // We're in UAC role, receiving incoming response with session description + if (message instanceof IncomingResponseMessage) { + switch (this._signalingState) { + case SignalingState.Initial: + case SignalingState.Stable: + this._signalingState = SignalingState.HaveRemoteOffer; + this._offer = body; + this._answer = undefined; + break; + case SignalingState.HaveLocalOffer: + this._signalingState = SignalingState.Stable; + this._answer = body; + break; + case 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 SignalingState.Closed: + break; + default: + throw new Error("Unexpected signaling state."); + } + } + // We're in UAC role, sending outgoing request with session description + if (message instanceof OutgoingRequestMessage) { + switch (this._signalingState) { + case SignalingState.Initial: + case SignalingState.Stable: + this._signalingState = SignalingState.HaveLocalOffer; + this._offer = body; + this._answer = undefined; + break; + case 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 SignalingState.HaveRemoteOffer: + this._signalingState = SignalingState.Stable; + this._answer = body; + break; + case SignalingState.Closed: + break; + default: + throw new Error("Unexpected signaling state."); + } + } + // We're in UAS role, sending outgoing response with session description + if (isBody(message)) { + switch (this._signalingState) { + case SignalingState.Initial: + case SignalingState.Stable: + this._signalingState = SignalingState.HaveLocalOffer; + this._offer = body; + this._answer = undefined; + break; + case 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 SignalingState.HaveRemoteOffer: + this._signalingState = SignalingState.Stable; + this._answer = body; + break; + case SignalingState.Closed: + break; + default: + throw new Error("Unexpected signaling state."); + } + } + } + start2xxRetransmissionTimer() { + if (this.initialTransaction instanceof InviteServerTransaction) { + const transaction = 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 + let timeout = Timers.T1; + const retransmission = () => { + if (!this.ackWait) { + this.invite2xxTimer = undefined; + return; + } + this.logger.log("No ACK for 2xx response received, attempting retransmission"); + transaction.retransmitAcceptedResponse(); + timeout = Math.min(timeout * 2, Timers.T2); + this.invite2xxTimer = setTimeout(retransmission, timeout); + }; + this.invite2xxTimer = setTimeout(retransmission, timeout); + // 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 + const stateChanged = () => { + if (transaction.state === TransactionState.Terminated) { + transaction.removeStateChangeListener(stateChanged); + 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.addStateChangeListener(stateChanged); + } + } + // FIXME: Refactor + startReInvite2xxRetransmissionTimer() { + if (this.reinviteUserAgentServer && this.reinviteUserAgentServer.transaction instanceof InviteServerTransaction) { + const transaction = 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 + let timeout = Timers.T1; + const retransmission = () => { + if (!this.reinviteUserAgentServer) { + this.invite2xxTimer = undefined; + return; + } + this.logger.log("No ACK for 2xx response received, attempting retransmission"); + transaction.retransmitAcceptedResponse(); + timeout = Math.min(timeout * 2, Timers.T2); + this.invite2xxTimer = setTimeout(retransmission, timeout); + }; + this.invite2xxTimer = setTimeout(retransmission, timeout); + // 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 + const stateChanged = () => { + if (transaction.state === TransactionState.Terminated) { + transaction.removeStateChangeListener(stateChanged); + if (this.invite2xxTimer) { + clearTimeout(this.invite2xxTimer); + this.invite2xxTimer = undefined; + } + if (this.reinviteUserAgentServer) { + // FIXME: TODO: What to do here + } + } + }; + transaction.addStateChangeListener(stateChanged); + } + } +} diff --git a/lib/core/dialogs/subscription-dialog.d.ts b/lib/core/dialogs/subscription-dialog.d.ts new file mode 100644 index 000000000..62d30aebc --- /dev/null +++ b/lib/core/dialogs/subscription-dialog.d.ts @@ -0,0 +1,121 @@ +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 { + 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); + /** + * 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; + dispose(): void; + get autoRefresh(): boolean; + set autoRefresh(autoRefresh: boolean); + get subscriptionEvent(): string; + /** Number of seconds until subscription expires. */ + get subscriptionExpires(): number; + set subscriptionExpires(expires: number); + get subscriptionExpiresInitial(): number; + /** Number of seconds until subscription auto refresh. */ + get subscriptionRefresh(): number | undefined; + get 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 timerN; +} +//# 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 new file mode 100644 index 000000000..a16a5a935 --- /dev/null +++ b/lib/core/dialogs/subscription-dialog.d.ts.map @@ -0,0 +1 @@ +{"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;IAC7D,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,CAAqB;IAC9B,OAAO,CAAC,YAAY,CAAqB;gBAGvC,iBAAiB,EAAE,MAAM,EACzB,mBAAmB,EAAE,MAAM,EAC3B,iBAAiB,EAAE,iBAAiB,EACpC,IAAI,EAAE,aAAa,EACnB,KAAK,EAAE,WAAW,EAClB,QAAQ,CAAC,EAAE,oBAAoB;IAgBjC;;;;;;;OAOG;WACW,iCAAiC,CAC7C,+BAA+B,EAAE,sBAAsB,EACvD,4BAA4B,EAAE,sBAAsB,GACnD,WAAW;IA+FP,OAAO,IAAI,IAAI;IAUtB,IAAI,WAAW,IAAI,OAAO,CAEzB;IAED,IAAI,WAAW,CAAC,WAAW,EAAE,OAAO,EAGnC;IAED,IAAI,iBAAiB,IAAI,MAAM,CAE9B;IAED,oDAAoD;IACpD,IAAI,mBAAmB,IAAI,MAAM,CAIhC;IAED,IAAI,mBAAmB,CAAC,OAAO,EAAE,MAAM,EAYtC;IAED,IAAI,0BAA0B,IAAI,MAAM,CAEvC;IAED,yDAAyD;IACzD,IAAI,mBAAmB,IAAI,MAAM,GAAG,SAAS,CAO5C;IAED,IAAI,iBAAiB,IAAI,iBAAiB,CAEzC;IAED;;;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;IAqB3B;;;;;;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,MAAM;CAOf"} \ No newline at end of file diff --git a/lib/core/dialogs/subscription-dialog.js b/lib/core/dialogs/subscription-dialog.js new file mode 100644 index 000000000..d28e4feb3 --- /dev/null +++ b/lib/core/dialogs/subscription-dialog.js @@ -0,0 +1,471 @@ +import { C, NameAddrHeader } from "../messages"; +import { SubscriptionState } from "../subscription"; +import { Timers } from "../timers"; +import { AllowedMethods } from "../user-agent-core/allowed-methods"; +import { NotifyUserAgentServer } from "../user-agents/notify-user-agent-server"; +import { ReSubscribeUserAgentClient } from "../user-agents/re-subscribe-user-agent-client"; +import { Dialog } from "./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 + */ +export class SubscriptionDialog extends Dialog { + constructor(subscriptionEvent, subscriptionExpires, subscriptionState, core, state, delegate) { + super(core, state); + 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`); + } + /** + * 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, 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 + const 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 + const routeSet = incomingNotifyRequestMessage.getHeaders("record-route"); + const contact = incomingNotifyRequestMessage.parseHeader("contact"); + if (!contact) { + // TODO: Review to make sure this will never happen + throw new Error("Contact undefined."); + } + if (!(contact instanceof NameAddrHeader)) { + throw new Error("Contact not instance of NameAddrHeader."); + } + const 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 + const localSequenceNumber = outgoingSubscribeRequestMessage.cseq; + const remoteSequenceNumber = undefined; + const callId = outgoingSubscribeRequestMessage.callId; + const localTag = outgoingSubscribeRequestMessage.fromTag; + const 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."); + } + const localURI = outgoingSubscribeRequestMessage.from.uri; + const 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 + const early = false; + const dialogState = { + id: callId + localTag + remoteTag, + early, + callId, + localTag, + remoteTag, + localSequenceNumber, + remoteSequenceNumber, + localURI, + remoteURI, + remoteTarget, + routeSet, + secure + }; + return dialogState; + } + dispose() { + super.dispose(); + if (this.N) { + clearTimeout(this.N); + this.N = undefined; + } + this.refreshTimerClear(); + this.logger.log(`SUBSCRIBE dialog ${this.id} destroyed`); + } + get autoRefresh() { + return this._autoRefresh; + } + set autoRefresh(autoRefresh) { + this._autoRefresh = true; + this.refreshTimerSet(); + } + get subscriptionEvent() { + return this._subscriptionEvent; + } + /** Number of seconds until subscription expires. */ + get subscriptionExpires() { + const secondsSinceLastSet = Math.floor(Date.now() / 1000) - this._subscriptionExpiresLastSet; + const secondsUntilExpires = this._subscriptionExpires - secondsSinceLastSet; + return Math.max(secondsUntilExpires, 0); + } + set subscriptionExpires(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) { + const refresh = this.subscriptionRefresh; + if (refresh === undefined || refresh >= expires) { + this.refreshTimerSet(); + } + } + } + get subscriptionExpiresInitial() { + return this._subscriptionExpiresInitial; + } + /** Number of seconds until subscription auto refresh. */ + get subscriptionRefresh() { + if (this._subscriptionRefresh === undefined || this._subscriptionRefreshLastSet === undefined) { + return undefined; + } + const secondsSinceLastSet = Math.floor(Date.now() / 1000) - this._subscriptionRefreshLastSet; + const secondsUntilExpires = this._subscriptionRefresh - secondsSinceLastSet; + return Math.max(secondsUntilExpires, 0); + } + get subscriptionState() { + return this._subscriptionState; + } + /** + * Receive in dialog request message from transport. + * @param message - The incoming request message. + */ + receiveRequest(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.receiveRequest(message); + // Switch on method and then delegate. + switch (message.method) { + case 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 + */ + refresh() { + const allowHeader = "Allow: " + AllowedMethods.toString(); + const 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. + */ + subscribe(delegate, options = {}) { + if (this.subscriptionState !== SubscriptionState.Pending && this.subscriptionState !== 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`); + const uac = new ReSubscribeUserAgentClient(this, delegate, options); + // Abort any outstanding timer (as it would otherwise become guaranteed to terminate us). + if (this.N) { + clearTimeout(this.N); + this.N = undefined; + } + // 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(() => this.timerN(), 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 + */ + terminate() { + this.stateTransition(SubscriptionState.Terminated); + this.onTerminated(); + } + /** + * 4.1.2.3. Unsubscribing + * https://tools.ietf.org/html/rfc6665#section-4.1.2.3 + */ + unsubscribe() { + const allowHeader = "Allow: " + AllowedMethods.toString(); + const 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. + */ + onNotify(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 + const 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 + const subscriptionState = message.parseHeader("Subscription-State"); + if (!subscriptionState || !subscriptionState.state) { + this.core.replyStateless(message, { statusCode: 489 }); + return; + } + const state = subscriptionState.state; + const expires = subscriptionState.expires ? Math.max(subscriptionState.expires, 0) : undefined; + // Update our state and expiration. + switch (state) { + case "pending": + this.stateTransition(SubscriptionState.Pending, expires); + break; + case "active": + this.stateTransition(SubscriptionState.Active, expires); + break; + case "terminated": + this.stateTransition(SubscriptionState.Terminated, expires); + break; + default: + this.logger.warn("Unrecognized subscription state."); + break; + } + // Delegate remainder of NOTIFY handling. + const uas = new NotifyUserAgentServer(this, message); + if (this.delegate && this.delegate.onNotify) { + this.delegate.onNotify(uas); + } + else { + uas.accept(); + } + } + onRefresh(request) { + if (this.delegate && this.delegate.onRefresh) { + this.delegate.onRefresh(request); + } + } + onTerminated() { + if (this.delegate && this.delegate.onTerminated) { + this.delegate.onTerminated(); + } + } + refreshTimerClear() { + if (this.refreshTimer) { + clearTimeout(this.refreshTimer); + this.refreshTimer = undefined; + } + } + refreshTimerSet() { + this.refreshTimerClear(); + if (this.autoRefresh && this.subscriptionExpires > 0) { + const refresh = this.subscriptionExpires * 900; + this._subscriptionRefresh = Math.floor(refresh / 1000); + this._subscriptionRefreshLastSet = Math.floor(Date.now() / 1000); + this.refreshTimer = setTimeout(() => { + this.refreshTimer = undefined; + this._subscriptionRefresh = undefined; + this._subscriptionRefreshLastSet = undefined; + this.onRefresh(this.refresh()); + }, refresh); + } + } + stateTransition(newState, newExpires) { + // Assert valid state transitions. + const invalidStateTransition = () => { + this.logger.warn(`Invalid subscription state transition from ${this.subscriptionState} to ${newState}`); + }; + switch (newState) { + case SubscriptionState.Initial: + invalidStateTransition(); + return; + case SubscriptionState.NotifyWait: + invalidStateTransition(); + return; + case SubscriptionState.Pending: + if (this.subscriptionState !== SubscriptionState.NotifyWait && + this.subscriptionState !== SubscriptionState.Pending) { + invalidStateTransition(); + return; + } + break; + case SubscriptionState.Active: + if (this.subscriptionState !== SubscriptionState.NotifyWait && + this.subscriptionState !== SubscriptionState.Pending && + this.subscriptionState !== SubscriptionState.Active) { + invalidStateTransition(); + return; + } + break; + case SubscriptionState.Terminated: + if (this.subscriptionState !== SubscriptionState.NotifyWait && + this.subscriptionState !== SubscriptionState.Pending && + this.subscriptionState !== 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 === 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 === 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 === 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 + */ + timerN() { + this.logger.warn(`Timer N expired for SUBSCRIBE dialog. Timed out waiting for NOTIFY.`); + if (this.subscriptionState !== SubscriptionState.Terminated) { + this.stateTransition(SubscriptionState.Terminated); + this.onTerminated(); + } + } +} diff --git a/lib/core/exceptions/exception.d.ts b/lib/core/exceptions/exception.d.ts new file mode 100644 index 000000000..476b4fad0 --- /dev/null +++ b/lib/core/exceptions/exception.d.ts @@ -0,0 +1,9 @@ +/** + * 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 new file mode 100644 index 000000000..d9b0b27c2 --- /dev/null +++ b/lib/core/exceptions/exception.d.ts.map @@ -0,0 +1 @@ +{"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 new file mode 100644 index 000000000..f1fb9b899 --- /dev/null +++ b/lib/core/exceptions/exception.js @@ -0,0 +1,11 @@ +/** + * 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 class Exception extends Error { + constructor(message) { + super(message); // 'Error' breaks prototype chain here + Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain + } +} diff --git a/lib/core/exceptions/index.d.ts b/lib/core/exceptions/index.d.ts new file mode 100644 index 000000000..fad2dd3c9 --- /dev/null +++ b/lib/core/exceptions/index.d.ts @@ -0,0 +1,4 @@ +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 new file mode 100644 index 000000000..cb6188c01 --- /dev/null +++ b/lib/core/exceptions/index.d.ts.map @@ -0,0 +1 @@ +{"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 new file mode 100644 index 000000000..a7b5eb621 --- /dev/null +++ b/lib/core/exceptions/index.js @@ -0,0 +1,3 @@ +export * from "./exception"; +export * from "./transaction-state-error"; +export * from "./transport-error"; diff --git a/lib/core/exceptions/transaction-state-error.d.ts b/lib/core/exceptions/transaction-state-error.d.ts new file mode 100644 index 000000000..efac75de6 --- /dev/null +++ b/lib/core/exceptions/transaction-state-error.d.ts @@ -0,0 +1,9 @@ +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 new file mode 100644 index 000000000..a9ee2adab --- /dev/null +++ b/lib/core/exceptions/transaction-state-error.d.ts.map @@ -0,0 +1 @@ +{"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 new file mode 100644 index 000000000..60c5493f0 --- /dev/null +++ b/lib/core/exceptions/transaction-state-error.js @@ -0,0 +1,10 @@ +import { Exception } from "./exception"; +/** + * Indicates that the operation could not be completed given the current transaction state. + * @public + */ +export class TransactionStateError extends Exception { + constructor(message) { + super(message ? message : "Transaction state error."); + } +} diff --git a/lib/core/exceptions/transport-error.d.ts b/lib/core/exceptions/transport-error.d.ts new file mode 100644 index 000000000..29db45f93 --- /dev/null +++ b/lib/core/exceptions/transport-error.d.ts @@ -0,0 +1,9 @@ +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 new file mode 100644 index 000000000..7f7e3f494 --- /dev/null +++ b/lib/core/exceptions/transport-error.d.ts.map @@ -0,0 +1 @@ +{"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 new file mode 100644 index 000000000..e5fb84d6c --- /dev/null +++ b/lib/core/exceptions/transport-error.js @@ -0,0 +1,10 @@ +import { Exception } from "./exception"; +/** + * Transport error. + * @public + */ +export class TransportError extends Exception { + constructor(message) { + super(message ? message : "Unspecified transport error."); + } +} diff --git a/lib/core/index.d.ts b/lib/core/index.d.ts new file mode 100644 index 000000000..aeaad6230 --- /dev/null +++ b/lib/core/index.d.ts @@ -0,0 +1,16 @@ +/** + * 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 new file mode 100644 index 000000000..d5d7687f4 --- /dev/null +++ b/lib/core/index.d.ts.map @@ -0,0 +1 @@ +{"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 new file mode 100644 index 000000000..7df7074f8 --- /dev/null +++ b/lib/core/index.js @@ -0,0 +1,17 @@ +/** + * A core library implementing low level SIP protocol elements. + * @packageDocumentation + */ +// Directories +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"; +// Files +export * from "./timers"; +export * from "./transport"; diff --git a/lib/core/log/index.d.ts b/lib/core/log/index.d.ts new file mode 100644 index 000000000..011860395 --- /dev/null +++ b/lib/core/log/index.d.ts @@ -0,0 +1,4 @@ +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 new file mode 100644 index 000000000..b9ae7b73a --- /dev/null +++ b/lib/core/log/index.d.ts.map @@ -0,0 +1 @@ +{"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 new file mode 100644 index 000000000..2d59354ff --- /dev/null +++ b/lib/core/log/index.js @@ -0,0 +1,3 @@ +export * from "./levels"; +export * from "./logger-factory"; +export * from "./logger"; diff --git a/lib/core/log/levels.d.ts b/lib/core/log/levels.d.ts new file mode 100644 index 000000000..49a9b7296 --- /dev/null +++ b/lib/core/log/levels.d.ts @@ -0,0 +1,11 @@ +/** + * 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 new file mode 100644 index 000000000..494d285b6 --- /dev/null +++ b/lib/core/log/levels.d.ts.map @@ -0,0 +1 @@ +{"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 new file mode 100644 index 000000000..ec90080e5 --- /dev/null +++ b/lib/core/log/levels.js @@ -0,0 +1,11 @@ +/** + * Log levels. + * @public + */ +export 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 || (Levels = {})); diff --git a/lib/core/log/logger-factory.d.ts b/lib/core/log/logger-factory.d.ts new file mode 100644 index 000000000..667eb99bf --- /dev/null +++ b/lib/core/log/logger-factory.d.ts @@ -0,0 +1,22 @@ +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(); + get level(): Levels; + set level(newLevel: Levels); + get connector(): ((level: string, category: string, label: string | undefined, content: any) => void) | undefined; + set connector(value: ((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 new file mode 100644 index 000000000..48072ee40 --- /dev/null +++ b/lib/core/log/logger-factory.d.ts.map @@ -0,0 +1 @@ +{"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,UAAQ;IAE7B,OAAO,CAAC,MAAM,CAAsB;IAEpC,OAAO,CAAC,UAAU,CAAmG;IAGrH,OAAO,CAAC,OAAO,CAAW;IAC1B,OAAO,CAAC,MAAM,CAAS;;IAMvB,IAAI,KAAK,IAAI,MAAM,CAElB;IACD,IAAI,KAAK,CAAC,QAAQ,EAAE,MAAM,EAWzB;IAGD,IAAI,SAAS,IAAI,CAAC,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,SAAS,EAAE,OAAO,EAAE,GAAG,KAAK,IAAI,CAAC,GAAG,SAAS,CAEhH;IACD,IAAI,SAAS,CACX,KAAK,EACD,CAAC,CACC,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,GAAG,SAAS,EAEzB,OAAO,EAAE,GAAG,KACT,IAAI,CAAC,GACV,SAAS,EASd;IAEM,SAAS,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM;IAanD,UAAU,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,SAAS,EAAE,OAAO,EAAE,GAAG,GAAG,IAAI;IAatG,OAAO,CAAC,KAAK;CA8Bd"} \ No newline at end of file diff --git a/lib/core/log/logger-factory.js b/lib/core/log/logger-factory.js new file mode 100644 index 000000000..81d5034a3 --- /dev/null +++ b/lib/core/log/logger-factory.js @@ -0,0 +1,103 @@ +import { Levels } from "./levels"; +import { Logger } from "./logger"; +/** + * Logger. + * @public + */ +export class LoggerFactory { + constructor() { + this.builtinEnabled = true; + this._level = Levels.log; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this.loggers = {}; + this.logger = this.getLogger("sip:loggerfactory"); + } + get level() { + return this._level; + } + set level(newLevel) { + if (newLevel >= 0 && newLevel <= 3) { + this._level = newLevel; + } + else if (newLevel > 3) { + this._level = 3; + // eslint-disable-next-line no-prototype-builtins + } + else if (Levels.hasOwnProperty(newLevel)) { + this._level = newLevel; + } + else { + this.logger.error("invalid 'level' parameter value: " + JSON.stringify(newLevel)); + } + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + get connector() { + return this._connector; + } + set connector(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)); + } + } + getLogger(category, label) { + if (label && this.level === 3) { + return new Logger(this, category, label); + } + else if (this.loggers[category]) { + return this.loggers[category]; + } + else { + const logger = new Logger(this, category); + this.loggers[category] = logger; + return logger; + } + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + genericLog(levelToLog, category, label, content) { + if (this.level >= levelToLog) { + if (this.builtinEnabled) { + this.print(levelToLog, category, label, content); + } + } + if (this.connector) { + this.connector(Levels[levelToLog], category, label, content); + } + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + print(levelToLog, category, label, content) { + if (typeof content === "string") { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const prefix = [new Date(), category]; + if (label) { + prefix.push(label); + } + content = prefix.concat(content).join(" | "); + } + switch (levelToLog) { + case Levels.error: + // eslint-disable-next-line no-console + console.error(content); + break; + case Levels.warn: + // eslint-disable-next-line no-console + console.warn(content); + break; + case Levels.log: + // eslint-disable-next-line no-console + console.log(content); + break; + case Levels.debug: + // eslint-disable-next-line no-console + console.debug(content); + break; + default: + break; + } + } +} diff --git a/lib/core/log/logger.d.ts b/lib/core/log/logger.d.ts new file mode 100644 index 000000000..f203808af --- /dev/null +++ b/lib/core/log/logger.d.ts @@ -0,0 +1,20 @@ +import { Levels } from "./levels"; +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; + get level(): Levels; + set level(newLevel: Levels); +} +//# 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 new file mode 100644 index 000000000..239b3a111 --- /dev/null +++ b/lib/core/log/logger.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"logger.d.ts","sourceRoot":"","sources":["../../../src/core/log/logger.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAClC,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;IAG5B,IAAI,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAG3B,GAAG,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAG1B,KAAK,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAInC,OAAO,CAAC,UAAU;IAIlB,IAAI,KAAK,IAAI,MAAM,CAElB;IACD,IAAI,KAAK,CAAC,QAAQ,EAAE,MAAM,EAEzB;CACF"} \ No newline at end of file diff --git a/lib/core/log/logger.js b/lib/core/log/logger.js new file mode 100644 index 000000000..c0cd9dc7d --- /dev/null +++ b/lib/core/log/logger.js @@ -0,0 +1,33 @@ +import { Levels } from "./levels"; +/** + * Logger. + * @public + */ +export class Logger { + constructor(logger, category, label) { + this.logger = logger; + this.category = category; + this.label = label; + } + error(content) { + this.genericLog(Levels.error, content); + } + warn(content) { + this.genericLog(Levels.warn, content); + } + log(content) { + this.genericLog(Levels.log, content); + } + debug(content) { + this.genericLog(Levels.debug, content); + } + genericLog(level, content) { + this.logger.genericLog(level, this.category, this.label, content); + } + get level() { + return this.logger.level; + } + set level(newLevel) { + this.logger.level = newLevel; + } +} diff --git a/lib/core/messages/body.d.ts b/lib/core/messages/body.d.ts new file mode 100644 index 000000000..3bf8c6c33 --- /dev/null +++ b/lib/core/messages/body.d.ts @@ -0,0 +1,65 @@ +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; +/** + * User-Defined Type Guard for Body. + * @param body - Body to check. + * @internal + */ +export declare function isBody(body: any): body is 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; +//# 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 new file mode 100644 index 000000000..146bf548e --- /dev/null +++ b/lib/core/messages/body.d.ts.map @@ -0,0 +1 @@ +{"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;AAcpE;;;;;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;;;;GAIG;AAEH,wBAAgB,MAAM,CAAC,IAAI,EAAE,GAAG,GAAG,IAAI,IAAI,IAAI,CAO9C;AAED;;;;;GAKG;AACH,wBAAgB,OAAO,CACrB,OAAO,EAAE,sBAAsB,GAAG,uBAAuB,GAAG,sBAAsB,GAAG,IAAI,GACxF,IAAI,GAAG,SAAS,CA4ElB"} \ No newline at end of file diff --git a/lib/core/messages/body.js b/lib/core/messages/body.js new file mode 100644 index 000000000..ae97e762c --- /dev/null +++ b/lib/core/messages/body.js @@ -0,0 +1,118 @@ +import { IncomingRequestMessage } from "./incoming-request-message"; +import { IncomingResponseMessage } from "./incoming-response-message"; +import { OutgoingRequestMessage } from "./outgoing-request-message"; +// 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"; + } +} +/** + * Create a Body given a legacy body type. + * @param bodyLegacy - Body Object + * @internal + */ +export function fromBodyLegacy(bodyLegacy) { + const content = typeof bodyLegacy === "string" ? bodyLegacy : bodyLegacy.body; + const contentType = typeof bodyLegacy === "string" ? "application/sdp" : bodyLegacy.contentType; + const contentDisposition = contentTypeToContentDisposition(contentType); + const body = { contentDisposition, contentType, content }; + return body; +} +/** + * User-Defined Type Guard for Body. + * @param body - Body to check. + * @internal + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export function isBody(body) { + return body && + typeof body.content === "string" && + typeof body.contentType === "string" && + body.contentDisposition === undefined + ? true + : typeof body.contentDisposition === "string"; +} +/** + * Given a message, get a normalized body. + * The content disposition is inferred if not set. + * @param message - The message. + * @internal + */ +export function getBody(message) { + let contentDisposition; + let contentType; + let content; + // We're in UAS role, receiving incoming request + if (message instanceof IncomingRequestMessage) { + if (message.body) { + // FIXME: Parsing needs typing + const 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 IncomingResponseMessage) { + if (message.body) { + // FIXME: Parsing needs typing + const 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 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, + contentType, + content + }; +} diff --git a/lib/core/messages/digest-authentication.d.ts b/lib/core/messages/digest-authentication.d.ts new file mode 100644 index 000000000..39a6755d7 --- /dev/null +++ b/lib/core/messages/digest-authentication.d.ts @@ -0,0 +1,52 @@ +import { LoggerFactory } from "../log"; +import { OutgoingRequestMessage } from "./outgoing-request-message"; +/** + * Digest Authentication. + * @internal + */ +export declare class DigestAuthentication { + stale: boolean | undefined; + private logger; + private ha1; + 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, ha1: string | undefined, 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 new file mode 100644 index 000000000..02e471095 --- /dev/null +++ b/lib/core/messages/digest-authentication.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"digest-authentication.d.ts","sourceRoot":"","sources":["../../../src/core/messages/digest-authentication.ts"],"names":[],"mappings":"AAGA,OAAO,EAAU,aAAa,EAAE,MAAM,QAAQ,CAAC;AAC/C,OAAO,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AAOpE;;;GAGG;AACH,qBAAa,oBAAoB;IACxB,KAAK,EAAE,OAAO,GAAG,SAAS,CAAC;IAElC,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,GAAG,CAAqB;IAChC,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,CAAqB;IACrC,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;gBAED,aAAa,EAAE,aAAa,EAC5B,GAAG,EAAE,MAAM,GAAG,SAAS,EACvB,QAAQ,EAAE,MAAM,GAAG,SAAS,EAC5B,QAAQ,EAAE,MAAM,GAAG,SAAS;IAU9B;;;;;;OAMG;IAEI,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;CA0B1B"} \ No newline at end of file diff --git a/lib/core/messages/digest-authentication.js b/lib/core/messages/digest-authentication.js new file mode 100644 index 000000000..b40b36cee --- /dev/null +++ b/lib/core/messages/digest-authentication.js @@ -0,0 +1,149 @@ +import { Md5 } from "./md5"; +import { createRandomToken } from "./utils"; +function MD5(s) { + return Md5.hashStr(s); +} +/** + * Digest Authentication. + * @internal + */ +export class DigestAuthentication { + /** + * Constructor. + * @param loggerFactory - LoggerFactory. + * @param username - Username. + * @param password - Password. + */ + constructor(loggerFactory, ha1, username, password) { + this.logger = loggerFactory.getLogger("sipjs.digestauthentication"); + this.username = username; + this.password = password; + this.ha1 = ha1; + 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. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + authenticate(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 = 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. + */ + toString() { + const 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. + */ + updateNcHex() { + const hex = Number(this.nc).toString(16); + this.ncHex = "00000000".substr(0, 8 - hex.length) + hex; + } + /** + * Generate Digest 'response' value. + */ + calculateResponse(body) { + let ha1, ha2; + // HA1 = MD5(A1) = MD5(username:realm:password) + ha1 = this.ha1; + if (ha1 === "" || ha1 === undefined) { + ha1 = MD5(this.username + ":" + this.realm + ":" + this.password); + } + if (this.qop === "auth") { + // HA2 = MD5(A2) = MD5(method:digestURI) + ha2 = MD5(this.method + ":" + this.uri); + // response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2)` + this.response = MD5(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(this.method + ":" + this.uri + ":" + MD5(body ? body : "")); + // response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2) + this.response = MD5(ha1 + ":" + this.nonce + ":" + this.ncHex + ":" + this.cnonce + ":auth-int:" + ha2); + } + else if (this.qop === undefined) { + // HA2 = MD5(A2) = MD5(method:digestURI) + ha2 = MD5(this.method + ":" + this.uri); + // response = MD5(HA1:nonce:HA2) + this.response = MD5(ha1 + ":" + this.nonce + ":" + ha2); + } + } +} diff --git a/lib/core/messages/incoming-message.d.ts b/lib/core/messages/incoming-message.d.ts new file mode 100644 index 000000000..196d2f2f3 --- /dev/null +++ b/lib/core/messages/incoming-message.d.ts @@ -0,0 +1,80 @@ +import { NameAddrHeader } from "../../grammar"; +/** + * 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 new file mode 100644 index 000000000..7dbd82dd7 --- /dev/null +++ b/lib/core/messages/incoming-message.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"incoming-message.d.ts","sourceRoot":"","sources":["../../../src/core/messages/incoming-message.ts"],"names":[],"mappings":"AAAA,OAAO,EAAW,cAAc,EAAE,MAAM,eAAe,CAAC;AAGxD;;;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;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;IAErC,OAAO,EAAE;QAAE,CAAC,IAAI,EAAE,MAAM,GAAG,KAAK,CAAC;YAAE,MAAM,CAAC,EAAE,GAAG,CAAC;YAAC,GAAG,EAAE,MAAM,CAAA;SAAE,CAAC,CAAA;KAAE,CAAM;IACvE,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;IAc9C;;;;OAIG;IACI,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO;IAIvC;;;;;;OAMG;IAEI,WAAW,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,SAAI,GAAG,GAAG,GAAG,SAAS;IA+B1D;;;;;;;;;OASG;IAEI,CAAC,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,SAAI,GAAG,GAAG,GAAG,SAAS;IAIhD;;;;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 new file mode 100644 index 000000000..eb9023b3c --- /dev/null +++ b/lib/core/messages/incoming-message.js @@ -0,0 +1,129 @@ +import { Grammar } from "../../grammar"; +import { headerize } from "./utils"; +/** + * Incoming message. + * @public + */ +export class IncomingMessage { + constructor() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + 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 + */ + addHeader(name, value) { + const header = { raw: value }; + name = 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. + */ + getHeader(name) { + const header = this.headers[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. + */ + getHeaders(name) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const header = this.headers[headerize(name)]; + const result = []; + if (!header) { + return []; + } + for (const headerPart of header) { + 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 + */ + hasHeader(name) { + return !!this.headers[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. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + parseHeader(name, idx = 0) { + name = 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; + } + const header = this.headers[name][idx]; + const value = header.raw; + if (header.parsed) { + return header.parsed; + } + // substitute '-' by '_' for grammar rule matching. + const parsed = 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 + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + s(name, 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 + */ + setHeader(name, value) { + this.headers[headerize(name)] = [{ raw: value }]; + } + toString() { + return this.data; + } +} diff --git a/lib/core/messages/incoming-request-message.d.ts b/lib/core/messages/incoming-request-message.d.ts new file mode 100644 index 000000000..eb50bbc8e --- /dev/null +++ b/lib/core/messages/incoming-request-message.d.ts @@ -0,0 +1,11 @@ +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 new file mode 100644 index 000000000..23beeffa3 --- /dev/null +++ b/lib/core/messages/incoming-request-message.d.ts.map @@ -0,0 +1 @@ +{"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 new file mode 100644 index 000000000..6e5abb2ea --- /dev/null +++ b/lib/core/messages/incoming-request-message.js @@ -0,0 +1,10 @@ +import { IncomingMessage } from "./incoming-message"; +/** + * Incoming request message. + * @public + */ +export class IncomingRequestMessage extends IncomingMessage { + constructor() { + super(); + } +} diff --git a/lib/core/messages/incoming-request.d.ts b/lib/core/messages/incoming-request.d.ts new file mode 100644 index 000000000..56da6209b --- /dev/null +++ b/lib/core/messages/incoming-request.d.ts @@ -0,0 +1,68 @@ +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 new file mode 100644 index 000000000..5cde494a7 --- /dev/null +++ b/lib/core/messages/incoming-request.d.ts.map @@ -0,0 +1 @@ +{"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 new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/core/messages/incoming-request.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/core/messages/incoming-response-message.d.ts b/lib/core/messages/incoming-response-message.d.ts new file mode 100644 index 000000000..a04152af4 --- /dev/null +++ b/lib/core/messages/incoming-response-message.d.ts @@ -0,0 +1,11 @@ +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 new file mode 100644 index 000000000..7c9d9853b --- /dev/null +++ b/lib/core/messages/incoming-response-message.d.ts.map @@ -0,0 +1 @@ +{"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 new file mode 100644 index 000000000..65bada916 --- /dev/null +++ b/lib/core/messages/incoming-response-message.js @@ -0,0 +1,10 @@ +import { IncomingMessage } from "./incoming-message"; +/** + * Incoming response message. + * @public + */ +export class IncomingResponseMessage extends IncomingMessage { + constructor() { + super(); + } +} diff --git a/lib/core/messages/incoming-response.d.ts b/lib/core/messages/incoming-response.d.ts new file mode 100644 index 000000000..f2a2daefa --- /dev/null +++ b/lib/core/messages/incoming-response.d.ts @@ -0,0 +1,13 @@ +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 new file mode 100644 index 000000000..96bd96b83 --- /dev/null +++ b/lib/core/messages/incoming-response.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"incoming-response.d.ts","sourceRoot":"","sources":["../../../src/core/messages/incoming-response.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,6BAA6B,CAAC;AAEtE;;;;;;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 new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/core/messages/incoming-response.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/core/messages/index.d.ts b/lib/core/messages/index.d.ts new file mode 100644 index 000000000..03d0aa8da --- /dev/null +++ b/lib/core/messages/index.d.ts @@ -0,0 +1,14 @@ +export * from "../../grammar"; +export * from "./methods"; +export * from "./body"; +export * from "./digest-authentication"; +export * from "./incoming-message"; +export * from "./incoming-request-message"; +export * from "./incoming-request"; +export * from "./incoming-response-message"; +export * from "./incoming-response"; +export * from "./outgoing-request-message"; +export * from "./outgoing-request"; +export * from "./outgoing-response"; +export * from "./parser"; +//# 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 new file mode 100644 index 000000000..00c0a820a --- /dev/null +++ b/lib/core/messages/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/messages/index.ts"],"names":[],"mappings":"AACA,cAAc,eAAe,CAAC;AAG9B,cAAc,WAAW,CAAC;AAG1B,cAAc,QAAQ,CAAC;AACvB,cAAc,yBAAyB,CAAC;AACxC,cAAc,oBAAoB,CAAC;AACnC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,oBAAoB,CAAC;AACnC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,qBAAqB,CAAC;AACpC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,oBAAoB,CAAC;AACnC,cAAc,qBAAqB,CAAC;AACpC,cAAc,UAAU,CAAC"} \ No newline at end of file diff --git a/lib/core/messages/index.js b/lib/core/messages/index.js new file mode 100644 index 000000000..ccf8af4bc --- /dev/null +++ b/lib/core/messages/index.js @@ -0,0 +1,16 @@ +// Grammar +export * from "../../grammar"; +// Directories +export * from "./methods"; +// Files +export * from "./body"; +export * from "./digest-authentication"; +export * from "./incoming-message"; +export * from "./incoming-request-message"; +export * from "./incoming-request"; +export * from "./incoming-response-message"; +export * from "./incoming-response"; +export * from "./outgoing-request-message"; +export * from "./outgoing-request"; +export * from "./outgoing-response"; +export * from "./parser"; diff --git a/lib/core/messages/md5.d.ts b/lib/core/messages/md5.d.ts new file mode 100644 index 000000000..73d63f408 --- /dev/null +++ b/lib/core/messages/md5.d.ts @@ -0,0 +1,33 @@ +export declare class Md5 { + static hashStr(str: string, raw?: false): string; + static hashStr(str: string, raw?: true): Int32Array; + static hashAsciiStr(str: string, raw?: false): string; + static hashAsciiStr(str: string, raw?: true): Int32Array; + private static stateIdentity; + private static buffer32Identity; + private static hexChars; + private static hexOut; + private static onePassHasher; + private static _hex; + private static _md5cycle; + private _dataLength; + private _bufferLength; + private _state; + private _buffer; + private _buffer8; + private _buffer32; + constructor(); + start(): this; + appendStr(str: string): this; + appendAsciiStr(str: string): this; + appendByteArray(input: Uint8Array): this; + getState(): { + buffer: string; + buflen: number; + length: number; + state: number[]; + }; + setState(state: any): void; + end(raw?: boolean): string | Int32Array | undefined; +} +//# sourceMappingURL=md5.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/md5.d.ts.map b/lib/core/messages/md5.d.ts.map new file mode 100644 index 000000000..0a4c6d95c --- /dev/null +++ b/lib/core/messages/md5.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"md5.d.ts","sourceRoot":"","sources":["../../../src/core/messages/md5.ts"],"names":[],"mappings":"AA2DA,qBAAa,GAAG;WAGA,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,KAAK,GAAG,MAAM;WACzC,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,IAAI,GAAG,UAAU;WAQ5C,YAAY,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,KAAK,GAAG,MAAM;WAC9C,YAAY,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,IAAI,GAAG,UAAU;IAQ/D,OAAO,CAAC,MAAM,CAAC,aAAa,CAAoE;IAChG,OAAO,CAAC,MAAM,CAAC,gBAAgB,CAAoE;IACnG,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAsB;IAC7C,OAAO,CAAC,MAAM,CAAC,MAAM,CAAgB;IAGrC,OAAO,CAAC,MAAM,CAAC,aAAa,CAAa;IAEzC,OAAO,CAAC,MAAM,CAAC,IAAI;IAqBnB,OAAO,CAAC,MAAM,CAAC,SAAS;IAgJxB,OAAO,CAAC,WAAW,CAAa;IAChC,OAAO,CAAC,aAAa,CAAa;IAElC,OAAO,CAAC,MAAM,CAAiC;IAC/C,OAAO,CAAC,OAAO,CAAoC;IACnD,OAAO,CAAC,QAAQ,CAAa;IAC7B,OAAO,CAAC,SAAS,CAAc;;IAQxB,KAAK;IAUL,SAAS,CAAC,GAAG,EAAE,MAAM;IAuCrB,cAAc,CAAC,GAAG,EAAE,MAAM;IAuB1B,eAAe,CAAC,KAAK,EAAE,UAAU;IAuBjC,QAAQ;;;;;;IAYR,QAAQ,CAAC,KAAK,EAAE,GAAG;IAkBnB,GAAG,CAAC,GAAG,GAAE,OAAe;CAwChC"} \ No newline at end of file diff --git a/lib/core/messages/md5.js b/lib/core/messages/md5.js new file mode 100644 index 000000000..0f2bafe98 --- /dev/null +++ b/lib/core/messages/md5.js @@ -0,0 +1,399 @@ +/* eslint-disable */ +// +// Scoped from: https://github.com/cotag/ts-md5 +// +/* + +TypeScript Md5 +============== + +Based on work by +* Joseph Myers: http://www.myersdaily.org/joseph/javascript/md5-text.html +* André Cruz: https://github.com/satazor/SparkMD5 +* Raymond Hill: https://github.com/gorhill/yamd5.js + +Effectively a TypeScrypt re-write of Raymond Hill JS Library + +The MIT License (MIT) + +Copyright (C) 2014 Raymond Hill + +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. + + + + DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE + Version 2, December 2004 + + Copyright (C) 2015 André Cruz + + Everyone is permitted to copy and distribute verbatim or modified + copies of this license document, and changing it is allowed as long + as the name is changed. + + DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. You just DO WHAT THE FUCK YOU WANT TO. + + +*/ +export class Md5 { + constructor() { + this._dataLength = 0; + this._bufferLength = 0; + this._state = new Int32Array(4); + this._buffer = new ArrayBuffer(68); + this._buffer8 = new Uint8Array(this._buffer, 0, 68); + this._buffer32 = new Uint32Array(this._buffer, 0, 17); + this.start(); + } + static hashStr(str, raw = false) { + return this.onePassHasher + .start() + .appendStr(str) + .end(raw); + } + static hashAsciiStr(str, raw = false) { + return this.onePassHasher + .start() + .appendAsciiStr(str) + .end(raw); + } + static _hex(x) { + const hc = Md5.hexChars; + const ho = Md5.hexOut; + let n; + let offset; + let j; + let i; + for (i = 0; i < 4; i += 1) { + offset = i * 8; + n = x[i]; + for (j = 0; j < 8; j += 2) { + ho[offset + 1 + j] = hc.charAt(n & 0x0F); + n >>>= 4; + ho[offset + 0 + j] = hc.charAt(n & 0x0F); + n >>>= 4; + } + } + return ho.join(''); + } + static _md5cycle(x, k) { + let a = x[0]; + let b = x[1]; + let c = x[2]; + let d = x[3]; + // ff() + a += (b & c | ~b & d) + k[0] - 680876936 | 0; + a = (a << 7 | a >>> 25) + b | 0; + d += (a & b | ~a & c) + k[1] - 389564586 | 0; + d = (d << 12 | d >>> 20) + a | 0; + c += (d & a | ~d & b) + k[2] + 606105819 | 0; + c = (c << 17 | c >>> 15) + d | 0; + b += (c & d | ~c & a) + k[3] - 1044525330 | 0; + b = (b << 22 | b >>> 10) + c | 0; + a += (b & c | ~b & d) + k[4] - 176418897 | 0; + a = (a << 7 | a >>> 25) + b | 0; + d += (a & b | ~a & c) + k[5] + 1200080426 | 0; + d = (d << 12 | d >>> 20) + a | 0; + c += (d & a | ~d & b) + k[6] - 1473231341 | 0; + c = (c << 17 | c >>> 15) + d | 0; + b += (c & d | ~c & a) + k[7] - 45705983 | 0; + b = (b << 22 | b >>> 10) + c | 0; + a += (b & c | ~b & d) + k[8] + 1770035416 | 0; + a = (a << 7 | a >>> 25) + b | 0; + d += (a & b | ~a & c) + k[9] - 1958414417 | 0; + d = (d << 12 | d >>> 20) + a | 0; + c += (d & a | ~d & b) + k[10] - 42063 | 0; + c = (c << 17 | c >>> 15) + d | 0; + b += (c & d | ~c & a) + k[11] - 1990404162 | 0; + b = (b << 22 | b >>> 10) + c | 0; + a += (b & c | ~b & d) + k[12] + 1804603682 | 0; + a = (a << 7 | a >>> 25) + b | 0; + d += (a & b | ~a & c) + k[13] - 40341101 | 0; + d = (d << 12 | d >>> 20) + a | 0; + c += (d & a | ~d & b) + k[14] - 1502002290 | 0; + c = (c << 17 | c >>> 15) + d | 0; + b += (c & d | ~c & a) + k[15] + 1236535329 | 0; + b = (b << 22 | b >>> 10) + c | 0; + // gg() + a += (b & d | c & ~d) + k[1] - 165796510 | 0; + a = (a << 5 | a >>> 27) + b | 0; + d += (a & c | b & ~c) + k[6] - 1069501632 | 0; + d = (d << 9 | d >>> 23) + a | 0; + c += (d & b | a & ~b) + k[11] + 643717713 | 0; + c = (c << 14 | c >>> 18) + d | 0; + b += (c & a | d & ~a) + k[0] - 373897302 | 0; + b = (b << 20 | b >>> 12) + c | 0; + a += (b & d | c & ~d) + k[5] - 701558691 | 0; + a = (a << 5 | a >>> 27) + b | 0; + d += (a & c | b & ~c) + k[10] + 38016083 | 0; + d = (d << 9 | d >>> 23) + a | 0; + c += (d & b | a & ~b) + k[15] - 660478335 | 0; + c = (c << 14 | c >>> 18) + d | 0; + b += (c & a | d & ~a) + k[4] - 405537848 | 0; + b = (b << 20 | b >>> 12) + c | 0; + a += (b & d | c & ~d) + k[9] + 568446438 | 0; + a = (a << 5 | a >>> 27) + b | 0; + d += (a & c | b & ~c) + k[14] - 1019803690 | 0; + d = (d << 9 | d >>> 23) + a | 0; + c += (d & b | a & ~b) + k[3] - 187363961 | 0; + c = (c << 14 | c >>> 18) + d | 0; + b += (c & a | d & ~a) + k[8] + 1163531501 | 0; + b = (b << 20 | b >>> 12) + c | 0; + a += (b & d | c & ~d) + k[13] - 1444681467 | 0; + a = (a << 5 | a >>> 27) + b | 0; + d += (a & c | b & ~c) + k[2] - 51403784 | 0; + d = (d << 9 | d >>> 23) + a | 0; + c += (d & b | a & ~b) + k[7] + 1735328473 | 0; + c = (c << 14 | c >>> 18) + d | 0; + b += (c & a | d & ~a) + k[12] - 1926607734 | 0; + b = (b << 20 | b >>> 12) + c | 0; + // hh() + a += (b ^ c ^ d) + k[5] - 378558 | 0; + a = (a << 4 | a >>> 28) + b | 0; + d += (a ^ b ^ c) + k[8] - 2022574463 | 0; + d = (d << 11 | d >>> 21) + a | 0; + c += (d ^ a ^ b) + k[11] + 1839030562 | 0; + c = (c << 16 | c >>> 16) + d | 0; + b += (c ^ d ^ a) + k[14] - 35309556 | 0; + b = (b << 23 | b >>> 9) + c | 0; + a += (b ^ c ^ d) + k[1] - 1530992060 | 0; + a = (a << 4 | a >>> 28) + b | 0; + d += (a ^ b ^ c) + k[4] + 1272893353 | 0; + d = (d << 11 | d >>> 21) + a | 0; + c += (d ^ a ^ b) + k[7] - 155497632 | 0; + c = (c << 16 | c >>> 16) + d | 0; + b += (c ^ d ^ a) + k[10] - 1094730640 | 0; + b = (b << 23 | b >>> 9) + c | 0; + a += (b ^ c ^ d) + k[13] + 681279174 | 0; + a = (a << 4 | a >>> 28) + b | 0; + d += (a ^ b ^ c) + k[0] - 358537222 | 0; + d = (d << 11 | d >>> 21) + a | 0; + c += (d ^ a ^ b) + k[3] - 722521979 | 0; + c = (c << 16 | c >>> 16) + d | 0; + b += (c ^ d ^ a) + k[6] + 76029189 | 0; + b = (b << 23 | b >>> 9) + c | 0; + a += (b ^ c ^ d) + k[9] - 640364487 | 0; + a = (a << 4 | a >>> 28) + b | 0; + d += (a ^ b ^ c) + k[12] - 421815835 | 0; + d = (d << 11 | d >>> 21) + a | 0; + c += (d ^ a ^ b) + k[15] + 530742520 | 0; + c = (c << 16 | c >>> 16) + d | 0; + b += (c ^ d ^ a) + k[2] - 995338651 | 0; + b = (b << 23 | b >>> 9) + c | 0; + // ii() + a += (c ^ (b | ~d)) + k[0] - 198630844 | 0; + a = (a << 6 | a >>> 26) + b | 0; + d += (b ^ (a | ~c)) + k[7] + 1126891415 | 0; + d = (d << 10 | d >>> 22) + a | 0; + c += (a ^ (d | ~b)) + k[14] - 1416354905 | 0; + c = (c << 15 | c >>> 17) + d | 0; + b += (d ^ (c | ~a)) + k[5] - 57434055 | 0; + b = (b << 21 | b >>> 11) + c | 0; + a += (c ^ (b | ~d)) + k[12] + 1700485571 | 0; + a = (a << 6 | a >>> 26) + b | 0; + d += (b ^ (a | ~c)) + k[3] - 1894986606 | 0; + d = (d << 10 | d >>> 22) + a | 0; + c += (a ^ (d | ~b)) + k[10] - 1051523 | 0; + c = (c << 15 | c >>> 17) + d | 0; + b += (d ^ (c | ~a)) + k[1] - 2054922799 | 0; + b = (b << 21 | b >>> 11) + c | 0; + a += (c ^ (b | ~d)) + k[8] + 1873313359 | 0; + a = (a << 6 | a >>> 26) + b | 0; + d += (b ^ (a | ~c)) + k[15] - 30611744 | 0; + d = (d << 10 | d >>> 22) + a | 0; + c += (a ^ (d | ~b)) + k[6] - 1560198380 | 0; + c = (c << 15 | c >>> 17) + d | 0; + b += (d ^ (c | ~a)) + k[13] + 1309151649 | 0; + b = (b << 21 | b >>> 11) + c | 0; + a += (c ^ (b | ~d)) + k[4] - 145523070 | 0; + a = (a << 6 | a >>> 26) + b | 0; + d += (b ^ (a | ~c)) + k[11] - 1120210379 | 0; + d = (d << 10 | d >>> 22) + a | 0; + c += (a ^ (d | ~b)) + k[2] + 718787259 | 0; + c = (c << 15 | c >>> 17) + d | 0; + b += (d ^ (c | ~a)) + k[9] - 343485551 | 0; + b = (b << 21 | b >>> 11) + c | 0; + x[0] = a + x[0] | 0; + x[1] = b + x[1] | 0; + x[2] = c + x[2] | 0; + x[3] = d + x[3] | 0; + } + start() { + this._dataLength = 0; + this._bufferLength = 0; + this._state.set(Md5.stateIdentity); + return this; + } + // Char to code point to to array conversion: + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt + // #Example.3A_Fixing_charCodeAt_to_handle_non-Basic-Multilingual-Plane_characters_if_their_presence_earlier_in_the_string_is_unknown + appendStr(str) { + const buf8 = this._buffer8; + const buf32 = this._buffer32; + let bufLen = this._bufferLength; + let code; + let i; + for (i = 0; i < str.length; i += 1) { + code = str.charCodeAt(i); + if (code < 128) { + buf8[bufLen++] = code; + } + else if (code < 0x800) { + buf8[bufLen++] = (code >>> 6) + 0xC0; + buf8[bufLen++] = code & 0x3F | 0x80; + } + else if (code < 0xD800 || code > 0xDBFF) { + buf8[bufLen++] = (code >>> 12) + 0xE0; + buf8[bufLen++] = (code >>> 6 & 0x3F) | 0x80; + buf8[bufLen++] = (code & 0x3F) | 0x80; + } + else { + code = ((code - 0xD800) * 0x400) + (str.charCodeAt(++i) - 0xDC00) + 0x10000; + if (code > 0x10FFFF) { + throw new Error('Unicode standard supports code points up to U+10FFFF'); + } + buf8[bufLen++] = (code >>> 18) + 0xF0; + buf8[bufLen++] = (code >>> 12 & 0x3F) | 0x80; + buf8[bufLen++] = (code >>> 6 & 0x3F) | 0x80; + buf8[bufLen++] = (code & 0x3F) | 0x80; + } + if (bufLen >= 64) { + this._dataLength += 64; + Md5._md5cycle(this._state, buf32); + bufLen -= 64; + buf32[0] = buf32[16]; + } + } + this._bufferLength = bufLen; + return this; + } + appendAsciiStr(str) { + const buf8 = this._buffer8; + const buf32 = this._buffer32; + let bufLen = this._bufferLength; + let i; + let j = 0; + for (;;) { + i = Math.min(str.length - j, 64 - bufLen); + while (i--) { + buf8[bufLen++] = str.charCodeAt(j++); + } + if (bufLen < 64) { + break; + } + this._dataLength += 64; + Md5._md5cycle(this._state, buf32); + bufLen = 0; + } + this._bufferLength = bufLen; + return this; + } + appendByteArray(input) { + const buf8 = this._buffer8; + const buf32 = this._buffer32; + let bufLen = this._bufferLength; + let i; + let j = 0; + for (;;) { + i = Math.min(input.length - j, 64 - bufLen); + while (i--) { + buf8[bufLen++] = input[j++]; + } + if (bufLen < 64) { + break; + } + this._dataLength += 64; + Md5._md5cycle(this._state, buf32); + bufLen = 0; + } + this._bufferLength = bufLen; + return this; + } + getState() { + const self = this; + const s = self._state; + return { + buffer: String.fromCharCode.apply(null, self._buffer8), + buflen: self._bufferLength, + length: self._dataLength, + state: [s[0], s[1], s[2], s[3]] + }; + } + setState(state) { + const buf = state.buffer; + const x = state.state; + const s = this._state; + let i; + this._dataLength = state.length; + this._bufferLength = state.buflen; + s[0] = x[0]; + s[1] = x[1]; + s[2] = x[2]; + s[3] = x[3]; + for (i = 0; i < buf.length; i += 1) { + this._buffer8[i] = buf.charCodeAt(i); + } + } + end(raw = false) { + const bufLen = this._bufferLength; + const buf8 = this._buffer8; + const buf32 = this._buffer32; + const i = (bufLen >> 2) + 1; + let dataBitsLen; + this._dataLength += bufLen; + buf8[bufLen] = 0x80; + buf8[bufLen + 1] = buf8[bufLen + 2] = buf8[bufLen + 3] = 0; + buf32.set(Md5.buffer32Identity.subarray(i), i); + if (bufLen > 55) { + Md5._md5cycle(this._state, buf32); + buf32.set(Md5.buffer32Identity); + } + // Do the final computation based on the tail and length + // Beware that the final length may not fit in 32 bits so we take care of that + dataBitsLen = this._dataLength * 8; + if (dataBitsLen <= 0xFFFFFFFF) { + buf32[14] = dataBitsLen; + } + else { + const matches = dataBitsLen.toString(16).match(/(.*?)(.{0,8})$/); + if (matches === null) { + return; + } + const lo = parseInt(matches[2], 16); + const hi = parseInt(matches[1], 16) || 0; + buf32[14] = lo; + buf32[15] = hi; + } + Md5._md5cycle(this._state, buf32); + return raw ? this._state : Md5._hex(this._state); + } +} +// Private Static Variables +Md5.stateIdentity = new Int32Array([1732584193, -271733879, -1732584194, 271733878]); +Md5.buffer32Identity = new Int32Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); +Md5.hexChars = '0123456789abcdef'; +Md5.hexOut = []; +// Permanent instance is to use for one-call hashing +Md5.onePassHasher = new Md5(); +if (Md5.hashStr('hello') !== '5d41402abc4b2a76b9719d911017c592') { + console.error('Md5 self test failed.'); +} diff --git a/lib/core/messages/methods/ack.d.ts b/lib/core/messages/methods/ack.d.ts new file mode 100644 index 000000000..864a450e2 --- /dev/null +++ b/lib/core/messages/methods/ack.d.ts @@ -0,0 +1,19 @@ +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 new file mode 100644 index 000000000..28a6505ec --- /dev/null +++ b/lib/core/messages/methods/ack.d.ts.map @@ -0,0 +1 @@ +{"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 new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/core/messages/methods/ack.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/core/messages/methods/bye.d.ts b/lib/core/messages/methods/bye.d.ts new file mode 100644 index 000000000..b1252b205 --- /dev/null +++ b/lib/core/messages/methods/bye.d.ts @@ -0,0 +1,22 @@ +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 new file mode 100644 index 000000000..280284ced --- /dev/null +++ b/lib/core/messages/methods/bye.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"bye.d.ts","sourceRoot":"","sources":["../../../../src/core/messages/methods/bye.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,MAAM,WAAW,kBAAmB,SAAQ,eAAe;CAAG;AAE9D;;;GAGG;AACH,MAAM,WAAW,mBAAoB,SAAQ,gBAAgB;CAAG;AAEhE;;;GAGG;AACH,MAAM,WAAW,kBAAmB,SAAQ,eAAe;CAAG"} \ No newline at end of file diff --git a/lib/core/messages/methods/bye.js b/lib/core/messages/methods/bye.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/core/messages/methods/bye.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/core/messages/methods/cancel.d.ts b/lib/core/messages/methods/cancel.d.ts new file mode 100644 index 000000000..8046a0a5b --- /dev/null +++ b/lib/core/messages/methods/cancel.d.ts @@ -0,0 +1,22 @@ +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 new file mode 100644 index 000000000..bb7b87db7 --- /dev/null +++ b/lib/core/messages/methods/cancel.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"cancel.d.ts","sourceRoot":"","sources":["../../../../src/core/messages/methods/cancel.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,MAAM,WAAW,qBAAsB,SAAQ,eAAe;CAAG;AAEjE;;;GAGG;AACH,MAAM,WAAW,sBAAuB,SAAQ,gBAAgB;CAAG;AAEnE;;;GAGG;AACH,MAAM,WAAW,qBAAsB,SAAQ,eAAe;CAAG"} \ No newline at end of file diff --git a/lib/core/messages/methods/cancel.js b/lib/core/messages/methods/cancel.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/core/messages/methods/cancel.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/core/messages/methods/constants.d.ts b/lib/core/messages/methods/constants.d.ts new file mode 100644 index 000000000..02e5a2fdb --- /dev/null +++ b/lib/core/messages/methods/constants.d.ts @@ -0,0 +1,21 @@ +/** + * 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 new file mode 100644 index 000000000..95b4929ab --- /dev/null +++ b/lib/core/messages/methods/constants.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../../../src/core/messages/methods/constants.ts"],"names":[],"mappings":"AACA;;;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 new file mode 100644 index 000000000..9a744dde4 --- /dev/null +++ b/lib/core/messages/methods/constants.js @@ -0,0 +1,22 @@ +/* eslint-disable @typescript-eslint/no-namespace */ +/** + * SIP Methods + * @internal + */ +export 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 || (C = {})); diff --git a/lib/core/messages/methods/index.d.ts b/lib/core/messages/methods/index.d.ts new file mode 100644 index 000000000..84e1892a3 --- /dev/null +++ b/lib/core/messages/methods/index.d.ts @@ -0,0 +1,14 @@ +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 new file mode 100644 index 000000000..95b4d8d8b --- /dev/null +++ b/lib/core/messages/methods/index.d.ts.map @@ -0,0 +1 @@ +{"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 new file mode 100644 index 000000000..f60ff2931 --- /dev/null +++ b/lib/core/messages/methods/index.js @@ -0,0 +1,13 @@ +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"; diff --git a/lib/core/messages/methods/info.d.ts b/lib/core/messages/methods/info.d.ts new file mode 100644 index 000000000..c5c26d00c --- /dev/null +++ b/lib/core/messages/methods/info.d.ts @@ -0,0 +1,22 @@ +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 new file mode 100644 index 000000000..2d98e15a5 --- /dev/null +++ b/lib/core/messages/methods/info.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"info.d.ts","sourceRoot":"","sources":["../../../../src/core/messages/methods/info.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,MAAM,WAAW,mBAAoB,SAAQ,eAAe;CAAG;AAE/D;;;GAGG;AACH,MAAM,WAAW,oBAAqB,SAAQ,gBAAgB;CAAG;AAEjE;;;GAGG;AACH,MAAM,WAAW,mBAAoB,SAAQ,eAAe;CAAG"} \ No newline at end of file diff --git a/lib/core/messages/methods/info.js b/lib/core/messages/methods/info.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/core/messages/methods/info.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/core/messages/methods/invite.d.ts b/lib/core/messages/methods/invite.d.ts new file mode 100644 index 000000000..8ee3ab809 --- /dev/null +++ b/lib/core/messages/methods/invite.d.ts @@ -0,0 +1,87 @@ +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 new file mode 100644 index 000000000..8db910146 --- /dev/null +++ b/lib/core/messages/methods/invite.d.ts.map @@ -0,0 +1 @@ +{"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;AAM/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 new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/core/messages/methods/invite.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/core/messages/methods/message.d.ts b/lib/core/messages/methods/message.d.ts new file mode 100644 index 000000000..b501e63ed --- /dev/null +++ b/lib/core/messages/methods/message.d.ts @@ -0,0 +1,22 @@ +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 new file mode 100644 index 000000000..ca4d83c3b --- /dev/null +++ b/lib/core/messages/methods/message.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"message.d.ts","sourceRoot":"","sources":["../../../../src/core/messages/methods/message.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,MAAM,WAAW,sBAAuB,SAAQ,eAAe;CAAG;AAElE;;;GAGG;AACH,MAAM,WAAW,uBAAwB,SAAQ,gBAAgB;CAAG;AAEpE;;;GAGG;AACH,MAAM,WAAW,sBAAuB,SAAQ,eAAe;CAAG"} \ No newline at end of file diff --git a/lib/core/messages/methods/message.js b/lib/core/messages/methods/message.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/core/messages/methods/message.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/core/messages/methods/notify.d.ts b/lib/core/messages/methods/notify.d.ts new file mode 100644 index 000000000..a19936699 --- /dev/null +++ b/lib/core/messages/methods/notify.d.ts @@ -0,0 +1,22 @@ +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 new file mode 100644 index 000000000..2668f5b3c --- /dev/null +++ b/lib/core/messages/methods/notify.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"notify.d.ts","sourceRoot":"","sources":["../../../../src/core/messages/methods/notify.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,MAAM,WAAW,qBAAsB,SAAQ,eAAe;CAAG;AAEjE;;;GAGG;AACH,MAAM,WAAW,sBAAuB,SAAQ,gBAAgB;CAAG;AAEnE;;;GAGG;AACH,MAAM,WAAW,qBAAsB,SAAQ,eAAe;CAAG"} \ No newline at end of file diff --git a/lib/core/messages/methods/notify.js b/lib/core/messages/methods/notify.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/core/messages/methods/notify.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/core/messages/methods/prack.d.ts b/lib/core/messages/methods/prack.d.ts new file mode 100644 index 000000000..4b565334d --- /dev/null +++ b/lib/core/messages/methods/prack.d.ts @@ -0,0 +1,22 @@ +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 new file mode 100644 index 000000000..d8e69158a --- /dev/null +++ b/lib/core/messages/methods/prack.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"prack.d.ts","sourceRoot":"","sources":["../../../../src/core/messages/methods/prack.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,MAAM,WAAW,oBAAqB,SAAQ,eAAe;CAAG;AAEhE;;;GAGG;AACH,MAAM,WAAW,qBAAsB,SAAQ,gBAAgB;CAAG;AAElE;;;GAGG;AACH,MAAM,WAAW,oBAAqB,SAAQ,eAAe;CAAG"} \ No newline at end of file diff --git a/lib/core/messages/methods/prack.js b/lib/core/messages/methods/prack.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/core/messages/methods/prack.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/core/messages/methods/publish.d.ts b/lib/core/messages/methods/publish.d.ts new file mode 100644 index 000000000..c0c25b526 --- /dev/null +++ b/lib/core/messages/methods/publish.d.ts @@ -0,0 +1,22 @@ +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 new file mode 100644 index 000000000..8b963dadd --- /dev/null +++ b/lib/core/messages/methods/publish.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"publish.d.ts","sourceRoot":"","sources":["../../../../src/core/messages/methods/publish.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,MAAM,WAAW,sBAAuB,SAAQ,eAAe;CAAG;AAElE;;;GAGG;AACH,MAAM,WAAW,uBAAwB,SAAQ,gBAAgB;CAAG;AAEpE;;;GAGG;AACH,MAAM,WAAW,sBAAuB,SAAQ,eAAe;CAAG"} \ No newline at end of file diff --git a/lib/core/messages/methods/publish.js b/lib/core/messages/methods/publish.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/core/messages/methods/publish.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/core/messages/methods/refer.d.ts b/lib/core/messages/methods/refer.d.ts new file mode 100644 index 000000000..cb11370f7 --- /dev/null +++ b/lib/core/messages/methods/refer.d.ts @@ -0,0 +1,22 @@ +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 new file mode 100644 index 000000000..46f632e79 --- /dev/null +++ b/lib/core/messages/methods/refer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"refer.d.ts","sourceRoot":"","sources":["../../../../src/core/messages/methods/refer.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,MAAM,WAAW,oBAAqB,SAAQ,eAAe;CAAG;AAEhE;;;GAGG;AACH,MAAM,WAAW,qBAAsB,SAAQ,gBAAgB;CAAG;AAElE;;;GAGG;AACH,MAAM,WAAW,oBAAqB,SAAQ,eAAe;CAAG"} \ No newline at end of file diff --git a/lib/core/messages/methods/refer.js b/lib/core/messages/methods/refer.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/core/messages/methods/refer.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/core/messages/methods/register.d.ts b/lib/core/messages/methods/register.d.ts new file mode 100644 index 000000000..f5fb52552 --- /dev/null +++ b/lib/core/messages/methods/register.d.ts @@ -0,0 +1,22 @@ +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 new file mode 100644 index 000000000..360af5c4e --- /dev/null +++ b/lib/core/messages/methods/register.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"register.d.ts","sourceRoot":"","sources":["../../../../src/core/messages/methods/register.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,MAAM,WAAW,uBAAwB,SAAQ,eAAe;CAAG;AAEnE;;;GAGG;AACH,MAAM,WAAW,wBAAyB,SAAQ,gBAAgB;CAAG;AAErE;;;GAGG;AACH,MAAM,WAAW,uBAAwB,SAAQ,eAAe;CAAG"} \ No newline at end of file diff --git a/lib/core/messages/methods/register.js b/lib/core/messages/methods/register.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/core/messages/methods/register.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/core/messages/methods/subscribe.d.ts b/lib/core/messages/methods/subscribe.d.ts new file mode 100644 index 000000000..43b41c6dc --- /dev/null +++ b/lib/core/messages/methods/subscribe.d.ts @@ -0,0 +1,55 @@ +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 new file mode 100644 index 000000000..6c028a615 --- /dev/null +++ b/lib/core/messages/methods/subscribe.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"subscribe.d.ts","sourceRoot":"","sources":["../../../../src/core/messages/methods/subscribe.ts"],"names":[],"mappings":"AACA,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;AAEjD;;;GAGG;AACH,MAAM,WAAW,wBAAyB,SAAQ,eAAe;CAAG;AAEpE;;;GAGG;AACH,MAAM,WAAW,yBAA0B,SAAQ,gBAAgB;CAAG;AAEtE;;;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 new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/core/messages/methods/subscribe.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/core/messages/outgoing-request-message.d.ts b/lib/core/messages/outgoing-request-message.d.ts new file mode 100644 index 000000000..5957a1b34 --- /dev/null +++ b/lib/core/messages/outgoing-request-message.d.ts @@ -0,0 +1,95 @@ +import { NameAddrHeader, URI } from "../../grammar"; +import { Body } from "./body"; +/** + * 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 { + 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 a copy of the default options. */ + private static getDefaultOptions; + private static makeNameAddrHeader; + /** + * 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 transport - The sent protocol transport. + */ + setViaHeader(branch: string, transport: 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 new file mode 100644 index 000000000..df46577f0 --- /dev/null +++ b/lib/core/messages/outgoing-request-message.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"outgoing-request-message.d.ts","sourceRoot":"","sources":["../../../src/core/messages/outgoing-request-message.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,GAAG,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AAG9B;;;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;IACjC,SAAgB,OAAO,EAAE;QAAE,CAAC,IAAI,EAAE,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,CAAA;KAAE,CAAM;IAEhE,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,CAA0C;gBAGvD,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;IAuEb,yCAAyC;IACzC,OAAO,CAAC,MAAM,CAAC,iBAAiB;IAkBhC,OAAO,CAAC,MAAM,CAAC,kBAAkB;IAQjC;;;;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,SAAS,EAAE,MAAM,GAAG,IAAI;IAcrD,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 new file mode 100644 index 000000000..48d3c9c33 --- /dev/null +++ b/lib/core/messages/outgoing-request-message.js @@ -0,0 +1,229 @@ +import { NameAddrHeader } from "../../grammar"; +import { createRandomToken, headerize, newTag, utf8Length } from "./utils"; +/** + * Outgoing SIP request message. + * @public + */ +export class OutgoingRequestMessage { + constructor(method, ruri, fromURI, toURI, options, extraHeaders, body) { + this.headers = {}; + this.extraHeaders = []; + // Initialize default options + this.options = OutgoingRequestMessage.getDefaultOptions(); + // Options - merge a deep copy + if (options) { + this.options = Object.assign(Object.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 : 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 + 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. */ + static getDefaultOptions() { + return { + callId: "", + callIdPrefix: "", + cseq: 1, + toDisplayName: "", + toTag: "", + fromDisplayName: "", + fromTag: "", + forceRport: false, + hackViaTcp: false, + optionTags: ["outbound"], + routeSet: [], + userAgentString: "sip.js", + viaHost: "" + }; + } + static makeNameAddrHeader(uri, displayName, tag) { + const parameters = {}; + if (tag) { + parameters.tag = tag; + } + return new 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. + */ + getHeader(name) { + const header = this.headers[headerize(name)]; + if (header) { + if (header[0]) { + return header[0]; + } + } + else { + const regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); + for (const exHeader of this.extraHeaders) { + 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. + */ + getHeaders(name) { + const result = []; + const headerArray = this.headers[headerize(name)]; + if (headerArray) { + for (const headerPart of headerArray) { + result.push(headerPart); + } + } + else { + const regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); + for (const exHeader of this.extraHeaders) { + 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 + */ + hasHeader(name) { + if (this.headers[headerize(name)]) { + return true; + } + else { + const regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); + for (const extraHeader of this.extraHeaders) { + 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 + */ + setHeader(name, value) { + this.headers[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 transport - The sent protocol transport. + */ + setViaHeader(branch, transport) { + // FIXME: Hack + if (this.options.hackViaTcp) { + transport = "TCP"; + } + let via = "SIP/2.0/" + transport; + via += " " + this.options.viaHost + ";branch=" + branch; + if (this.options.forceRport) { + via += ";rport"; + } + this.setHeader("via", via); + this.branch = branch; + } + toString() { + let msg = ""; + msg += this.method + " " + this.ruri.toRaw() + " SIP/2.0\r\n"; + for (const header in this.headers) { + if (this.headers[header]) { + for (const headerPart of this.headers[header]) { + msg += header + ": " + headerPart + "\r\n"; + } + } + } + for (const header of this.extraHeaders) { + 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: " + utf8Length(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: " + utf8Length(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; + } +} diff --git a/lib/core/messages/outgoing-request.d.ts b/lib/core/messages/outgoing-request.d.ts new file mode 100644 index 000000000..c88155faa --- /dev/null +++ b/lib/core/messages/outgoing-request.d.ts @@ -0,0 +1,68 @@ +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 new file mode 100644 index 000000000..35d2e0d88 --- /dev/null +++ b/lib/core/messages/outgoing-request.d.ts.map @@ -0,0 +1 @@ +{"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 new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/core/messages/outgoing-request.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/core/messages/outgoing-response.d.ts b/lib/core/messages/outgoing-response.d.ts new file mode 100644 index 000000000..cae196ed8 --- /dev/null +++ b/lib/core/messages/outgoing-response.d.ts @@ -0,0 +1,43 @@ +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 new file mode 100644 index 000000000..2e5601c2b --- /dev/null +++ b/lib/core/messages/outgoing-response.d.ts.map @@ -0,0 +1 @@ +{"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,CAAC,OAAO,EAAE,sBAAsB,EAAE,OAAO,EAAE,eAAe,GAAG,gBAAgB,CAgIrH"} \ No newline at end of file diff --git a/lib/core/messages/outgoing-response.js b/lib/core/messages/outgoing-response.js new file mode 100644 index 000000000..c1fcb2009 --- /dev/null +++ b/lib/core/messages/outgoing-response.js @@ -0,0 +1,126 @@ +import { getReasonPhrase, newTag, utf8Length } from "./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 + */ +export function constructOutgoingResponse(message, options) { + const CRLF = "\r\n"; + if (options.statusCode < 100 || options.statusCode > 699) { + throw new TypeError("Invalid statusCode: " + options.statusCode); + } + const reasonPhrase = options.reasonPhrase ? options.reasonPhrase : 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 + let 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 + const fromHeader = "From: " + message.getHeader("From") + CRLF; + const callIdHeader = "Call-ID: " + message.callId + CRLF; + const cSeqHeader = "CSeq: " + message.cseq + " " + message.method + CRLF; + const viaHeaders = message.getHeaders("via").reduce((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 + let toHeader = "To: " + message.getHeader("to"); + if (options.statusCode > 100 && !message.parseHeader("to").hasParam("tag")) { + let 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 = 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... + let supportedHeader = ""; + if (options.supported) { + supportedHeader = "Supported: " + options.supported.join(", ") + CRLF; + } + // FIXME: TODO: needs review... + let userAgentHeader = ""; + if (options.userAgent) { + userAgentHeader = "User-Agent: " + options.userAgent + CRLF; + } + let extensionHeaders = ""; + if (options.extraHeaders) { + extensionHeaders = options.extraHeaders.reduce((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: " + utf8Length(options.body.content) + CRLF + CRLF; + response += options.body.content; + } + else { + response += "Content-Length: " + 0 + CRLF + CRLF; + } + return { message: response }; +} diff --git a/lib/core/messages/parser.d.ts b/lib/core/messages/parser.d.ts new file mode 100644 index 000000000..af603be99 --- /dev/null +++ b/lib/core/messages/parser.d.ts @@ -0,0 +1,15 @@ +import { Logger } from "../log/logger"; +import { IncomingRequestMessage } from "./incoming-request-message"; +import { IncomingResponseMessage } from "./incoming-response-message"; +/** + * Extract and parse every header of a SIP message. + * @internal + */ +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; + }; + function parseMessage(data: string, logger: Logger): IncomingRequestMessage | IncomingResponseMessage | undefined; +} +//# sourceMappingURL=parser.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/parser.d.ts.map b/lib/core/messages/parser.d.ts.map new file mode 100644 index 000000000..5279a9f5c --- /dev/null +++ b/lib/core/messages/parser.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"parser.d.ts","sourceRoot":"","sources":["../../../src/core/messages/parser.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AACvC,OAAO,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AACpE,OAAO,EAAE,uBAAuB,EAAE,MAAM,6BAA6B,CAAC;AAEtE;;;GAGG;AACH,yBAAiB,MAAM,CAAC;IAEtB,SAAgB,SAAS,CAAC,IAAI,EAAE,GAAG,EAAE,WAAW,EAAE,MAAM,GAAG,MAAM,CAkChE;IAED,SAAgB,WAAW,CACzB,OAAO,EAAE,sBAAsB,GAAG,uBAAuB,EAEzD,IAAI,EAAE,GAAG,EACT,WAAW,EAAE,MAAM,EACnB,SAAS,EAAE,MAAM,GAChB,OAAO,GAAG;QAAE,KAAK,EAAE,MAAM,CAAA;KAAE,CAwI7B;IAED,SAAgB,YAAY,CAC1B,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,GACb,sBAAsB,GAAG,uBAAuB,GAAG,SAAS,CAmE9D;CACF"} \ No newline at end of file diff --git a/lib/core/messages/parser.js b/lib/core/messages/parser.js new file mode 100644 index 000000000..b0267d72d --- /dev/null +++ b/lib/core/messages/parser.js @@ -0,0 +1,241 @@ +/* eslint-disable no-inner-declarations */ +/* eslint-disable @typescript-eslint/no-namespace */ +import { Grammar } from "../../grammar"; +import { IncomingRequestMessage } from "./incoming-request-message"; +import { IncomingResponseMessage } from "./incoming-response-message"; +/** + * Extract and parse every header of a SIP message. + * @internal + */ +export var Parser; +(function (Parser) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + function getHeader(data, headerStart) { + // 'start' position of the header. + let start = headerStart; + // 'end' position of the header. + let end = 0; + // 'partial end' position of the header. + let 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, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + data, headerStart, headerEnd) { + const hcolonIndex = data.indexOf(":", headerStart); + const headerName = data.substring(headerStart, hcolonIndex).trim(); + const headerValue = data.substring(hcolonIndex + 1, headerEnd).trim(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let 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 = Grammar.parse(headerValue, "Record_Route"); + if (parsed === -1) { + parsed = undefined; + break; + } + if (!(parsed instanceof Array)) { + parsed = undefined; + break; + } + parsed.forEach((header) => { + message.addHeader("record-route", headerValue.substring(header.position, header.offset)); + message.headers["Record-Route"][message.getHeaders("record-route").length - 1].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 = Grammar.parse(headerValue, "Contact"); + if (parsed === -1) { + parsed = undefined; + break; + } + if (!(parsed instanceof Array)) { + parsed = undefined; + break; + } + parsed.forEach((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 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; + function parseMessage(data, logger) { + let headerStart = 0; + let 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. + const firstLine = data.substring(0, headerEnd); + const parsed = Grammar.parse(firstLine, "Request_Response"); + let message; + if (parsed === -1) { + logger.warn('error parsing first line of SIP message: "' + firstLine + '"'); + return; + } + else if (!parsed.status_code) { + message = new IncomingRequestMessage(); + message.method = parsed.method; + message.ruri = parsed.uri; + } + else { + message = new 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. + let bodyStart; + // eslint-disable-next-line no-constant-condition + 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; + } + const parsedHeader = parseHeader(message, data, headerStart, headerEnd); + if (parsedHeader && parsedHeader !== true) { + logger.error(parsedHeader.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 || (Parser = {})); diff --git a/lib/core/messages/utils.d.ts b/lib/core/messages/utils.d.ts new file mode 100644 index 000000000..11b08deff --- /dev/null +++ b/lib/core/messages/utils.d.ts @@ -0,0 +1,25 @@ +/** + * @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 utf8Length(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 new file mode 100644 index 000000000..d646f66dd --- /dev/null +++ b/lib/core/messages/utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../src/core/messages/utils.ts"],"names":[],"mappings":"AA+EA;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,SAAK,GAAG,MAAM,CAOjE;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,CAwB7C;AAED;;;GAGG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAE9C"} \ No newline at end of file diff --git a/lib/core/messages/utils.js b/lib/core/messages/utils.js new file mode 100644 index 000000000..1838a9308 --- /dev/null +++ b/lib/core/messages/utils.js @@ -0,0 +1,138 @@ +/** + * SIP Response Reasons + * DOC: http://www.iana.org/assignments/sip-parameters + * @internal + */ +const 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" +}; +/** + * @param size - + * @param base - + * @internal + */ +export function createRandomToken(size, base = 32) { + let token = ""; + for (let i = 0; i < size; i++) { + const r = Math.floor(Math.random() * base); + token += r.toString(base); + } + return token; +} +/** + * @internal + */ +export function getReasonPhrase(code) { + return REASON_PHRASE[code] || ""; +} +/** + * @internal + */ +export function newTag() { + return createRandomToken(10); +} +/** + * @param str - + * @internal + */ +export function headerize(str) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const exceptions = { + "Call-Id": "Call-ID", + Cseq: "CSeq", + "Min-Se": "Min-SE", + Rack: "RAck", + Rseq: "RSeq", + "Www-Authenticate": "WWW-Authenticate" + }; + const name = str.toLowerCase().replace(/_/g, "-").split("-"); + const parts = name.length; + let hname = ""; + for (let 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; +} +/** + * @param str - + * @internal + */ +export function utf8Length(str) { + return encodeURIComponent(str).replace(/%[A-F\d]{2}/g, "U").length; +} diff --git a/lib/core/session/index.d.ts b/lib/core/session/index.d.ts new file mode 100644 index 000000000..27ebc6836 --- /dev/null +++ b/lib/core/session/index.d.ts @@ -0,0 +1,3 @@ +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 new file mode 100644 index 000000000..e32c4cc66 --- /dev/null +++ b/lib/core/session/index.d.ts.map @@ -0,0 +1 @@ +{"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 new file mode 100644 index 000000000..765f8ba7f --- /dev/null +++ b/lib/core/session/index.js @@ -0,0 +1,2 @@ +export * from "./session"; +export * from "./session-delegate"; diff --git a/lib/core/session/session-delegate.d.ts b/lib/core/session/session-delegate.d.ts new file mode 100644 index 000000000..c58b48d62 --- /dev/null +++ b/lib/core/session/session-delegate.d.ts @@ -0,0 +1,71 @@ +import { IncomingAckRequest, IncomingByeRequest, IncomingInfoRequest, IncomingInviteRequest, IncomingMessageRequest, IncomingNotifyRequest, IncomingPrackRequest, IncomingReferRequest } from "../messages"; +/** + * Session delegate. + * @public + */ +export interface SessionDelegate { + /** + * Receive ACK request. + * @param request - Incoming ACK request. + * @returns + * The callback MUST return a promise if it asynchronously handles answers. + * For example, an ACK with an answer (offer in the 200 Ok) may require + * asynchronous processing in which case the callback MUST return a Promise + * which resolves when the answer handling is complete. + * @privateRemarks + * Unlike INVITE handling where we can rely on the generation of a response + * to indicate when offer/answer processing has been completed, ACK handling + * requires some indication from the handler that answer processing is complete + * so that we can avoid some race conditions (see comments in code for more details). + * Having the handler return a Promise provides said indication. + */ + onAck?(request: IncomingAckRequest): Promise | 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 MESSAGE request. + * https://tools.ietf.org/html/rfc3428#section-7 + * @param request - Incoming MESSAGE request. + */ + onMessage?(request: IncomingMessageRequest): 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 new file mode 100644 index 000000000..6593f0ab4 --- /dev/null +++ b/lib/core/session/session-delegate.d.ts.map @@ -0,0 +1 @@ +{"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,sBAAsB,EACtB,qBAAqB,EACrB,oBAAoB,EACpB,oBAAoB,EACrB,MAAM,aAAa,CAAC;AAErB;;;GAGG;AACH,MAAM,WAAW,eAAe;IAC9B;;;;;;;;;;;;;;OAcG;IACH,KAAK,CAAC,CAAC,OAAO,EAAE,kBAAkB,GAAG,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IAE1D;;;;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,SAAS,CAAC,CAAC,OAAO,EAAE,sBAAsB,GAAG,IAAI,CAAC;IAElD;;;;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 new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/core/session/session-delegate.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/core/session/session.d.ts b/lib/core/session/session.d.ts new file mode 100644 index 000000000..bd6a67ccd --- /dev/null +++ b/lib/core/session/session.d.ts @@ -0,0 +1,135 @@ +import { Body, OutgoingByeRequest, OutgoingInfoRequest, OutgoingInviteRequest, OutgoingInviteRequestDelegate, OutgoingMessageRequest, 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 MESSAGE request. + * Deliver a message during a session. + * https://tools.ietf.org/html/rfc3428#section-4 + * @param delegate - Request delegate. + * @param options - Options bucket. + */ + message(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingMessageRequest; + /** + * 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. + * 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 new file mode 100644 index 000000000..01a0e41e6 --- /dev/null +++ b/lib/core/session/session.d.ts.map @@ -0,0 +1 @@ +{"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,sBAAsB,EACtB,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;;;;;;OAMG;IACH,OAAO,CAAC,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,sBAAsB,CAAC;IAE9F;;;;;;;;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 new file mode 100644 index 000000000..688c65a7c --- /dev/null +++ b/lib/core/session/session.js @@ -0,0 +1,40 @@ +/** + * Session state. + * @remarks + * https://tools.ietf.org/html/rfc3261#section-13 + * @public + */ +export var SessionState; +(function (SessionState) { + SessionState["Initial"] = "Initial"; + SessionState["Early"] = "Early"; + SessionState["AckWait"] = "AckWait"; + SessionState["Confirmed"] = "Confirmed"; + SessionState["Terminated"] = "Terminated"; +})(SessionState || (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 + */ +export var SignalingState; +(function (SignalingState) { + SignalingState["Initial"] = "Initial"; + SignalingState["HaveLocalOffer"] = "HaveLocalOffer"; + SignalingState["HaveRemoteOffer"] = "HaveRemoteOffer"; + SignalingState["Stable"] = "Stable"; + SignalingState["Closed"] = "Closed"; +})(SignalingState || (SignalingState = {})); diff --git a/lib/core/subscription/index.d.ts b/lib/core/subscription/index.d.ts new file mode 100644 index 000000000..1c22343d6 --- /dev/null +++ b/lib/core/subscription/index.d.ts @@ -0,0 +1,3 @@ +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 new file mode 100644 index 000000000..8ddb57378 --- /dev/null +++ b/lib/core/subscription/index.d.ts.map @@ -0,0 +1 @@ +{"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 new file mode 100644 index 000000000..28f539cf8 --- /dev/null +++ b/lib/core/subscription/index.js @@ -0,0 +1,2 @@ +export * from "./subscription"; +export * from "./subscription-delegate"; diff --git a/lib/core/subscription/subscription-delegate.d.ts b/lib/core/subscription/subscription-delegate.d.ts new file mode 100644 index 000000000..33bd060f2 --- /dev/null +++ b/lib/core/subscription/subscription-delegate.d.ts @@ -0,0 +1,28 @@ +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 new file mode 100644 index 000000000..7dae89514 --- /dev/null +++ b/lib/core/subscription/subscription-delegate.d.ts.map @@ -0,0 +1 @@ +{"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 new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/core/subscription/subscription-delegate.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/core/subscription/subscription.d.ts b/lib/core/subscription/subscription.d.ts new file mode 100644 index 000000000..e05f64883 --- /dev/null +++ b/lib/core/subscription/subscription.d.ts @@ -0,0 +1,56 @@ +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 new file mode 100644 index 000000000..9bef75cc1 --- /dev/null +++ b/lib/core/subscription/subscription.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"subscription.d.ts","sourceRoot":"","sources":["../../../src/core/subscription/subscription.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,gCAAgC,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AACzG,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 new file mode 100644 index 000000000..4d7281d0f --- /dev/null +++ b/lib/core/subscription/subscription.js @@ -0,0 +1,14 @@ +/** + * Subscription state. + * @remarks + * https://tools.ietf.org/html/rfc6665#section-4.1.2 + * @public + */ +export var SubscriptionState; +(function (SubscriptionState) { + SubscriptionState["Initial"] = "Initial"; + SubscriptionState["NotifyWait"] = "NotifyWait"; + SubscriptionState["Pending"] = "Pending"; + SubscriptionState["Active"] = "Active"; + SubscriptionState["Terminated"] = "Terminated"; +})(SubscriptionState || (SubscriptionState = {})); diff --git a/lib/core/timers.d.ts b/lib/core/timers.d.ts new file mode 100644 index 000000000..70dda6301 --- /dev/null +++ b/lib/core/timers.d.ts @@ -0,0 +1,21 @@ +/** + * 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 new file mode 100644 index 000000000..a1d612df2 --- /dev/null +++ b/lib/core/timers.d.ts.map @@ -0,0 +1 @@ +{"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 new file mode 100644 index 000000000..6f1cd7d0f --- /dev/null +++ b/lib/core/timers.js @@ -0,0 +1,23 @@ +const T1 = 500; +const T2 = 4000; +const T4 = 5000; +/** + * Timers. + * @public + */ +export const Timers = { + T1, + T2, + 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 new file mode 100644 index 000000000..5ea1d1451 --- /dev/null +++ b/lib/core/transactions/client-transaction.d.ts @@ -0,0 +1,46 @@ +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; + protected constructor(_request: OutgoingRequestMessage, transport: Transport, user: ClientTransactionUser, state: TransactionState, loggerCategory: string); + private static makeId; + /** The outgoing request the transaction handling. */ + get request(): OutgoingRequestMessage; + /** + * 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; + /** + * 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; +} +//# 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 new file mode 100644 index 000000000..5504a19c3 --- /dev/null +++ b/lib/core/transactions/client-transaction.d.ts.map @@ -0,0 +1 @@ +{"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;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;IAYxB,OAAO,CAAC,MAAM,CAAC,MAAM;IAWrB,qDAAqD;IACrD,IAAI,OAAO,IAAI,sBAAsB,CAEpC;IAED;;;;;;;;;OASG;IACH,SAAS,CAAC,gBAAgB,IAAI,IAAI;IAMlC;;;;OAIG;aACa,eAAe,CAAC,QAAQ,EAAE,uBAAuB,GAAG,IAAI;CACzE"} \ No newline at end of file diff --git a/lib/core/transactions/client-transaction.js b/lib/core/transactions/client-transaction.js new file mode 100644 index 000000000..75e012bce --- /dev/null +++ b/lib/core/transactions/client-transaction.js @@ -0,0 +1,60 @@ +import { Transaction } from "./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 + */ +export class ClientTransaction extends Transaction { + constructor(_request, transport, user, state, loggerCategory) { + super(transport, user, ClientTransaction.makeId(_request), state, loggerCategory); + 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 + _request.setViaHeader(this.id, transport.protocol); + } + static makeId(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); + } + } + /** The outgoing request the transaction handling. */ + get request() { + return this._request; + } + /** + * 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 + */ + onRequestTimeout() { + if (this.user.onRequestTimeout) { + this.user.onRequestTimeout(); + } + } +} diff --git a/lib/core/transactions/index.d.ts b/lib/core/transactions/index.d.ts new file mode 100644 index 000000000..96371a98d --- /dev/null +++ b/lib/core/transactions/index.d.ts @@ -0,0 +1,11 @@ +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 new file mode 100644 index 000000000..5df90caf9 --- /dev/null +++ b/lib/core/transactions/index.d.ts.map @@ -0,0 +1 @@ +{"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 new file mode 100644 index 000000000..c4f66d3f7 --- /dev/null +++ b/lib/core/transactions/index.js @@ -0,0 +1,10 @@ +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"; diff --git a/lib/core/transactions/invite-client-transaction.d.ts b/lib/core/transactions/invite-client-transaction.d.ts new file mode 100644 index 000000000..9cf9e00e8 --- /dev/null +++ b/lib/core/transactions/invite-client-transaction.d.ts @@ -0,0 +1,117 @@ +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. */ + get 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 timerA; + /** + * 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 timerB; + /** + * 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 timerD; + /** + * 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 timerM; +} +//# 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 new file mode 100644 index 000000000..48d0bf0b5 --- /dev/null +++ b/lib/core/transactions/invite-client-transaction.d.ts.map @@ -0,0 +1 @@ +{"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,CAAqB;IAC9B,OAAO,CAAC,CAAC,CAAqB;IAC9B,OAAO,CAAC,CAAC,CAAqB;IAE9B;;;;;OAKG;IACH,OAAO,CAAC,sBAAsB,CAA8D;IAE5F;;;;;;;;;;OAUG;gBACS,OAAO,EAAE,sBAAsB,EAAE,SAAS,EAAE,SAAS,EAAE,IAAI,EAAE,qBAAqB;IAoB9F;;OAEG;IACI,OAAO,IAAI,IAAI;IAgBtB,oCAAoC;IACpC,IAAI,IAAI,IAAI,MAAM,CAEjB;IAED;;;;;;;;;;;;;;;;OAgBG;IACI,WAAW,CAAC,GAAG,EAAE,sBAAsB,GAAG,IAAI;IAarD;;;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;IA4EvB;;;;;;;;;;;OAWG;IACH,OAAO,CAAC,MAAM;IAId;;;;;OAKG;IACH,OAAO,CAAC,MAAM;IAQd;;;;OAIG;IACH,OAAO,CAAC,MAAM;IAOd;;;;OAIG;IACH,OAAO,CAAC,MAAM;CAMf"} \ No newline at end of file diff --git a/lib/core/transactions/invite-client-transaction.js b/lib/core/transactions/invite-client-transaction.js new file mode 100644 index 000000000..97c12e52b --- /dev/null +++ b/lib/core/transactions/invite-client-transaction.js @@ -0,0 +1,467 @@ +import { Timers } from "../timers"; +import { ClientTransaction } from "./client-transaction"; +import { TransactionState } from "./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 + */ +export class InviteClientTransaction extends ClientTransaction { + /** + * 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, transport, user) { + super(request, transport, user, TransactionState.Calling, "sip.transaction.ict"); + /** + * 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(() => this.timerB(), Timers.TIMER_B); + this.send(request.toString()).catch((error) => { + this.logTransportError(error, "Failed to send initial outgoing request."); + }); + } + /** + * Destructor. + */ + dispose() { + 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.dispose(); + } + /** Transaction kind. Deprecated. */ + get kind() { + return "ict"; + } + /** + * 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) { + const toTag = ack.toTag; + if (!toTag) { + throw new Error("To tag undefined."); + } + const id = "z9hG4bK" + Math.floor(Math.random() * 10000000); + ack.setViaHeader(id, this.transport.protocol); + this.ackRetransmissionCache.set(toTag, ack); // Add to ACK retransmission cache + this.send(ack.toString()).catch((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. + */ + receiveResponse(response) { + const statusCode = response.statusCode; + if (!statusCode || statusCode < 100 || statusCode > 699) { + throw new Error(`Invalid status code ${statusCode}`); + } + switch (this.state) { + case 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(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(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(TransactionState.Completed); + this.ack(response); + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + break; + case 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(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(TransactionState.Completed); + this.ack(response); + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + break; + case 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. + const ack = this.ackRetransmissionCache.get(response.toTag); + if (ack) { + this.send(ack.toString()).catch((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 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 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 + const 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. + */ + onTransportError(error) { + if (this.user.onTransportError) { + this.user.onTransportError(error); + } + this.stateTransition(TransactionState.Terminated, true); + } + /** For logging. */ + typeToString() { + return "INVITE client transaction"; + } + ack(response) { + // 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 + const ruri = this.request.ruri; + const callId = this.request.callId; + const cseq = this.request.cseq; + const from = this.request.getHeader("from"); + const to = response.getHeader("to"); + const via = this.request.getHeader("via"); + const 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."); + } + let 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((error) => { + this.logTransportError(error, "Failed to send ACK to non-2xx response."); + }); + return; + } + /** + * Execute a state transition. + * @param newState - New state. + */ + stateTransition(newState, dueToTransportError = false) { + // Assert valid state transitions. + const invalidStateTransition = () => { + throw new Error(`Invalid state transition from ${this.state} to ${newState}`); + }; + switch (newState) { + case TransactionState.Calling: + invalidStateTransition(); + break; + case TransactionState.Proceeding: + if (this.state !== TransactionState.Calling) { + invalidStateTransition(); + } + break; + case TransactionState.Accepted: + case TransactionState.Completed: + if (this.state !== TransactionState.Calling && this.state !== TransactionState.Proceeding) { + invalidStateTransition(); + } + break; + case TransactionState.Terminated: + if (this.state !== TransactionState.Calling && + this.state !== TransactionState.Accepted && + this.state !== 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 === 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 === TransactionState.Completed) { + this.D = setTimeout(() => this.timerD(), 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 === TransactionState.Accepted) { + this.M = setTimeout(() => this.timerM(), 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 === 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 + */ + timerA() { + // 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 + */ + timerB() { + this.logger.debug(`Timer B expired for INVITE client transaction ${this.id}.`); + if (this.state === TransactionState.Calling) { + this.onRequestTimeout(); + this.stateTransition(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 + */ + timerD() { + this.logger.debug(`Timer D expired for INVITE client transaction ${this.id}.`); + if (this.state === TransactionState.Completed) { + this.stateTransition(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 + */ + timerM() { + this.logger.debug(`Timer M expired for INVITE client transaction ${this.id}.`); + if (this.state === TransactionState.Accepted) { + this.stateTransition(TransactionState.Terminated); + } + } +} diff --git a/lib/core/transactions/invite-server-transaction.d.ts b/lib/core/transactions/invite-server-transaction.d.ts new file mode 100644 index 000000000..8298f77f9 --- /dev/null +++ b/lib/core/transactions/invite-server-transaction.d.ts @@ -0,0 +1,128 @@ +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. */ + get 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 timerG; + /** + * 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 timerH; + /** + * Once timer I fires, the server MUST transition to the "Terminated" state. + * https://tools.ietf.org/html/rfc3261#section-17.2.1 + */ + private timerI; + /** + * 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 timerL; +} +//# 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 new file mode 100644 index 000000000..618d11f32 --- /dev/null +++ b/lib/core/transactions/invite-server-transaction.d.ts.map @@ -0,0 +1 @@ +{"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,CAAqB;IAC9B,OAAO,CAAC,CAAC,CAAqB;IAC9B,OAAO,CAAC,CAAC,CAAqB;IAE9B;;;;;;;;;;;;;;;;;OAiBG;IACH,OAAO,CAAC,sBAAsB,CAAqB;IAEnD;;;;;;;;;OASG;gBACS,OAAO,EAAE,sBAAsB,EAAE,SAAS,EAAE,SAAS,EAAE,IAAI,EAAE,qBAAqB;IAI9F;;OAEG;IACI,OAAO,IAAI,IAAI;IAiBtB,oCAAoC;IACpC,IAAI,IAAI,IAAI,MAAM,CAEjB;IAED;;;OAGG;IACI,cAAc,CAAC,OAAO,EAAE,sBAAsB,GAAG,IAAI;IAsE5D;;;;OAIG;IACI,eAAe,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI;IAgFlE;;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,MAAM;IAId;;;;;OAKG;IACH,OAAO,CAAC,MAAM;IAQd;;;OAGG;IACH,OAAO,CAAC,MAAM;IAKd;;;;;;;;OAQG;IACH,OAAO,CAAC,MAAM;CAMf"} \ No newline at end of file diff --git a/lib/core/transactions/invite-server-transaction.js b/lib/core/transactions/invite-server-transaction.js new file mode 100644 index 000000000..277e1b417 --- /dev/null +++ b/lib/core/transactions/invite-server-transaction.js @@ -0,0 +1,376 @@ +import { C } from "../messages"; +import { Timers } from "../timers"; +import { ServerTransaction } from "./server-transaction"; +import { TransactionState } from "./transaction-state"; +/** + * INVITE Server Transaction. + * @remarks + * https://tools.ietf.org/html/rfc3261#section-17.2.1 + * @public + */ +export class InviteServerTransaction extends ServerTransaction { + /** + * 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, transport, user) { + super(request, transport, user, TransactionState.Proceeding, "sip.transaction.ist"); + } + /** + * Destructor. + */ + dispose() { + 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.dispose(); + } + /** Transaction kind. Deprecated. */ + get kind() { + return "ist"; + } + /** + * Receive requests from transport matching this transaction. + * @param request - Request matching this transaction. + */ + receiveRequest(request) { + switch (this.state) { + case 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 === C.INVITE) { + if (this.lastProvisionalResponse) { + this.send(this.lastProvisionalResponse).catch((error) => { + this.logTransportError(error, "Failed to send retransmission of provisional response."); + }); + } + return; + } + break; + case 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 === C.INVITE) { + return; + } + break; + case 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 === C.INVITE) { + if (!this.lastFinalResponse) { + throw new Error("Last final response undefined."); + } + this.send(this.lastFinalResponse).catch((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 === C.ACK) { + this.stateTransition(TransactionState.Confirmed); + return; + } + break; + case 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 === C.INVITE || request.method === C.ACK) { + return; + } + break; + case TransactionState.Terminated: + // For good measure absorb any additional messages that arrive (should not happen). + if (request.method === C.INVITE || request.method === C.ACK) { + return; + } + break; + default: + throw new Error(`Invalid state ${this.state}`); + } + const 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. + */ + receiveResponse(statusCode, response) { + if (statusCode < 100 || statusCode > 699) { + throw new Error(`Invalid status code ${statusCode}`); + } + switch (this.state) { + case 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((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(TransactionState.Accepted); + this.send(response).catch((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(TransactionState.Completed); + this.send(response).catch((error) => { + this.logTransportError(error, "Failed to send non-2xx final response."); + }); + return; + } + break; + case 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((error) => { + this.logTransportError(error, "Failed to send 2xx response."); + }); + return; + } + break; + case TransactionState.Completed: + break; + case TransactionState.Confirmed: + break; + case TransactionState.Terminated: + break; + default: + throw new Error(`Invalid state ${this.state}`); + } + const 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. + */ + retransmitAcceptedResponse() { + if (this.state === TransactionState.Accepted && this.lastFinalResponse) { + this.send(this.lastFinalResponse).catch((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 + */ + onTransportError(error) { + if (this.user.onTransportError) { + this.user.onTransportError(error); + } + } + /** For logging. */ + typeToString() { + return "INVITE server transaction"; + } + /** + * Execute a state transition. + * @param newState - New state. + */ + stateTransition(newState) { + // Assert valid state transitions. + const invalidStateTransition = () => { + throw new Error(`Invalid state transition from ${this.state} to ${newState}`); + }; + switch (newState) { + case TransactionState.Proceeding: + invalidStateTransition(); + break; + case TransactionState.Accepted: + case TransactionState.Completed: + if (this.state !== TransactionState.Proceeding) { + invalidStateTransition(); + } + break; + case TransactionState.Confirmed: + if (this.state !== TransactionState.Completed) { + invalidStateTransition(); + } + break; + case TransactionState.Terminated: + if (this.state !== TransactionState.Accepted && + this.state !== TransactionState.Completed && + this.state !== TransactionState.Confirmed) { + invalidStateTransition(); + } + break; + default: + invalidStateTransition(); + } + // On any state transition, stop resending provisional 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 === TransactionState.Accepted) { + this.L = setTimeout(() => this.timerL(), 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 === TransactionState.Completed) { + // FIXME: Missing timer G for unreliable transports. + this.H = setTimeout(() => this.timerH(), 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 === TransactionState.Confirmed) { + // FIXME: This timer is not getting set correctly for unreliable transports. + this.I = setTimeout(() => this.timerI(), 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 === 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. + */ + startProgressExtensionTimer() { + // Start the progress extension timer only for the first non-100 provisional response. + if (this.progressExtensionTimer === undefined) { + this.progressExtensionTimer = setInterval(() => { + 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((error) => { + this.logTransportError(error, "Failed to send retransmission of provisional response."); + }); + }, 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. + */ + stopProgressExtensionTimer() { + 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 + */ + timerG() { + // 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 + */ + timerH() { + this.logger.debug(`Timer H expired for INVITE server transaction ${this.id}.`); + if (this.state === TransactionState.Completed) { + this.logger.warn("ACK to negative final response was never received, terminating transaction."); + this.stateTransition(TransactionState.Terminated); + } + } + /** + * Once timer I fires, the server MUST transition to the "Terminated" state. + * https://tools.ietf.org/html/rfc3261#section-17.2.1 + */ + timerI() { + this.logger.debug(`Timer I expired for INVITE server transaction ${this.id}.`); + this.stateTransition(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 + */ + timerL() { + this.logger.debug(`Timer L expired for INVITE server transaction ${this.id}.`); + if (this.state === TransactionState.Accepted) { + this.stateTransition(TransactionState.Terminated); + } + } +} diff --git a/lib/core/transactions/non-invite-client-transaction.d.ts b/lib/core/transactions/non-invite-client-transaction.d.ts new file mode 100644 index 000000000..4450a067b --- /dev/null +++ b/lib/core/transactions/non-invite-client-transaction.d.ts @@ -0,0 +1,70 @@ +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. */ + get 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 fail over mechanisms described in [4]. + * https://tools.ietf.org/html/rfc3261#section-17.1.4 + * @param error - Transport 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 timerF; + /** + * 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 timerK; +} +//# 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 new file mode 100644 index 000000000..2231bc53e --- /dev/null +++ b/lib/core/transactions/non-invite-client-transaction.d.ts.map @@ -0,0 +1 @@ +{"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,CAAqB;IAC9B,OAAO,CAAC,CAAC,CAAqB;IAE9B;;;;;;;;;;OAUG;gBACS,OAAO,EAAE,sBAAsB,EAAE,SAAS,EAAE,SAAS,EAAE,IAAI,EAAE,qBAAqB;IAe9F;;OAEG;IACI,OAAO,IAAI,IAAI;IAYtB,oCAAoC;IACpC,IAAI,IAAI,IAAI,MAAM,CAEjB;IAED;;;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;IA2DvB;;;;;;;OAOG;IACH,OAAO,CAAC,MAAM;IAQd;;;;OAIG;IACH,OAAO,CAAC,MAAM;CAKf"} \ 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 new file mode 100644 index 000000000..cddff137a --- /dev/null +++ b/lib/core/transactions/non-invite-client-transaction.js @@ -0,0 +1,233 @@ +import { Timers } from "../timers"; +import { ClientTransaction } from "./client-transaction"; +import { TransactionState } from "./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 + */ +export class NonInviteClientTransaction extends ClientTransaction { + /** + * 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, transport, user) { + super(request, transport, user, TransactionState.Trying, "sip.transaction.nict"); + // 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(() => this.timerF(), Timers.TIMER_F); + this.send(request.toString()).catch((error) => { + this.logTransportError(error, "Failed to send initial outgoing request."); + }); + } + /** + * Destructor. + */ + dispose() { + if (this.F) { + clearTimeout(this.F); + this.F = undefined; + } + if (this.K) { + clearTimeout(this.K); + this.K = undefined; + } + super.dispose(); + } + /** Transaction kind. Deprecated. */ + get kind() { + return "nict"; + } + /** + * Handler for incoming responses from the transport which match this transaction. + * @param response - The incoming response. + */ + receiveResponse(response) { + const statusCode = response.statusCode; + if (!statusCode || statusCode < 100 || statusCode > 699) { + throw new Error(`Invalid status code ${statusCode}`); + } + switch (this.state) { + case 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(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(TransactionState.Completed); + if (statusCode === 408) { + this.onRequestTimeout(); + return; + } + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + break; + case 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(TransactionState.Completed); + if (statusCode === 408) { + this.onRequestTimeout(); + return; + } + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + break; + case 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 TransactionState.Terminated: + // For good measure just absorb additional response retransmissions. + return; + default: + throw new Error(`Invalid state ${this.state}`); + } + const 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 fail over mechanisms described in [4]. + * https://tools.ietf.org/html/rfc3261#section-17.1.4 + * @param error - Transport error + */ + onTransportError(error) { + if (this.user.onTransportError) { + this.user.onTransportError(error); + } + this.stateTransition(TransactionState.Terminated, true); + } + /** For logging. */ + typeToString() { + return "non-INVITE client transaction"; + } + /** + * Execute a state transition. + * @param newState - New state. + */ + stateTransition(newState, dueToTransportError = false) { + // Assert valid state transitions. + const invalidStateTransition = () => { + throw new Error(`Invalid state transition from ${this.state} to ${newState}`); + }; + switch (newState) { + case TransactionState.Trying: + invalidStateTransition(); + break; + case TransactionState.Proceeding: + if (this.state !== TransactionState.Trying) { + invalidStateTransition(); + } + break; + case TransactionState.Completed: + if (this.state !== TransactionState.Trying && this.state !== TransactionState.Proceeding) { + invalidStateTransition(); + } + break; + case TransactionState.Terminated: + if (this.state !== TransactionState.Trying && + this.state !== TransactionState.Proceeding && + this.state !== 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 === TransactionState.Completed) { + if (this.F) { + clearTimeout(this.F); + this.F = undefined; + } + this.K = setTimeout(() => this.timerK(), 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 === 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 + */ + timerF() { + this.logger.debug(`Timer F expired for non-INVITE client transaction ${this.id}.`); + if (this.state === TransactionState.Trying || this.state === TransactionState.Proceeding) { + this.onRequestTimeout(); + this.stateTransition(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 + */ + timerK() { + if (this.state === TransactionState.Completed) { + this.stateTransition(TransactionState.Terminated); + } + } +} diff --git a/lib/core/transactions/non-invite-server-transaction.d.ts b/lib/core/transactions/non-invite-server-transaction.d.ts new file mode 100644 index 000000000..884974d9e --- /dev/null +++ b/lib/core/transactions/non-invite-server-transaction.d.ts @@ -0,0 +1,58 @@ +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. */ + get 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. 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 timerJ; +} +//# 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 new file mode 100644 index 000000000..efbbcfef9 --- /dev/null +++ b/lib/core/transactions/non-invite-server-transaction.d.ts.map @@ -0,0 +1 @@ +{"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,CAAqB;IAE9B;;;;;;;;OAQG;gBACS,OAAO,EAAE,sBAAsB,EAAE,SAAS,EAAE,SAAS,EAAE,IAAI,EAAE,qBAAqB;IAI9F;;OAEG;IACI,OAAO,IAAI,IAAI;IAQtB,oCAAoC;IACpC,IAAI,IAAI,IAAI,MAAM,CAEjB;IAED;;;OAGG;IAEI,cAAc,CAAC,OAAO,EAAE,sBAAsB,GAAG,IAAI;IAoC5D;;;;OAIG;IACI,eAAe,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI;IAuElE;;;;;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,MAAM;CAMf"} \ 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 new file mode 100644 index 000000000..f591e69ad --- /dev/null +++ b/lib/core/transactions/non-invite-server-transaction.js @@ -0,0 +1,218 @@ +import { Timers } from "../timers"; +import { ServerTransaction } from "./server-transaction"; +import { TransactionState } from "./transaction-state"; +/** + * Non-INVITE Server Transaction. + * @remarks + * https://tools.ietf.org/html/rfc3261#section-17.2.2 + * @public + */ +export class NonInviteServerTransaction extends ServerTransaction { + /** + * 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, transport, user) { + super(request, transport, user, TransactionState.Trying, "sip.transaction.nist"); + } + /** + * Destructor. + */ + dispose() { + if (this.J) { + clearTimeout(this.J); + this.J = undefined; + } + super.dispose(); + } + /** Transaction kind. Deprecated. */ + get kind() { + return "nist"; + } + /** + * Receive requests from transport matching this transaction. + * @param request - Request matching this transaction. + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + receiveRequest(request) { + switch (this.state) { + case 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 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((error) => { + this.logTransportError(error, "Failed to send retransmission of provisional response."); + }); + break; + case 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((error) => { + this.logTransportError(error, "Failed to send retransmission of final response."); + }); + break; + case TransactionState.Terminated: + break; + default: + throw new Error(`Invalid state ${this.state}`); + } + } + /** + * Receive responses from TU for this transaction. + * @param statusCode - Status code of response. 101-199 not allowed per RFC 4320. + * @param response - Response to send. + */ + receiveResponse(statusCode, response) { + 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 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(TransactionState.Proceeding); + this.send(response).catch((error) => { + this.logTransportError(error, "Failed to send provisional response."); + }); + return; + } + if (statusCode >= 200 && statusCode <= 699) { + this.stateTransition(TransactionState.Completed); + this.send(response).catch((error) => { + this.logTransportError(error, "Failed to send final response."); + }); + return; + } + break; + case 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(TransactionState.Completed); + this.send(response).catch((error) => { + this.logTransportError(error, "Failed to send final response."); + }); + return; + } + break; + case 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 TransactionState.Terminated: + break; + default: + throw new Error(`Invalid state ${this.state}`); + } + const 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 + */ + onTransportError(error) { + if (this.user.onTransportError) { + this.user.onTransportError(error); + } + this.stateTransition(TransactionState.Terminated, true); + } + /** For logging. */ + typeToString() { + return "non-INVITE server transaction"; + } + stateTransition(newState, dueToTransportError = false) { + // Assert valid state transitions. + const invalidStateTransition = () => { + throw new Error(`Invalid state transition from ${this.state} to ${newState}`); + }; + switch (newState) { + case TransactionState.Trying: + invalidStateTransition(); + break; + case TransactionState.Proceeding: + if (this.state !== TransactionState.Trying) { + invalidStateTransition(); + } + break; + case TransactionState.Completed: + if (this.state !== TransactionState.Trying && this.state !== TransactionState.Proceeding) { + invalidStateTransition(); + } + break; + case TransactionState.Terminated: + if (this.state !== TransactionState.Proceeding && this.state !== 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 === TransactionState.Completed) { + this.J = setTimeout(() => this.timerJ(), 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 === 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 + */ + timerJ() { + this.logger.debug(`Timer J expired for NON-INVITE server transaction ${this.id}.`); + if (this.state === TransactionState.Completed) { + this.stateTransition(TransactionState.Terminated); + } + } +} diff --git a/lib/core/transactions/server-transaction.d.ts b/lib/core/transactions/server-transaction.d.ts new file mode 100644 index 000000000..d28757edf --- /dev/null +++ b/lib/core/transactions/server-transaction.d.ts @@ -0,0 +1,36 @@ +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. */ + get 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 new file mode 100644 index 000000000..aeff54873 --- /dev/null +++ b/lib/core/transactions/server-transaction.d.ts.map @@ -0,0 +1 @@ +{"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;IAKxB,qDAAqD;IACrD,IAAI,OAAO,IAAI,sBAAsB,CAEpC;IAED;;;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 new file mode 100644 index 000000000..729c26cbb --- /dev/null +++ b/lib/core/transactions/server-transaction.js @@ -0,0 +1,23 @@ +import { Transaction } from "./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 + */ +export class ServerTransaction extends Transaction { + constructor(_request, transport, user, state, loggerCategory) { + super(transport, user, _request.viaBranch, state, loggerCategory); + this._request = _request; + this.user = user; + } + /** The incoming request the transaction handling. */ + get request() { + return this._request; + } +} diff --git a/lib/core/transactions/transaction-state.d.ts b/lib/core/transactions/transaction-state.d.ts new file mode 100644 index 000000000..7b8e5165b --- /dev/null +++ b/lib/core/transactions/transaction-state.d.ts @@ -0,0 +1,14 @@ +/** + * 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 new file mode 100644 index 000000000..6cb37738a --- /dev/null +++ b/lib/core/transactions/transaction-state.d.ts.map @@ -0,0 +1 @@ +{"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 new file mode 100644 index 000000000..c940b2dc5 --- /dev/null +++ b/lib/core/transactions/transaction-state.js @@ -0,0 +1,14 @@ +/** + * Transaction state. + * @public + */ +export 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 || (TransactionState = {})); diff --git a/lib/core/transactions/transaction-user.d.ts b/lib/core/transactions/transaction-user.d.ts new file mode 100644 index 000000000..4cfcb99d6 --- /dev/null +++ b/lib/core/transactions/transaction-user.d.ts @@ -0,0 +1,73 @@ +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 new file mode 100644 index 000000000..4d661ceb1 --- /dev/null +++ b/lib/core/transactions/transaction-user.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"transaction-user.d.ts","sourceRoot":"","sources":["../../../src/core/transactions/transaction-user.ts"],"names":[],"mappings":"AACA,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;AAEvD;;;;;;;;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 new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/core/transactions/transaction-user.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/core/transactions/transaction.d.ts b/lib/core/transactions/transaction.d.ts new file mode 100644 index 000000000..74d3b91e6 --- /dev/null +++ b/lib/core/transactions/transaction.d.ts @@ -0,0 +1,80 @@ +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 { + private _transport; + private _user; + private _id; + private _state; + protected logger: Logger; + private listeners; + 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. */ + get id(): string; + /** Transaction kind. Deprecated. */ + get kind(): string; + /** Transaction state. */ + get state(): TransactionState; + /** Transaction transport. */ + get transport(): Transport; + /** + * Sets up a function that will be called whenever the transaction state changes. + * @param listener - Callback function. + * @param options - An options object that specifies characteristics about the listener. + * If once true, indicates that the listener should be invoked at most once after being added. + * If once true, the listener would be automatically removed when invoked. + */ + addStateChangeListener(listener: () => void, options?: { + once?: boolean; + }): void; + /** + * This is currently public so tests may spy on it. + * @internal + */ + notifyStateChangeListeners(): void; + /** + * Removes a listener previously registered with addStateListener. + * @param listener - Callback function. + */ + removeStateChangeListener(listener: () => void): void; + protected logTransportError(error: TransportError, message: string): 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; + protected abstract onTransportError(error: TransportError): void; +} +//# 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 new file mode 100644 index 000000000..d84eb4926 --- /dev/null +++ b/lib/core/transactions/transaction.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"transaction.d.ts","sourceRoot":"","sources":["../../../src/core/transactions/transaction.ts"],"names":[],"mappings":"AAAA,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,WAAW;IAM7B,OAAO,CAAC,UAAU;IAClB,OAAO,CAAC,KAAK;IACb,OAAO,CAAC,GAAG;IACX,OAAO,CAAC,MAAM;IARhB,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC;IAEzB,OAAO,CAAC,SAAS,CAA2B;IAE5C,SAAS,aACC,UAAU,EAAE,SAAS,EACrB,KAAK,EAAE,eAAe,EACtB,GAAG,EAAE,MAAM,EACX,MAAM,EAAE,gBAAgB,EAChC,cAAc,EAAE,MAAM;IAMxB;;;;;;;;;OASG;IACI,OAAO,IAAI,IAAI;IAItB,sBAAsB;IACtB,IAAI,EAAE,IAAI,MAAM,CAEf;IAED,oCAAoC;IACpC,IAAI,IAAI,IAAI,MAAM,CAEjB;IAED,yBAAyB;IACzB,IAAI,KAAK,IAAI,gBAAgB,CAE5B;IAED,6BAA6B;IAC7B,IAAI,SAAS,IAAI,SAAS,CAEzB;IAED;;;;;;OAMG;IACI,sBAAsB,CAAC,QAAQ,EAAE,MAAM,IAAI,EAAE,OAAO,CAAC,EAAE;QAAE,IAAI,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG,IAAI;IAQvF;;;OAGG;IACI,0BAA0B,IAAI,IAAI;IAIzC;;;OAGG;IACI,yBAAyB,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,IAAI;IAI5D,SAAS,CAAC,iBAAiB,CAAC,KAAK,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI;IAMzE;;;;;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;IAIhC,SAAS,CAAC,QAAQ,CAAC,gBAAgB,CAAC,KAAK,EAAE,cAAc,GAAG,IAAI;CACjE"} \ No newline at end of file diff --git a/lib/core/transactions/transaction.js b/lib/core/transactions/transaction.js new file mode 100644 index 000000000..542461c0f --- /dev/null +++ b/lib/core/transactions/transaction.js @@ -0,0 +1,126 @@ +import { TransportError } from "../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 + */ +export class Transaction { + constructor(_transport, _user, _id, _state, loggerCategory) { + this._transport = _transport; + this._user = _user; + this._id = _id; + this._state = _state; + this.listeners = new Array(); + this.logger = _user.loggerFactory.getLogger(loggerCategory, _id); + this.logger.debug(`Constructing ${this.typeToString()} with id ${this.id}.`); + } + /** + * 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() { + this.logger.debug(`Destroyed ${this.typeToString()} with id ${this.id}.`); + } + /** Transaction id. */ + get id() { + return this._id; + } + /** Transaction kind. Deprecated. */ + get kind() { + throw new Error("Invalid kind."); + } + /** Transaction state. */ + get state() { + return this._state; + } + /** Transaction transport. */ + get transport() { + return this._transport; + } + /** + * Sets up a function that will be called whenever the transaction state changes. + * @param listener - Callback function. + * @param options - An options object that specifies characteristics about the listener. + * If once true, indicates that the listener should be invoked at most once after being added. + * If once true, the listener would be automatically removed when invoked. + */ + addStateChangeListener(listener, options) { + const onceWrapper = () => { + this.removeStateChangeListener(onceWrapper); + listener(); + }; + (options === null || options === void 0 ? void 0 : options.once) === true ? this.listeners.push(onceWrapper) : this.listeners.push(listener); + } + /** + * This is currently public so tests may spy on it. + * @internal + */ + notifyStateChangeListeners() { + this.listeners.slice().forEach((listener) => listener()); + } + /** + * Removes a listener previously registered with addStateListener. + * @param listener - Callback function. + */ + removeStateChangeListener(listener) { + this.listeners = this.listeners.filter((l) => l !== listener); + } + logTransportError(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. + */ + send(message) { + return this.transport.send(message).catch((error) => { + // If the transport rejects, it SHOULD reject with a TransportError. + // But the transport may be external code, so we are careful + // make sure we convert it to a TransportError if need be. + if (error instanceof TransportError) { + this.onTransportError(error); + throw error; + } + let transportError; + if (error && typeof error.message === "string") { + transportError = new TransportError(error.message); + } + else { + transportError = new TransportError(); + } + this.onTransportError(transportError); + throw transportError; + }); + } + setState(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.notifyStateChangeListeners(); + } + typeToString() { + return "UnknownType"; + } +} diff --git a/lib/core/transport.d.ts b/lib/core/transport.d.ts new file mode 100644 index 000000000..ded0095d3 --- /dev/null +++ b/lib/core/transport.d.ts @@ -0,0 +1,32 @@ +/** + * Transport layer interface expected by the user agent core. + * + * @remarks + * The transport layer is responsible for the actual transmission of + * requests and responses over network transports. This includes + * determination of the connection to use for a request or response in + * the case of connection-oriented transports. + * https://tools.ietf.org/html/rfc3261#section-18 + * + * @public + */ +export interface Transport { + /** + * The transport protocol. + * + * @remarks + * Formatted as defined for the Via header sent-protocol transport. + * https://tools.ietf.org/html/rfc3261#section-20.42 + */ + readonly protocol: string; + /** + * Send a message. + * + * @remarks + * Resolves once message is sent. Otherwise rejects with an Error. + * + * @param message - Message to send. + */ + send(message: string): Promise; +} +//# 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 new file mode 100644 index 000000000..1a50dd250 --- /dev/null +++ b/lib/core/transport.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"transport.d.ts","sourceRoot":"","sources":["../../src/core/transport.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,MAAM,WAAW,SAAS;IACxB;;;;;;OAMG;IACH,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAE1B;;;;;;;OAOG;IACH,IAAI,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACtC"} \ No newline at end of file diff --git a/lib/core/transport.js b/lib/core/transport.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/core/transport.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/core/user-agent-core/allowed-methods.d.ts b/lib/core/user-agent-core/allowed-methods.d.ts new file mode 100644 index 000000000..25b377a6d --- /dev/null +++ b/lib/core/user-agent-core/allowed-methods.d.ts @@ -0,0 +1,5 @@ +/** + * 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 new file mode 100644 index 000000000..236310557 --- /dev/null +++ b/lib/core/user-agent-core/allowed-methods.d.ts.map @@ -0,0 +1 @@ +{"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 new file mode 100644 index 000000000..9667b54dc --- /dev/null +++ b/lib/core/user-agent-core/allowed-methods.js @@ -0,0 +1,18 @@ +import { C } from "../messages"; +/** + * FIXME: TODO: Should be configurable/variable. + */ +export const AllowedMethods = [ + C.ACK, + C.BYE, + C.CANCEL, + C.INFO, + C.INVITE, + C.MESSAGE, + C.NOTIFY, + C.OPTIONS, + C.PRACK, + C.REFER, + C.REGISTER, + C.SUBSCRIBE +]; diff --git a/lib/core/user-agent-core/index.d.ts b/lib/core/user-agent-core/index.d.ts new file mode 100644 index 000000000..1dd187fa5 --- /dev/null +++ b/lib/core/user-agent-core/index.d.ts @@ -0,0 +1,4 @@ +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 new file mode 100644 index 000000000..3251b93f2 --- /dev/null +++ b/lib/core/user-agent-core/index.d.ts.map @@ -0,0 +1 @@ +{"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 new file mode 100644 index 000000000..189fc40b8 --- /dev/null +++ b/lib/core/user-agent-core/index.js @@ -0,0 +1,3 @@ +export * from "./user-agent-core"; +export * from "./user-agent-core-configuration"; +export * from "./user-agent-core-delegate"; 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 new file mode 100644 index 000000000..0a890a30f --- /dev/null +++ b/lib/core/user-agent-core/user-agent-core-configuration.d.ts @@ -0,0 +1,100 @@ +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?: { + anonymous?: boolean; + outbound?: boolean; + }) => 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 extensions. + */ + supportedOptionTags: Array; + /** + * Option tags of supported SIP extensions. + * Used in responses. + * @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 new file mode 100644 index 000000000..d734d54da --- /dev/null +++ b/lib/core/user-agent-core/user-agent-core-configuration.d.ts.map @@ -0,0 +1 @@ +{"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;QAAE,SAAS,CAAC,EAAE,OAAO,CAAC;QAAC,QAAQ,CAAC,EAAE,OAAO,CAAA;KAAE,KAAK,MAAM,CAAC;CAC7E;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 new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/core/user-agent-core/user-agent-core-configuration.js @@ -0,0 +1 @@ +export {}; 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 new file mode 100644 index 000000000..598f7776f --- /dev/null +++ b/lib/core/user-agent-core/user-agent-core-delegate.d.ts @@ -0,0 +1,38 @@ +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 new file mode 100644 index 000000000..e7d8950bd --- /dev/null +++ b/lib/core/user-agent-core/user-agent-core-delegate.d.ts.map @@ -0,0 +1 @@ +{"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 new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/core/user-agent-core/user-agent-core-delegate.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/core/user-agent-core/user-agent-core.d.ts b/lib/core/user-agent-core/user-agent-core.d.ts new file mode 100644 index 000000000..791db205e --- /dev/null +++ b/lib/core/user-agent-core/user-agent-core.d.ts @@ -0,0 +1,180 @@ +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. */ + get loggerFactory(): LoggerFactory; + /** Transport. */ + get 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 new file mode 100644 index 000000000..f341f1b00 --- /dev/null +++ b/lib/core/user-agent-core/user-agent-core.d.ts.map @@ -0,0 +1 @@ +{"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;AAErB,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;AAOnE;;;;;;;;;;;;;;;;;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;gBACS,aAAa,EAAE,0BAA0B,EAAE,QAAQ,GAAE,qBAA0B;IAQ3F,kBAAkB;IACX,OAAO,IAAI,IAAI;IAItB,aAAa;IACN,KAAK,IAAI,IAAI;IAWpB,sBAAsB;IACtB,IAAI,aAAa,IAAI,aAAa,CAEjC;IAED,iBAAiB;IACjB,IAAI,SAAS,IAAI,SAAS,CAMzB;IAED;;;;OAIG;IACI,MAAM,CAAC,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,6BAA6B,GAAG,qBAAqB;IAI/G;;;;OAIG;IACI,OAAO,CAAC,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,uBAAuB,GAAG,sBAAsB;IAI3G;;;;OAIG;IACI,OAAO,CAAC,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,uBAAuB,GAAG,sBAAsB;IAI3G;;;;OAIG;IACI,QAAQ,CAAC,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,uBAAuB,GAAG,uBAAuB;IAI7G;;;;OAIG;IACI,SAAS,CACd,OAAO,EAAE,sBAAsB,EAC/B,QAAQ,CAAC,EAAE,gCAAgC,GAC1C,wBAAwB;IAI3B;;;;OAIG;IACI,OAAO,CAAC,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,uBAAuB,GAAG,eAAe;IAIpG;;;;;;;;;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;IAqCzB;;;OAGG;IACI,mCAAmC,CAAC,OAAO,EAAE,sBAAsB,GAAG,IAAI;IAIjF;;;OAGG;IACI,oCAAoC,CAAC,OAAO,EAAE,uBAAuB,GAAG,IAAI;IAInF;;;;;;;;;;;;;;;OAeG;IACI,cAAc,CAAC,OAAO,EAAE,sBAAsB,EAAE,OAAO,EAAE,eAAe,GAAG,gBAAgB;IAmBlG;;;;;;;;;;;OAWG;IACH,OAAO,CAAC,2BAA2B;IA4HnC;;;;;;;;OAQG;IACH,OAAO,CAAC,cAAc;IAgJtB;;;;;;;;;OASG;IACH,OAAO,CAAC,0BAA0B;IAqIlC;;;;;OAKG;IACH,OAAO,CAAC,2BAA2B;IA6GnC;;;;;;;;OAQG;IACH,OAAO,CAAC,4BAA4B;CA0DrC"} \ 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 new file mode 100644 index 000000000..18b4257ae --- /dev/null +++ b/lib/core/user-agent-core/user-agent-core.js @@ -0,0 +1,782 @@ +import { C, constructOutgoingResponse, OutgoingRequestMessage } from "../messages"; +import { InviteServerTransaction, NonInviteClientTransaction, TransactionState } from "../transactions"; +import { InviteUserAgentClient, InviteUserAgentServer, MessageUserAgentClient, MessageUserAgentServer, NotifyUserAgentServer, PublishUserAgentClient, ReferUserAgentServer, RegisterUserAgentClient, RegisterUserAgentServer, SubscribeUserAgentClient, SubscribeUserAgentServer, UserAgentClient } from "../user-agents"; +import { AllowedMethods } from "./allowed-methods"; +/** + * This is ported from UA.C.ACCEPTED_BODY_TYPES. + * FIXME: TODO: Should be configurable/variable. + */ +const 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 + */ +export class UserAgentCore { + /** + * Constructor. + * @param configuration - Configuration. + * @param delegate - Delegate. + */ + constructor(configuration, 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. */ + dispose() { + this.reset(); + } + /** Reset. */ + reset() { + this.dialogs.forEach((dialog) => dialog.dispose()); + this.dialogs.clear(); + this.subscribers.forEach((subscriber) => subscriber.dispose()); + this.subscribers.clear(); + this.userAgentClients.forEach((uac) => uac.dispose()); + this.userAgentClients.clear(); + this.userAgentServers.forEach((uac) => uac.dispose()); + this.userAgentServers.clear(); + } + /** Logger factory. */ + get loggerFactory() { + return this.configuration.loggerFactory; + } + /** Transport. */ + get transport() { + const transport = this.configuration.transportAccessor(); + if (!transport) { + throw new Error("Transport undefined."); + } + return transport; + } + /** + * Send INVITE. + * @param request - Outgoing request. + * @param delegate - Request delegate. + */ + invite(request, delegate) { + return new InviteUserAgentClient(this, request, delegate); + } + /** + * Send MESSAGE. + * @param request - Outgoing request. + * @param delegate - Request delegate. + */ + message(request, delegate) { + return new MessageUserAgentClient(this, request, delegate); + } + /** + * Send PUBLISH. + * @param request - Outgoing request. + * @param delegate - Request delegate. + */ + publish(request, delegate) { + return new PublishUserAgentClient(this, request, delegate); + } + /** + * Send REGISTER. + * @param request - Outgoing request. + * @param delegate - Request delegate. + */ + register(request, delegate) { + return new RegisterUserAgentClient(this, request, delegate); + } + /** + * Send SUBSCRIBE. + * @param request - Outgoing request. + * @param delegate - Request delegate. + */ + subscribe(request, delegate) { + return new SubscribeUserAgentClient(this, request, delegate); + } + /** + * Send a request. + * @param request - Outgoing request. + * @param delegate - Request delegate. + */ + request(request, delegate) { + return new UserAgentClient(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. + */ + makeOutgoingRequestMessage(method, requestURI, fromURI, toURI, options, extraHeaders, body) { + // default values from user agent configuration + const callIdPrefix = this.configuration.sipjsId; + const fromDisplayName = this.configuration.displayName; + const forceRport = this.configuration.viaForceRport; + const hackViaTcp = this.configuration.hackViaTcp; + const optionTags = this.configuration.supportedOptionTags.slice(); + if (method === C.REGISTER) { + optionTags.push("path", "gruu"); + } + if (method === C.INVITE && (this.configuration.contact.pubGruu || this.configuration.contact.tempGruu)) { + optionTags.push("gruu"); + } + const routeSet = this.configuration.routeSet; + const userAgentString = this.configuration.userAgentHeaderFieldValue; + const viaHost = this.configuration.viaHost; + const defaultOptions = { + callIdPrefix, + forceRport, + fromDisplayName, + hackViaTcp, + optionTags, + routeSet, + userAgentString, + viaHost + }; + // merge provided options with default options + const requestOptions = Object.assign(Object.assign({}, defaultOptions), options); + return new OutgoingRequestMessage(method, requestURI, fromURI, toURI, requestOptions, extraHeaders, body); + } + /** + * Handle an incoming request message from the transport. + * @param message - Incoming request message from transport layer. + */ + receiveIncomingRequestFromTransport(message) { + this.receiveRequestFromTransport(message); + } + /** + * Handle an incoming response message from the transport. + * @param message - Incoming response message from transport layer. + */ + receiveIncomingResponseFromTransport(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. + */ + replyStateless(message, options) { + const userAgent = this.configuration.userAgentHeaderFieldValue; + const supported = this.configuration.supportedOptionTagsResponse; + options = Object.assign(Object.assign({}, options), { userAgent, supported }); + const response = constructOutgoingResponse(message, options); + this.transport.send(response.message).catch((error) => { + // If the transport rejects, it SHOULD reject with a TransportError. + // But the transport may be external code, so we are careful... + if (error instanceof Error) { + this.logger.error(error.message); + } + this.logger.error(`Transport error occurred sending stateless reply to ${message.method} request.`); + // TODO: Currently there is no hook to provide notification that a transport error occurred + // and throwing would result in an uncaught error (in promise), so we silently eat the error. + // Furthermore, silently eating stateless reply transport errors is arguably what we want to do here. + }); + 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. + */ + receiveRequestFromTransport(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 + const transactionId = message.viaBranch; // FIXME: Currently only using rule 1... + const 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 === C.ACK) { + if (uas && uas.transaction.state === TransactionState.Accepted) { + if (uas instanceof 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 === 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 InviteServerTransaction && + uas.transaction.state === TransactionState.Proceeding) { + if (uas instanceof 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. + */ + receiveRequest(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 (!AllowedMethods.includes(message.method)) { + const allowHeader = "Allow: " + 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 + const ruri = message.ruri; + const ruriMatches = (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 !== 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 === 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) { + const transactionId = message.viaBranch; + if (!this.userAgentServers.has(transactionId)) { + const mergedRequest = Array.from(this.userAgentServers.values()).some((uas) => 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. + */ + receiveInsideDialogRequest(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 === C.NOTIFY) { + const event = message.parseHeader("Event"); + if (!event || !event.event) { + this.replyStateless(message, { statusCode: 489 }); + return; + } + // FIXME: Subscriber id should also matching on event id. + const subscriberId = message.callId + message.toTag + event.event; + const subscriber = this.subscribers.get(subscriberId); + if (subscriber) { + const uas = new 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 + const dialogId = message.callId + message.toTag + message.fromTag; + const 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 === C.OPTIONS) { + const allowHeader = "Allow: " + AllowedMethods.toString(); + const 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 === 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. + */ + receiveOutsideDialogRequest(message) { + switch (message.method) { + case C.ACK: + // Absorb stray out of dialog ACKs + break; + case 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 C.CANCEL: + throw new Error(`Unexpected out of dialog request method ${message.method}.`); + break; + case 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 C.INVITE: + // https://tools.ietf.org/html/rfc3261#section-13.3.1 + { + const uas = new InviteUserAgentServer(this, message); + this.delegate.onInvite ? this.delegate.onInvite(uas) : uas.reject(); + } + break; + case 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 + { + const uas = new MessageUserAgentServer(this, message); + this.delegate.onMessage ? this.delegate.onMessage(uas) : uas.accept(); + } + break; + case 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 + { + const uas = new NotifyUserAgentServer(this, message); + this.delegate.onNotify ? this.delegate.onNotify(uas) : uas.reject({ statusCode: 405 }); + } + break; + case C.OPTIONS: + // https://tools.ietf.org/html/rfc3261#section-11.2 + { + const allowHeader = "Allow: " + AllowedMethods.toString(); + const acceptHeader = "Accept: " + acceptedBodyTypes.toString(); + this.replyStateless(message, { + statusCode: 200, + extraHeaders: [allowHeader, acceptHeader] + }); + } + break; + case C.REFER: + // https://tools.ietf.org/html/rfc3515#section-2.4.2 + { + const uas = new ReferUserAgentServer(this, message); + this.delegate.onRefer ? this.delegate.onRefer(uas) : uas.reject({ statusCode: 405 }); + } + break; + case C.REGISTER: + // https://tools.ietf.org/html/rfc3261#section-10.3 + { + const uas = new RegisterUserAgentServer(this, message); + this.delegate.onRegister ? this.delegate.onRegister(uas) : uas.reject({ statusCode: 405 }); + } + break; + case C.SUBSCRIBE: + // https://tools.ietf.org/html/rfc6665#section-4.2 + { + const uas = new 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. + */ + receiveResponseFromTransport(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 + const userAgentClientId = message.viaBranch + message.method; + const 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}.`); + } + } +} diff --git a/lib/core/user-agents/bye-user-agent-client.d.ts b/lib/core/user-agents/bye-user-agent-client.d.ts new file mode 100644 index 000000000..c0f22aa95 --- /dev/null +++ b/lib/core/user-agents/bye-user-agent-client.d.ts @@ -0,0 +1,11 @@ +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 new file mode 100644 index 000000000..3cc958863 --- /dev/null +++ b/lib/core/user-agents/bye-user-agent-client.d.ts.map @@ -0,0 +1 @@ +{"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;gBACvE,MAAM,EAAE,aAAa,EAAE,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc;CAKhG"} \ 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 new file mode 100644 index 000000000..8309a8027 --- /dev/null +++ b/lib/core/user-agents/bye-user-agent-client.js @@ -0,0 +1,14 @@ +import { C } from "../messages"; +import { NonInviteClientTransaction } from "../transactions"; +import { UserAgentClient } from "./user-agent-client"; +/** + * BYE UAC. + * @public + */ +export class ByeUserAgentClient extends UserAgentClient { + constructor(dialog, delegate, options) { + const message = dialog.createOutgoingRequestMessage(C.BYE, options); + super(NonInviteClientTransaction, dialog.userAgentCore, message, delegate); + dialog.dispose(); + } +} diff --git a/lib/core/user-agents/bye-user-agent-server.d.ts b/lib/core/user-agents/bye-user-agent-server.d.ts new file mode 100644 index 000000000..85a98258e --- /dev/null +++ b/lib/core/user-agents/bye-user-agent-server.d.ts @@ -0,0 +1,11 @@ +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 new file mode 100644 index 000000000..c89c04774 --- /dev/null +++ b/lib/core/user-agents/bye-user-agent-server.d.ts.map @@ -0,0 +1 @@ +{"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;gBACvE,MAAM,EAAE,aAAa,EAAE,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,uBAAuB;CAGvG"} \ 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 new file mode 100644 index 000000000..b0812dde8 --- /dev/null +++ b/lib/core/user-agents/bye-user-agent-server.js @@ -0,0 +1,11 @@ +import { NonInviteServerTransaction } from "../transactions"; +import { UserAgentServer } from "./user-agent-server"; +/** + * BYE UAS. + * @public + */ +export class ByeUserAgentServer extends UserAgentServer { + constructor(dialog, message, delegate) { + super(NonInviteServerTransaction, dialog.userAgentCore, message, delegate); + } +} diff --git a/lib/core/user-agents/cancel-user-agent-client.d.ts b/lib/core/user-agents/cancel-user-agent-client.d.ts new file mode 100644 index 000000000..e83c423f2 --- /dev/null +++ b/lib/core/user-agents/cancel-user-agent-client.d.ts @@ -0,0 +1,11 @@ +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 new file mode 100644 index 000000000..20eb91265 --- /dev/null +++ b/lib/core/user-agents/cancel-user-agent-client.d.ts.map @@ -0,0 +1 @@ +{"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;gBAC7E,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,uBAAuB;CAGrG"} \ 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 new file mode 100644 index 000000000..58676c41f --- /dev/null +++ b/lib/core/user-agents/cancel-user-agent-client.js @@ -0,0 +1,11 @@ +import { NonInviteClientTransaction } from "../transactions"; +import { UserAgentClient } from "./user-agent-client"; +/** + * CANCEL UAC. + * @public + */ +export class CancelUserAgentClient extends UserAgentClient { + constructor(core, message, delegate) { + super(NonInviteClientTransaction, core, message, delegate); + } +} diff --git a/lib/core/user-agents/index.d.ts b/lib/core/user-agents/index.d.ts new file mode 100644 index 000000000..ac74c459b --- /dev/null +++ b/lib/core/user-agents/index.d.ts @@ -0,0 +1,27 @@ +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 new file mode 100644 index 000000000..816b4d781 --- /dev/null +++ b/lib/core/user-agents/index.d.ts.map @@ -0,0 +1 @@ +{"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 new file mode 100644 index 000000000..3a036707d --- /dev/null +++ b/lib/core/user-agents/index.js @@ -0,0 +1,26 @@ +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"; diff --git a/lib/core/user-agents/info-user-agent-client.d.ts b/lib/core/user-agents/info-user-agent-client.d.ts new file mode 100644 index 000000000..48bcafb3d --- /dev/null +++ b/lib/core/user-agents/info-user-agent-client.d.ts @@ -0,0 +1,11 @@ +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 new file mode 100644 index 000000000..3e4c0f7da --- /dev/null +++ b/lib/core/user-agents/info-user-agent-client.d.ts.map @@ -0,0 +1 @@ +{"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;gBACzE,MAAM,EAAE,aAAa,EAAE,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc;CAIhG"} \ 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 new file mode 100644 index 000000000..92e343ad8 --- /dev/null +++ b/lib/core/user-agents/info-user-agent-client.js @@ -0,0 +1,13 @@ +import { C } from "../messages"; +import { NonInviteClientTransaction } from "../transactions"; +import { UserAgentClient } from "./user-agent-client"; +/** + * INFO UAC. + * @public + */ +export class InfoUserAgentClient extends UserAgentClient { + constructor(dialog, delegate, options) { + const message = dialog.createOutgoingRequestMessage(C.INFO, options); + super(NonInviteClientTransaction, dialog.userAgentCore, message, delegate); + } +} diff --git a/lib/core/user-agents/info-user-agent-server.d.ts b/lib/core/user-agents/info-user-agent-server.d.ts new file mode 100644 index 000000000..1a15097b1 --- /dev/null +++ b/lib/core/user-agents/info-user-agent-server.d.ts @@ -0,0 +1,11 @@ +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 new file mode 100644 index 000000000..3b93ee1ec --- /dev/null +++ b/lib/core/user-agents/info-user-agent-server.d.ts.map @@ -0,0 +1 @@ +{"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;gBACzE,MAAM,EAAE,aAAa,EAAE,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,uBAAuB;CAGvG"} \ 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 new file mode 100644 index 000000000..006c0d0b3 --- /dev/null +++ b/lib/core/user-agents/info-user-agent-server.js @@ -0,0 +1,11 @@ +import { NonInviteServerTransaction } from "../transactions"; +import { UserAgentServer } from "./user-agent-server"; +/** + * INFO UAS. + * @public + */ +export class InfoUserAgentServer extends UserAgentServer { + constructor(dialog, message, delegate) { + super(NonInviteServerTransaction, dialog.userAgentCore, message, delegate); + } +} diff --git a/lib/core/user-agents/invite-user-agent-client.d.ts b/lib/core/user-agents/invite-user-agent-client.d.ts new file mode 100644 index 000000000..5e7d85852 --- /dev/null +++ b/lib/core/user-agents/invite-user-agent-client.d.ts @@ -0,0 +1,36 @@ +import { TransportError } from "../exceptions"; +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; + /** + * Special case for transport error while sending ACK. + * @param error - Transport error + */ + protected onTransportError(error: TransportError): 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 new file mode 100644 index 000000000..aeaedf91f --- /dev/null +++ b/lib/core/user-agents/invite-user-agent-client.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"invite-user-agent-client.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/invite-user-agent-client.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAC/C,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;gBAE5C,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,6BAA6B;IAKnG,OAAO,IAAI,IAAI;IAgBtB;;;OAGG;IACH,SAAS,CAAC,gBAAgB,CAAC,KAAK,EAAE,cAAc,GAAG,IAAI;IASvD;;;;;OAKG;IACH,SAAS,CAAC,eAAe,CAAC,OAAO,EAAE,uBAAuB,GAAG,IAAI;CA0UlE"} \ 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 new file mode 100644 index 000000000..174505092 --- /dev/null +++ b/lib/core/user-agents/invite-user-agent-client.js @@ -0,0 +1,362 @@ +import { Dialog, SessionDialog } from "../dialogs"; +import { SignalingState } from "../session"; +import { InviteClientTransaction, TransactionState } from "../transactions"; +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 class InviteUserAgentClient extends UserAgentClient { + constructor(core, message, delegate) { + super(InviteClientTransaction, core, message, delegate); + this.confirmedDialogAcks = new Map(); + this.confirmedDialogs = new Map(); + this.earlyDialogs = new Map(); + this.delegate = delegate; + } + dispose() { + // 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((earlyDialog) => earlyDialog.dispose()); + this.earlyDialogs.clear(); + super.dispose(); + } + /** + * Special case for transport error while sending ACK. + * @param error - Transport error + */ + onTransportError(error) { + if (this.transaction.state === TransactionState.Calling) { + return super.onTransportError(error); + } + // If not in 'calling' state, the transport error occurred while sending an ACK. + this.logger.error(error.message); + this.logger.error("User agent client request transport error while sending ACK."); + } + /** + * 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. + */ + receiveResponse(message) { + if (!this.authenticationGuard(message)) { + return; + } + const 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 }); + } + 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 + { + // Dialogs are created through the generation of non-failure responses + // to requests with specific methods. Within this specification, only + // 2xx and 101-199 responses with a To tag, where the request was + // INVITE, will establish a dialog. A dialog established by a non-final + // response to a request is in the "early" state and it is called an + // early dialog. + // https://tools.ietf.org/html/rfc3261#section-12.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; + } + // 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. + // https://tools.ietf.org/html/rfc3261#section-12.1.1 + // Provisional without Contact header field, malformed response. + const contact = message.parseHeader("contact"); + if (!contact) { + this.logger.error("Non-100 1xx INVITE response received without a Contact header field, dropping."); + return; + } + // Compute dialog state. + const dialogState = Dialog.initialDialogStateForUserAgentClient(this.message, message); + // Have existing early dialog or create a new one. + let earlyDialog = this.earlyDialogs.get(dialogState.id); + if (!earlyDialog) { + const transaction = this.transaction; + if (!(transaction instanceof InviteClientTransaction)) { + throw new Error("Transaction not instance of InviteClientTransaction."); + } + earlyDialog = new 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 or is a retransmission, 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 === SignalingState.Initial || + earlyDialog.signalingState === SignalingState.HaveLocalOffer) { + earlyDialog.signalingStateTransition(message); + } + // Pass response to delegate. + const session = earlyDialog; + if (this.delegate && this.delegate.onProgress) { + this.delegate.onProgress({ + message, + session, + prack: (options) => { + const outgoingPrackRequest = session.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 + { + // Dialogs are created through the generation of non-failure responses + // to requests with specific methods. Within this specification, only + // 2xx and 101-199 responses with a To tag, where the request was + // INVITE, will establish a dialog. A dialog established by a non-final + // response to a request is in the "early" state and it is called an + // early dialog. + // https://tools.ietf.org/html/rfc3261#section-12.1 + // Final without to tag, malformed response. + if (!message.toTag) { + this.logger.error("2xx INVITE response received without a to tag, dropping."); + return; + } + // 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. + // https://tools.ietf.org/html/rfc3261#section-12.1.1 + // Final without Contact header field, malformed response. + const contact = message.parseHeader("contact"); + if (!contact) { + this.logger.error("2xx INVITE response received without a Contact header field, dropping."); + return; + } + // Compute dialog state. + const dialogState = 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. + let 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 + const outgoingAckRequest = this.confirmedDialogAcks.get(dialogState.id); + if (outgoingAckRequest) { + const transaction = this.transaction; + if (!(transaction instanceof 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 { + const transaction = this.transaction; + if (!(transaction instanceof InviteClientTransaction)) { + throw new Error("Transaction not instance of InviteClientTransaction."); + } + dialog = new 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 === SignalingState.Initial || + dialog.signalingState === SignalingState.HaveLocalOffer) { + dialog.signalingStateTransition(message); + } + // Session Initiated! :) + const session = 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, + session, + ack: (options) => { + const outgoingAckRequest = session.ack(options); + this.confirmedDialogAcks.set(session.id, outgoingAckRequest); + return outgoingAckRequest; + } + }); + } + else { + const outgoingAckRequest = session.ack(); + this.confirmedDialogAcks.set(session.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((earlyDialog) => 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 }); + } + 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((earlyDialog) => 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 }); + } + return; + default: + throw new Error(`Invalid status code ${statusCode}`); + } + throw new Error(`Executing what should be an unreachable code path receiving ${statusCode} response.`); + } +} diff --git a/lib/core/user-agents/invite-user-agent-server.d.ts b/lib/core/user-agents/invite-user-agent-server.d.ts new file mode 100644 index 000000000..54968462a --- /dev/null +++ b/lib/core/user-agents/invite-user-agent-server.d.ts @@ -0,0 +1,78 @@ +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 new file mode 100644 index 000000000..4f0e086ac --- /dev/null +++ b/lib/core/user-agents/invite-user-agent-server.d.ts.map @@ -0,0 +1 @@ +{"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;IAM7E,SAAS,CAAC,IAAI,EAAE,aAAa;IALzC,oCAAoC;IACpC,OAAO,CAAC,eAAe,CAA4B;IACnD,gCAAgC;IAChC,OAAO,CAAC,WAAW,CAA4B;gBAEzB,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,uBAAuB;IAIvG,OAAO,IAAI,IAAI;IAOtB;;;;;;;OAOG;IACI,MAAM,CAAC,OAAO,GAAE,eAAqC,GAAG,2BAA2B;IAsG1F;;;;;;;;;;;;;;;;;;;;;OAqBG;IACI,QAAQ,CAAC,OAAO,GAAE,eAAqC,GAAG,2BAA2B;IAgE5F;;;;;;;;;;;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 new file mode 100644 index 000000000..9ca0b6df3 --- /dev/null +++ b/lib/core/user-agents/invite-user-agent-server.js @@ -0,0 +1,232 @@ +import { Dialog, SessionDialog } from "../dialogs"; +import { TransactionStateError } from "../exceptions"; +import { SignalingState } from "../session"; +import { InviteServerTransaction } from "../transactions"; +import { AllowedMethods } from "../user-agent-core/allowed-methods"; +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 class InviteUserAgentServer extends UserAgentServer { + constructor(core, message, delegate) { + super(InviteServerTransaction, core, message, delegate); + this.core = core; + } + dispose() { + if (this.earlyDialog) { + this.earlyDialog.dispose(); + } + super.dispose(); + } + /** + * 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 = { statusCode: 200 }) { + if (!this.acceptable) { + throw new 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 { + const transaction = this.transaction; + if (!(transaction instanceof InviteServerTransaction)) { + throw new Error("Transaction not instance of InviteClientTransaction."); + } + const state = Dialog.initialDialogStateForUserAgentServer(this.message, this.toTag); + this.confirmedDialog = new 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 + const recordRouteHeader = this.message.getHeaders("record-route").map((header) => `Record-Route: ${header}`); + const 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. + const allowHeader = "Allow: " + 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 === SignalingState.Stable) { + options.body = this.confirmedDialog.answer; // resend the answer sent in provisional response + } + else if (this.confirmedDialog.signalingState === SignalingState.Initial || + this.confirmedDialog.signalingState === 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); + const response = super.accept(options); + const session = this.confirmedDialog; + const result = Object.assign(Object.assign({}, response), { 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 !== 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. + */ + progress(options = { statusCode: 180 }) { + if (!this.progressable) { + throw new 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) { + const transaction = this.transaction; + if (!(transaction instanceof InviteServerTransaction)) { + throw new Error("Transaction not instance of InviteClientTransaction."); + } + const state = Dialog.initialDialogStateForUserAgentServer(this.message, this.toTag, true); + this.earlyDialog = new 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 + const recordRouteHeader = this.message.getHeaders("record-route").map((header) => `Record-Route: ${header}`); + const contactHeader = `Contact: ${this.core.configuration.contact}`; + options.extraHeaders = options.extraHeaders || []; + options.extraHeaders = options.extraHeaders.concat(recordRouteHeader); + options.extraHeaders.push(contactHeader); + const response = super.progress(options); + const session = this.earlyDialog; + const result = Object.assign(Object.assign({}, response), { 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 !== 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. + */ + redirect(contacts, options = { statusCode: 302 }) { + return super.redirect(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. + */ + reject(options = { statusCode: 486 }) { + return super.reject(options); + } +} diff --git a/lib/core/user-agents/message-user-agent-client.d.ts b/lib/core/user-agents/message-user-agent-client.d.ts new file mode 100644 index 000000000..e8ca14058 --- /dev/null +++ b/lib/core/user-agents/message-user-agent-client.d.ts @@ -0,0 +1,11 @@ +import { OutgoingMessageRequest, OutgoingRequestDelegate, OutgoingRequestMessage } from "../messages"; +import { UserAgentCore } from "../user-agent-core"; +import { UserAgentClient } from "./user-agent-client"; +/** + * MESSAGE UAC. + * @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 new file mode 100644 index 000000000..0e10c72cd --- /dev/null +++ b/lib/core/user-agents/message-user-agent-client.d.ts.map @@ -0,0 +1 @@ +{"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;gBAC/E,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,uBAAuB;CAGrG"} \ 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 new file mode 100644 index 000000000..1606220fd --- /dev/null +++ b/lib/core/user-agents/message-user-agent-client.js @@ -0,0 +1,11 @@ +import { NonInviteClientTransaction } from "../transactions"; +import { UserAgentClient } from "./user-agent-client"; +/** + * MESSAGE UAC. + * @public + */ +export class MessageUserAgentClient extends UserAgentClient { + constructor(core, message, delegate) { + super(NonInviteClientTransaction, core, message, delegate); + } +} diff --git a/lib/core/user-agents/message-user-agent-server.d.ts b/lib/core/user-agents/message-user-agent-server.d.ts new file mode 100644 index 000000000..21f3c6a02 --- /dev/null +++ b/lib/core/user-agents/message-user-agent-server.d.ts @@ -0,0 +1,11 @@ +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 { + 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 new file mode 100644 index 000000000..25c19c262 --- /dev/null +++ b/lib/core/user-agents/message-user-agent-server.d.ts.map @@ -0,0 +1 @@ +{"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;gBAC/E,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,uBAAuB;CAGrG"} \ 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 new file mode 100644 index 000000000..7c94c20b4 --- /dev/null +++ b/lib/core/user-agents/message-user-agent-server.js @@ -0,0 +1,11 @@ +import { NonInviteServerTransaction } from "../transactions"; +import { UserAgentServer } from "./user-agent-server"; +/** + * MESSAGE UAS. + * @public + */ +export class MessageUserAgentServer extends UserAgentServer { + constructor(core, message, delegate) { + super(NonInviteServerTransaction, core, message, delegate); + } +} diff --git a/lib/core/user-agents/notify-user-agent-client.d.ts b/lib/core/user-agents/notify-user-agent-client.d.ts new file mode 100644 index 000000000..2bbd23eac --- /dev/null +++ b/lib/core/user-agents/notify-user-agent-client.d.ts @@ -0,0 +1,11 @@ +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 new file mode 100644 index 000000000..ada9a9754 --- /dev/null +++ b/lib/core/user-agents/notify-user-agent-client.d.ts.map @@ -0,0 +1 @@ +{"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;gBAC7E,MAAM,EAAE,aAAa,EAAE,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc;CAIhG"} \ 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 new file mode 100644 index 000000000..e29ff2ebf --- /dev/null +++ b/lib/core/user-agents/notify-user-agent-client.js @@ -0,0 +1,13 @@ +import { C } from "../messages"; +import { NonInviteClientTransaction } from "../transactions"; +import { UserAgentClient } from "./user-agent-client"; +/** + * NOTIFY UAS. + * @public + */ +export class NotifyUserAgentClient extends UserAgentClient { + constructor(dialog, delegate, options) { + const message = dialog.createOutgoingRequestMessage(C.NOTIFY, options); + super(NonInviteClientTransaction, dialog.userAgentCore, message, delegate); + } +} diff --git a/lib/core/user-agents/notify-user-agent-server.d.ts b/lib/core/user-agents/notify-user-agent-server.d.ts new file mode 100644 index 000000000..9a22df7ca --- /dev/null +++ b/lib/core/user-agents/notify-user-agent-server.d.ts @@ -0,0 +1,17 @@ +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 new file mode 100644 index 000000000..8bceaf25c --- /dev/null +++ b/lib/core/user-agents/notify-user-agent-server.d.ts.map @@ -0,0 +1 @@ +{"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;AAOtD;;;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;CAKrC"} \ 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 new file mode 100644 index 000000000..b025c77c5 --- /dev/null +++ b/lib/core/user-agents/notify-user-agent-server.js @@ -0,0 +1,21 @@ +import { NonInviteServerTransaction } from "../transactions"; +import { UserAgentServer } from "./user-agent-server"; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function instanceOfDialog(object) { + return object.userAgentCore !== undefined; +} +/** + * NOTIFY UAS. + * @public + */ +export class NotifyUserAgentServer extends UserAgentServer { + /** + * 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, message, delegate) { + const userAgentCore = instanceOfDialog(dialogOrCore) ? dialogOrCore.userAgentCore : dialogOrCore; + super(NonInviteServerTransaction, userAgentCore, message, delegate); + } +} diff --git a/lib/core/user-agents/prack-user-agent-client.d.ts b/lib/core/user-agents/prack-user-agent-client.d.ts new file mode 100644 index 000000000..b7dea252a --- /dev/null +++ b/lib/core/user-agents/prack-user-agent-client.d.ts @@ -0,0 +1,11 @@ +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 new file mode 100644 index 000000000..54c8effac --- /dev/null +++ b/lib/core/user-agents/prack-user-agent-client.d.ts.map @@ -0,0 +1 @@ +{"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;gBAC3E,MAAM,EAAE,aAAa,EAAE,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc;CAKhG"} \ 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 new file mode 100644 index 000000000..e5477d456 --- /dev/null +++ b/lib/core/user-agents/prack-user-agent-client.js @@ -0,0 +1,14 @@ +import { C } from "../messages"; +import { NonInviteClientTransaction } from "../transactions"; +import { UserAgentClient } from "./user-agent-client"; +/** + * PRACK UAC. + * @public + */ +export class PrackUserAgentClient extends UserAgentClient { + constructor(dialog, delegate, options) { + const message = dialog.createOutgoingRequestMessage(C.PRACK, options); + super(NonInviteClientTransaction, dialog.userAgentCore, message, delegate); + dialog.signalingStateTransition(message); + } +} diff --git a/lib/core/user-agents/prack-user-agent-server.d.ts b/lib/core/user-agents/prack-user-agent-server.d.ts new file mode 100644 index 000000000..ecc1fc075 --- /dev/null +++ b/lib/core/user-agents/prack-user-agent-server.d.ts @@ -0,0 +1,17 @@ +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 new file mode 100644 index 000000000..e222d765c --- /dev/null +++ b/lib/core/user-agents/prack-user-agent-server.d.ts.map @@ -0,0 +1 @@ +{"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;gBAElB,MAAM,EAAE,aAAa,EAAE,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,uBAAuB;IAOtG;;;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 new file mode 100644 index 000000000..8fdf74919 --- /dev/null +++ b/lib/core/user-agents/prack-user-agent-server.js @@ -0,0 +1,25 @@ +import { NonInviteServerTransaction } from "../transactions"; +import { UserAgentServer } from "./user-agent-server"; +/** + * PRACK UAS. + * @public + */ +export class PrackUserAgentServer extends UserAgentServer { + constructor(dialog, message, delegate) { + super(NonInviteServerTransaction, dialog.userAgentCore, message, delegate); + // Update dialog signaling state with offer/answer in body + dialog.signalingStateTransition(message); + this.dialog = dialog; + } + /** + * Update the dialog signaling state on a 2xx response. + * @param options - Options bucket. + */ + accept(options = { statusCode: 200 }) { + if (options.body) { + // Update dialog signaling state with offer/answer in body + this.dialog.signalingStateTransition(options.body); + } + return super.accept(options); + } +} diff --git a/lib/core/user-agents/publish-user-agent-client.d.ts b/lib/core/user-agents/publish-user-agent-client.d.ts new file mode 100644 index 000000000..d63bc4e8d --- /dev/null +++ b/lib/core/user-agents/publish-user-agent-client.d.ts @@ -0,0 +1,11 @@ +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 new file mode 100644 index 000000000..09255237d --- /dev/null +++ b/lib/core/user-agents/publish-user-agent-client.d.ts.map @@ -0,0 +1 @@ +{"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;gBAC/E,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,uBAAuB;CAGrG"} \ 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 new file mode 100644 index 000000000..13b21521a --- /dev/null +++ b/lib/core/user-agents/publish-user-agent-client.js @@ -0,0 +1,11 @@ +import { NonInviteClientTransaction } from "../transactions"; +import { UserAgentClient } from "./user-agent-client"; +/** + * PUBLISH UAC. + * @public + */ +export class PublishUserAgentClient extends UserAgentClient { + constructor(core, message, delegate) { + super(NonInviteClientTransaction, core, message, delegate); + } +} 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 new file mode 100644 index 000000000..bdb157024 --- /dev/null +++ b/lib/core/user-agents/re-invite-user-agent-client.d.ts @@ -0,0 +1,19 @@ +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 new file mode 100644 index 000000000..29f9cee61 --- /dev/null +++ b/lib/core/user-agents/re-invite-user-agent-client.d.ts.map @@ -0,0 +1 @@ +{"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;gBAElB,MAAM,EAAE,aAAa,EAAE,QAAQ,CAAC,EAAE,6BAA6B,EAAE,OAAO,CAAC,EAAE,cAAc;IAUrG,SAAS,CAAC,eAAe,CAAC,OAAO,EAAE,uBAAuB,GAAG,IAAI;CAyFlE"} \ 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 new file mode 100644 index 000000000..23399896e --- /dev/null +++ b/lib/core/user-agents/re-invite-user-agent-client.js @@ -0,0 +1,108 @@ +import { C } from "../messages"; +import { InviteClientTransaction } from "../transactions"; +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 class ReInviteUserAgentClient extends UserAgentClient { + constructor(dialog, delegate, options) { + const message = dialog.createOutgoingRequestMessage(C.INVITE, options); + super(InviteClientTransaction, dialog.userAgentCore, message, delegate); + 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; + } + receiveResponse(message) { + if (!this.authenticationGuard(message, this.dialog)) { + return; + } + const 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 }); + } + break; + case /^1[0-9]{2}$/.test(statusCode): + if (this.delegate && this.delegate.onProgress) { + this.delegate.onProgress({ + message, + session: this.dialog, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + prack: (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, + session: this.dialog, + ack: (options) => { + const 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 }); + } + 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 }); + } + 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}`); + } + } +} 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 new file mode 100644 index 000000000..8083bb671 --- /dev/null +++ b/lib/core/user-agents/re-invite-user-agent-server.d.ts @@ -0,0 +1,42 @@ +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 new file mode 100644 index 000000000..08deb75fb --- /dev/null +++ b/lib/core/user-agents/re-invite-user-agent-server.d.ts.map @@ -0,0 +1 @@ +{"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;gBAElB,MAAM,EAAE,aAAa,EAAE,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,uBAAuB;IAMtG;;;OAGG;IACI,MAAM,CAAC,OAAO,GAAE,eAAqC,GAAG,2BAA2B;IA8B1F;;;OAGG;IACI,QAAQ,CAAC,OAAO,GAAE,eAAqC,GAAG,2BAA2B;IAc5F;;;;OAIG;IAEI,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 new file mode 100644 index 000000000..afac1c31a --- /dev/null +++ b/lib/core/user-agents/re-invite-user-agent-server.js @@ -0,0 +1,86 @@ +import { InviteServerTransaction } from "../transactions"; +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 class ReInviteUserAgentServer extends UserAgentServer { + constructor(dialog, message, delegate) { + super(InviteServerTransaction, dialog.userAgentCore, message, delegate); + dialog.reinviteUserAgentServer = this; + this.dialog = dialog; + } + /** + * Update the dialog signaling state on a 2xx response. + * @param options - Options bucket. + */ + accept(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((route) => `Record-Route: ${route}`)); + // Send and return the response + const response = super.accept(options); + const session = this.dialog; + const result = Object.assign(Object.assign({}, response), { 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. + */ + progress(options = { statusCode: 180 }) { + // Send and return the response + const response = super.progress(options); + const session = this.dialog; + const result = Object.assign(Object.assign({}, response), { 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. + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + redirect(contacts, 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. + */ + reject(options = { statusCode: 488 }) { + this.dialog.signalingStateRollback(); + this.dialog.reinviteUserAgentServer = undefined; // ACK will be handled by transaction + return super.reject(options); + } +} 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 new file mode 100644 index 000000000..75183c74c --- /dev/null +++ b/lib/core/user-agents/re-subscribe-user-agent-client.d.ts @@ -0,0 +1,18 @@ +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 new file mode 100644 index 000000000..9a65ba290 --- /dev/null +++ b/lib/core/user-agents/re-subscribe-user-agent-client.d.ts.map @@ -0,0 +1 @@ +{"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;gBAEvB,MAAM,EAAE,kBAAkB,EAAE,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc;IAM7F,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 new file mode 100644 index 000000000..15807215c --- /dev/null +++ b/lib/core/user-agents/re-subscribe-user-agent-client.js @@ -0,0 +1,65 @@ +import { C } from "../messages"; +import { NonInviteClientTransaction } from "../transactions"; +import { UserAgentClient } from "./user-agent-client"; +/** + * Re-SUBSCRIBE UAC. + * @public + */ +export class ReSubscribeUserAgentClient extends UserAgentClient { + constructor(dialog, delegate, options) { + const message = dialog.createOutgoingRequestMessage(C.SUBSCRIBE, options); + super(NonInviteClientTransaction, dialog.userAgentCore, message, delegate); + this.dialog = dialog; + } + waitNotifyStop() { + // TODO: Placeholder. Not utilized currently. + return; + } + /** + * Receive a response from the transaction layer. + * @param message - Incoming response message. + */ + receiveResponse(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 + const expires = message.getHeader("Expires"); + if (!expires) { + this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE"); + } + else { + const 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 + const 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.receiveResponse(message); + } +} 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 new file mode 100644 index 000000000..0a11912a4 --- /dev/null +++ b/lib/core/user-agents/re-subscribe-user-agent-server.d.ts @@ -0,0 +1,11 @@ +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 new file mode 100644 index 000000000..7400f6a4d --- /dev/null +++ b/lib/core/user-agents/re-subscribe-user-agent-server.d.ts.map @@ -0,0 +1 @@ +{"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;gBACrF,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,uBAAuB;CAGhG"} \ 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 new file mode 100644 index 000000000..e97ae98e1 --- /dev/null +++ b/lib/core/user-agents/re-subscribe-user-agent-server.js @@ -0,0 +1,11 @@ +import { NonInviteServerTransaction } from "../transactions"; +import { UserAgentServer } from "./user-agent-server"; +/** + * Re-SUBSCRIBE UAS. + * @public + */ +export class ReSubscribeUserAgentServer extends UserAgentServer { + constructor(dialog, message, delegate) { + super(NonInviteServerTransaction, dialog.userAgentCore, message, delegate); + } +} diff --git a/lib/core/user-agents/refer-user-agent-client.d.ts b/lib/core/user-agents/refer-user-agent-client.d.ts new file mode 100644 index 000000000..92e14d6f7 --- /dev/null +++ b/lib/core/user-agents/refer-user-agent-client.d.ts @@ -0,0 +1,11 @@ +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 new file mode 100644 index 000000000..20d33b578 --- /dev/null +++ b/lib/core/user-agents/refer-user-agent-client.d.ts.map @@ -0,0 +1 @@ +{"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;gBAC3E,MAAM,EAAE,aAAa,EAAE,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc;CAIhG"} \ 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 new file mode 100644 index 000000000..abefcbbf6 --- /dev/null +++ b/lib/core/user-agents/refer-user-agent-client.js @@ -0,0 +1,13 @@ +import { C } from "../messages"; +import { NonInviteClientTransaction } from "../transactions"; +import { UserAgentClient } from "./user-agent-client"; +/** + * REFER UAC. + * @public + */ +export class ReferUserAgentClient extends UserAgentClient { + constructor(dialog, delegate, options) { + const message = dialog.createOutgoingRequestMessage(C.REFER, options); + super(NonInviteClientTransaction, dialog.userAgentCore, message, delegate); + } +} diff --git a/lib/core/user-agents/refer-user-agent-server.d.ts b/lib/core/user-agents/refer-user-agent-server.d.ts new file mode 100644 index 000000000..8203a6445 --- /dev/null +++ b/lib/core/user-agents/refer-user-agent-server.d.ts @@ -0,0 +1,17 @@ +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 new file mode 100644 index 000000000..735fcd7f5 --- /dev/null +++ b/lib/core/user-agents/refer-user-agent-server.d.ts.map @@ -0,0 +1 @@ +{"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;AAOtD;;;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;CAKrC"} \ 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 new file mode 100644 index 000000000..34492b359 --- /dev/null +++ b/lib/core/user-agents/refer-user-agent-server.js @@ -0,0 +1,21 @@ +import { NonInviteServerTransaction } from "../transactions"; +import { UserAgentServer } from "./user-agent-server"; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function instanceOfSessionDialog(object) { + return object.userAgentCore !== undefined; +} +/** + * REFER UAS. + * @public + */ +export class ReferUserAgentServer extends UserAgentServer { + /** + * REFER UAS constructor. + * @param dialogOrCore - Dialog for in dialog REFER, UserAgentCore for out of dialog REFER. + * @param message - Incoming REFER request message. + */ + constructor(dialogOrCore, message, delegate) { + const userAgentCore = instanceOfSessionDialog(dialogOrCore) ? dialogOrCore.userAgentCore : dialogOrCore; + super(NonInviteServerTransaction, userAgentCore, message, delegate); + } +} diff --git a/lib/core/user-agents/register-user-agent-client.d.ts b/lib/core/user-agents/register-user-agent-client.d.ts new file mode 100644 index 000000000..71e4150be --- /dev/null +++ b/lib/core/user-agents/register-user-agent-client.d.ts @@ -0,0 +1,11 @@ +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 new file mode 100644 index 000000000..82113b017 --- /dev/null +++ b/lib/core/user-agents/register-user-agent-client.d.ts.map @@ -0,0 +1 @@ +{"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;gBACjF,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,uBAAuB;CAGrG"} \ 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 new file mode 100644 index 000000000..be483bf61 --- /dev/null +++ b/lib/core/user-agents/register-user-agent-client.js @@ -0,0 +1,11 @@ +import { NonInviteClientTransaction } from "../transactions"; +import { UserAgentClient } from "./user-agent-client"; +/** + * REGISTER UAC. + * @public + */ +export class RegisterUserAgentClient extends UserAgentClient { + constructor(core, message, delegate) { + super(NonInviteClientTransaction, core, message, delegate); + } +} diff --git a/lib/core/user-agents/register-user-agent-server.d.ts b/lib/core/user-agents/register-user-agent-server.d.ts new file mode 100644 index 000000000..b9f6ce296 --- /dev/null +++ b/lib/core/user-agents/register-user-agent-server.d.ts @@ -0,0 +1,12 @@ +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 new file mode 100644 index 000000000..6b7cc9df7 --- /dev/null +++ b/lib/core/user-agents/register-user-agent-server.d.ts.map @@ -0,0 +1 @@ +{"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;IACjF,SAAS,CAAC,IAAI,EAAE,aAAa;gBAAnB,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,uBAAuB;CAG/G"} \ 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 new file mode 100644 index 000000000..c6ce3507c --- /dev/null +++ b/lib/core/user-agents/register-user-agent-server.js @@ -0,0 +1,12 @@ +import { NonInviteServerTransaction } from "../transactions"; +import { UserAgentServer } from "./user-agent-server"; +/** + * REGISTER UAS. + * @public + */ +export class RegisterUserAgentServer extends UserAgentServer { + constructor(core, message, delegate) { + super(NonInviteServerTransaction, core, message, delegate); + this.core = core; + } +} diff --git a/lib/core/user-agents/subscribe-user-agent-client.d.ts b/lib/core/user-agents/subscribe-user-agent-client.d.ts new file mode 100644 index 000000000..12ba96540 --- /dev/null +++ b/lib/core/user-agents/subscribe-user-agent-client.d.ts @@ -0,0 +1,66 @@ +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 requests. + * @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 associated 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 timerN; +} +//# 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 new file mode 100644 index 000000000..93dc42d26 --- /dev/null +++ b/lib/core/user-agents/subscribe-user-agent-client.d.ts.map @@ -0,0 +1 @@ +{"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,CAAqB;gBAElB,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,gCAAgC;IAwB7G;;;;;;;;OAQG;IACI,OAAO,IAAI,IAAI;IAItB;;;;OAIG;IACI,QAAQ,CAAC,GAAG,EAAE,qBAAqB,GAAG,IAAI;IAgK1C,eAAe,IAAI,IAAI;IASvB,cAAc,IAAI,IAAI;IAU7B;;;OAGG;IACH,SAAS,CAAC,eAAe,CAAC,OAAO,EAAE,uBAAuB,GAAG,IAAI;IAyDjE;;;;;;;;OAQG;IACH,OAAO,CAAC,MAAM;CAOf"} \ 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 new file mode 100644 index 000000000..583d7a83c --- /dev/null +++ b/lib/core/user-agents/subscribe-user-agent-client.js @@ -0,0 +1,287 @@ +import { SubscriptionDialog } from "../dialogs/subscription-dialog"; +import { SubscriptionState } from "../subscription"; +import { Timers } from "../timers"; +import { NonInviteClientTransaction } from "../transactions"; +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 requests. + * @public + */ +export class SubscribeUserAgentClient extends UserAgentClient { + constructor(core, message, delegate) { + // Get event from request message. + const event = message.getHeader("Event"); + if (!event) { + throw new Error("Event undefined"); + } + // Get expires from request message. + const expires = message.getHeader("Expires"); + if (!expires) { + throw new Error("Expires undefined"); + } + super(NonInviteClientTransaction, core, message, delegate); + 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 = SubscriptionState.NotifyWait; + // Start waiting for a NOTIFY we can use to create a subscription. + this.waitNotifyStart(); + } + /** + * 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() { + super.dispose(); + } + /** + * Handle out of dialog NOTIFY associated 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) { + // 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 + const 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 + const 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. + const 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 + const 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 multiple subscriptions. + // As such and in accordance with the specification, 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 subscription state. + switch (state) { + case "pending": + this.subscriptionState = SubscriptionState.Pending; + break; + case "active": + this.subscriptionState = SubscriptionState.Active; + break; + case "terminated": + this.subscriptionState = 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 !== 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 + const dialogState = SubscriptionDialog.initialDialogStateForSubscription(this.message, uas.message); + // Subscription Initiated! :) + this.dialog = new SubscriptionDialog(this.subscriptionEvent, this.subscriptionExpires, this.subscriptionState, this.core, dialogState); + } + // Delegate. + if (this.delegate && this.delegate.onNotify) { + const request = uas; + const subscription = this.dialog; + this.delegate.onNotify({ request, subscription }); + } + else { + uas.accept(); + } + } + waitNotifyStart() { + 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(() => this.timerN(), Timers.TIMER_N); + } + } + waitNotifyStop() { + 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. + */ + receiveResponse(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 + const expires = message.getHeader("Expires"); + if (!expires) { + this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE"); + } + else { + const 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.receiveResponse(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 + */ + timerN() { + 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(); + } + } +} diff --git a/lib/core/user-agents/subscribe-user-agent-server.d.ts b/lib/core/user-agents/subscribe-user-agent-server.d.ts new file mode 100644 index 000000000..ad65a8261 --- /dev/null +++ b/lib/core/user-agents/subscribe-user-agent-server.d.ts @@ -0,0 +1,12 @@ +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 new file mode 100644 index 000000000..5a807c08c --- /dev/null +++ b/lib/core/user-agents/subscribe-user-agent-server.d.ts.map @@ -0,0 +1 @@ +{"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;IACnF,SAAS,CAAC,IAAI,EAAE,aAAa;gBAAnB,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,uBAAuB;CAG/G"} \ 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 new file mode 100644 index 000000000..0a74d226d --- /dev/null +++ b/lib/core/user-agents/subscribe-user-agent-server.js @@ -0,0 +1,12 @@ +import { NonInviteServerTransaction } from "../transactions"; +import { UserAgentServer } from "./user-agent-server"; +/** + * SUBSCRIBE UAS. + * @public + */ +export class SubscribeUserAgentServer extends UserAgentServer { + constructor(core, message, delegate) { + super(NonInviteServerTransaction, core, message, delegate); + this.core = core; + } +} diff --git a/lib/core/user-agents/user-agent-client.d.ts b/lib/core/user-agents/user-agent-client.d.ts new file mode 100644 index 000000000..bef772398 --- /dev/null +++ b/lib/core/user-agents/user-agent-client.d.ts @@ -0,0 +1,104 @@ +import { Dialog } from "../dialogs"; +import { TransportError } from "../exceptions"; +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; + get loggerFactory(): LoggerFactory; + /** The transaction associated with this request. */ + get 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. + * @param dialog - If defined, the dialog within which the response was received. + * @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, dialog?: Dialog): boolean; + /** + * 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 + */ + protected onRequestTimeout(): void; + /** + * 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 + * @param error - Transport error + */ + protected onTransportError(error: TransportError): void; + /** + * Receive a response from the transaction layer. + * @param message - Incoming response message. + */ + protected receiveResponse(message: IncomingResponseMessage): void; + private init; +} +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 new file mode 100644 index 000000000..3744966e9 --- /dev/null +++ b/lib/core/user-agents/user-agent-client.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"user-agent-client.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/user-agent-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AACpC,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAC/C,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;IAWnD,OAAO,CAAC,sBAAsB;IAC9B,SAAS,CAAC,IAAI,EAAE,aAAa;IACtB,OAAO,EAAE,sBAAsB;IAC/B,QAAQ,CAAC;IAblB,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC;IAEzB,OAAO,CAAC,YAAY,CAAgC;IAGpD,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;IAItB,IAAI,aAAa,IAAI,aAAa,CAEjC;IAED,oDAAoD;IACpD,IAAI,WAAW,IAAI,iBAAiB,CAKnC;IAED;;;;;;OAMG;IACI,MAAM,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,OAAO,GAAE,cAAmB,GAAG,sBAAsB;IA4EpF;;;;;;;;;;;;;;;;;;;;;OAqBG;IACH,SAAS,CAAC,mBAAmB,CAAC,OAAO,EAAE,uBAAuB,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO;IA+EzF;;;;;;;;;;;OAWG;IACH,SAAS,CAAC,gBAAgB,IAAI,IAAI;IASlC;;;;;;;;;;;;OAYG;IACH,SAAS,CAAC,gBAAgB,CAAC,KAAK,EAAE,cAAc,GAAG,IAAI;IASvD;;;OAGG;IACH,SAAS,CAAC,eAAe,CAAC,OAAO,EAAE,uBAAuB,GAAG,IAAI;IAyCjE,OAAO,CAAC,IAAI;CA6Bb"} \ 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 new file mode 100644 index 000000000..a492ae038 --- /dev/null +++ b/lib/core/user-agents/user-agent-client.js @@ -0,0 +1,309 @@ +import { C, IncomingResponseMessage } from "../messages"; +import { NonInviteClientTransaction, TransactionState } from "../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 + */ +export class UserAgentClient { + constructor(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(); + } + dispose() { + this.transaction.dispose(); + } + get loggerFactory() { + return this.core.loggerFactory; + } + /** The transaction associated with this request. */ + get transaction() { + if (!this._transaction) { + throw new Error("Transaction undefined."); + } + return this._transaction; + } + /** + * 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, 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 + const message = this.core.makeOutgoingRequestMessage(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 === TransactionState.Proceeding) { + new UserAgentClient(NonInviteClientTransaction, this.core, message); + } + else { + this.transaction.addStateChangeListener(() => { + if (this.transaction && this.transaction.state === TransactionState.Proceeding) { + new UserAgentClient(NonInviteClientTransaction, this.core, message); + } + }, { once: true }); + } + 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. + * @param dialog - If defined, the dialog within which the response was received. + * @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. + */ + authenticationGuard(message, dialog) { + const 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. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let challenge; + let 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; + } + // If response to out of dialog request, assume incrementing the CSeq will suffice. + let cseq = (this.message.cseq += 1); + // If response to in dialog request, get a valid next CSeq number. + if (dialog && dialog.localSequenceNumber) { + dialog.incrementLocalSequenceNumber(); + cseq = this.message.cseq = dialog.localSequenceNumber; + } + 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; + } + /** + * 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 + */ + onRequestTimeout() { + this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout."); + const message = new 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 + * @param error - Transport error + */ + onTransportError(error) { + this.logger.error(error.message); + this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable."); + const message = new IncomingResponseMessage(); + message.statusCode = 503; + message.reasonPhrase = "Service Unavailable"; + this.receiveResponse(message); + } + /** + * Receive a response from the transaction layer. + * @param message - Incoming response message. + */ + receiveResponse(message) { + if (!this.authenticationGuard(message)) { + return; + } + const 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 }); + } + break; + case /^1[0-9]{2}$/.test(statusCode): + if (this.delegate && this.delegate.onProgress) { + this.delegate.onProgress({ message }); + } + break; + case /^2[0-9]{2}$/.test(statusCode): + if (this.delegate && this.delegate.onAccept) { + this.delegate.onAccept({ message }); + } + break; + case /^3[0-9]{2}$/.test(statusCode): + if (this.delegate && this.delegate.onRedirect) { + this.delegate.onRedirect({ message }); + } + break; + case /^[4-6][0-9]{2}$/.test(statusCode): + if (this.delegate && this.delegate.onReject) { + this.delegate.onReject({ message }); + } + break; + default: + throw new Error(`Invalid status code ${statusCode}`); + } + } + init() { + // We are the transaction user. + const user = { + loggerFactory: this.loggerFactory, + onRequestTimeout: () => this.onRequestTimeout(), + onStateChange: (newState) => { + if (newState === TransactionState.Terminated) { + // Remove the terminated transaction from the core. + // eslint-disable-next-line @typescript-eslint/no-use-before-define + 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. + // eslint-disable-next-line @typescript-eslint/no-use-before-define + if (transaction === this._transaction) { + this.dispose(); + } + } + }, + onTransportError: (error) => this.onTransportError(error), + receiveResponse: (message) => this.receiveResponse(message) + }; + // Create a new transaction with us as the user. + const transaction = new this.transactionConstructor(this.message, this.core.transport, user); + this._transaction = transaction; + // Add the new transaction to the core. + const userAgentClientId = transaction.id + transaction.request.method; + this.core.userAgentClients.set(userAgentClientId, this); + } +} diff --git a/lib/core/user-agents/user-agent-server.d.ts b/lib/core/user-agents/user-agent-server.d.ts new file mode 100644 index 000000000..807a60604 --- /dev/null +++ b/lib/core/user-agents/user-agent-server.d.ts @@ -0,0 +1,80 @@ +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; + get loggerFactory(): LoggerFactory; + /** The transaction associated with this request. */ + get 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 get acceptable(): boolean; + protected get progressable(): boolean; + protected get redirectable(): boolean; + protected get rejectable(): boolean; + protected get 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 new file mode 100644 index 000000000..8474aa6d7 --- /dev/null +++ b/lib/core/user-agents/user-agent-server.d.ts.map @@ -0,0 +1 @@ +{"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;IAItB,IAAI,aAAa,IAAI,aAAa,CAEjC;IAED,oDAAoD;IACpD,IAAI,WAAW,IAAI,iBAAiB,CAKnC;IAEM,MAAM,CAAC,OAAO,GAAE,eAAqC,GAAG,gBAAgB;IAYxE,QAAQ,CAAC,OAAO,GAAE,eAAqC,GAAG,gBAAgB;IAY1E,QAAQ,CAAC,QAAQ,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,OAAO,GAAE,eAAqC,GAAG,gBAAgB;IAehG,MAAM,CAAC,OAAO,GAAE,eAAqC,GAAG,gBAAgB;IAaxE,MAAM,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,gBAAgB;IAQ1D;;;;;;;;;;;;;;;;;OAiBG;IACI,aAAa,CAAC,OAAO,EAAE,sBAAsB,GAAG,IAAI;IAW3D,SAAS,KAAK,UAAU,IAAI,OAAO,CAYlC;IAED,SAAS,KAAK,YAAY,IAAI,OAAO,CAQpC;IAED,SAAS,KAAK,YAAY,IAAI,OAAO,CAUpC;IAED,SAAS,KAAK,UAAU,IAAI,OAAO,CAUlC;IAED,SAAS,KAAK,UAAU,IAAI,OAAO,CAQlC;IAED;;;;;;;;;;;;OAYG;IACH,OAAO,CAAC,KAAK;IAWb,OAAO,CAAC,IAAI;CA4Bb"} \ 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 new file mode 100644 index 000000000..b33cd37bb --- /dev/null +++ b/lib/core/user-agents/user-agent-server.js @@ -0,0 +1,222 @@ +import { TransactionStateError } from "../exceptions"; +import { constructOutgoingResponse } from "../messages"; +import { newTag } from "../messages/utils"; +import { InviteServerTransaction, NonInviteServerTransaction, TransactionState } from "../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 + */ +export class UserAgentServer { + constructor(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 : newTag(); + this.init(); + } + dispose() { + this.transaction.dispose(); + } + get loggerFactory() { + return this.core.loggerFactory; + } + /** The transaction associated with this request. */ + get transaction() { + if (!this._transaction) { + throw new Error("Transaction undefined."); + } + return this._transaction; + } + accept(options = { statusCode: 200 }) { + if (!this.acceptable) { + throw new TransactionStateError(`${this.message.method} not acceptable in state ${this.transaction.state}.`); + } + const statusCode = options.statusCode; + if (statusCode < 200 || statusCode > 299) { + throw new TypeError(`Invalid statusCode: ${statusCode}`); + } + const response = this.reply(options); + return response; + } + progress(options = { statusCode: 180 }) { + if (!this.progressable) { + throw new TransactionStateError(`${this.message.method} not progressable in state ${this.transaction.state}.`); + } + const statusCode = options.statusCode; + if (statusCode < 101 || statusCode > 199) { + throw new TypeError(`Invalid statusCode: ${statusCode}`); + } + const response = this.reply(options); + return response; + } + redirect(contacts, options = { statusCode: 302 }) { + if (!this.redirectable) { + throw new TransactionStateError(`${this.message.method} not redirectable in state ${this.transaction.state}.`); + } + const statusCode = options.statusCode; + if (statusCode < 300 || statusCode > 399) { + throw new TypeError(`Invalid statusCode: ${statusCode}`); + } + const contactHeaders = new Array(); + contacts.forEach((contact) => contactHeaders.push(`Contact: ${contact.toString()}`)); + options.extraHeaders = (options.extraHeaders || []).concat(contactHeaders); + const response = this.reply(options); + return response; + } + reject(options = { statusCode: 480 }) { + if (!this.rejectable) { + throw new TransactionStateError(`${this.message.method} not rejectable in state ${this.transaction.state}.`); + } + const statusCode = options.statusCode; + if (statusCode < 400 || statusCode > 699) { + throw new TypeError(`Invalid statusCode: ${statusCode}`); + } + const response = this.reply(options); + return response; + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + trying(options) { + if (!this.tryingable) { + throw new TransactionStateError(`${this.message.method} not tryingable in state ${this.transaction.state}.`); + } + const 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. + */ + receiveCancel(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); + } + } + get acceptable() { + if (this.transaction instanceof InviteServerTransaction) { + return (this.transaction.state === TransactionState.Proceeding || this.transaction.state === TransactionState.Accepted); + } + if (this.transaction instanceof NonInviteServerTransaction) { + return (this.transaction.state === TransactionState.Trying || this.transaction.state === TransactionState.Proceeding); + } + throw new Error("Unknown transaction type."); + } + get progressable() { + if (this.transaction instanceof InviteServerTransaction) { + return this.transaction.state === TransactionState.Proceeding; + } + if (this.transaction instanceof NonInviteServerTransaction) { + return false; // https://tools.ietf.org/html/rfc4320#section-4.1 + } + throw new Error("Unknown transaction type."); + } + get redirectable() { + if (this.transaction instanceof InviteServerTransaction) { + return this.transaction.state === TransactionState.Proceeding; + } + if (this.transaction instanceof NonInviteServerTransaction) { + return (this.transaction.state === TransactionState.Trying || this.transaction.state === TransactionState.Proceeding); + } + throw new Error("Unknown transaction type."); + } + get rejectable() { + if (this.transaction instanceof InviteServerTransaction) { + return this.transaction.state === TransactionState.Proceeding; + } + if (this.transaction instanceof NonInviteServerTransaction) { + return (this.transaction.state === TransactionState.Trying || this.transaction.state === TransactionState.Proceeding); + } + throw new Error("Unknown transaction type."); + } + get tryingable() { + if (this.transaction instanceof InviteServerTransaction) { + return this.transaction.state === TransactionState.Proceeding; + } + if (this.transaction instanceof NonInviteServerTransaction) { + return this.transaction.state === TransactionState.Trying; + } + throw new Error("Unknown transaction type."); + } + /** + * 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. + */ + reply(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; + const response = constructOutgoingResponse(this.message, options); + this.transaction.receiveResponse(options.statusCode, response.message); + return response; + } + init() { + // We are the transaction user. + const user = { + loggerFactory: this.loggerFactory, + onStateChange: (newState) => { + if (newState === TransactionState.Terminated) { + // Remove the terminated transaction from the core. + // eslint-disable-next-line @typescript-eslint/no-use-before-define + this.core.userAgentServers.delete(userAgentServerId); + this.dispose(); + } + }, + onTransportError: (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. + const transaction = new this.transactionConstructor(this.message, this.core.transport, user); + this._transaction = transaction; + // Add the new transaction to the core. + const userAgentServerId = transaction.id; + this.core.userAgentServers.set(transaction.id, this); + } +} diff --git a/lib/grammar/grammar.d.ts b/lib/grammar/grammar.d.ts new file mode 100644 index 000000000..656d32dfd --- /dev/null +++ b/lib/grammar/grammar.d.ts @@ -0,0 +1,27 @@ +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/grammar/grammar.d.ts.map b/lib/grammar/grammar.d.ts.map new file mode 100644 index 000000000..597a2ca5d --- /dev/null +++ b/lib/grammar/grammar.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"grammar.d.ts","sourceRoot":"","sources":["../../src/grammar/grammar.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAE,GAAG,EAAE,MAAM,OAAO,CAAC;AAE5B;;;GAGG;AACH,yBAAiB,OAAO,CAAC;IAEvB;;;;OAIG;IAEH,SAAgB,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,GAAG,CAU3D;IAED;;;;OAIG;IACH,SAAgB,mBAAmB,CAAC,cAAc,EAAE,MAAM,GAAG,cAAc,GAAG,SAAS,CAKtF;IAED;;;;OAIG;IACH,SAAgB,QAAQ,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,GAAG,SAAS,CAKrD;CACF"} \ No newline at end of file diff --git a/lib/grammar/grammar.js b/lib/grammar/grammar.js new file mode 100644 index 000000000..1f6bdae99 --- /dev/null +++ b/lib/grammar/grammar.js @@ -0,0 +1,50 @@ +/* eslint-disable @typescript-eslint/no-namespace */ +/* eslint-disable no-inner-declarations */ +import * as pegGrammar from "./pegjs/dist/grammar"; +/** + * Grammar. + * @internal + */ +export var Grammar; +(function (Grammar) { + /** + * Parse. + * @param input - + * @param startRule - + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + function parse(input, startRule) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const options = { 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) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const 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) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const parsedUri = Grammar.parse(uri, "SIP_URI"); + return parsedUri !== -1 ? parsedUri : undefined; + } + Grammar.URIParse = URIParse; +})(Grammar || (Grammar = {})); diff --git a/lib/grammar/index.d.ts b/lib/grammar/index.d.ts new file mode 100644 index 000000000..3f672880a --- /dev/null +++ b/lib/grammar/index.d.ts @@ -0,0 +1,5 @@ +export * from "./grammar"; +export * from "./name-addr-header"; +export * from "./parameters"; +export * from "./uri"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/grammar/index.d.ts.map b/lib/grammar/index.d.ts.map new file mode 100644 index 000000000..61a386066 --- /dev/null +++ b/lib/grammar/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/grammar/index.ts"],"names":[],"mappings":"AAAA,cAAc,WAAW,CAAC;AAC1B,cAAc,oBAAoB,CAAC;AACnC,cAAc,cAAc,CAAC;AAC7B,cAAc,OAAO,CAAC"} \ No newline at end of file diff --git a/lib/grammar/index.js b/lib/grammar/index.js new file mode 100644 index 000000000..6e2c72b5c --- /dev/null +++ b/lib/grammar/index.js @@ -0,0 +1,4 @@ +export * from "./grammar"; +export * from "./name-addr-header"; +export * from "./parameters"; +export * from "./uri"; diff --git a/lib/grammar/name-addr-header.d.ts b/lib/grammar/name-addr-header.d.ts new file mode 100644 index 000000000..93a329038 --- /dev/null +++ b/lib/grammar/name-addr-header.d.ts @@ -0,0 +1,25 @@ +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; + }); + get friendlyName(): string; + get displayName(): string; + set displayName(value: string); + clone(): NameAddrHeader; + toString(): string; +} +//# sourceMappingURL=name-addr-header.d.ts.map \ No newline at end of file diff --git a/lib/grammar/name-addr-header.d.ts.map b/lib/grammar/name-addr-header.d.ts.map new file mode 100644 index 000000000..ada0c2016 --- /dev/null +++ b/lib/grammar/name-addr-header.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"name-addr-header.d.ts","sourceRoot":"","sources":["../../src/grammar/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;IAMjF,IAAI,YAAY,IAAI,MAAM,CAEzB;IAED,IAAI,WAAW,IAAI,MAAM,CAA8B;IACvD,IAAI,WAAW,CAAC,KAAK,EAAE,MAAM,EAE5B;IAEM,KAAK,IAAI,cAAc;IAOvB,QAAQ,IAAI,MAAM;CAiB1B"} \ No newline at end of file diff --git a/lib/grammar/name-addr-header.js b/lib/grammar/name-addr-header.js new file mode 100644 index 000000000..306b0766b --- /dev/null +++ b/lib/grammar/name-addr-header.js @@ -0,0 +1,42 @@ +import { Parameters } from "./parameters"; +/** + * Name Address SIP header. + * @public + */ +export class NameAddrHeader extends Parameters { + /** + * Constructor + * @param uri - + * @param displayName - + * @param parameters - + */ + constructor(uri, displayName, parameters) { + super(parameters); + this.uri = uri; + this._displayName = displayName; + } + get friendlyName() { + return this.displayName || this.uri.aor; + } + get displayName() { return this._displayName; } + set displayName(value) { + this._displayName = value; + } + clone() { + return new NameAddrHeader(this.uri.clone(), this._displayName, JSON.parse(JSON.stringify(this.parameters))); + } + toString() { + let body = (this.displayName || this.displayName === "0") ? '"' + this.displayName + '" ' : ""; + body += "<" + this.uri.toString() + ">"; + for (const parameter in this.parameters) { + // eslint-disable-next-line no-prototype-builtins + if (this.parameters.hasOwnProperty(parameter)) { + body += ";" + parameter; + if (this.parameters[parameter] !== null) { + body += "=" + this.parameters[parameter]; + } + } + } + return body; + } +} diff --git a/lib/grammar/parameters.d.ts b/lib/grammar/parameters.d.ts new file mode 100644 index 000000000..63755e2d2 --- /dev/null +++ b/lib/grammar/parameters.d.ts @@ -0,0 +1,17 @@ +/** + * @internal + */ +export declare class Parameters { + parameters: { + [name: string]: string | null; + }; + constructor(parameters: { + [name: string]: string | number | null | undefined; + }); + setParam(key: string, value: string | number | null | undefined): void; + getParam(key: string): string | null | undefined; + hasParam(key: string): boolean; + deleteParam(key: string): string | null | undefined; + clearParams(): void; +} +//# sourceMappingURL=parameters.d.ts.map \ No newline at end of file diff --git a/lib/grammar/parameters.d.ts.map b/lib/grammar/parameters.d.ts.map new file mode 100644 index 000000000..f26d82b39 --- /dev/null +++ b/lib/grammar/parameters.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"parameters.d.ts","sourceRoot":"","sources":["../../src/grammar/parameters.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,qBAAa,UAAU;IACd,UAAU,EAAE;QAAC,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAAA;KAAC,CAAM;gBAE5C,UAAU,EAAE;QAAC,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,IAAI,GAAG,SAAS,CAAA;KAAC;IAUrE,QAAQ,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,IAAI;IAMtE,QAAQ,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,GAAG,SAAS;IAMhD,QAAQ,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO;IAI9B,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,GAAG,SAAS;IASnD,WAAW,IAAI,IAAI;CAG3B"} \ No newline at end of file diff --git a/lib/grammar/parameters.js b/lib/grammar/parameters.js new file mode 100644 index 000000000..938d682f4 --- /dev/null +++ b/lib/grammar/parameters.js @@ -0,0 +1,39 @@ +/** + * @internal + */ +export class Parameters { + constructor(parameters) { + this.parameters = {}; + // for in is required here as the Grammar parser is adding to the prototype chain + for (const param in parameters) { + // eslint-disable-next-line no-prototype-builtins + if (parameters.hasOwnProperty(param)) { + this.setParam(param, parameters[param]); + } + } + } + setParam(key, value) { + if (key) { + this.parameters[key.toLowerCase()] = (typeof value === "undefined" || value === null) ? null : value.toString(); + } + } + getParam(key) { + if (key) { + return this.parameters[key.toLowerCase()]; + } + } + hasParam(key) { + return !!(key && this.parameters[key.toLowerCase()] !== undefined); + } + deleteParam(key) { + key = key.toLowerCase(); + if (this.hasParam(key)) { + const value = this.parameters[key]; + delete this.parameters[key]; + return value; + } + } + clearParams() { + this.parameters = {}; + } +} diff --git a/lib/grammar/pegjs/dist/grammar.d.ts b/lib/grammar/pegjs/dist/grammar.d.ts new file mode 100644 index 000000000..5dff5415d --- /dev/null +++ b/lib/grammar/pegjs/dist/grammar.d.ts @@ -0,0 +1,51 @@ +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/pegjs/dist/grammar.d.ts.map b/lib/grammar/pegjs/dist/grammar.d.ts.map new file mode 100644 index 000000000..4b2899795 --- /dev/null +++ b/lib/grammar/pegjs/dist/grammar.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"grammar.d.ts","sourceRoot":"","sources":["../../../../src/grammar/pegjs/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/pegjs/dist/grammar.js b/lib/grammar/pegjs/dist/grammar.js new file mode 100644 index 000000000..1ba49d653 --- /dev/null +++ b/lib/grammar/pegjs/dist/grammar.js @@ -0,0 +1,1475 @@ +import { NameAddrHeader } from "../../name-addr-header"; +import { URI } from "../../uri"; +export class SyntaxError extends Error { + constructor(message, expected, found, location) { + super(); + this.message = message; + this.expected = expected; + this.found = found; + this.location = location; + this.name = "SyntaxError"; + if (typeof Error.captureStackTrace === "function") { + Error.captureStackTrace(this, SyntaxError); + } + } + static buildMessage(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, (ch) => "\\x0" + hex(ch)) + .replace(/[\x10-\x1F\x7F-\x9F]/g, (ch) => "\\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, (ch) => "\\x0" + hex(ch)) + .replace(/[\x10-\x1F\x7F-\x9F]/g, (ch) => "\\x" + hex(ch)); + } + function describeExpectation(expectation) { + switch (expectation.type) { + case "literal": + return "\"" + literalEscape(expectation.text) + "\""; + case "class": + const escapedParts = expectation.parts.map((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) { + const descriptions = expected1.map(describeExpectation); + let i; + let 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."; + } +} +function peg$parse(input, options) { + options = options !== undefined ? options : {}; + const peg$FAILED = {}; + const 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 }; + let peg$startRuleIndex = 119; + const 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(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(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(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 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 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 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 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 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 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) + ]; + const 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((ch) => ch.charCodeAt(0) - 32); + } + function peg$parseRule(index) { + const bc = peg$bytecode[index]; + let ip = 0; + const ips = []; + let end = bc.length; + const ends = []; + const stack = []; + let 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)); + } +} +export const parse = peg$parse; diff --git a/lib/grammar/uri.d.ts b/lib/grammar/uri.d.ts new file mode 100644 index 000000000..238cc4c90 --- /dev/null +++ b/lib/grammar/uri.d.ts @@ -0,0 +1,45 @@ +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 | undefined, user: string, host: string, port?: number, parameters?: { + [name: string]: string | number | null; + }, headers?: any); + get scheme(): string; + set scheme(value: string); + get user(): string | undefined; + set user(value: string | undefined); + get host(): string; + set host(value: string); + get aor(): string; + get port(): number | undefined; + set port(value: 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 get _normal(); + private get _raw(); + private _toString; + private escapeUser; + private headerize; +} +//# sourceMappingURL=uri.d.ts.map \ No newline at end of file diff --git a/lib/grammar/uri.d.ts.map b/lib/grammar/uri.d.ts.map new file mode 100644 index 000000000..8b5d8f560 --- /dev/null +++ b/lib/grammar/uri.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"uri.d.ts","sourceRoot":"","sources":["../../src/grammar/uri.ts"],"names":[],"mappings":"AACA,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,oBAAQ,EACd,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,EACZ,IAAI,CAAC,EAAE,MAAM,EACb,UAAU,CAAC,EAAE;QAAE,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,IAAI,CAAA;KAAE,EACvD,OAAO,CAAC,EAAE,GAAG;IAgCf,IAAI,MAAM,IAAI,MAAM,CAA+B;IACnD,IAAI,MAAM,CAAC,KAAK,EAAE,MAAM,EAGvB;IAED,IAAI,IAAI,IAAI,MAAM,GAAG,SAAS,CAA6B;IAC3D,IAAI,IAAI,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,EAEjC;IAED,IAAI,IAAI,IAAI,MAAM,CAA6B;IAC/C,IAAI,IAAI,CAAC,KAAK,EAAE,MAAM,EAGrB;IAED,IAAI,GAAG,IAAI,MAAM,CAAsD;IAEvE,IAAI,IAAI,IAAI,MAAM,GAAG,SAAS,CAA6B;IAC3D,IAAI,IAAI,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,EAEjC;IAEM,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;IAKhC,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG,GAAG;IAWjC,YAAY,IAAI,IAAI;IAIpB,KAAK,IAAI,GAAG;IAUZ,KAAK,IAAI,MAAM;IAIf,QAAQ,IAAI,MAAM;IAIzB,OAAO,KAAK,OAAO,GAAqC;IAExD,OAAO,KAAK,IAAI,GAAkC;IAElD,OAAO,CAAC,SAAS;IAkDjB,OAAO,CAAC,UAAU;IAwBlB,OAAO,CAAC,SAAS;CAwBlB"} \ No newline at end of file diff --git a/lib/grammar/uri.js b/lib/grammar/uri.js new file mode 100644 index 000000000..3aaed7d19 --- /dev/null +++ b/lib/grammar/uri.js @@ -0,0 +1,188 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +import { Parameters } from "./parameters"; +/** + * URI. + * @public + */ +export class URI extends Parameters { + /** + * Constructor + * @param scheme - + * @param user - + * @param host - + * @param port - + * @param parameters - + * @param headers - + */ + constructor(scheme = "sip", user, host, port, parameters, headers) { + super(parameters || {}); + this.headers = {}; + // Checks + if (!host) { + throw new TypeError('missing or invalid "host" parameter'); + } + for (const header in headers) { + // eslint-disable-next-line no-prototype-builtins + if (headers.hasOwnProperty(header)) { + this.setHeader(header, headers[header]); + } + } + // Raw URI + this.raw = { + scheme, + user, + host, + port + }; + // Normalized URI + this.normal = { + scheme: scheme.toLowerCase(), + user, + host: host.toLowerCase(), + port + }; + } + get scheme() { return this.normal.scheme; } + set scheme(value) { + this.raw.scheme = value; + this.normal.scheme = value.toLowerCase(); + } + get user() { return this.normal.user; } + set user(value) { + this.normal.user = this.raw.user = value; + } + get host() { return this.normal.host; } + set host(value) { + this.raw.host = value; + this.normal.host = value.toLowerCase(); + } + get aor() { return this.normal.user + "@" + this.normal.host; } + get port() { return this.normal.port; } + set port(value) { + this.normal.port = this.raw.port = value === 0 ? value : value; + } + setHeader(name, value) { + this.headers[this.headerize(name)] = (value instanceof Array) ? value : [value]; + } + getHeader(name) { + if (name) { + return this.headers[this.headerize(name)]; + } + } + hasHeader(name) { + // eslint-disable-next-line no-prototype-builtins + return !!name && !!this.headers.hasOwnProperty(this.headerize(name)); + } + deleteHeader(header) { + header = this.headerize(header); + // eslint-disable-next-line no-prototype-builtins + if (this.headers.hasOwnProperty(header)) { + const value = this.headers[header]; + delete this.headers[header]; + return value; + } + } + clearHeaders() { + this.headers = {}; + } + clone() { + 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))); + } + toRaw() { + return this._toString(this._raw); + } + toString() { + return this._toString(this._normal); + } + get _normal() { return this.normal; } + get _raw() { return this.raw; } + _toString(uri) { + let 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 (const parameter in this.parameters) { + // eslint-disable-next-line no-prototype-builtins + if (this.parameters.hasOwnProperty(parameter)) { + uriString += ";" + parameter; + if (this.parameters[parameter] !== null) { + uriString += "=" + this.parameters[parameter]; + } + } + } + const headers = []; + for (const header in this.headers) { + // eslint-disable-next-line no-prototype-builtins + if (this.headers.hasOwnProperty(header)) { + for (const idx in this.headers[header]) { + // eslint-disable-next-line no-prototype-builtins + 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 + */ + escapeUser(user) { + let 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. + // eslint-disable-next-line no-useless-catch + 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, "/"); + } + headerize(str) { + const exceptions = { + "Call-Id": "Call-ID", + "Cseq": "CSeq", + "Min-Se": "Min-SE", + "Rack": "RAck", + "Rseq": "RSeq", + "Www-Authenticate": "WWW-Authenticate", + }; + const name = str.toLowerCase().replace(/_/g, "-").split("-"); + const parts = name.length; + let hname = ""; + for (let 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; + } +} diff --git a/lib/index.d.ts b/lib/index.d.ts new file mode 100644 index 000000000..f861119b3 --- /dev/null +++ b/lib/index.d.ts @@ -0,0 +1,10 @@ +declare const version = "0.18.0"; +declare const name = "sip.js"; +export { name, version }; +export * from "./api"; +export * from "./grammar"; +import * as Core from "./core"; +export { Core }; +import * as Web from "./platform/web"; +export { Web }; +//# 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 new file mode 100644 index 000000000..3da2129e6 --- /dev/null +++ b/lib/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,QAAA,MAAM,OAAO,WAAkB,CAAC;AAChC,QAAA,MAAM,IAAI,WAAW,CAAC;AACtB,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;AAGzB,cAAc,OAAO,CAAC;AAGtB,cAAc,WAAW,CAAC;AAG1B,OAAO,KAAK,IAAI,MAAM,QAAQ,CAAC;AAC/B,OAAO,EAAE,IAAI,EAAE,CAAC;AAGhB,OAAO,KAAK,GAAG,MAAM,gBAAgB,CAAC;AACtC,OAAO,EAAE,GAAG,EAAE,CAAC"} \ No newline at end of file diff --git a/lib/index.js b/lib/index.js new file mode 100644 index 000000000..3b7fa4729 --- /dev/null +++ b/lib/index.js @@ -0,0 +1,15 @@ +// Helpful name and version exports +import { LIBRARY_VERSION } from "./version"; +const version = LIBRARY_VERSION; +const name = "sip.js"; +export { name, version }; +// Export api +export * from "./api"; +// Export grammar +export * from "./grammar"; +// Export namespaced core +import * as Core from "./core"; +export { Core }; +// Export namespaced web +import * as Web from "./platform/web"; +export { Web }; diff --git a/lib/platform/web/index.d.ts b/lib/platform/web/index.d.ts new file mode 100644 index 000000000..9f2af6e9a --- /dev/null +++ b/lib/platform/web/index.d.ts @@ -0,0 +1,5 @@ +export * from "./modifiers"; +export * from "./session-description-handler"; +export * from "./simple-user"; +export * from "./transport"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/index.d.ts.map b/lib/platform/web/index.d.ts.map new file mode 100644 index 000000000..fade71b09 --- /dev/null +++ b/lib/platform/web/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/platform/web/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,cAAc,+BAA+B,CAAC;AAC9C,cAAc,eAAe,CAAC;AAC9B,cAAc,aAAa,CAAC"} \ No newline at end of file diff --git a/lib/platform/web/index.js b/lib/platform/web/index.js new file mode 100644 index 000000000..627e6198d --- /dev/null +++ b/lib/platform/web/index.js @@ -0,0 +1,4 @@ +export * from "./modifiers"; +export * from "./session-description-handler"; +export * from "./simple-user"; +export * from "./transport"; diff --git a/lib/platform/web/modifiers/index.d.ts b/lib/platform/web/modifiers/index.d.ts new file mode 100644 index 000000000..4816d5405 --- /dev/null +++ b/lib/platform/web/modifiers/index.d.ts @@ -0,0 +1,6 @@ +/** + * SessionDescriptionHandlerModifer functions for web browsers. + * @packageDocumentation + */ +export * from "./modifiers"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/modifiers/index.d.ts.map b/lib/platform/web/modifiers/index.d.ts.map new file mode 100644 index 000000000..afac4a503 --- /dev/null +++ b/lib/platform/web/modifiers/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/modifiers/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,cAAc,aAAa,CAAC"} \ No newline at end of file diff --git a/lib/platform/web/modifiers/index.js b/lib/platform/web/modifiers/index.js new file mode 100644 index 000000000..5e3c3bade --- /dev/null +++ b/lib/platform/web/modifiers/index.js @@ -0,0 +1,5 @@ +/** + * SessionDescriptionHandlerModifer functions for web browsers. + * @packageDocumentation + */ +export * from "./modifiers"; diff --git a/lib/platform/web/modifiers/modifiers.d.ts b/lib/platform/web/modifiers/modifiers.d.ts new file mode 100644 index 000000000..4a18e9ffb --- /dev/null +++ b/lib/platform/web/modifiers/modifiers.d.ts @@ -0,0 +1,42 @@ +import { SessionDescriptionHandlerModifier } from "../../../api"; +/** + * Modifier. + * @public + */ +export declare function stripTcpCandidates(description: RTCSessionDescriptionInit): Promise; +/** + * Modifier. + * @public + */ +export declare function stripTelephoneEvent(description: RTCSessionDescriptionInit): Promise; +/** + * Modifier. + * @public + */ +export declare function cleanJitsiSdpImageattr(description: RTCSessionDescriptionInit): Promise; +/** + * Modifier. + * @public + */ +export declare function stripG722(description: RTCSessionDescriptionInit): Promise; +/** + * Modifier. + * @public + */ +export declare function stripRtpPayload(payload: string): SessionDescriptionHandlerModifier; +/** + * Modifier. + * @public + */ +export declare function stripVideo(description: RTCSessionDescriptionInit): Promise; +/** + * Modifier. + * @public + */ +export declare function addMidLines(description: RTCSessionDescriptionInit): Promise; +/** + * The modifier that should be used when the session would like to place the call on hold. + * @param description - The description that will be modified. + */ +export declare function holdModifier(description: RTCSessionDescriptionInit): Promise; +//# sourceMappingURL=modifiers.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/modifiers/modifiers.d.ts.map b/lib/platform/web/modifiers/modifiers.d.ts.map new file mode 100644 index 000000000..cbb2af238 --- /dev/null +++ b/lib/platform/web/modifiers/modifiers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"modifiers.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/modifiers/modifiers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iCAAiC,EAAE,MAAM,cAAc,CAAC;AA+EjE;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,WAAW,EAAE,yBAAyB,GAAG,OAAO,CAAC,yBAAyB,CAAC,CAG7G;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,WAAW,EAAE,yBAAyB,GAAG,OAAO,CAAC,yBAAyB,CAAC,CAG9G;AAED;;;GAGG;AACH,wBAAgB,sBAAsB,CAAC,WAAW,EAAE,yBAAyB,GAAG,OAAO,CAAC,yBAAyB,CAAC,CAGjH;AAED;;;GAGG;AACH,wBAAgB,SAAS,CAAC,WAAW,EAAE,yBAAyB,GAAG,OAAO,CAAC,yBAAyB,CAAC,CAGpG;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,iCAAiC,CAKlF;AAED;;;GAGG;AACH,wBAAgB,UAAU,CAAC,WAAW,EAAE,yBAAyB,GAAG,OAAO,CAAC,yBAAyB,CAAC,CAGrG;AAED;;;GAGG;AACH,wBAAgB,WAAW,CAAC,WAAW,EAAE,yBAAyB,GAAG,OAAO,CAAC,yBAAyB,CAAC,CAmBtG;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAAC,WAAW,EAAE,yBAAyB,GAAG,OAAO,CAAC,yBAAyB,CAAC,CAevG"} \ No newline at end of file diff --git a/lib/platform/web/modifiers/modifiers.js b/lib/platform/web/modifiers/modifiers.js new file mode 100644 index 000000000..bc87b33b7 --- /dev/null +++ b/lib/platform/web/modifiers/modifiers.js @@ -0,0 +1,163 @@ +const stripPayload = (sdp, payload) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const mediaDescs = []; + const lines = sdp.split(/\r\n/); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let currentMediaDesc; + for (let i = 0; i < lines.length;) { + const line = lines[i]; + if (/^m=(?:audio|video)/.test(line)) { + currentMediaDesc = { + index: i, + stripped: [] + }; + mediaDescs.push(currentMediaDesc); + } + else if (currentMediaDesc) { + const 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 (const mediaDesc of mediaDescs) { + const mline = lines[mediaDesc.index].split(" "); + // Ignore the first 3 parameters of the mline. The codec information is after that + for (let 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"); +}; +const stripMediaDescription = (sdp, description) => { + const descriptionRegExp = new RegExp("m=" + description + ".*$", "gm"); + const groupRegExp = new RegExp("^a=group:.*$", "gm"); + if (descriptionRegExp.test(sdp)) { + let midLineToRemove; + sdp = sdp.split(/^m=/gm).filter((section) => { + if (section.substr(0, description.length) === description) { + midLineToRemove = section.match(/^a=mid:.*$/gm); + if (midLineToRemove) { + const step = midLineToRemove[0].match(/:.+$/g); + if (step) { + midLineToRemove = step[0].substr(1); + } + } + return false; + } + return true; + }).join("m="); + const groupLine = sdp.match(groupRegExp); + if (groupLine && groupLine.length === 1) { + let groupLinePortion = groupLine[0]; + // eslint-disable-next-line no-useless-escape + const groupRegExpReplace = new RegExp("\ *" + midLineToRemove + "[^\ ]*", "g"); + groupLinePortion = groupLinePortion.replace(groupRegExpReplace, ""); + sdp = sdp.split(groupRegExp).join(groupLinePortion); + } + } + return sdp; +}; +/** + * Modifier. + * @public + */ +export function stripTcpCandidates(description) { + description.sdp = (description.sdp || "").replace(/^a=candidate:\d+ \d+ tcp .*?\r\n/img, ""); + return Promise.resolve(description); +} +/** + * Modifier. + * @public + */ +export function stripTelephoneEvent(description) { + description.sdp = stripPayload(description.sdp || "", "telephone-event"); + return Promise.resolve(description); +} +/** + * Modifier. + * @public + */ +export function cleanJitsiSdpImageattr(description) { + description.sdp = (description.sdp || "").replace(/^(a=imageattr:.*?)(x|y)=\[0-/gm, "$1$2=[1:"); + return Promise.resolve(description); +} +/** + * Modifier. + * @public + */ +export function stripG722(description) { + description.sdp = stripPayload(description.sdp || "", "G722"); + return Promise.resolve(description); +} +/** + * Modifier. + * @public + */ +export function stripRtpPayload(payload) { + return (description) => { + description.sdp = stripPayload(description.sdp || "", payload); + return Promise.resolve(description); + }; +} +/** + * Modifier. + * @public + */ +export function stripVideo(description) { + description.sdp = stripMediaDescription(description.sdp || "", "video"); + return Promise.resolve(description); +} +/** + * Modifier. + * @public + */ +export function addMidLines(description) { + let sdp = description.sdp || ""; + if (sdp.search(/^a=mid.*$/gm) === -1) { + const mlines = sdp.match(/^m=.*$/gm); + const sdpArray = sdp.split(/^m=.*$/gm); + if (mlines) { + mlines.forEach((elem, idx) => { + mlines[idx] = elem + "\na=mid:" + idx; + }); + } + sdpArray.forEach((elem, idx) => { + if (mlines && mlines[idx]) { + sdpArray[idx] = elem + mlines[idx]; + } + }); + sdp = sdpArray.join(""); + description.sdp = sdp; + } + return Promise.resolve(description); +} +/** + * The modifier that should be used when the session would like to place the call on hold. + * @param description - The description that will be modified. + */ +export function holdModifier(description) { + if (!description.sdp || !description.type) { + throw new Error("Invalid SDP"); + } + let sdp = description.sdp; + const type = description.type; + if (sdp) { + if (!/a=(sendrecv|sendonly|recvonly|inactive)/.test(sdp)) { + sdp = sdp.replace(/(m=[^\r]*\r\n)/g, "$1a=sendonly\r\n"); + } + else { + sdp = sdp.replace(/a=sendrecv\r\n/g, "a=sendonly\r\n"); + sdp = sdp.replace(/a=recvonly\r\n/g, "a=inactive\r\n"); + } + } + return Promise.resolve({ sdp, type }); +} diff --git a/lib/platform/web/session-description-handler/index.d.ts b/lib/platform/web/session-description-handler/index.d.ts new file mode 100644 index 000000000..c2d06bcce --- /dev/null +++ b/lib/platform/web/session-description-handler/index.d.ts @@ -0,0 +1,15 @@ +/** + * A SessionDescriptionHandler for web browsers. + * @packageDocumentation + */ +export * from "./media-stream-factory-default"; +export * from "./media-stream-factory"; +export * from "./peer-connection-configuration-default"; +export * from "./peer-connection-delegate"; +export * from "./session-description-handler-configuration"; +export * from "./session-description-handler-factory-default"; +export * from "./session-description-handler-factory-options"; +export * from "./session-description-handler-factory"; +export * from "./session-description-handler-options"; +export * from "./session-description-handler"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/index.d.ts.map b/lib/platform/web/session-description-handler/index.d.ts.map new file mode 100644 index 000000000..3737a47e0 --- /dev/null +++ b/lib/platform/web/session-description-handler/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/session-description-handler/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,cAAc,gCAAgC,CAAC;AAC/C,cAAc,wBAAwB,CAAC;AACvC,cAAc,yCAAyC,CAAC;AACxD,cAAc,4BAA4B,CAAC;AAC3C,cAAc,6CAA6C,CAAC;AAC5D,cAAc,+CAA+C,CAAC;AAC9D,cAAc,+CAA+C,CAAC;AAC9D,cAAc,uCAAuC,CAAC;AACtD,cAAc,uCAAuC,CAAC;AACtD,cAAc,+BAA+B,CAAC"} \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/index.js b/lib/platform/web/session-description-handler/index.js new file mode 100644 index 000000000..63c3b42f0 --- /dev/null +++ b/lib/platform/web/session-description-handler/index.js @@ -0,0 +1,14 @@ +/** + * A SessionDescriptionHandler for web browsers. + * @packageDocumentation + */ +export * from "./media-stream-factory-default"; +export * from "./media-stream-factory"; +export * from "./peer-connection-configuration-default"; +export * from "./peer-connection-delegate"; +export * from "./session-description-handler-configuration"; +export * from "./session-description-handler-factory-default"; +export * from "./session-description-handler-factory-options"; +export * from "./session-description-handler-factory"; +export * from "./session-description-handler-options"; +export * from "./session-description-handler"; diff --git a/lib/platform/web/session-description-handler/media-stream-factory-default.d.ts b/lib/platform/web/session-description-handler/media-stream-factory-default.d.ts new file mode 100644 index 000000000..5c1537d99 --- /dev/null +++ b/lib/platform/web/session-description-handler/media-stream-factory-default.d.ts @@ -0,0 +1,7 @@ +import { MediaStreamFactory } from "./media-stream-factory"; +/** + * Function which returns a MediaStreamFactory. + * @public + */ +export declare function defaultMediaStreamFactory(): MediaStreamFactory; +//# sourceMappingURL=media-stream-factory-default.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/media-stream-factory-default.d.ts.map b/lib/platform/web/session-description-handler/media-stream-factory-default.d.ts.map new file mode 100644 index 000000000..791b6f5ea --- /dev/null +++ b/lib/platform/web/session-description-handler/media-stream-factory-default.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"media-stream-factory-default.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/session-description-handler/media-stream-factory-default.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAE5D;;;GAGG;AACH,wBAAgB,yBAAyB,IAAI,kBAAkB,CAe9D"} \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/media-stream-factory-default.js b/lib/platform/web/session-description-handler/media-stream-factory-default.js new file mode 100644 index 000000000..abbed9c71 --- /dev/null +++ b/lib/platform/web/session-description-handler/media-stream-factory-default.js @@ -0,0 +1,20 @@ +/** + * Function which returns a MediaStreamFactory. + * @public + */ +export function defaultMediaStreamFactory() { + return (constraints) => { + // if no audio or video, return a media stream without tracks + if (!constraints.audio && !constraints.video) { + return Promise.resolve(new MediaStream()); + } + // getUserMedia() is a powerful feature which can only be used in secure contexts; in insecure contexts, + // navigator.mediaDevices is undefined, preventing access to getUserMedia(). A secure context is, in short, + // a page loaded using HTTPS or the file:/// URL scheme, or a page loaded from localhost. + // https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia#Privacy_and_security + if (navigator.mediaDevices === undefined) { + return Promise.reject(new Error("Media devices not available in insecure contexts.")); + } + return navigator.mediaDevices.getUserMedia.call(navigator.mediaDevices, constraints); + }; +} diff --git a/lib/platform/web/session-description-handler/media-stream-factory.d.ts b/lib/platform/web/session-description-handler/media-stream-factory.d.ts new file mode 100644 index 000000000..99935573f --- /dev/null +++ b/lib/platform/web/session-description-handler/media-stream-factory.d.ts @@ -0,0 +1,7 @@ +import { SessionDescriptionHandler } from "./session-description-handler"; +/** + * Interface of factory function which produces a MediaStream. + * @public + */ +export declare type MediaStreamFactory = (constraints: MediaStreamConstraints, sessionDescriptionHandler: SessionDescriptionHandler) => Promise; +//# sourceMappingURL=media-stream-factory.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/media-stream-factory.d.ts.map b/lib/platform/web/session-description-handler/media-stream-factory.d.ts.map new file mode 100644 index 000000000..f591f66fc --- /dev/null +++ b/lib/platform/web/session-description-handler/media-stream-factory.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"media-stream-factory.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/session-description-handler/media-stream-factory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAE1E;;;GAGG;AACH,oBAAY,kBAAkB,GAAG,CAC/B,WAAW,EAAE,sBAAsB,EACnC,yBAAyB,EAAE,yBAAyB,KACjD,OAAO,CAAC,WAAW,CAAC,CAAC"} \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/media-stream-factory.js b/lib/platform/web/session-description-handler/media-stream-factory.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/platform/web/session-description-handler/media-stream-factory.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/platform/web/session-description-handler/peer-connection-configuration-default.d.ts b/lib/platform/web/session-description-handler/peer-connection-configuration-default.d.ts new file mode 100644 index 000000000..2a875e2ee --- /dev/null +++ b/lib/platform/web/session-description-handler/peer-connection-configuration-default.d.ts @@ -0,0 +1,6 @@ +/** + * Function which returns an RTCConfiguration. + * @public + */ +export declare function defaultPeerConnectionConfiguration(): RTCConfiguration; +//# sourceMappingURL=peer-connection-configuration-default.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/peer-connection-configuration-default.d.ts.map b/lib/platform/web/session-description-handler/peer-connection-configuration-default.d.ts.map new file mode 100644 index 000000000..7e73cdd1c --- /dev/null +++ b/lib/platform/web/session-description-handler/peer-connection-configuration-default.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"peer-connection-configuration-default.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/session-description-handler/peer-connection-configuration-default.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,wBAAgB,kCAAkC,IAAI,gBAAgB,CAWrE"} \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/peer-connection-configuration-default.js b/lib/platform/web/session-description-handler/peer-connection-configuration-default.js new file mode 100644 index 000000000..2ab132086 --- /dev/null +++ b/lib/platform/web/session-description-handler/peer-connection-configuration-default.js @@ -0,0 +1,16 @@ +/** + * Function which returns an RTCConfiguration. + * @public + */ +export function defaultPeerConnectionConfiguration() { + const configuration = { + bundlePolicy: "balanced", + certificates: undefined, + iceCandidatePoolSize: 0, + iceServers: [{ urls: "stun:stun.l.google.com:19302" }], + iceTransportPolicy: "all", + peerIdentity: undefined, + rtcpMuxPolicy: "require" + }; + return configuration; +} diff --git a/lib/platform/web/session-description-handler/peer-connection-delegate.d.ts b/lib/platform/web/session-description-handler/peer-connection-delegate.d.ts new file mode 100644 index 000000000..8d1f8e511 --- /dev/null +++ b/lib/platform/web/session-description-handler/peer-connection-delegate.d.ts @@ -0,0 +1,64 @@ +/** + * Delegate to handle PeerConnection state changes. + * @public + */ +export interface PeerConnectionDelegate { + /** + * This happens whenever the aggregate state of the connection changes. + * The aggregate state is a combination of the states of all of the + * individual network transports being used by the connection. + * @param event - Event. + */ + onconnectionstatechange?(event: Event): void; + /** + * Triggered when an RTCDataChannel is added to the connection by the + * remote peer calling createDataChannel(). + * @param event - RTCDataChannelEvent. + */ + ondatachannel?(event: RTCDataChannelEvent): void; + /** + * Triggered when a new ICE candidate has been found. + * @param event - RTCPeerConnectionIceEvent. + */ + onicecandidate?(event: RTCPeerConnectionIceEvent): void; + /** + * Triggered when an error occurred during ICE candidate gathering. + * @param event - RTCPeerConnectionIceErrorEvent. + */ + onicecandidateerror?(event: RTCPeerConnectionIceErrorEvent): void; + /** + * This happens whenever the local ICE agent needs to deliver a message to + * the other peer through the signaling server. This lets the ICE agent + * perform negotiation with the remote peer without the browser itself + * needing to know any specifics about the technology being used for + * signalingTriggered when the IceConnectionState changes. + * @param event - Event. + */ + oniceconnectionstatechange?(event: Event): void; + /** + * Triggered when the ICE gathering state changes. + * @param event - Event. + */ + onicegatheringstatechange?(event: Event): void; + /** + * Triggered when renegotiation is necessary. + * @param event - Event. + */ + onnegotiationneeded?(event: Event): void; + /** + * Triggered when the SignalingState changes. + * @param event - Event. + */ + onsignalingstatechange?(event: Event): void; + /** + * Triggered when when a statistics object being monitored is deleted. + * @param event - Event. + */ + onstatsended?(event: Event): void; + /** + * Triggered when a new track is signaled by the remote peer, as a result of setRemoteDescription. + * @param event - Event. + */ + ontrack?(event: Event): void; +} +//# sourceMappingURL=peer-connection-delegate.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/peer-connection-delegate.d.ts.map b/lib/platform/web/session-description-handler/peer-connection-delegate.d.ts.map new file mode 100644 index 000000000..5a133138d --- /dev/null +++ b/lib/platform/web/session-description-handler/peer-connection-delegate.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"peer-connection-delegate.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/session-description-handler/peer-connection-delegate.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,WAAW,sBAAsB;IACrC;;;;;OAKG;IACH,uBAAuB,CAAC,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,CAAC;IAE7C;;;;OAIG;IACH,aAAa,CAAC,CAAC,KAAK,EAAE,mBAAmB,GAAG,IAAI,CAAC;IAEjD;;;OAGG;IACH,cAAc,CAAC,CAAC,KAAK,EAAE,yBAAyB,GAAG,IAAI,CAAC;IAExD;;;OAGG;IACH,mBAAmB,CAAC,CAAC,KAAK,EAAE,8BAA8B,GAAG,IAAI,CAAC;IAElE;;;;;;;OAOG;IACH,0BAA0B,CAAC,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,CAAC;IAEhD;;;OAGG;IACH,yBAAyB,CAAC,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,CAAC;IAE/C;;;OAGG;IACH,mBAAmB,CAAC,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,CAAC;IAEzC;;;OAGG;IACH,sBAAsB,CAAC,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,CAAC;IAE5C;;;OAGG;IACH,YAAY,CAAC,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,CAAC;IAElC;;;OAGG;IACH,OAAO,CAAC,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,CAAC;CAC9B"} \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/peer-connection-delegate.js b/lib/platform/web/session-description-handler/peer-connection-delegate.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/platform/web/session-description-handler/peer-connection-delegate.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/platform/web/session-description-handler/session-description-handler-configuration.d.ts b/lib/platform/web/session-description-handler/session-description-handler-configuration.d.ts new file mode 100644 index 000000000..3b212fc76 --- /dev/null +++ b/lib/platform/web/session-description-handler/session-description-handler-configuration.d.ts @@ -0,0 +1,17 @@ +/** + * Configuration for SessionDescriptionHandler. + * @public + */ +export interface SessionDescriptionHandlerConfiguration { + /** + * The maximum duration to wait in ms for ICE gathering to complete. + * If undefined, implementation dependent. + * If zero, no timeout. + */ + iceGatheringTimeout?: number; + /** + * Peer connection options. + */ + peerConnectionConfiguration?: RTCConfiguration; +} +//# sourceMappingURL=session-description-handler-configuration.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/session-description-handler-configuration.d.ts.map b/lib/platform/web/session-description-handler/session-description-handler-configuration.d.ts.map new file mode 100644 index 000000000..d31181610 --- /dev/null +++ b/lib/platform/web/session-description-handler/session-description-handler-configuration.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"session-description-handler-configuration.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/session-description-handler/session-description-handler-configuration.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,WAAW,sCAAsC;IACrD;;;;OAIG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAE7B;;OAEG;IACH,2BAA2B,CAAC,EAAE,gBAAgB,CAAC;CAChD"} \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/session-description-handler-configuration.js b/lib/platform/web/session-description-handler/session-description-handler-configuration.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/platform/web/session-description-handler/session-description-handler-configuration.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/platform/web/session-description-handler/session-description-handler-factory-default.d.ts b/lib/platform/web/session-description-handler/session-description-handler-factory-default.d.ts new file mode 100644 index 000000000..c0a3341d9 --- /dev/null +++ b/lib/platform/web/session-description-handler/session-description-handler-factory-default.d.ts @@ -0,0 +1,12 @@ +import { SessionDescriptionHandler } from "./session-description-handler"; +import { SessionDescriptionHandlerFactory } from "./session-description-handler-factory"; +/** + * Function which returns a SessionDescriptionHandlerFactory. + * @remarks + * See {@link defaultPeerConnectionConfiguration} for the default peer connection configuration. + * The ICE gathering timeout defaults to 5000ms. + * @param mediaStreamFactory - MediaStream factory. + * @public + */ +export declare function defaultSessionDescriptionHandlerFactory(mediaStreamFactory?: (constraints: MediaStreamConstraints, sessionDescriptionHandler: SessionDescriptionHandler) => Promise): SessionDescriptionHandlerFactory; +//# sourceMappingURL=session-description-handler-factory-default.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/session-description-handler-factory-default.d.ts.map b/lib/platform/web/session-description-handler/session-description-handler-factory-default.d.ts.map new file mode 100644 index 000000000..2f5f9627d --- /dev/null +++ b/lib/platform/web/session-description-handler/session-description-handler-factory-default.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"session-description-handler-factory-default.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/session-description-handler/session-description-handler-factory-default.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAE1E,OAAO,EAAE,gCAAgC,EAAE,MAAM,uCAAuC,CAAC;AAGzF;;;;;;;GAOG;AACH,wBAAgB,uCAAuC,CACrD,kBAAkB,CAAC,EAAE,CACnB,WAAW,EAAE,sBAAsB,EACnC,yBAAyB,EAAE,yBAAyB,KACjD,OAAO,CAAC,WAAW,CAAC,GACxB,gCAAgC,CAuBlC"} \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/session-description-handler-factory-default.js b/lib/platform/web/session-description-handler/session-description-handler-factory-default.js new file mode 100644 index 000000000..cf2bd48b7 --- /dev/null +++ b/lib/platform/web/session-description-handler/session-description-handler-factory-default.js @@ -0,0 +1,28 @@ +import { defaultMediaStreamFactory } from "./media-stream-factory-default"; +import { defaultPeerConnectionConfiguration } from "./peer-connection-configuration-default"; +import { SessionDescriptionHandler } from "./session-description-handler"; +/** + * Function which returns a SessionDescriptionHandlerFactory. + * @remarks + * See {@link defaultPeerConnectionConfiguration} for the default peer connection configuration. + * The ICE gathering timeout defaults to 5000ms. + * @param mediaStreamFactory - MediaStream factory. + * @public + */ +export function defaultSessionDescriptionHandlerFactory(mediaStreamFactory) { + return (session, options) => { + // provide a default media stream factory if need be + if (mediaStreamFactory === undefined) { + mediaStreamFactory = defaultMediaStreamFactory(); + } + // make sure we allow `0` to be passed in so timeout can be disabled + const iceGatheringTimeout = (options === null || options === void 0 ? void 0 : options.iceGatheringTimeout) !== undefined ? options === null || options === void 0 ? void 0 : options.iceGatheringTimeout : 5000; + // merge passed factory options into default session description configuration + const sessionDescriptionHandlerConfiguration = { + iceGatheringTimeout, + peerConnectionConfiguration: Object.assign(Object.assign({}, defaultPeerConnectionConfiguration()), options === null || options === void 0 ? void 0 : options.peerConnectionConfiguration) + }; + const logger = session.userAgent.getLogger("sip.SessionDescriptionHandler"); + return new SessionDescriptionHandler(logger, mediaStreamFactory, sessionDescriptionHandlerConfiguration); + }; +} diff --git a/lib/platform/web/session-description-handler/session-description-handler-factory-options.d.ts b/lib/platform/web/session-description-handler/session-description-handler-factory-options.d.ts new file mode 100644 index 000000000..dd3c97b4d --- /dev/null +++ b/lib/platform/web/session-description-handler/session-description-handler-factory-options.d.ts @@ -0,0 +1,10 @@ +import { SessionDescriptionHandlerConfiguration } from "./session-description-handler-configuration"; +/** + * Options for SessionDescriptionHandlerFactory. + * @remarks + * The "options" are provided as part of the UserAgent configuration and passed through + * on every call to SessionDescriptionHandlerFactory's constructor. + * @public + */ +export declare type SessionDescriptionHandlerFactoryOptions = SessionDescriptionHandlerConfiguration; +//# sourceMappingURL=session-description-handler-factory-options.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/session-description-handler-factory-options.d.ts.map b/lib/platform/web/session-description-handler/session-description-handler-factory-options.d.ts.map new file mode 100644 index 000000000..6ac43615b --- /dev/null +++ b/lib/platform/web/session-description-handler/session-description-handler-factory-options.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"session-description-handler-factory-options.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/session-description-handler/session-description-handler-factory-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sCAAsC,EAAE,MAAM,6CAA6C,CAAC;AAErG;;;;;;GAMG;AACH,oBAAY,uCAAuC,GAAG,sCAAsC,CAAC"} \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/session-description-handler-factory-options.js b/lib/platform/web/session-description-handler/session-description-handler-factory-options.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/platform/web/session-description-handler/session-description-handler-factory-options.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/platform/web/session-description-handler/session-description-handler-factory.d.ts b/lib/platform/web/session-description-handler/session-description-handler-factory.d.ts new file mode 100644 index 000000000..8239fd08e --- /dev/null +++ b/lib/platform/web/session-description-handler/session-description-handler-factory.d.ts @@ -0,0 +1,17 @@ +import { Session, SessionDescriptionHandlerFactory as SessionDescriptionHandlerFactoryDefinition } from "../../../api"; +import { SessionDescriptionHandler } from "./session-description-handler"; +import { SessionDescriptionHandlerFactoryOptions } from "./session-description-handler-factory-options"; +/** + * Factory for {@link SessionDescriptionHandler}. + * @public + */ +export interface SessionDescriptionHandlerFactory extends SessionDescriptionHandlerFactoryDefinition { + /** + * SessionDescriptionHandler factory function. + * @remarks + * The `options` are provided as part of the UserAgent configuration + * and passed through on every call to SessionDescriptionHandlerFactory's constructor. + */ + (session: Session, options?: SessionDescriptionHandlerFactoryOptions): SessionDescriptionHandler; +} +//# sourceMappingURL=session-description-handler-factory.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/session-description-handler-factory.d.ts.map b/lib/platform/web/session-description-handler/session-description-handler-factory.d.ts.map new file mode 100644 index 000000000..ba3f315a0 --- /dev/null +++ b/lib/platform/web/session-description-handler/session-description-handler-factory.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"session-description-handler-factory.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/session-description-handler/session-description-handler-factory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,gCAAgC,IAAI,0CAA0C,EAAE,MAAM,cAAc,CAAC;AACvH,OAAO,EAAE,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAC1E,OAAO,EAAE,uCAAuC,EAAE,MAAM,+CAA+C,CAAC;AAExG;;;GAGG;AACH,MAAM,WAAW,gCAAiC,SAAQ,0CAA0C;IAClG;;;;;OAKG;IACH,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,uCAAuC,GAAG,yBAAyB,CAAC;CAClG"} \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/session-description-handler-factory.js b/lib/platform/web/session-description-handler/session-description-handler-factory.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/platform/web/session-description-handler/session-description-handler-factory.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/platform/web/session-description-handler/session-description-handler-options.d.ts b/lib/platform/web/session-description-handler/session-description-handler-options.d.ts new file mode 100644 index 000000000..0e34afc95 --- /dev/null +++ b/lib/platform/web/session-description-handler/session-description-handler-options.d.ts @@ -0,0 +1,44 @@ +import { SessionDescriptionHandlerOptions as SessionDescriptionHandlerOptionsDefinition } from "../../../api"; +/** + * Options for {@link SessionDescriptionHandler}. + * @public + */ +export interface SessionDescriptionHandlerOptions extends SessionDescriptionHandlerOptionsDefinition { + /** + * Answer options to use when creating an answer. + */ + answerOptions?: RTCAnswerOptions; + /** + * Constraints to use when creating local media stream. + * @remarks + * If undefined, defaults to audio true and video false. + * If audio and video are false, media stream will have no tracks. + */ + constraints?: MediaStreamConstraints; + /** + * If true, create a data channel when making initial offer. + */ + dataChannel?: boolean; + /** + * A human-readable name to use when creating the data channel. + */ + dataChannelLabel?: string; + /** + * Configuration options for creating the data channel. + */ + dataChannelOptions?: RTCDataChannelInit; + /** + * The maximum duration to wait in ms for ICE gathering to complete. + * No timeout if undefined or zero. + */ + iceGatheringTimeout?: number; + /** + * Offer options to use when creating an offer. + */ + offerOptions?: RTCOfferOptions; + /** + * Called upon creating a data channel. + */ + onDataChannel?: (dataChannel: RTCDataChannel) => void; +} +//# sourceMappingURL=session-description-handler-options.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/session-description-handler-options.d.ts.map b/lib/platform/web/session-description-handler/session-description-handler-options.d.ts.map new file mode 100644 index 000000000..3d6f37c61 --- /dev/null +++ b/lib/platform/web/session-description-handler/session-description-handler-options.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"session-description-handler-options.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/session-description-handler/session-description-handler-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gCAAgC,IAAI,0CAA0C,EAAE,MAAM,cAAc,CAAC;AAE9G;;;GAGG;AACH,MAAM,WAAW,gCAAiC,SAAQ,0CAA0C;IAClG;;OAEG;IACH,aAAa,CAAC,EAAE,gBAAgB,CAAC;IAEjC;;;;;OAKG;IACH,WAAW,CAAC,EAAE,sBAAsB,CAAC;IAErC;;OAEG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;IAEtB;;OAEG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAE1B;;OAEG;IACH,kBAAkB,CAAC,EAAE,kBAAkB,CAAC;IAExC;;;OAGG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAE7B;;OAEG;IACH,YAAY,CAAC,EAAE,eAAe,CAAC;IAE/B;;OAEG;IACH,aAAa,CAAC,EAAE,CAAC,WAAW,EAAE,cAAc,KAAK,IAAI,CAAC;CACvD"} \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/session-description-handler-options.js b/lib/platform/web/session-description-handler/session-description-handler-options.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/platform/web/session-description-handler/session-description-handler-options.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/platform/web/session-description-handler/session-description-handler.d.ts b/lib/platform/web/session-description-handler/session-description-handler.d.ts new file mode 100644 index 000000000..c29b1f552 --- /dev/null +++ b/lib/platform/web/session-description-handler/session-description-handler.d.ts @@ -0,0 +1,208 @@ +import { BodyAndContentType, SessionDescriptionHandler as SessionDescriptionHandlerDefinition, SessionDescriptionHandlerModifier } from "../../../api"; +import { Logger } from "../../../core"; +import { MediaStreamFactory } from "./media-stream-factory"; +import { SessionDescriptionHandlerConfiguration } from "./session-description-handler-configuration"; +import { SessionDescriptionHandlerOptions } from "./session-description-handler-options"; +import { PeerConnectionDelegate } from "./peer-connection-delegate"; +/** + * A base class implementing a WebRTC session description handler for sip.js. + * @remarks + * It is expected/intended to be extended by specific WebRTC based applications. + * @privateRemarks + * So do not put application specific implementation in here. + * @public + */ +export declare class SessionDescriptionHandler implements SessionDescriptionHandlerDefinition { + /** Logger. */ + protected logger: Logger; + /** Media stream factory. */ + protected mediaStreamFactory: MediaStreamFactory; + /** Configuration options. */ + protected sessionDescriptionHandlerConfiguration?: SessionDescriptionHandlerConfiguration; + /** The local media stream. */ + protected _localMediaStream: MediaStream; + /** The remote media stream. */ + protected _remoteMediaStream: MediaStream; + /** The data channel. Undefined before created. */ + protected _dataChannel: RTCDataChannel | undefined; + /** The peer connection. Undefined after SessionDescriptionHandler.close(). */ + protected _peerConnection: RTCPeerConnection | undefined; + /** The peer connection delegate. */ + protected _peerConnectionDelegate: PeerConnectionDelegate | undefined; + private iceGatheringCompletePromise; + private iceGatheringCompleteTimeoutId; + private iceGatheringCompleteResolve; + private iceGatheringCompleteReject; + private localMediaStreamConstraints; + private onDataChannel; + /** + * Constructor + * @param logger - A logger + * @param mediaStreamFactory - A factory to provide a MediaStream + * @param options - Options passed from the SessionDescriptionHandleFactory + */ + constructor(logger: Logger, mediaStreamFactory: MediaStreamFactory, sessionDescriptionHandlerConfiguration?: SessionDescriptionHandlerConfiguration); + /** + * The local media stream currently being sent. + * + * @remarks + * The local media stream initially has no tracks, so the presence of tracks + * should not be assumed. Furthermore, tracks may be added or removed if the + * local media changes - for example, on upgrade from audio only to a video session. + * At any given time there will be at most one audio track and one video track + * (it's possible that this restriction may not apply to sub-classes). + * Use `MediaStream.onaddtrack` or add a listener for the `addtrack` event + * to detect when a new track becomes available: + * https://developer.mozilla.org/en-US/docs/Web/API/MediaStream/onaddtrack + */ + get localMediaStream(): MediaStream; + /** + * The remote media stream currently being received. + * + * @remarks + * The remote media stream initially has no tracks, so the presence of tracks + * should not be assumed. Furthermore, tracks may be added or removed if the + * remote media changes - for example, on upgrade from audio only to a video session. + * At any given time there will be at most one audio track and one video track + * (it's possible that this restriction may not apply to sub-classes). + * Use `MediaStream.onaddtrack` or add a listener for the `addtrack` event + * to detect when a new track becomes available: + * https://developer.mozilla.org/en-US/docs/Web/API/MediaStream/onaddtrack + */ + get remoteMediaStream(): MediaStream; + /** + * The data channel. Undefined before it is created. + */ + get dataChannel(): RTCDataChannel | undefined; + /** + * The peer connection. Undefined if peer connection has closed. + * + * @remarks + * While access to the underlying `RTCPeerConnection` is provided, note that + * using methods with modify it may break the operation of this class. + * In particular, this class depends on exclusive access to the + * event handler properties. If you need access to the peer connection + * events, either register for events using `addEventListener()` on + * the `RTCPeerConnection` or set the `peerConnectionDelegate` on + * this `SessionDescriptionHandler`. + */ + get peerConnection(): RTCPeerConnection | undefined; + /** + * A delegate which provides access to the peer connection event handlers. + * + * @remarks + * Setting the peer connection event handlers directly is not supported + * and may break this class. As this class depends on exclusive access + * to them, a delegate may be set which provides alternative access to + * the event handlers in a fashion which is supported. + */ + get peerConnectionDelegate(): PeerConnectionDelegate | undefined; + set peerConnectionDelegate(delegate: PeerConnectionDelegate | undefined); + private static dispatchAddTrackEvent; + private static dispatchRemoveTrackEvent; + /** + * Stop tracks and close peer connection. + */ + close(): void; + /** + * Creates an offer or answer. + * @param options - Options bucket. + * @param modifiers - Modifiers. + */ + getDescription(options?: SessionDescriptionHandlerOptions, modifiers?: Array): Promise; + /** + * Returns true if the SessionDescriptionHandler can handle the Content-Type described by a SIP message. + * @param contentType - The content type that is in the SIP Message. + */ + hasDescription(contentType: string): boolean; + /** + * 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. + */ + sendDtmf(tones: string, options?: { + duration: number; + interToneGap: number; + }): boolean; + /** + * Sets an offer or answer. + * @param sdp - The session description. + * @param options - Options bucket. + * @param modifiers - Modifiers. + */ + setDescription(sdp: string, options?: SessionDescriptionHandlerOptions, modifiers?: Array): Promise; + /** + * Applies modifiers to SDP prior to setting the local or remote description. + * @param sdp - SDP to modify. + * @param modifiers - Modifiers to apply. + */ + protected applyModifiers(sdp: RTCSessionDescriptionInit, modifiers?: Array): Promise; + /** + * Create a data channel. + * @remarks + * Only creates a data channel if SessionDescriptionHandlerOptions.dataChannel is true. + * Only creates a data channel if creating a local offer. + * Only if one does not already exist. + * @param options - Session description handler options. + */ + protected createDataChannel(options?: SessionDescriptionHandlerOptions): Promise; + /** + * Depending on current signaling state, create a local offer or answer. + * @param options - Session description handler options. + */ + protected createLocalOfferOrAnswer(options?: SessionDescriptionHandlerOptions): Promise; + /** + * Get a media stream from the media stream factory and set the local media stream. + * @param options - Session description handler options. + */ + protected getLocalMediaStream(options?: SessionDescriptionHandlerOptions): Promise; + /** + * Sets the peer connection's sender tracks and local media stream tracks. + * + * @remarks + * Only the first audio and video tracks of the provided MediaStream are utilized. + * Adds tracks if audio and/or video tracks are not already present, otherwise replaces tracks. + * + * @param stream - Media stream containing tracks to be utilized. + */ + protected setLocalMediaStream(stream: MediaStream): Promise; + /** + * Gets the peer connection's local session description. + */ + protected getLocalSessionDescription(): Promise; + /** + * Sets the peer connection's local session description. + * @param sessionDescription - sessionDescription The session description. + */ + protected setLocalSessionDescription(sessionDescription: RTCSessionDescriptionInit): Promise; + /** + * Sets the peer connection's remote session description. + * @param sessionDescription - The session description. + */ + protected setRemoteSessionDescription(sessionDescription: RTCSessionDescriptionInit): Promise; + /** + * Sets a remote media stream track. + * + * @remarks + * Adds tracks if audio and/or video tracks are not already present, otherwise replaces tracks. + * + * @param track - Media stream track to be utilized. + */ + protected setRemoteTrack(track: MediaStreamTrack): void; + /** + * Called when ICE gathering completes and resolves any waiting promise. + */ + protected iceGatheringComplete(): void; + /** + * Wait for ICE gathering to complete. + * @param restart - If true, waits if current state is "complete" (waits for transition to "complete"). + * @param timeout - Milliseconds after which waiting times out. No timeout if 0. + */ + protected waitForIceGatheringComplete(restart?: boolean, timeout?: number): Promise; + /** + * Initializes the peer connection event handlers + */ + private initPeerConnectionEventHandlers; +} +//# sourceMappingURL=session-description-handler.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/session-description-handler.d.ts.map b/lib/platform/web/session-description-handler/session-description-handler.d.ts.map new file mode 100644 index 000000000..ebeb96425 --- /dev/null +++ b/lib/platform/web/session-description-handler/session-description-handler.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"session-description-handler.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/session-description-handler/session-description-handler.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,yBAAyB,IAAI,mCAAmC,EAChE,iCAAiC,EAClC,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AACvC,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAC5D,OAAO,EAAE,sCAAsC,EAAE,MAAM,6CAA6C,CAAC;AACrG,OAAO,EAAE,gCAAgC,EAAE,MAAM,uCAAuC,CAAC;AACzF,OAAO,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AAoBpE;;;;;;;GAOG;AACH,qBAAa,yBAA0B,YAAW,mCAAmC;IACnF,cAAc;IACd,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC;IACzB,4BAA4B;IAC5B,SAAS,CAAC,kBAAkB,EAAE,kBAAkB,CAAC;IACjD,6BAA6B;IAC7B,SAAS,CAAC,sCAAsC,CAAC,EAAE,sCAAsC,CAAC;IAE1F,8BAA8B;IAC9B,SAAS,CAAC,iBAAiB,EAAE,WAAW,CAAC;IACzC,+BAA+B;IAC/B,SAAS,CAAC,kBAAkB,EAAE,WAAW,CAAC;IAC1C,kDAAkD;IAClD,SAAS,CAAC,YAAY,EAAE,cAAc,GAAG,SAAS,CAAC;IACnD,8EAA8E;IAC9E,SAAS,CAAC,eAAe,EAAE,iBAAiB,GAAG,SAAS,CAAC;IACzD,oCAAoC;IACpC,SAAS,CAAC,uBAAuB,EAAE,sBAAsB,GAAG,SAAS,CAAC;IAEtE,OAAO,CAAC,2BAA2B,CAA4B;IAC/D,OAAO,CAAC,6BAA6B,CAAqB;IAC1D,OAAO,CAAC,2BAA2B,CAA8B;IACjE,OAAO,CAAC,0BAA0B,CAA6B;IAC/D,OAAO,CAAC,2BAA2B,CAAqC;IACxE,OAAO,CAAC,aAAa,CAAsD;IAE3E;;;;;OAKG;gBAED,MAAM,EAAE,MAAM,EACd,kBAAkB,EAAE,kBAAkB,EACtC,sCAAsC,CAAC,EAAE,sCAAsC;IAYjF;;;;;;;;;;;;OAYG;IACH,IAAI,gBAAgB,IAAI,WAAW,CAElC;IAED;;;;;;;;;;;;OAYG;IACH,IAAI,iBAAiB,IAAI,WAAW,CAEnC;IAED;;OAEG;IACH,IAAI,WAAW,IAAI,cAAc,GAAG,SAAS,CAE5C;IAED;;;;;;;;;;;OAWG;IACH,IAAI,cAAc,IAAI,iBAAiB,GAAG,SAAS,CAElD;IAED;;;;;;;;OAQG;IACH,IAAI,sBAAsB,IAAI,sBAAsB,GAAG,SAAS,CAE/D;IAED,IAAI,sBAAsB,CAAC,QAAQ,EAAE,sBAAsB,GAAG,SAAS,EAEtE;IAID,OAAO,CAAC,MAAM,CAAC,qBAAqB;IAKpC,OAAO,CAAC,MAAM,CAAC,wBAAwB;IAIvC;;OAEG;IACI,KAAK,IAAI,IAAI;IAkBpB;;;;OAIG;IACI,cAAc,CACnB,OAAO,CAAC,EAAE,gCAAgC,EAC1C,SAAS,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,GACnD,OAAO,CAAC,kBAAkB,CAAC;IAoC9B;;;OAGG;IACI,cAAc,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO;IAKnD;;;;;OAKG;IACI,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,YAAY,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO;IA4B7F;;;;;OAKG;IACI,cAAc,CACnB,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,gCAAgC,EAC1C,SAAS,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,GACnD,OAAO,CAAC,IAAI,CAAC;IAqBhB;;;;OAIG;IACH,SAAS,CAAC,cAAc,CACtB,GAAG,EAAE,yBAAyB,EAC9B,SAAS,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,GACnD,OAAO,CAAC,yBAAyB,CAAC;IAgBrC;;;;;;;OAOG;IACH,SAAS,CAAC,iBAAiB,CAAC,OAAO,CAAC,EAAE,gCAAgC,GAAG,OAAO,CAAC,IAAI,CAAC;IAuCtF;;;OAGG;IACH,SAAS,CAAC,wBAAwB,CAAC,OAAO,CAAC,EAAE,gCAAgC,GAAG,OAAO,CAAC,yBAAyB,CAAC;IAsBlH;;;OAGG;IACH,SAAS,CAAC,mBAAmB,CAAC,OAAO,CAAC,EAAE,gCAAgC,GAAG,OAAO,CAAC,IAAI,CAAC;IA+BxF;;;;;;;;OAQG;IACH,SAAS,CAAC,mBAAmB,CAAC,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC;IAgFjE;;OAEG;IACH,SAAS,CAAC,0BAA0B,IAAI,OAAO,CAAC,qBAAqB,CAAC;IAYtE;;;OAGG;IACH,SAAS,CAAC,0BAA0B,CAAC,kBAAkB,EAAE,yBAAyB,GAAG,OAAO,CAAC,IAAI,CAAC;IAQlG;;;OAGG;IACH,SAAS,CAAC,2BAA2B,CAAC,kBAAkB,EAAE,yBAAyB,GAAG,OAAO,CAAC,IAAI,CAAC;IA8BnG;;;;;;;OAOG;IACH,SAAS,CAAC,cAAc,CAAC,KAAK,EAAE,gBAAgB,GAAG,IAAI;IA4BvD;;OAEG;IACH,SAAS,CAAC,oBAAoB,IAAI,IAAI;IAkBtC;;;;OAIG;IACH,SAAS,CAAC,2BAA2B,CAAC,OAAO,UAAQ,EAAE,OAAO,SAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAgClF;;OAEG;IACH,OAAO,CAAC,+BAA+B;CA0FxC"} \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/session-description-handler.js b/lib/platform/web/session-description-handler/session-description-handler.js new file mode 100644 index 000000000..003192159 --- /dev/null +++ b/lib/platform/web/session-description-handler/session-description-handler.js @@ -0,0 +1,661 @@ +/** + * A base class implementing a WebRTC session description handler for sip.js. + * @remarks + * It is expected/intended to be extended by specific WebRTC based applications. + * @privateRemarks + * So do not put application specific implementation in here. + * @public + */ +export class SessionDescriptionHandler { + /** + * Constructor + * @param logger - A logger + * @param mediaStreamFactory - A factory to provide a MediaStream + * @param options - Options passed from the SessionDescriptionHandleFactory + */ + constructor(logger, mediaStreamFactory, sessionDescriptionHandlerConfiguration) { + logger.debug("SessionDescriptionHandler.constructor"); + this.logger = logger; + this.mediaStreamFactory = mediaStreamFactory; + this.sessionDescriptionHandlerConfiguration = sessionDescriptionHandlerConfiguration; + this._localMediaStream = new MediaStream(); + this._remoteMediaStream = new MediaStream(); + this._peerConnection = new RTCPeerConnection(sessionDescriptionHandlerConfiguration === null || sessionDescriptionHandlerConfiguration === void 0 ? void 0 : sessionDescriptionHandlerConfiguration.peerConnectionConfiguration); + this.initPeerConnectionEventHandlers(); + } + /** + * The local media stream currently being sent. + * + * @remarks + * The local media stream initially has no tracks, so the presence of tracks + * should not be assumed. Furthermore, tracks may be added or removed if the + * local media changes - for example, on upgrade from audio only to a video session. + * At any given time there will be at most one audio track and one video track + * (it's possible that this restriction may not apply to sub-classes). + * Use `MediaStream.onaddtrack` or add a listener for the `addtrack` event + * to detect when a new track becomes available: + * https://developer.mozilla.org/en-US/docs/Web/API/MediaStream/onaddtrack + */ + get localMediaStream() { + return this._localMediaStream; + } + /** + * The remote media stream currently being received. + * + * @remarks + * The remote media stream initially has no tracks, so the presence of tracks + * should not be assumed. Furthermore, tracks may be added or removed if the + * remote media changes - for example, on upgrade from audio only to a video session. + * At any given time there will be at most one audio track and one video track + * (it's possible that this restriction may not apply to sub-classes). + * Use `MediaStream.onaddtrack` or add a listener for the `addtrack` event + * to detect when a new track becomes available: + * https://developer.mozilla.org/en-US/docs/Web/API/MediaStream/onaddtrack + */ + get remoteMediaStream() { + return this._remoteMediaStream; + } + /** + * The data channel. Undefined before it is created. + */ + get dataChannel() { + return this._dataChannel; + } + /** + * The peer connection. Undefined if peer connection has closed. + * + * @remarks + * While access to the underlying `RTCPeerConnection` is provided, note that + * using methods with modify it may break the operation of this class. + * In particular, this class depends on exclusive access to the + * event handler properties. If you need access to the peer connection + * events, either register for events using `addEventListener()` on + * the `RTCPeerConnection` or set the `peerConnectionDelegate` on + * this `SessionDescriptionHandler`. + */ + get peerConnection() { + return this._peerConnection; + } + /** + * A delegate which provides access to the peer connection event handlers. + * + * @remarks + * Setting the peer connection event handlers directly is not supported + * and may break this class. As this class depends on exclusive access + * to them, a delegate may be set which provides alternative access to + * the event handlers in a fashion which is supported. + */ + get peerConnectionDelegate() { + return this._peerConnectionDelegate; + } + set peerConnectionDelegate(delegate) { + this._peerConnectionDelegate = delegate; + } + // The addtrack event does not get fired when JavaScript code explicitly adds tracks to the stream (by calling addTrack()). + // https://developer.mozilla.org/en-US/docs/Web/API/MediaStream/onaddtrack + static dispatchAddTrackEvent(stream, track) { + stream.dispatchEvent(new MediaStreamTrackEvent("addtrack", { track })); + } + // The removetrack event does not get fired when JavaScript code explicitly removes tracks from the stream (by calling removeTrack()). + // https://developer.mozilla.org/en-US/docs/Web/API/MediaStream/onremovetrack + static dispatchRemoveTrackEvent(stream, track) { + stream.dispatchEvent(new MediaStreamTrackEvent("removetrack", { track })); + } + /** + * Stop tracks and close peer connection. + */ + close() { + this.logger.debug("SessionDescriptionHandler.close"); + if (this._peerConnection === undefined) { + return; + } + this._peerConnection.getReceivers().forEach((receiver) => { + receiver.track && receiver.track.stop(); + }); + this._peerConnection.getSenders().forEach((sender) => { + sender.track && sender.track.stop(); + }); + if (this._dataChannel) { + this._dataChannel.close(); + } + this._peerConnection.close(); + this._peerConnection = undefined; + } + /** + * Creates an offer or answer. + * @param options - Options bucket. + * @param modifiers - Modifiers. + */ + getDescription(options, modifiers) { + var _a, _b; + this.logger.debug("SessionDescriptionHandler.getDescription"); + if (this._peerConnection === undefined) { + return Promise.reject(new Error("Peer connection closed.")); + } + // Callback on data channel creation + this.onDataChannel = options === null || options === void 0 ? void 0 : options.onDataChannel; + // ICE will restart upon applying an offer created with the iceRestart option + const iceRestart = (_a = options === null || options === void 0 ? void 0 : options.offerOptions) === null || _a === void 0 ? void 0 : _a.iceRestart; + // ICE gathering timeout may be set on a per call basis, otherwise the configured default is used + const iceTimeout = (options === null || options === void 0 ? void 0 : options.iceGatheringTimeout) === undefined + ? (_b = this.sessionDescriptionHandlerConfiguration) === null || _b === void 0 ? void 0 : _b.iceGatheringTimeout : options === null || options === void 0 ? void 0 : options.iceGatheringTimeout; + return this.getLocalMediaStream(options) + .then(() => this.createDataChannel(options)) + .then(() => this.createLocalOfferOrAnswer(options)) + .then((sessionDescription) => this.applyModifiers(sessionDescription, modifiers)) + .then((sessionDescription) => this.setLocalSessionDescription(sessionDescription)) + .then(() => this.waitForIceGatheringComplete(iceRestart, iceTimeout)) + .then(() => this.getLocalSessionDescription()) + .then((sessionDescription) => { + return { + body: sessionDescription.sdp, + contentType: "application/sdp" + }; + }) + .catch((error) => { + this.logger.error("SessionDescriptionHandler.getDescription failed - " + error); + throw error; + }); + } + /** + * Returns true if the SessionDescriptionHandler can handle the Content-Type described by a SIP message. + * @param contentType - The content type that is in the SIP Message. + */ + hasDescription(contentType) { + this.logger.debug("SessionDescriptionHandler.hasDescription"); + return contentType === "application/sdp"; + } + /** + * 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. + */ + sendDtmf(tones, options) { + this.logger.debug("SessionDescriptionHandler.sendDtmf"); + if (this._peerConnection === undefined) { + this.logger.error("SessionDescriptionHandler.sendDtmf failed - peer connection closed"); + return false; + } + const senders = this._peerConnection.getSenders(); + if (senders.length === 0) { + this.logger.error("SessionDescriptionHandler.sendDtmf failed - no senders"); + return false; + } + const dtmfSender = senders[0].dtmf; + if (!dtmfSender) { + this.logger.error("SessionDescriptionHandler.sendDtmf failed - no DTMF sender"); + return false; + } + const duration = options === null || options === void 0 ? void 0 : options.duration; + const interToneGap = options === null || options === void 0 ? void 0 : options.interToneGap; + try { + dtmfSender.insertDTMF(tones, duration, interToneGap); + } + catch (e) { + this.logger.error(e); + return false; + } + this.logger.log("SessionDescriptionHandler.sendDtmf sent via RTP: " + tones.toString()); + return true; + } + /** + * Sets an offer or answer. + * @param sdp - The session description. + * @param options - Options bucket. + * @param modifiers - Modifiers. + */ + setDescription(sdp, options, modifiers) { + this.logger.debug("SessionDescriptionHandler.setDescription"); + if (this._peerConnection === undefined) { + return Promise.reject(new Error("Peer connection closed.")); + } + // Callback on data channel creation + this.onDataChannel = options === null || options === void 0 ? void 0 : options.onDataChannel; + // SDP type + const type = this._peerConnection.signalingState === "have-local-offer" ? "answer" : "offer"; + return this.getLocalMediaStream(options) + .then(() => this.applyModifiers({ sdp, type }, modifiers)) + .then((sessionDescription) => this.setRemoteSessionDescription(sessionDescription)) + .catch((error) => { + this.logger.error("SessionDescriptionHandler.setDescription failed - " + error); + throw error; + }); + } + /** + * Applies modifiers to SDP prior to setting the local or remote description. + * @param sdp - SDP to modify. + * @param modifiers - Modifiers to apply. + */ + applyModifiers(sdp, modifiers) { + this.logger.debug("SessionDescriptionHandler.applyModifiers"); + if (!modifiers || modifiers.length === 0) { + return Promise.resolve(sdp); + } + return modifiers + .reduce((cur, next) => cur.then(next), Promise.resolve(sdp)) + .then((modified) => { + this.logger.debug("SessionDescriptionHandler.applyModifiers - modified sdp"); + if (!modified.sdp || !modified.type) { + throw new Error("Invalid SDP."); + } + return { sdp: modified.sdp, type: modified.type }; + }); + } + /** + * Create a data channel. + * @remarks + * Only creates a data channel if SessionDescriptionHandlerOptions.dataChannel is true. + * Only creates a data channel if creating a local offer. + * Only if one does not already exist. + * @param options - Session description handler options. + */ + createDataChannel(options) { + if (this._peerConnection === undefined) { + return Promise.reject(new Error("Peer connection closed.")); + } + // only create a data channel if requested + if ((options === null || options === void 0 ? void 0 : options.dataChannel) !== true) { + return Promise.resolve(); + } + // do not create a data channel if we already have one + if (this._dataChannel) { + return Promise.resolve(); + } + switch (this._peerConnection.signalingState) { + case "stable": + // if we are stable, assume we are creating a local offer so create a data channel + this.logger.debug("SessionDescriptionHandler.createDataChannel - creating data channel"); + try { + this._dataChannel = this._peerConnection.createDataChannel((options === null || options === void 0 ? void 0 : options.dataChannelLabel) || "", options === null || options === void 0 ? void 0 : options.dataChannelOptions); + if (this.onDataChannel) { + this.onDataChannel(this._dataChannel); + } + return Promise.resolve(); + } + catch (error) { + return Promise.reject(error); + } + case "have-remote-offer": + return Promise.resolve(); + case "have-local-offer": + case "have-local-pranswer": + case "have-remote-pranswer": + case "closed": + default: + return Promise.reject(new Error("Invalid signaling state " + this._peerConnection.signalingState)); + } + } + /** + * Depending on current signaling state, create a local offer or answer. + * @param options - Session description handler options. + */ + createLocalOfferOrAnswer(options) { + if (this._peerConnection === undefined) { + return Promise.reject(new Error("Peer connection closed.")); + } + switch (this._peerConnection.signalingState) { + case "stable": + // if we are stable, assume we are creating a local offer + this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP offer"); + return this._peerConnection.createOffer(options === null || options === void 0 ? void 0 : options.offerOptions); + case "have-remote-offer": + // if we have a remote offer, assume we are creating a local answer + this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP answer"); + return this._peerConnection.createAnswer(options === null || options === void 0 ? void 0 : options.answerOptions); + case "have-local-offer": + case "have-local-pranswer": + case "have-remote-pranswer": + case "closed": + default: + return Promise.reject(new Error("Invalid signaling state " + this._peerConnection.signalingState)); + } + } + /** + * Get a media stream from the media stream factory and set the local media stream. + * @param options - Session description handler options. + */ + getLocalMediaStream(options) { + this.logger.debug("SessionDescriptionHandler.getLocalMediaStream"); + if (this._peerConnection === undefined) { + return Promise.reject(new Error("Peer connection closed.")); + } + let constraints = Object.assign({}, options === null || options === void 0 ? void 0 : options.constraints); + // if we already have a local media stream... + if (this.localMediaStreamConstraints) { + // ignore constraint "downgrades" + constraints.audio = constraints.audio || this.localMediaStreamConstraints.audio; + constraints.video = constraints.video || this.localMediaStreamConstraints.video; + // if constraints have not changed, do not get a new media stream + if (JSON.stringify(this.localMediaStreamConstraints.audio) === JSON.stringify(constraints.audio) && + JSON.stringify(this.localMediaStreamConstraints.video) === JSON.stringify(constraints.video)) { + return Promise.resolve(); + } + } + else { + // if no constraints have been specified, default to audio for initial media stream + if (constraints.audio === undefined && constraints.video === undefined) { + constraints = { audio: true }; + } + } + this.localMediaStreamConstraints = constraints; + return this.mediaStreamFactory(constraints, this).then((mediaStream) => this.setLocalMediaStream(mediaStream)); + } + /** + * Sets the peer connection's sender tracks and local media stream tracks. + * + * @remarks + * Only the first audio and video tracks of the provided MediaStream are utilized. + * Adds tracks if audio and/or video tracks are not already present, otherwise replaces tracks. + * + * @param stream - Media stream containing tracks to be utilized. + */ + setLocalMediaStream(stream) { + this.logger.debug("SessionDescriptionHandler.setLocalMediaStream"); + if (!this._peerConnection) { + throw new Error("Peer connection undefined."); + } + const pc = this._peerConnection; + const localStream = this._localMediaStream; + const trackUpdates = []; + const updateTrack = (newTrack) => { + const kind = newTrack.kind; + if (kind !== "audio" && kind !== "video") { + throw new Error(`Unknown new track kind ${kind}.`); + } + const sender = pc.getSenders().find((sender) => sender.track && sender.track.kind === kind); + if (sender) { + trackUpdates.push(new Promise((resolve) => { + this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - replacing sender ${kind} track`); + resolve(); + }).then(() => sender + .replaceTrack(newTrack) + .then(() => { + const oldTrack = localStream.getTracks().find((localTrack) => localTrack.kind === kind); + if (oldTrack) { + oldTrack.stop(); + localStream.removeTrack(oldTrack); + SessionDescriptionHandler.dispatchRemoveTrackEvent(localStream, oldTrack); + } + localStream.addTrack(newTrack); + SessionDescriptionHandler.dispatchAddTrackEvent(localStream, newTrack); + }) + .catch((error) => { + this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to replace sender ${kind} track`); + throw error; + }))); + } + else { + trackUpdates.push(new Promise((resolve) => { + this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - adding sender ${kind} track`); + resolve(); + }).then(() => { + // Review: could make streamless tracks a configurable option? + // https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/addTrack#Usage_notes + try { + pc.addTrack(newTrack, localStream); + } + catch (error) { + this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to add sender ${kind} track`); + throw error; + } + localStream.addTrack(newTrack); + SessionDescriptionHandler.dispatchAddTrackEvent(localStream, newTrack); + })); + } + }; + // update peer connection audio tracks + const audioTracks = stream.getAudioTracks(); + if (audioTracks.length) { + updateTrack(audioTracks[0]); + } + // update peer connection video tracks + const videoTracks = stream.getVideoTracks(); + if (videoTracks.length) { + updateTrack(videoTracks[0]); + } + return trackUpdates.reduce((p, x) => p.then(() => x), Promise.resolve()); + } + /** + * Gets the peer connection's local session description. + */ + getLocalSessionDescription() { + this.logger.debug("SessionDescriptionHandler.getLocalSessionDescription"); + if (this._peerConnection === undefined) { + return Promise.reject(new Error("Peer connection closed.")); + } + const sdp = this._peerConnection.localDescription; + if (!sdp) { + return Promise.reject(new Error("Failed to get local session description")); + } + return Promise.resolve(sdp); + } + /** + * Sets the peer connection's local session description. + * @param sessionDescription - sessionDescription The session description. + */ + setLocalSessionDescription(sessionDescription) { + this.logger.debug("SessionDescriptionHandler.setLocalSessionDescription"); + if (this._peerConnection === undefined) { + return Promise.reject(new Error("Peer connection closed.")); + } + return this._peerConnection.setLocalDescription(sessionDescription); + } + /** + * Sets the peer connection's remote session description. + * @param sessionDescription - The session description. + */ + setRemoteSessionDescription(sessionDescription) { + this.logger.debug("SessionDescriptionHandler.setRemoteSessionDescription"); + if (this._peerConnection === undefined) { + return Promise.reject(new Error("Peer connection closed.")); + } + const sdp = sessionDescription.sdp; + let type; + switch (this._peerConnection.signalingState) { + case "stable": + // if we are stable assume this is a remote offer + type = "offer"; + break; + case "have-local-offer": + // if we made an offer, assume this is a remote answer + type = "answer"; + break; + case "have-local-pranswer": + case "have-remote-offer": + case "have-remote-pranswer": + case "closed": + default: + return Promise.reject(new Error("Invalid signaling state " + this._peerConnection.signalingState)); + } + if (!sdp) { + this.logger.error("SessionDescriptionHandler.setRemoteSessionDescription failed - cannot set null sdp"); + return Promise.reject(new Error("SDP is undefined")); + } + return this._peerConnection.setRemoteDescription({ sdp, type }); + } + /** + * Sets a remote media stream track. + * + * @remarks + * Adds tracks if audio and/or video tracks are not already present, otherwise replaces tracks. + * + * @param track - Media stream track to be utilized. + */ + setRemoteTrack(track) { + this.logger.debug("SessionDescriptionHandler.setRemoteTrack"); + const remoteStream = this._remoteMediaStream; + if (remoteStream.getTrackById(track.id)) { + this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - have remote ${track.kind} track`); + } + else if (track.kind === "audio") { + this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${track.kind} track`); + remoteStream.getAudioTracks().forEach((track) => { + track.stop(); + remoteStream.removeTrack(track); + SessionDescriptionHandler.dispatchRemoveTrackEvent(remoteStream, track); + }); + remoteStream.addTrack(track); + SessionDescriptionHandler.dispatchAddTrackEvent(remoteStream, track); + } + else if (track.kind === "video") { + this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${track.kind} track`); + remoteStream.getVideoTracks().forEach((track) => { + track.stop(); + remoteStream.removeTrack(track); + SessionDescriptionHandler.dispatchRemoveTrackEvent(remoteStream, track); + }); + remoteStream.addTrack(track); + SessionDescriptionHandler.dispatchAddTrackEvent(remoteStream, track); + } + } + /** + * Called when ICE gathering completes and resolves any waiting promise. + */ + iceGatheringComplete() { + this.logger.debug("SessionDescriptionHandler.iceGatheringComplete"); + // clear timer if need be + if (this.iceGatheringCompleteTimeoutId !== undefined) { + this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - clearing timeout"); + clearTimeout(this.iceGatheringCompleteTimeoutId); + this.iceGatheringCompleteTimeoutId = undefined; + } + // resolve and cleanup promise if need be + if (this.iceGatheringCompletePromise !== undefined) { + this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - resolving promise"); + this.iceGatheringCompleteResolve && this.iceGatheringCompleteResolve(); + this.iceGatheringCompletePromise = undefined; + this.iceGatheringCompleteResolve = undefined; + this.iceGatheringCompleteReject = undefined; + } + } + /** + * Wait for ICE gathering to complete. + * @param restart - If true, waits if current state is "complete" (waits for transition to "complete"). + * @param timeout - Milliseconds after which waiting times out. No timeout if 0. + */ + waitForIceGatheringComplete(restart = false, timeout = 0) { + this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete"); + if (this._peerConnection === undefined) { + return Promise.reject("Peer connection closed."); + } + // guard already complete + if (!restart && this._peerConnection.iceGatheringState === "complete") { + this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - already complete"); + return Promise.resolve(); + } + // only one may be waiting, reject any prior + if (this.iceGatheringCompletePromise !== undefined) { + this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - rejecting prior waiting promise"); + this.iceGatheringCompleteReject && this.iceGatheringCompleteReject(new Error("Promise superseded.")); + this.iceGatheringCompletePromise = undefined; + this.iceGatheringCompleteResolve = undefined; + this.iceGatheringCompleteReject = undefined; + } + this.iceGatheringCompletePromise = new Promise((resolve, reject) => { + this.iceGatheringCompleteResolve = resolve; + this.iceGatheringCompleteReject = reject; + if (timeout > 0) { + this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout in " + timeout); + this.iceGatheringCompleteTimeoutId = setTimeout(() => { + this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout"); + this.iceGatheringComplete(); + }, timeout); + } + }); + return this.iceGatheringCompletePromise; + } + /** + * Initializes the peer connection event handlers + */ + initPeerConnectionEventHandlers() { + this.logger.debug("SessionDescriptionHandler.initPeerConnectionEventHandlers"); + if (!this._peerConnection) + throw new Error("Peer connection undefined."); + const peerConnection = this._peerConnection; + peerConnection.onconnectionstatechange = (event) => { + var _a; + const newState = peerConnection.connectionState; + this.logger.debug(`SessionDescriptionHandler.onconnectionstatechange ${newState}`); + if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onconnectionstatechange) { + this._peerConnectionDelegate.onconnectionstatechange(event); + } + }; + peerConnection.ondatachannel = (event) => { + var _a; + this.logger.debug(`SessionDescriptionHandler.ondatachannel`); + this._dataChannel = event.channel; + if (this.onDataChannel) { + this.onDataChannel(this._dataChannel); + } + if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.ondatachannel) { + this._peerConnectionDelegate.ondatachannel(event); + } + }; + peerConnection.onicecandidate = (event) => { + var _a; + this.logger.debug(`SessionDescriptionHandler.onicecandidate`); + if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onicecandidate) { + this._peerConnectionDelegate.onicecandidate(event); + } + }; + peerConnection.onicecandidateerror = (event) => { + var _a; + this.logger.debug(`SessionDescriptionHandler.onicecandidateerror`); + if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onicecandidateerror) { + this._peerConnectionDelegate.onicecandidateerror(event); + } + }; + peerConnection.oniceconnectionstatechange = (event) => { + var _a; + const newState = peerConnection.iceConnectionState; + this.logger.debug(`SessionDescriptionHandler.oniceconnectionstatechange ${newState}`); + if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.oniceconnectionstatechange) { + this._peerConnectionDelegate.oniceconnectionstatechange(event); + } + }; + peerConnection.onicegatheringstatechange = (event) => { + var _a; + const newState = peerConnection.iceGatheringState; + this.logger.debug(`SessionDescriptionHandler.onicegatheringstatechange ${newState}`); + if (newState === "complete") { + this.iceGatheringComplete(); // complete waiting for ICE gathering to complete + } + if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onicegatheringstatechange) { + this._peerConnectionDelegate.onicegatheringstatechange(event); + } + }; + peerConnection.onnegotiationneeded = (event) => { + var _a; + this.logger.debug(`SessionDescriptionHandler.onnegotiationneeded`); + if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onnegotiationneeded) { + this._peerConnectionDelegate.onnegotiationneeded(event); + } + }; + peerConnection.onsignalingstatechange = (event) => { + var _a; + const newState = peerConnection.signalingState; + this.logger.debug(`SessionDescriptionHandler.onsignalingstatechange ${newState}`); + if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onsignalingstatechange) { + this._peerConnectionDelegate.onsignalingstatechange(event); + } + }; + peerConnection.onstatsended = (event) => { + var _a; + this.logger.debug(`SessionDescriptionHandler.onstatsended`); + if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onstatsended) { + this._peerConnectionDelegate.onstatsended(event); + } + }; + peerConnection.ontrack = (event) => { + var _a; + const kind = event.track.kind; + const enabled = event.track.enabled ? "enabled" : "disabled"; + this.logger.debug(`SessionDescriptionHandler.ontrack ${kind} ${enabled}`); + this.setRemoteTrack(event.track); + if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.ontrack) { + this._peerConnectionDelegate.ontrack(event); + } + }; + } +} diff --git a/lib/platform/web/simple-user/index.d.ts b/lib/platform/web/simple-user/index.d.ts new file mode 100644 index 000000000..ecf9f4fa4 --- /dev/null +++ b/lib/platform/web/simple-user/index.d.ts @@ -0,0 +1,8 @@ +/** + * A simple SIP user implementation for web browsers. + * @packageDocumentation + */ +export * from "./simple-user"; +export * from "./simple-user-delegate"; +export * from "./simple-user-options"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/simple-user/index.d.ts.map b/lib/platform/web/simple-user/index.d.ts.map new file mode 100644 index 000000000..8b8931df7 --- /dev/null +++ b/lib/platform/web/simple-user/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/simple-user/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,cAAc,eAAe,CAAC;AAC9B,cAAc,wBAAwB,CAAC;AACvC,cAAc,uBAAuB,CAAC"} \ No newline at end of file diff --git a/lib/platform/web/simple-user/index.js b/lib/platform/web/simple-user/index.js new file mode 100644 index 000000000..6231e8cd7 --- /dev/null +++ b/lib/platform/web/simple-user/index.js @@ -0,0 +1,7 @@ +/** + * A simple SIP user implementation for web browsers. + * @packageDocumentation + */ +export * from "./simple-user"; +export * from "./simple-user-delegate"; +export * from "./simple-user-options"; diff --git a/lib/platform/web/simple-user/simple-user-delegate.d.ts b/lib/platform/web/simple-user/simple-user-delegate.d.ts new file mode 100644 index 000000000..dff4542c8 --- /dev/null +++ b/lib/platform/web/simple-user/simple-user-delegate.d.ts @@ -0,0 +1,73 @@ +/** + * Delegate for {@link SimpleUser}. + * @public + */ +export interface SimpleUserDelegate { + /** + * Called when a call is answered. + * @remarks + * Callback for handling establishment of a new Session. + */ + onCallAnswered?(): void; + /** + * Called when a call is created. + * @remarks + * Callback for handling the creation of a new Session. + */ + onCallCreated?(): void; + /** + * Called when a call is received. + * @remarks + * Callback for handling incoming INVITE requests. + * The callback must either accept or reject the incoming call by calling `answer()` or `decline()` respectively. + */ + onCallReceived?(): void; + /** + * Called when a call is hung up. + * @remarks + * Callback for handling termination of a Session. + */ + onCallHangup?(): void; + /** + * Called when a call is put on hold or taken off hold. + * @remarks + * Callback for handling re-INVITE responses. + */ + onCallHold?(held: boolean): void; + /** + * Called when a call receives an incoming DTMF tone. + * @remarks + * Callback for handling an incoming INFO request with content type application/dtmf-relay. + */ + onCallDTMFReceived?(tone: string, duration: number): void; + /** + * Called upon receiving a message. + * @remarks + * Callback for handling incoming MESSAGE requests. + * @param message - The message received. + */ + onMessageReceived?(message: string): void; + /** + * Called when user is registered to received calls. + */ + onRegistered?(): void; + /** + * Called when user is no longer registered to received calls. + */ + onUnregistered?(): void; + /** + * Called when user is connected to server. + * @remarks + * Callback for handling user becomes connected. + */ + onServerConnect?(): void; + /** + * Called when user is no longer connected. + * @remarks + * Callback for handling user becomes disconnected. + * + * @param error - An Error if server caused the disconnect. Otherwise undefined. + */ + onServerDisconnect?(error?: Error): void; +} +//# sourceMappingURL=simple-user-delegate.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/simple-user/simple-user-delegate.d.ts.map b/lib/platform/web/simple-user/simple-user-delegate.d.ts.map new file mode 100644 index 000000000..90e080a39 --- /dev/null +++ b/lib/platform/web/simple-user/simple-user-delegate.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"simple-user-delegate.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/simple-user/simple-user-delegate.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,WAAW,kBAAkB;IACjC;;;;OAIG;IACH,cAAc,CAAC,IAAI,IAAI,CAAC;IAExB;;;;OAIG;IACH,aAAa,CAAC,IAAI,IAAI,CAAC;IAEvB;;;;;OAKG;IACH,cAAc,CAAC,IAAI,IAAI,CAAC;IAExB;;;;OAIG;IACH,YAAY,CAAC,IAAI,IAAI,CAAC;IAEtB;;;;OAIG;IACH,UAAU,CAAC,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI,CAAC;IAEjC;;;;OAIG;IACH,kBAAkB,CAAC,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IAE1D;;;;;OAKG;IACH,iBAAiB,CAAC,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IAE1C;;OAEG;IACH,YAAY,CAAC,IAAI,IAAI,CAAC;IAEtB;;OAEG;IACH,cAAc,CAAC,IAAI,IAAI,CAAC;IAExB;;;;OAIG;IACH,eAAe,CAAC,IAAI,IAAI,CAAC;IAEzB;;;;;;OAMG;IACH,kBAAkB,CAAC,CAAC,KAAK,CAAC,EAAE,KAAK,GAAG,IAAI,CAAC;CAC1C"} \ No newline at end of file diff --git a/lib/platform/web/simple-user/simple-user-delegate.js b/lib/platform/web/simple-user/simple-user-delegate.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/platform/web/simple-user/simple-user-delegate.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/platform/web/simple-user/simple-user-options.d.ts b/lib/platform/web/simple-user/simple-user-options.d.ts new file mode 100644 index 000000000..f5feb00cc --- /dev/null +++ b/lib/platform/web/simple-user/simple-user-options.d.ts @@ -0,0 +1,91 @@ +import { UserAgentOptions } from "../../../api"; +import { SimpleUserDelegate } from "./simple-user-delegate"; +/** + * Media for {@link SimpleUserOptions}. + * @public + */ +export interface SimpleUserMedia { + /** + * Offer/Answer constraints determine if audio and/or video are utilized. + * If not specified, only audio is utilized (audio is true, video is false). + * @remarks + * Constraints are used when creating local media stream. + * If undefined, defaults to audio true and video false. + * If audio and video are false, media stream will have no tracks. + */ + constraints?: SimpleUserMediaConstraints; + /** HTML elements for local media streams. */ + local?: SimpleUserMediaLocal; + /** Local HTML media elements. */ + remote?: SimpleUserMediaRemote; +} +/** + * Constraints for {@link SimpleUserMedia}. + * @public + */ +export interface SimpleUserMediaConstraints { + /** If true, offer and answer to send and receive audio. */ + audio: boolean; + /** If true, offer and answer to send and receive video. */ + video: boolean; +} +/** + * Local media elements for {@link SimpleUserMedia}. + * @public + */ +export interface SimpleUserMediaLocal { + /** The local video media stream is attached to this element. */ + video?: HTMLVideoElement; +} +/** + * Remote media elements for {@link SimpleUserMedia}. + * @public + */ +export interface SimpleUserMediaRemote { + /** The remote audio media stream is attached to this element. */ + audio?: HTMLAudioElement; + /** The remote video media stream is attached to this element. */ + video?: HTMLVideoElement; +} +/** + * Options for {@link SimpleUser}. + * @public + */ +export interface SimpleUserOptions { + /** + * User's SIP Address of Record (AOR). + * @remarks + * The AOR is registered to receive incoming calls. + * If not specified, a random anonymous address is created for the user. + */ + aor?: string; + /** + * Delegate for SimpleUser. + */ + delegate?: SimpleUserDelegate; + /** + * Media options. + */ + media?: SimpleUserMedia; + /** + * Maximum number of times to attempt to reconnection. + * @remarks + * When the transport connection is lost (WebSocket disconnects), + * reconnection will be attempted immediately. If that fails, + * reconnection will be attempted again when the browser indicates + * the application has come online. See: + * https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine + * @defaultValue 3 + */ + reconnectionAttempts?: number; + /** + * Seconds to wait between reconnection attempts. + * @defaultValue 4 + */ + reconnectionDelay?: number; + /** + * Options for UserAgent. + */ + userAgentOptions?: UserAgentOptions; +} +//# sourceMappingURL=simple-user-options.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/simple-user/simple-user-options.d.ts.map b/lib/platform/web/simple-user/simple-user-options.d.ts.map new file mode 100644 index 000000000..b904deb68 --- /dev/null +++ b/lib/platform/web/simple-user/simple-user-options.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"simple-user-options.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/simple-user/simple-user-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAChD,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAE5D;;;GAGG;AACH,MAAM,WAAW,eAAe;IAC9B;;;;;;;OAOG;IACH,WAAW,CAAC,EAAE,0BAA0B,CAAC;IAEzC,6CAA6C;IAC7C,KAAK,CAAC,EAAE,oBAAoB,CAAC;IAE7B,iCAAiC;IACjC,MAAM,CAAC,EAAE,qBAAqB,CAAC;CAChC;AAED;;;GAGG;AACH,MAAM,WAAW,0BAA0B;IACzC,2DAA2D;IAC3D,KAAK,EAAE,OAAO,CAAC;IACf,2DAA2D;IAC3D,KAAK,EAAE,OAAO,CAAC;CAChB;AAED;;;GAGG;AACH,MAAM,WAAW,oBAAoB;IACnC,gEAAgE;IAChE,KAAK,CAAC,EAAE,gBAAgB,CAAC;CAC1B;AAED;;;GAGG;AACH,MAAM,WAAW,qBAAqB;IACpC,iEAAiE;IACjE,KAAK,CAAC,EAAE,gBAAgB,CAAC;IACzB,iEAAiE;IACjE,KAAK,CAAC,EAAE,gBAAgB,CAAC;CAC1B;AAED;;;GAGG;AACH,MAAM,WAAW,iBAAiB;IAChC;;;;;OAKG;IACH,GAAG,CAAC,EAAE,MAAM,CAAC;IAEb;;OAEG;IACH,QAAQ,CAAC,EAAE,kBAAkB,CAAC;IAE9B;;OAEG;IACH,KAAK,CAAC,EAAE,eAAe,CAAC;IAExB;;;;;;;;;OASG;IACH,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAE9B;;;OAGG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAE3B;;OAEG;IACH,gBAAgB,CAAC,EAAE,gBAAgB,CAAC;CACrC"} \ No newline at end of file diff --git a/lib/platform/web/simple-user/simple-user-options.js b/lib/platform/web/simple-user/simple-user-options.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/platform/web/simple-user/simple-user-options.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/platform/web/simple-user/simple-user.d.ts b/lib/platform/web/simple-user/simple-user.d.ts new file mode 100644 index 000000000..70e4da390 --- /dev/null +++ b/lib/platform/web/simple-user/simple-user.d.ts @@ -0,0 +1,224 @@ +import { InvitationAcceptOptions, InviterInviteOptions, InviterOptions, RegistererOptions, RegistererRegisterOptions, RegistererUnregisterOptions } from "../../../api"; +import { SimpleUserDelegate } from "./simple-user-delegate"; +import { SimpleUserOptions } from "./simple-user-options"; +/** + * A simple SIP user class. + * @remarks + * While this class is completely functional for simple use cases, it is not intended + * to provide an interface which is suitable for most (must less all) applications. + * While this class has many limitations (for example, it only handles a single concurrent session), + * it is, however, intended to serve as a simple example of using the SIP.js API. + * @public + */ +export declare class SimpleUser { + /** Delegate. */ + delegate: SimpleUserDelegate | undefined; + private attemptingReconnection; + private connectRequested; + private logger; + private held; + private options; + private registerer; + private registerRequested; + private session; + private userAgent; + /** + * Constructs a new instance of the `SimpleUser` class. + * @param server - SIP WebSocket Server URL. + * @param options - Options bucket. See {@link SimpleUserOptions} for details. + */ + constructor(server: string, options?: SimpleUserOptions); + /** + * Instance identifier. + * @internal + */ + get id(): string; + /** The local media stream. Undefined if call not answered. */ + get localMediaStream(): MediaStream | undefined; + /** The remote media stream. Undefined if call not answered. */ + get remoteMediaStream(): MediaStream | undefined; + /** + * The local audio track, if available. + * @deprecated Use localMediaStream and get track from the stream. + */ + get localAudioTrack(): MediaStreamTrack | undefined; + /** + * The local video track, if available. + * @deprecated Use localMediaStream and get track from the stream. + */ + get localVideoTrack(): MediaStreamTrack | undefined; + /** + * The remote audio track, if available. + * @deprecated Use remoteMediaStream and get track from the stream. + */ + get remoteAudioTrack(): MediaStreamTrack | undefined; + /** + * The remote video track, if available. + * @deprecated Use remoteMediaStream and get track from the stream. + */ + get remoteVideoTrack(): MediaStreamTrack | undefined; + /** + * Connect. + * @remarks + * Start the UserAgent's WebSocket Transport. + */ + connect(): Promise; + /** + * Disconnect. + * @remarks + * Stop the UserAgent's WebSocket Transport. + */ + disconnect(): Promise; + /** + * Return true if connected. + */ + isConnected(): boolean; + /** + * Start receiving incoming calls. + * @remarks + * Send a REGISTER request for the UserAgent's AOR. + * Resolves when the REGISTER request is sent, otherwise rejects. + */ + register(registererOptions?: RegistererOptions, registererRegisterOptions?: RegistererRegisterOptions): Promise; + /** + * Stop receiving incoming calls. + * @remarks + * Send an un-REGISTER request for the UserAgent's AOR. + * Resolves when the un-REGISTER request is sent, otherwise rejects. + */ + unregister(registererUnregisterOptions?: RegistererUnregisterOptions): Promise; + /** + * Make an outgoing call. + * @remarks + * Send an INVITE request to create a new Session. + * Resolves when the INVITE request is sent, otherwise rejects. + * Use `onCallAnswered` delegate method to determine if Session is established. + * @param destination - The target destination to call. A SIP address to send the INVITE to. + * @param inviterOptions - Optional options for Inviter constructor. + * @param inviterInviteOptions - Optional options for Inviter.invite(). + */ + call(destination: string, inviterOptions?: InviterOptions, inviterInviteOptions?: InviterInviteOptions): Promise; + /** + * Hangup a call. + * @remarks + * Send a BYE request, CANCEL request or reject response to end the current Session. + * Resolves when the request/response is sent, otherwise rejects. + * Use `onCallTerminated` delegate method to determine if and when call is ended. + */ + hangup(): Promise; + /** + * Answer an incoming call. + * @remarks + * Accept an incoming INVITE request creating a new Session. + * Resolves with the response is sent, otherwise rejects. + * Use `onCallAnswered` delegate method to determine if and when call is established. + * @param invitationAcceptOptions - Optional options for Inviter.accept(). + */ + answer(invitationAcceptOptions?: InvitationAcceptOptions): Promise; + /** + * Decline an incoming call. + * @remarks + * Reject an incoming INVITE request. + * Resolves with the response is sent, otherwise rejects. + * Use `onCallTerminated` delegate method to determine if and when call is ended. + */ + decline(): Promise; + /** + * Hold call + * @remarks + * Send a re-INVITE with new offer indicating "hold". + * Resolves when the re-INVITE request is sent, otherwise rejects. + * Use `onCallHold` delegate method to determine if request is accepted or rejected. + * See: https://tools.ietf.org/html/rfc6337 + */ + hold(): Promise; + /** + * Unhold call. + * @remarks + * Send a re-INVITE with new offer indicating "unhold". + * Resolves when the re-INVITE request is sent, otherwise rejects. + * Use `onCallHold` delegate method to determine if request is accepted or rejected. + * See: https://tools.ietf.org/html/rfc6337 + */ + unhold(): Promise; + /** + * Hold state. + * @remarks + * True if session media is on hold. + */ + isHeld(): boolean; + /** + * Mute call. + * @remarks + * Disable sender's media tracks. + */ + mute(): void; + /** + * Unmute call. + * @remarks + * Enable sender's media tracks. + */ + unmute(): void; + /** + * Mute state. + * @remarks + * True if sender's media track is disabled. + */ + isMuted(): boolean; + /** + * Send DTMF. + * @remarks + * Send an INFO request with content type application/dtmf-relay. + * @param tone - Tone to send. + */ + sendDTMF(tone: string): Promise; + /** + * Send a message. + * @remarks + * Send a MESSAGE request. + * @param destination - The target destination for the message. A SIP address to send the MESSAGE to. + */ + message(destination: string, message: string): Promise; + /** Media constraints. */ + private get constraints(); + /** + * Attempt reconnection up to `maxReconnectionAttempts` times. + * @param reconnectionAttempt - Current attempt number. + */ + private attemptReconnection; + /** Helper function to remove media from html elements. */ + private cleanupMedia; + /** Helper function to enable/disable media tracks. */ + private enableSenderTracks; + /** + * Setup session delegate and state change handler. + * @param session - Session to setup + * @param referralInviterOptions - Options for any Inviter created as result of a REFER. + */ + private initSession; + /** Helper function to init send then send invite. */ + private sendInvite; + /** + * Puts Session on hold. + * @param hold - Hold on if true, off if false. + */ + private setHold; + /** + * Puts Session on mute. + * @param mute - Mute on if true, off if false. + */ + private setMute; + /** Helper function to attach local media to html elements. */ + private setupLocalMedia; + /** Helper function to attach remote media to html elements. */ + private setupRemoteMedia; + /** + * End a session. + * @remarks + * Send a BYE request, CANCEL request or reject response to end the current Session. + * Resolves when the request/response is sent, otherwise rejects. + * Use `onCallTerminated` delegate method to determine if and when Session is terminated. + */ + private terminate; +} +//# sourceMappingURL=simple-user.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/simple-user/simple-user.d.ts.map b/lib/platform/web/simple-user/simple-user.d.ts.map new file mode 100644 index 000000000..9b9123774 --- /dev/null +++ b/lib/platform/web/simple-user/simple-user.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"simple-user.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/simple-user/simple-user.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,uBAAuB,EAEvB,oBAAoB,EACpB,cAAc,EAKd,iBAAiB,EACjB,yBAAyB,EAEzB,2BAA2B,EAQ5B,MAAM,cAAc,CAAC;AAKtB,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAC5D,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAE1D;;;;;;;;GAQG;AACH,qBAAa,UAAU;IACrB,gBAAgB;IACT,QAAQ,EAAE,kBAAkB,GAAG,SAAS,CAAC;IAEhD,OAAO,CAAC,sBAAsB,CAAS;IACvC,OAAO,CAAC,gBAAgB,CAAS;IACjC,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,IAAI,CAAS;IACrB,OAAO,CAAC,OAAO,CAAoB;IACnC,OAAO,CAAC,UAAU,CAAqC;IACvD,OAAO,CAAC,iBAAiB,CAAS;IAClC,OAAO,CAAC,OAAO,CAAkC;IACjD,OAAO,CAAC,SAAS,CAAY;IAE7B;;;;OAIG;gBACS,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,iBAAsB;IAoJ3D;;;OAGG;IACH,IAAI,EAAE,IAAI,MAAM,CAEf;IAED,8DAA8D;IAC9D,IAAI,gBAAgB,IAAI,WAAW,GAAG,SAAS,CAS9C;IAED,+DAA+D;IAC/D,IAAI,iBAAiB,IAAI,WAAW,GAAG,SAAS,CAS/C;IAED;;;OAGG;IACH,IAAI,eAAe,IAAI,gBAAgB,GAAG,SAAS,CAElD;IAED;;;OAGG;IACH,IAAI,eAAe,IAAI,gBAAgB,GAAG,SAAS,CAElD;IAED;;;OAGG;IACH,IAAI,gBAAgB,IAAI,gBAAgB,GAAG,SAAS,CAEnD;IAED;;;OAGG;IACH,IAAI,gBAAgB,IAAI,gBAAgB,GAAG,SAAS,CAEnD;IAED;;;;OAIG;IACI,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAS/B;;;;OAIG;IACI,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAMlC;;OAEG;IACI,WAAW,IAAI,OAAO;IAI7B;;;;;OAKG;IACI,QAAQ,CACb,iBAAiB,CAAC,EAAE,iBAAiB,EACrC,yBAAyB,CAAC,EAAE,yBAAyB,GACpD,OAAO,CAAC,IAAI,CAAC;IAkChB;;;;;OAKG;IACI,UAAU,CAAC,2BAA2B,CAAC,EAAE,2BAA2B,GAAG,OAAO,CAAC,IAAI,CAAC;IAa3F;;;;;;;;;OASG;IACI,IAAI,CACT,WAAW,EAAE,MAAM,EACnB,cAAc,CAAC,EAAE,cAAc,EAC/B,oBAAoB,CAAC,EAAE,oBAAoB,GAC1C,OAAO,CAAC,IAAI,CAAC;IAgChB;;;;;;OAMG;IACI,MAAM,IAAI,OAAO,CAAC,IAAI,CAAC;IAK9B;;;;;;;OAOG;IACI,MAAM,CAAC,uBAAuB,CAAC,EAAE,uBAAuB,GAAG,OAAO,CAAC,IAAI,CAAC;IAyB/E;;;;;;OAMG;IACI,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAc/B;;;;;;;OAOG;IACI,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAK5B;;;;;;;OAOG;IACI,MAAM,IAAI,OAAO,CAAC,IAAI,CAAC;IAK9B;;;;OAIG;IACI,MAAM,IAAI,OAAO;IAIxB;;;;OAIG;IACI,IAAI,IAAI,IAAI;IAKnB;;;;OAIG;IACI,MAAM,IAAI,IAAI;IAKrB;;;;OAIG;IACI,OAAO,IAAI,OAAO;IAKzB;;;;;OAKG;IACI,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IA6C5C;;;;;OAKG;IACI,OAAO,CAAC,WAAW,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAUnE,yBAAyB;IACzB,OAAO,KAAK,WAAW,GAMtB;IAED;;;OAGG;IACH,OAAO,CAAC,mBAAmB;IA0D3B,0DAA0D;IAC1D,OAAO,CAAC,YAAY;IAqBpB,sDAAsD;IACtD,OAAO,CAAC,kBAAkB;IAsB1B;;;;OAIG;IACH,OAAO,CAAC,WAAW;IAkInB,qDAAqD;IACrD,OAAO,CAAC,UAAU;IAclB;;;OAGG;IACH,OAAO,CAAC,OAAO;IAoEf;;;OAGG;IACH,OAAO,CAAC,OAAO;IAcf,8DAA8D;IAC9D,OAAO,CAAC,eAAe;IAoBvB,+DAA+D;IAC/D,OAAO,CAAC,gBAAgB;IA6BxB;;;;;;OAMG;IACH,OAAO,CAAC,SAAS;CA+ClB"} \ No newline at end of file diff --git a/lib/platform/web/simple-user/simple-user.js b/lib/platform/web/simple-user/simple-user.js new file mode 100644 index 000000000..2624b2223 --- /dev/null +++ b/lib/platform/web/simple-user/simple-user.js @@ -0,0 +1,925 @@ +import { Invitation, Inviter, Messager, Registerer, RegistererState, RequestPendingError, SessionState, UserAgent, UserAgentState } from "../../../api"; +import { holdModifier } from "../modifiers"; +import { SessionDescriptionHandler } from "../session-description-handler"; +import { Transport } from "../transport"; +/** + * A simple SIP user class. + * @remarks + * While this class is completely functional for simple use cases, it is not intended + * to provide an interface which is suitable for most (must less all) applications. + * While this class has many limitations (for example, it only handles a single concurrent session), + * it is, however, intended to serve as a simple example of using the SIP.js API. + * @public + */ +export class SimpleUser { + /** + * Constructs a new instance of the `SimpleUser` class. + * @param server - SIP WebSocket Server URL. + * @param options - Options bucket. See {@link SimpleUserOptions} for details. + */ + constructor(server, options = {}) { + this.attemptingReconnection = false; + this.connectRequested = false; + this.held = false; + this.registerer = undefined; + this.registerRequested = false; + this.session = undefined; + // Delegate + this.delegate = options.delegate; + // Copy options + this.options = Object.assign({}, options); + // UserAgentOptions + const userAgentOptions = Object.assign({}, options.userAgentOptions); + // Transport + if (!userAgentOptions.transportConstructor) { + userAgentOptions.transportConstructor = Transport; + } + // TransportOptions + if (!userAgentOptions.transportOptions) { + userAgentOptions.transportOptions = { + server + }; + } + // URI + if (!userAgentOptions.uri) { + // If an AOR was provided, convert it to a URI + if (options.aor) { + const uri = UserAgent.makeURI(options.aor); + if (!uri) { + throw new Error(`Failed to create valid URI from ${options.aor}`); + } + userAgentOptions.uri = uri; + } + } + // UserAgent + this.userAgent = new UserAgent(userAgentOptions); + // UserAgent's delegate + this.userAgent.delegate = { + // Handle connection with server established + onConnect: () => { + this.logger.log(`[${this.id}] Connected`); + if (this.delegate && this.delegate.onServerConnect) { + this.delegate.onServerConnect(); + } + if (this.registerer && this.registerRequested) { + this.logger.log(`[${this.id}] Registering...`); + this.registerer.register().catch((e) => { + this.logger.error(`[${this.id}] Error occurred registering after connection with server was obtained.`); + this.logger.error(e.toString()); + }); + } + }, + // Handle connection with server lost + onDisconnect: (error) => { + this.logger.log(`[${this.id}] Disconnected`); + if (this.delegate && this.delegate.onServerDisconnect) { + this.delegate.onServerDisconnect(error); + } + if (this.session) { + this.logger.log(`[${this.id}] Hanging up...`); + this.hangup() // cleanup hung calls + .catch((e) => { + this.logger.error(`[${this.id}] Error occurred hanging up call after connection with server was lost.`); + this.logger.error(e.toString()); + }); + } + if (this.registerer) { + this.logger.log(`[${this.id}] Unregistering...`); + this.registerer + .unregister() // cleanup invalid registrations + .catch((e) => { + this.logger.error(`[${this.id}] Error occurred unregistering after connection with server was lost.`); + this.logger.error(e.toString()); + }); + } + // Only attempt to reconnect if network/server dropped the connection. + if (error) { + this.attemptReconnection(); + } + }, + // Handle incoming invitations + onInvite: (invitation) => { + this.logger.log(`[${this.id}] Received INVITE`); + // Guard against a pre-existing session. This implementation only supports one session at a time. + // However an incoming INVITE request may be received at any time and/or while in the process + // of sending an outgoing INVITE request. So we reject any incoming INVITE in those cases. + if (this.session) { + this.logger.warn(`[${this.id}] Session already in progress, rejecting INVITE...`); + invitation + .reject() + .then(() => { + this.logger.log(`[${this.id}] Rejected INVITE`); + }) + .catch((error) => { + this.logger.error(`[${this.id}] Failed to reject INVITE`); + this.logger.error(error.toString()); + }); + return; + } + // Use our configured constraints as options for any Inviter created as result of a REFER + const referralInviterOptions = { + sessionDescriptionHandlerOptions: { constraints: this.constraints } + }; + // Initialize our session + this.initSession(invitation, referralInviterOptions); + // Delegate + if (this.delegate && this.delegate.onCallReceived) { + this.delegate.onCallReceived(); + } + else { + this.logger.warn(`[${this.id}] No handler available, rejecting INVITE...`); + invitation + .reject() + .then(() => { + this.logger.log(`[${this.id}] Rejected INVITE`); + }) + .catch((error) => { + this.logger.error(`[${this.id}] Failed to reject INVITE`); + this.logger.error(error.toString()); + }); + } + }, + // Handle incoming messages + onMessage: (message) => { + message.accept().then(() => { + if (this.delegate && this.delegate.onMessageReceived) { + this.delegate.onMessageReceived(message.request.body); + } + }); + } + }; + // Use the SIP.js logger + this.logger = this.userAgent.getLogger("sip.SimpleUser"); + // Monitor network connectivity and attempt reconnection when we come online + window.addEventListener("online", () => { + this.logger.log(`[${this.id}] Online`); + this.attemptReconnection(); + }); + } + /** + * Instance identifier. + * @internal + */ + get id() { + return (this.options.userAgentOptions && this.options.userAgentOptions.displayName) || "Anonymous"; + } + /** The local media stream. Undefined if call not answered. */ + get localMediaStream() { + var _a; + const sdh = (_a = this.session) === null || _a === void 0 ? void 0 : _a.sessionDescriptionHandler; + if (!sdh) { + return undefined; + } + if (!(sdh instanceof SessionDescriptionHandler)) { + throw new Error("Session description handler not instance of web SessionDescriptionHandler"); + } + return sdh.localMediaStream; + } + /** The remote media stream. Undefined if call not answered. */ + get remoteMediaStream() { + var _a; + const sdh = (_a = this.session) === null || _a === void 0 ? void 0 : _a.sessionDescriptionHandler; + if (!sdh) { + return undefined; + } + if (!(sdh instanceof SessionDescriptionHandler)) { + throw new Error("Session description handler not instance of web SessionDescriptionHandler"); + } + return sdh.remoteMediaStream; + } + /** + * The local audio track, if available. + * @deprecated Use localMediaStream and get track from the stream. + */ + get localAudioTrack() { + var _a; + return (_a = this.localMediaStream) === null || _a === void 0 ? void 0 : _a.getTracks().find((track) => track.kind === "audio"); + } + /** + * The local video track, if available. + * @deprecated Use localMediaStream and get track from the stream. + */ + get localVideoTrack() { + var _a; + return (_a = this.localMediaStream) === null || _a === void 0 ? void 0 : _a.getTracks().find((track) => track.kind === "video"); + } + /** + * The remote audio track, if available. + * @deprecated Use remoteMediaStream and get track from the stream. + */ + get remoteAudioTrack() { + var _a; + return (_a = this.remoteMediaStream) === null || _a === void 0 ? void 0 : _a.getTracks().find((track) => track.kind === "audio"); + } + /** + * The remote video track, if available. + * @deprecated Use remoteMediaStream and get track from the stream. + */ + get remoteVideoTrack() { + var _a; + return (_a = this.remoteMediaStream) === null || _a === void 0 ? void 0 : _a.getTracks().find((track) => track.kind === "video"); + } + /** + * Connect. + * @remarks + * Start the UserAgent's WebSocket Transport. + */ + connect() { + this.logger.log(`[${this.id}] Connecting UserAgent...`); + this.connectRequested = true; + if (this.userAgent.state !== UserAgentState.Started) { + return this.userAgent.start(); + } + return this.userAgent.reconnect(); + } + /** + * Disconnect. + * @remarks + * Stop the UserAgent's WebSocket Transport. + */ + disconnect() { + this.logger.log(`[${this.id}] Disconnecting UserAgent...`); + this.connectRequested = false; + return this.userAgent.stop(); + } + /** + * Return true if connected. + */ + isConnected() { + return this.userAgent.isConnected(); + } + /** + * Start receiving incoming calls. + * @remarks + * Send a REGISTER request for the UserAgent's AOR. + * Resolves when the REGISTER request is sent, otherwise rejects. + */ + register(registererOptions, registererRegisterOptions) { + this.logger.log(`[${this.id}] Registering UserAgent...`); + this.registerRequested = true; + if (!this.registerer) { + this.registerer = new Registerer(this.userAgent, registererOptions); + this.registerer.stateChange.addListener((state) => { + switch (state) { + case RegistererState.Initial: + break; + case RegistererState.Registered: + if (this.delegate && this.delegate.onRegistered) { + this.delegate.onRegistered(); + } + break; + case RegistererState.Unregistered: + if (this.delegate && this.delegate.onUnregistered) { + this.delegate.onUnregistered(); + } + break; + case RegistererState.Terminated: + this.registerer = undefined; + break; + default: + throw new Error("Unknown registerer state."); + } + }); + } + return this.registerer.register(registererRegisterOptions).then(() => { + return; + }); + } + /** + * Stop receiving incoming calls. + * @remarks + * Send an un-REGISTER request for the UserAgent's AOR. + * Resolves when the un-REGISTER request is sent, otherwise rejects. + */ + unregister(registererUnregisterOptions) { + this.logger.log(`[${this.id}] Unregistering UserAgent...`); + this.registerRequested = false; + if (!this.registerer) { + return Promise.resolve(); + } + return this.registerer.unregister(registererUnregisterOptions).then(() => { + return; + }); + } + /** + * Make an outgoing call. + * @remarks + * Send an INVITE request to create a new Session. + * Resolves when the INVITE request is sent, otherwise rejects. + * Use `onCallAnswered` delegate method to determine if Session is established. + * @param destination - The target destination to call. A SIP address to send the INVITE to. + * @param inviterOptions - Optional options for Inviter constructor. + * @param inviterInviteOptions - Optional options for Inviter.invite(). + */ + call(destination, inviterOptions, inviterInviteOptions) { + this.logger.log(`[${this.id}] Beginning Session...`); + if (this.session) { + return Promise.reject(new Error("Session already exists.")); + } + const target = UserAgent.makeURI(destination); + if (!target) { + return Promise.reject(new Error(`Failed to create a valid URI from "${destination}"`)); + } + // Use our configured constraints as InviterOptions if none provided + if (!inviterOptions) { + inviterOptions = {}; + } + if (!inviterOptions.sessionDescriptionHandlerOptions) { + inviterOptions.sessionDescriptionHandlerOptions = {}; + } + if (!inviterOptions.sessionDescriptionHandlerOptions.constraints) { + inviterOptions.sessionDescriptionHandlerOptions.constraints = this.constraints; + } + // Create a new Inviter for the outgoing Session + const inviter = new Inviter(this.userAgent, target, inviterOptions); + // Send INVITE + return this.sendInvite(inviter, inviterOptions, inviterInviteOptions).then(() => { + return; + }); + } + /** + * Hangup a call. + * @remarks + * Send a BYE request, CANCEL request or reject response to end the current Session. + * Resolves when the request/response is sent, otherwise rejects. + * Use `onCallTerminated` delegate method to determine if and when call is ended. + */ + hangup() { + this.logger.log(`[${this.id}] Hangup...`); + return this.terminate(); + } + /** + * Answer an incoming call. + * @remarks + * Accept an incoming INVITE request creating a new Session. + * Resolves with the response is sent, otherwise rejects. + * Use `onCallAnswered` delegate method to determine if and when call is established. + * @param invitationAcceptOptions - Optional options for Inviter.accept(). + */ + answer(invitationAcceptOptions) { + this.logger.log(`[${this.id}] Accepting Invitation...`); + if (!this.session) { + return Promise.reject(new Error("Session does not exist.")); + } + if (!(this.session instanceof Invitation)) { + return Promise.reject(new Error("Session not instance of Invitation.")); + } + // Use our configured constraints as InvitationAcceptOptions if none provided + if (!invitationAcceptOptions) { + invitationAcceptOptions = {}; + } + if (!invitationAcceptOptions.sessionDescriptionHandlerOptions) { + invitationAcceptOptions.sessionDescriptionHandlerOptions = {}; + } + if (!invitationAcceptOptions.sessionDescriptionHandlerOptions.constraints) { + invitationAcceptOptions.sessionDescriptionHandlerOptions.constraints = this.constraints; + } + return this.session.accept(invitationAcceptOptions); + } + /** + * Decline an incoming call. + * @remarks + * Reject an incoming INVITE request. + * Resolves with the response is sent, otherwise rejects. + * Use `onCallTerminated` delegate method to determine if and when call is ended. + */ + decline() { + this.logger.log(`[${this.id}] rejecting Invitation...`); + if (!this.session) { + return Promise.reject(new Error("Session does not exist.")); + } + if (!(this.session instanceof Invitation)) { + return Promise.reject(new Error("Session not instance of Invitation.")); + } + return this.session.reject(); + } + /** + * Hold call + * @remarks + * Send a re-INVITE with new offer indicating "hold". + * Resolves when the re-INVITE request is sent, otherwise rejects. + * Use `onCallHold` delegate method to determine if request is accepted or rejected. + * See: https://tools.ietf.org/html/rfc6337 + */ + hold() { + this.logger.log(`[${this.id}] holding session...`); + return this.setHold(true); + } + /** + * Unhold call. + * @remarks + * Send a re-INVITE with new offer indicating "unhold". + * Resolves when the re-INVITE request is sent, otherwise rejects. + * Use `onCallHold` delegate method to determine if request is accepted or rejected. + * See: https://tools.ietf.org/html/rfc6337 + */ + unhold() { + this.logger.log(`[${this.id}] unholding session...`); + return this.setHold(false); + } + /** + * Hold state. + * @remarks + * True if session media is on hold. + */ + isHeld() { + return this.held; + } + /** + * Mute call. + * @remarks + * Disable sender's media tracks. + */ + mute() { + this.logger.log(`[${this.id}] disabling media tracks...`); + this.setMute(true); + } + /** + * Unmute call. + * @remarks + * Enable sender's media tracks. + */ + unmute() { + this.logger.log(`[${this.id}] enabling media tracks...`); + this.setMute(false); + } + /** + * Mute state. + * @remarks + * True if sender's media track is disabled. + */ + isMuted() { + const track = this.localAudioTrack || this.localVideoTrack; + return track ? !track.enabled : false; + } + /** + * Send DTMF. + * @remarks + * Send an INFO request with content type application/dtmf-relay. + * @param tone - Tone to send. + */ + sendDTMF(tone) { + this.logger.log(`[${this.id}] sending DTMF...`); + // As RFC 6086 states, sending DTMF via INFO is not standardized... + // + // Companies have been using INFO messages in order to transport + // Dual-Tone Multi-Frequency (DTMF) tones. All mechanisms are + // proprietary and have not been standardized. + // https://tools.ietf.org/html/rfc6086#section-2 + // + // It is however widely supported based on this draft: + // https://tools.ietf.org/html/draft-kaplan-dispatch-info-dtmf-package-00 + // Validate tone + if (!/^[0-9A-D#*,]$/.exec(tone)) { + return Promise.reject(new Error("Invalid DTMF tone.")); + } + if (!this.session) { + return Promise.reject(new Error("Session does not exist.")); + } + // The UA MUST populate the "application/dtmf-relay" body, as defined + // earlier, with the button pressed and the duration it was pressed + // for. Technically, this actually requires the INFO to be generated + // when the user *releases* the button, however if the user has still + // not released a button after 5 seconds, which is the maximum duration + // supported by this mechanism, the UA should generate the INFO at that + // time. + // https://tools.ietf.org/html/draft-kaplan-dispatch-info-dtmf-package-00#section-5.3 + this.logger.log(`[${this.id}] Sending DTMF tone: ${tone}`); + const dtmf = tone; + const duration = 2000; + const body = { + contentDisposition: "render", + contentType: "application/dtmf-relay", + content: "Signal=" + dtmf + "\r\nDuration=" + duration + }; + const requestOptions = { body }; + return this.session.info({ requestOptions }).then(() => { + return; + }); + } + /** + * Send a message. + * @remarks + * Send a MESSAGE request. + * @param destination - The target destination for the message. A SIP address to send the MESSAGE to. + */ + message(destination, message) { + this.logger.log(`[${this.id}] sending message...`); + const target = UserAgent.makeURI(destination); + if (!target) { + return Promise.reject(new Error(`Failed to create a valid URI from "${destination}"`)); + } + return new Messager(this.userAgent, target, message).message(); + } + /** Media constraints. */ + get constraints() { + var _a; + let constraints = { audio: true, video: false }; // default to audio only calls + if ((_a = this.options.media) === null || _a === void 0 ? void 0 : _a.constraints) { + constraints = Object.assign({}, this.options.media.constraints); + } + return constraints; + } + /** + * Attempt reconnection up to `maxReconnectionAttempts` times. + * @param reconnectionAttempt - Current attempt number. + */ + attemptReconnection(reconnectionAttempt = 1) { + const reconnectionAttempts = this.options.reconnectionAttempts || 3; + const reconnectionDelay = this.options.reconnectionDelay || 4; + if (!this.connectRequested) { + this.logger.log(`[${this.id}] Reconnection not currently desired`); + return; // If intentionally disconnected, don't reconnect. + } + if (this.attemptingReconnection) { + this.logger.log(`[${this.id}] Reconnection attempt already in progress`); + } + if (reconnectionAttempt > reconnectionAttempts) { + this.logger.log(`[${this.id}] Reconnection maximum attempts reached`); + return; + } + if (reconnectionAttempt === 1) { + this.logger.log(`[${this.id}] Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - trying`); + } + else { + this.logger.log(`[${this.id}] Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - trying in ${reconnectionDelay} seconds`); + } + this.attemptingReconnection = true; + setTimeout(() => { + if (!this.connectRequested) { + this.logger.log(`[${this.id}] Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - aborted`); + this.attemptingReconnection = false; + return; // If intentionally disconnected, don't reconnect. + } + this.userAgent + .reconnect() + .then(() => { + this.logger.log(`[${this.id}] Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - succeeded`); + this.attemptingReconnection = false; + }) + .catch((error) => { + this.logger.log(`[${this.id}] Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - failed`); + this.logger.error(error.message); + this.attemptingReconnection = false; + this.attemptReconnection(++reconnectionAttempt); + }); + }, reconnectionAttempt === 1 ? 0 : reconnectionDelay * 1000); + } + /** Helper function to remove media from html elements. */ + cleanupMedia() { + if (this.options.media) { + if (this.options.media.local) { + if (this.options.media.local.video) { + this.options.media.local.video.srcObject = null; + this.options.media.local.video.pause(); + } + } + if (this.options.media.remote) { + if (this.options.media.remote.audio) { + this.options.media.remote.audio.srcObject = null; + this.options.media.remote.audio.pause(); + } + if (this.options.media.remote.video) { + this.options.media.remote.video.srcObject = null; + this.options.media.remote.video.pause(); + } + } + } + } + /** Helper function to enable/disable media tracks. */ + enableSenderTracks(enable) { + if (!this.session) { + throw new Error("Session does not exist."); + } + const sessionDescriptionHandler = this.session.sessionDescriptionHandler; + if (!(sessionDescriptionHandler instanceof SessionDescriptionHandler)) { + throw new Error("Session's session description handler not instance of SessionDescriptionHandler."); + } + const peerConnection = sessionDescriptionHandler.peerConnection; + if (!peerConnection) { + throw new Error("Peer connection closed."); + } + peerConnection.getSenders().forEach((sender) => { + if (sender.track) { + sender.track.enabled = enable; + } + }); + } + /** + * Setup session delegate and state change handler. + * @param session - Session to setup + * @param referralInviterOptions - Options for any Inviter created as result of a REFER. + */ + initSession(session, referralInviterOptions) { + // Set session + this.session = session; + // Call session created callback + if (this.delegate && this.delegate.onCallCreated) { + this.delegate.onCallCreated(); + } + // Setup session state change handler + this.session.stateChange.addListener((state) => { + if (this.session !== session) { + return; // if our session has changed, just return + } + this.logger.log(`[${this.id}] session state changed to ${state}`); + switch (state) { + case SessionState.Initial: + break; + case SessionState.Establishing: + break; + case SessionState.Established: + this.setupLocalMedia(); + this.setupRemoteMedia(); + if (this.delegate && this.delegate.onCallAnswered) { + this.delegate.onCallAnswered(); + } + break; + case SessionState.Terminating: + // fall through + case SessionState.Terminated: + this.session = undefined; + this.cleanupMedia(); + if (this.delegate && this.delegate.onCallHangup) { + this.delegate.onCallHangup(); + } + break; + default: + throw new Error("Unknown session state."); + } + }); + // Setup delegate + this.session.delegate = { + onInfo: (info) => { + // As RFC 6086 states, sending DTMF via INFO is not standardized... + // + // Companies have been using INFO messages in order to transport + // Dual-Tone Multi-Frequency (DTMF) tones. All mechanisms are + // proprietary and have not been standardized. + // https://tools.ietf.org/html/rfc6086#section-2 + // + // It is however widely supported based on this draft: + // https://tools.ietf.org/html/draft-kaplan-dispatch-info-dtmf-package-00 + var _a; + // FIXME: TODO: We should reject correctly... + // + // 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. + // https://tools.ietf.org/html/rfc6086#section-4.2.2 + // No delegate + if (((_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onCallDTMFReceived) === undefined) { + info.reject(); + return; + } + // Invalid content type + const contentType = info.request.getHeader("content-type"); + if (!contentType || !/^application\/dtmf-relay/i.exec(contentType)) { + info.reject(); + return; + } + // Invalid body + const body = info.request.body.split("\r\n", 2); + if (body.length !== 2) { + info.reject(); + return; + } + // Invalid tone + let tone; + const toneRegExp = /^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/; + if (toneRegExp.test(body[0])) { + tone = body[0].replace(toneRegExp, "$2"); + } + if (!tone) { + info.reject(); + return; + } + // Invalid duration + let duration; + const durationRegExp = /^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/; + if (durationRegExp.test(body[1])) { + duration = parseInt(body[1].replace(durationRegExp, "$2"), 10); + } + if (!duration) { + info.reject(); + return; + } + info + .accept() + .then(() => { + if (this.delegate && this.delegate.onCallDTMFReceived) { + if (!tone || !duration) { + throw new Error("Tone or duration undefined."); + } + this.delegate.onCallDTMFReceived(tone, duration); + } + }) + .catch((error) => { + this.logger.error(error.message); + }); + }, + onRefer: (referral) => { + referral + .accept() + .then(() => this.sendInvite(referral.makeInviter(referralInviterOptions), referralInviterOptions)) + .catch((error) => { + this.logger.error(error.message); + }); + } + }; + } + /** Helper function to init send then send invite. */ + sendInvite(inviter, inviterOptions, inviterInviteOptions) { + // Initialize our session + this.initSession(inviter, inviterOptions); + // Send the INVITE + return inviter.invite(inviterInviteOptions).then(() => { + this.logger.log(`[${this.id}] sent INVITE`); + }); + } + /** + * Puts Session on hold. + * @param hold - Hold on if true, off if false. + */ + setHold(hold) { + if (!this.session) { + return Promise.reject(new Error("Session does not exist.")); + } + const session = this.session; + // Just resolve if we are already in correct state + if (this.held === hold) { + return Promise.resolve(); + } + const sessionDescriptionHandler = this.session.sessionDescriptionHandler; + if (!(sessionDescriptionHandler instanceof SessionDescriptionHandler)) { + throw new Error("Session's session description handler not instance of SessionDescriptionHandler."); + } + const options = { + requestDelegate: { + onAccept: () => { + this.held = hold; + if (this.delegate && this.delegate.onCallHold) { + this.delegate.onCallHold(this.held); + } + }, + onReject: () => { + this.logger.warn(`[${this.id}] re-invite request was rejected`); + if (this.delegate && this.delegate.onCallHold) { + this.delegate.onCallHold(this.held); + } + } + } + }; + // Session properties used to pass modifiers to the SessionDescriptionHandler: + // + // 1) Session.sessionDescriptionHandlerModifiers + // - used in all cases when handling the initial INVITE transaction as either UAC or UAS + // - may be set directly at anytime + // - may optionally be set via constructor option + // - may optionally be set via options passed to Inviter.invite() or Invitation.accept() + // + // 2) Session.sessionDescriptionHandlerModifiersReInvite + // - used in all cases when handling a re-INVITE transaction as either UAC or UAS + // - may be set directly at anytime + // - may optionally be set via constructor option + // - may optionally be set via options passed to Session.invite() + // Set the session's SDH re-INVITE modifiers to produce the appropriate SDP offer to place call on hold + session.sessionDescriptionHandlerModifiersReInvite = hold ? [holdModifier] : []; + // Send re-INVITE + return this.session + .invite(options) + .then(() => { + // Reset the session's SDH re-INVITE modifiers. + // Note that if the modifiers are not reset, they will be applied + // to the SDP answer as well (which we do not want in this case). + session.sessionDescriptionHandlerModifiersReInvite = []; + this.enableSenderTracks(!hold); // mute/unmute + }) + .catch((error) => { + if (error instanceof RequestPendingError) { + this.logger.error(`[${this.id}] A hold request is already in progress.`); + } + throw error; + }); + } + /** + * Puts Session on mute. + * @param mute - Mute on if true, off if false. + */ + setMute(mute) { + if (!this.session) { + this.logger.warn(`[${this.id}] A session is required to enabled/disable media tracks`); + return; + } + if (this.session.state !== SessionState.Established) { + this.logger.warn(`[${this.id}] An established session is required to enable/disable media tracks`); + return; + } + this.enableSenderTracks(!mute); + } + /** Helper function to attach local media to html elements. */ + setupLocalMedia() { + var _a, _b; + if (!this.session) { + throw new Error("Session does not exist."); + } + const mediaElement = (_b = (_a = this.options.media) === null || _a === void 0 ? void 0 : _a.local) === null || _b === void 0 ? void 0 : _b.video; + if (mediaElement) { + const localStream = this.localMediaStream; + if (!localStream) { + throw new Error("Local media stream undefiend."); + } + mediaElement.srcObject = localStream; + mediaElement.volume = 0; + mediaElement.play().catch((error) => { + this.logger.error(`[${this.id}] Failed to play local media`); + this.logger.error(error.message); + }); + } + } + /** Helper function to attach remote media to html elements. */ + setupRemoteMedia() { + var _a, _b, _c, _d; + if (!this.session) { + throw new Error("Session does not exist."); + } + const mediaElement = ((_b = (_a = this.options.media) === null || _a === void 0 ? void 0 : _a.remote) === null || _b === void 0 ? void 0 : _b.video) || ((_d = (_c = this.options.media) === null || _c === void 0 ? void 0 : _c.remote) === null || _d === void 0 ? void 0 : _d.audio); + if (mediaElement) { + const remoteStream = this.remoteMediaStream; + if (!remoteStream) { + throw new Error("Remote media stream undefiend."); + } + mediaElement.autoplay = true; // Safari hack, because you cannot call .play() from a non user action + mediaElement.srcObject = remoteStream; + mediaElement.play().catch((error) => { + this.logger.error(`[${this.id}] Failed to play remote media`); + this.logger.error(error.message); + }); + remoteStream.onaddtrack = () => { + this.logger.log(`[${this.id}] Remote media onaddtrack`); + mediaElement.load(); // Safari hack, as it doesn't work otheriwse + mediaElement.play().catch((error) => { + this.logger.error(`[${this.id}] Failed to play remote media`); + this.logger.error(error.message); + }); + }; + } + } + /** + * End a session. + * @remarks + * Send a BYE request, CANCEL request or reject response to end the current Session. + * Resolves when the request/response is sent, otherwise rejects. + * Use `onCallTerminated` delegate method to determine if and when Session is terminated. + */ + terminate() { + this.logger.log(`[${this.id}] Terminating...`); + if (!this.session) { + return Promise.reject(new Error("Session does not exist.")); + } + switch (this.session.state) { + case SessionState.Initial: + if (this.session instanceof Inviter) { + return this.session.cancel().then(() => { + this.logger.log(`[${this.id}] Inviter never sent INVITE (canceled)`); + }); + } + else if (this.session instanceof Invitation) { + return this.session.reject().then(() => { + this.logger.log(`[${this.id}] Invitation rejected (sent 480)`); + }); + } + else { + throw new Error("Unknown session type."); + } + case SessionState.Establishing: + if (this.session instanceof Inviter) { + return this.session.cancel().then(() => { + this.logger.log(`[${this.id}] Inviter canceled (sent CANCEL)`); + }); + } + else if (this.session instanceof Invitation) { + return this.session.reject().then(() => { + this.logger.log(`[${this.id}] Invitation rejected (sent 480)`); + }); + } + else { + throw new Error("Unknown session type."); + } + case SessionState.Established: + return this.session.bye().then(() => { + this.logger.log(`[${this.id}] Session ended (sent BYE)`); + }); + case SessionState.Terminating: + break; + case SessionState.Terminated: + break; + default: + throw new Error("Unknown state"); + } + this.logger.log(`[${this.id}] Terminating in state ${this.session.state}, no action taken`); + return Promise.resolve(); + } +} diff --git a/lib/platform/web/transport/index.d.ts b/lib/platform/web/transport/index.d.ts new file mode 100644 index 000000000..9744fd081 --- /dev/null +++ b/lib/platform/web/transport/index.d.ts @@ -0,0 +1,7 @@ +/** + * A Transport implementation for web browsers. + * @packageDocumentation + */ +export * from "./transport"; +export * from "./transport-options"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/transport/index.d.ts.map b/lib/platform/web/transport/index.d.ts.map new file mode 100644 index 000000000..8147590c0 --- /dev/null +++ b/lib/platform/web/transport/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/transport/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,cAAc,aAAa,CAAC;AAC5B,cAAc,qBAAqB,CAAC"} \ No newline at end of file diff --git a/lib/platform/web/transport/index.js b/lib/platform/web/transport/index.js new file mode 100644 index 000000000..a7ef71939 --- /dev/null +++ b/lib/platform/web/transport/index.js @@ -0,0 +1,6 @@ +/** + * A Transport implementation for web browsers. + * @packageDocumentation + */ +export * from "./transport"; +export * from "./transport-options"; diff --git a/lib/platform/web/transport/transport-options.d.ts b/lib/platform/web/transport/transport-options.d.ts new file mode 100644 index 000000000..7c8b34088 --- /dev/null +++ b/lib/platform/web/transport/transport-options.d.ts @@ -0,0 +1,31 @@ +/** + * Transport options. + * @public + */ +export interface TransportOptions { + /** + * URL of WebSocket server to connect with. For example, "wss://localhost:8080". + */ + server: string; + /** + * Seconds to wait for WebSocket to connect before giving up. + * @defaultValue `5` + */ + connectionTimeout?: number; + /** + * Keep alive - needs review. + * @internal + */ + keepAliveInterval?: number; + /** + * Keep alive - needs review. + * @internal + */ + keepAliveDebounce?: number; + /** + * If true, messages sent and received by the transport are logged. + * @defaultValue `true` + */ + traceSip?: boolean; +} +//# sourceMappingURL=transport-options.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/transport/transport-options.d.ts.map b/lib/platform/web/transport/transport-options.d.ts.map new file mode 100644 index 000000000..2d23e8cfc --- /dev/null +++ b/lib/platform/web/transport/transport-options.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"transport-options.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/transport/transport-options.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,WAAW,gBAAgB;IAC/B;;OAEG;IACH,MAAM,EAAE,MAAM,CAAC;IAEf;;;OAGG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAE3B;;;OAGG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAE3B;;;OAGG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAE3B;;;OAGG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB"} \ No newline at end of file diff --git a/lib/platform/web/transport/transport-options.js b/lib/platform/web/transport/transport-options.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/platform/web/transport/transport-options.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/platform/web/transport/transport.d.ts b/lib/platform/web/transport/transport.d.ts new file mode 100644 index 000000000..31621fbf2 --- /dev/null +++ b/lib/platform/web/transport/transport.d.ts @@ -0,0 +1,126 @@ +import { Emitter } from "../../../api/emitter"; +import { Transport as TransportDefinition } from "../../../api/transport"; +import { TransportState } from "../../../api/transport-state"; +import { Logger } from "../../../core"; +import { TransportOptions } from "./transport-options"; +/** + * Transport for SIP over secure WebSocket (WSS). + * @public + */ +export declare class Transport implements TransportDefinition { + private static defaultOptions; + onConnect: (() => void) | undefined; + onDisconnect: ((error?: Error) => void) | undefined; + onMessage: ((message: string) => void) | undefined; + private _protocol; + private _state; + private _stateEventEmitter; + private _ws; + private configuration; + private connectPromise; + private connectResolve; + private connectReject; + private connectTimeout; + private disconnectPromise; + private disconnectResolve; + private disconnectReject; + private keepAliveInterval; + private keepAliveDebounceTimeout; + private logger; + private transitioningState; + constructor(logger: Logger, options?: TransportOptions); + dispose(): Promise; + /** + * The protocol. + * + * @remarks + * Formatted as defined for the Via header sent-protocol transport. + * https://tools.ietf.org/html/rfc3261#section-20.42 + */ + get protocol(): string; + /** + * The URL of the WebSocket Server. + */ + get server(): string; + /** + * Transport state. + */ + get state(): TransportState; + /** + * Transport state change emitter. + */ + get stateChange(): Emitter; + /** + * The WebSocket. + */ + get ws(): WebSocket | undefined; + /** + * Connect to network. + * Resolves once connected. Otherwise rejects with an Error. + */ + connect(): Promise; + /** + * Disconnect from network. + * Resolves once disconnected. Otherwise rejects with an Error. + */ + disconnect(): Promise; + /** + * Returns true if the `state` equals "Connected". + * @remarks + * This is equivalent to `state === TransportState.Connected`. + */ + isConnected(): boolean; + /** + * Sends a message. + * Resolves once message is sent. Otherwise rejects with an Error. + * @param message - Message to send. + */ + send(message: string): Promise; + private _connect; + private _disconnect; + private _send; + /** + * WebSocket "onclose" event handler. + * @param ev - Event. + */ + private onWebSocketClose; + /** + * WebSocket "onerror" event handler. + * @param ev - Event. + */ + private onWebSocketError; + /** + * WebSocket "onmessage" event handler. + * @param ev - Event. + */ + private onWebSocketMessage; + /** + * WebSocket "onopen" event handler. + * @param ev - Event. + */ + private onWebSocketOpen; + /** + * Helper function to generate an Error. + * @param state - State transitioning to. + */ + private transitionLoopDetectedError; + /** + * Transition transport state. + * @internal + */ + private transitionState; + private clearKeepAliveTimeout; + /** + * Send a keep-alive (a double-CRLF sequence). + */ + private sendKeepAlive; + /** + * Start sending keep-alives. + */ + private startSendingKeepAlives; + /** + * Stop sending keep-alives. + */ + private stopSendingKeepAlives; +} +//# sourceMappingURL=transport.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/transport/transport.d.ts.map b/lib/platform/web/transport/transport.d.ts.map new file mode 100644 index 000000000..89e8b2ec9 --- /dev/null +++ b/lib/platform/web/transport/transport.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"transport.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/transport/transport.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAe,MAAM,sBAAsB,CAAC;AAE5D,OAAO,EAAE,SAAS,IAAI,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAC1E,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAC9D,OAAO,EAAW,MAAM,EAAE,MAAM,eAAe,CAAC;AAChD,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAEvD;;;GAGG;AACH,qBAAa,SAAU,YAAW,mBAAmB;IACnD,OAAO,CAAC,MAAM,CAAC,cAAc,CAM3B;IAEK,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,GAAG,SAAS,CAAC;IACpC,YAAY,EAAE,CAAC,CAAC,KAAK,CAAC,EAAE,KAAK,KAAK,IAAI,CAAC,GAAG,SAAS,CAAC;IACpD,SAAS,EAAE,CAAC,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC,GAAG,SAAS,CAAC;IAE1D,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,MAAM,CAA+C;IAC7D,OAAO,CAAC,kBAAkB,CAA8B;IACxD,OAAO,CAAC,GAAG,CAAwB;IAEnC,OAAO,CAAC,aAAa,CAA6B;IAElD,OAAO,CAAC,cAAc,CAA4B;IAClD,OAAO,CAAC,cAAc,CAA2B;IACjD,OAAO,CAAC,aAAa,CAAuC;IAC5D,OAAO,CAAC,cAAc,CAAqB;IAE3C,OAAO,CAAC,iBAAiB,CAA4B;IACrD,OAAO,CAAC,iBAAiB,CAA2B;IACpD,OAAO,CAAC,gBAAgB,CAAwC;IAEhE,OAAO,CAAC,iBAAiB,CAAqB;IAC9C,OAAO,CAAC,wBAAwB,CAAqB;IAErD,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,kBAAkB,CAAS;gBAEvB,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,gBAAgB;IA0D/C,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAI/B;;;;;;OAMG;IACH,IAAW,QAAQ,IAAI,MAAM,CAE5B;IAED;;OAEG;IACH,IAAW,MAAM,IAAI,MAAM,CAE1B;IAED;;OAEG;IACH,IAAW,KAAK,IAAI,cAAc,CAEjC;IAED;;OAEG;IACH,IAAW,WAAW,IAAI,OAAO,CAAC,cAAc,CAAC,CAEhD;IAED;;OAEG;IACH,IAAW,EAAE,IAAI,SAAS,GAAG,SAAS,CAErC;IAED;;;OAGG;IACI,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAI/B;;;OAGG;IACI,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAIlC;;;;OAIG;IACI,WAAW,IAAI,OAAO;IAI7B;;;;OAIG;IACI,IAAI,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAkB3C,OAAO,CAAC,QAAQ;IA+FhB,OAAO,CAAC,WAAW;IA+EnB,OAAO,CAAC,KAAK;IA2Bb;;;OAGG;IACH,OAAO,CAAC,gBAAgB;IAmBxB;;;OAGG;IACH,OAAO,CAAC,gBAAgB;IAOxB;;;OAGG;IACH,OAAO,CAAC,kBAAkB;IA8D1B;;;OAGG;IACH,OAAO,CAAC,eAAe;IAUvB;;;OAGG;IACH,OAAO,CAAC,2BAA2B;IAQnC;;;OAGG;IACH,OAAO,CAAC,eAAe;IAiKvB,OAAO,CAAC,qBAAqB;IAO7B;;OAEG;IACH,OAAO,CAAC,aAAa;IAarB;;OAEG;IACH,OAAO,CAAC,sBAAsB;IAe9B;;OAEG;IACH,OAAO,CAAC,qBAAqB;CAU9B"} \ No newline at end of file diff --git a/lib/platform/web/transport/transport.js b/lib/platform/web/transport/transport.js new file mode 100644 index 000000000..ae7600e49 --- /dev/null +++ b/lib/platform/web/transport/transport.js @@ -0,0 +1,648 @@ +import { EmitterImpl } from "../../../api/emitter"; +import { StateTransitionError } from "../../../api/exceptions"; +import { TransportState } from "../../../api/transport-state"; +import { Grammar } from "../../../core"; +/** + * Transport for SIP over secure WebSocket (WSS). + * @public + */ +export class Transport { + constructor(logger, options) { + this._state = TransportState.Disconnected; + this.transitioningState = false; + // state emitter + this._stateEventEmitter = new EmitterImpl(); + // logger + this.logger = logger; + // guard deprecated options (remove this in version 16.x) + if (options) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const optionsDeprecated = options; + const wsServersDeprecated = optionsDeprecated === null || optionsDeprecated === void 0 ? void 0 : optionsDeprecated.wsServers; + const maxReconnectionAttemptsDeprecated = optionsDeprecated === null || optionsDeprecated === void 0 ? void 0 : optionsDeprecated.maxReconnectionAttempts; + if (wsServersDeprecated !== undefined) { + const deprecatedMessage = `The transport option "wsServers" as has apparently been specified and has been deprecated. ` + + "It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly."; + this.logger.warn(deprecatedMessage); + } + if (maxReconnectionAttemptsDeprecated !== undefined) { + const deprecatedMessage = `The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. ` + + "It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly."; + this.logger.warn(deprecatedMessage); + } + // hack + if (wsServersDeprecated && !options.server) { + if (typeof wsServersDeprecated === "string") { + options.server = wsServersDeprecated; + } + if (wsServersDeprecated instanceof Array) { + options.server = wsServersDeprecated[0]; + } + } + } + // initialize configuration + this.configuration = Object.assign(Object.assign({}, Transport.defaultOptions), options); + // validate server URL + const url = this.configuration.server; + const parsed = Grammar.parse(url, "absoluteURI"); + if (parsed === -1) { + this.logger.error(`Invalid WebSocket Server URL "${url}"`); + throw new Error("Invalid WebSocket Server URL"); + } + if (!["wss", "ws", "udp"].includes(parsed.scheme)) { + this.logger.error(`Invalid scheme in WebSocket Server URL "${url}"`); + throw new Error("Invalid scheme in WebSocket Server URL"); + } + this._protocol = parsed.scheme.toUpperCase(); + } + dispose() { + return this.disconnect(); + } + /** + * The protocol. + * + * @remarks + * Formatted as defined for the Via header sent-protocol transport. + * https://tools.ietf.org/html/rfc3261#section-20.42 + */ + get protocol() { + return this._protocol; + } + /** + * The URL of the WebSocket Server. + */ + get server() { + return this.configuration.server; + } + /** + * Transport state. + */ + get state() { + return this._state; + } + /** + * Transport state change emitter. + */ + get stateChange() { + return this._stateEventEmitter; + } + /** + * The WebSocket. + */ + get ws() { + return this._ws; + } + /** + * Connect to network. + * Resolves once connected. Otherwise rejects with an Error. + */ + connect() { + return this._connect(); + } + /** + * Disconnect from network. + * Resolves once disconnected. Otherwise rejects with an Error. + */ + disconnect() { + return this._disconnect(); + } + /** + * Returns true if the `state` equals "Connected". + * @remarks + * This is equivalent to `state === TransportState.Connected`. + */ + isConnected() { + return this.state === TransportState.Connected; + } + /** + * Sends a message. + * Resolves once message is sent. Otherwise rejects with an Error. + * @param message - Message to send. + */ + send(message) { + // Error handling is independent of whether the message was a request or + // response. + // + // If the transport user asks for a message to be sent over an + // unreliable transport, and the result is an ICMP error, the behavior + // depends on the type of ICMP error. Host, network, port or protocol + // unreachable errors, or parameter problem errors SHOULD cause the + // transport layer to inform the transport user of a failure in sending. + // Source quench and TTL exceeded ICMP errors SHOULD be ignored. + // + // If the transport user asks for a request to be sent over a reliable + // transport, and the result is a connection failure, the transport + // layer SHOULD inform the transport user of a failure in sending. + // https://tools.ietf.org/html/rfc3261#section-18.4 + return this._send(message); + } + _connect() { + this.logger.log(`Connecting ${this.server}`); + switch (this.state) { + case TransportState.Connecting: + // If `state` is "Connecting", `state` MUST NOT transition before returning. + if (this.transitioningState) { + return Promise.reject(this.transitionLoopDetectedError(TransportState.Connecting)); + } + if (!this.connectPromise) { + throw new Error("Connect promise must be defined."); + } + return this.connectPromise; // Already connecting + case TransportState.Connected: + // If `state` is "Connected", `state` MUST NOT transition before returning. + if (this.transitioningState) { + return Promise.reject(this.transitionLoopDetectedError(TransportState.Connecting)); + } + if (this.connectPromise) { + throw new Error("Connect promise must not be defined."); + } + return Promise.resolve(); // Already connected + case TransportState.Disconnecting: + // If `state` is "Disconnecting", `state` MUST transition to "Connecting" before returning + if (this.connectPromise) { + throw new Error("Connect promise must not be defined."); + } + try { + this.transitionState(TransportState.Connecting); + } + catch (e) { + if (e instanceof StateTransitionError) { + return Promise.reject(e); // Loop detected + } + throw e; + } + break; + case TransportState.Disconnected: + // If `state` is "Disconnected" `state` MUST transition to "Connecting" before returning + if (this.connectPromise) { + throw new Error("Connect promise must not be defined."); + } + try { + this.transitionState(TransportState.Connecting); + } + catch (e) { + if (e instanceof StateTransitionError) { + return Promise.reject(e); // Loop detected + } + throw e; + } + break; + default: + throw new Error("Unknown state"); + } + let ws; + try { + // WebSocket() + // https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/WebSocket + ws = new WebSocket(this.server, "sip"); + ws.binaryType = "arraybuffer"; // set data type of received binary messages + ws.addEventListener("close", (ev) => this.onWebSocketClose(ev, ws)); + ws.addEventListener("error", (ev) => this.onWebSocketError(ev, ws)); + ws.addEventListener("open", (ev) => this.onWebSocketOpen(ev, ws)); + ws.addEventListener("message", (ev) => this.onWebSocketMessage(ev, ws)); + this._ws = ws; + } + catch (error) { + this._ws = undefined; + this.logger.error("WebSocket construction failed."); + this.logger.error(error); + return new Promise((resolve, reject) => { + this.connectResolve = resolve; + this.connectReject = reject; + // The `state` MUST transition to "Disconnecting" or "Disconnected" before rejecting + this.transitionState(TransportState.Disconnected, error); + }); + } + this.connectPromise = new Promise((resolve, reject) => { + this.connectResolve = resolve; + this.connectReject = reject; + this.connectTimeout = setTimeout(() => { + this.logger.warn("Connect timed out. " + + "Exceeded time set in configuration.connectionTimeout: " + + this.configuration.connectionTimeout + + "s."); + ws.close(1000); // careful here to use a local reference instead of this._ws + }, this.configuration.connectionTimeout * 1000); + }); + return this.connectPromise; + } + _disconnect() { + this.logger.log(`Disconnecting ${this.server}`); + switch (this.state) { + case TransportState.Connecting: + // If `state` is "Connecting", `state` MUST transition to "Disconnecting" before returning. + if (this.disconnectPromise) { + throw new Error("Disconnect promise must not be defined."); + } + try { + this.transitionState(TransportState.Disconnecting); + } + catch (e) { + if (e instanceof StateTransitionError) { + return Promise.reject(e); // Loop detected + } + throw e; + } + break; + case TransportState.Connected: + // If `state` is "Connected", `state` MUST transition to "Disconnecting" before returning. + if (this.disconnectPromise) { + throw new Error("Disconnect promise must not be defined."); + } + try { + this.transitionState(TransportState.Disconnecting); + } + catch (e) { + if (e instanceof StateTransitionError) { + return Promise.reject(e); // Loop detected + } + throw e; + } + break; + case TransportState.Disconnecting: + // If `state` is "Disconnecting", `state` MUST NOT transition before returning. + if (this.transitioningState) { + return Promise.reject(this.transitionLoopDetectedError(TransportState.Disconnecting)); + } + if (!this.disconnectPromise) { + throw new Error("Disconnect promise must be defined."); + } + return this.disconnectPromise; // Already disconnecting + case TransportState.Disconnected: + // If `state` is "Disconnected", `state` MUST NOT transition before returning. + if (this.transitioningState) { + return Promise.reject(this.transitionLoopDetectedError(TransportState.Disconnecting)); + } + if (this.disconnectPromise) { + throw new Error("Disconnect promise must not be defined."); + } + return Promise.resolve(); // Already disconnected + default: + throw new Error("Unknown state"); + } + if (!this._ws) { + throw new Error("WebSocket must be defined."); + } + const ws = this._ws; + this.disconnectPromise = new Promise((resolve, reject) => { + this.disconnectResolve = resolve; + this.disconnectReject = reject; + try { + // WebSocket.close() + // https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close + ws.close(1000); // careful here to use a local reference instead of this._ws + } + catch (error) { + // Treating this as a coding error as it apparently can only happen + // if you pass close() invalid parameters (so it should never happen) + this.logger.error("WebSocket close failed."); + this.logger.error(error); + throw error; + } + }); + return this.disconnectPromise; + } + _send(message) { + if (this.configuration.traceSip === true) { + this.logger.log("Sending WebSocket message:\n\n" + message + "\n"); + } + if (this._state !== TransportState.Connected) { + return Promise.reject(new Error("Not connected.")); + } + if (!this._ws) { + throw new Error("WebSocket undefined."); + } + try { + // WebSocket.send() + // https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send + this._ws.send(message); + } + catch (error) { + if (error instanceof Error) { + return Promise.reject(error); + } + return Promise.reject(new Error("WebSocket send failed.")); + } + return Promise.resolve(); + } + /** + * WebSocket "onclose" event handler. + * @param ev - Event. + */ + onWebSocketClose(ev, ws) { + if (ws !== this._ws) { + return; + } + const message = `WebSocket closed ${this.server} (code: ${ev.code})`; + const error = !this.disconnectPromise ? new Error(message) : undefined; + if (error) { + this.logger.warn("WebSocket closed unexpectedly"); + } + this.logger.log(message); + // We are about to transition to disconnected, so clear our web socket + this._ws = undefined; + // The `state` MUST transition to "Disconnected" before resolving (assuming `state` is not already "Disconnected"). + this.transitionState(TransportState.Disconnected, error); + } + /** + * WebSocket "onerror" event handler. + * @param ev - Event. + */ + onWebSocketError(ev, ws) { + if (ws !== this._ws) { + return; + } + this.logger.error("WebSocket error occurred."); + } + /** + * WebSocket "onmessage" event handler. + * @param ev - Event. + */ + onWebSocketMessage(ev, ws) { + if (ws !== this._ws) { + return; + } + const data = ev.data; + let 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; + } + if (!data) { + this.logger.warn("Received empty message, discarding..."); + return; + } + if (typeof data !== "string") { + // WebSocket binary message. + try { + finishedData = new TextDecoder().decode(new Uint8Array(data)); + // TextDecoder (above) is not supported by old browsers, but it correctly decodes UTF-8. + // The line below is an ISO 8859-1 (Latin 1) decoder, so just UTF-8 code points that are 1 byte. + // It's old code and works in old browsers (IE), so leaving it here in a comment in case someone needs it. + // finishedData = String.fromCharCode.apply(null, (new Uint8Array(data) as unknown as Array)); + } + catch (err) { + this.logger.error(err); + this.logger.error("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" + finishedData + "\n"); + } + } + else { + // WebSocket text message. + finishedData = data; + if (this.configuration.traceSip === true) { + this.logger.log("Received WebSocket text message:\n\n" + finishedData + "\n"); + } + } + if (this.state !== TransportState.Connected) { + this.logger.warn("Received message while not connected, discarding..."); + return; + } + if (this.onMessage) { + try { + this.onMessage(finishedData); + } + catch (e) { + this.logger.error(e); + this.logger.error("Exception thrown by onMessage callback"); + throw e; // rethrow unhandled exception + } + } + } + /** + * WebSocket "onopen" event handler. + * @param ev - Event. + */ + onWebSocketOpen(ev, ws) { + if (ws !== this._ws) { + return; + } + if (this._state === TransportState.Connecting) { + this.logger.log(`WebSocket opened ${this.server}`); + this.transitionState(TransportState.Connected); + } + } + /** + * Helper function to generate an Error. + * @param state - State transitioning to. + */ + transitionLoopDetectedError(state) { + let message = `A state transition loop has been detected.`; + message += ` An attempt to transition from ${this._state} to ${state} before the prior transition completed.`; + message += ` Perhaps you are synchronously calling connect() or disconnect() from a callback or state change handler?`; + this.logger.error(message); + return new StateTransitionError("Loop detected."); + } + /** + * Transition transport state. + * @internal + */ + transitionState(newState, error) { + const invalidTransition = () => { + throw new Error(`Invalid state transition from ${this._state} to ${newState}`); + }; + if (this.transitioningState) { + throw this.transitionLoopDetectedError(newState); + } + this.transitioningState = true; + // Validate state transition + switch (this._state) { + case TransportState.Connecting: + if (newState !== TransportState.Connected && + newState !== TransportState.Disconnecting && + newState !== TransportState.Disconnected) { + invalidTransition(); + } + break; + case TransportState.Connected: + if (newState !== TransportState.Disconnecting && newState !== TransportState.Disconnected) { + invalidTransition(); + } + break; + case TransportState.Disconnecting: + if (newState !== TransportState.Connecting && newState !== TransportState.Disconnected) { + invalidTransition(); + } + break; + case TransportState.Disconnected: + if (newState !== TransportState.Connecting) { + invalidTransition(); + } + break; + default: + throw new Error("Unknown state."); + } + // Update state + const oldState = this._state; + this._state = newState; + // Local copies of connect promises (guarding against callbacks changing them indirectly) + // const connectPromise = this.connectPromise; + const connectResolve = this.connectResolve; + const connectReject = this.connectReject; + // Reset connect promises if no longer connecting + if (oldState === TransportState.Connecting) { + this.connectPromise = undefined; + this.connectResolve = undefined; + this.connectReject = undefined; + } + // Local copies of disconnect promises (guarding against callbacks changing them indirectly) + // const disconnectPromise = this.disconnectPromise; + const disconnectResolve = this.disconnectResolve; + const disconnectReject = this.disconnectReject; + // Reset disconnect promises if no longer disconnecting + if (oldState === TransportState.Disconnecting) { + this.disconnectPromise = undefined; + this.disconnectResolve = undefined; + this.disconnectReject = undefined; + } + // Clear any outstanding connect timeout + if (this.connectTimeout) { + clearTimeout(this.connectTimeout); + this.connectTimeout = undefined; + } + this.logger.log(`Transitioned from ${oldState} to ${this._state}`); + this._stateEventEmitter.emit(this._state); + // Transition to Connected + if (newState === TransportState.Connected) { + this.startSendingKeepAlives(); + if (this.onConnect) { + try { + this.onConnect(); + } + catch (e) { + this.logger.error(e); + this.logger.error("Exception thrown by onConnect callback"); + throw e; // rethrow unhandled exception + } + } + } + // Transition from Connected + if (oldState === TransportState.Connected) { + this.stopSendingKeepAlives(); + if (this.onDisconnect) { + try { + if (error) { + this.onDisconnect(error); + } + else { + this.onDisconnect(); + } + } + catch (e) { + this.logger.error(e); + this.logger.error("Exception thrown by onDisconnect callback"); + throw e; // rethrow unhandled exception + } + } + } + // Complete connect promise + if (oldState === TransportState.Connecting) { + if (!connectResolve) { + throw new Error("Connect resolve undefined."); + } + if (!connectReject) { + throw new Error("Connect reject undefined."); + } + newState === TransportState.Connected ? connectResolve() : connectReject(error || new Error("Connect aborted.")); + } + // Complete disconnect promise + if (oldState === TransportState.Disconnecting) { + if (!disconnectResolve) { + throw new Error("Disconnect resolve undefined."); + } + if (!disconnectReject) { + throw new Error("Disconnect reject undefined."); + } + newState === TransportState.Disconnected + ? disconnectResolve() + : disconnectReject(error || new Error("Disconnect aborted.")); + } + this.transitioningState = false; + } + // TODO: Review "KeepAlive Stuff". + // It is not clear if it works and there are no tests for it. + // It was blindly lifted the keep alive code unchanged from earlier transport code. + // + // From the RFC... + // + // SIP WebSocket Clients and Servers may keep their WebSocket + // connections open by sending periodic WebSocket "Ping" frames as + // described in [RFC6455], Section 5.5.2. + // ... + // The indication and use of the CRLF NAT keep-alive mechanism defined + // for SIP connection-oriented transports in [RFC5626], Section 3.5.1 or + // [RFC6223] are, of course, usable over the transport defined in this + // specification. + // https://tools.ietf.org/html/rfc7118#section-6 + // + // and... + // + // The Ping frame contains an opcode of 0x9. + // https://tools.ietf.org/html/rfc6455#section-5.5.2 + // + // ============================== + // KeepAlive Stuff + // ============================== + clearKeepAliveTimeout() { + if (this.keepAliveDebounceTimeout) { + clearTimeout(this.keepAliveDebounceTimeout); + } + this.keepAliveDebounceTimeout = undefined; + } + /** + * Send a keep-alive (a double-CRLF sequence). + */ + sendKeepAlive() { + if (this.keepAliveDebounceTimeout) { + // We already have an outstanding keep alive, do not send another. + return Promise.resolve(); + } + this.keepAliveDebounceTimeout = setTimeout(() => { + this.clearKeepAliveTimeout(); + }, this.configuration.keepAliveDebounce * 1000); + return this.send("\r\n\r\n"); + } + /** + * Start sending keep-alives. + */ + startSendingKeepAlives() { + // Compute an amount of time in seconds to wait before sending another keep-alive. + const computeKeepAliveTimeout = (upperBound) => { + const lowerBound = upperBound * 0.8; + return 1000 * (Math.random() * (upperBound - lowerBound) + lowerBound); + }; + if (this.configuration.keepAliveInterval && !this.keepAliveInterval) { + this.keepAliveInterval = setInterval(() => { + this.sendKeepAlive(); + this.startSendingKeepAlives(); + }, computeKeepAliveTimeout(this.configuration.keepAliveInterval)); + } + } + /** + * Stop sending keep-alives. + */ + stopSendingKeepAlives() { + if (this.keepAliveInterval) { + clearInterval(this.keepAliveInterval); + } + if (this.keepAliveDebounceTimeout) { + clearTimeout(this.keepAliveDebounceTimeout); + } + this.keepAliveInterval = undefined; + this.keepAliveDebounceTimeout = undefined; + } +} +Transport.defaultOptions = { + server: "", + connectionTimeout: 5, + keepAliveInterval: 0, + keepAliveDebounce: 10, + traceSip: true +}; diff --git a/lib/version.d.ts b/lib/version.d.ts new file mode 100644 index 000000000..de17dca23 --- /dev/null +++ b/lib/version.d.ts @@ -0,0 +1,2 @@ +export declare const LIBRARY_VERSION = "0.18.0"; +//# 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 new file mode 100644 index 000000000..fb526ad54 --- /dev/null +++ b/lib/version.d.ts.map @@ -0,0 +1 @@ +{"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 new file mode 100644 index 000000000..1f002fef6 --- /dev/null +++ b/lib/version.js @@ -0,0 +1 @@ +export const LIBRARY_VERSION = "0.18.0";