"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.Telemetry = void 0;
const os = __importStar(require("node:os"));
const path = __importStar(require("node:path"));
const node_core_library_1 = require("@rushstack/node-core-library");
const Rush_1 = require("../api/Rush");
const performance_1 = require("../utilities/performance");
const MAX_FILE_COUNT = 100;
const ONE_MEGABYTE_IN_BYTES = 1048576;
class Telemetry {
    constructor(rushConfiguration, rushSession) {
        this._flushAsyncTasks = new Set();
        this._telemetryStartTime = 0;
        this._rushConfiguration = rushConfiguration;
        this._rushSession = rushSession;
        this._enabled = this._rushConfiguration.telemetryEnabled;
        this._store = [];
        const folderName = 'telemetry';
        this._dataFolder = path.join(this._rushConfiguration.commonTempFolder, folderName);
    }
    log(telemetryData) {
        if (!this._enabled) {
            return;
        }
        const cpus = os.cpus();
        const data = {
            ...telemetryData,
            performanceEntries: telemetryData.performanceEntries || (0, performance_1.collectPerformanceEntries)(this._telemetryStartTime),
            machineInfo: telemetryData.machineInfo || {
                machineArchitecture: os.arch(),
                // The Node.js model is sometimes padded, for example:
                // "AMD Ryzen 7 3700X 8-Core Processor             "
                machineCpu: cpus[0].model.trim(),
                machineCores: cpus.length,
                machineTotalMemoryMiB: Math.round(os.totalmem() / ONE_MEGABYTE_IN_BYTES),
                machineFreeMemoryMiB: Math.round(os.freemem() / ONE_MEGABYTE_IN_BYTES)
            },
            timestampMs: telemetryData.timestampMs || new Date().getTime(),
            platform: telemetryData.platform || process.platform,
            rushVersion: telemetryData.rushVersion || Rush_1.Rush.version
        };
        this._telemetryStartTime = performance.now();
        this._store.push(data);
    }
    flush() {
        if (!this._enabled || this._store.length === 0) {
            return;
        }
        const fullPath = this._getFilePath();
        node_core_library_1.JsonFile.save(this._store, fullPath, { ensureFolderExists: true, ignoreUndefinedValues: true });
        if (this._rushSession.hooks.flushTelemetry.isUsed()) {
            /**
             * User defined flushTelemetry should not block anything, so we don't await here,
             * and store the promise into a list so that we can await it later.
             */
            const asyncTaskPromise = this._rushSession.hooks.flushTelemetry.promise(this._store);
            this._flushAsyncTasks.add(asyncTaskPromise);
            asyncTaskPromise.then(() => {
                this._flushAsyncTasks.delete(asyncTaskPromise);
            }, () => {
                this._flushAsyncTasks.delete(asyncTaskPromise);
            });
        }
        this._store = [];
        this._cleanUp();
    }
    /**
     * There are some async tasks that are not finished when the process is exiting.
     */
    async ensureFlushedAsync() {
        await Promise.all(this._flushAsyncTasks);
    }
    get store() {
        return this._store;
    }
    /**
     * When there are too many log files, delete the old ones.
     */
    _cleanUp() {
        if (node_core_library_1.FileSystem.exists(this._dataFolder)) {
            const files = node_core_library_1.FileSystem.readFolderItemNames(this._dataFolder);
            if (files.length > MAX_FILE_COUNT) {
                const sortedFiles = files
                    .map((fileName) => {
                    const filePath = path.join(this._dataFolder, fileName);
                    const stats = node_core_library_1.FileSystem.getStatistics(filePath);
                    return {
                        filePath: filePath,
                        modifiedTime: stats.mtime.getTime(),
                        isFile: stats.isFile()
                    };
                })
                    .filter((value) => {
                    // Only delete files
                    return value.isFile;
                })
                    .sort((a, b) => {
                    return a.modifiedTime - b.modifiedTime;
                })
                    .map((s) => {
                    return s.filePath;
                });
                const filesToDelete = sortedFiles.length - MAX_FILE_COUNT;
                for (let i = 0; i < filesToDelete; i++) {
                    node_core_library_1.FileSystem.deleteFile(sortedFiles[i]);
                }
            }
        }
    }
    _getFilePath() {
        let fileName = `telemetry_${new Date().toISOString()}`;
        fileName = fileName.replace(/[\-\:\.]/g, '_') + '.json';
        return path.join(this._dataFolder, fileName);
    }
}
exports.Telemetry = Telemetry;
//# sourceMappingURL=Telemetry.js.map