All files / ide/vscode pipe.ts

100% Statements 66/66
100% Branches 5/5
100% Functions 30/30
100% Lines 65/65

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                                                    10x 41x   10x 10x     9x 9x     1x     2x     1x     1x         3x 3x 3x   3x       2x     1x     1x     2x       2x     1x   1x       1x 1x       1x     1x     1x 1x   1x         1x 1x           2x 2x   2x   2x 2x   1x     2x     2x 1x     2x     3x   3x   3x 3x       12x 12x   12x         12x 12x   3x 3x 2x 2x         3x       1x 1x 1x   1x 1x   1x   1x           1x 1x             10x 8x    
/*
  Copyright (C) 2023 Sber
 
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at
 
          http://www.apache.org/licenses/LICENSE-2.0
 
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/
 
import { v4 as uuidv4 } from 'uuid';
import md5 from 'md5';
import { vsCodeHost } from './host';
 
import plantuml from '@front/helpers/plantuml';
import { prepareHTMLForPrint } from '@front/helpers/html';
import {papiSettingUpdated} from '@ide/papiLifeCycle';
import gateway from '@ide/gateway';
import compress from '@global/compress/compress.mjs';
 
const emit = (command: string, content: any): Promise<any> | void =>
  vscode.postMessage({ command, content });
 
export const listeners: { [key: string]: any } = {};
const compressor = compress();
 
export default (): void => {
  gateway.initVsCodeGateway();
  window.$PAPI = {
    settings: vsCodeHost()?.settings,
    checkIsRootManifest(): void {
      emit('check-is-root-manifest', '');
    },
    pluginList(plugins) {
      emit('pluginList', plugins);
    },
    loaded() {
      emit('loaded', '');
    },
    initProject(mode): void {
      emit('create', mode);
    },
    print() {
      // Экспорт для печати намеренно вызывает все обработчики печати в окне.
      // Снимок получает подготовленный DOM, а afterprint восстанавливает интерактивное состояние.
      window.dispatchEvent(new Event('beforeprint'));
      try {
        emit('print', { document: prepareHTMLForPrint() });
      } finally {
        window.dispatchEvent(new Event('afterprint'));
      }
    },
    addLinks(node): void {
      emit('addLinks', node);
    },
    applyEntitiesSchema(schema) {
      emit('applyschema', JSON.stringify({ schema }));
    },
    debug() {
      emit('debug', undefined);
    },
    download(content, title, description, extension, fileName = `dh_${Date.now()}`): void {
      const stringifedUri = JSON.stringify({
        content, title, description, extension, fileName
      });
 
      emit('download', stringifedUri);
    },
    upload(): Promise<void> {
      const uuid = uuidv4();
 
      emit('upload', {
        uuid
      });
 
      return new Promise((res, rej): void => {
        listeners[uuid] = { res, rej };
      });
    },
    goto(source, entity, id): void {
      emit('goto', JSON.stringify({ source, entity, id }));
    },
    reload(currentRoute): void {
      emit('reload-force', { currentRoute });
    },
    renderPlantUML(uml): Promise<void> {
      const stringifedUri = JSON.stringify(plantuml.svgURL(uml));
      const uuid = uuidv4();
 
      emit('plantuml', {
        stringifedUri,
        uuid
      });
 
      return new Promise((res, rej): void => {
        listeners[uuid] = { res, rej };
      });
    },
    // Расчёт схемы SmartAnts в расширении: JVM-сервис по протоколу портала (base64 gzip JSON параметров).
    // Есть, только если расширение объявило поддержку в настройках (settings.smartants); ответ сервиса {result, queryID, graph|error}
    async computeSmartAnts(params: object): Promise<any> {
      const query = await compressor.encodeBase64(JSON.stringify(params));
      const uuid = uuidv4();
 
      emit('smartants', { query, uuid });
 
      const { data } = await new Promise<any>((res, rej): void => {
        listeners[uuid] = { res, rej };
      });
      return data;
    },
    invalidateCache() {
      emit('invalidateCache', null);
    },
    clearDatasetsCache(datasetsIDs: string[]) {
      const datasetCacheKeys = datasetsIDs.map(id => md5(`{"path":"/datasets/${id}"}`));
      emit('clearCaches', { datasetCacheKeys });
    },
    updateCache(key: string, data: any) {
      emit('updateCache', { key, data: JSON.stringify(data) });
    },
    pullFromCache(key: string, resolver: () => void, args: object): Promise<void> {
      const uuid = uuidv4();
 
      emit('pullFromCache', { uuid, key: md5(key) });
 
      return new Promise((res, rej): void => {
        listeners[uuid] = { res, rej, resolver, args };
      });
    },
    request(uri): Promise<any> {
      const stringifedUri = JSON.stringify(uri);
      const uuid = uuidv4();
 
      emit('request', {
        stringifedUri,
        uuid
      });
 
      return new Promise((res, rej): void => {
        listeners[uuid] = { res, rej };
      }).catch((err) => {
        let error = err;
        if (typeof err === 'string') {
          try {
            error = JSON.parse(err);
          } catch (_) {
            // noop
          }
        }
        throw error;
      });
    },
    pushFile(fullPath, content): Promise<void> {
      const url = new URL(fullPath);
      const uri = { raw: false, url };
      const stringifedUri = JSON.stringify(uri);
 
      const arrayBuffer = new TextEncoder().encode(content);
      const uint8Array = new Uint8Array(arrayBuffer);
 
      const uuid = uuidv4();
 
      emit('push-file', {
        stringifedUri,
        uuid,
        value: uint8Array
      });
 
      return new Promise((res, rej): void => {
        listeners[uuid] = { res, rej };
      });
    }
  };
};
 
//Событие обновления настроек кидаем только если запущены в vscode о чем нам говорит наличие моста плагина
if (vsCodeHost()) {
  papiSettingUpdated();
}