"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.anonymize = void 0;
const is_in_subnet_1 = require("is-in-subnet");
/**
 * This definition of "anonymization" matches that used by the Event API in its
 * "anonymize_ip" setting.
 * Source: https://github.com/optimizely/optimizely-flume/blob/560389d7d1d366d3d0894662680b0cb928e673d4/src/main/java/com/optimizely/flume/interceptor/IPAnonymizingInterceptor.java#L69-L83
 *
 * @param {String} ip
 *        A valid v4 or v6 address.
 * @returns {String}
 *        A version of the given address, with low bits zeroed out.
 *        Lower 8 bits in the case of IPv4; 80 bits in case of IPv6.
 */
function anonymize(ip) {
    const version = (0, is_in_subnet_1.isIP)(ip);
    if (version === 4) {
        // Zero out low octet
        return ip.replace(/(\d+)$/, '0');
    }
    // => version === 6. Zero out the low 5 hextets.
    // Split into 8 pieces, keep only the first 3, and append '::' to signify the rest.
    return v6Parts(ip).slice(0, 3).join(':') + '::';
}
exports.anonymize = anonymize;
/**
 * @param {String} ip
 * @returns {Array.<String>}
 *        The given address, with the '::' (if it exists) expanded, and no empty
 *        hextets. E.g.,
 *        'abc:de:32::bed:293a' => ['abc', 'de', '32', '0', '0', '0', 'bed', '293a'].
 */
function v6Parts(ip) {
    if (ip.includes('::')) {
        const colonCount = (ip.match(/:/g) || []).length;
        if (colonCount !== 7) {
            ip = ip.replace('::', ':'.repeat(7 - colonCount + 2));
        }
    }
    return ip.split(':').map(el => el || '0');
}
