All files / Cognigy-CLI/build/lib lexicons.js

0% Statements 0/176
0% Branches 0/74
0% Functions 0/19
0% Lines 0/163

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
"use strict";
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;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.diffLexicons = exports.pushLexicon = exports.restoreLexicons = exports.pullLexicon = exports.cloneLexicons = void 0;
const fs = __importStar(require("fs"));
const axios_1 = __importDefault(require("axios"));
const Diff = __importStar(require("diff"));
const cli_spinner_1 = require("cli-spinner");
const chalk_1 = __importDefault(require("../utils/chalk"));
const form_data_1 = __importDefault(require("form-data"));
const progressBar_1 = require("../utils/progressBar");
const config_1 = __importDefault(require("../utils/config"));
const cognigyClient_1 = __importDefault(require("../utils/cognigyClient"));
const axiosClient_1 = require("../utils/axiosClient");
const checks_1 = require("../utils/checks");
const indexAll_1 = require("../utils/indexAll");
const chunk_1 = require("../utils/chunk");
const cloneLexicons = async (availableProgress) => {
    (0, checks_1.checkCreateDir)(config_1.default.agentDir);
    (0, checks_1.checkCreateDir)(config_1.default.agentDir + '/lexicons');
    const lexiconDir = config_1.default.agentDir + '/lexicons';
    await (0, checks_1.removeCreateDir)(lexiconDir);
    const lexicons = await (0, indexAll_1.indexAll)(cognigyClient_1.default.indexLexicons)({
        projectId: config_1.default.agent,
    });
    const incrementPerLexicon = availableProgress / lexicons.items.length;
    const lexiconsPromiseArr = [];
    for (let lexicon of lexicons.items) {
        lexiconsPromiseArr.push(() => (0, exports.pullLexicon)(lexicon.name, incrementPerLexicon));
    }
    const chunkedLexiconssPromiseArr = (0, chunk_1.chunkArray)(lexiconsPromiseArr, 5);
    for (let chunk of chunkedLexiconssPromiseArr) {
        await Promise.all(chunk.map((func) => func()));
    }
    return Promise.resolve();
};
exports.cloneLexicons = cloneLexicons;
const pullLexicon = async (lexiconName, availableProgress) => {
    (0, checks_1.checkCreateDir)(config_1.default.agentDir);
    (0, checks_1.checkCreateDir)(config_1.default.agentDir + '/lexicons');
    const lexiconDir = config_1.default.agentDir + '/lexicons/' + lexiconName;
    const progressIncrement = availableProgress / 3;
    const lexicons = await (0, indexAll_1.indexAll)(cognigyClient_1.default.indexLexicons)({
        projectId: config_1.default.agent,
    });
    (0, progressBar_1.addToProgressBar)(progressIncrement);
    const lexicon = lexicons.items.find((lexicon) => {
        if (lexicon.name === lexiconName)
            return lexicon;
    });
    if (!lexicon) {
        console.log(`\n\Lexicon with name ${lexiconName} can't be found in your Virtual Agent on Cognigy.AI. Aborting...`);
        process.exit(0);
    }
    await (0, checks_1.removeCreateDir)(lexiconDir);
    (0, progressBar_1.addToProgressBar)(progressIncrement);
    const lexiconConfig = {
        lexiconId: lexicon._id,
    };
    fs.writeFileSync(lexiconDir + '/config.json', JSON.stringify(lexiconConfig, undefined, 4));
    let lexiconFile;
    const keyphraseCount = (await cognigyClient_1.default.indexLexiconKeyphrases(lexiconConfig)).total;
    if (keyphraseCount > 0) {
        let exportFromLexiconTask;
        exportFromLexiconTask = await cognigyClient_1.default.exportFromLexicon({
            lexiconId: lexicon._id,
            projectId: config_1.default.agent,
        });
        await (0, checks_1.checkTask)(exportFromLexiconTask._id);
        const downloadLink = await cognigyClient_1.default.composeLexiconDownloadLink({
            lexiconId: lexicon._id,
        });
        lexiconFile = (await axios_1.default.get(downloadLink.downloadLink)).data;
    }
    else {
        lexiconFile = '';
    }
    fs.writeFileSync(lexiconDir + '/keyphrases.csv', lexiconFile);
    (0, progressBar_1.addToProgressBar)(progressIncrement);
    return Promise.resolve();
};
exports.pullLexicon = pullLexicon;
const restoreLexicons = async (availableProgress) => {
    const agentLexiconDir = config_1.default.agentDir + '/lexicons';
    const lexiconDirectories = fs.readdirSync(agentLexiconDir);
    if (!lexiconDirectories || lexiconDirectories.length === 0) {
        console.log('No Lexicons found, aborting...\n');
        return;
    }
    const incrementPerLexicon = availableProgress / lexiconDirectories.length;
    for (let lexicon of lexiconDirectories) {
        await (0, exports.pushLexicon)(lexicon, incrementPerLexicon);
    }
    return Promise.resolve();
};
exports.restoreLexicons = restoreLexicons;
const pushLexicon = async (lexiconName, availableProgress, options) => {
    const lexiconDir = config_1.default.agentDir + '/lexicons/' + lexiconName;
    if (!fs.existsSync(`${lexiconDir}/config.json`)) {
        console.log(`Lexicon ${lexiconName} can't be found in '${lexiconDir}'`);
        process.exit(0);
    }
    const spinner = new cli_spinner_1.Spinner(`Uploading lexicon ${lexiconName} to Cognigy.AI... %s`);
    spinner.setSpinnerString('|/-\\');
    try {
        spinner.start();
        const lexiconConfig = JSON.parse(fs.readFileSync(`${lexiconDir}/config.json`).toString());
        const lexiconId = lexiconConfig.lexiconId;
        const keyphrasesPath = `${lexiconDir}/keyphrases.csv`;
        if (!fs.existsSync(keyphrasesPath)) {
            throw new Error('keyphrases.csv file is missing.');
        }
        const fileStats = fs.statSync(keyphrasesPath);
        if (fileStats.size === 0) {
            console.log(`The keyphrases.csv file is empty. Skipping the API call.`);
            spinner.stop();
            return Promise.resolve();
        }
        const form = new form_data_1.default();
        form.append('mode', 'overwrite');
        form.append('lexiconId', lexiconId);
        form.append('file', fs.createReadStream(keyphrasesPath));
        const result = await (0, axiosClient_1.makeAxiosRequest)({
            path: `/new/v2.0/lexicons/${lexiconId}/import`,
            method: 'POST',
            type: 'multipart/form-data',
            form: form,
        });
        await (0, checks_1.checkTask)(result?.data?._id, options?.timeout);
        spinner.stop();
        console.log(`Successfully uploaded lexicon ${lexiconName}.`);
    }
    catch (err) {
        spinner.stop();
        console.error(`\n${chalk_1.default.red('Error:')} Failed to upload Lexicon ${lexiconName} to Cognigy.AI: ${err.message}.\n Aborting...`);
        process.exit(1);
    }
    return Promise.resolve();
};
exports.pushLexicon = pushLexicon;
const diffLexicons = async (lexiconName, mode = 'full') => {
    try {
        if (['full'].indexOf(mode) === -1) {
            console.log(`Selected mode not supported for Lexicons. Supported modes:\n\n- full\n`);
            process.exit(0);
        }
        const spinner = new cli_spinner_1.Spinner(`Comparing ${chalk_1.default.green('local')} and ${chalk_1.default.red('remote')} Lexicon resource ${lexiconName}... %s`);
        spinner.setSpinnerString('|/-\\');
        spinner.start();
        const lexiconDir = config_1.default.agentDir + '/lexicons';
        if (!fs.existsSync(lexiconDir + '/' + lexiconName) ||
            !fs.existsSync(lexiconDir + '/' + lexiconName + '/config.json') ||
            !fs.existsSync(lexiconDir + '/' + lexiconName + '/keyphrases.csv')) {
            spinner.stop();
            console.log(`\nThe requested Lexicon resource (${lexiconName}) couldn't be found ${chalk_1.default.green('locally')}. Aborting...`);
            process.exit(0);
        }
        const localConfig = JSON.parse(fs
            .readFileSync(lexiconDir + '/' + lexiconName + '/config.json')
            .toString());
        const localCsvData = fs
            .readFileSync(lexiconDir + '/' + lexiconName + '/keyphrases.csv')
            .toString();
        const remoteConfig = await cognigyClient_1.default.readLexicon({
            lexiconId: localConfig.lexiconId,
        });
        const exportFromLexiconTask = await cognigyClient_1.default.exportFromLexicon({
            lexiconId: localConfig.lexiconId,
            projectId: config_1.default.agent,
        });
        await (0, checks_1.checkTask)(exportFromLexiconTask._id);
        const downloadLink = await cognigyClient_1.default.composeLexiconDownloadLink({
            lexiconId: localConfig.lexiconId,
        });
        const remoteCsvData = (await axios_1.default.get(downloadLink.downloadLink)).data;
        const diff = Diff.diffChars(remoteCsvData, localCsvData);
        let diffString = '';
        diff.forEach((part) => {
            if (part.added) {
                diffString += chalk_1.default.green(part.value);
            }
            else if (part.removed) {
                diffString += chalk_1.default.red(part.value);
            }
            else {
                diffString += chalk_1.default.grey(part.value);
            }
        });
        spinner.stop();
        if (diffString)
            console.log(`\n\n ${diffString}`);
        else
            console.log(`\n\nThe local and remote resource are identical.`);
        return;
    }
    catch (err) {
        console.log(err.message);
        process.exit(0);
    }
};
exports.diffLexicons = diffLexicons;