var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
import { _bytesToString, _defineProperty, _stringToBytes, FormatError } from '@syncfusion/ej2-pdf';
import { _expertEncoding, _standardEncoding, _getEncoding, _getGlyphsUnicode } from './encoding-utils';
import { _recoverGlyphName } from './font-utils';
var _PdfCompactFontParser = /** @class */ (function () {
    function _PdfCompactFontParser(file, properties, isAnalysisEnabled) {
        this._characterValidationData = [
            null,
            { id: 'hstem', min: 2, stackClearing: true, stem: true },
            null,
            { id: 'vstem', min: 2, stackClearing: true, stem: true },
            { id: 'vmoveto', min: 1, stackClearing: true },
            { id: 'rlineto', min: 2, resetStack: true },
            { id: 'hlineto', min: 1, resetStack: true },
            { id: 'vlineto', min: 1, resetStack: true },
            { id: 'rrcurveto', min: 6, resetStack: true },
            null,
            { id: 'callsubr', min: 1, undefStack: true },
            { id: 'return', min: 0, undefStack: true },
            null,
            null,
            { id: 'endchar', min: 0, stackClearing: true },
            null,
            null,
            null,
            { id: 'hstemhm', min: 2, stackClearing: true, stem: true },
            { id: 'hintmask', min: 0, stackClearing: true },
            { id: 'cntrmask', min: 0, stackClearing: true },
            { id: 'rmoveto', min: 2, stackClearing: true },
            { id: 'hmoveto', min: 1, stackClearing: true },
            { id: 'vstemhm', min: 2, stackClearing: true, stem: true },
            { id: 'rcurveline', min: 8, resetStack: true },
            { id: 'rlinecurve', min: 8, resetStack: true },
            { id: 'vvcurveto', min: 4, resetStack: true },
            { id: 'hhcurveto', min: 4, resetStack: true },
            null,
            { id: 'callgsubr', min: 1, undefStack: true },
            { id: 'vhcurveto', min: 4, resetStack: true },
            { id: 'hvcurveto', min: 4, resetStack: true }
        ];
        this._characterValidationData12 = [
            null,
            null,
            null,
            { id: 'and', min: 2, stackDelta: -1 },
            { id: 'or', min: 2, stackDelta: -1 },
            { id: 'not', min: 1, stackDelta: 0 },
            null,
            null,
            null,
            { id: 'abs', min: 1, stackDelta: 0 },
            {
                id: 'add',
                min: 2,
                stackDelta: -1,
                stackFn: function (stack, index) {
                    stack[index - 2] = stack[index - 2] + stack[index - 1];
                }
            },
            {
                id: 'sub',
                min: 2,
                stackDelta: -1,
                stackFn: function (stack, index) {
                    stack[index - 2] = stack[index - 2] - stack[index - 1];
                }
            },
            {
                id: 'div',
                min: 2,
                stackDelta: -1,
                stackFn: function (stack, index) {
                    stack[index - 2] = stack[index - 2] / stack[index - 1];
                }
            },
            null,
            {
                id: 'neg',
                min: 1,
                stackDelta: 0,
                stackFn: function (stack, index) {
                    stack[index - 1] = -stack[index - 1];
                }
            },
            { id: 'eq', min: 2, stackDelta: -1 },
            null,
            null,
            { id: 'drop', min: 1, stackDelta: -1 },
            null,
            { id: 'put', min: 2, stackDelta: -2 },
            { id: 'get', min: 1, stackDelta: 0 },
            { id: 'ifelse', min: 4, stackDelta: -3 },
            { id: 'random', min: 0, stackDelta: 1 },
            {
                id: 'mul',
                min: 2,
                stackDelta: -1,
                stackFn: function (stack, index) {
                    stack[index - 2] = stack[index - 2] * stack[index - 1];
                }
            },
            null,
            { id: 'sqrt', min: 1, stackDelta: 0 },
            { id: 'dup', min: 1, stackDelta: 1 },
            { id: 'exch', min: 2, stackDelta: 0 },
            { id: 'index', min: 2, stackDelta: 0 },
            { id: 'roll', min: 3, stackDelta: -2 },
            null,
            null,
            null,
            { id: 'hflex', min: 7, resetStack: true },
            { id: 'flex', min: 13, resetStack: true },
            { id: 'hflex1', min: 9, resetStack: true },
            { id: 'flex1', min: 11, resetStack: true }
        ];
        this._compactCharSetPredefinedTypes = {
            standard: 0,
            expert: 1,
            expertSubset: 2
        };
        this._standardCharSet = [
            '.notdef', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar',
            'percent', 'ampersand', 'quoteright', 'parenleft', 'parenright',
            'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero',
            'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight',
            'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question',
            'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
            'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
            'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore',
            'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
            'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
            'braceleft', 'bar', 'braceright', 'asciitilde', 'exclamdown', 'cent',
            'sterling', 'fraction', 'yen', 'florin', 'section', 'currency',
            'quotesingle', 'quotedblleft', 'guillemotleft', 'guilsinglleft',
            'guilsinglright', 'fi', 'fl', 'endash', 'dagger', 'daggerdbl',
            'periodcentered', 'paragraph', 'bullet', 'quotesinglbase',
            'quotedblbase', 'quotedblright', 'guillemotright', 'ellipsis',
            'perthousand', 'questiondown', 'grave', 'acute', 'circumflex', 'tilde',
            'macron', 'breve', 'dotaccent', 'dieresis', 'ring', 'cedilla',
            'hungarumlaut', 'ogonek', 'caron', 'emdash', 'AE', 'ordfeminine',
            'Lslash', 'Oslash', 'OE', 'ordmasculine', 'ae', 'dotlessi', 'lslash',
            'oslash', 'oe', 'germandbls', 'onesuperior', 'logicalnot', 'mu',
            'trademark', 'Eth', 'onehalf', 'plusminus', 'Thorn', 'onequarter',
            'divide', 'brokenbar', 'degree', 'thorn', 'threequarters', 'twosuperior',
            'registered', 'minus', 'eth', 'multiply', 'threesuperior', 'copyright',
            'Aacute', 'Acircumflex', 'Adieresis', 'Agrave', 'Aring', 'Atilde',
            'Ccedilla', 'Eacute', 'Ecircumflex', 'Edieresis', 'Egrave', 'Iacute',
            'Icircumflex', 'Idieresis', 'Igrave', 'Ntilde', 'Oacute', 'Ocircumflex',
            'Odieresis', 'Ograve', 'Otilde', 'Scaron', 'Uacute', 'Ucircumflex',
            'Udieresis', 'Ugrave', 'Yacute', 'Ydieresis', 'Zcaron', 'aacute',
            'acircumflex', 'adieresis', 'agrave', 'aring', 'atilde', 'ccedilla',
            'eacute', 'ecircumflex', 'edieresis', 'egrave', 'iacute', 'icircumflex',
            'idieresis', 'igrave', 'ntilde', 'oacute', 'ocircumflex', 'odieresis',
            'ograve', 'otilde', 'scaron', 'uacute', 'ucircumflex', 'udieresis',
            'ugrave', 'yacute', 'ydieresis', 'zcaron'
        ];
        this._expertCharSet = [
            '.notdef', 'space', 'exclamsmall', 'Hungarumlautsmall', 'dollaroldstyle',
            'dollarsuperior', 'ampersandsmall', 'Acutesmall', 'parenleftsuperior',
            'parenrightsuperior', 'twodotenleader', 'onedotenleader', 'comma',
            'hyphen', 'period', 'fraction', 'zerooldstyle', 'oneoldstyle',
            'twooldstyle', 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle',
            'sixoldstyle', 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle',
            'colon', 'semicolon', 'commasuperior', 'threequartersemdash',
            'periodsuperior', 'questionsmall', 'asuperior', 'bsuperior',
            'centsuperior', 'dsuperior', 'esuperior', 'isuperior', 'lsuperior',
            'msuperior', 'nsuperior', 'osuperior', 'rsuperior', 'ssuperior',
            'tsuperior', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'parenleftinferior',
            'parenrightinferior', 'Circumflexsmall', 'hyphensuperior', 'Gravesmall',
            'Asmall', 'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall',
            'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall',
            'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall',
            'Vsmall', 'Wsmall', 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary',
            'onefitted', 'rupiah', 'Tildesmall', 'exclamdownsmall', 'centoldstyle',
            'Lslashsmall', 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall',
            'Brevesmall', 'Caronsmall', 'Dotaccentsmall', 'Macronsmall',
            'figuredash', 'hypheninferior', 'Ogoneksmall', 'Ringsmall',
            'Cedillasmall', 'onequarter', 'onehalf', 'threequarters',
            'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths',
            'seveneighths', 'onethird', 'twothirds', 'zerosuperior', 'onesuperior',
            'twosuperior', 'threesuperior', 'foursuperior', 'fivesuperior',
            'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior',
            'zeroinferior', 'oneinferior', 'twoinferior', 'threeinferior',
            'fourinferior', 'fiveinferior', 'sixinferior', 'seveninferior',
            'eightinferior', 'nineinferior', 'centinferior', 'dollarinferior',
            'periodinferior', 'commainferior', 'Agravesmall', 'Aacutesmall',
            'Acircumflexsmall', 'Atildesmall', 'Adieresissmall', 'Aringsmall',
            'AEsmall', 'Ccedillasmall', 'Egravesmall', 'Eacutesmall',
            'Ecircumflexsmall', 'Edieresissmall', 'Igravesmall', 'Iacutesmall',
            'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall',
            'Ogravesmall', 'Oacutesmall', 'Ocircumflexsmall', 'Otildesmall',
            'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall', 'Uacutesmall',
            'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall',
            'Ydieresissmall'
        ];
        this._expertSubsetCharSet = [
            '.notdef', 'space', 'dollaroldstyle', 'dollarsuperior',
            'parenleftsuperior', 'parenrightsuperior', 'twodotenleader',
            'onedotenleader', 'comma', 'hyphen', 'period', 'fraction',
            'zerooldstyle', 'oneoldstyle', 'twooldstyle', 'threeoldstyle',
            'fouroldstyle', 'fiveoldstyle', 'sixoldstyle', 'sevenoldstyle',
            'eightoldstyle', 'nineoldstyle', 'colon', 'semicolon', 'commasuperior',
            'threequartersemdash', 'periodsuperior', 'asuperior', 'bsuperior',
            'centsuperior', 'dsuperior', 'esuperior', 'isuperior', 'lsuperior',
            'msuperior', 'nsuperior', 'osuperior', 'rsuperior', 'ssuperior',
            'tsuperior', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'parenleftinferior',
            'parenrightinferior', 'hyphensuperior', 'colonmonetary', 'onefitted',
            'rupiah', 'centoldstyle', 'figuredash', 'hypheninferior', 'onequarter',
            'onehalf', 'threequarters', 'oneeighth', 'threeeighths', 'fiveeighths',
            'seveneighths', 'onethird', 'twothirds', 'zerosuperior', 'onesuperior',
            'twosuperior', 'threesuperior', 'foursuperior', 'fivesuperior',
            'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior',
            'zeroinferior', 'oneinferior', 'twoinferior', 'threeinferior',
            'fourinferior', 'fiveinferior', 'sixinferior', 'seveninferior',
            'eightinferior', 'nineinferior', 'centinferior', 'dollarinferior',
            'periodinferior', 'commainferior'
        ];
        this._standardEncodingChars = []; //eslint-disable-line
        this._widths = []; //eslint-disable-line
        this._pos = 0;
        this._bytes = file.getBytes();
        this._properties = properties;
        this._isAnalysisEnabled = isAnalysisEnabled;
    }
    _PdfCompactFontParser.prototype._parsePrivateDictionary = function (parentDictionary) {
        if (!parentDictionary._hasName('Private')) {
            this._emptyPrivateDictionary(parentDictionary);
            return;
        }
        var privateOffset = parentDictionary._getByName('Private'); //eslint-disable-line
        if (!Array.isArray(privateOffset) || privateOffset.length !== 2) {
            parentDictionary._removeByName('Private');
            return;
        }
        var size = privateOffset[0];
        var offset = privateOffset[1];
        if (size === 0 || offset >= this._bytes.length) {
            this._emptyPrivateDictionary(parentDictionary);
            return;
        }
        var privateDictionary = this._createDictionary(_PdfCompactFontPrivateDictionary, this._parseDictionary(this._bytes.subarray(offset, offset + size)), parentDictionary.strings); //eslint-disable-line
        parentDictionary.privateDictionary = privateDictionary;
        if (privateDictionary._getByName('ExpansionFactor') === 0) {
            privateDictionary._setByName('ExpansionFactor', 0.06);
        }
        if (!privateDictionary._getByName('Subrs')) {
            return;
        }
        var subrsOffset = privateDictionary._getByName('Subrs'); //eslint-disable-line
        var relativeOffset = offset + subrsOffset; //eslint-disable-line
        if (subrsOffset === 0 || relativeOffset >= this._bytes.length) {
            this._emptyPrivateDictionary(parentDictionary);
            return;
        }
        var subroutineIndex = this._parseIndex(relativeOffset); //eslint-disable-line
        privateDictionary.subroutineIndex = subroutineIndex.obj;
    };
    _PdfCompactFontParser.prototype._parse = function (properties) {
        var compactFontFormat = new _PdfCompactFormatFont();
        this._compactFontFormat = compactFontFormat;
        var header = this._parseHeader(); //eslint-disable-line
        var nameIndex = this._parseIndex(header.endPos); //eslint-disable-line
        var topDictIndex = this._parseIndex(nameIndex.endPos); //eslint-disable-line
        var stringIndex = this._parseIndex(topDictIndex.endPos); //eslint-disable-line
        var globalSubroutineIndex = this._parseIndex(stringIndex.endPos); //eslint-disable-line
        var topDictParsed = this._parseDictionary(topDictIndex.obj._get(0)); //eslint-disable-line
        var topDict = this._createDictionary(_PdfCompactFontTopDictionary, topDictParsed, compactFontFormat.strings); //eslint-disable-line
        compactFontFormat.header = header.obj;
        compactFontFormat.names = this._parseNameIndex(nameIndex.obj);
        compactFontFormat.strings = this._parseStringIndex(stringIndex.obj);
        compactFontFormat.topDictionary = topDict;
        compactFontFormat.globalSubroutineIndex = globalSubroutineIndex.obj;
        this._parsePrivateDictionary(compactFontFormat.topDictionary);
        compactFontFormat.isCharacterIdentifierFont = topDict._hasName('ROS');
        var charStringOffset = topDict._getByName('CharStrings'); //eslint-disable-line
        var charStringIndex = this._parseIndex(charStringOffset).obj; //eslint-disable-line
        var fontMatrix = topDict._getByName('FontMatrix'); //eslint-disable-line
        if (fontMatrix) {
            properties._fontStructure._fontMatrix = fontMatrix;
        }
        var fontBBox = topDict._getByName('FontBBox'); //eslint-disable-line
        if (fontBBox) {
            properties.ascent = Math.max(fontBBox[3], fontBBox[1]);
            properties.descent = Math.min(fontBBox[1], fontBBox[3]);
            properties.ascentScaled = true;
        }
        var charSet; //eslint-disable-line
        var encoding; //eslint-disable-line
        if (compactFontFormat.isCharacterIdentifierFont) {
            var fontDictionaryArrayIndex = this._parseIndex(topDict._getByName('FDArray')).obj; //eslint-disable-line
            for (var i = 0, ii = fontDictionaryArrayIndex.count; i < ii; ++i) {
                var dictRaw = fontDictionaryArrayIndex._get(i); //eslint-disable-line
                var fontDict = this._createDictionary(//eslint-disable-line
                _PdfCompactFontTopDictionary, this._parseDictionary(dictRaw), compactFontFormat.strings);
                this._parsePrivateDictionary(fontDict);
                compactFontFormat.fontDictionaryArray.push(fontDict);
            }
            encoding = null;
            charSet = this._parseCharSets(topDict._getByName('charSet'), charStringIndex.count, compactFontFormat.strings, true);
            compactFontFormat.fontDictionarySelect = this._parseFontDictionarySelect(topDict._getByName('FDSelect'), charStringIndex.count);
        }
        else {
            charSet = this._parseCharSets(topDict._getByName('charSet'), charStringIndex.count, compactFontFormat.strings, false);
            encoding = this._parseEncoding(topDict._getByName('Encoding'), this._properties, compactFontFormat.strings, charSet.charSet);
        }
        compactFontFormat.charSet = charSet;
        compactFontFormat.encoding = encoding;
        var charStringsAndSeacs = this._parseCharStrings(//eslint-disable-line
        charStringIndex, topDict.privateDictionary.subroutineIndex, globalSubroutineIndex.obj, compactFontFormat.fontDictionarySelect, compactFontFormat.fontDictionaryArray, topDict.privateDictionary);
        compactFontFormat.charStrings = charStringsAndSeacs.charStrings;
        compactFontFormat.standardEncodingChars = charStringsAndSeacs.standardEncodingChars;
        compactFontFormat.widths = charStringsAndSeacs.widths;
        return compactFontFormat;
    };
    _PdfCompactFontParser.prototype._parseCharStrings = function (charStrings, localSubroutineIndex, globalSubroutineIndex, fontDictionarySelect, fontDictionaryArray, //eslint-disable-line
    privateDictionary) {
        var count = charStrings.count;
        for (var i = 0; i < count; i++) {
            var charstring = charStrings._get(i); //eslint-disable-line
            var state = {
                callDepth: 0,
                stackSize: 0,
                stack: [],
                undefStack: true,
                hints: 0,
                firstStackClearing: true,
                standardCharacter: null,
                width: null,
                hasVStems: false
            };
            var valid = true;
            var localSubrToUse = null; //eslint-disable-line
            var dictionaryToUse = privateDictionary; //eslint-disable-line
            if (fontDictionarySelect && fontDictionaryArray.length) {
                var fontDictionaryIndex = fontDictionarySelect.getFDIndex(i);
                if (fontDictionaryIndex === -1) {
                    //warn('Glyph index is not in font dictionary select.');
                    valid = false;
                }
                if (fontDictionaryIndex >= fontDictionaryArray.length) {
                    //warn('Invalid font dictionary index for glyph index.');
                    valid = false;
                }
                if (valid) {
                    dictionaryToUse = fontDictionaryArray[Number.parseInt(fontDictionaryIndex.toString(), 10)].privateDictionary;
                    localSubrToUse = dictionaryToUse.subroutineIndex;
                }
            }
            else if (localSubroutineIndex) {
                localSubrToUse = localSubroutineIndex;
            }
            if (valid) {
                valid = this._parseCharString(state, charstring, localSubrToUse, globalSubroutineIndex);
            }
            if (state.width !== null) {
                var nominalWidth = dictionaryToUse._getByName('nominalWidthX');
                this._widths[Number.parseInt(i.toString(), 10)] = nominalWidth + state.width;
            }
            else {
                var defaultWidth = dictionaryToUse._getByName('defaultWidthX'); //eslint-disable-line
                this._widths[Number.parseInt(i.toString(), 10)] = defaultWidth;
            }
            if (state.standardCharacter !== null) {
                this._standardEncodingChars[Number.parseInt(i.toString(), 10)] = state.standardCharacter;
            }
            if (!valid) {
                // resetting invalid charstring to single 'endchar'
                charStrings.set(i, new Uint8Array([14]));
            }
        }
        return { charStrings: charStrings, this: this._standardEncodingChars, widths: this._widths };
    };
    _PdfCompactFontParser.prototype._parseFontDictionarySelect = function (pos, length) {
        var bytes = this._bytes; //eslint-disable-line
        var format = bytes[pos++]; //eslint-disable-line
        var fontDictionarySelect = []; //eslint-disable-line
        var i;
        var rangesCount;
        switch (format) {
            case 0:
                for (i = 0; i < length; ++i) {
                    var id = bytes[pos++]; //eslint-disable-line
                    fontDictionarySelect.push(id);
                }
                break;
            case 3:
                rangesCount = (bytes[pos++] << 8) | bytes[pos++];
                for (i = 0; i < rangesCount; ++i) {
                    var first = (bytes[pos++] << 8) | bytes[pos++];
                    if (i === 0 && first !== 0) {
                        first = 0;
                    }
                    var fontDictionaryIndex = bytes[pos++]; //eslint-disable-line
                    var next = (bytes[Number.parseInt(pos.toString(), 10)] << 8) | bytes[pos + 1];
                    for (var j = first; j < next; ++j) {
                        fontDictionarySelect.push(fontDictionaryIndex);
                    }
                }
                pos += 2;
                break;
            default:
                throw new FormatError("parseFDSelect: Unknown format '" + format + "'.");
        }
        if (fontDictionarySelect.length !== length) {
            throw new FormatError('parseFDSelect: Invalid font data.');
        }
        return new _PdfCompactFontSelect(format, fontDictionarySelect);
    };
    _PdfCompactFontParser.prototype._parseCharSets = function (pos, length, strings, characterIdentifier) {
        if (pos === 0) {
            return new _PdfCompactFontCharacterSet(true, this._compactCharSetPredefinedTypes.standard, this._standardCharSet);
        }
        else if (pos === 1) {
            return new _PdfCompactFontCharacterSet(true, this._compactCharSetPredefinedTypes.expert, this._expertCharSet);
        }
        else if (pos === 2) {
            return new _PdfCompactFontCharacterSet(true, this._compactCharSetPredefinedTypes.expertSubset, this._expertSubsetCharSet);
        }
        var bytes = this._bytes; //eslint-disable-line
        var start = pos;
        var format = bytes[pos++]; //eslint-disable-line
        var charSet = [characterIdentifier ? 0 : '.notdef']; //eslint-disable-line
        var id;
        var count;
        var i;
        length -= 1;
        switch (format) {
            case 0:
                for (i = 0; i < length; i++) {
                    id = (bytes[pos++] << 8) | bytes[pos++];
                    charSet.push(characterIdentifier ? id : strings._get(id));
                }
                break;
            case 1:
                while (charSet.length <= length) {
                    id = (bytes[pos++] << 8) | bytes[pos++];
                    count = bytes[pos++];
                    for (i = 0; i <= count; i++) {
                        charSet.push(characterIdentifier ? id++ : strings._get(id++));
                    }
                }
                break;
            case 2:
                while (charSet.length <= length) {
                    id = (bytes[pos++] << 8) | bytes[pos++];
                    count = (bytes[pos++] << 8) | bytes[pos++];
                    for (i = 0; i <= count; i++) {
                        charSet.push(characterIdentifier ? id++ : strings._get(id++));
                    }
                }
                break;
            default:
                throw new FormatError('Unknown charSet format');
        }
        var end = pos;
        var raw = bytes.subarray(start, end); //eslint-disable-line
        return new _PdfCompactFontCharacterSet(false, format, charSet, raw);
    };
    _PdfCompactFontParser.prototype._readSupplement = function (bytes, pos, encoding, charSet, strings) {
        ; //eslint-disable-line
        var supplementsCount = bytes[pos++];
        for (var i = 0; i < supplementsCount; i++) {
            var code = bytes[pos++]; //eslint-disable-line
            var sid = (bytes[pos++] << 8) + (bytes[pos++] & 0xff); //eslint-disable-line
            encoding[Number.parseInt(code.toString(), 10)] = charSet.indexOf(strings._get(sid));
        }
        return encoding;
    };
    _PdfCompactFontParser.prototype._parseEncoding = function (pos, properties, strings, charSet) {
        var encoding = Object.create(null); //eslint-disable-line
        var bytes = this._bytes; //eslint-disable-line
        var predefined = false;
        var format;
        var i;
        var ii;
        var raw = null; //eslint-disable-line
        if (pos === 0 || pos === 1) {
            predefined = true;
            format = pos;
            var baseEncoding = pos ? _expertEncoding : _standardEncoding;
            for (i = 0, ii = charSet.length; i < ii; i++) {
                var index = baseEncoding.indexOf(charSet[Number.parseInt(i.toString(), 10)]);
                if (index !== -1) {
                    encoding[Number.parseInt(index.toString(), 10)] = i;
                }
            }
        }
        else {
            var dataStart = pos;
            format = bytes[pos++];
            var rangesCount = void 0;
            var glyphsCount = void 0;
            var gid = void 0;
            switch (format & 0x7f) {
                case 0:
                    glyphsCount = bytes[pos++];
                    for (i = 1; i <= glyphsCount; i++) {
                        encoding[bytes[pos++]] = i;
                    }
                    break;
                case 1:
                    rangesCount = bytes[pos++];
                    gid = 1;
                    for (i = 0; i < rangesCount; i++) {
                        var start = bytes[pos++];
                        var left = bytes[pos++];
                        for (var j = start; j <= start + left; j++) {
                            encoding[Number.parseInt(j.toString(), 10)] = gid++;
                        }
                    }
                    break;
                default:
                    throw new FormatError("Unknown encoding format: " + format + " in compactFont");
            }
            var dataEnd = pos;
            if (format & 0x80) {
                bytes[Number.parseInt(dataStart.toString(), 10)] &= 0x7f;
                encoding = this._readSupplement(bytes, pos, encoding, charSet, strings);
            }
            raw = bytes.subarray(dataStart, dataEnd);
        }
        format &= 0x7f;
        return new _PdfCompactFontEncoding(predefined, format, encoding, raw);
    };
    _PdfCompactFontParser.prototype._parseHeader = function () {
        var bytes = this._bytes; //eslint-disable-line
        var bytesLength = bytes.length;
        var offset = 0;
        while (offset < bytesLength && bytes[Number.parseInt(offset.toString(), 10)] !== 1) {
            ++offset;
        }
        if (offset >= bytesLength) {
            throw new FormatError('Invalid compactFont header');
        }
        if (offset !== 0) {
            bytes = bytes.subarray(offset);
            this._bytes = bytes;
        }
        var major = bytes[0]; //eslint-disable-line
        var minor = bytes[1]; //eslint-disable-line
        var headerSize = bytes[2]; //eslint-disable-line
        var offSize = bytes[3]; //eslint-disable-line
        var header = new _PdfCompactFontHeader(major, minor, headerSize, offSize);
        return { obj: header, endPos: headerSize };
    };
    _PdfCompactFontParser.prototype._parseOperand = function (dictionary) {
        var value = dictionary[this._pos++];
        if (value === 30) {
            return this._parseFloatOperand(dictionary);
        }
        else if (value === 28) {
            value = dictionary[this._pos++];
            value = ((value << 24) | (dictionary[this._pos++] << 16)) >> 16;
            return value;
        }
        else if (value === 29) {
            value = dictionary[this._pos++];
            value = (value << 8) | dictionary[this._pos++];
            value = (value << 8) | dictionary[this._pos++];
            value = (value << 8) | dictionary[this._pos++];
            return value;
        }
        else if (value >= 32 && value <= 246) {
            return value - 139;
        }
        else if (value >= 247 && value <= 250) {
            return (value - 247) * 256 + dictionary[this._pos++] + 108;
        }
        else if (value >= 251 && value <= 254) {
            return -((value - 251) * 256) - dictionary[this._pos++] - 108;
        }
        return NaN;
    };
    _PdfCompactFontParser.prototype._parseFloatOperand = function (dictionary) {
        var str = '';
        var eof = 15;
        var lookup = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', 'E', 'E-', null, '-']; //eslint-disable-line
        var length = dictionary.length;
        while (this._pos < length) {
            var b = dictionary[this._pos++];
            var b1 = b >> 4;
            var b2 = b & 15;
            if (b1 === eof) {
                break;
            }
            str += lookup[Number.parseInt(b1.toString(), 10)];
            if (b2 === eof) {
                break;
            }
            str += lookup[Number.parseInt(b2.toString(), 10)];
        }
        return parseFloat(str);
    };
    _PdfCompactFontParser.prototype._parseDictionary = function (dictionary) {
        var operands = [];
        var entries = [];
        var end = dictionary.length;
        this._pos = 0;
        while (this._pos < end) {
            var b = dictionary[this._pos];
            if (b <= 21) {
                if (b === 12) {
                    b = (b << 8) | dictionary[++this._pos];
                }
                entries.push([b, operands]);
                operands = [];
                ++this._pos;
            }
            else {
                operands.push(this._parseOperand(dictionary));
            }
        }
        return entries;
    };
    _PdfCompactFontParser.prototype._parseIndex = function (pos) {
        var compactFontIndex = new _PdfCompactFontIndex();
        var bytes = this._bytes; //eslint-disable-line
        var count = (bytes[pos++] << 8) | bytes[pos++];
        var offsets = [];
        var end = pos;
        if (count !== 0) {
            var offsetSize = bytes[pos++];
            var startPos = pos + (count + 1) * offsetSize - 1;
            for (var i = 0, ii = count + 1; i < ii; ++i) {
                var offset = 0;
                for (var j = 0; j < offsetSize; ++j) {
                    offset <<= 8;
                    offset += bytes[pos++];
                }
                offsets.push(startPos + offset);
            }
            end = offsets[Number.parseInt(count.toString(), 10)];
        }
        for (var i = 0, ii = offsets.length - 1; i < ii; ++i) {
            var offsetStart = offsets[Number.parseInt(i.toString(), 10)];
            var offsetEnd = offsets[i + 1];
            compactFontIndex.add(bytes.subarray(offsetStart, offsetEnd));
        }
        return { obj: compactFontIndex, endPos: end };
    };
    _PdfCompactFontParser.prototype._parseNameIndex = function (index) {
        var names = [];
        for (var i = 0, ii = index.count; i < ii; ++i) {
            var name_1 = index._get(i); //eslint-disable-line
            names.push(_bytesToString(name_1));
        }
        return names;
    };
    _PdfCompactFontParser.prototype._parseStringIndex = function (index) {
        var strings = new _PdfCompactFontStrings();
        for (var i = 0, ii = index.count; i < ii; ++i) {
            var data = index._get(i); //eslint-disable-line
            strings._add(_bytesToString(data));
        }
        return strings;
    };
    _PdfCompactFontParser.prototype._createDictionary = function (type, dictionary, strings) {
        var compactFontDict = new type(strings); //eslint-disable-line
        for (var _i = 0, dictionary_1 = dictionary; _i < dictionary_1.length; _i++) {
            var _a = dictionary_1[_i], key = _a[0], value = _a[1];
            compactFontDict._setByKey(key, value);
        }
        return compactFontDict;
    };
    _PdfCompactFontParser.prototype._parseCharString = function (state, //eslint-disable-line
    data, localSubroutineIndex, globalSubroutineIndex) {
        if (!data || state.callDepth > 1000) {
            return false;
        }
        var stackSize = state.stackSize;
        var stack = state.stack; //eslint-disable-line
        var length = data.length;
        for (var j = 0; j < length;) {
            var value = data[j++];
            var validationCommand = null; //eslint-disable-line
            if (value === 12) {
                var q = data[j++];
                if (q === 0) {
                    data[j - 2] = 139;
                    data[j - 1] = 22;
                    stackSize = 0;
                }
                else {
                    validationCommand = this._characterValidationData12[Number.parseInt(q.toString(), 10)];
                }
            }
            else if (value === 28) {
                stack[Number.parseInt(stackSize.toString(), 10)] = ((data[Number.parseInt(j.toString(), 10)] << 24) |
                    (data[j + 1] << 16)) >> 16;
                j += 2;
                stackSize++;
            }
            else if (value === 14) {
                if (stackSize >= 4) {
                    stackSize -= 4;
                    if (this._isAnalysisEnabled) {
                        state.standardCharacter = stack.slice(stackSize, stackSize + 4);
                        return false;
                    }
                }
                validationCommand = this._characterValidationData[Number.parseInt(value.toString(), 10)];
            }
            else if (value >= 32 && value <= 246) {
                stack[Number.parseInt(stackSize.toString(), 10)] = value - 139;
                stackSize++;
            }
            else if (value >= 247 && value <= 254) {
                stack[Number.parseInt(stackSize.toString(), 10)] = value < 251
                    ? ((value - 247) << 8) + data[Number.parseInt(j.toString(), 10)] + 108
                    : -((value - 251) << 8) - data[Number.parseInt(j.toString(), 10)] - 108;
                j++;
                stackSize++;
            }
            else if (value === 255) {
                stack[Number.parseInt(stackSize.toString(), 10)] = ((data[Number.parseInt(j.toString(), 10)] << 24) |
                    (data[j + 1] << 16) |
                    (data[j + 2] << 8) |
                    data[j + 3]) / 65536;
                j += 4;
                stackSize++;
            }
            else if (value === 19 || value === 20) {
                state.hints += stackSize >> 1;
                if (state.hints === 0) {
                    data.copyWithin(j - 1, j, -1);
                    j -= 1;
                    length -= 1;
                    continue;
                }
                j += (state.hints + 7) >> 3;
                stackSize %= 2;
                validationCommand = this._characterValidationData[Number.parseInt(value.toString(), 10)];
            }
            else if (value === 10 || value === 29) {
                var subroutineIndex = value === 10 ? localSubroutineIndex : globalSubroutineIndex; //eslint-disable-line
                if (!subroutineIndex) {
                    validationCommand = this._characterValidationData[Number.parseInt(value.toString(), 10)];
                    return false;
                }
                var bias = 32768;
                if (subroutineIndex.count < 1240) {
                    bias = 107;
                }
                else if (subroutineIndex.count < 33900) {
                    bias = 1131;
                }
                var subrNumber = stack[--stackSize] + bias;
                if (subrNumber < 0 || subrNumber >= subroutineIndex.count || isNaN(subrNumber)) {
                    validationCommand = this._characterValidationData[Number.parseInt(value.toString(), 10)];
                    return false;
                }
                state.stackSize = stackSize;
                state.callDepth++;
                var valid = this._parseCharString(state, subroutineIndex._get(subrNumber), localSubroutineIndex, globalSubroutineIndex);
                if (!valid) {
                    return false;
                }
                state.callDepth--;
                stackSize = state.stackSize;
                continue;
            }
            else if (value === 11) {
                state.stackSize = stackSize;
                return true;
            }
            else if (value === 0 && j === data.length) {
                data[j - 1] = 14;
                validationCommand = this._characterValidationData[14];
            }
            else if (value === 9) {
                data.copyWithin(j - 1, j, -1);
                j -= 1;
                length -= 1;
                continue;
            }
            else {
                validationCommand = this._characterValidationData[Number.parseInt(value.toString(), 10)];
            }
            if (validationCommand) {
                if (validationCommand.stem) {
                    state.hints += stackSize >> 1;
                    if (value === 3 || value === 23) {
                        state.hasVStems = true;
                    }
                    else if (state.hasVStems && (value === 1 || value === 18)) {
                        data[j - 1] = value === 1 ? 3 : 23;
                    }
                }
                if ('min' in validationCommand) {
                    if (!state.undefStack && stackSize < validationCommand.min) {
                        if (stackSize === 0) {
                            data[j - 1] = 14;
                            return true;
                        }
                        return false;
                    }
                }
                if (state.firstStackClearing && validationCommand.stackClearing) {
                    state.firstStackClearing = false;
                    stackSize -= validationCommand.min;
                    if (stackSize >= 2 && validationCommand.stem) {
                        stackSize %= 2;
                    }
                    if (stackSize > 0) {
                        state.width = stack[stackSize - 1];
                    }
                }
                if ('stackDelta' in validationCommand) {
                    if ('stackFn' in validationCommand) {
                        validationCommand.stackFn(stack, stackSize);
                    }
                    stackSize += validationCommand.stackDelta;
                }
                else if (validationCommand.stackClearing) {
                    stackSize = 0;
                }
                else if (validationCommand.resetStack) {
                    stackSize = 0;
                    state.undefStack = false;
                }
                else if (validationCommand.undefStack) {
                    stackSize = 0;
                    state.undefStack = true;
                    state.firstStackClearing = false;
                }
            }
        }
        if (length < data.length) {
            data.fill(/* endchar = */ 14, length);
        }
        state.stackSize = stackSize;
        return true;
    };
    _PdfCompactFontParser.prototype._emptyPrivateDictionary = function (parentDictionary) {
        var privateDictionary = this._createDictionary(_PdfCompactFontPrivateDictionary, [], parentDictionary.strings); //eslint-disable-line
        parentDictionary._setByKey(18, [0, 0]);
        parentDictionary.privateDictionary = privateDictionary;
    };
    return _PdfCompactFontParser;
}());
export { _PdfCompactFontParser };
var _PdfCompactFormatFont = /** @class */ (function () {
    function _PdfCompactFormatFont() {
        this.isCharacterIdentifierFont = false;
        this.standardEncodingChars = []; //eslint-disable-line
        this.widths = []; //eslint-disable-line
        this.header = null;
        this.names = [];
        this.topDictionary = null;
        this.strings = new _PdfCompactFontStrings();
        this.globalSubroutineIndex = null;
        this.encoding = null;
        this.charSet = null;
        this.charStrings = null;
        this.fontDictionaryArray = [];
        this.fontDictionarySelect = null;
        this.isCharacterIdentifierFont = false;
    }
    _PdfCompactFormatFont.prototype._duplicateFirstGlyph = function () {
        if (this.charStrings.count >= 65535) {
            return;
        }
        var glyphZero = this.charStrings._get(0); //eslint-disable-line
        this.charStrings.add(glyphZero);
        if (this.isCharacterIdentifierFont) {
            this.fontDictionarySelect.fontDictionarySelect.push(this.fontDictionarySelect.fontDictionarySelect[0]);
        }
    };
    _PdfCompactFormatFont.prototype._hasGlyphId = function (id) {
        if (id < 0 || id >= this.charStrings.count) {
            return false;
        }
        var glyph = this.charStrings._get(id); //eslint-disable-line
        return glyph.length > 0;
    };
    return _PdfCompactFormatFont;
}());
export { _PdfCompactFormatFont };
var _PdfCompactFontHeader = /** @class */ (function () {
    function _PdfCompactFontHeader(major, minor, headerSize, offSize) {
        this.major = major;
        this.minor = minor;
        this.headerSize = headerSize;
        this.offSize = offSize;
    }
    return _PdfCompactFontHeader;
}());
export { _PdfCompactFontHeader };
var _PdfCompactFontStrings = /** @class */ (function () {
    function _PdfCompactFontStrings() {
        this._numberOfStandardCompactFontStrings = 391;
        this._compactFontStandardStrings = [
            '.notdef', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent',
            'ampersand', 'quoteright', 'parenleft', 'parenright', 'asterisk', 'plus',
            'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four',
            'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less',
            'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
            'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
            'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum',
            'underscore', 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
            'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
            'z', 'braceleft', 'bar', 'braceright', 'asciitilde', 'exclamdown', 'cent',
            'sterling', 'fraction', 'yen', 'florin', 'section', 'currency',
            'quotesingle', 'quotedblleft', 'guillemotleft', 'guilsinglleft',
            'guilsinglright', 'fi', 'fl', 'endash', 'dagger', 'daggerdbl',
            'periodcentered', 'paragraph', 'bullet', 'quotesinglbase', 'quotedblbase',
            'quotedblright', 'guillemotright', 'ellipsis', 'perthousand', 'questiondown',
            'grave', 'acute', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent',
            'dieresis', 'ring', 'cedilla', 'hungarumlaut', 'ogonek', 'caron', 'emdash',
            'AE', 'ordfeminine', 'Lslash', 'Oslash', 'OE', 'ordmasculine', 'ae',
            'dotlessi', 'lslash', 'oslash', 'oe', 'germandbls', 'onesuperior',
            'logicalnot', 'mu', 'trademark', 'Eth', 'onehalf', 'plusminus', 'Thorn',
            'onequarter', 'divide', 'brokenbar', 'degree', 'thorn', 'threequarters',
            'twosuperior', 'registered', 'minus', 'eth', 'multiply', 'threesuperior',
            'copyright', 'Aacute', 'Acircumflex', 'Adieresis', 'Agrave', 'Aring',
            'Atilde', 'Ccedilla', 'Eacute', 'Ecircumflex', 'Edieresis', 'Egrave',
            'Iacute', 'Icircumflex', 'Idieresis', 'Igrave', 'Ntilde', 'Oacute',
            'Ocircumflex', 'Odieresis', 'Ograve', 'Otilde', 'Scaron', 'Uacute',
            'Ucircumflex', 'Udieresis', 'Ugrave', 'Yacute', 'Ydieresis', 'Zcaron',
            'aacute', 'acircumflex', 'adieresis', 'agrave', 'aring', 'atilde',
            'ccedilla', 'eacute', 'ecircumflex', 'edieresis', 'egrave', 'iacute',
            'icircumflex', 'idieresis', 'igrave', 'ntilde', 'oacute', 'ocircumflex',
            'odieresis', 'ograve', 'otilde', 'scaron', 'uacute', 'ucircumflex',
            'udieresis', 'ugrave', 'yacute', 'ydieresis', 'zcaron', 'exclamsmall',
            'Hungarumlautsmall', 'dollaroldstyle', 'dollarsuperior', 'ampersandsmall',
            'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader',
            'onedotenleader', 'zerooldstyle', 'oneoldstyle', 'twooldstyle',
            'threeoldstyle', 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle',
            'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'commasuperior',
            'threequartersemdash', 'periodsuperior', 'questionsmall', 'asuperior',
            'bsuperior', 'centsuperior', 'dsuperior', 'esuperior', 'isuperior',
            'lsuperior', 'msuperior', 'nsuperior', 'osuperior', 'rsuperior', 'ssuperior',
            'tsuperior', 'ff', 'ffi', 'ffl', 'parenleftinferior', 'parenrightinferior',
            'Circumflexsmall', 'hyphensuperior', 'Gravesmall', 'Asmall', 'Bsmall',
            'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall',
            'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall', 'Osmall', 'Psmall',
            'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall',
            'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah',
            'Tildesmall', 'exclamdownsmall', 'centoldstyle', 'Lslashsmall',
            'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', 'Brevesmall', 'Caronsmall',
            'Dotaccentsmall', 'Macronsmall', 'figuredash', 'hypheninferior',
            'Ogoneksmall', 'Ringsmall', 'Cedillasmall', 'questiondownsmall', 'oneeighth',
            'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds',
            'zerosuperior', 'foursuperior', 'fivesuperior', 'sixsuperior',
            'sevensuperior', 'eightsuperior', 'ninesuperior', 'zeroinferior',
            'oneinferior', 'twoinferior', 'threeinferior', 'fourinferior',
            'fiveinferior', 'sixinferior', 'seveninferior', 'eightinferior',
            'nineinferior', 'centinferior', 'dollarinferior', 'periodinferior',
            'commainferior', 'Agravesmall', 'Aacutesmall', 'Acircumflexsmall',
            'Atildesmall', 'Adieresissmall', 'Aringsmall', 'AEsmall', 'Ccedillasmall',
            'Egravesmall', 'Eacutesmall', 'Ecircumflexsmall', 'Edieresissmall',
            'Igravesmall', 'Iacutesmall', 'Icircumflexsmall', 'Idieresissmall',
            'Ethsmall', 'Ntildesmall', 'Ogravesmall', 'Oacutesmall', 'Ocircumflexsmall',
            'Otildesmall', 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall',
            'Uacutesmall', 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall',
            'Thornsmall', 'Ydieresissmall', '001.000', '001.001', '001.002', '001.003',
            'Black', 'Bold', 'Book', 'Light', 'Medium', 'Regular', 'Roman', 'Semibold'
        ];
        this.strings = [];
    }
    _PdfCompactFontStrings.prototype._get = function (index) {
        if (index >= 0 && index <= this._numberOfStandardCompactFontStrings - 1) {
            return this._compactFontStandardStrings[Number.parseInt(index.toString(), 10)];
        }
        if (index - this._numberOfStandardCompactFontStrings <= this.strings.length) {
            return this.strings[index - this._numberOfStandardCompactFontStrings];
        }
        return this._compactFontStandardStrings[0];
    };
    _PdfCompactFontStrings.prototype._fetchStringIdentifier = function (text) {
        var index = this._compactFontStandardStrings.indexOf(text);
        if (index !== -1) {
            return index;
        }
        index = this.strings.indexOf(text);
        if (index !== -1) {
            return index + this._numberOfStandardCompactFontStrings;
        }
        return -1;
    };
    _PdfCompactFontStrings.prototype._add = function (value) {
        this.strings.push(value);
    };
    Object.defineProperty(_PdfCompactFontStrings.prototype, "count", {
        get: function () {
            return this.strings.length;
        },
        enumerable: true,
        configurable: true
    });
    return _PdfCompactFontStrings;
}());
export { _PdfCompactFontStrings };
var _PdfCompactFontIndex = /** @class */ (function () {
    function _PdfCompactFontIndex() {
        this.objects = [];
        this.length = 0;
    }
    _PdfCompactFontIndex.prototype.add = function (data) {
        this.length += data.length;
        this.objects.push(data);
    };
    _PdfCompactFontIndex.prototype.set = function (index, data) {
        this.length += data.length - this.objects[Number.parseInt(index.toString(), 10)].length;
        this.objects[Number.parseInt(index.toString(), 10)] = data;
    };
    _PdfCompactFontIndex.prototype._get = function (index) {
        return this.objects[Number.parseInt(index.toString(), 10)];
    };
    Object.defineProperty(_PdfCompactFontIndex.prototype, "count", {
        get: function () {
            return this.objects.length;
        },
        enumerable: true,
        configurable: true
    });
    return _PdfCompactFontIndex;
}());
export { _PdfCompactFontIndex };
var _PdfCompactFontDictionary = /** @class */ (function () {
    function _PdfCompactFontDictionary(tables, strings) {
        this.values = Object.create(null); //eslint-disable-line
        this.keyToNameMap = tables.keyToNameMap;
        this.nameToKeyMap = tables.nameToKeyMap;
        this.defaults = tables.defaults;
        this.types = tables.types;
        this.opcodes = tables.opcodes;
        this.order = tables.order;
        this.strings = strings;
        this.values = Object.create(null);
    }
    _PdfCompactFontDictionary.prototype._setByKey = function (key, value) {
        if (!this.keyToNameMap && (key in this.keyToNameMap)) {
            return false;
        }
        if (value.length === 0) {
            return true;
        }
        for (var _i = 0, value_1 = value; _i < value_1.length; _i++) {
            var val = value_1[_i];
            if (isNaN(val)) {
                return true;
            }
        }
        var type = this.types[key]; //eslint-disable-line
        if (type === 'num' || type === 'sid' || type === 'offset') {
            value = value[0];
        }
        this.values[Number.parseInt(key.toString(), 10)] = value;
        return true;
    };
    _PdfCompactFontDictionary.prototype._setByName = function (name, value) {
        if (!(name in this.nameToKeyMap)) {
            throw new FormatError("Invalid dictionary name '" + name + "'");
        }
        this.values[this.nameToKeyMap[Number.parseInt(name.toString(), 10)]] = value;
    };
    _PdfCompactFontDictionary.prototype._hasName = function (name) {
        return this.nameToKeyMap[Number.parseInt(name.toString(), 10)] in this.values;
    };
    _PdfCompactFontDictionary.prototype._getByName = function (name) {
        if (!(name in this.nameToKeyMap)) {
            throw new FormatError("Invalid dictionary name " + name + "'");
        }
        var key = this.nameToKeyMap[name]; //eslint-disable-line
        if (!(key in this.values)) {
            return this.defaults[key]; // eslint-disable-line
        }
        return this.values[key]; //eslint-disable-line
    };
    _PdfCompactFontDictionary.prototype._removeByName = function (name) {
        delete this.values[this.nameToKeyMap[Number.parseInt(name.toString(), 10)]];
    };
    _PdfCompactFontDictionary.prototype._createTables = function (layout) {
        var tables = {
            keyToNameMap: {},
            nameToKeyMap: {},
            defaults: {},
            types: {},
            opcodes: {},
            order: []
        };
        for (var _i = 0, layout_1 = layout; _i < layout_1.length; _i++) {
            var entry = layout_1[_i];
            var key = Array.isArray(entry[0]) //eslint-disable-line
                ? (entry[0][0] << 8) + entry[0][1]
                : entry[0];
            tables.keyToNameMap[Number.parseInt(key.toString(), 10)] = entry[1];
            tables.nameToKeyMap[entry[1]] = key;
            tables.types[Number.parseInt(key.toString(), 10)] = entry[2];
            tables.defaults[Number.parseInt(key.toString(), 10)] = entry[3];
            tables.opcodes[Number.parseInt(key.toString(), 10)] = Array.isArray(entry[0]) ? entry[0] : [entry[0]];
            tables.order.push(key);
        }
        return tables;
    };
    return _PdfCompactFontDictionary;
}());
export { _PdfCompactFontDictionary };
var _PdfCompactFontTopDictionary = /** @class */ (function (_super) {
    __extends(_PdfCompactFontTopDictionary, _super);
    function _PdfCompactFontTopDictionary(strings) {
        var _this = _super.call(this, _PdfCompactFontTopDictionary._createTables(), strings) || this;
        _this.privateDictionary = null;
        return _this;
    }
    Object.defineProperty(_PdfCompactFontTopDictionary, "_tables", {
        get: function () {
            return _defineProperty(this, 'tables', _PdfCompactFontTopDictionary._createTables());
        },
        enumerable: true,
        configurable: true
    });
    _PdfCompactFontTopDictionary._createTables = function () {
        var layout = [
            [[12, 30], 'ROS', ['sid', 'sid', 'num'], null],
            [[12, 20], 'SyntheticBase', 'num', null],
            [0, 'version', 'sid', null],
            [1, 'Notice', 'sid', null],
            [[12, 0], 'Copyright', 'sid', null],
            [2, 'FullName', 'sid', null],
            [3, 'FamilyName', 'sid', null],
            [4, 'Weight', 'sid', null],
            [[12, 1], 'isFixedPitch', 'num', 0],
            [[12, 2], 'ItalicAngle', 'num', 0],
            [[12, 3], 'UnderlinePosition', 'num', -100],
            [[12, 4], 'UnderlineThickness', 'num', 50],
            [[12, 5], 'PaintType', 'num', 0],
            [[12, 6], 'CharstringType', 'num', 2],
            [[12, 7], 'FontMatrix', ['num', 'num', 'num', 'num', 'num', 'num'],
                [0.001, 0, 0, 0.001, 0, 0]],
            [13, 'UniqueID', 'num', null],
            [5, 'FontBBox', ['num', 'num', 'num', 'num'], [0, 0, 0, 0]],
            [[12, 8], 'StrokeWidth', 'num', 0],
            [14, 'XUID', 'array', null],
            [15, 'charSet', 'offset', 0],
            [16, 'Encoding', 'offset', 0],
            [17, 'CharStrings', 'offset', 0],
            [18, 'Private', ['offset', 'offset'], null],
            [[12, 21], 'PostScript', 'sid', null],
            [[12, 22], 'BaseFontName', 'sid', null],
            [[12, 23], 'BaseFontBlend', 'delta', null],
            [[12, 31], 'CIDFontVersion', 'num', 0],
            [[12, 32], 'CIDFontRevision', 'num', 0],
            [[12, 33], 'CIDFontType', 'num', 0],
            [[12, 34], 'CIDCount', 'num', 8720],
            [[12, 35], 'UIDBase', 'num', null],
            [[12, 37], 'FDSelect', 'offset', null],
            [[12, 36], 'FDArray', 'offset', null],
            [[12, 38], 'FontName', 'sid', null]
        ];
        var tables = {
            keyToNameMap: {},
            nameToKeyMap: {},
            defaults: {},
            types: {},
            opcodes: {},
            order: []
        };
        for (var _i = 0, layout_2 = layout; _i < layout_2.length; _i++) {
            var entry = layout_2[_i];
            var key = Array.isArray(entry[0]) //eslint-disable-line
                ? (entry[0][0] << 8) + entry[0][1]
                : entry[0];
            tables.keyToNameMap[Number.parseInt(key.toString(), 10)] = entry[1];
            tables.nameToKeyMap[entry[1]] = key;
            tables.types[Number.parseInt(key.toString(), 10)] = entry[2];
            tables.defaults[Number.parseInt(key.toString(), 10)] = entry[3];
            tables.opcodes[Number.parseInt(key.toString(), 10)] = Array.isArray(entry[0]) ? entry[0] : [entry[0]];
            tables.order.push(key);
        }
        return tables;
    };
    return _PdfCompactFontTopDictionary;
}(_PdfCompactFontDictionary));
export { _PdfCompactFontTopDictionary };
var _PdfCompactFontPrivateDictionary = /** @class */ (function (_super) {
    __extends(_PdfCompactFontPrivateDictionary, _super);
    function _PdfCompactFontPrivateDictionary(strings) {
        var _this = this;
        var layout = [
            [6, 'BlueValues', 'delta', null],
            [7, 'OtherBlues', 'delta', null],
            [8, 'FamilyBlues', 'delta', null],
            [9, 'FamilyOtherBlues', 'delta', null],
            [[12, 9], 'BlueScale', 'num', 0.039625],
            [[12, 10], 'BlueShift', 'num', 7],
            [[12, 11], 'BlueFuzz', 'num', 1],
            [10, 'StdHW', 'num', null],
            [11, 'StdVW', 'num', null],
            [[12, 12], 'StemSnapH', 'delta', null],
            [[12, 13], 'StemSnapV', 'delta', null],
            [[12, 14], 'ForceBold', 'num', 0],
            [[12, 17], 'LanguageGroup', 'num', 0],
            [[12, 18], 'ExpansionFactor', 'num', 0.06],
            [[12, 19], 'initialRandomSeed', 'num', 0],
            [20, 'defaultWidthX', 'num', 0],
            [21, 'nominalWidthX', 'num', 0],
            [19, 'Subrs', 'offset', null]
        ];
        var tables = {
            keyToNameMap: {},
            nameToKeyMap: {},
            defaults: {},
            types: {},
            opcodes: {},
            order: []
        };
        for (var _i = 0, layout_3 = layout; _i < layout_3.length; _i++) {
            var entry = layout_3[_i];
            var key = Array.isArray(entry[0]) //eslint-disable-line
                ? (entry[0][0] << 8) + entry[0][1]
                : entry[0];
            tables.keyToNameMap[Number.parseInt(key.toString(), 10)] = entry[1];
            tables.nameToKeyMap[entry[1]] = key;
            tables.types[Number.parseInt(key.toString(), 10)] = entry[2];
            tables.defaults[Number.parseInt(key.toString(), 10)] = entry[3];
            tables.opcodes[Number.parseInt(key.toString(), 10)] = Array.isArray(entry[0]) ? entry[0] : [entry[0]];
            tables.order.push(key);
        }
        _this = _super.call(this, tables, strings) || this;
        _this.tables = tables;
        _this.subroutineIndex = null;
        return _this;
    }
    return _PdfCompactFontPrivateDictionary;
}(_PdfCompactFontDictionary));
export { _PdfCompactFontPrivateDictionary };
var _PdfCompactFontCharacterSet = /** @class */ (function () {
    function _PdfCompactFontCharacterSet(predefined, format, charSet, raw) {
        this.predefined = predefined;
        this.format = format;
        this.charSet = charSet;
        this.raw = raw;
    }
    return _PdfCompactFontCharacterSet;
}());
export { _PdfCompactFontCharacterSet };
var _PdfCompactFontEncoding = /** @class */ (function () {
    function _PdfCompactFontEncoding(predefined, format, encoding, raw) {
        this.predefined = predefined;
        this.format = format;
        this.encoding = encoding;
        this.raw = raw;
    }
    return _PdfCompactFontEncoding;
}());
export { _PdfCompactFontEncoding };
var _PdfCompactFontSelect = /** @class */ (function () {
    function _PdfCompactFontSelect(format, fontDictionarySelect) {
        this.format = format;
        this.fontDictionarySelect = fontDictionarySelect;
    }
    _PdfCompactFontSelect.prototype._getFontDictionaryIndex = function (glyphIndex) {
        if (glyphIndex < 0 || glyphIndex >= this.fontDictionarySelect.length) {
            return -1;
        }
        return this.fontDictionarySelect[Number.parseInt(glyphIndex.toString(), 10)];
    };
    return _PdfCompactFontSelect;
}());
export { _PdfCompactFontSelect };
var _PdfCompactFontOffsetTracker = /** @class */ (function () {
    function _PdfCompactFontOffsetTracker() {
        this.offsets = Object.create(null);
    }
    _PdfCompactFontOffsetTracker.prototype._isTracking = function (key) {
        return key in this.offsets;
    };
    _PdfCompactFontOffsetTracker.prototype._track = function (key, location) {
        if (key in this.offsets) {
            throw new FormatError("Already tracking location of " + key);
        }
        this.offsets[Number.parseInt(key.toString(), 10)] = location;
    };
    _PdfCompactFontOffsetTracker.prototype._offset = function (value) {
        var keys = Object.keys(this.offsets); //eslint-disable-line
        for (var i = 0; i < keys.length; i++) {
            var key = keys[Number.parseInt(i.toString(), 10)]; //eslint-disable-line
            var numericKey = Number.parseInt(key, 10);
            this.offsets[Number.parseInt(numericKey.toString(), 10)] += value;
        }
    };
    _PdfCompactFontOffsetTracker.prototype._setEntryLocation = function (key, values, output) {
        if (!(key in this.offsets)) {
            throw new FormatError("Not tracking location of " + key);
        }
        var data = output.data; //eslint-disable-line
        var dataOffset = this.offsets[Number.parseInt(key.toString(), 10)];
        var size = 5;
        for (var i = 0, ii = values.length; i < ii; ++i) {
            var offset0 = i * size + dataOffset;
            var offset1 = offset0 + 1;
            var offset2 = offset0 + 2;
            var offset3 = offset0 + 3;
            var offset4 = offset0 + 4;
            if (data[Number.parseInt(offset0.toString(), 10)] !== 0x1d || data[Number.parseInt(offset1.toString(), 10)] !== 0 ||
                data[Number.parseInt(offset2.toString(), 10)] !== 0 || data[Number.parseInt(offset3.toString(), 10)] !== 0 ||
                data[Number.parseInt(offset4.toString(), 10)] !== 0) {
                throw new FormatError('writing to an offset that is not empty');
            }
            var value = values[Number.parseInt(i.toString(), 10)];
            data[Number.parseInt(offset0.toString(), 10)] = 0x1d;
            data[Number.parseInt(offset1.toString(), 10)] = (value >> 24) & 0xff;
            data[Number.parseInt(offset2.toString(), 10)] = (value >> 16) & 0xff;
            data[Number.parseInt(offset3.toString(), 10)] = (value >> 8) & 0xff;
            data[Number.parseInt(offset4.toString(), 10)] = value & 0xff;
        }
    };
    return _PdfCompactFontOffsetTracker;
}());
export { _PdfCompactFontOffsetTracker };
var _PdfCompactFontCompiler = /** @class */ (function () {
    function _PdfCompactFontCompiler(compactFont) {
        this.compactFont = compactFont;
    }
    _PdfCompactFontCompiler.prototype.compile = function () {
        var compactFont = this.compactFont; //eslint-disable-line
        var output = {
            data: [],
            length: 0,
            add: function (data) {
                var _a;
                try {
                    (_a = this.data).push.apply(_a, data);
                }
                catch (_b) {
                    this.data = this.data.concat(data);
                }
                this.length = this.data.length;
            }
        };
        var header = this._compileHeader(compactFont.header); //eslint-disable-line
        output.add(header);
        var nameIndex = this._compileNameIndex(compactFont.names); //eslint-disable-line
        output.add(nameIndex);
        if (compactFont.isCharacterIdentifierFont) {
            if (compactFont.topDict._hasName('FontMatrix')) {
                var base = compactFont.topDict._getByName('FontMatrix'); //eslint-disable-line
                compactFont.topDict._removeByName('FontMatrix');
                for (var _i = 0, _a = compactFont.fontDictionaryArray; _i < _a.length; _i++) {
                    var subDict = _a[_i];
                    var matrix = base.slice(0); //eslint-disable-line
                    if (subDict._hasName('FontMatrix')) {
                        matrix = this._transform(matrix, subDict._getByName('FontMatrix'));
                    }
                    subDict._setByName('FontMatrix', matrix);
                }
            }
        }
        var xuid = compactFont.topDict._getByName('XUID'); //eslint-disable-line
        if (xuid && xuid.length > 16) {
            compactFont.topDict._removeByName('XUID');
        }
        compactFont.topDict._setByName('charSet', 0);
        var compiled = this._compileTopDictionary([compactFont.topDict], output.length, compactFont.isCharacterIdentifierFont); //eslint-disable-line
        output.add(compiled.output);
        var topDictTracker = compiled.trackers[0]; //eslint-disable-line
        var stringIndex = this._compileStringIndex(compactFont.strings.strings); //eslint-disable-line
        output.add(stringIndex);
        var globalSubroutineIndex = this._compileIndex(compactFont.globalSubroutineIndex); //eslint-disable-line
        output.add(globalSubroutineIndex);
        if (compactFont.encoding && compactFont.topDict._hasName('Encoding')) {
            if (compactFont.encoding.predefined) {
                topDictTracker._setEntryLocation('Encoding', [compactFont.encoding.format], output);
            }
            else {
                var encoding = this._compileEncoding(compactFont.encoding); //eslint-disable-line
                topDictTracker._setEntryLocation('Encoding', [output.length], output);
                output.add(encoding);
            }
        }
        var charSet = this._compileCharSet(//eslint-disable-line
        compactFont.charSet, compactFont.charStrings.count, compactFont.strings, compactFont.isCharacterIdentifierFont);
        topDictTracker._setEntryLocation('charSet', [output.length], output);
        output.add(charSet);
        var charStrings = this._compileCharStrings(compactFont.charStrings); //eslint-disable-line
        topDictTracker._setEntryLocation('CharStrings', [output.length], output);
        output.add(charStrings);
        if (compactFont.isCharacterIdentifierFont) {
            topDictTracker._setEntryLocation('FDSelect', [output.length], output);
            var fontDictionarySelect = this._compileFontDictionarySelect(compactFont.fontDictionarySelect); //eslint-disable-line
            output.add(fontDictionarySelect);
            compiled = this._compileTopDictionary(compactFont.fontDictionaryArray, output.length, true);
            topDictTracker._setEntryLocation('FDArray', [output.length], output);
            output.add(compiled.output);
            var fontDictTrackers = compiled.trackers; //eslint-disable-line
            this._compilePrivateDictionary(compactFont.fontDictionaryArray, fontDictTrackers, output);
        }
        this._compilePrivateDictionary([compactFont.topDict], [topDictTracker], output);
        output.add([0]);
        return output.data;
    };
    _PdfCompactFontCompiler.prototype._transform = function (m1, m2) {
        return [
            m1[0] * m2[0] + m1[2] * m2[1],
            m1[1] * m2[0] + m1[3] * m2[1],
            m1[0] * m2[2] + m1[2] * m2[3],
            m1[1] * m2[2] + m1[3] * m2[3],
            m1[0] * m2[4] + m1[2] * m2[5] + m1[4],
            m1[1] * m2[4] + m1[3] * m2[5] + m1[5]
        ];
    };
    _PdfCompactFontCompiler.prototype._encodeNumber = function (value) {
        if (Number.isInteger(value)) {
            return this._encodeInteger(value);
        }
        return this._encodeFloat(value);
    };
    _PdfCompactFontCompiler.prototype._encodeFloat = function (count) {
        var value = count.toString();
        var m = _defineProperty(this, 'EncodeFloatRegExp', /\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/).exec(value); //eslint-disable-line
        if (m) {
            var epsilon = parseFloat('1e' + ((m[2] ? +m[2] : 0) + m[1].length));
            value = (Math.round(count * epsilon) / epsilon).toString();
        }
        var nibbles = '';
        for (var i = 0; i < value.length; ++i) {
            var a = value[Number.parseInt(i.toString(), 10)];
            if (a === 'e') {
                nibbles += value[++i] === '-' ? 'c' : 'b';
            }
            else if (a === '.') {
                nibbles += 'a';
            }
            else if (a === '-') {
                nibbles += 'e';
            }
            else {
                nibbles += a;
            }
        }
        nibbles += nibbles.length & 1 ? 'f' : 'ff';
        var result = [30];
        for (var i = 0; i < nibbles.length; i += 2) {
            result.push(parseInt(nibbles.substring(i, i + 2), 16));
        }
        return result;
    };
    _PdfCompactFontCompiler.prototype._encodeInteger = function (value) {
        var code;
        if (value >= -107 && value <= 107) {
            code = [value + 139];
        }
        else if (value >= 108 && value <= 1131) {
            value -= 108;
            code = [(value >> 8) + 247, value & 0xff];
        }
        else if (value >= -1131 && value <= -108) {
            value = -value - 108;
            code = [(value >> 8) + 251, value & 0xff];
        }
        else if (value >= -32768 && value <= 32767) {
            code = [0x1c, (value >> 8) & 0xff, value & 0xff];
        }
        else {
            code = [
                0x1d,
                (value >> 24) & 0xff,
                (value >> 16) & 0xff,
                (value >> 8) & 0xff,
                value & 0xff
            ];
        }
        return code;
    };
    _PdfCompactFontCompiler.prototype._compileHeader = function (header) {
        return [header.major, header.minor, 4, header.offSize];
    };
    _PdfCompactFontCompiler.prototype._compileNameIndex = function (names) {
        var nameIndex = new _PdfCompactFontIndex();
        for (var _i = 0, names_1 = names; _i < names_1.length; _i++) {
            var name_2 = names_1[_i];
            var length_1 = Math.min(name_2.length, 127);
            var sanitizedName = new Array(length_1); //eslint-disable-line
            for (var j = 0; j < length_1; j++) {
                var char = name_2[Number.parseInt(j.toString(), 10)];
                if (char < '!' ||
                    char > '~' ||
                    char === '[' ||
                    char === ']' ||
                    char === '(' ||
                    char === ')' ||
                    char === '{' ||
                    char === '}' ||
                    char === '<' ||
                    char === '>' ||
                    char === '/' ||
                    char === '%') {
                    char = '_';
                }
                sanitizedName[Number.parseInt(j.toString(), 10)] = char;
            }
            sanitizedName = sanitizedName.join('');
            if (sanitizedName === '') {
                sanitizedName = 'Bad_Font_Name';
            }
            nameIndex.add(_stringToBytes(sanitizedName));
        }
        return this._compileIndex(nameIndex);
    };
    _PdfCompactFontCompiler.prototype._compileTopDictionary = function (dictionary, length, removeCidKeys) {
        var fontDictTrackers = []; //eslint-disable-line
        var fontDictionaryArrayIndex = new _PdfCompactFontIndex();
        for (var _i = 0, dictionary_2 = dictionary; _i < dictionary_2.length; _i++) {
            var fontDict = dictionary_2[_i];
            if (removeCidKeys) {
                fontDict._removeByName('CIDFontVersion');
                fontDict._removeByName('CIDFontRevision');
                fontDict._removeByName('CIDFontType');
                fontDict._removeByName('CIDCount');
                fontDict._removeByName('UIDBase');
            }
            var fontDictTracker = new _PdfCompactFontOffsetTracker();
            var fontDictData = this._compileDictionary(fontDict, fontDictTracker); //eslint-disable-line
            fontDictTrackers.push(fontDictTracker);
            fontDictionaryArrayIndex.add(fontDictData);
            fontDictTracker._offset(length);
        }
        fontDictionaryArrayIndex = this._compileIndex(fontDictionaryArrayIndex, fontDictTrackers);
        return {
            trackers: fontDictTrackers,
            output: fontDictionaryArrayIndex
        };
    };
    _PdfCompactFontCompiler.prototype._compilePrivateDictionary = function (dictionary, trackers, output) {
        for (var i = 0, ii = dictionary.length; i < ii; ++i) {
            var fontDict = dictionary[Number.parseInt(i.toString(), 10)]; //eslint-disable-line
            var privateDictionary = fontDict.privateDictionary; //eslint-disable-line
            if (!privateDictionary || !fontDict._hasName('Private')) {
                throw new FormatError('There must be a private dictionary.');
            }
            var privateDictionaryTracker = new _PdfCompactFontOffsetTracker();
            var privateDictionaryData = this._compileDictionary(privateDictionary, privateDictionaryTracker); //eslint-disable-line
            var outputLength = output.length;
            privateDictionaryTracker._offset(outputLength);
            if (!privateDictionaryData.length) {
                outputLength = 0;
            }
            trackers[Number.parseInt(i.toString(), 10)].setEntryLocation('Private', [privateDictionaryData.length, outputLength], output);
            output.add(privateDictionaryData);
            if (privateDictionary.subroutineIndex && privateDictionary._hasName('Subrs')) {
                var subrs = this._compileIndex(privateDictionary.subroutineIndex); //eslint-disable-line
                privateDictionaryTracker._setEntryLocation('Subrs', [privateDictionaryData.length], output);
                output.add(subrs);
            }
        }
    };
    _PdfCompactFontCompiler.prototype._compileDictionary = function (dictionary, offsetTracker) {
        var out = []; //eslint-disable-line
        for (var _i = 0, _a = dictionary.order; _i < _a.length; _i++) {
            var key = _a[_i];
            if (!(key in dictionary.values)) {
                continue;
            }
            var values = dictionary.values[key]; //eslint-disable-line
            var types = dictionary.types[key]; //eslint-disable-line
            if (!Array.isArray(types)) {
                types = [types];
            }
            if (!Array.isArray(values)) {
                values = [values];
            }
            if (values.length === 0) {
                continue;
            }
            for (var j = 0, jj = types.length; j < jj; ++j) {
                var type = types[Number.parseInt(j.toString(), 10)]; //eslint-disable-line
                var value = values[Number.parseInt(jj.toString(), 10)];
                var name_3 = '';
                switch (type) {
                    case 'num':
                    case 'sid':
                        try {
                            out.push.apply(out, this._encodeNumber(value));
                        }
                        catch (ex) {
                            // Ignoring the error intentionally because...
                        }
                        break;
                    case 'offset':
                        name_3 = dictionary.keyToNameMap[Number.parseInt(key.toString(), 10)];
                        if (!offsetTracker.isTracking(name_3)) {
                            offsetTracker.track(name_3, out.length);
                        }
                        out.push(0x1d, 0, 0, 0, 0);
                        break;
                    case 'array':
                    case 'delta':
                        out.push.apply(out, this._encodeNumber(value));
                        for (var k = 1, kk = values.length; k < kk; ++k) {
                            out.push.apply(out, this._encodeNumber(values[Number.parseInt(k.toString(), 10)]));
                        }
                        break;
                    default:
                        throw new FormatError("Unknown data type of " + type);
                }
            }
            out.push.apply(out, dictionary.opcodes[Number.parseInt(key.toString(), 10)]);
        }
        return out;
    };
    _PdfCompactFontCompiler.prototype._compileStringIndex = function (strings) {
        var stringIndex = new _PdfCompactFontIndex();
        for (var _i = 0, strings_1 = strings; _i < strings_1.length; _i++) {
            var string = strings_1[_i];
            stringIndex.add(_stringToBytes(string));
        }
        return this._compileIndex(stringIndex);
    };
    _PdfCompactFontCompiler.prototype._compileCharStrings = function (charStrings) {
        var charStringsIndex = new _PdfCompactFontIndex();
        for (var i = 0; i < charStrings.count; i++) {
            var glyph = charStrings._get(i); //eslint-disable-line
            if (glyph.length === 0) {
                charStringsIndex.add(new Uint8Array([0x8b, 0x0e]));
                continue;
            }
            charStringsIndex.add(glyph);
        }
        return this._compileIndex(charStringsIndex);
    };
    _PdfCompactFontCompiler.prototype._compileCharSet = function (charSet, glyphCount, strings, isCharacterIdentifierFont) {
        var out; //eslint-disable-line
        var glyphCountLessNotDef = glyphCount - 1;
        if (isCharacterIdentifierFont) {
            out = new Uint8Array([2, 0, 0, (glyphCountLessNotDef >> 8) & 0xff, glyphCountLessNotDef & 0xff]);
        }
        else {
            var length_2 = 1 + glyphCountLessNotDef * 2;
            out = new Uint8Array(length_2);
            out[0] = 0;
            var charSetIndex = 0;
            var numcharSets = charSet.charSet.length;
            var warned = false;
            for (var i = 1; i < out.length; i += 2) {
                var sid = 0;
                if (charSetIndex < numcharSets) {
                    var name_4 = charSet.charSet[charSetIndex++]; //eslint-disable-line
                    sid = strings.getSID(name_4);
                    if (sid === -1) {
                        sid = 0;
                        if (!warned) {
                            warned = true;
                        }
                    }
                }
                out[Number.parseInt(i.toString(), 10)] = (sid >> 8) & 0xff;
                out[i + 1] = sid & 0xff;
            }
        }
        return this._compileTypedArray(out);
    };
    _PdfCompactFontCompiler.prototype._compileEncoding = function (encoding) {
        return this._compileTypedArray(encoding.raw);
    };
    _PdfCompactFontCompiler.prototype._compileFontDictionarySelect = function (fontDictionarySelect) {
        var format = fontDictionarySelect.format; //eslint-disable-line
        var out;
        var i;
        var numRanges;
        var start;
        switch (format) {
            case 0:
                out = new Uint8Array(1 + fontDictionarySelect.fontDictionarySelect.length);
                out[0] = format;
                for (i = 0; i < fontDictionarySelect.fontDictionarySelect.length; i++) {
                    out[i + 1] = fontDictionarySelect.fontDictionarySelect[Number.parseInt(i.toString(), 10)];
                }
                break;
            case 3:
                start = 0;
                var lastFD = fontDictionarySelect.fontDictionarySelect[0]; //eslint-disable-line
                var ranges = [format, 0, 0, (start >> 8) & 0xff, start & 0xff, lastFD]; //eslint-disable-line
                for (i = 1; i < fontDictionarySelect.fontDictionarySelect.length; i++) {
                    var currentFD = fontDictionarySelect.fontDictionarySelect[Number.parseInt(i.toString(), 10)]; //eslint-disable-line
                    if (currentFD !== lastFD) {
                        ranges.push((i >> 8) & 0xff, i & 0xff, currentFD);
                        lastFD = currentFD;
                    }
                }
                numRanges = (ranges.length - 3) / 3;
                ranges[1] = (numRanges >> 8) & 0xff;
                ranges[2] = numRanges & 0xff;
                ranges.push((i >> 8) & 0xff, i & 0xff);
                out = new Uint8Array(ranges);
                break;
        }
        return this._compileTypedArray(out);
    };
    _PdfCompactFontCompiler.prototype._compileTypedArray = function (data) {
        return Array.from(data);
    };
    _PdfCompactFontCompiler.prototype._compileIndex = function (index, trackers) {
        if (trackers === void 0) { trackers = []; }
        var objects = index.objects; //eslint-disable-line
        var count = objects.length;
        if (count === 0) {
            return [0, 0];
        }
        var data = [(count >> 8) & 0xff, count & 0xff]; //eslint-disable-line
        var lastOffset = 1;
        var i;
        for (i = 0; i < count; ++i) {
            lastOffset += objects[Number.parseInt(i.toString(), 10)].length;
        }
        var offsetSize;
        if (lastOffset < 0x100) {
            offsetSize = 1;
        }
        else if (lastOffset < 0x10000) {
            offsetSize = 2;
        }
        else if (lastOffset < 0x1000000) {
            offsetSize = 3;
        }
        else {
            offsetSize = 4;
        }
        data.push(offsetSize);
        var relativeOffset = 1;
        for (i = 0; i < count + 1; i++) {
            if (offsetSize === 1) {
                data.push(relativeOffset & 0xff);
            }
            else if (offsetSize === 2) {
                data.push((relativeOffset >> 8) & 0xff, relativeOffset & 0xff);
            }
            else if (offsetSize === 3) {
                data.push((relativeOffset >> 16) & 0xff, (relativeOffset >> 8) & 0xff, relativeOffset & 0xff);
            }
            else {
                data.push((relativeOffset >>> 24) & 0xff, (relativeOffset >> 16) & 0xff, (relativeOffset >> 8) & 0xff, relativeOffset & 0xff);
            }
            if (objects[Number.parseInt(i.toString(), 10)]) {
                relativeOffset += objects[Number.parseInt(i.toString(), 10)].length;
            }
        }
        for (i = 0; i < count; i++) {
            if (trackers[Number.parseInt(i.toString(), 10)]) {
                trackers[Number.parseInt(i.toString(), 10)].offset(data.length);
            }
            data.push.apply(data, objects[Number.parseInt(i.toString(), 10)]);
        }
        return data;
    };
    return _PdfCompactFontCompiler;
}());
export { _PdfCompactFontCompiler };
var _PdfCompactFont = /** @class */ (function () {
    function _PdfCompactFont(file, properties) {
        this.properties = properties;
        var parser = new _PdfCompactFontParser(file, properties, true);
        this.compactFont = parser._parse(properties);
        this.compactFont._duplicateFirstGlyph();
        var compiler = new _PdfCompactFontCompiler(this.compactFont);
        this.standardCharacter = this.compactFont.standardCharacter;
        try {
            this.data = compiler.compile();
        }
        catch (_a) {
            this.data = file;
        }
        this._createBuiltInEncoding();
    }
    Object.defineProperty(_PdfCompactFont.prototype, "_glyphCount", {
        get: function () {
            return this.compactFont.charStrings.count;
        },
        enumerable: true,
        configurable: true
    });
    _PdfCompactFont.prototype._getCharSet = function () {
        return this.compactFont.charSet.charSet;
    };
    _PdfCompactFont.prototype._getGlyphMapping = function () {
        var compactFont = this.compactFont; //eslint-disable-line
        var properties = this.properties; //eslint-disable-line
        var cidToGidMap; //eslint-disable-line
        var cMap = properties._fontStructure._cMap; //eslint-disable-line
        var charSets = compactFont.charSet.charSet; //eslint-disable-line
        var charCodeToGlyphId = {};
        var glyphId;
        if (properties._fontStructure._composite) {
            var invCidToGidMap = void 0;
            if (cidToGidMap && cidToGidMap.length > 0) {
                invCidToGidMap = Object.create(null);
                for (var i = 0, ii = cidToGidMap.length; i < ii; i++) {
                    var gid = cidToGidMap[Number.parseInt(i.toString(), 10)]; //eslint-disable-line
                    if (typeof (gid) !== 'undefined') {
                        invCidToGidMap[Number.parseInt(gid.toString(), 10)] = i;
                    }
                }
            }
            var charCode = void 0;
            if (compactFont.isCharacterIdentifierFont) {
                for (glyphId = 0; glyphId < charSets.length; glyphId++) {
                    var cid = charSets[glyphId]; //eslint-disable-line
                    charCode = cMap._charCodeOf(cid);
                    if (invCidToGidMap && typeof (invCidToGidMap[Number.parseInt(charCode.toString(), 10)]) !== 'undefined') {
                        charCode = invCidToGidMap[Number.parseInt(charCode.toString(), 10)];
                    }
                    charCodeToGlyphId[Number.parseInt(charCode.toString(), 10)] = glyphId;
                }
            }
            else {
                for (glyphId = 0; glyphId < compactFont.charStrings.count; glyphId++) {
                    charCode = cMap._charCodeOf(glyphId);
                    charCodeToGlyphId[Number.parseInt(charCode.toString(), 10)] = glyphId;
                }
            }
            return charCodeToGlyphId;
        }
        var encoding = compactFont.encoding ? compactFont.encoding.encoding : null; //eslint-disable-line
        if (properties._fontStructure._isInternalFont) {
            encoding = properties._fontStructure._defaultEncoding;
        }
        charCodeToGlyphId = this._type1FontGlyphMapping(properties, encoding, charSets);
        return charCodeToGlyphId;
    };
    _PdfCompactFont.prototype._hasGlyphId = function (id) {
        return this.compactFont.hasGlyphId(id);
    };
    _PdfCompactFont.prototype._type1FontGlyphMapping = function (properties, builtInEncoding, glyphNames) {
        var charCodeToGlyphId = Object.create(null); //eslint-disable-line
        var glyphId;
        var charCode; //eslint-disable-line
        var baseEncoding; //eslint-disable-line
        var isSymbolicFont = !!(properties._flags & properties._fontFlags.Symbolic);
        if (properties._fontStructure._isInternalFont) {
            baseEncoding = builtInEncoding;
            for (charCode = 0; charCode < baseEncoding.length; charCode++) {
                glyphId = glyphNames.indexOf(baseEncoding[Number.parseInt(charCode.toString(), 10)]);
                charCodeToGlyphId[Number.parseInt(charCode.toString(), 10)] = glyphId >= 0 ? glyphId : /* notdef = */ 0;
            }
        }
        else if (properties.baseEncodingName) {
            baseEncoding = _getEncoding(properties.baseEncodingName);
            for (charCode = 0; charCode < baseEncoding.length; charCode++) {
                glyphId = glyphNames.indexOf(baseEncoding[Number.parseInt(charCode.toString(), 10)]);
                charCodeToGlyphId[Number.parseInt(charCode.toString(), 10)] = glyphId >= 0 ? glyphId : /* notdef = */ 0;
            }
        }
        else if (isSymbolicFont) {
            var builtInEncodingKeys = Object.keys(builtInEncoding); //eslint-disable-line
            for (var i = 0; i < builtInEncodingKeys.length; i++) {
                var charCode_1 = builtInEncodingKeys[Number.parseInt(i.toString(), 10)]; //eslint-disable-line
                var numericCharCode = Number.parseInt(charCode_1, 10); //eslint-disable-line
                charCodeToGlyphId[Number.parseInt(numericCharCode.toString(), 10)] =
                    builtInEncoding[Number.parseInt(numericCharCode.toString(), 10)];
            }
        }
        else {
            baseEncoding = _standardEncoding;
            for (charCode = 0; charCode < baseEncoding.length; charCode++) {
                glyphId = glyphNames.indexOf(baseEncoding[Number.parseInt(charCode.toString(), 10)]);
                charCodeToGlyphId[Number.parseInt(charCode.toString(), 10)] = glyphId >= 0 ? glyphId : /* notdef = */ 0;
            }
        }
        var differences = properties._fontStructure._differences; //eslint-disable-line
        var glyphsUnicodeMap; //eslint-disable-line
        if (differences) {
            var differencesKeys = Object.keys(differences); //eslint-disable-line
            for (var i = 0; i < differencesKeys.length; i++) {
                var charCode_2 = differencesKeys[Number.parseInt(i.toString(), 10)]; //eslint-disable-line
                var glyphName = differences[Number.parseInt(charCode_2.toString(), 10)]; //eslint-disable-line
                var glyphId_1 = -1;
                for (var j = 0; j < glyphNames.length; j++) {
                    if (glyphNames[Number.parseInt(j.toString(), 10)] === glyphName) {
                        glyphId_1 = j;
                        break;
                    }
                }
                if (glyphId_1 === -1) {
                    if (!glyphsUnicodeMap) {
                        glyphsUnicodeMap = _getGlyphsUnicode();
                    }
                    var standardGlyphName = _recoverGlyphName(glyphName, glyphsUnicodeMap); //eslint-disable-line
                    if (standardGlyphName !== glyphName) {
                        for (var k = 0; k < glyphNames.length; k++) {
                            if (glyphNames[Number.parseInt(k.toString(), 10)] === standardGlyphName) {
                                glyphId_1 = k;
                                break;
                            }
                        }
                    }
                }
                charCodeToGlyphId[Number.parseInt(charCode_2, 10)] = glyphId_1 >= 0 ? glyphId_1 : 0;
            }
        }
        return charCodeToGlyphId;
    };
    _PdfCompactFont.prototype._createBuiltInEncoding = function () {
        var _a = this.compactFont, charSet = _a.charSet, encoding = _a.encoding;
        if (!charSet || !encoding) {
            return;
        }
        var charSets = charSet.charSet; //eslint-disable-line
        var encodings = encoding.encoding; //eslint-disable-line
        var map = []; //eslint-disable-line
        var keys = Object.keys(encodings); //eslint-disable-line
        for (var i = 0; i < keys.length; i++) {
            var charCode = keys[Number.parseInt(i.toString(), 10)]; //eslint-disable-line
            var glyphId = encodings[Number.parseInt(charCode, 10)];
            if (glyphId >= 0) {
                var glyphName = charSets[glyphId]; //eslint-disable-line
                if (glyphName) {
                    map[Number(charCode)] = glyphName;
                }
            }
        }
        if (map.length > 0) {
            this._builtInEncoding = map;
        }
    };
    return _PdfCompactFont;
}());
export { _PdfCompactFont };
