All files / frontend/helpers/fileloader2 fileDownload.ts

100% Statements 25/25
90% Branches 9/10
100% Functions 4/4
100% Lines 23/23

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                                        3x     3x               20x 3x     17x   17x 12x 12x   3x         8x 8x   4x 4x     4x               7x 7x 1x     6x 6x 6x 6x 6x 6x    
/*
  Copyright (C) 2026 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 { getLoggerWithTag } from '@global/logger/v2/logger.mjs';
import { toFileloaderClientError } from './fileloader2.client';
import type { DownloadedFile } from './fileloader2.types';
 
const logger = getLoggerWithTag('f/h/fileloader2/fileDownload');
 
// Firefox отменяет скачивание, если отозвать blob-адрес сразу после click()
const REVOKE_DELAY_MS = 1000;
 
/**
 * Имя файла из заголовка Content-Disposition: сначала filename* (RFC 5987), затем filename
 * @param contentDisposition - значение заголовка
 * @returns имя файла или null, если его нет в заголовке
 */
export function parseFilename(contentDisposition: string | null | undefined): string | null {
  if (!contentDisposition) {
    return null;
  }
 
  const encodedFilenameMatch = /filename\*\s*=\s*UTF-8''([^;\s\r\n]+)/i.exec(contentDisposition);
 
  if (encodedFilenameMatch) {
    try {
      return decodeURIComponent(encodedFilenameMatch[1]);
    } catch (error) {
      logger.error(() => `Не удалось декодировать filename* из Content-Disposition: ${contentDisposition}`, error);
    }
  }
  // Параметр filename= (filename*= не подходит: после имени идёт '*'), значение в кавычках или без них.
  // Захватывается до кавычки, ';' или перевода строки
  const plainFilenameMatch = /filename\s*=\s*"?([^";\r\n]+)"?/i.exec(contentDisposition);
  if (plainFilenameMatch) {
    // filename без кодирования: fileloader2 кладёт сюда ASCII-имя, остальные символы заменены на _
    const plainFilename = plainFilenameMatch[1].trim();
    return plainFilename || null;
  }
 
  return null;
}
 
/**
 * Сохраняет скачанный файл в браузере. Имя берётся только из Content-Disposition
 * @param download - заголовки ответа (ключи в нижнем регистре) и тело файла
 */
export function saveDownloadedFile({ headers, blob }: DownloadedFile): void {
  const fileName = parseFilename(headers?.['content-disposition']);
  if (!fileName) {
    throw toFileloaderClientError('Сервис не вернул имя файла');
  }
 
  const href = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = href;
  link.download = fileName;
  link.click();
  setTimeout(() => URL.revokeObjectURL(href), REVOKE_DELAY_MS);
}