"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.IccDocumentXApi = void 0;
const icc_api_1 = require("../icc-api");
const XHR_1 = require("../icc-api/api/XHR");
const models = require("../icc-api/model/models");
const binary_utils_1 = require("./utils/binary-utils");
const AuthenticationProvider_1 = require("./auth/AuthenticationProvider");
const SecureDelegation_1 = require("../icc-api/model/SecureDelegation");
const utils_1 = require("./utils");
var AccessLevelEnum = SecureDelegation_1.SecureDelegation.AccessLevelEnum;
const SecretIdUseOption_1 = require("./crypto/SecretIdUseOption");
const compression_utils_1 = require("./utils/compression-utils");
// noinspection JSUnusedGlobalSymbols
class IccDocumentXApi extends icc_api_1.IccDocumentApi {
    constructor(host, headers, crypto, authApi, dataOwnerApi, autofillAuthor, authenticationProvider = new AuthenticationProvider_1.NoAuthenticationProvider(), encryptedKeys = [], fetchImpl = typeof window !== 'undefined'
        ? window.fetch
        : typeof self !== 'undefined'
            ? self.fetch
            : fetch) {
        super(host, headers, authenticationProvider, fetchImpl);
        this.crypto = crypto;
        this.authApi = authApi;
        this.autofillAuthor = autofillAuthor;
        /** maps invalid UTI values to corresponding MIME type for backward-compatibility (pre-v1.0.117) */
        this.compatUtiRevDefs = {
            'com.adobe.encapsulatedPostscript': 'image/eps',
            'com.adobe.illustrator.aiImage': 'application/illustrator',
            'com.adobe.indesignImage': 'image/indesign',
            'com.adobe.photoshopImage': 'image/psd',
            'com.adobe.postscriptPfaFont': 'application/x-font-type1',
            'com.adobe.postscriptPfbFont': 'application/x-font-type1',
            'com.allume.stuffitArchive': 'application/stuffit',
            'com.apple.binhexArchive': 'application/binhex',
            'com.apple.diskImageUdif': 'application/x-apple-diskimage',
            'com.apple.macbinaryArchive': 'application/macbinary',
            'com.apple.quartzComposerComposition': 'application/x-quartzcomposer',
            'com.apple.quicktimeImage': 'image/x-quicktime',
            'com.apple.quicktimeMovie': 'video/quicktime',
            'com.js.efxFax': 'image/efax',
            'com.macromedia.shockwaveFlash': 'application/x-shockwave-flash',
            'com.microsoft.advancedStreamRedirector': 'video/x-ms-asx',
            'com.microsoft.advancedSystemsFormat': 'video/x-ms-asf',
            'com.microsoft.waveformAudio': 'audio/wave',
            'com.microsoft.windowsDynamicLinkLibrary': 'application/x-msdownload',
            'com.microsoft.windowsExecutable': 'application/exe',
            'com.microsoft.windowsMediaWax': 'audio/x-ms-wax',
            'com.microsoft.windowsMediaWm': 'video/x-ms-wm',
            'com.microsoft.windowsMediaWma': 'audio/x-ms-wma',
            'com.microsoft.windowsMediaWmd': 'video/x-ms-wmd',
            'com.microsoft.windowsMediaWmp': 'video/x-ms-wmp',
            'com.microsoft.windowsMediaWmv': 'video/x-ms-wmv',
            'com.microsoft.windowsMediaWmx': 'video/x-ms-wmx',
            'com.microsoft.windowsMediaWmz': 'video/x-ms-wmz',
            'com.microsoft.windowsMediaWvx': 'video/x-ms-wvx',
            'com.netscape.javascriptSource': 'text/javascript',
            'com.pkware.zipArchive': 'application/zip',
            'com.rarlab.rarArchive': 'application/rar',
            'com.redhat.redhatPackage': 'application/x-redhat-package',
            'com.sgi.sgiImage': 'image/sgi',
            'com.sun.javaAppDescriptor': 'text/vnd.sun.j2me.app-descriptor',
            'com.sun.javaArchive': 'application/java-archive',
            'com.sun.javaClass': 'application/java',
            'com.sun.javaSource': 'text/x-java-source',
            'com.sun.javaWebStart': 'application/jnlp',
            'com.truevision.tgaImage': 'image/tga',
            'org.bzip.bzip2Archive': 'application/x-bzip2',
            'org.debian.debianPackage': 'application/x-debian-package',
            'org.gnu.gnuTarArchive': 'application/x-gtar',
            'org.gnu.gnuZipArchive': 'application/gzip',
            'org.oasis.opendocument.textMaster': 'application/vnd.oasis.opendocument.text-master',
            'org.oasis.opendocument.textWeb': 'application/vnd.oasis.opendocument.text-web',
            'org.xiph.oggTheora': 'video/ogg',
            'org.xiph.oggVorbis': 'audio/ogg',
            'public.aifcAudio': 'audio/aiff',
            'public.aiffAudio': 'audio/aiff',
            'public.assemblySource': 'text/x-asm',
            'public.cHeader': 'text/x-c-header',
            'public.cpioArchive': 'application/x-cpio',
            'public.cPlusPlusHeader': 'text/x-c++-hdr',
            'public.cPlusPlusSource': 'application/x-cplusplus',
            'public.cshScript': 'application/x-csh',
            'public.cSource': 'text/x-c-code',
            'public.isoImage': 'application/x-iso-image',
            'public.mpeg4Audio': 'audio/mp4',
            'public.objectiveCPlusPlusSource': 'text/x-objcppsrc',
            'public.objectiveCSource': 'text/x-objcsrc',
            'public.opentypeFont': 'font/opentype',
            'public.perlScript': 'text/x-perl',
            'public.phpScript': 'text/php',
            'public.plainText': 'text/plain',
            'public.pythonScript': 'text/x-python-script',
            'public.shellScript': 'application/x-sh',
            'public.tarArchive': 'application/tar',
            'public.truetypeTtfFont': 'application/x-font-ttf',
            'public.ulawAudio': 'audio/au',
            'public.xbitmapImage': 'image/xbm',
            'unofficial.atomFeed': 'application/atom+xml',
            'unofficial.m3u8Playlist': 'application/x-mpegURL',
            'unofficial.plsPlaylist': 'audio/scpls',
            'unofficial.rdfFeed': 'application/rdf+xml',
            'unofficial.rssFeed': 'application/rss+xml',
        };
        this.utiRevDefs = Object.assign(Object.assign({}, this.compatUtiRevDefs), { 'com.adobe.encapsulated-postscript': 'image/eps', 'com.adobe.illustrator.ai-image': 'application/illustrator', 'com.adobe.indesign-image': 'image/indesign', 'com.adobe.pdf': 'application/pdf', 'com.adobe.photoshop-image': 'image/psd', 'com.adobe.postscript': 'application/postscript', 'com.adobe.postscript-pfa-font': 'application/x-font-type1', 'com.adobe.postscript-pfb-font': 'application/x-font-type1', 'com.allume.stuffit-archive': 'application/stuffit', 'com.apple.applescript.script': 'application/x-applescript', 'com.apple.applescript.text': 'application/x-applescript', 'com.apple.binhex-archive': 'application/binhex', 'com.apple.disk-image-udif': 'application/x-apple-diskimage', 'com.apple.ical.ics': 'text/calendar', 'com.apple.ical.vcs': 'text/x-vcalendar', 'com.apple.macbinary-archive': 'application/macbinary', 'com.apple.pict': 'image/pict', 'com.apple.quartz-composer-composition': 'application/x-quartzcomposer', 'com.apple.quicktime-image': 'image/x-quicktime', 'com.apple.quicktime-movie': 'video/quicktime', 'com.bittorrent.torrent': 'application/x-bittorrent', 'com.compuserve.gif': 'image/gif', 'com.js.efx-fax': 'image/efax', 'com.kodak.flashpix.image': 'image/vndfpx', 'com.lizardtech.djvu': 'image/vnd.djvu', 'com.macromedia.shockwave-flash': 'application/x-shockwave-flash', 'com.microsoft.advanced-stream-redirector': 'video/x-ms-asx', 'com.microsoft.advanced-systems-format': 'video/x-ms-asf', 'com.microsoft.bmp': 'image/bmp', 'com.microsoft.excel.xls': 'application/excel', 'com.microsoft.ico': 'image/x-icon', 'com.microsoft.powerpoint.ppt': 'application/powerpoint', 'com.microsoft.waveform-audio': 'audio/wave', 'com.microsoft.windows-dynamic-link-library': 'application/x-msdownload', 'com.microsoft.windows-executable': 'application/exe', 'com.microsoft.windows-media-wax': 'audio/x-ms-wax', 'com.microsoft.windows-media-wm': 'video/x-ms-wm', 'com.microsoft.windows-media-wma': 'audio/x-ms-wma', 'com.microsoft.windows-media-wmd': 'video/x-ms-wmd', 'com.microsoft.windows-media-wmp': 'video/x-ms-wmp', 'com.microsoft.windows-media-wmv': 'video/x-ms-wmv', 'com.microsoft.windows-media-wmx': 'video/x-ms-wmx', 'com.microsoft.windows-media-wmz': 'video/x-ms-wmz', 'com.microsoft.windows-media-wvx': 'video/x-ms-wvx', 'com.microsoft.word.doc': 'application/msword', 'com.netscape.javascript-source': 'text/javascript', 'com.pkware.zip-archive': 'application/zip', 'com.rarlab.rar-archive': 'application/rar', 'com.real.realaudio': 'audio/vnd.rn-realaudio', 'com.real.realmedia': 'application/vnd.rn-realmedia', 'com.real.smil': 'application/smil', 'com.redhat.redhat-package': 'application/x-redhat-package', 'com.sgi.sgi-image': 'image/sgi', 'com.soundblaster.soundfont': 'application/x-soundfont', 'com.sun.java-app-descriptor': 'text/vnd.sun.j2me.app-descriptor', 'com.sun.java-archive': 'application/java-archive', 'com.sun.java-class': 'application/java', 'com.sun.java-source': 'text/x-java-source', 'com.sun.java-web-start': 'application/jnlp', 'com.truevision.tga-image': 'image/tga', 'org.bzip.bzip2-archive': 'application/x-bzip2', 'org.debian.debian-package': 'application/x-debian-package', 'org.gnu.gnu-tar-archive': 'application/x-gtar', 'org.gnu.gnu-zip-archive': 'application/gzip', 'org.neooffice.calc': 'application/vnd.sun.xml.calc', 'org.neooffice.draw': 'application/vnd.sun.xml.draw', 'org.neooffice.global': 'application/vnd.sun.xml.writer.global', 'org.neooffice.impress': 'application/vnd.sun.xml.impress', 'org.neooffice.math': 'application/vnd.sun.xml.math', 'org.neooffice.writer': 'application/vnd.sun.xml.writer', 'org.oasis.opendocument.chart': 'application/vnd.oasis.opendocument.chart', 'org.oasis.opendocument.database': 'application/vnd.oasis.opendocument.database', 'org.oasis.opendocument.formula': 'application/vnd.oasis.opendocument.formula', 'org.oasis.opendocument.graphics': 'application/vnd.oasis.opendocument.graphics', 'org.oasis.opendocument.image': 'application/vnd.oasis.opendocument.image', 'org.oasis.opendocument.presentation': 'application/vnd.oasis.opendocument.presentation', 'org.oasis.opendocument.spreadsheet': 'application/vnd.oasis.opendocument.spreadsheet', 'org.oasis.opendocument.text': 'application/vnd.oasis.opendocument.text', 'org.oasis.opendocument.text-master': 'application/vnd.oasis.opendocument.text-master', 'org.oasis.opendocument.text-web': 'application/vnd.oasis.opendocument.text-web', 'org.tug.tex': 'text/tex', 'org.xiph.flac': 'audio/flac', 'org.xiph.ogg-theora': 'video/ogg', 'org.xiph.ogg-vorbis': 'audio/ogg', 'public.3gpp': 'video/3gpp', 'public.3gpp2': 'video/3gpp2', 'public.aifc-audio': 'audio/aiff', 'public.aiff-audio': 'audio/aiff', 'public.assembly-source': 'text/x-asm', 'public.avi': 'video/avi', 'public.c-header': 'text/x-c-header', 'public.cpio-archive': 'application/x-cpio', 'public.c-plus-plus-header': 'text/x-c++-hdr', 'public.c-plus-plus-source': 'application/x-cplusplus', 'public.csh-script': 'application/x-csh', 'public.c-source': 'text/x-c-code', 'public.css': 'text/css', 'public.dv': 'video/x-dv', 'public.flv': 'video/x-flv', 'public.html': 'text/html', 'public.iso-image': 'application/x-iso-image', 'public.jpeg': 'image/jpeg', 'public.jpeg2000': 'image/jp2', 'public.midi': 'audio/midi', 'public.mka': 'audio/x-matroska', 'public.mkv': 'video/x-matroska', 'public.mp3': 'audio/mp3', 'public.mpeg': 'video/mpeg', 'public.mpeg4': 'video/mp4', 'public.mpeg4-audio': 'audio/mp4', 'public.mpegts': 'video/MP2T', 'public.objective-c-plus-plus-source': 'text/x-objcppsrc', 'public.objective-c-source': 'text/x-objcsrc', 'public.opentype-font': 'font/opentype', 'public.perl-script': 'text/x-perl', 'public.php-script': 'text/php', 'public.plain-text': 'text/plain', 'public.png': 'image/png', 'public.python-script': 'text/x-python-script', 'public.rtf': 'text/rtf', 'public.shell-script': 'application/x-sh', 'public.tar-archive': 'application/tar', 'public.tiff': 'image/tiff', 'public.truetype-ttf-font': 'application/x-font-ttf', 'public.ulaw-audio': 'audio/au', 'public.vcard': 'text/vcard', 'public.webm': 'video/webm', 'public.xbitmap-image': 'image/xbm', 'public.xml': 'text/xml', 'unofficial.atom-feed': 'application/atom+xml', 'unofficial.m3u8-playlist': 'application/x-mpegURL', 'unofficial.opml': 'text/x-opml', 'unofficial.pls-playlist': 'audio/scpls', 'unofficial.rdf-feed': 'application/rdf+xml', 'unofficial.rss-feed': 'application/rss+xml' });
        this.utiExts = {
            jpg: 'public.jpeg',
            jpeg: 'public.jpeg',
            png: 'public.png',
            rtf: 'public.rtf',
            mpeg: 'public.mpeg',
            mpg: 'public.mpeg',
            html: 'public.html',
            htm: 'public.html',
            pdf: 'com.adobe.pdf',
            xls: 'com.microsoft.excel.xls',
            xlsx: 'com.microsoft.excel.xls',
            doc: 'com.microsoft.word.doc',
            docx: 'com.microsoft.word.doc',
        };
        this.utiDefs = {
            'application/atom+xml': 'unofficial.atom-feed',
            'application/bat': 'com.microsoft.windows-executable',
            'application/binhex': 'com.apple.binhex-archive',
            'application/binhex4': 'com.apple.binhex-archive',
            'application/ecmascript': 'com.netscape.javascript-source',
            'application/eps': 'com.adobe.encapsulated-postscript',
            'application/excel': 'com.microsoft.excel.xls',
            'application/exe': 'com.microsoft.windows-executable',
            'application/gnutar': 'public.tar-archive',
            'application/gzip': 'org.gnu.gnu-zip-archive',
            'application/illustrator': 'com.adobe.illustrator.ai-image',
            'application/indesign': 'com.adobe.indesign-image',
            'application/java-archive': 'com.sun.java-archive',
            'application/java-byte-code': 'com.sun.java-class',
            'application/java': 'com.sun.java-class',
            'application/javascript': 'com.netscape.javascript-source',
            'application/jnlp': 'com.sun.java-web-start',
            'application/latex': 'org.tug.tex',
            'application/mac-binary': 'com.apple.macbinary-archive',
            'application/mac-binhex': 'com.apple.binhex-archive',
            'application/mac-binhex40': 'com.apple.binhex-archive',
            'application/macbinary': 'com.apple.macbinary-archive',
            'application/mspowerpoint': 'com.microsoft.powerpoint.ppt',
            'application/msword': 'com.microsoft.word.doc',
            'application/octet-stream': 'com.microsoft.windows-executable',
            'application/pdf': 'com.adobe.pdf',
            'application/photoshop': 'com.adobe.photoshop-image',
            'application/php': 'public.php-script',
            'application/plain': 'public.plain-text',
            'application/postscript': 'com.adobe.postscript',
            'application/powerpoint': 'com.microsoft.powerpoint.ppt',
            'application/rar': 'com.rarlab.rar-archive',
            'application/rdf+xml': 'unofficial.rdf-feed',
            'application/rss+xml': 'unofficial.rss-feed',
            'application/rtf': 'public.rtf',
            'application/smil': 'com.real.smil',
            'application/stuffit': 'com.allume.stuffit-archive',
            'application/tar': 'public.tar-archive',
            'application/tga': 'com.truevision.tga-image',
            'application/vnd.fpx': 'com.kodak.flashpix.image',
            'application/vnd.ms-excel': 'com.microsoft.excel.xls',
            'application/vnd.ms-powerpoint': 'com.microsoft.powerpoint.ppt',
            'application/vnd.oasis.opendocument.chart': 'org.oasis.opendocument.chart',
            'application/vnd.oasis.opendocument.database': 'org.oasis.opendocument.database',
            'application/vnd.oasis.opendocument.formula': 'org.oasis.opendocument.formula',
            'application/vnd.oasis.opendocument.graphics-template': 'org.oasis.opendocument.graphics',
            'application/vnd.oasis.opendocument.graphics': 'org.oasis.opendocument.graphics',
            'application/vnd.oasis.opendocument.image': 'org.oasis.opendocument.image',
            'application/vnd.oasis.opendocument.presentation-template': 'org.oasis.opendocument.presentation',
            'application/vnd.oasis.opendocument.presentation': 'org.oasis.opendocument.presentation',
            'application/vnd.oasis.opendocument.spreadsheet-template': 'org.oasis.opendocument.spreadsheet',
            'application/vnd.oasis.opendocument.spreadsheet': 'org.oasis.opendocument.spreadsheet',
            'application/vnd.oasis.opendocument.text-master': 'org.oasis.opendocument.text-master',
            'application/vnd.oasis.opendocument.text-template': 'org.oasis.opendocument.text',
            'application/vnd.oasis.opendocument.text-web': 'org.oasis.opendocument.text-web',
            'application/vnd.oasis.opendocument.text': 'org.oasis.opendocument.text',
            'application/vnd.rn-realmedia': 'com.real.realmedia',
            'application/vnd.sun.xml.calc.template': 'org.neooffice.calc',
            'application/vnd.sun.xml.calc': 'org.neooffice.calc',
            'application/vnd.sun.xml.draw.template': 'org.neooffice.draw',
            'application/vnd.sun.xml.draw': 'org.neooffice.draw',
            'application/vnd.sun.xml.impress.template': 'org.neooffice.impress',
            'application/vnd.sun.xml.impress': 'org.neooffice.impress',
            'application/vnd.sun.xml.math': 'org.neooffice.math',
            'application/vnd.sun.xml.writer.global': 'org.neooffice.global',
            'application/vnd.sun.xml.writer.template': 'org.neooffice.writer',
            'application/vnd.sun.xml.writer': 'org.neooffice.writer',
            'application/vndms-excel': 'com.microsoft.excel.xls',
            'application/vndms-powerpoint': 'com.microsoft.powerpoint.ppt',
            'application/vndrn-realmedia': 'com.real.realmedia',
            'application/x-apple-diskimage': 'com.apple.disk-image-udif',
            'application/x-applescript': 'com.apple.applescript.script',
            'application/x-bat': 'com.microsoft.windows-executable',
            'application/x-binary': 'com.apple.macbinary-archive',
            'application/x-binhex40': 'com.apple.binhex-archive',
            'application/x-bittorrent': 'com.bittorrent.torrent',
            'application/x-bzip2': 'org.bzip.bzip2-archive',
            'application/x-cpio': 'public.cpio-archive',
            'application/x-cplusplus': 'public.c-plus-plus-source',
            'application/x-csh': 'public.csh-script',
            'application/x-deb': 'org.debian.debian-package',
            'application/x-debian-package': 'org.debian.debian-package',
            'application/x-eps': 'com.adobe.encapsulated-postscript',
            'application/x-excel': 'com.microsoft.excel.xls',
            'application/x-exe': 'com.microsoft.windows-executable',
            'application/x-flac': 'org.xiph.flac',
            'application/x-font-ttf': 'public.truetype-ttf-font',
            'application/x-font-type1': 'com.adobe.postscript-pfa-font',
            'application/x-gtar': 'org.gnu.gnu-tar-archive',
            'application/x-gzip': 'org.gnu.gnu-zip-archive',
            'application/x-iso-image': 'public.iso-image',
            'application/x-java-class': 'com.sun.java-class',
            'application/x-java': 'com.sun.java-web-start',
            'application/x-javascript': 'com.netscape.javascript-source',
            'application/x-latex': 'org.tug.tex',
            'application/x-mac-binhex40': 'com.apple.binhex-archive',
            'application/x-macbinary': 'com.apple.macbinary-archive',
            'application/x-midi': 'public.midi',
            'application/x-mpegURL': 'unofficial.m3u8-playlist',
            'application/x-ms-wmd': 'com.microsoft.windows-media-wmd',
            'application/x-ms-wmz': 'com.microsoft.windows-media-wmz',
            'application/x-msdos-program': 'com.microsoft.windows-executable',
            'application/x-msdownload': 'com.microsoft.windows-executable',
            'application/x-msexcel': 'com.microsoft.excel.xls',
            'application/x-mspowerpoint': 'com.microsoft.powerpoint.ppt',
            'application/x-pdf': 'com.adobe.pdf',
            'application/x-perl': 'public.perl-script',
            'application/x-php': 'public.php-script',
            'application/x-quartzcomposer': 'com.apple.quartz-composer-composition',
            'application/x-rar-compressed': 'com.rarlab.rar-archive',
            'application/x-redhat-package': 'com.redhat.redhat-package',
            'application/x-rpm': 'com.redhat.redhat-package',
            'application/x-rtf': 'public.rtf',
            'application/x-sh': 'public.shell-script',
            'application/x-shellscript': 'public.shell-script',
            'application/x-shockwave-flash': 'com.macromedia.shockwave-flash',
            'application/x-sit': 'com.allume.stuffit-archive',
            'application/x-smil': 'com.real.smil',
            'application/x-soundfont': 'com.soundblaster.soundfont',
            'application/x-stuffit': 'com.allume.stuffit-archive',
            'application/x-tar': 'public.tar-archive',
            'application/x-tex': 'org.tug.tex',
            'application/x-texinfo': 'org.tug.tex',
            'application/x-troff-msvideo': 'public.avi',
            'application/x-zip-compressed': 'com.pkware.zip-archive',
            'application/xhtml+xml': 'public.html',
            'application/xml': 'public.xml',
            'application/zip': 'com.pkware.zip-archive',
            'audio/3gpp': 'public.3gpp',
            'audio/3gpp2': 'public.3gpp2',
            'audio/aiff': 'public.aiff-audio',
            'audio/au': 'public.ulaw-audio',
            'audio/basic': 'public.ulaw-audio',
            'audio/flac': 'org.xiph.flac',
            'audio/mid': 'public.midi',
            'audio/midi': 'public.midi',
            'audio/mp3': 'public.mp3',
            'audio/mp4': 'public.mpeg4-audio',
            'audio/mp4a-latm': 'public.mpeg4-audio',
            'audio/mpeg': 'public.mp3',
            'audio/mpeg3': 'public.mp3',
            'audio/mpegurl': 'unofficial.m3u-playlist',
            'audio/mpg': 'public.mp3',
            'audio/ogg': 'org.xiph.ogg-vorbis',
            'audio/scpls': 'unofficial.pls-playlist',
            'audio/snd': 'public.ulaw-audio',
            'audio/vnd.rn-realaudio': 'com.real.realaudio',
            'audio/wav': 'com.microsoft.waveform-audio',
            'audio/wave': 'com.microsoft.waveform-audio',
            'audio/webm': 'public.webm',
            'audio/x-adpcm': 'public.ulaw-audio',
            'audio/x-aiff': 'public.aiff-audio',
            'audio/x-au': 'public.ulaw-audio',
            'audio/x-flac': 'org.xiph.flac',
            'audio/x-matroska': 'public.mka',
            'audio/x-mid': 'public.midi',
            'audio/x-midi': 'public.midi',
            'audio/x-mp3': 'public.mp3',
            'audio/x-mpeg-3': 'public.mp3',
            'audio/x-mpeg': 'public.mp3',
            'audio/x-mpeg3': 'public.mp3',
            'audio/x-mpegurl': 'unofficial.m3u-playlist',
            'audio/x-mpg': 'public.mp3',
            'audio/x-ms-wax': 'com.microsoft.windows-media-wax',
            'audio/x-ms-wma': 'com.microsoft.windows-media-wma',
            'audio/x-ogg': 'org.xiph.ogg-vorbis',
            'audio/x-pn-realaudio-plugin': 'com.real.realaudio',
            'audio/x-pn-realaudio': 'com.real.realaudio',
            'audio/x-pn-wav': 'com.microsoft.waveform-audio',
            'audio/x-realaudio': 'com.real.realmedia',
            'audio/x-scpls': 'unofficial.pls-playlist',
            'audio/x-wav': 'com.microsoft.waveform-audio',
            'font/opentype': 'public.opentype-font',
            'image/bmp': 'com.microsoft.bmp',
            'image/efax': 'com.js.efx-fax',
            'image/eps': 'com.adobe.encapsulated-postscript',
            'image/fpx': 'com.kodak.flashpix.image',
            'image/gif': 'com.compuserve.gif',
            'image/indd': 'com.adobe.indesign-image',
            'image/indesign': 'com.adobe.indesign-image',
            'image/jp2': 'public.jpeg2000',
            'image/jpeg': 'public.jpeg',
            'image/ms-bmp': 'com.microsoft.bmp',
            'image/photoshop': 'com.adobe.photoshop-image',
            'image/pict': 'com.apple.pict',
            'image/pipeg': 'public.jpeg',
            'image/pjpeg': 'public.jpeg',
            'image/png': 'public.png',
            'image/psd': 'com.adobe.photoshop-image',
            'image/sgi': 'com.sgi.sgi-image',
            'image/targa': 'com.truevision.tga-image',
            'image/tga': 'com.truevision.tga-image',
            'image/tiff': 'public.tiff',
            'image/vnd.djvu': 'com.lizardtech.djvu',
            'image/vndfpx': 'com.kodak.flashpix.image',
            'image/vndnet-fpx': 'com.kodak.flashpix.image',
            'image/webp': 'public.webp',
            'image/x-bitmap': 'com.microsoft.bmp',
            'image/x-bmp': 'com.microsoft.bmp',
            'image/x-djvu': 'com.lizardtech.djvu',
            'image/x-eps': 'com.adobe.encapsulated-postscript',
            'image/x-icon': 'com.microsoft.ico',
            'image/x-indesign': 'com.adobe.indesign-image',
            'image/x-macpict': 'com.apple.pict',
            'image/x-ms-bmp': 'com.microsoft.bmp',
            'image/x-photoshop': 'com.adobe.photoshop-image',
            'image/x-pict': 'com.apple.pict',
            'image/x-quicktime': 'com.apple.quicktime-image',
            'image/x-tiff': 'public.tiff',
            'image/x-windows-bmp': 'com.microsoft.bmp',
            'image/x-xbitmap': 'com.microsoft.bmp',
            'image/x-xbm': 'public.xbitmap-image',
            'image/xbm': 'public.xbitmap-image',
            'multipart/x-gzip': 'org.gnu.gnu-zip-archive',
            'multipart/x-zip': 'com.pkware.zip-archive',
            'music/crescendo': 'public.midi',
            'text/calendar': 'com.apple.ical.ics',
            'text/css': 'public.css',
            'text/directory': 'public.vcard',
            'text/ecmascript': 'com.netscape.javascript-source',
            'text/html': 'public.html',
            'text/javascript': 'com.netscape.javascript-source',
            'text/php': 'public.php-script',
            'text/plain': 'public.plain-text',
            'text/richtext': 'public.rtf',
            'text/rtf': 'public.rtf',
            'text/ruby-script': 'public.ruby-script',
            'text/tex': 'org.tug.tex',
            'text/vcard': 'public.vcard',
            'text/vnd.sun.j2me.app-descriptor': 'com.sun.java-app-descriptor',
            'text/x-asm': 'public.assembly-source',
            'text/x-c-code': 'public.c-source',
            'text/x-c-header': 'public.c-header',
            'text/x-c': 'public.c-source',
            'text/x-c++-code': 'public.c-plus-plus-source',
            'text/x-c++-hdr': 'public.c-plus-plus-header',
            'text/x-c++-src': 'public.c-plus-plus-source',
            'text/x-c++src': 'public.c-plus-plus-source',
            'text/x-h': 'public.c-header',
            'text/x-java-source': 'com.sun.java-source',
            'text/x-latex': 'org.tug.tex',
            'text/x-objcppsrc': 'public.objective-c-plus-plus-source',
            'text/x-objcsrc': 'public.objective-c-source',
            'text/x-opml': 'unofficial.opml',
            'text/x-perl-script': 'public.perl-script',
            'text/x-perl': 'public.perl-script',
            'text/x-php-script': 'public.php-script',
            'text/x-python-script': 'public.python-script',
            'text/x-python': 'public.python-script',
            'text/x-scriptcsh': 'public.csh-script',
            'text/x-scriptperl-module': 'public.perl-script',
            'text/x-scriptperl': 'public.perl-script',
            'text/x-scriptphyton': 'public.python-script',
            'text/x-scriptsh': 'public.shell-script',
            'text/x-server-parsed-html': 'public.html',
            'text/x-tex': 'org.tug.tex',
            'text/x-vcalendar': 'com.apple.ical.vcs',
            'text/x-vcard': 'public.vcard',
            'text/xhtml': 'public.html',
            'text/xml': 'public.xml',
            'video/3gpp': 'public.3gpp',
            'video/3gpp2': 'public.3gpp2',
            'video/avi': 'public.avi',
            'video/MP2T': 'public.mpegts',
            'video/mp4': 'public.mpeg4',
            'video/mp4v': 'public.mpeg4',
            'video/mpeg': 'public.mpeg',
            'video/mpg': 'public.mpeg',
            'video/msvideo': 'public.avi',
            'video/ogg': 'org.xiph.ogg-theora',
            'video/quicktime': 'com.apple.quicktime-movie',
            'video/webm': 'public.webm',
            'video/x-dv': 'public.dv',
            'video/x-flv': 'public.flv',
            'video/x-m4v': 'public.mpeg4',
            'video/x-matroska': 'public.mkv',
            'video/x-mpeg': 'public.mpeg',
            'video/x-mpg': 'public.mpeg',
            'video/x-ms-asf-plugin': 'com.microsoft.advanced-systems-format',
            'video/x-ms-asf': 'com.microsoft.advanced-systems-format',
            'video/x-ms-asx': 'com.microsoft.advanced-stream-redirector',
            'video/x-ms-wm': 'com.microsoft.windows-media-wm',
            'video/x-ms-wmd': 'com.microsoft.windows-media-wmd',
            'video/x-ms-wmp': 'com.microsoft.windows-media-wmp',
            'video/x-ms-wmv': 'com.microsoft.windows-media-wmv',
            'video/x-ms-wmx': 'com.microsoft.windows-media-wmx',
            'video/x-ms-wmz': 'com.microsoft.windows-media-wmz',
            'video/x-ms-wvx': 'com.microsoft.windows-media-wvx',
            'video/x-msvideo': 'public.avi',
            'video/x-ogg': 'org.xiph.ogg-theora',
            'x-msdos-program': 'com.microsoft.windows-executable',
            'x-music/x-midi': 'public.midi',
        };
        this.fetchImpl = fetchImpl;
        this.authenticationProvider = authenticationProvider;
        this.dataOwnerApi = dataOwnerApi;
        this.encryptedFields = (0, utils_1.parseEncryptedFields)(encryptedKeys, 'Document.');
    }
    get headers() {
        return super.headers.then((h) => this.crypto.accessControlKeysHeaders.addAccessControlKeysHeaders(h, utils_1.EntityWithDelegationTypeName.Document));
    }
    /**
     * Creates a new instance of document with initialised encryption metadata (not in the database).
     * @param user the current user.
     * @param message the message this document refers to.
     * @param c initialised data for the document. Metadata such as id, creation data, etc. will be automatically initialised, but you can specify
     * other kinds of data or overwrite generated metadata with this. You can't specify encryption metadata.
     * @param options optional parameters:
     * - additionalDelegates: delegates which will have access to the entity in addition to the current data owner and delegates from the
     * auto-delegations. Must be an object which associates each data owner id with the access level to give to that data owner. May overlap with
     * auto-delegations, in such case the access level specified here will be used.
     * - sfkOption: specifies which sfk of the owning entity to use.
     * - ignoreAutoDelegations: if true the data won't be shared with the autodelegations of the user, but only with additional delegates
     * - alternateRootDelegation: by default a new entity is created with a root delegation from self to self. In keyless mode this is not possible,
     * and instead the root delegation will be from self to another. You have to specify which delegate will be part of the root delegation.
     * @return a new instance of document.
     */
    newInstance(user_1, message_1) {
        return __awaiter(this, arguments, void 0, function* (user, message, c = {}, options = {}) {
            var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
            const document = Object.assign(Object.assign({}, (c !== null && c !== void 0 ? c : {})), { _type: 'org.taktik.icure.entities.Document', id: (_a = c === null || c === void 0 ? void 0 : c.id) !== null && _a !== void 0 ? _a : this.crypto.primitives.randomUuid(), created: (_b = c === null || c === void 0 ? void 0 : c.created) !== null && _b !== void 0 ? _b : new Date().getTime(), modified: (_c = c === null || c === void 0 ? void 0 : c.modified) !== null && _c !== void 0 ? _c : new Date().getTime(), responsible: (_d = c === null || c === void 0 ? void 0 : c.responsible) !== null && _d !== void 0 ? _d : (this.autofillAuthor ? this.dataOwnerApi.getDataOwnerIdOf(user) : undefined), author: (_e = c === null || c === void 0 ? void 0 : c.author) !== null && _e !== void 0 ? _e : (this.autofillAuthor ? user.id : undefined), codes: (_f = c === null || c === void 0 ? void 0 : c.codes) !== null && _f !== void 0 ? _f : [], tags: (_g = c === null || c === void 0 ? void 0 : c.tags) !== null && _g !== void 0 ? _g : [] });
            const ownerId = this.dataOwnerApi.getDataOwnerIdOf(user);
            if (ownerId !== (yield this.dataOwnerApi.getCurrentDataOwnerId()))
                throw new Error('Can only initialise entities as current data owner.');
            const sfk = message
                ? yield this.crypto.xapi.resolveSecretIdUseOptions({ entity: message, type: utils_1.EntityWithDelegationTypeName.Message }, (_h = options.sfkOption) !== null && _h !== void 0 ? _h : SecretIdUseOption_1.SecretIdUseOption.UseAnySharedWithParent)
                : [];
            const extraDelegations = Object.assign(Object.assign({}, (options.ignoreAutoDelegations == true
                ? {}
                : Object.fromEntries([...((_k = (_j = user.autoDelegations) === null || _j === void 0 ? void 0 : _j.all) !== null && _k !== void 0 ? _k : []), ...((_m = (_l = user.autoDelegations) === null || _l === void 0 ? void 0 : _l.medicalInformation) !== null && _m !== void 0 ? _m : [])].map((d) => [d, AccessLevelEnum.WRITE])))), ((_o = options === null || options === void 0 ? void 0 : options.additionalDelegates) !== null && _o !== void 0 ? _o : {}));
            return new models.Document(yield this.crypto.xapi
                .entityWithInitialisedEncryptedMetadata(document, utils_1.EntityWithDelegationTypeName.Document, message === null || message === void 0 ? void 0 : message.id, sfk, true, extraDelegations, options.alternateRootDelegation)
                .then((x) => x.updatedEntity));
        });
    }
    // noinspection JSUnusedGlobalSymbols
    /**
     * Same as {@link findByMessage} but it will only return the ids of the documents. It can also filter the documents where Document.created is between
     * startDate and endDate in ascending or descending order by that field. (default: ascending).
     */
    findIdsByMessage(hcpartyId, message, startDate, endDate, descending) {
        return __awaiter(this, void 0, void 0, function* () {
            const extractedKeys = yield this.crypto.xapi.secretIdsOf({ entity: message, type: utils_1.EntityWithDelegationTypeName.Message }, hcpartyId);
            const topmostParentId = (yield this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())[0];
            return this.findDocumentIdsByDataOwnerSecretForeignKey(topmostParentId, [...new Set(extractedKeys)], startDate, endDate, descending);
        });
    }
    /**
     * Decrypts an array of documents.
     * @param documents the documents to decrypt.
     * @return an array of objects containing the document and a flag indicating if it was successfully decrypted.
     */
    decrypt(documents) {
        return __awaiter(this, void 0, void 0, function* () {
            return yield this.crypto.xapi.tryDecryptEntities(documents, utils_1.EntityWithDelegationTypeName.Document, (x) => new models.Document(x));
        });
    }
    /**
     * Encrypts an array of documents.
     * @param documents the documents to encrypt.
     * @return the encrypted documents.
     */
    encrypt(documents) {
        return this.crypto.xapi.tryEncryptEntities(documents, utils_1.EntityWithDelegationTypeName.Document, this.encryptedFields, true, false, (x) => new models.Document(x));
    }
    /**
     * @deprecated use getMainAttachmentAs instead
     */
    getAttachmentAs(documentId, attachmentId, returnType, enckeys, fileName) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!!enckeys || !!fileName) {
                console.warn('Using getAttachmentAs method with a value for enckeys or fileName does nothing anymore.');
            }
            return this.getMainAttachmentAs(documentId, returnType);
        });
    }
    /**
     * Gets the main attachment of a document without decrypting it.
     * @param documentId the id of the document.
     * @param returnType the desired return type for the attachment data.
     * @param tryHardToParseJson if true, will attempt to parse JSON even if the content type is not application/json.
     * @return the attachment data in the requested format.
     */
    getMainAttachmentAs(documentId_1, returnType_1) {
        return __awaiter(this, arguments, void 0, function* (documentId, returnType, tryHardToParseJson = false) {
            const url = this.host + `/document/${documentId}/attachment` + '?ts=' + new Date().getTime();
            return XHR_1.XHR.sendCommand('GET', url, yield this.headers, null, this.fetchImpl, returnType, this.authenticationProvider.getAuthService(), undefined, returnType == 'application/json' && tryHardToParseJson)
                .then((doc) => doc.body)
                .catch((err) => this.handleError(err));
        });
    }
    /**
     * Gets and decrypts the main attachment of a document, parsing it to the requested format.
     * @param document the document containing the attachment.
     * @param returnType the desired return type for the attachment data.
     * @return the decrypted and parsed attachment data, or undefined if decryption failed or parsing was unsuccessful.
     */
    getAndTryDecryptMainAttachmentAs(document, returnType) {
        return __awaiter(this, void 0, void 0, function* () {
            const key = (yield this.crypto.xapi.encryptionKeysOf({ entity: document, type: utils_1.EntityWithDelegationTypeName.Document }, undefined))[0];
            if (!key)
                return undefined;
            const tryParse = this.parserFor(returnType);
            const attachmentInfo = yield this.getAndTryDecryptDocumentAttachment(document, (decrypted) => Promise.resolve(tryParse(decrypted) !== undefined));
            if (attachmentInfo.wasDecrypted) {
                return tryParse(attachmentInfo.data);
            }
            else
                return undefined;
        });
    }
    parserFor(returnType) {
        if (returnType === 'application/octet-stream') {
            return (data) => data;
        }
        else if (returnType === 'text/plain') {
            return (data) => {
                try {
                    return (0, binary_utils_1.ua2utf8)(data);
                }
                catch (e) {
                    return undefined;
                }
            };
        }
        else if (returnType === 'application/json') {
            return (data) => {
                try {
                    return JSON.parse((0, binary_utils_1.ua2utf8)(data));
                }
                catch (e) {
                    return undefined;
                }
            };
        }
        else
            throw new Error(`Unsupported type ${returnType}`);
    }
    // noinspection JSUnusedGlobalSymbols
    /**
     * Converts a MIME type and file extension to a UTI (Uniform Type Identifier).
     * @param mimeType the MIME type.
     * @param extension the file extension.
     * @return the corresponding UTI.
     */
    uti(mimeType, extension) {
        return (mimeType && mimeType !== 'application/octet-stream' ? this.utiDefs[mimeType] : this.utiExts[extension]) || this.utiDefs[mimeType];
    }
    // noinspection JSUnusedGlobalSymbols
    /**
     * Converts a UTI (Uniform Type Identifier) to a MIME type.
     * @param uti the UTI.
     * @return the corresponding MIME type.
     */
    mimeType(uti) {
        return this.utiRevDefs[uti];
    }
    /**
     * Adds an attachment to a document, encrypting it on client side using the encryption keys of the provided document.
     * @param document a document.
     * @param attachment a new main attachment for the document.
     * @param utis an array of UTIs for the attachment. The first element will be considered as the main UTI for the document. If provided and non-empty
     * overrides existing values.
     * @param deflate if true, compress the attachment before uploading. Reliable decompression of compressed data requires version 26.5 of the API and all users to be using at least version 8.7.0 of the SDK    * @return the updated document.
     */
    encryptAndSetDocumentAttachment(document_1, attachment_1, utis_1) {
        const _super = Object.create(null, {
            setMainDocumentAttachment: { get: () => super.setMainDocumentAttachment }
        });
        return __awaiter(this, arguments, void 0, function* (document, attachment, utis, deflate = false) {
            var _a;
            if (!document.rev)
                throw new Error('Cannot set attachment on document without rev');
            const realDataSize = (0, binary_utils_1.ua2ab)(attachment).byteLength;
            const { data: dataToEncrypt, algorithm: compressionAlgorithm } = deflate
                ? yield (0, compression_utils_1.compressData)(attachment, utis)
                : { data: (0, binary_utils_1.ua2ab)(attachment), algorithm: undefined };
            const { encryptedData, updatedEntity } = yield this.crypto.xapi.encryptDataOf(document, utils_1.EntityWithDelegationTypeName.Document, dataToEncrypt, (d) => this.modifyDocumentWithUser(undefined, d));
            return (yield this.decrypt([
                yield _super.setMainDocumentAttachment.call(this, document.id, (_a = updatedEntity === null || updatedEntity === void 0 ? void 0 : updatedEntity.rev) !== null && _a !== void 0 ? _a : document.rev, encryptedData, utis, true, compressionAlgorithm, (0, compression_utils_1.getCompressionVersion)(), realDataSize),
            ]))[0].entity;
        });
    }
    /**
     * Adds an unencrypted attachment to a document.
     * @param document a document.
     * @param attachment a new main attachment for the document.
     * @param utis an array of UTIs for the attachment. The first element will be considered as the main UTI for the document. If provided and non-empty
     * overrides existing values.
     * @param deflate if true, compress the attachment before uploading. Reliable decompression of compressed data requires version 26.5 of the API and all users to be using at least version 8.7.0 of the SDK    * @return the updated document.
     */
    setClearDocumentAttachment(document_1, attachment_1, utis_1) {
        const _super = Object.create(null, {
            setMainDocumentAttachment: { get: () => super.setMainDocumentAttachment }
        });
        return __awaiter(this, arguments, void 0, function* (document, attachment, utis, deflate = false) {
            if (!document.rev)
                throw new Error('Cannot set attachment on document without rev');
            const realDataSize = (0, binary_utils_1.ua2ab)(attachment).byteLength;
            const { data: dataToUpload, algorithm: compressionAlgorithm } = deflate
                ? yield (0, compression_utils_1.compressData)(attachment, utis)
                : { data: (0, binary_utils_1.ua2ab)(attachment), algorithm: undefined };
            return (yield this.decrypt([
                yield _super.setMainDocumentAttachment.call(this, document.id, document.rev, dataToUpload, utis, false, compressionAlgorithm, (0, compression_utils_1.getCompressionVersion)(), realDataSize),
            ]))[0].entity;
        });
    }
    /**
     * Adds a secondary attachment to a document, encrypting it on client side using the encryption keys of the provided document.
     * @param document a document.
     * @param secondaryAttachmentKey key for the secondary attachment.
     * @param attachment a new secondary attachment for the document.
     * @param utis an array of UTIs for the attachment. The first element will be considered as the main UTI for the document. If provided and non-empty
     * overrides existing values.
     * @param deflate if true, compress the attachment before uploading. Reliable decompression of compressed data requires version 26.5 of the API and all users to be using at least version 8.7.0 of the SDK    * @return the updated document.
     */
    encryptAndSetSecondaryDocumentAttachment(document_1, secondaryAttachmentKey_1, attachment_1, utis_1) {
        const _super = Object.create(null, {
            setSecondaryAttachment: { get: () => super.setSecondaryAttachment }
        });
        return __awaiter(this, arguments, void 0, function* (document, secondaryAttachmentKey, attachment, utis, deflate = false) {
            var _a;
            if (!document.rev)
                throw new Error('Cannot set attachment on document without rev');
            const realDataSize = (0, binary_utils_1.ua2ab)(attachment).byteLength;
            const { data: dataToEncrypt, algorithm: compressionAlgorithm } = deflate
                ? yield (0, compression_utils_1.compressData)(attachment, utis)
                : { data: (0, binary_utils_1.ua2ab)(attachment), algorithm: undefined };
            const { encryptedData, updatedEntity } = yield this.crypto.xapi.encryptDataOf(document, utils_1.EntityWithDelegationTypeName.Document, dataToEncrypt, (d) => this.modifyDocumentWithUser(undefined, d));
            return (yield this.decrypt([
                yield _super.setSecondaryAttachment.call(this, document.id, secondaryAttachmentKey, (_a = updatedEntity === null || updatedEntity === void 0 ? void 0 : updatedEntity.rev) !== null && _a !== void 0 ? _a : document.rev, encryptedData, utis, true, compressionAlgorithm, (0, compression_utils_1.getCompressionVersion)(), realDataSize),
            ]))[0].entity;
        });
    }
    /**
     * Adds an unencrypted secondary attachment to a document.
     * @param document a document.
     * @param secondaryAttachmentKey key for the secondary attachment.
     * @param attachment a new secondary attachment for the document.
     * @param utis an array of UTIs for the attachment. The first element will be considered as the main UTI for the document. If provided and non-empty
     * overrides existing values.
     * @param deflate if true, compress the attachment before uploading. Reliable decompression of compressed data requires version 26.5 of the API and all users to be using at least version 8.7.0 of the SDK
     * @return the updated document.
     */
    setClearSecondaryDocumentAttachment(document_1, secondaryAttachmentKey_1, attachment_1, utis_1) {
        const _super = Object.create(null, {
            setSecondaryAttachment: { get: () => super.setSecondaryAttachment }
        });
        return __awaiter(this, arguments, void 0, function* (document, secondaryAttachmentKey, attachment, utis, deflate = false) {
            const realDataSize = (0, binary_utils_1.ua2ab)(attachment).byteLength;
            const { data: dataToUpload, algorithm: compressionAlgorithm } = deflate
                ? yield (0, compression_utils_1.compressData)(attachment, utis)
                : { data: (0, binary_utils_1.ua2ab)(attachment), algorithm: undefined };
            return (yield this.decrypt([
                yield _super.setSecondaryAttachment.call(this, document.id, secondaryAttachmentKey, document.rev, dataToUpload, utis, false, compressionAlgorithm, (0, compression_utils_1.getCompressionVersion)(), realDataSize),
            ]))[0].entity;
        });
    }
    /**
     * Gets the main attachment of a document and tries to decrypt it using the encryption keys of the document, throwing an error if the operation fails.
     * @param document a document.
     * @param validator optionally a validator function which checks if the decryption was successful. In cases where the document has many encryption
     * keys and it is unclear which one should be used this function can help to detect bad decryptions.
     * @return the decrypted attachment, if it could be decrypted, else the encrypted attachment.
     */
    getAndDecryptDocumentAttachment(document_1) {
        return __awaiter(this, arguments, void 0, function* (document, validator = () => Promise.resolve(true)) {
            const retrieved = yield this.getAndTryDecryptDocumentAttachment(document, (x) => validator(x));
            if (!retrieved.wasDecrypted)
                throw new Error(`No valid key found to decrypt data of document ${document.id}.`);
            return retrieved.data;
        });
    }
    /**
     * Gets the main attachment of a document and tries to decrypt it using the encryption keys of the document.
     * @param document a document.
     * @param validator optionally a validator function which checks if the decryption was successful. In cases where the document has many encryption
     * keys and it is unclear which one should be used this function can help to detect bad decryptions.
     * @return an object containing:
     * - data: the decrypted attachment, if it could be decrypted, else the encrypted attachment.
     * - wasDecrypted: if the data was successfully decrypted or not
     */
    getAndTryDecryptDocumentAttachment(document_1) {
        const _super = Object.create(null, {
            getRawMainDocumentAttachment: { get: () => super.getRawMainDocumentAttachment }
        });
        return __awaiter(this, arguments, void 0, function* (document, validator = () => Promise.resolve(true)) {
            var _a;
            const compressionAlgorithm = (_a = document.extraMainAttachmentInfo) === null || _a === void 0 ? void 0 : _a.compressionAlgorithm;
            return yield this.crypto.xapi.tryDecryptDataOf({ entity: document, type: utils_1.EntityWithDelegationTypeName.Document }, yield _super.getRawMainDocumentAttachment.call(this, document.id), (decrypted) => __awaiter(this, void 0, void 0, function* () {
                try {
                    const data = compressionAlgorithm ? yield (0, compression_utils_1.decompressData)(decrypted, compressionAlgorithm) : decrypted;
                    return (yield validator(data)) ? data : undefined;
                }
                catch (_a) {
                    return undefined;
                }
            }));
        });
    }
    /**
     * Gets the secondary attachment of a document and tries to decrypt it using the encryption keys of the document, throwing an error if the operation fails.
     * @param document a document.
     * @param secondaryAttachmentKey key of the secondary attachment.
     * @param validator optionally a validator function which checks if the decryption was successful. In cases where the document has many encryption
     * keys and it is unclear which one should be used this function can help to detect bad decryptions.
     * @return the decrypted attachment.
     */
    getAndDecryptSecondaryDocumentAttachment(document_1, secondaryAttachmentKey_1) {
        return __awaiter(this, arguments, void 0, function* (document, secondaryAttachmentKey, validator = () => Promise.resolve(true)) {
            const { data, wasDecrypted } = yield this.getAndTryDecryptSecondaryDocumentAttachment(document, secondaryAttachmentKey, (x) => validator(x));
            if (!wasDecrypted)
                throw new Error(`No valid key found to decrypt data of document ${document.id}.`);
            return data;
        });
    }
    /**
     * Gets the secondary attachment of a document and tries to decrypt it using the encryption keys of the document.
     * @param document a document.
     * @param secondaryAttachmentKey key of the secondary attachment.
     * @param validator optionally a validator function which checks if the decryption was successful. In cases where the document has many encryption
     * keys and it is unclear which one should be used this function can help to detect bad decryptions.
     * @return an object containing:
     * - data: the decrypted attachment, if it could be decrypted, else the encrypted attachment.
     * - wasDecrypted: if the data was successfully decrypted or not
     */
    getAndTryDecryptSecondaryDocumentAttachment(document_1, secondaryAttachmentKey_1) {
        const _super = Object.create(null, {
            getSecondaryAttachment: { get: () => super.getSecondaryAttachment }
        });
        return __awaiter(this, arguments, void 0, function* (document, secondaryAttachmentKey, validator = () => Promise.resolve(true)) {
            var _a, _b;
            const compressionAlgorithm = (_b = (_a = document.secondaryAttachments) === null || _a === void 0 ? void 0 : _a[secondaryAttachmentKey]) === null || _b === void 0 ? void 0 : _b.compressionAlgorithm;
            return yield this.crypto.xapi.tryDecryptDataOf({ entity: document, type: utils_1.EntityWithDelegationTypeName.Document }, yield _super.getSecondaryAttachment.call(this, document.id, secondaryAttachmentKey), (decrypted) => __awaiter(this, void 0, void 0, function* () {
                try {
                    const data = compressionAlgorithm ? yield (0, compression_utils_1.decompressData)(decrypted, compressionAlgorithm) : decrypted;
                    return (yield validator(data)) ? data : undefined;
                }
                catch (_a) {
                    return undefined;
                }
            }));
        });
    }
    /**
     * @param document a document
     * @return the id of the message that the document refers to, retrieved from the encrypted metadata. Normally there should only be one element
     * in the returned array, but in case of entity merges there could be multiple values.
     */
    decryptMessageIdOf(document) {
        return __awaiter(this, void 0, void 0, function* () {
            return this.crypto.xapi.owningEntityIdsOf({ entity: document, type: utils_1.EntityWithDelegationTypeName.Document }, undefined);
        });
    }
    /**
     * @return if the logged data owner has write access to the content of the given document
     */
    hasWriteAccess(document) {
        return __awaiter(this, void 0, void 0, function* () {
            return this.crypto.xapi.hasWriteAccess({ entity: document, type: utils_1.EntityWithDelegationTypeName.Document });
        });
    }
    /**
     * Share an existing document with other data owners, allowing them to access the non-encrypted data of the document and optionally also
     * the encrypted content, with read-only or read-write permissions.
     * @param delegateId the id of the data owner which will be granted access to the document.
     * @param document the document to share.
     * @param options optional parameters to customize the sharing behaviour:
     * - shareSecretIds: specifies which secret ids of the entity should be shared. If not provided all secret ids available to the current user will be shared
     * - shareEncryptionKey: specifies if the encryption key of the access log should be shared with the delegate, giving access to all encrypted
     * content of the entity, excluding other encrypted metadata (defaults to {@link ShareMetadataBehaviour.IF_AVAILABLE}).
     * - shareMessageId: specifies if the id of the message that this document refers to should be shared with the delegate (defaults to
     * {@link ShareMetadataBehaviour.IF_AVAILABLE}).
     * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.
     * @return the updated entity
     */
    shareWith(delegateId_1, document_1) {
        return __awaiter(this, arguments, void 0, function* (delegateId, document, options = {}) {
            return this.shareWithMany(document, { [delegateId]: options });
        });
    }
    /**
     * Share an existing document with other data owners, allowing them to access the non-encrypted data of the document and optionally also
     * the encrypted content, with read-only or read-write permissions.
     * @param document the document to share.
     * @param delegates associates the id of data owners which will be granted access to the entity, to the following sharing options:
     * - shareSecretIds: specifies which secret ids of the entity should be shared. If not provided all secret ids available to the current user will be shared
     * - shareEncryptionKey: specifies if the encryption key of the access log should be shared with the delegate, giving access to all encrypted
     * content of the entity, excluding other encrypted metadata (defaults to {@link ShareMetadataBehaviour.IF_AVAILABLE}).
     * - shareMessageId: specifies if the id of the message that this document refers to should be shared with the delegate (defaults to
     * {@link ShareMetadataBehaviour.IF_AVAILABLE}).
     * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.
     * @return the updated entity.
     */
    shareWithMany(document, delegates) {
        return __awaiter(this, void 0, void 0, function* () {
            return (yield this.tryShareWithMany(document, delegates)).updatedEntityOrThrow;
        });
    }
    /**
     * Share an existing document with other data owners, allowing them to access the non-encrypted data of the document and optionally also
     * the encrypted content, with read-only or read-write permissions.
     * @param document the document to share.
     * @param delegates associates the id of data owners which will be granted access to the entity, to the following sharing options:
     * - shareSecretIds: specifies which secret ids of the entity should be shared. If not provided all secret ids available to the current user will be shared
     * - shareEncryptionKey: specifies if the encryption key of the access log should be shared with the delegate, giving access to all encrypted
     * content of the entity, excluding other encrypted metadata (defaults to {@link ShareMetadataBehaviour.IF_AVAILABLE}).
     * - shareMessageId: specifies if the id of the message that this document refers to should be shared with the delegate (defaults to
     * {@link ShareMetadataBehaviour.IF_AVAILABLE}).
     * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.
     * @return a promise which will contain the result of the operation: the updated entity if the operation was successful or details of the error if
     * the operation failed.
     */
    tryShareWithMany(document, delegates) {
        const _super = Object.create(null, {
            bulkShareDocument: { get: () => super.bulkShareDocument }
        });
        return __awaiter(this, void 0, void 0, function* () {
            const self = yield this.dataOwnerApi.getCurrentDataOwnerId();
            // All entities should have an encryption key.
            const entityWithEncryptionKey = yield this.crypto.xapi.ensureEncryptionKeysInitialised(document, utils_1.EntityWithDelegationTypeName.Document);
            const updatedEntity = entityWithEncryptionKey ? yield this.modifyDocumentWithUser(undefined, entityWithEncryptionKey) : document;
            return this.crypto.xapi
                .simpleShareOrUpdateEncryptedEntityMetadata({
                entity: updatedEntity,
                type: utils_1.EntityWithDelegationTypeName.Document,
            }, Object.fromEntries(Object.entries(delegates).map(([delegateId, options]) => [
                delegateId,
                {
                    requestedPermissions: options.requestedPermissions,
                    shareEncryptionKeys: options.shareEncryptionKey,
                    shareOwningEntityIds: options.shareMessageId,
                    shareSecretIds: options.shareSecretIds,
                },
            ])), (x) => _super.bulkShareDocument.call(this, x))
                .then((r) => r.mapSuccessAsync((m) => __awaiter(this, void 0, void 0, function* () { return (yield this.decrypt([m]))[0].entity; })));
        });
    }
    /**
     * Gets the data owners that have access to a document.
     * @param entity the document.
     * @return an object containing the permissions by data owner id and a flag indicating if there are unknown anonymous data owners.
     */
    getDataOwnersWithAccessTo(entity) {
        return this.crypto.delegationsDeAnonymization.getDataOwnersWithAccessTo({ entity, type: utils_1.EntityWithDelegationTypeName.Document });
    }
    /**
     * Gets the encryption keys of a document.
     * @param entity the document.
     * @return an array of encryption keys.
     */
    getEncryptionKeysOf(entity) {
        return this.crypto.xapi.encryptionKeysOf({ entity, type: utils_1.EntityWithDelegationTypeName.Document }, undefined);
    }
    /**
     * Creates delegation de-anonymization metadata for a document.
     * @param entity the document.
     * @param delegates the data owner ids of the delegates.
     */
    createDelegationDeAnonymizationMetadata(entity, delegates) {
        return this.crypto.delegationsDeAnonymization.createOrUpdateDeAnonymizationInfo({ entity, type: utils_1.EntityWithDelegationTypeName.Document }, delegates);
    }
    decryptPage(page) {
        return __awaiter(this, void 0, void 0, function* () {
            var _a;
            return Object.assign(Object.assign({}, page), { rows: (yield this.decrypt((_a = page.rows) !== null && _a !== void 0 ? _a : [])).map((x) => x.entity) });
        });
    }
    /**
     * Creates a new document.
     * @param user the user (not used).
     * @param body the document to create.
     * @return the created document.
     */
    createDocumentWithUser(user, body) {
        const _super = Object.create(null, {
            createDocument: { get: () => super.createDocument }
        });
        return __awaiter(this, void 0, void 0, function* () {
            return (yield this.decrypt([yield _super.createDocument.call(this, (yield this.encrypt([body]))[0])]))[0].entity;
        });
    }
    /**
     * Deletes the main attachment of a document.
     * @param user the user (not used).
     * @param documentId the id of the document.
     * @return the updated document.
     */
    deleteAttachmentWithUser(user, documentId) {
        const _super = Object.create(null, {
            deleteAttachment: { get: () => super.deleteAttachment }
        });
        return __awaiter(this, void 0, void 0, function* () {
            return (yield this.decrypt([yield _super.deleteAttachment.call(this, documentId)]))[0].entity;
        });
    }
    /**
     * @deprecated
     */
    findByTypeHCPartyMessageSecretFKeysWithUser(user, documentTypeCode, hcPartyId, secretFKeys) {
        const _super = Object.create(null, {
            findByTypeHCPartyMessageSecretFKeys: { get: () => super.findByTypeHCPartyMessageSecretFKeys }
        });
        return __awaiter(this, void 0, void 0, function* () {
            return (yield this.decrypt(yield _super.findByTypeHCPartyMessageSecretFKeys.call(this, documentTypeCode, hcPartyId, secretFKeys))).map((x) => x.entity);
        });
    }
    /**
     * @deprecated
     */
    findDocumentsByHCPartyPatientForeignKeysWithUser(user, hcPartyId, secretFKeys) {
        const _super = Object.create(null, {
            findDocumentsByHCPartyPatientForeignKeys: { get: () => super.findDocumentsByHCPartyPatientForeignKeys }
        });
        return __awaiter(this, void 0, void 0, function* () {
            return (yield this.decrypt(yield _super.findDocumentsByHCPartyPatientForeignKeys.call(this, hcPartyId, secretFKeys))).map((x) => x.entity);
        });
    }
    /**
     * @deprecated
     */
    findDocumentsByHCPartyPatientForeignKeyWithUser(user, hcPartyId, secretFKey, startKey, startDocumentId, limit) {
        const _super = Object.create(null, {
            findDocumentsByHCPartyPatientForeignKey: { get: () => super.findDocumentsByHCPartyPatientForeignKey }
        });
        return __awaiter(this, void 0, void 0, function* () {
            return yield this.decryptPage(yield _super.findDocumentsByHCPartyPatientForeignKey.call(this, hcPartyId, secretFKey, startKey, startDocumentId, limit));
        });
    }
    findWithoutDelegationWithUser(user, limit) {
        const _super = Object.create(null, {
            findWithoutDelegation: { get: () => super.findWithoutDelegation }
        });
        return __awaiter(this, void 0, void 0, function* () {
            return (yield this.decrypt(yield _super.findWithoutDelegation.call(this, limit))).map((x) => x.entity);
        });
    }
    /**
     * Gets a document by id.
     * @param user the user (not used).
     * @param documentId the id of the document.
     * @return the document.
     */
    getDocumentWithUser(user, documentId) {
        const _super = Object.create(null, {
            getDocument: { get: () => super.getDocument }
        });
        return __awaiter(this, void 0, void 0, function* () {
            return (yield this.decrypt([yield _super.getDocument.call(this, documentId)]))[0].entity;
        });
    }
    /**
     * Gets a document by external UUID.
     * @param user the user (not used).
     * @param externalUuid the external UUID of the document.
     * @return the document.
     */
    getDocumentByExternalUuidWithUser(user, externalUuid) {
        const _super = Object.create(null, {
            getDocumentByExternalUuid: { get: () => super.getDocumentByExternalUuid }
        });
        return __awaiter(this, void 0, void 0, function* () {
            return (yield this.decrypt([yield _super.getDocumentByExternalUuid.call(this, externalUuid)]))[0].entity;
        });
    }
    /**
     * Gets multiple documents by their ids.
     * @param user the user (not used).
     * @param body a list of document ids.
     * @return the documents.
     */
    getDocumentsWithUser(user, body) {
        const _super = Object.create(null, {
            getDocuments: { get: () => super.getDocuments }
        });
        return __awaiter(this, void 0, void 0, function* () {
            return (yield this.decrypt(yield _super.getDocuments.call(this, body))).map((x) => x.entity);
        });
    }
    /**
     * Gets all documents with a specific external UUID.
     * @param user the user (not used).
     * @param externalUuid the external UUID.
     * @return the documents.
     */
    getDocumentsByExternalUuidWithUser(user, externalUuid) {
        const _super = Object.create(null, {
            getDocumentsByExternalUuid: { get: () => super.getDocumentsByExternalUuid }
        });
        return __awaiter(this, void 0, void 0, function* () {
            return (yield this.decrypt(yield _super.getDocumentsByExternalUuid.call(this, externalUuid))).map((x) => x.entity);
        });
    }
    /**
     * Updates a document.
     * @param user the user (not used).
     * @param body the document to update.
     * @return the updated document.
     */
    modifyDocumentWithUser(user, body) {
        const _super = Object.create(null, {
            modifyDocument: { get: () => super.modifyDocument }
        });
        return __awaiter(this, void 0, void 0, function* () {
            return (yield this.decrypt([yield _super.modifyDocument.call(this, (yield this.encrypt([body]))[0])]))[0].entity;
        });
    }
    /**
     * Updates multiple documents.
     * @param user the user (not used).
     * @param body the documents to update.
     * @return the updated documents.
     */
    modifyDocumentsWithUser(user, body) {
        const _super = Object.create(null, {
            modifyDocuments: { get: () => super.modifyDocuments }
        });
        return __awaiter(this, void 0, void 0, function* () {
            return (yield this.decrypt(yield _super.modifyDocuments.call(this, yield this.encrypt(body)))).map((x) => x.entity);
        });
    }
    /**
     * Sets the main attachment of a document.
     * @param user the user (not used).
     * @param documentId the id of the document.
     * @param documentRev the revision of the document.
     * @param body the attachment data.
     * @param utis an array of UTIs for the attachment.
     * @param dataIsEncrypted whether the data is already encrypted.
     * @return the updated document.
     */
    setMainDocumentAttachmentWithUser(user, documentId, documentRev, body, utis, dataIsEncrypted) {
        const _super = Object.create(null, {
            setMainDocumentAttachment: { get: () => super.setMainDocumentAttachment }
        });
        return __awaiter(this, void 0, void 0, function* () {
            return (yield this.decrypt([yield _super.setMainDocumentAttachment.call(this, documentId, documentRev, body, utis, dataIsEncrypted)]))[0].entity;
        });
    }
    /**
     * Sets a secondary attachment on a document.
     * @param user the user (not used).
     * @param documentId the id of the document.
     * @param key the key for the secondary attachment.
     * @param rev the revision of the document.
     * @param attachment the attachment data.
     * @param utis an array of UTIs for the attachment.
     * @param dataIsEncrypted whether the data is already encrypted.
     * @return the updated document.
     */
    setSecondaryAttachmentWithUser(user, documentId, key, rev, attachment, utis, dataIsEncrypted) {
        const _super = Object.create(null, {
            setSecondaryAttachment: { get: () => super.setSecondaryAttachment }
        });
        return __awaiter(this, void 0, void 0, function* () {
            return (yield this.decrypt([yield _super.setSecondaryAttachment.call(this, documentId, key, rev, attachment, utis, dataIsEncrypted)]))[0].entity;
        });
    }
    /**
     * Deletes a secondary attachment from a document.
     * @param user the user (not used).
     * @param documentId the id of the document.
     * @param key the key of the secondary attachment.
     * @param rev the revision of the document.
     * @return the updated document.
     */
    deleteSecondaryAttachmentWithUser(user, documentId, key, rev) {
        const _super = Object.create(null, {
            deleteSecondaryAttachment: { get: () => super.deleteSecondaryAttachment }
        });
        return __awaiter(this, void 0, void 0, function* () {
            return (yield this.decrypt([yield _super.deleteSecondaryAttachment.call(this, documentId, key, rev)]))[0].entity;
        });
    }
    createDocument(body) {
        throw new Error('Use withUser method');
    }
    deleteAttachment(documentId) {
        throw new Error('Use withUser method');
    }
    findByTypeHCPartyMessageSecretFKeys(documentTypeCode, hcPartyId, secretFKeys) {
        throw new Error('Use withUser method');
    }
    findDocumentsByHCPartyPatientForeignKeys(hcPartyId, secretFKeys) {
        throw new Error('Use withUser method');
    }
    findDocumentsByHCPartyPatientForeignKey(hcPartyId, secretFKey, startKey, startDocumentId, limit) {
        throw new Error('Use withUser method');
    }
    findWithoutDelegation(limit) {
        throw new Error('Use withUser method');
    }
    getDocument(documentId) {
        throw new Error('Use withUser method');
    }
    getDocumentByExternalUuid(externalUuid) {
        throw new Error('Use withUser method');
    }
    getDocuments(body) {
        throw new Error('Use withUser method');
    }
    getDocumentsByExternalUuid(externalUuid) {
        throw new Error('Use withUser method');
    }
    modifyDocument(body) {
        throw new Error('Use withUser method');
    }
    modifyDocuments(body) {
        throw new Error('Use withUser method');
    }
    setMainDocumentAttachment(documentId, documentRev, body, utis, dataIsEncrypted) {
        throw new Error('Use withUser method');
    }
    setDocumentAttachmentBody(documentId, documentRev, enckeys, body, utis) {
        throw new Error('Use withUser method');
    }
    setDocumentAttachment(documentId, documentRev, enckeys, body, utis) {
        throw new Error('Use withUser method');
    }
    setDocumentAttachmentMulti(attachment, documentRev, documentId, enckeys) {
        throw new Error('Use withUser method');
    }
    setSecondaryAttachment(documentId, key, rev, attachment, utis, dataIsEncrypted) {
        throw new Error('Use withUser method');
    }
    deleteSecondaryAttachment(documentId, key, rev) {
        throw new Error('Use withUser method');
    }
}
exports.IccDocumentXApi = IccDocumentXApi;
//# sourceMappingURL=icc-document-x-api.js.map