"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSessionCookieString = exports.getOptOutCookieString = exports.getCookieString = exports.getCookieDomain = exports.SECURE_CROSSSITE_OPTIONS = void 0;
const cookie_1 = __importDefault(require("cookie"));
const parse_domain_1 = require("parse-domain");
const constants_1 = require("../constants");
// Chrome 80 (and likely other browsers in the future) require the secure flag if SameSite is set to none, so we combine the options
exports.SECURE_CROSSSITE_OPTIONS = {
    sameSite: 'none',
    secure: true,
};
function getCookieDomain(url, logger) {
    // See https://optimizely.slack.com/archives/CEEG8DQHJ/p1565742227243100?thread_ts=1565741636.237900&cid=CEEG8DQHJ
    const parsedDomain = (0, parse_domain_1.parseDomain)((0, parse_domain_1.fromUrl)(url));
    if (!parsedDomain.topLevelDomains) {
        logger.logError(new Error('Env / Error computing cookie domain'));
        return null;
    }
    return `${parsedDomain.domain}.${parsedDomain.topLevelDomains.join('.')}`;
}
exports.getCookieDomain = getCookieDomain;
const getCookieString = (...args) => cookie_1.default.serialize(...args);
exports.getCookieString = getCookieString;
/**
 * Construct a cookie string to set the OptimizelyOptOut cookie in the opt out
 * response.
 * @param {String} cookieDomain
 * @param {Boolean} [secureCrossSiteCookies false]
 * @return {String} The opt out response will write to document.cookie.
 */
function getOptOutCookieString(cookieDomain, secureCrossSiteCookies = false) {
    let options = {
        maxAge: constants_1.OPT_OUT_COOKIE_EXPIRATION,
        path: '/',
        domain: cookieDomain,
    };
    if (secureCrossSiteCookies) {
        Object.assign(options, exports.SECURE_CROSSSITE_OPTIONS);
    }
    return (0, exports.getCookieString)(constants_1.OptimizelyCookies.OPT_OUT, 'true', options);
}
exports.getOptOutCookieString = getOptOutCookieString;
function getSessionCookieString(sessionId) {
    const options = {
        path: '/',
    };
    return (0, exports.getCookieString)(constants_1.OptimizelyCookies.OPTIMIZELY_SESSION, sessionId, options);
}
exports.getSessionCookieString = getSessionCookieString;
