"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.NodeSDK = void 0;
const PresenceRainbow_js_1 = require("./common/models/PresenceRainbow.js");
require("fix-esm").register();
const Core_1 = require("./Core");
const Channel_1 = require("./common/models/Channel");
const ErrorManager_1 = require("./common/ErrorManager");
const Utils_1 = require("./common/Utils");
const StateManager_1 = require("./common/StateManager");
const AdminService_1 = require("./services/AdminService");
const config_1 = require("./config/config");
const util_1 = require("util");
const LevelLogs_js_1 = require("./common/LevelLogs.js");
const CalendarManager_js_1 = require("./common/CalendarManager.js");
const AutoReplyManager_js_1 = require("./common/AutoReplyManager.js");
let LOG_ID = "NodeSDK/IDX";
/**
 * @enum { String }
 *
*/
let Type = {
    home: "home",
    work: "work",
    other: "other"
};
/**
 * @enum { String }
 *
*/
let DeviceType = {
    landline: "landline",
    mobile: "mobile",
    fax: "fax",
    other: "other"
};
function uncaughtException(err) {
    console.error('Possibly uncaughtException err : ', err);
}
function warning(err) {
    console.error('Possibly unhandledRejection err : ', err);
}
function unhandledRejection(reason, p) {
    console.error('Possibly Unhandled Rejection at: Promise ', p, " reason: ", reason);
}
/**
 * @module
 * @name SDK
 * @version 2.42.0-lts.4 - Documentation generated on 2026/04/24T11:38:22.926Z
 * @public
 * @description
 *      This module is the core module of the Rainbow SDK for Node.JS <br>.
 *      It gives access to the other modules and allow to start/stop the SDK
 *      <br><br>
 *      The main methods proposed in that module allow to: <br>
 *      - Access to each module like Bubbles, Contacts...<br>
 *      - Access to Event module <br>
 *      - Start and stop the SDK <br>
 *      - Get the version number <br>
 *      - Get the SDK internal state
 *
 *      Warning: Before deploying in production a bot that can generate heavy traffic, please contact ALE.
 */
class SDK {
    constructor() { }
}
/**
 * @public
 * @name NodeSDK
 * @class
 * @description
 * NodeSDK Class
 */
class NodeSDK {
    get option() {
        return this._option;
    }
    /**
     * @method constructor
     * @public
     * @description
     *      The entry point of the Rainbow Node SDK.
     * @param {Object} options SDK Startup options of constructor.
     * @param {string} options.rainbow.host "official", Can be "sandbox" (developer platform), "official" or any other hostname when using dedicated AIO.
     * @param {string} options.rainbow.mode "xmpp", The event mode used to receive the events. Can be `xmpp` or `s2s` (default : `xmpp`).
     * @param {string} options.xmpp.timeBetweenXmppRequests the time between two xmpp request (avoid burst)
     * @param {string} options.xmpp.raiseLowLevelXmppInEvent enable the raise of event "rainbow_onxmmpeventreceived" when a data is received in xmpp pipe.
     * @param {string} options.xmpp.xmppRessourceName to define the name of the xmpp resource.
     * @param {string} options.xmpp.raiseLowLevelXmppOutReq enable the raise of event "rainbow_onxmmprequestsent" when a data is sent in xmpp pipe.
     * @param {string} options.xmpp.maxIdleTimer to define the delay without xmpp exchange after which a ping is sent to server.
     * @param {string} options.xmpp.maxPingAnswerTimer to define the time to wait the xmpp ping response.
     * @param {string} options.xmpp.maxPendingAsyncLockXmppQueue the number of xmpp requests waiting for sending.
     * @param {string} options.s2s.hostCallback "http://3d260881.ngrok.io", S2S Callback URL used to receive events on internet.
     * @param {string} options.s2s.locallistenningport "4000", Local port where the events must be forwarded from S2S Callback Web server.
     * @param {string} options.s2s.expressEngine Local instance for S2S Callback Web server.
     * @param {string} options.rest.useRestAtStartup enable the REST requests to the rainbow server at startup (used with startWSOnly method). default value is true.
     * @param {string} options.rest.useGotLibForHttp allows to enable the use of `got` lib for REST requests (esle the old Request lib is used). Default value is true.
     * @param {string} options.rest.gotOptions, allows to customize the `got` lib for REST requests options. Default value is : </BR>
     *  {</BR>
     *  agentOptions: { </BR>
     * //Keep sockets around in a pool to be used by other requests in the future. Default = false</BR>
     * keepAlive: true, // ?: boolean or undefined;</BR>
     * </BR>
     * //When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 4301.</BR>
     * //Only relevant if keepAlive is set to true.</BR>
     * keepAliveMsecs: 4301, // ?: number or undefined;</BR>
     * </BR>
     * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity</BR>
     * maxSockets: 26, // ?: number or undefined;</BR>
     * </BR>
     * Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached. Default: Infinity.</BR>
     * maxTotalSockets: Infinity, // ?: number or undefined;</BR>
     * </BR>
     * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256.</BR>
     * maxFreeSockets: 1001, // ?: number or undefined;</BR>
     * </BR>
     * Socket timeout in milliseconds. This will set the timeout after the socket is connected.</BR>
     * timeout: 60001 , // ?: number or undefined;</BR>
     * rejectUnauthorized: true // If not false, the server certificate is verified against the list of supplied CAs. Default: true.
     * }</BR> ,
     * gotRequestOptions : {</BR>
     *  timeout: { // This object describes the maximum allowed time for particular events.</BR>
     *      lookup: 800, // Starts when a socket is assigned.  Ends when the hostname has been resolved.</BR>
     *      connect: 1250, // Starts when lookup completes.  Ends when the socket is fully connected.</BR>
     *      secureConnect: 1250, // Starts when connect completes. Ends when the handshake process completes.</BR>
     *      socket: 2000, // Starts when the socket is connected. Resets when new data is transferred.</BR>
     *      send: 90000, // Starts when the socket is connected. Ends when all data have been written to the socket.</BR>
     *      response: 2000 // Starts when request has been flushed. Ends when the headers are received.</BR>
     *   }</BR>
     *  }</BR>
     * }</BR>
     *
     * @param {string} options.credentials.login "user@xxxx.xxx", The Rainbow email account to use.
     * @param {string} options.credentials.password "XXXXX", The password.
     * @param {string} options.application.appID "XXXXXXXXXXXXXXXXXXXXXXXXXXXX", The Rainbow Application Identifier.
     * @param {string} options.application.appSecret "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX", The Rainbow Application Secret.
     * @param {string} options.proxy.host "xxx.xxx.xxx.xxx", The proxy address.
     * @param {string} options.proxy.port xxxx, The proxy port.
     * @param {string} options.proxy.protocol "http", The proxy protocol (note http is used to https also).
     * @param {string} options.proxy.user "proxyuser", The proxy username.
     * @param {string} options.proxy.password "XXXXX", The proxy password.
     * @param {boolean} options.logs.enableConsoleLogs false, Activate logs on the console.
     * @param {boolean} options.logs.enableFileLogs false, Activate the logs in a file.
     * @param {boolean} options.logs.enableEventsLogs: false, Activate the logs to be raised from the events service (with `onLog` listener). Used for logs in connection node in red node contrib.
     * @param {boolean} options.logs.enableEncryptedLogs: true, Activate the encryption of stanza in logs.
     * @param {boolean} options.logs.color true, Activate the ansii color in the log (more humain readable, but need a term console or reader compatible (ex : vim + AnsiEsc module)).
     * @param {string} options.logs.level "info", The level of logs. The value can be "error", "warn", "info", "trace", "http", "xmpp", "debug", "internalerror", "internal". These Severities of levels are shown in an inclusive order, so "error" level only show "error" logs, "warn" level only show "error" and "warn" levels, and so on.
     * @param {LogLevelAreas} options.logs.areas Areas allow to override the log level for specifics limited area of code.
     * @param {string} options.logs.customLabel "MyRBProject", A label inserted in every lines of the logs. It is usefull if you use multiple SDK instances at a same time. It allows to separate logs in console.
     * @param {string} options.logs.file.path "c:/temp/", Path to the log file.
     * @param {string} options.logs.file.customFileName "R-SDK-Node-MyRBProject", A label inserted in the name of the log file.
     * @param {string} options.logs.file.zippedArchive false Can activate a zip of file. It needs CPU process, so avoid it.
     * @param {boolean} options.testOutdatedVersion true, Parameter to verify at startup if the current SDK Version is the lastest published on npmjs.com.
     * @param {boolean} options.testDNSentry true, Parameter to verify at startup/reconnection that the rainbow server DNS entry name is available.
     * @param {boolean} options.httpoverxmppserver false, Activate the treatment of Http over Xmpp requests (xep0332).
     * @param {number} options.intervalBetweenCleanMemoryCache 21600000 (6 hours), There is a cleannig process to reduce memory use and this option allow to modify the interval between it.
     * @param {string} options.requestsRate.useRequestRateLimiter true, // Allows to use the rate limit of the http requests to server.
     * @param {string} options.requestsRate.maxReqByIntervalForRequestRate 600, // nb requests during the interval of the rate limit of the http requests to server.
     * @param {string} options.requestsRate.intervalForRequestRate 60, // nb of seconds used for the calcul of the rate limit of the rate limit of the http requests to server.
     * @param {string} options.requestsRate.timeoutRequestForRequestRate 600 // nb seconds Request stay in queue before being rejected if queue is full of the rate limit of the http requests to server.
     * @param {boolean} options.im.sendReadReceipt true, Allow to automatically send back a 'read' status of the received message. Usefull for Bots.
     * @param {string} options.im.messageMaxLength 16384, Maximum size of messages send by rainbow. Note that this value should not be modified without ALE Agreement. Max stanza's size on server is 18432.
     * @param {boolean} options.im.sendMessageToConnectedUser false, Forbid the SDK to send a message to the connected user it self. This is to avoid bot loopback.
     * @param {string} options.im.conversationsRetrievedFormat "small", Set the size of the conversation's content retrieved from server. Can be `small`, `medium`, `full`.
     * @param {string} options.im.storeMessages false, Tell the server to store the message for delay distribution and also for history. Please avoid to set it to true for a bot which will not read anymore the messages. It is a better way to store it in your own CPaaS application.
     * @param {boolean} options.im.copyMessage to manage if the Messages hint should not be copied to others resources (https://xmpp.org/extensions/xep-0334.html#no-copy) . The default value is true.
     * @param {string} options.im.nbMaxConversations 15, Parameter to set the maximum number of conversations to keep (defaut value to 15). Old ones are remove from XMPP server with the new method `ConversationsService::removeOlderConversations`.
     * @param {number} options.im.rateLimitPerHour 1000, Parameter to set the maximum of "message" stanza sent to server by hour. Default value is 1000.
     * @param {string} options.im.messagesDataStore Parameter to override the storeMessages parameter of the SDK to define the behaviour of the storage of the messages (Enum DataStoreType in lib/config/config , default value "DataStoreType.UsestoreMessagesField" so it follows the storeMessages behaviour).<br>
     *                         DataStoreType.NoStore "no-store" Tell the server to NOT store the messages for delay distribution or for history of the bot and the contact.<br>
     *                          DataStoreType.NoPermanentStore "no-permanent-store" Tell the server to NOT store the messages for history of the bot and the contact. But being stored temporarily as a normal part of delivery (e.g. if the recipient is offline at the time of sending).<br>
     *                          DataStoreType.StoreTwinSide "storetwinside" The messages are fully stored.<br>
     *                          DataStoreType.UsestoreMessagesField "OldstoreMessagesUsed" to follow the storeMessages SDK's parameter behaviour.
     * @param {boolean} options.im.autoInitialGetBubbles to allow automatic opening of the bubbles the user is in. Default value is true.
     * @param {boolean} options.im.autoInitialBubblePresence to allow automatic opening of conversation to the bubbles with sending XMPP initial presence to the room. Default value is true.
     * @param {number} options.im.maxBubbleJoinInProgress to define the maximum of simultaneous "send initial presence of the bubbles".
     * @param {boolean} options.im.autoInitialBubbleFormat to allow modify format of data received at getting the bubbles. Default value is true.
     * @param {boolean} options.im.autoInitialBubbleUnsubscribed to allow get the bubbles when the user is unsubscribed form it. Default value is true.
     * @param {boolean} options.im.autoLoadConversations to activate the retrieve of conversations from the server. The default value is true.
     * @param {boolean} options.im.autoLoadConversationHistory to activate the retrieve of conversation's messages from the server. The default value is false.
     * @param {boolean} options.im.autoLoadContacts to activate the retrieve of contacts from roster from the server. The default value is true.
     * @param {boolean} options.im.autoLoadCallLog to activate the retrieve of calllog from the server. The default value is false.
     * @param {boolean} options.im.forceHistoryGetContactFromServer Allows to force to retrieve information about contacts when history messages are getted from server.
     * @param {boolean} options.im.enableCarbon to manage carbon copy of message (https://xmpp.org/extensions/xep-0280.html). The default value is true.     * @param {string} options.im.enablesendurgentpushmessages permit to add <retry-push xmlns='urn:xmpp:hints'/> tag to allows the server sending this messge in push with a small ttl (meaning urgent for apple/google backend) and retry sending it 10 times to increase probability that it is received by mobile device. The default value is false.
     * @param {boolean} options.im.enablesendurgentpushmessages permit to add <retry-push xmlns='urn:xmpp:hints'/> tag to allows the server sending this messge in push with a small ttl (meaning urgent for apple/google backend) and retry sending it 10 times to increase probability that it is received by mobile device. The default value is false.
     * @param {boolean} options.im.storeMessagesInConversation Allows to store messages in conversation cache if true else the conversation.messages property stay empty. The default value is true.
     * @param {number} options.im.maxMessagesStoredInConversation Allows to store messages in conversation with a maximum entries. The default value is 1000. Note: `storeMessagesInConversation` needs to be setted to true to be relevant.
     * @param {Object} options.servicesToStart <br>
     *    Services to start. This allows to start the SDK with restricted number of services, so there are less call to API.<br>
     *    Take care, severals services are linked, so disabling a service can disturb an other one.<br>
     *    By default all the services are started. Events received from server are not yet filtered.<br>
     *    So this feature is realy risky, and should be used with much more cautions.<br>
     *        {<br>
     *       "bubbles": {<br>
     *           "start_up": true,<br>
     *       },<br>
     *       "telephony": {<br>
     *           "start_up": true,<br>
     *       },<br>
     *       "channels": {<br>
     *           "start_up": true,<br>
     *       },<br>
     *       "admin": {<br>
     *           "start_up": true,<br>
     *       },<br>
     *       "fileServer": {<br>
     *           "start_up": true,<br>
     *       },<br>
     *       "fileStorage": {<br>
     *           start_up: true,<br>
     *       },<br>
     *       "calllog": {<br>
     *           "start_up": true,<br>
     *       },<br>
     *       "favorites": {<br>
     *           "start_up": true,<br>
     *
     */
    constructor(options) {
        this._option = {};
        /*
             *       @ deprecated "storeMessages": false, Tell the server to store the message for delay distribution and also for history. Please avoid to set it to true for a bot which will not read anymore the messages. It is a better way to store it in your own CPaaS application<br>
     *       "nbMaxConversations": 15, Parameter to set the maximum number of conversations to keep (defaut value to 15). Old ones are remove from XMPP server with the new method `ConversationsService::removeOlderConversations`.<br>
     *       "rateLimitPerHour": 1000, Parameter to set the maximum of "message" stanza sent to server by hour. Default value is 1000.<br>
     *       "messagesDataStore":
     *  DataStoreType.NoStoreBotSide, "no-store" Parameter to define the behaviour of the storage of the messages (Enum DataStoreType in lib/config/config , default value "DataStoreType.NoStoreBotSide")<br>
     *                          DataStoreType.NoStore "no-permanent-store" Same behaviour as previously `storeMessages=false` Tell the server to NOT store the messages for delay distribution or for history of the bot and the contact.<br>
     *                          DataStoreType.NoStoreBotSide "storetwinside" The messages are not stored on  loggued-in Bot's history, but are stored on the other side. So the contact kept the messages exchanged with bot in his history.<br>
     *                          DataStoreType.StoreTwinSide "OldstoreMessagesUsed" The messages are fully stored.<br>

         */
        /* process.on("uncaughtException", (err) => {
            console.error(err);
        });

        process.on("warning", (err) => {
            console.error(err);
        });

        process.on("unhandledRejection", (err, p) => {
            console.error(err);
        }); // */
        process.removeListener("unhandledRejection", unhandledRejection);
        process.removeListener("warning", warning);
        process.removeListener("uncaughtException", uncaughtException);
        process.on("unhandledRejection", unhandledRejection);
        process.on("warning", warning);
        process.on("uncaughtException", uncaughtException);
        // Stop the SDK if the node exe receiv a signal to stop, except for sigkill.
        process.removeListener("SIGINT", this.stopProcess());
        process.removeListener("SIGQUIT", this.stopProcess());
        process.removeListener("SIGTERM", this.stopProcess());
        process.on("SIGINT", this.stopProcess());
        process.on("SIGQUIT", this.stopProcess());
        process.on("SIGTERM", this.stopProcess());
        //process.on("SIGUSR2", that.stopProcess());
        this._option = options;
        this._core = new Core_1.Core(options);
        this._logger = this._core._logger;
    }
    /**
     * @public
     * @method start
     * @instance
     * @param {String} token a valid token to login without login/password. <br>
     * if Oauth token is provided to the SDK then application MUST implement the refresh token and send it back to SDK with `setRenewedToken` API, while following event are raised : <br>
     * Events rainbow_onusertokenrenewfailed : fired when an oauth token is expired. <br>
     * Events rainbow_onusertokenwillexpire : fired when the duration of the current user token reaches half of the maximum time. <br>
     *      For instance, if the token is valid for 1 hour, this event will arrive at 30 minutes. <br>
     *      It is recommended to renew the token upon the arrival of this event. <br>
     * @description
     *    Start the SDK <br>
     *    Note :<br>
     *    The token must be empty to signin with credentials.<br>
     *    The SDK is disconnected when the renew of the token had expired (No initial signin possible with out credentials.)<br>
     *    There is a sample using the oauth and sdk at https://github.com/Rainbow-CPaaS/passport-rainbow-oauth2-with-rainbow-node-sdk-example <br>
     */
    start(token) {
        let that = this;
        that.startTime = new Date();
        return new Promise(function (resolve, reject) {
            return that._core.start(token).then(function () {
                return that._core.signin(false, token);
                //throw new Error("error test");
            }).then(function (result) {
                let startDuration;
                // @ts-ignore
                startDuration = Math.round(new Date() - that.startTime);
                if (!result) {
                    result = {};
                }
                result.startDuration = startDuration;
                resolve(result);
                //reject ({message : "Error !!!"});
            }).catch(async function (err) {
                try {
                    await that.stop();
                }
                catch (e) {
                }
                await (0, Utils_1.setTimeoutPromised)(500).then(() => {
                    that._core._stateManager.transitTo(false, StateManager_1.SDKSTATUSENUM.STOPPED);
                });
                if (err) {
                    console.log("[index ] : rainbow_onconnectionerror : ", (0, util_1.inspect)(err));
                    // It looks that winston is close before this line :(, so console is used. 
                    // that.logger.log("error", LOG_ID + " (evt_internal_xmppfatalerror) Error XMPP, Stop le SDK : ", err);
                    that.events.publish("connectionerror", err);
                    reject(err);
                }
                else {
                    let error = ErrorManager_1.ErrorManager.getErrorManager().UNAUTHORIZED;
                    error.details = err;
                    console.log("[index ] : rainbow_onconnectionerror : ", (0, util_1.inspect)(error));
                    that.events.publish("connectionerror", error);
                    reject(error);
                }
            });
        });
    }
    /**
     * @public
     * @method startWSOnly
     * @instance
     * @description
     *    Start the SDK with only XMPP link<br>
     *
     */
    startWSOnly(token, userInfos) {
        let that = this;
        that.startTime = new Date();
        return new Promise(function (resolve, reject) {
            // Force to work without the REST API at startup :
            that._core.options._restOptions.useRestAtStartup = false;
            return that._core.start(token).then(function () {
                return that._core.signinWSOnly(false, token, userInfos);
            }).then(function (result) {
                let startDuration;
                // @ts-ignore
                startDuration = Math.round(new Date() - that.startTime);
                if (!result) {
                    result = {};
                }
                result.startDuration = startDuration;
                resolve(result);
                //reject ({message : "Error !!!"});
            }).catch(async function (err) {
                try {
                    await that.stop();
                }
                catch (e) {
                }
                await (0, Utils_1.setTimeoutPromised)(500).then(() => {
                    that._core._stateManager.transitTo(false, StateManager_1.SDKSTATUSENUM.STOPPED);
                });
                if (err) {
                    console.log("[index ] : rainbow_onconnectionerror : ", (0, util_1.inspect)(err));
                    // It looks that winston is close before this line :(, so console is used. 
                    // that.logger.log("error", LOG_ID + " (evt_internal_xmppfatalerror) Error XMPP, Stop le SDK : ", err);
                    that.events.publish("connectionerror", err);
                    reject(err);
                }
                else {
                    let error = ErrorManager_1.ErrorManager.getErrorManager().UNAUTHORIZED;
                    error.details = err;
                    console.log("[index ] : rainbow_onconnectionerror : ", (0, util_1.inspect)(error));
                    that.events.publish("connectionerror", error);
                    reject(error);
                }
            });
        });
    }
    /**
     * @public
     * @method startCLI
     * @instance
     * @description
     *      Start the SDK in CLI Mode
     */
    startCLI() {
        let that = this;
        return new Promise(function (resolve, reject) {
            return that._core.start(true).then(function () {
                resolve(undefined);
            }).catch(async function (err) {
                try {
                    await that.stop();
                }
                catch (e) {
                }
                let error = ErrorManager_1.ErrorManager.getErrorManager().UNAUTHORIZED;
                error.details = err;
                that.events.publish("connectionerror", error);
                reject(error);
            });
        });
    }
    /**
     * @public
     * @method siginCLI
     * @instance
     * @description
     *      Sign-in in CLI Mode (without the XMPP link)
     */
    signinCLI() {
        let that = this;
        return new Promise(function (resolve, reject) {
            return that._core.signin(false, undefined).then(function (json) {
                resolve(json);
            }).catch(async function (err) {
                try {
                    await that.stop();
                }
                catch (e) {
                }
                let error = ErrorManager_1.ErrorManager.getErrorManager().UNAUTHORIZED;
                error.details = err;
                that.events.publish("connectionerror", error);
                reject(error);
            });
        });
    }
    /**
     * @public
     * @method setRenewedToken
     * @instance
     * @description
     *    Set the token renewed externaly of the SDK. This is for oauth authentication.</br>
     *   Note: An event #rainbow_onusertokenrenewfailed is fired when an oauth token is expired.</br>
     *      The application must refresh the token and send it back to SDK with `setRenewedToken` API.
     */
    setRenewedToken(strToken) {
        let that = this;
        return that._core.setRenewedToken(strToken);
    }
    /**
     * @public
     * @method setCredentialPassword
     * @instance
     * @description
     *    Set the password credential of the Bot for the login.</br>
     *    Note: The SDK use this password in the next connection/reconnection.
     */
    setCredentialPassword(strPassword) {
        let that = this;
        return that._core.setCredentialPassword(strPassword);
    }
    /**
     * @public
     * @method stop
     * @instance
     * @description
     *    Stop the SDK
     */
    stop() {
        let that = this;
        return new Promise(function (resolve, reject) {
            return that._core.stop().then(function (result) {
                //let success = ErrorManager.getErrorManager().OK;
                (0, Utils_1.setTimeoutPromised)(1500).then(() => {
                    //that._core._stateManager.stop();
                    //that.events.publish("stopped", success);
                    resolve(result);
                });
            }).catch(function (err) {
                let error = ErrorManager_1.ErrorManager.getErrorManager().ERROR;
                error.details = err;
                that.events.publish("stopped", error);
                reject(error);
            });
        });
    }
    /**
     * @public
     * @method destroy
     * @instance
     * @description
     *    This method should be called before the bot to point to the SDK's instance to remove listener of "process" object. </br>
     *    And then avoid the error `MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 SIGINT listeners added to [process]. Use emitter.setMaxListeners() to increase limit` when the SDK is instantiated and removed more than
     *    10 times.
     *
     */
    destroy() {
        process.removeListener("SIGINT", this.stopProcess());
        process.removeListener("SIGQUIT", this.stopProcess());
        process.removeListener("SIGTERM", this.stopProcess());
        process.removeListener("unhandledRejection", unhandledRejection);
        process.removeListener("warning", warning);
        process.removeListener("uncaughtException", uncaughtException);
    }
    stopProcess() {
        let self = this;
        // console.log("stopProcess.");
        return async () => {
            try {
                // console.log("stopProcess");
                await self.stop().catch((ee) => {
                    console.log("stopProcess, stop failed : ", ee);
                });
                await (0, Utils_1.setTimeoutPromised)(1000);
                // eslint-disable-next-line no-process-exit
            }
            catch (e) {
                console.log("stopProcess, CATCH Error !!! stop failed : ", e);
            }
            process.exit(0);
        };
    }
    setAreasLogs(areasLogs) {
        this._logger.areasLogs = areasLogs;
    }
    /**
     * @public
     * @method {LogLevelAreas} getAreasLogs
     * @instance
     * @nodered true
     * @description
     *    Get access to the Logs Areas
     * @return {ImsService}
     */
    getAreasLogs() {
        return this._logger.areasLogs;
    }
    /**
     * @public
     * @property {ImsService} im
     * @instance
     * @nodered true
     * @service true
     * @description
     *    Get access to the IM module
     * @return {ImsService}
     */
    get im() {
        return this._core.im;
    }
    /**
     * @public
     * @property {ChannelsService} channels
     * @instance
     * @nodered true
     * @service true
     * @description
     *    Get access to the Channels module
     * @return {ChannelsService}
     */
    get channels() {
        return this._core.channels;
    }
    /**
     * @public
     * @property {ContactsService} contacts
     * @nodered true
     * @service true
     * @instance
     * @description
     *    Get access to the Contacts module
     * @return {ContactsService}
     */
    get contacts() {
        return this._core.contacts;
    }
    /**
     * @public
     * @property {ConversationsService} conversations
     * @nodered true
     * @service true
     * @instance
     * @description
     *    Get access to the Conversations module
     * @return {ConversationsService}
     */
    get conversations() {
        return this._core.conversations;
    }
    /**
     * @public
     * @property {PresenceService} presence
     * @instance
     * @nodered true
     * @service true
     * @description
     *    Get access to the Presence module
     * @return {PresenceService}
     */
    get presence() {
        return this._core.presence;
    }
    /**
     * @public
     * @property {BubblesService} bubbles
     * @instance
     * @nodered true
     * @service true
     * @description
     *    Get access to the Bubbles module
     * @return {BubblesService}
     */
    get bubbles() {
        return this._core.bubbles;
    }
    /**
     * @public
     * @property {GroupsService} groups
     * @instance
     * @nodered true
     * @service true
     * @description
     *    Get access to the Groups module
     * @return {GroupsService}
     */
    get groups() {
        return this._core.groups;
    }
    /**
     * @public
     * @property {Events} events
     * @instance
     * @nodered true
     * @description
     *    Get access to the Events module
     * @return {Events}
     */
    get events() {
        return this._core.events;
    }
    /**
     * @public
     * @property {FileServerService} fileServer
     * @instance
     * @nodered true
     * @service true
     * @description
     *    Get access to the File Server module
     * @return {FileServerService}
     */
    get fileServer() {
        return this._core.fileServer;
    }
    /**
     * @public
     * @property {FileStorageService} fileStorage
     * @instance
     * @nodered true
     * @service true
     * @description
     *    Get access to the File Storage module
     * @return {FileStorageService}
     */
    get fileStorage() {
        return this._core.fileStorage;
    }
    /**
     * @public
     * @property {AdminService} admin
     * @instance
     * @nodered true
     * @service true
     * @description
     *    Get access to the Admin module
     * @return {AdminService}
     */
    get admin() {
        return this._core.admin;
    }
    /**
     * @public
     * @property {Object} profiles
     * @instance
     * @nodered true
     * @service true
     * @description
     *    Get access to the Profiles module
     * @return {ProfilesService}
     */
    get profiles() {
        return this._core.profiles;
    }
    /**
     * @private
     * @property {RESTService} rest
     * @instance
     * @description
     *    Get access to the REST module
     * @return {RESTService}
     */
    get rest() {
        return this._core.rest;
    }
    /**
     * @public
     * @property {SettingsService} settings
     * @instance
     * @nodered true
     * @service true
     * @description
     *    Get access to the Settings module
     * @return {SettingsService}
     */
    get settings() {
        return this._core.settings;
    }
    /**
     * @public
     * @property {SDKSTATUSENUM} state
     * @instance
     * @nodered true
     * @description
     *    Return the state of the SDK (eg: STOPPED, STARTED, CONNECTED, READY, DISCONNECTED, RECONNECTING, FAILED, ERROR)
     * @return {SDKSTATUSENUM}
     */
    get state() {
        return this._core.state;
    }
    /**
     * @public
     * @property {String} version
     * @instance
     * @nodered true
     * @description
     *      Return the version of the SDK
     * @return {String}
     */
    get version() {
        return this._core.version;
    }
    /**
     * @public
     * @property {ConnectedUser} connectedUser
     * @instance
     * @nodered true
     * @description
     *      Return the connected user information
     * @return {any}
     */
    get connectedUser() {
        return this._core.rest.account;
    }
    /**
     * @public
     * @property {TelephonyService} telephony
     * @instance
     * @nodered true
     * @service true
     * @description
     *    Get access to the telephony module
     * @return {TelephonyService}
     */
    get telephony() {
        return this._core.telephony;
    }
    /**
     * @public
     * @property {TasksService} tasks
     * @instance
     * @nodered true
     * @service true
     * @description
     *    Get access to the tasks module
     * @return {TasksService}
     */
    get tasks() {
        return this._core.tasks;
    }
    /**
     * @public
     * @property {CallLogService} calllog
     * @instance
     * @nodered true
     * @service true
     * @description
     *    Get access to the calllog module
     * @return {CallLogService}
     */
    get calllog() {
        return this._core.calllog;
    }
    /**
     * @public
     * @property {FavoritesService} favorites
     * @instance
     * @nodered true
     * @service true
     * @description
     *    Get access to the favorite module
     * @return {FavoritesService}
     */
    get favorites() {
        return this._core._favorites;
    }
    /**
     * @public
     * @property {InvitationsService} invitations
     * @instance
     * @nodered true
     * @service true
     * @description
     *    Get access to the invitation module
     * @return {InvitationsService}
     */
    get invitations() {
        return this._core._invitations;
    }
    /**
     * @public
     * @property {S2SService} s2s
     * @instance
     * @nodered true
     * @service true
     * @description
     *    Get access to the s2s module
     * @return {S2SService}
     */
    get s2s() {
        return this._core._s2s;
    }
    /**
     * @public
     * @property {AlertsService} alerts
     * @instance
     * @nodered true
     * @service true
     * @description
     *    Get access to the alerts module
     * @return {AlertsService}
     */
    get alerts() {
        return this._core._alerts;
    }
    /**
     * @public
     * @property {RBVoiceService} alerts
     * @instance
     * @nodered true
     * @service true
     * @description
     *    Get access to the webinar module
     * @return {RBVoiceService}
     */
    get rbvoice() {
        return this._core._rbvoice;
    }
    /**
     * @public
     * @property {WebinarsService} alerts
     * @intance
     * @nodered true
     * @service true
     * @description
     *    Get access to the webinar module
     * @return {WebinarsService}
     */
    get webinars() {
        return this._core._webinars;
    }
    /**
     * @public
     * @property {HTTPoverXMPP} httpoverxmpp
     * @instance
     * @nodered true
     * @service true
     * @description
     *    Get access to the httpoverxmpp module
     * @return {HTTPoverXMPP}
     */
    get httpoverxmpp() {
        return this._core._httpoverxmpp;
    }
    /**
     * @public
     * @property {RPCoverXMPPService} rpcoverxmpp
     * @instance
     * @nodered true
     * @service true
     * @description
     *    Get access to the rpcoverxmpp module
     * @return {RPCoverXMPPService}
     */
    get rpcoverxmpp() {
        return this._core._rpcoverxmpp;
    }
    //region Access to enum types
    /**
     * @public
     * @property {Object} DataStoreType
     * @description
     *    Get access to the DataStoreType type
     * @return {DataStoreType}
     */
    static get DataStoreType() {
        return config_1.DataStoreType;
    }
    /**
     * @public
     * @property {Object} UrgencyType
     * @description
     *    Get access to the UrgencyType type
     * @return {UrgencyType}
     */
    static get UrgencyType() {
        return config_1.UrgencyType;
    }
    /**
     * @public
     * @property {Object} CLOUDPBXCLIOPTIONPOLICY
     * @description
     *    Get access to the CLOUDPBXCLIOPTIONPOLICY type
     * @return {CLOUDPBXCLIOPTIONPOLICY}
     */
    static get CLOUDPBXCLIOPTIONPOLICY() {
        return AdminService_1.CLOUDPBXCLIOPTIONPOLICY;
    }
    /**
     * @public
     * @property {Object} PresenceLevel
     * @description
     *    Get access to the PresenceLevel type
     * @return {PresenceLevel}
     */
    static get PresenceLevel() {
        return PresenceRainbow_js_1.PresenceLevel;
    }
    /**
     * @public
     * @property {Object} PresenceShow
     * @description
     *    Get access to the PresenceShow type
     * @return {PresenceShow}
     */
    static get PresenceShow() {
        return PresenceRainbow_js_1.PresenceShow;
    }
    /**
     * @public
     * @property {Object} PresenceStatus
     * @description
     *    Get access to the PresenceStatus type
     * @return {PresenceStatus}
     */
    static get PresenceStatus() {
        return PresenceRainbow_js_1.PresenceStatus;
    }
    /**
     * @public
     * @property {Object} PresenceDetails
     * @description
     *    Get access to the PresenceDetails type
     * @return {PresenceDetails}
     */
    static get PresenceDetails() {
        return PresenceRainbow_js_1.PresenceDetails;
    }
    /**
     * @public
     * @property {Object} PresencePhone
     * @description
     *    Get access to the PresencePhone type
     * @return {PresencePhone}
     */
    static get PresencePhone() {
        return PresenceRainbow_js_1.PresencePhone;
    }
    /**
     * @public
     * @property {Object} LEVELSNAMES
     * @description
     *    Get access to the LEVELSNAMES type
     * @return {LEVELSNAMES}
     */
    static get LEVELSNAMES() {
        return LevelLogs_js_1.LEVELSNAMES;
    }
    /**
     * @public
     * @property {Object} LEVELS
     * @description
     *    Get access to the LEVELS type
     * @return {LEVELS}
     */
    static get LEVELS() {
        return LevelLogs_js_1.LEVELS;
    }
    /**
     * @public
     * @property {Object} LEVELSCOLORS
     * @description
     *    Get access to the PresencePhone type
     * @return {LEVELSCOLORS}
     */
    static get LEVELSCOLORS() {
        return LevelLogs_js_1.LEVELSCOLORS;
    }
    //endregion Access to enum types
    get Utils() {
        return this._core.Utils;
    }
    /**
     * @public
     * @method getConnectionStatus
     * @instance
     * @nodered true
     * @description
     *    Get connections status of each low layer services, and also the full SDK state. <br>
     * <br>
     * { <br>
     * restStatus: boolean, The status of the REST connection authentication to rainbow server. <br>
     * xmppStatus: boolean, The status of the XMPP Connection to rainbow server. <br>
     * s2sStatus: boolean, The status of the S2S Connection to rainbow server. <br>
     * state: SDKSTATUSENUM The state of the SDK. <br>
     * nbHttpAdded: number, the number of HTTP requests (any verb GET, HEAD, POST, ...) added in the HttpManager queue. Note that it is reset to zero when it reaches Number.MAX_SAFE_INTEGER value. <br>
     * httpQueueSize: number, the number of requests stored in the Queue. Note that when a request is sent to server, it is already removed from the queue. <br>
     * nbRunningReq: number, the number of requests which has been poped from the queue and the SDK did not yet received an answer for it. <br>
     * maxSimultaneousRequests : number, the number of request which can be launch at a same time. <br>
     * nbReqInQueue : number, the number of requests waiting for being treated by the HttpManager.  <br>
     * } <br>
     * @return {Promise<{ restStatus: boolean, xmppStatus: boolean, s2sStatus: boolean, state: SDKSTATUSENUM, nbHttpAdded: number, httpQueueSize: number, nbRunningReq: number, maxSimultaneousRequests : number }>}
     * @category async
     */
    getConnectionStatus() {
        return this._core.getConnectionStatus();
    }
    /**
     * @public
     * @property {Object} Appreciation
     * @static
     * @description
     *    Get connections Appreciation type. <br>
     * @return {Appreciation}
     */
    static get Appreciation() {
        return Channel_1.Appreciation;
    }
    /**
     * @public
     * @property {Object} CalendarManager
     * @static
     * @description
     *    Get connections CalendarManager type. <br>
     * @return {CalendarManager}
     */
    static get CalendarManager() {
        return CalendarManager_js_1.CalendarManager;
    }
    /**
     * @public
     * @property {Object} AutoReplyManager
     * @static
     * @description
     *    Get connections AutoReplyManager type. <br>
     * @return {AutoReplyManager}
     */
    static get AutoReplyManager() {
        return AutoReplyManager_js_1.AutoReplyManager;
    }
}
exports.NodeSDK = NodeSDK;
module.exports = NodeSDK;
module.exports.NodeSDK = NodeSDK;
module.exports.default = NodeSDK;
exports.default = NodeSDK;
//# sourceMappingURL=NodeSDK.js.map