All files / frontend/helpers env.ts

97.94% Statements 143/146
99.47% Branches 191/192
97.01% Functions 65/67
99.3% Lines 143/144

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 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416                                                                                                        140x 140x   140x 140x 140x 140x                                                               652x 652x   652x   153x     98x     401x         4x 1x 3x 1x 2x 2x             365x       2x       1x         5x 5x         9x     213x 213x 213x     32x     6x     10x     3x     2x     23x     32x     6x   6x 4x 3x   2x 1x     3x     22x   22x 12x     10x 9x     1x     189x     3x     6x       13x       71x     1x     10x 1x 9x 4x 5x     4x       8x     9x     6x     7x     7x     6x       3x       33x 33x 5x 28x 1x   33x 5x     28x 2x 26x       2x       2x     6x 3x 3x   3x     6x 3x   3x       23x 22x 6x 16x 4x       13x   13x 12x   1x     2x     10x 10x 10x 3x 7x 5x 5x 3x   3x 3x 2x   10x 10x 10x     3x     3x     3x     3x     2x     2x     2x     4x 4x       23x     23x     15x     4x 2x   2x     12x     12x     2x     3x         9x     33x         9x 5x   4x     3x     295x     8x 7x   1x     3x       3x 3x     6x     6x      
/*
  Copyright (C) 2021 owner Roman Piontik R.Piontik@mail.ru
 
  Copyright (C) 2022 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
 
  In any derivative products, you must retain the information of
  owner of the original code and provide clear attribution to the project
 
  https://dochub.info
 
  The use of this product or its derivatives for any purpose cannot be a secret.
 
 
  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.
 
  Maintainers:
      R.Piontik <r.piontik@mail.ru>
 
  Contributors:
      R.Piontik <r.piontik@mail.ru> - 2023
*/
 
import consts from '@front/consts';
import {getLoggerWithTag} from '@global/logger/v2/logger.mjs';
import {toNumerOrDefault} from '@global/helpers/numberUtils.mjs';
import { stringToBooleanOrDefault } from '@global/helpers/booleanUtils.mjs';
import {ideEnv, vsCodeHost} from '@ide/vscode/host';
 
export type TCacheMethods = 'GET' | 'HEAD';
export type TEnvValue = string | undefined;
export type TProcessEnvValues = { [key: string | symbol]: TEnvValue };
 
export enum Plugins {
  idea = 'idea',
  vscode = 'vscode'
}
 
export enum CACHE_LEVEL {
  low = 1,
  high = 2
}
 
const ENV_ERROR_TAG = '[env.dochub]';
const logger = getLoggerWithTag(ENV_ERROR_TAG);
 
const DEF_METAMODEL_URI_PORTAL = '/metamodel/root.yaml';
const DEF_METAMODEL_URI_IDEA = 'plugin:/idea/metamodel/root.yaml';
const DEFAULT_PROJECT_TITLE = 'SEAF';
const DEFAULT_SUPPORT_CHANNELS = [
  {
    icon: 'mdi-account-group',
    name: 'Для сотрудников ДЗО и ПАО (при наличии доступа)',
    desc: 'Страница в SberWorks',
    link: 'https://sberworks.ru/wiki/pages/viewpage.action?pageId=1195934204'
  },
  {
    icon: 'mdi-chat',
    name: 'Для сотрудников ПАО и ДЗО (при наличии доступа)',
    desc: 'Группа в СберЧат',
    link: 'https://sberchat.sberbank.ru/@seaf'
  },
  {
    icon: 'mdi-bank',
    name: 'Для сотрудников ПАО',
    desc: 'Страница в Друге',
    link: 'https://sberfriend.sberbank.ru/sberfriend/#/application/7C76A51BFEF149999F2F1C4CDFC5FD8'
  },
  {
    icon: 'mdi-earth',
    name: 'Для всех категорий пользователей',
    desc: 'Задачи в GitVerse',
    link: 'https://gitverse.ru/seafteam/seaf-archtool-core/tasktracker?view=list'
  }
];
 
let configFromBack;
 
export default {
  dochub: <TProcessEnvValues>{},
  isPlugin(plugin?: Plugins): boolean {
    const isIdea = !!window.DocHubIDEACodeExt;
    const isVsCode = !!vsCodeHost();
 
    switch (plugin) {
      case Plugins.idea: {
        return isIdea;
      }
      case Plugins.vscode: {
        return isVsCode;
      }
      default: {
        return isIdea || isVsCode;
      }
    }
  },
  get pluginName(): Plugins | undefined {
    if (!this.isPlugin()) {
      return undefined;
    } else if (this.isPlugin(Plugins.idea)) {
      return Plugins.idea;
    } else if (this.isPlugin(Plugins.vscode)) {
      return Plugins.vscode;
    } else E{
      return undefined;
    }
  },
  // Адрес backend сервере
  get backendURL(): string {
    return this.dochub?.VUE_APP_DOCHUB_BACKEND_URL || (window?.origin && (window?.origin !== 'null') ? window?.origin : 'http://localhost:3030/');
  },
  // Адрес API доступа к файлам backend сервера
  get backendFileStorageURL(): string {
    return (new URL('/seaf-core/api/core/storage/', this.backendURL)).toString();
  },
  // Каталог внешних документных плагинов в статической поставке портала.
  get pluginsCatalogUrl(): string {
    return '/plugins/catalog.json';
  },
  // Режим SmartAnts берётся из backend (env-config передаёт его всегда, без переменной - front);
  // значение сборки - только если env-config не получен или backend старый
  get smartantsMode() {
    const mode = configFromBack?.smartantsMode || process.env.VUE_APP_DOCHUB_SMART_ANTS_MODE;
    return (this.isBackendMode && mode) ? mode.toLowerCase() : 'front';
  },
  // Плагин считает SmartAnts сам ($PAPI.computeSmartAnts: JetBrains - в процессе IDE, VS Code - JVM-сервисом)
  // и объявляет это в настройках; сборка для плагинов не содержит smartants.js, старый плагин получает ошибку
  get isSmartantsInPlugin(): boolean {
    return this.isPlugin() && !!this.ideSettings?.smartants;
  },
  get isBackendMode() {
    const backendUrl = process.env.VUE_APP_DOCHUB_BACKEND_URL;
    const mode = (process.env.VUE_APP_DOCHUB_MODE || '').toLowerCase().trim();
    return !this.isPlugin() && (backendUrl || (mode === 'backend'));
  },
  get isEnvelopedRequests(): boolean {
    return process.env.VUE_APP_SEAF_ENVELOPED_REQUESTS === 'true';
  },
  get isRolesMode(): boolean {
    return (configFromBack?.roleModeEnabled || process.env.VUE_APP_DOCHUB_ROLES_MODEL || 'N').toUpperCase() === 'Y';
  },
  get hasOidcAuthority(): boolean {
    return Boolean(this.authorityServer && this.authorityClientId);
  },
  get showOidcLogin(): boolean {
    return this.isBackendMode && this.hasOidcAuthority && this.isRolesMode;
  },
  get isProduction(): boolean {
    return this.dochub.NODE_ENV === 'production';
  },
  get isTraceJSONata(): boolean {
    return (this.dochub.VUE_APP_DOCHUB_JSONATA_ANALYZER || this.additionalIdeEnv?.VUE_APP_DOCHUB_JSONATA_ANALYZER || 'N').toUpperCase() === 'Y';
  },
  get isPerfLoggerEnabled(): boolean {
    return !this.isBackendMode && process?.env?.VUE_APP_DOCHUB_PERF_LOGGER_ENABLE === 'on';
  },
  cacheWithPriority(priority: CACHE_LEVEL): boolean {
    const systemSetting = +this.dochub.VUE_APP_DOCHUB_CACHE_LEVEL;
 
    if (systemSetting in CACHE_LEVEL) {
      if (this.cache) {
        return systemSetting === priority;
      }
    } else if (systemSetting) {
      logger.error(() => `Неправильно указан параметр "VUE_APP_DOCHUB_CACHE_LEVEL=${systemSetting}" в env!`);
    }
 
    return false;
  },
  get cache(): TCacheMethods | null {
    const currentMethod = (this.dochub.VUE_APP_DOCHUB_CACHE || 'NONE').toUpperCase();
 
    if (currentMethod === 'NONE') {
      return null;
    }
 
    if (['GET', 'HEAD'].includes(currentMethod)) {
      return currentMethod as TCacheMethods;
    }
 
    throw new Error(`Неправильно указан параметр "VUE_APP_DOCHUB_CACHE=${currentMethod}" в env!`);
  },
  get ideSettings() {
    return (window.DocHubIDEACodeExt || vsCodeHost())?.settings;
  },
  get logLevel() {
    return this.ideSettings?.logLevel;
  },
  get isJsonataLogFuncEnable() {
    return this.ideSettings?.isJsonataLogFuncEnable
      ?? (this.dochub.VUE_APP_DOCHUB_JSONATA_LOG_FUNC_ENABLE?.toLowerCase() !== 'off');
  },
  get mcpServerEnabled(): boolean {
    return this.ideSettings?.mcpServerEnabled === true;
  },
  // Приходят из настройки env в ide в настройках плагина
  get additionalIdeEnv() {
    return window.additionalIdeEnv;
  },
  get rootDocument(): TEnvValue {
    return this.dochub.VUE_APP_DOCHUB_ROOT_DOCUMENT;
  },
  get rootManifest(): TEnvValue {
    if (this.isPlugin(Plugins.idea)) {
      return consts.plugin.ROOT_MANIFEST;
    } else if (this.isPlugin(Plugins.vscode)) {
      return vsCodeHost()?.rootManifest;
    } else return this.dochub.VUE_APP_DOCHUB_ROOT_MANIFEST;
  },
  get renderCore(): TEnvValue {
    return this.ideSettings?.render?.mode || this.dochub.VUE_APP_DOCHUB_RENDER_CORE || 'graphviz';
  },
  // Переменные систем управления версиями
  get gitlabUrl(): TEnvValue {
    return ideEnv(this.ideSettings?.env, 'GITLAB_URL') || this.dochub.VUE_APP_DOCHUB_GITLAB_URL;
  },
  get bitbucketUrl(): TEnvValue {
    return ideEnv(this.ideSettings?.env, 'BITBUCKET_URL') || this.dochub.VUE_APP_DOCHUB_BITBUCKET_URL;
  },
  get personalToken(): TEnvValue {
    return ideEnv(this.ideSettings?.env, 'PERSONAL_TOKEN') || this.dochub.VUE_APP_DOCHUB_PERSONAL_TOKEN;
  },
  get bitbucketMode(): TEnvValue {
    return ideEnv(this.ideSettings?.env, 'BITBUCKET_MODE') || this.dochub.VUE_APP_DOCHUB_BITBUCKET_MODE;
  },
  get gitlabMode(): TEnvValue {
    return ideEnv(this.ideSettings?.env, 'GITLAB_MODE') || this.dochub.VUE_APP_DOCHUB_GITLAB_MODE || 'api';
  },
  get gitlabAdapterUrl(): TEnvValue {
    return ideEnv(this.ideSettings?.env, 'GITLAB_ADAPTER_URL') || this.dochub.VUE_APP_DOCHUB_GITLAB_ADAPTER_URL;
  },
  //
  get appendDocHubDocs(): TEnvValue {
    return this.dochub.VUE_APP_DOCHUB_APPEND_DOCHUB_DOCS;
  },
  // Определяет сервер рендеринга
  get plantUmlServer(): TEnvValue {
    let envValue = configFromBack?.plantUmlServer || this.dochub.VUE_APP_PLANTUML_SERVER;
    if (!envValue) {
      envValue = consts.plantuml.DEFAULT_SERVER;
    } else if (envValue === 'ORIGIN') {
      envValue = consts.plantuml.ORIGIN;
    }
    if (this.isPlugin(Plugins.idea)) {
      return this.ideSettings?.isEnterprise ? envValue : (
        this.ideSettings?.render?.external ? this.ideSettings?.render?.server : null
      );
    } else if (this.isPlugin(Plugins.vscode)) {
      return this.ideSettings?.render.server;
    } else return envValue;
  },
  // Адрес статики редактора drawio: значение бэкенда приоритетнее значения сборки
  get drawioServerUri(): TEnvValue {
    return configFromBack?.drawioServerUri || process.env.VUE_APP_DOCHUB_PLUGIN_DRAWIO_SERVER_URI;
  },
  // Глобальные query-параметры iframe drawio
  get drawioUrlParams(): TEnvValue {
    return configFromBack?.drawioUrlParams || process.env.VUE_APP_DOCHUB_PLUGIN_DRAWIO_URL_PARAMS;
  },
  get s3CloudUrl(): string {
    if (this.isPlugin(Plugins.idea)) {
      const url = this.ideSettings?.s3CloudUrl ?? '';
      return `${url}`;
    }
    return configFromBack?.s3CloudUrl || process.env.VUE_APP_DOCHUB_S3_CLOUD_URL || '';
  },
  get usingS3Mode(): boolean {
    if (this.isPlugin(Plugins.idea)) {
      return this.ideSettings?.usingS3Mode ?? false;
    }
    return (configFromBack?.usingS3Mode || process.env.VUE_APP_DOCHUB_USING_S3 || 'N').toUpperCase() === 'Y';
  },
  // Определяет тип запроса к серверу рендеринга
  get plantUmlRequestType(): TEnvValue {
    if (!this.ideSettings?.isEnterprise) {
      if (this.isPlugin(Plugins.idea)) {
        return this.ideSettings?.render?.external ? this.ideSettings?.render?.request_type || 'get' : 'plugin';
      } else if (this.isPlugin(Plugins.vscode)) {
        return this.ideSettings?.render?.request_type || 'get';
      }
    }
 
    const requestType = (configFromBack?.plantUmlRequestType || this.dochub.VUE_APP_PLANTUML_REQUEST_TYPE)?.toLowerCase() || 'get';
 
    if (['get', 'post', 'post_compressed'].includes(requestType)) {
      return requestType as TCacheMethods;
    }
    throw new Error(`Неправильно указан параметр "VUE_APP_PLANTUML_REQUEST_TYPE=${requestType}" в env!`);
  },
  get isAppendDocHubDocs(): boolean {
    return (this.appendDocHubDocs || 'y').toLowerCase() === 'y';
  },
  get uriMetamodel(): string {
    let result = this.dochub.VUE_APP_DOCHUB_METAMODEL || DEF_METAMODEL_URI_PORTAL;
    let host = window.location.toString();
    if (this.isPlugin(Plugins.idea)) {
      result = this.ideSettings?.isEnterprise ? result : DEF_METAMODEL_URI_IDEA;
    } else if (this.isPlugin(Plugins.vscode)) {
      const metamodelUri = vsCodeHost()?.metamodelUri;
      if (!this.ideSettings?.isEnterprise && metamodelUri) {
        const {scheme, path, authority} = metamodelUri;
 
        result = `${path}`;
        host = `${scheme}://${authority}`;
      } else host = this.ideSettings?.enterpriseServer;
    }
    result = (new URL(result, host)).toString();
    logger.info(() => `Source of metamodel is ${result}`);
    return result;
  },
  get gigachatCredential(): string {
    return this.ideSettings?.gigachatCredential || this.dochub.VUE_APP_GIGACHAT_CREDENTIAL || '';
  },
  get gigachatScope(): string {
    return this.ideSettings?.gigachatScope || this.dochub.VUE_APP_GIGACHAT_SCOPE || '';
  },
  get gigachatDefaultModel(): string {
    return this.ideSettings?.gigachatDefaultModel || this.dochub.VUE_APP_GIGACHAT_DEFAULT_MODEL || null;
  },
  get gigachatTimeout(): number {
    return this.ideSettings?.gigachatTimeout || parseInt(this.dochub.VUE_APP_GIGACHAT_TIMEOUT) || null;
  },
  get gigachatMaxMsgInHistory(): number {
    return toNumerOrDefault(process.env.VUE_APP_DOCHUB_GIGACHAT_MAX_MESSAGE_COUNT_IN_HISTORY, Number.MAX_SAFE_INTEGER);
  },
  get gigachatMaxSumSymbolOfAllMsg(): number {
    return toNumerOrDefault(process.env.VUE_APP_DOCHUB_GIGACHAT_MAX_SUM_SYMBOL_OF_ALL_MESSAGES, Number.MAX_SAFE_INTEGER);
  },
  get gigachatSessionTtl(): number {
    return toNumerOrDefault(process.env.VUE_APP_DOCHUB_GIGACHAT_SESSION_TTL_MS, 900000);
  },
  get gigachatTokenCounterIsShown(): boolean {
    const envar = this.additionalIdeEnv?.VUE_APP_DOCHUB_LLM_COUNTER || process.env?.VUE_APP_DOCHUB_LLM_COUNTER;
    return stringToBooleanOrDefault(envar, false);
  },
 
  get clickstreamReportUrl(): string {
    return this.additionalIdeEnv?.VUE_APP_CLICKSTREAM_REPORT_URL || process.env.VUE_APP_CLICKSTREAM_REPORT_URL;
  },
  get clickstreamApiKey(): string {
    return this.additionalIdeEnv?.VUE_APP_CLICKSTREAM_API_KEY || process.env.VUE_APP_CLICKSTREAM_API_KEY;
  },
  get pluginVersion(): string | null {
    return this.ideSettings?.pluginVersion;
  },
  get pluginMode(): string | null {
    if (!this.isPlugin() || !this.ideSettings) {
      return undefined;
    }
    return this.ideSettings.isEnterprise ? 'enterprise' : 'personal';
  },
  get authorityServer(): string | null {
    return configFromBack?.authorityServer || process.env.VUE_APP_DOCHUB_AUTHORITY_SERVER;
  },
  get authorityClientId(): string | null {
    return configFromBack?.authorityClientId || process.env.VUE_APP_DOCHUB_AUTHORITY_CLIENT_ID;
  },
  get authorityScope(): string | null {
    return configFromBack?.authorityScope || process.env.VUE_APP_DOCHUB_AUTHORITY_SCOPE;
  },
  get authorityResponseMode(): string {
    return configFromBack?.authorityResponseMode
      || process.env.VUE_APP_DOCHUB_AUTHORITY_RESPONSE_MODE
      || 'fragment';
  },
  get orgSwitcherFirstAlias(): string | undefined {
    return configFromBack?.orgSwitcherFirstAlias;
  },
  get archChooserEnabled(): boolean {
    return configFromBack?.archChooser || false;
  },
  // Новогоднее оформление. Портал: из конфигурации бэкенда (env пода, без пересборки).
  // Плагины и фронт без бэкенда: из переменной, заданной при сборке.
  get newYearDecorEnabled(): boolean {
    if (configFromBack) {
      return configFromBack.newYearDecor === true;
    }
    return stringToBooleanOrDefault(process.env.VUE_APP_SEAF_NEW_YEAR_DECOR, false);
  },
  get backendEnv() {
    return configFromBack;
  },
  setBackendEnv(backendEnv: Record<string, unknown>) {
    configFromBack = backendEnv;
  },
  get isCacheMode(): boolean {
    if (this.isPlugin()) {
      return this.ideSettings?.isCacheMode;
    }
    return false;
  },
  get projectTitle(): string {
    return configFromBack?.projectTitle
      ?? (typeof process?.env?.VUE_APP_DOCHUB_TITLE === 'string' ? process.env.VUE_APP_DOCHUB_TITLE : DEFAULT_PROJECT_TITLE);
  },
  get showSupportButton(): boolean {
    const envar = process.env.VUE_APP_DOCHUB_SHOW_SUPPORT_BUTTON;
    return configFromBack?.showSupportButton ?? (stringToBooleanOrDefault(envar, false));
  },
  get supportChannels(): Array<{name: string, link: string, icon?: string, desc?: string}> {
    const channels = this.isPlugin()
      ? this.ideSettings?.supportChannels
      : configFromBack?.supportChannels;
    return channels?.length ? channels : DEFAULT_SUPPORT_CHANNELS;
  }
 };