(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('universal-base64url'), require('@wharfkit/antelope'), require('@consento/sync-randombytes'), require('elliptic'), require('@tonomy/did-jwt'), require('@tonomy/did-resolver'), require('@tonomy/antelope-did-resolver'), require('cross-fetch'), require('@tonomy/did-jwt-vc')) :
    typeof define === 'function' && define.amd ? define(['exports', 'universal-base64url', '@wharfkit/antelope', '@consento/sync-randombytes', 'elliptic', '@tonomy/did-jwt', '@tonomy/did-resolver', '@tonomy/antelope-did-resolver', 'cross-fetch', '@tonomy/did-jwt-vc'], factory) :
    (global = global || self, factory(global.tonomyIdSdk = {}, global.universalBase64Url, global.antelope, global.rb, global.elliptic, global.didJwt, global.didResolver, global.antelopeDidResolver, global.crossFetch, global.didJwtVc));
})(this, (function (exports, universalBase64url, antelope, rb, elliptic, didJwt, didResolver, antelopeDidResolver, crossFetch, didJwtVc) {
    function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

    var rb__default = /*#__PURE__*/_interopDefaultLegacy(rb);
    var elliptic__default = /*#__PURE__*/_interopDefaultLegacy(elliptic);
    var crossFetch__default = /*#__PURE__*/_interopDefaultLegacy(crossFetch);

    function percentToByte(p) {
        return String.fromCharCode(parseInt(p.slice(1), 16));
    }
    function encode$2(str) {
        return btoa(encodeURIComponent(str).replace(/%[0-9A-F]{2}/g, percentToByte));
    }
    var encode_1 = encode$2;
    function byteToPercent(b) {
        return `%${`00${b.charCodeAt(0).toString(16)}`.slice(-2)}`;
    }
    function decode$2(str) {
        return decodeURIComponent(Array.from(atob(str), byteToPercent).join(""));
    }
    var decode_1 = decode$2;

    function asUint8Array(buf) {
      if (globalThis.Buffer != null) {
        return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
      }
      return buf;
    }

    function allocUnsafe(size = 0) {
      if (globalThis.Buffer != null && globalThis.Buffer.allocUnsafe != null) {
        return asUint8Array(globalThis.Buffer.allocUnsafe(size));
      }
      return new Uint8Array(size);
    }

    function base(ALPHABET, name) {
      if (ALPHABET.length >= 255) {
        throw new TypeError('Alphabet too long');
      }
      var BASE_MAP = new Uint8Array(256);
      for (var j = 0; j < BASE_MAP.length; j++) {
        BASE_MAP[j] = 255;
      }
      for (var i = 0; i < ALPHABET.length; i++) {
        var x = ALPHABET.charAt(i);
        var xc = x.charCodeAt(0);
        if (BASE_MAP[xc] !== 255) {
          throw new TypeError(x + ' is ambiguous');
        }
        BASE_MAP[xc] = i;
      }
      var BASE = ALPHABET.length;
      var LEADER = ALPHABET.charAt(0);
      var FACTOR = Math.log(BASE) / Math.log(256);
      var iFACTOR = Math.log(256) / Math.log(BASE);
      function encode(source) {
        if (source instanceof Uint8Array);
        else if (ArrayBuffer.isView(source)) {
          source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
        } else if (Array.isArray(source)) {
          source = Uint8Array.from(source);
        }
        if (!(source instanceof Uint8Array)) {
          throw new TypeError('Expected Uint8Array');
        }
        if (source.length === 0) {
          return '';
        }
        var zeroes = 0;
        var length = 0;
        var pbegin = 0;
        var pend = source.length;
        while (pbegin !== pend && source[pbegin] === 0) {
          pbegin++;
          zeroes++;
        }
        var size = (pend - pbegin) * iFACTOR + 1 >>> 0;
        var b58 = new Uint8Array(size);
        while (pbegin !== pend) {
          var carry = source[pbegin];
          var i = 0;
          for (var it1 = size - 1; (carry !== 0 || i < length) && it1 !== -1; it1--, i++) {
            carry += 256 * b58[it1] >>> 0;
            b58[it1] = carry % BASE >>> 0;
            carry = carry / BASE >>> 0;
          }
          if (carry !== 0) {
            throw new Error('Non-zero carry');
          }
          length = i;
          pbegin++;
        }
        var it2 = size - length;
        while (it2 !== size && b58[it2] === 0) {
          it2++;
        }
        var str = LEADER.repeat(zeroes);
        for (; it2 < size; ++it2) {
          str += ALPHABET.charAt(b58[it2]);
        }
        return str;
      }
      function decodeUnsafe(source) {
        if (typeof source !== 'string') {
          throw new TypeError('Expected String');
        }
        if (source.length === 0) {
          return new Uint8Array();
        }
        var psz = 0;
        if (source[psz] === ' ') {
          return;
        }
        var zeroes = 0;
        var length = 0;
        while (source[psz] === LEADER) {
          zeroes++;
          psz++;
        }
        var size = (source.length - psz) * FACTOR + 1 >>> 0;
        var b256 = new Uint8Array(size);
        while (source[psz]) {
          var carry = BASE_MAP[source.charCodeAt(psz)];
          if (carry === 255) {
            return;
          }
          var i = 0;
          for (var it3 = size - 1; (carry !== 0 || i < length) && it3 !== -1; it3--, i++) {
            carry += BASE * b256[it3] >>> 0;
            b256[it3] = carry % 256 >>> 0;
            carry = carry / 256 >>> 0;
          }
          if (carry !== 0) {
            throw new Error('Non-zero carry');
          }
          length = i;
          psz++;
        }
        if (source[psz] === ' ') {
          return;
        }
        var it4 = size - length;
        while (it4 !== size && b256[it4] === 0) {
          it4++;
        }
        var vch = new Uint8Array(zeroes + (size - it4));
        var j = zeroes;
        while (it4 !== size) {
          vch[j++] = b256[it4++];
        }
        return vch;
      }
      function decode(string) {
        var buffer = decodeUnsafe(string);
        if (buffer) {
          return buffer;
        }
        throw new Error(`Non-${ name } character`);
      }
      return {
        encode: encode,
        decodeUnsafe: decodeUnsafe,
        decode: decode
      };
    }
    var src = base;
    var _brrp__multiformats_scope_baseX = src;

    const coerce = o => {
      if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array')
        return o;
      if (o instanceof ArrayBuffer)
        return new Uint8Array(o);
      if (ArrayBuffer.isView(o)) {
        return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);
      }
      throw new Error('Unknown type, must be binary type');
    };
    const fromString$1 = str => new TextEncoder().encode(str);
    const toString$1 = b => new TextDecoder().decode(b);

    class Encoder {
      constructor(name, prefix, baseEncode) {
        this.name = name;
        this.prefix = prefix;
        this.baseEncode = baseEncode;
      }
      encode(bytes) {
        if (bytes instanceof Uint8Array) {
          return `${ this.prefix }${ this.baseEncode(bytes) }`;
        } else {
          throw Error('Unknown type, must be binary type');
        }
      }
    }
    class Decoder {
      constructor(name, prefix, baseDecode) {
        this.name = name;
        this.prefix = prefix;
        if (prefix.codePointAt(0) === undefined) {
          throw new Error('Invalid prefix character');
        }
        this.prefixCodePoint = prefix.codePointAt(0);
        this.baseDecode = baseDecode;
      }
      decode(text) {
        if (typeof text === 'string') {
          if (text.codePointAt(0) !== this.prefixCodePoint) {
            throw Error(`Unable to decode multibase string ${ JSON.stringify(text) }, ${ this.name } decoder only supports inputs prefixed with ${ this.prefix }`);
          }
          return this.baseDecode(text.slice(this.prefix.length));
        } else {
          throw Error('Can only multibase decode strings');
        }
      }
      or(decoder) {
        return or(this, decoder);
      }
    }
    class ComposedDecoder {
      constructor(decoders) {
        this.decoders = decoders;
      }
      or(decoder) {
        return or(this, decoder);
      }
      decode(input) {
        const prefix = input[0];
        const decoder = this.decoders[prefix];
        if (decoder) {
          return decoder.decode(input);
        } else {
          throw RangeError(`Unable to decode multibase string ${ JSON.stringify(input) }, only inputs prefixed with ${ Object.keys(this.decoders) } are supported`);
        }
      }
    }
    const or = (left, right) => new ComposedDecoder({
      ...left.decoders || { [left.prefix]: left },
      ...right.decoders || { [right.prefix]: right }
    });
    class Codec {
      constructor(name, prefix, baseEncode, baseDecode) {
        this.name = name;
        this.prefix = prefix;
        this.baseEncode = baseEncode;
        this.baseDecode = baseDecode;
        this.encoder = new Encoder(name, prefix, baseEncode);
        this.decoder = new Decoder(name, prefix, baseDecode);
      }
      encode(input) {
        return this.encoder.encode(input);
      }
      decode(input) {
        return this.decoder.decode(input);
      }
    }
    const from = ({name, prefix, encode, decode}) => new Codec(name, prefix, encode, decode);
    const baseX = ({prefix, name, alphabet}) => {
      const {encode, decode} = _brrp__multiformats_scope_baseX(alphabet, name);
      return from({
        prefix,
        name,
        encode,
        decode: text => coerce(decode(text))
      });
    };
    const decode$1 = (string, alphabet, bitsPerChar, name) => {
      const codes = {};
      for (let i = 0; i < alphabet.length; ++i) {
        codes[alphabet[i]] = i;
      }
      let end = string.length;
      while (string[end - 1] === '=') {
        --end;
      }
      const out = new Uint8Array(end * bitsPerChar / 8 | 0);
      let bits = 0;
      let buffer = 0;
      let written = 0;
      for (let i = 0; i < end; ++i) {
        const value = codes[string[i]];
        if (value === undefined) {
          throw new SyntaxError(`Non-${ name } character`);
        }
        buffer = buffer << bitsPerChar | value;
        bits += bitsPerChar;
        if (bits >= 8) {
          bits -= 8;
          out[written++] = 255 & buffer >> bits;
        }
      }
      if (bits >= bitsPerChar || 255 & buffer << 8 - bits) {
        throw new SyntaxError('Unexpected end of data');
      }
      return out;
    };
    const encode$1 = (data, alphabet, bitsPerChar) => {
      const pad = alphabet[alphabet.length - 1] === '=';
      const mask = (1 << bitsPerChar) - 1;
      let out = '';
      let bits = 0;
      let buffer = 0;
      for (let i = 0; i < data.length; ++i) {
        buffer = buffer << 8 | data[i];
        bits += 8;
        while (bits > bitsPerChar) {
          bits -= bitsPerChar;
          out += alphabet[mask & buffer >> bits];
        }
      }
      if (bits) {
        out += alphabet[mask & buffer << bitsPerChar - bits];
      }
      if (pad) {
        while (out.length * bitsPerChar & 7) {
          out += '=';
        }
      }
      return out;
    };
    const rfc4648 = ({name, prefix, bitsPerChar, alphabet}) => {
      return from({
        prefix,
        name,
        encode(input) {
          return encode$1(input, alphabet, bitsPerChar);
        },
        decode(input) {
          return decode$1(input, alphabet, bitsPerChar, name);
        }
      });
    };

    const identity = from({
      prefix: '\0',
      name: 'identity',
      encode: buf => toString$1(buf),
      decode: str => fromString$1(str)
    });

    var identityBase = {
        __proto__: null,
        identity: identity
    };

    const base2 = rfc4648({
      prefix: '0',
      name: 'base2',
      alphabet: '01',
      bitsPerChar: 1
    });

    var base2$1 = {
        __proto__: null,
        base2: base2
    };

    const base8 = rfc4648({
      prefix: '7',
      name: 'base8',
      alphabet: '01234567',
      bitsPerChar: 3
    });

    var base8$1 = {
        __proto__: null,
        base8: base8
    };

    const base10 = baseX({
      prefix: '9',
      name: 'base10',
      alphabet: '0123456789'
    });

    var base10$1 = {
        __proto__: null,
        base10: base10
    };

    const base16 = rfc4648({
      prefix: 'f',
      name: 'base16',
      alphabet: '0123456789abcdef',
      bitsPerChar: 4
    });
    const base16upper = rfc4648({
      prefix: 'F',
      name: 'base16upper',
      alphabet: '0123456789ABCDEF',
      bitsPerChar: 4
    });

    var base16$1 = {
        __proto__: null,
        base16: base16,
        base16upper: base16upper
    };

    const base32 = rfc4648({
      prefix: 'b',
      name: 'base32',
      alphabet: 'abcdefghijklmnopqrstuvwxyz234567',
      bitsPerChar: 5
    });
    const base32upper = rfc4648({
      prefix: 'B',
      name: 'base32upper',
      alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
      bitsPerChar: 5
    });
    const base32pad = rfc4648({
      prefix: 'c',
      name: 'base32pad',
      alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',
      bitsPerChar: 5
    });
    const base32padupper = rfc4648({
      prefix: 'C',
      name: 'base32padupper',
      alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',
      bitsPerChar: 5
    });
    const base32hex = rfc4648({
      prefix: 'v',
      name: 'base32hex',
      alphabet: '0123456789abcdefghijklmnopqrstuv',
      bitsPerChar: 5
    });
    const base32hexupper = rfc4648({
      prefix: 'V',
      name: 'base32hexupper',
      alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',
      bitsPerChar: 5
    });
    const base32hexpad = rfc4648({
      prefix: 't',
      name: 'base32hexpad',
      alphabet: '0123456789abcdefghijklmnopqrstuv=',
      bitsPerChar: 5
    });
    const base32hexpadupper = rfc4648({
      prefix: 'T',
      name: 'base32hexpadupper',
      alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',
      bitsPerChar: 5
    });
    const base32z = rfc4648({
      prefix: 'h',
      name: 'base32z',
      alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',
      bitsPerChar: 5
    });

    var base32$1 = {
        __proto__: null,
        base32: base32,
        base32upper: base32upper,
        base32pad: base32pad,
        base32padupper: base32padupper,
        base32hex: base32hex,
        base32hexupper: base32hexupper,
        base32hexpad: base32hexpad,
        base32hexpadupper: base32hexpadupper,
        base32z: base32z
    };

    const base36 = baseX({
      prefix: 'k',
      name: 'base36',
      alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'
    });
    const base36upper = baseX({
      prefix: 'K',
      name: 'base36upper',
      alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    });

    var base36$1 = {
        __proto__: null,
        base36: base36,
        base36upper: base36upper
    };

    const base58btc = baseX({
      name: 'base58btc',
      prefix: 'z',
      alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
    });
    const base58flickr = baseX({
      name: 'base58flickr',
      prefix: 'Z',
      alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
    });

    var base58 = {
        __proto__: null,
        base58btc: base58btc,
        base58flickr: base58flickr
    };

    const base64 = rfc4648({
      prefix: 'm',
      name: 'base64',
      alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
      bitsPerChar: 6
    });
    const base64pad = rfc4648({
      prefix: 'M',
      name: 'base64pad',
      alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
      bitsPerChar: 6
    });
    const base64url = rfc4648({
      prefix: 'u',
      name: 'base64url',
      alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',
      bitsPerChar: 6
    });
    const base64urlpad = rfc4648({
      prefix: 'U',
      name: 'base64urlpad',
      alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',
      bitsPerChar: 6
    });

    var base64$1 = {
        __proto__: null,
        base64: base64,
        base64pad: base64pad,
        base64url: base64url,
        base64urlpad: base64urlpad
    };

    const alphabet = Array.from('\uD83D\uDE80\uD83E\uDE90\u2604\uD83D\uDEF0\uD83C\uDF0C\uD83C\uDF11\uD83C\uDF12\uD83C\uDF13\uD83C\uDF14\uD83C\uDF15\uD83C\uDF16\uD83C\uDF17\uD83C\uDF18\uD83C\uDF0D\uD83C\uDF0F\uD83C\uDF0E\uD83D\uDC09\u2600\uD83D\uDCBB\uD83D\uDDA5\uD83D\uDCBE\uD83D\uDCBF\uD83D\uDE02\u2764\uD83D\uDE0D\uD83E\uDD23\uD83D\uDE0A\uD83D\uDE4F\uD83D\uDC95\uD83D\uDE2D\uD83D\uDE18\uD83D\uDC4D\uD83D\uDE05\uD83D\uDC4F\uD83D\uDE01\uD83D\uDD25\uD83E\uDD70\uD83D\uDC94\uD83D\uDC96\uD83D\uDC99\uD83D\uDE22\uD83E\uDD14\uD83D\uDE06\uD83D\uDE44\uD83D\uDCAA\uD83D\uDE09\u263A\uD83D\uDC4C\uD83E\uDD17\uD83D\uDC9C\uD83D\uDE14\uD83D\uDE0E\uD83D\uDE07\uD83C\uDF39\uD83E\uDD26\uD83C\uDF89\uD83D\uDC9E\u270C\u2728\uD83E\uDD37\uD83D\uDE31\uD83D\uDE0C\uD83C\uDF38\uD83D\uDE4C\uD83D\uDE0B\uD83D\uDC97\uD83D\uDC9A\uD83D\uDE0F\uD83D\uDC9B\uD83D\uDE42\uD83D\uDC93\uD83E\uDD29\uD83D\uDE04\uD83D\uDE00\uD83D\uDDA4\uD83D\uDE03\uD83D\uDCAF\uD83D\uDE48\uD83D\uDC47\uD83C\uDFB6\uD83D\uDE12\uD83E\uDD2D\u2763\uD83D\uDE1C\uD83D\uDC8B\uD83D\uDC40\uD83D\uDE2A\uD83D\uDE11\uD83D\uDCA5\uD83D\uDE4B\uD83D\uDE1E\uD83D\uDE29\uD83D\uDE21\uD83E\uDD2A\uD83D\uDC4A\uD83E\uDD73\uD83D\uDE25\uD83E\uDD24\uD83D\uDC49\uD83D\uDC83\uD83D\uDE33\u270B\uD83D\uDE1A\uD83D\uDE1D\uD83D\uDE34\uD83C\uDF1F\uD83D\uDE2C\uD83D\uDE43\uD83C\uDF40\uD83C\uDF37\uD83D\uDE3B\uD83D\uDE13\u2B50\u2705\uD83E\uDD7A\uD83C\uDF08\uD83D\uDE08\uD83E\uDD18\uD83D\uDCA6\u2714\uD83D\uDE23\uD83C\uDFC3\uD83D\uDC90\u2639\uD83C\uDF8A\uD83D\uDC98\uD83D\uDE20\u261D\uD83D\uDE15\uD83C\uDF3A\uD83C\uDF82\uD83C\uDF3B\uD83D\uDE10\uD83D\uDD95\uD83D\uDC9D\uD83D\uDE4A\uD83D\uDE39\uD83D\uDDE3\uD83D\uDCAB\uD83D\uDC80\uD83D\uDC51\uD83C\uDFB5\uD83E\uDD1E\uD83D\uDE1B\uD83D\uDD34\uD83D\uDE24\uD83C\uDF3C\uD83D\uDE2B\u26BD\uD83E\uDD19\u2615\uD83C\uDFC6\uD83E\uDD2B\uD83D\uDC48\uD83D\uDE2E\uD83D\uDE46\uD83C\uDF7B\uD83C\uDF43\uD83D\uDC36\uD83D\uDC81\uD83D\uDE32\uD83C\uDF3F\uD83E\uDDE1\uD83C\uDF81\u26A1\uD83C\uDF1E\uD83C\uDF88\u274C\u270A\uD83D\uDC4B\uD83D\uDE30\uD83E\uDD28\uD83D\uDE36\uD83E\uDD1D\uD83D\uDEB6\uD83D\uDCB0\uD83C\uDF53\uD83D\uDCA2\uD83E\uDD1F\uD83D\uDE41\uD83D\uDEA8\uD83D\uDCA8\uD83E\uDD2C\u2708\uD83C\uDF80\uD83C\uDF7A\uD83E\uDD13\uD83D\uDE19\uD83D\uDC9F\uD83C\uDF31\uD83D\uDE16\uD83D\uDC76\uD83E\uDD74\u25B6\u27A1\u2753\uD83D\uDC8E\uD83D\uDCB8\u2B07\uD83D\uDE28\uD83C\uDF1A\uD83E\uDD8B\uD83D\uDE37\uD83D\uDD7A\u26A0\uD83D\uDE45\uD83D\uDE1F\uD83D\uDE35\uD83D\uDC4E\uD83E\uDD32\uD83E\uDD20\uD83E\uDD27\uD83D\uDCCC\uD83D\uDD35\uD83D\uDC85\uD83E\uDDD0\uD83D\uDC3E\uD83C\uDF52\uD83D\uDE17\uD83E\uDD11\uD83C\uDF0A\uD83E\uDD2F\uD83D\uDC37\u260E\uD83D\uDCA7\uD83D\uDE2F\uD83D\uDC86\uD83D\uDC46\uD83C\uDFA4\uD83D\uDE47\uD83C\uDF51\u2744\uD83C\uDF34\uD83D\uDCA3\uD83D\uDC38\uD83D\uDC8C\uD83D\uDCCD\uD83E\uDD40\uD83E\uDD22\uD83D\uDC45\uD83D\uDCA1\uD83D\uDCA9\uD83D\uDC50\uD83D\uDCF8\uD83D\uDC7B\uD83E\uDD10\uD83E\uDD2E\uD83C\uDFBC\uD83E\uDD75\uD83D\uDEA9\uD83C\uDF4E\uD83C\uDF4A\uD83D\uDC7C\uD83D\uDC8D\uD83D\uDCE3\uD83E\uDD42');
    const alphabetBytesToChars = alphabet.reduce((p, c, i) => {
      p[i] = c;
      return p;
    }, []);
    const alphabetCharsToBytes = alphabet.reduce((p, c, i) => {
      p[c.codePointAt(0)] = i;
      return p;
    }, []);
    function encode(data) {
      return data.reduce((p, c) => {
        p += alphabetBytesToChars[c];
        return p;
      }, '');
    }
    function decode(str) {
      const byts = [];
      for (const char of str) {
        const byt = alphabetCharsToBytes[char.codePointAt(0)];
        if (byt === undefined) {
          throw new Error(`Non-base256emoji character: ${ char }`);
        }
        byts.push(byt);
      }
      return new Uint8Array(byts);
    }
    const base256emoji = from({
      prefix: '\uD83D\uDE80',
      name: 'base256emoji',
      encode,
      decode
    });

    var base256emoji$1 = {
        __proto__: null,
        base256emoji: base256emoji
    };

    new TextEncoder();
    new TextDecoder();

    const bases = {
      ...identityBase,
      ...base2$1,
      ...base8$1,
      ...base10$1,
      ...base16$1,
      ...base32$1,
      ...base36$1,
      ...base58,
      ...base64$1,
      ...base256emoji$1
    };

    function createCodec(name, prefix, encode, decode) {
      return {
        name,
        prefix,
        encoder: {
          name,
          prefix,
          encode
        },
        decoder: { decode }
      };
    }
    const string = createCodec('utf8', 'u', buf => {
      const decoder = new TextDecoder('utf8');
      return 'u' + decoder.decode(buf);
    }, str => {
      const encoder = new TextEncoder();
      return encoder.encode(str.substring(1));
    });
    const ascii = createCodec('ascii', 'a', buf => {
      let string = 'a';
      for (let i = 0; i < buf.length; i++) {
        string += String.fromCharCode(buf[i]);
      }
      return string;
    }, str => {
      str = str.substring(1);
      const buf = allocUnsafe(str.length);
      for (let i = 0; i < str.length; i++) {
        buf[i] = str.charCodeAt(i);
      }
      return buf;
    });
    const BASES = {
      utf8: string,
      'utf-8': string,
      hex: bases.base16,
      latin1: ascii,
      ascii: ascii,
      binary: ascii,
      ...bases
    };

    function fromString(string, encoding = 'utf8') {
      const base = BASES[encoding];
      if (!base) {
        throw new Error(`Unsupported encoding "${ encoding }"`);
      }
      if ((encoding === 'utf8' || encoding === 'utf-8') && globalThis.Buffer != null && globalThis.Buffer.from != null) {
        return asUint8Array(globalThis.Buffer.from(string, 'utf-8'));
      }
      return base.decoder.decode(`${ base.prefix }${ string }`);
    }

    function toString(array, encoding = 'utf8') {
      const base = BASES[encoding];
      if (!base) {
        throw new Error(`Unsupported encoding "${ encoding }"`);
      }
      if ((encoding === 'utf8' || encoding === 'utf-8') && globalThis.Buffer != null && globalThis.Buffer.from != null) {
        return globalThis.Buffer.from(array.buffer, array.byteOffset, array.byteLength).toString('utf8');
      }
      return base.encoder.encode(array).substring(1);
    }

    // From utf8 to base64url and visa versa
    // Adapted from https://github.com/decentralized-identity/did-jwt/blob/056b2e422896436b781ecab2b466bacf72708d23/src/util.ts
    function bnToBase64Url(bn) {
      const bnString = bn.toString();
      const bi = BigInt(bnString);
      const biBytes = bigintToBytes(bi);
      return bytesToBase64(biBytes);
    }
    // Copied from https://github.com/decentralized-identity/did-jwt/blob/056b2e422896436b781ecab2b466bacf72708d23/src/util.ts
    function bytesToBase64(b) {
      return toString(b, 'base64pad');
    }
    // Adapted from https://github.com/decentralized-identity/did-jwt/blob/056b2e422896436b781ecab2b466bacf72708d23/src/util.ts
    function bigintToBytes(n) {
      let b64 = n.toString(16);
      // Pad an extra '0' if the hex string is an odd length
      if (b64.length % 2 !== 0) {
        b64 = `0${b64}`;
      }
      return fromString(b64, 'base16');
    }
    // utf8 string to base64
    function strToBase64(str) {
      return encode_1(str);
    }
    // base64 to utf8 string
    function base64ToStr(str) {
      return decode_1(str);
    }
    // utf8 string to base64url
    function strToBase64Url(str) {
      return universalBase64url.encode(str);
    }
    function objToBase64Url(obj) {
      return universalBase64url.encode(JSON.stringify(obj));
    }
    // base64url to utf8 string
    function base64UrlToStr(str) {
      return universalBase64url.decode(str);
    }
    function base64UrlToObj(str) {
      return JSON.parse(universalBase64url.decode(str));
    }

    class HttpError extends Error {
      constructor(httpError) {
        super('HTTP Error');
        // Ensure the name of this error is the same as the class name
        this.path = void 0;
        this.response = void 0;
        this.code = void 0;
        this.line = void 0;
        this.column = void 0;
        this.sourceURL = void 0;
        this.name = this.constructor.name;
        // This clips the constructor invocation from the stack trace.
        // It's not absolutely essential, but it does make the stack trace a little nicer.
        //  @see Node.js reference (bottom)
        if (Error.captureStackTrace) {
          Error.captureStackTrace(this, this.constructor);
        }
        this.stack = new Error().stack;
        this.path = httpError.path;
        this.response = httpError.response;
        if (httpError.line) this.line = httpError.line;
        if (httpError.column) this.line = httpError.column;
        if (httpError.sourceURL) this.sourceURL = httpError.sourceURL;
        if (httpError.code) this.code = httpError.code;
      }
    }
    class CommunicationError extends Error {
      constructor(communicationError) {
        super('Communication Error');
        this.exception = void 0;
        this.name = 'CommunicationError';
        this.message = communicationError.exception.message;
        this.exception = communicationError.exception;
        // This clips the constructor invocation from the stack trace.
        // It's not absolutely essential, but it does make the stack trace a little nicer.
        //  @see Node.js reference (bottom)
        if (Error.captureStackTrace) {
          Error.captureStackTrace(this, this.constructor);
        } else {
          this.stack = new Error().stack;
        }
      }
    }
    class SdkError extends Error {
      constructor(message) {
        super(message);
        // Ensure the name of this error is the same as the class name
        this.code = void 0;
        this.name = this.constructor.name;
        // This clips the constructor invocation from the stack trace.
        // It's not absolutely essential, but it does make the stack trace a little nicer.
        if (Error.captureStackTrace) {
          Error.captureStackTrace(this, this.constructor);
        } else {
          this.stack = new Error().stack;
        }
      }
    }
    function createSdkError(message, code) {
      let error = new SdkError(message);
      if (code) {
        error = new SdkError(code + ': ' + message);
        error.code = code;
      }
      return error;
    }
    // using never to suppress error https://bobbyhadz.com/blog/typescript-function-that-throws-error#:~:text=To%20declare%20a%20function%20that,terminate%20execution%20of%20the%20program.
    function throwError(message, code) {
      throw createSdkError(message, code);
    }
    exports.SdkErrors = void 0;
    (function (SdkErrors) {
      SdkErrors["AccountDoesntExist"] = "AccountDoesntExist";
      SdkErrors["AccountNotFound"] = "AccountNotFound";
      SdkErrors["AccountServiceError"] = "AccountServiceError";
      SdkErrors["CommunicationNotConnected"] = "CommunicationNotConnected";
      SdkErrors["CommunicationNotLoggedIn"] = "CommunicationNotLoggedIn";
      SdkErrors["CommunicationTimeout"] = "CommunicationTimeout";
      SdkErrors["CouldntCreateApi"] = "CouldntCreateApi";
      SdkErrors["DataQueryNoRowDataFound"] = "DataQueryNoRowDataFound";
      SdkErrors["InvalidLinkAuthRequest"] = "InvalidLinkAuthRequest";
      SdkErrors["InvalidChallenge"] = "InvalidChallenge";
      SdkErrors["InvalidData"] = "InvalidData";
      SdkErrors["InvalidKey"] = "InvalidKey";
      SdkErrors["InvalidArgumentType"] = "InvalidArgumentType";
      SdkErrors["InvalidKeyLevel"] = "InvalidKeyLevel";
      SdkErrors["InvalidQrCode"] = "InvalidQrCode";
      SdkErrors["InvalidUsername"] = "InvalidUsername";
      SdkErrors["InvalidRequestType"] = "InvalidRequestType";
      SdkErrors["InvalidRequestResponseType"] = "InvalidRequestResponseType";
      SdkErrors["JwtNotValid"] = "JwtNotValid";
      SdkErrors["KeyNotFound"] = "KeyNotFound";
      SdkErrors["LinkAuthFailed"] = "LinkAuthFailed";
      SdkErrors["MessageSendError"] = "MessageSendError";
      SdkErrors["MissingChallenge"] = "MissingChallenge";
      SdkErrors["MissingParams"] = "MissingParams";
      SdkErrors["OriginNotFound"] = "OriginNotFound";
      SdkErrors["OriginMismatch"] = "OriginMismatch";
      SdkErrors["PasswordFormatInvalid"] = "PasswordFormatInvalid";
      SdkErrors["PasswordInvalid"] = "PasswordInvalid";
      SdkErrors["RequestsNotFound"] = "RequestsNotFound";
      SdkErrors["ResponsesNotFound"] = "ResponsesNotFound";
      SdkErrors["PasswordTooCommon"] = "PasswordTooCommon";
      SdkErrors["PinInvalid"] = "PinInvalid";
      SdkErrors["ReferrerEmpty"] = "ReferrerEmpty";
      SdkErrors["SenderNotAuthorized"] = "SenderNotAuthorized";
      SdkErrors["SettingsNotInitialized"] = "SettingsNotInitialized";
      SdkErrors["UpdateKeysTransactionNoKeys"] = "UpdateKeysTransactionNoKeys";
      SdkErrors["UserDeactivated"] = "UserDeactivated";
      SdkErrors["UsernameNotFound"] = "UsernameNotFound";
      SdkErrors["UsernameTaken"] = "UsernameTaken";
      SdkErrors["UsernameNotDefined"] = "UsernameNotDefined";
      SdkErrors["UserNotLoggedIn"] = "UserNotLoggedIn";
      SdkErrors["UserNotLoggedInWithThisApp"] = "UserNotLoggedInWithThisApp";
      SdkErrors["UserRefreshed"] = "UserRefreshed";
      SdkErrors["WrongOrigin"] = "WrongOrigin";
      SdkErrors["UserCancelled"] = "UserCancelled";
      SdkErrors["UserLogout"] = "UserLogout";
    })(exports.SdkErrors || (exports.SdkErrors = {}));
    // eslint-disable-next-line @typescript-eslint/no-namespace
    (function (SdkErrors) {
      /*
       * Returns the index of the enum value
       *
       * @param value The value to get the index of
       */
      function indexFor(value) {
        return Object.keys(SdkErrors).indexOf(value);
      }
      SdkErrors.indexFor = indexFor;
      /*
       * Creates an SdkErrors from a string or index of the level
       *
       * @param value The string or index
       */
      function from(value) {
        let index;
        if (typeof value !== 'number') {
          index = SdkErrors.indexFor(value);
        } else {
          index = value;
        }
        return Object.values(SdkErrors)[index];
      }
      SdkErrors.from = from;
    })(exports.SdkErrors || (exports.SdkErrors = {}));

    const secp256k1 = new elliptic__default["default"].ec('secp256k1');
    function randomBytes(bytes) {
      return rb__default["default"](new Uint8Array(bytes));
    }
    function byteArrayToNumber(byteArray) {
      let result = 0;
      for (let i = 0; i < byteArray.length; i++) {
        result += byteArray[i] << i * 8;
      }
      return result;
    }
    function randomNumber(min, max) {
      if (min > max) {
        throwError('Min value cannot be greater than max value');
      }
      const range = max - min;
      const calculateByte = Math.floor(Math.log(range) / Math.log(256)) + 1;
      const randomBytesArray = randomBytes(calculateByte);
      const randomValue = byteArrayToNumber(randomBytesArray) % (range + 1) + min;
      return randomValue;
    }
    function validateKey(keyPair) {
      const result = keyPair.validate();
      if (!result.result) {
        throwError(`Key not valid with reason ${result.reason}`, exports.SdkErrors.InvalidKey);
      }
    }
    /*

    /* Creates a signer from a private key that can be used to sign a JWT
     *
     * @param privateKey the private key to use to sign the JWT
     * @returns a signer (function) that can be used to sign a JWT
     */
    function createSigner(privateKey) {
      if (privateKey.type === antelope.KeyType.K1) {
        return didJwt.ES256KSigner(privateKey.data.array, true);
      }
      if (privateKey.type === antelope.KeyType.R1 || privateKey.type === antelope.KeyType.WA) {
        return didJwt.ES256Signer(privateKey.data.array);
      }
      throw new Error('Unsupported key type');
    }
    function toElliptic(key) {
      let ecKeyPair;
      if (key instanceof antelope.PublicKey) {
        ecKeyPair = secp256k1.keyFromPublic(key.data.array);
      } else {
        ecKeyPair = secp256k1.keyFromPrivate(key.data.array);
      }
      validateKey(ecKeyPair);
      return ecKeyPair;
    }
    function randomString(bytes) {
      const random = randomBytes(bytes);
      return Array.from(random).map(int2hex).join('');
    }
    function sha256(digest) {
      return antelope.Checksum256.hash(antelope.Bytes.from(encodeHex(digest), 'hex')).toString();
    }
    function int2hex(i) {
      return ('0' + i.toString(16)).slice(-2);
    }
    function encodeHex(str) {
      return str.split('').map(c => c.charCodeAt(0).toString(16).padStart(2, '0')).join('');
    }
    function decodeHex(hex) {
      return hex.split(/(\w\w)/g).filter(p => !!p).map(c => String.fromCharCode(parseInt(c, 16))).join('');
    }
    function generateRandomKeyPair() {
      const bytes = randomBytes(32);
      const privateKey = new antelope.PrivateKey(antelope.KeyType.K1, new antelope.Bytes(bytes));
      const publicKey = privateKey.toPublic();
      return {
        privateKey,
        publicKey
      };
    }
    function createVCSigner(keyManager, level) {
      return {
        sign: function (data) {
          try {
            return Promise.resolve(keyManager.signData({
              level,
              data,
              outputType: 'jwt'
            }));
          } catch (e) {
            return Promise.reject(e);
          }
        }
      };
    }

    function copyObject(object) {
      return JSON.parse(JSON.stringify(object));
    }

    // reference links is https://github.com/bitcoin/bips/blob/master/bip-0039/english.txt
    const englishPassphraseWords = ['abandon', 'ability', 'able', 'about', 'above', 'absent', 'absorb', 'abstract', 'absurd', 'abuse', 'access', 'accident', 'account', 'accuse', 'achieve', 'acid', 'acoustic', 'acquire', 'across', 'act', 'action', 'actor', 'actress', 'actual', 'adapt', 'add', 'addict', 'address', 'adjust', 'admit', 'adult', 'advance', 'advice', 'aerobic', 'affair', 'afford', 'afraid', 'again', 'age', 'agent', 'agree', 'ahead', 'aim', 'air', 'airport', 'aisle', 'alarm', 'album', 'alcohol', 'alert', 'alien', 'all', 'alley', 'allow', 'almost', 'alone', 'alpha', 'already', 'also', 'alter', 'always', 'amateur', 'amazing', 'among', 'amount', 'amused', 'analyst', 'anchor', 'ancient', 'anger', 'angle', 'angry', 'animal', 'ankle', 'announce', 'annual', 'another', 'answer', 'antenna', 'antique', 'anxiety', 'any', 'apart', 'apology', 'appear', 'apple', 'approve', 'april', 'arch', 'arctic', 'area', 'arena', 'argue', 'arm', 'armed', 'armor', 'army', 'around', 'arrange', 'arrest', 'arrive', 'arrow', 'art', 'artefact', 'artist', 'artwork', 'ask', 'aspect', 'assault', 'asset', 'assist', 'assume', 'asthma', 'athlete', 'atom', 'attack', 'attend', 'attitude', 'attract', 'auction', 'audit', 'august', 'aunt', 'author', 'auto', 'autumn', 'average', 'avocado', 'avoid', 'awake', 'aware', 'away', 'awesome', 'awful', 'awkward', 'axis', 'baby', 'bachelor', 'bacon', 'badge', 'bag', 'balance', 'balcony', 'ball', 'bamboo', 'banana', 'banner', 'bar', 'barely', 'bargain', 'barrel', 'base', 'basic', 'basket', 'battle', 'beach', 'bean', 'beauty', 'because', 'become', 'beef', 'before', 'begin', 'behave', 'behind', 'believe', 'below', 'belt', 'bench', 'benefit', 'best', 'betray', 'better', 'between', 'beyond', 'bicycle', 'bid', 'bike', 'bind', 'biology', 'bird', 'birth', 'bitter', 'black', 'blade', 'blame', 'blanket', 'blast', 'bleak', 'bless', 'blind', 'blood', 'blossom', 'blouse', 'blue', 'blur', 'blush', 'board', 'boat', 'body', 'boil', 'bomb', 'bone', 'bonus', 'book', 'boost', 'border', 'boring', 'borrow', 'boss', 'bottom', 'bounce', 'box', 'boy', 'bracket', 'brain', 'brand', 'brass', 'brave', 'bread', 'breeze', 'brick', 'bridge', 'brief', 'bright', 'bring', 'brisk', 'broccoli', 'broken', 'bronze', 'broom', 'brother', 'brown', 'brush', 'bubble', 'buddy', 'budget', 'buffalo', 'build', 'bulb', 'bulk', 'bullet', 'bundle', 'bunker', 'burden', 'burger', 'burst', 'bus', 'business', 'busy', 'butter', 'buyer', 'buzz', 'cabbage', 'cabin', 'cable', 'cactus', 'cage', 'cake', 'call', 'calm', 'camera', 'camp', 'can', 'canal', 'cancel', 'candy', 'cannon', 'canoe', 'canvas', 'canyon', 'capable', 'capital', 'captain', 'car', 'carbon', 'card', 'cargo', 'carpet', 'carry', 'cart', 'case', 'cash', 'casino', 'castle', 'casual', 'cat', 'catalog', 'catch', 'category', 'cattle', 'caught', 'cause', 'caution', 'cave', 'ceiling', 'celery', 'cement', 'census', 'century', 'cereal', 'certain', 'chair', 'chalk', 'champion', 'change', 'chaos', 'chapter', 'charge', 'chase', 'chat', 'cheap', 'check', 'cheese', 'chef', 'cherry', 'chest', 'chicken', 'chief', 'child', 'chimney', 'choice', 'choose', 'chronic', 'chuckle', 'chunk', 'churn', 'cigar', 'cinnamon', 'circle', 'citizen', 'city', 'civil', 'claim', 'clap', 'clarify', 'claw', 'clay', 'clean', 'clerk', 'clever', 'click', 'client', 'cliff', 'climb', 'clinic', 'clip', 'clock', 'clog', 'close', 'cloth', 'cloud', 'clown', 'club', 'clump', 'cluster', 'clutch', 'coach', 'coast', 'coconut', 'code', 'coffee', 'coil', 'coin', 'collect', 'color', 'column', 'combine', 'come', 'comfort', 'comic', 'common', 'company', 'concert', 'conduct', 'confirm', 'congress', 'connect', 'consider', 'control', 'convince', 'cook', 'cool', 'copper', 'copy', 'coral', 'core', 'corn', 'correct', 'cost', 'cotton', 'couch', 'country', 'couple', 'course', 'cousin', 'cover', 'coyote', 'crack', 'cradle', 'craft', 'cram', 'crane', 'crash', 'crater', 'crawl', 'crazy', 'cream', 'credit', 'creek', 'crew', 'cricket', 'crime', 'crisp', 'critic', 'crop', 'cross', 'crouch', 'crowd', 'crucial', 'cruel', 'cruise', 'crumble', 'crunch', 'crush', 'cry', 'crystal', 'cube', 'culture', 'cup', 'cupboard', 'curious', 'current', 'curtain', 'curve', 'cushion', 'custom', 'cute', 'cycle', 'dad', 'damage', 'damp', 'dance', 'danger', 'daring', 'dash', 'daughter', 'dawn', 'day', 'deal', 'debate', 'debris', 'decade', 'december', 'decide', 'decline', 'decorate', 'decrease', 'deer', 'defense', 'define', 'defy', 'degree', 'delay', 'deliver', 'demand', 'demise', 'denial', 'dentist', 'deny', 'depart', 'depend', 'deposit', 'depth', 'deputy', 'derive', 'describe', 'desert', 'design', 'desk', 'despair', 'destroy', 'detail', 'detect', 'develop', 'device', 'devote', 'diagram', 'dial', 'diamond', 'diary', 'dice', 'diesel', 'diet', 'differ', 'digital', 'dignity', 'dilemma', 'dinner', 'dinosaur', 'direct', 'dirt', 'disagree', 'discover', 'disease', 'dish', 'dismiss', 'disorder', 'display', 'distance', 'divert', 'divide', 'divorce', 'dizzy', 'doctor', 'document', 'dog', 'doll', 'dolphin', 'domain', 'donate', 'donkey', 'donor', 'door', 'dose', 'double', 'dove', 'draft', 'dragon', 'drama', 'drastic', 'draw', 'dream', 'dress', 'drift', 'drill', 'drink', 'drip', 'drive', 'drop', 'drum', 'dry', 'duck', 'dumb', 'dune', 'during', 'dust', 'dutch', 'duty', 'dwarf', 'dynamic', 'eager', 'eagle', 'early', 'earn', 'earth', 'easily', 'east', 'easy', 'echo', 'ecology', 'economy', 'edge', 'edit', 'educate', 'effort', 'egg', 'eight', 'either', 'elbow', 'elder', 'electric', 'elegant', 'element', 'elephant', 'elevator', 'elite', 'else', 'embark', 'embody', 'embrace', 'emerge', 'emotion', 'employ', 'empower', 'empty', 'enable', 'enact', 'end', 'endless', 'endorse', 'enemy', 'energy', 'enforce', 'engage', 'engine', 'enhance', 'enjoy', 'enlist', 'enough', 'enrich', 'enroll', 'ensure', 'enter', 'entire', 'entry', 'envelope', 'episode', 'equal', 'equip', 'era', 'erase', 'erode', 'erosion', 'error', 'erupt', 'escape', 'essay', 'essence', 'estate', 'eternal', 'ethics', 'evidence', 'evil', 'evoke', 'evolve', 'exact', 'example', 'excess', 'exchange', 'excite', 'exclude', 'excuse', 'execute', 'exercise', 'exhaust', 'exhibit', 'exile', 'exist', 'exit', 'exotic', 'expand', 'expect', 'expire', 'explain', 'expose', 'express', 'extend', 'extra', 'eye', 'eyebrow', 'fabric', 'face', 'faculty', 'fade', 'faint', 'faith', 'fall', 'false', 'fame', 'family', 'famous', 'fan', 'fancy', 'fantasy', 'farm', 'fashion', 'fat', 'fatal', 'father', 'fatigue', 'fault', 'favorite', 'feature', 'february', 'federal', 'fee', 'feed', 'feel', 'female', 'fence', 'festival', 'fetch', 'fever', 'few', 'fiber', 'fiction', 'field', 'figure', 'file', 'film', 'filter', 'final', 'find', 'fine', 'finger', 'finish', 'fire', 'firm', 'first', 'fiscal', 'fish', 'fit', 'fitness', 'fix', 'flag', 'flame', 'flash', 'flat', 'flavor', 'flee', 'flight', 'flip', 'float', 'flock', 'floor', 'flower', 'fluid', 'flush', 'fly', 'foam', 'focus', 'fog', 'foil', 'fold', 'follow', 'food', 'foot', 'force', 'forest', 'forget', 'fork', 'fortune', 'forum', 'forward', 'fossil', 'foster', 'found', 'fox', 'fragile', 'frame', 'frequent', 'fresh', 'friend', 'fringe', 'frog', 'front', 'frost', 'frown', 'frozen', 'fruit', 'fuel', 'fun', 'funny', 'furnace', 'fury', 'future', 'gadget', 'gain', 'galaxy', 'gallery', 'game', 'gap', 'garage', 'garbage', 'garden', 'garlic', 'garment', 'gas', 'gasp', 'gate', 'gather', 'gauge', 'gaze', 'general', 'genius', 'genre', 'gentle', 'genuine', 'gesture', 'ghost', 'giant', 'gift', 'giggle', 'ginger', 'giraffe', 'girl', 'give', 'glad', 'glance', 'glare', 'glass', 'glide', 'glimpse', 'globe', 'gloom', 'glory', 'glove', 'glow', 'glue', 'goat', 'goddess', 'gold', 'good', 'goose', 'gorilla', 'gospel', 'gossip', 'govern', 'gown', 'grab', 'grace', 'grain', 'grant', 'grape', 'grass', 'gravity', 'great', 'green', 'grid', 'grief', 'grit', 'grocery', 'group', 'grow', 'grunt', 'guard', 'guess', 'guide', 'guilt', 'guitar', 'gun', 'gym', 'habit', 'hair', 'half', 'hammer', 'hamster', 'hand', 'happy', 'harbor', 'hard', 'harsh', 'harvest', 'hat', 'have', 'hawk', 'hazard', 'head', 'health', 'heart', 'heavy', 'hedgehog', 'height', 'hello', 'helmet', 'help', 'hen', 'hero', 'hidden', 'high', 'hill', 'hint', 'hip', 'hire', 'history', 'hobby', 'hockey', 'hold', 'hole', 'holiday', 'hollow', 'home', 'honey', 'hood', 'hope', 'horn', 'horror', 'horse', 'hospital', 'host', 'hotel', 'hour', 'hover', 'hub', 'huge', 'human', 'humble', 'humor', 'hundred', 'hungry', 'hunt', 'hurdle', 'hurry', 'hurt', 'husband', 'hybrid', 'ice', 'icon', 'idea', 'identify', 'idle', 'ignore', 'ill', 'illegal', 'illness', 'image', 'imitate', 'immense', 'immune', 'impact', 'impose', 'improve', 'impulse', 'inch', 'include', 'income', 'increase', 'index', 'indicate', 'indoor', 'industry', 'infant', 'inflict', 'inform', 'inhale', 'inherit', 'initial', 'inject', 'injury', 'inmate', 'inner', 'innocent', 'input', 'inquiry', 'insane', 'insect', 'inside', 'inspire', 'install', 'intact', 'interest', 'into', 'invest', 'invite', 'involve', 'iron', 'island', 'isolate', 'issue', 'item', 'ivory', 'jacket', 'jaguar', 'jar', 'jazz', 'jealous', 'jeans', 'jelly', 'jewel', 'job', 'join', 'joke', 'journey', 'joy', 'judge', 'juice', 'jump', 'jungle', 'junior', 'junk', 'just', 'kangaroo', 'keen', 'keep', 'ketchup', 'key', 'kick', 'kid', 'kidney', 'kind', 'kingdom', 'kiss', 'kit', 'kitchen', 'kite', 'kitten', 'kiwi', 'knee', 'knife', 'knock', 'know', 'lab', 'label', 'labor', 'ladder', 'lady', 'lake', 'lamp', 'language', 'laptop', 'large', 'later', 'latin', 'laugh', 'laundry', 'lava', 'law', 'lawn', 'lawsuit', 'layer', 'lazy', 'leader', 'leaf', 'learn', 'leave', 'lecture', 'left', 'leg', 'legal', 'legend', 'leisure', 'lemon', 'lend', 'length', 'lens', 'leopard', 'lesson', 'letter', 'level', 'liar', 'liberty', 'library', 'license', 'life', 'lift', 'light', 'like', 'limb', 'limit', 'link', 'lion', 'liquid', 'list', 'little', 'live', 'lizard', 'load', 'loan', 'lobster', 'local', 'lock', 'logic', 'lonely', 'long', 'loop', 'lottery', 'loud', 'lounge', 'love', 'loyal', 'lucky', 'luggage', 'lumber', 'lunar', 'lunch', 'luxury', 'lyrics', 'machine', 'mad', 'magic', 'magnet', 'maid', 'mail', 'main', 'major', 'make', 'mammal', 'man', 'manage', 'mandate', 'mango', 'mansion', 'manual', 'maple', 'marble', 'march', 'margin', 'marine', 'market', 'marriage', 'mask', 'mass', 'master', 'match', 'material', 'math', 'matrix', 'matter', 'maximum', 'maze', 'meadow', 'mean', 'measure', 'meat', 'mechanic', 'medal', 'media', 'melody', 'melt', 'member', 'memory', 'mention', 'menu', 'mercy', 'merge', 'merit', 'merry', 'mesh', 'message', 'metal', 'method', 'middle', 'midnight', 'milk', 'million', 'mimic', 'mind', 'minimum', 'minor', 'minute', 'miracle', 'mirror', 'misery', 'miss', 'mistake', 'mix', 'mixed', 'mixture', 'mobile', 'model', 'modify', 'mom', 'moment', 'monitor', 'monkey', 'monster', 'month', 'moon', 'moral', 'more', 'morning', 'mosquito', 'mother', 'motion', 'motor', 'mountain', 'mouse', 'move', 'movie', 'much', 'muffin', 'mule', 'multiply', 'muscle', 'museum', 'mushroom', 'music', 'must', 'mutual', 'myself', 'mystery', 'myth', 'naive', 'name', 'napkin', 'narrow', 'nasty', 'nation', 'nature', 'near', 'neck', 'need', 'negative', 'neglect', 'neither', 'nephew', 'nerve', 'nest', 'net', 'network', 'neutral', 'never', 'news', 'next', 'nice', 'night', 'noble', 'noise', 'nominee', 'noodle', 'normal', 'north', 'nose', 'notable', 'note', 'nothing', 'notice', 'novel', 'now', 'nuclear', 'number', 'nurse', 'nut', 'oak', 'obey', 'object', 'oblige', 'obscure', 'observe', 'obtain', 'obvious', 'occur', 'ocean', 'october', 'odor', 'off', 'offer', 'office', 'often', 'oil', 'okay', 'old', 'olive', 'olympic', 'omit', 'once', 'one', 'onion', 'online', 'only', 'open', 'opera', 'opinion', 'oppose', 'option', 'orange', 'orbit', 'orchard', 'order', 'ordinary', 'organ', 'orient', 'original', 'orphan', 'ostrich', 'other', 'outdoor', 'outer', 'output', 'outside', 'oval', 'oven', 'over', 'own', 'owner', 'oxygen', 'oyster', 'ozone', 'pact', 'paddle', 'page', 'pair', 'palace', 'palm', 'panda', 'panel', 'panic', 'panther', 'paper', 'parade', 'parent', 'park', 'parrot', 'party', 'pass', 'patch', 'path', 'patient', 'patrol', 'pattern', 'pause', 'pave', 'payment', 'peace', 'peanut', 'pear', 'peasant', 'pelican', 'pen', 'penalty', 'pencil', 'people', 'pepper', 'perfect', 'permit', 'person', 'pet', 'phone', 'photo', 'phrase', 'physical', 'piano', 'picnic', 'picture', 'piece', 'pig', 'pigeon', 'pill', 'pilot', 'pink', 'pioneer', 'pipe', 'pistol', 'pitch', 'pizza', 'place', 'planet', 'plastic', 'plate', 'play', 'please', 'pledge', 'pluck', 'plug', 'plunge', 'poem', 'poet', 'point', 'polar', 'pole', 'police', 'pond', 'pony', 'pool', 'popular', 'portion', 'position', 'possible', 'post', 'potato', 'pottery', 'poverty', 'powder', 'power', 'practice', 'praise', 'predict', 'prefer', 'prepare', 'present', 'pretty', 'prevent', 'price', 'pride', 'primary', 'print', 'priority', 'prison', 'private', 'prize', 'problem', 'process', 'produce', 'profit', 'program', 'project', 'promote', 'proof', 'property', 'prosper', 'protect', 'proud', 'provide', 'public', 'pudding', 'pull', 'pulp', 'pulse', 'pumpkin', 'punch', 'pupil', 'puppy', 'purchase', 'purity', 'purpose', 'purse', 'push', 'put', 'puzzle', 'pyramid', 'quality', 'quantum', 'quarter', 'question', 'quick', 'quit', 'quiz', 'quote', 'rabbit', 'raccoon', 'race', 'rack', 'radar', 'radio', 'rail', 'rain', 'raise', 'rally', 'ramp', 'ranch', 'random', 'range', 'rapid', 'rare', 'rate', 'rather', 'raven', 'raw', 'razor', 'ready', 'real', 'reason', 'rebel', 'rebuild', 'recall', 'receive', 'recipe', 'record', 'recycle', 'reduce', 'reflect', 'reform', 'refuse', 'region', 'regret', 'regular', 'reject', 'relax', 'release', 'relief', 'rely', 'remain', 'remember', 'remind', 'remove', 'render', 'renew', 'rent', 'reopen', 'repair', 'repeat', 'replace', 'report', 'require', 'rescue', 'resemble', 'resist', 'resource', 'response', 'result', 'retire', 'retreat', 'return', 'reunion', 'reveal', 'review', 'reward', 'rhythm', 'rib', 'ribbon', 'rice', 'rich', 'ride', 'ridge', 'rifle', 'right', 'rigid', 'ring', 'riot', 'ripple', 'risk', 'ritual', 'rival', 'river', 'road', 'roast', 'robot', 'robust', 'rocket', 'romance', 'roof', 'rookie', 'room', 'rose', 'rotate', 'rough', 'round', 'route', 'royal', 'rubber', 'rude', 'rug', 'rule', 'run', 'runway', 'rural', 'sad', 'saddle', 'sadness', 'safe', 'sail', 'salad', 'salmon', 'salon', 'salt', 'salute', 'same', 'sample', 'sand', 'satisfy', 'satoshi', 'sauce', 'sausage', 'save', 'say', 'scale', 'scan', 'scare', 'scatter', 'scene', 'scheme', 'school', 'science', 'scissors', 'scorpion', 'scout', 'scrap', 'screen', 'script', 'scrub', 'sea', 'search', 'season', 'seat', 'second', 'secret', 'section', 'security', 'seed', 'seek', 'segment', 'select', 'sell', 'seminar', 'senior', 'sense', 'sentence', 'series', 'service', 'session', 'settle', 'setup', 'seven', 'shadow', 'shaft', 'shallow', 'share', 'shed', 'shell', 'sheriff', 'shield', 'shift', 'shine', 'ship', 'shiver', 'shock', 'shoe', 'shoot', 'shop', 'short', 'shoulder', 'shove', 'shrimp', 'shrug', 'shuffle', 'shy', 'sibling', 'sick', 'side', 'siege', 'sight', 'sign', 'silent', 'silk', 'silly', 'silver', 'similar', 'simple', 'since', 'sing', 'siren', 'sister', 'situate', 'six', 'size', 'skate', 'sketch', 'ski', 'skill', 'skin', 'skirt', 'skull', 'slab', 'slam', 'sleep', 'slender', 'slice', 'slide', 'slight', 'slim', 'slogan', 'slot', 'slow', 'slush', 'small', 'smart', 'smile', 'smoke', 'smooth', 'snack', 'snake', 'snap', 'sniff', 'snow', 'soap', 'soccer', 'social', 'sock', 'soda', 'soft', 'solar', 'soldier', 'solid', 'solution', 'solve', 'someone', 'song', 'soon', 'sorry', 'sort', 'soul', 'sound', 'soup', 'source', 'south', 'space', 'spare', 'spatial', 'spawn', 'speak', 'special', 'speed', 'spell', 'spend', 'sphere', 'spice', 'spider', 'spike', 'spin', 'spirit', 'split', 'spoil', 'sponsor', 'spoon', 'sport', 'spot', 'spray', 'spread', 'spring', 'spy', 'square', 'squeeze', 'squirrel', 'stable', 'stadium', 'staff', 'stage', 'stairs', 'stamp', 'stand', 'start', 'state', 'stay', 'steak', 'steel', 'stem', 'step', 'stereo', 'stick', 'still', 'sting', 'stock', 'stomach', 'stone', 'stool', 'story', 'stove', 'strategy', 'street', 'strike', 'strong', 'struggle', 'student', 'stuff', 'stumble', 'style', 'subject', 'submit', 'subway', 'success', 'such', 'sudden', 'suffer', 'sugar', 'suggest', 'suit', 'summer', 'sun', 'sunny', 'sunset', 'super', 'supply', 'supreme', 'sure', 'surface', 'surge', 'surprise', 'surround', 'survey', 'suspect', 'sustain', 'swallow', 'swamp', 'swap', 'swarm', 'swear', 'sweet', 'swift', 'swim', 'swing', 'switch', 'sword', 'symbol', 'symptom', 'syrup', 'system', 'table', 'tackle', 'tag', 'tail', 'talent', 'talk', 'tank', 'tape', 'target', 'task', 'taste', 'tattoo', 'taxi', 'teach', 'team', 'tell', 'ten', 'tenant', 'tennis', 'tent', 'term', 'test', 'text', 'thank', 'that', 'theme', 'then', 'theory', 'there', 'they', 'thing', 'this', 'thought', 'three', 'thrive', 'throw', 'thumb', 'thunder', 'ticket', 'tide', 'tiger', 'tilt', 'timber', 'time', 'tiny', 'tip', 'tired', 'tissue', 'title', 'toast', 'tobacco', 'today', 'toddler', 'toe', 'together', 'toilet', 'token', 'tomato', 'tomorrow', 'tone', 'tongue', 'tonight', 'tool', 'tooth', 'top', 'topic', 'topple', 'torch', 'tornado', 'tortoise', 'toss', 'total', 'tourist', 'toward', 'tower', 'town', 'toy', 'track', 'trade', 'traffic', 'tragic', 'train', 'transfer', 'trap', 'trash', 'travel', 'tray', 'treat', 'tree', 'trend', 'trial', 'tribe', 'trick', 'trigger', 'trim', 'trip', 'trophy', 'trouble', 'truck', 'true', 'truly', 'trumpet', 'trust', 'truth', 'try', 'tube', 'tuition', 'tumble', 'tuna', 'tunnel', 'turkey', 'turn', 'turtle', 'twelve', 'twenty', 'twice', 'twin', 'twist', 'two', 'type', 'typical', 'ugly', 'umbrella', 'unable', 'unaware', 'uncle', 'uncover', 'under', 'undo', 'unfair', 'unfold', 'unhappy', 'uniform', 'unique', 'unit', 'universe', 'unknown', 'unlock', 'until', 'unusual', 'unveil', 'update', 'upgrade', 'uphold', 'upon', 'upper', 'upset', 'urban', 'urge', 'usage', 'use', 'used', 'useful', 'useless', 'usual', 'utility', 'vacant', 'vacuum', 'vague', 'valid', 'valley', 'valve', 'van', 'vanish', 'vapor', 'various', 'vast', 'vault', 'vehicle', 'velvet', 'vendor', 'venture', 'venue', 'verb', 'verify', 'version', 'very', 'vessel', 'veteran', 'viable', 'vibrant', 'vicious', 'victory', 'video', 'view', 'village', 'vintage', 'violin', 'virtual', 'virus', 'visa', 'visit', 'visual', 'vital', 'vivid', 'vocal', 'voice', 'void', 'volcano', 'volume', 'vote', 'voyage', 'wage', 'wagon', 'wait', 'walk', 'wall', 'walnut', 'want', 'warfare', 'warm', 'warrior', 'wash', 'wasp', 'waste', 'water', 'wave', 'way', 'wealth', 'weapon', 'wear', 'weasel', 'weather', 'web', 'wedding', 'weekend', 'weird', 'welcome', 'west', 'wet', 'whale', 'what', 'wheat', 'wheel', 'when', 'where', 'whip', 'whisper', 'wide', 'width', 'wife', 'wild', 'will', 'win', 'window', 'wine', 'wing', 'wink', 'winner', 'winter', 'wire', 'wisdom', 'wise', 'wish', 'witness', 'wolf', 'woman', 'wonder', 'wood', 'wool', 'word', 'work', 'world', 'worry', 'worth', 'wrap', 'wreck', 'wrestle', 'wrist', 'write', 'wrong', 'yard', 'year', 'yellow', 'you', 'young', 'youth', 'zebra', 'zero', 'zone', 'zoo'];

    /**
     * Generates an array of random keywords.
     * @returns {string[]} An array of 6 random keywords.
     */
    function generateRandomKeywords() {
      const randomIndices = [];
      while (randomIndices.length < 6) {
        const randomIndex = randomNumber(0, 2047);
        if (!randomIndices.includes(randomIndex)) {
          randomIndices.push(randomIndex);
        }
      }
      const randomKeywords = randomIndices.map(index => englishPassphraseWords[index]);
      return randomKeywords;
    }
    /**
     * Generates auto-suggestions based on the input string.
     * @param {string} inputString - The input string for which auto-suggestions are generated.
     * @returns {string[]} An array of auto-suggestions with a maximum of 4 words.
     */
    function generateAutoSuggestions(inputString) {
      if (inputString.trim() === '') {
        return []; // Return an empty array for empty input string
      }

      inputString = inputString.toLowerCase();
      const matchingSuggestions = englishPassphraseWords.filter(word => word.toLowerCase().includes(inputString)).slice(0, 4);
      return matchingSuggestions;
    }
    /**
     * Checks if the input string is a valid keyword.
     * @param {string} word - The input string to be checked.
     * @returns {boolean} True if the input string is a valid keyword, false otherwise.
     */
    function isKeyword(word) {
      return englishPassphraseWords.includes(word);
    }

    if (typeof Proxy === 'undefined') {
      throw new Error("This browser doesn't support Proxy");
    }
    let settings;
    let initialized = false;
    function setSettings(newSettings) {
      if (newSettings.loggerLevel === 'debug') console.debug('setSettings', newSettings);
      settings = newSettings;
      initialized = true;
    }
    function getSettings() {
      if (!initialized) {
        throwError('Settings not yet initialized', exports.SdkErrors.SettingsNotInitialized);
      }
      const proxy = new Proxy(settings, {
        get(target, name, receiver) {
          if (Reflect.has(target, name)) {
            return Reflect.get(target, name, receiver);
          }
          throw new Error(`Tonomy SDK settings has not been initialized using setSettings() with property for variable: ${name.toString()}`);
        }
      });
      return proxy;
    }
    function isProduction() {
      if (!initialized) {
        throwError('Settings not yet initialized', exports.SdkErrors.SettingsNotInitialized);
      }
      return ['production', 'staging', 'testnet'].includes(settings.environment);
    }

    // reference https://github.com/OR13/did-jwk/blob/main/src/index.js#L177
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const resolve = function (did, options = {}) {
      try {
        if (options) options = {};
        const decoded = base64ToStr(did.split(':').pop().split('#')[0]);
        const jwk = JSON.parse(decoded.toString());
        const didDoc = toDidDocument(jwk);
        return Promise.resolve({
          didResolutionMetadata: {
            contentType: 'application/did+ld+json'
          },
          didDocument: didDoc,
          didDocumentMetadata: {}
        });
      } catch (e) {
        return Promise.reject(e);
      }
    };
    function createJWK(publicKey) {
      const ecPubKey = toElliptic(publicKey);
      const publicKeyJwk = {
        crv: 'secp256k1',
        kty: 'EC',
        x: bnToBase64Url(ecPubKey.getPublic().getX()),
        y: bnToBase64Url(ecPubKey.getPublic().getY()),
        kid: publicKey.toString()
      };
      return publicKeyJwk;
    }
    // reference https://github.com/OR13/did-jwk/blob/main/src/index.js#L120
    function toDid(jwk) {
      // eslint-disable-next-line no-unused-vars
      const {
        d,
        p,
        q,
        dp,
        dq,
        qi,
        ...publicKeyJwk
      } = jwk;
      // TODO replace with base64url encoder for web
      const id = strToBase64(JSON.stringify(publicKeyJwk));
      const did = `did:jwk:${id}`;
      return did;
    }
    // reference https://github.com/OR13/did-jwk/blob/main/src/index.js#L128
    function toDidDocument(jwk) {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const getPublicOperationsFromPrivate = keyOps => {
        if (keyOps.includes('sign')) {
          return ['verify'];
        }
        if (keyOps.includes('verify')) {
          return ['encrypt'];
        }
        return keyOps;
      };
      const {
        // eslint-disable-next-line no-unused-vars
        d,
        p,
        q,
        dp,
        dq,
        qi,
        // eslint-disable-next-line camelcase
        key_ops,
        ...publicKeyJwk
      } = jwk;
      // eslint-disable-next-line camelcase
      if (d && key_ops) {
        // eslint-disable-next-line camelcase
        publicKeyJwk.key_ops = getPublicOperationsFromPrivate(key_ops);
      }
      const did = toDid(publicKeyJwk);
      const vm = {
        id: '#0',
        type: 'JsonWebKey2020',
        controller: did,
        publicKeyJwk
      };
      const didDocument = {
        '@context': ['https://www.w3.org/ns/did/v1', {
          '@vocab': 'https://www.iana.org/assignments/jose#'
        }],
        id: did,
        verificationMethod: [vm]
      };
      return didDocument;
    }
    function getResolver() {
      return {
        jwk: (did,
        // @ts-expect-error(TS6133 declared but never used)
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        parsed,
        // @ts-expect-error(TS6133 declared but never used)
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        resolver) => {
          return resolve(did);
        }
      };
    }

    /**
     * Sleeps for the given number of milliseconds
     *
     * @async
     * @param {number} ms - Number of milliseconds to sleep
     */
    const sleep = function (ms) {
      try {
        return Promise.resolve(new Promise(resolve => setTimeout(resolve, ms)));
      } catch (e) {
        return Promise.reject(e);
      }
    };
    /**
     * Takes the number of seconds since epoch and returns a Date object
     *
     * @param {number} secs - Number of seconds since epoch
     * @returns {Date} - Date object
     */
    function toDateTime(secs) {
      const t = new Date(1970, 0, 1); // Epoch
      t.setSeconds(secs);
      return t;
    }

    /**
     * A W3C Verifiable Credential
     */
    class VerifiableCredential {
      /**
       * @param {JWT} jwt - a JWT string
       *
       * @returns {VerifiableCredential} a VerifiableCredential object
       */
      constructor(jwt) {
        this.decodedJwt = void 0;
        this.jwt = void 0;
        this.decodedJwt = didJwt.decodeJWT(jwt);
        this.jwt = jwt;
      }
      /**
       * Returns the payload of the JWT
       *
       * @returns {JWTPayload} the payload of the JWT
       */
      getPayload() {
        return this.decodedJwt.payload;
      }
      /**
       * Returns the vc object of the JWT
       *
       * @returns {JWTVCPayload} the vc object
       */
      getVc() {
        return this.getPayload().vc;
      }
      /**
       * Returns the credentialSubject object of the Verifiable Credential
       *
       * @returns {any} the credentialSubject object
       */
      getCredentialSubject() {
        return this.getVc().credentialSubject;
      }
      /**
       * Returns the issuer of the Verifiable Credential
       *
       * @returns {DIDurl | undefined} the issuer
       */
      getIssuer() {
        return this.getPayload().iss;
      }
      /**
       * Returns the subject of the Verifiable Credential
       *
       * @returns {DIDurl | undefined} the subject of the Verifiable Credential
       */
      getSubject() {
        return this.getPayload().sub;
      }
      /**
       * Returns the ID of the Verifiable Credential
       *
       * @returns {URL | undefined} the id
       */
      getId() {
        return this.getPayload().jti;
      }
      /**
       * Returns the audience of the Verifiable Credential
       *
       * @returns {DIDurl | DIDurl[] | undefined} the audience
       */
      getAudience() {
        return this.getPayload().aud;
      }
      /**
       * Returns the expiration of the Verifiable Credential
       *
       * @returns {Date | undefined} the expiration
       */
      getExpiration() {
        const secSinceEpoc = this.getPayload().exp;
        if (secSinceEpoc) {
          return toDateTime(secSinceEpoc);
        } else return undefined;
      }
      /**
       * Returns the issued time of the Verifiable Credential
       *
       * @returns {Date | undefined} the issued time
       */
      getIssuedAt() {
        const secSinceEpoc = this.getPayload().iat;
        if (secSinceEpoc) {
          return toDateTime(secSinceEpoc);
        } else return undefined;
      }
      /**
       * Returns the time the verifiable credential is valid after
       *
       * @returns {Date | undefined} the time the verifiable credential is valid after
       */
      getNotBefore() {
        const secSinceEpoc = this.getPayload().nbf;
        if (secSinceEpoc) {
          return toDateTime(secSinceEpoc);
        } else return undefined;
      }
      /**
       * Verifies the Verifiable Credential is signed by the issuer
       *
       * @returns {Promise<VerifiedCredential>} the verified credential
       * @throws {Error} if the Verifiable Credential is not signed correctly by the issuer
       */
      verify() {
        try {
          const _this = this;
          const settings = getSettings();
          // @ts-expect-error did-resolver and @tonomy/did-resolver types are not compatible
          const resolver = new didResolver.Resolver({
            ...getResolver(),
            ...antelopeDidResolver.getResolver({
              antelopeChainUrl: settings.blockchainUrl,
              fetch: crossFetch__default["default"]
            })
          });
          return Promise.resolve(didJwtVc.verifyCredential(_this.jwt, resolver));
        } catch (e) {
          return Promise.reject(e);
        }
      }
      /**
       * Creates a new Verifiable Credential object signed by the issuer
       *
       * @param {DIDurl} id - the id of the Verifiable Credential
       * @param {string[]} type - the type of the Verifiable Credential
       * @param {object} credentialSubject - the credential subject of the Verifiable Credential
       * @param {Issuer} issuer - the issuer of the Verifiable Credential
       * @property {URL} [options.subject] - the subject of the Verifiable Credential
       *
       * @returns {Promise<VerifiableCredential>} the Verifiable Credential
       */
      static sign(id, type, credentialSubject, issuer, options = {}) {
        try {
          const typeArray = Array.isArray(type) ? type : [type];
          if (!typeArray.includes('VerifiableCredential')) typeArray.push('VerifiableCredential');
          const vc = {
            '@context': ['https://www.w3.org/2018/credentials/v1'],
            id,
            type: typeArray,
            issuer: {
              id: issuer.did
            },
            issuanceDate: new Date().toISOString(),
            credentialSubject: credentialSubject
          };
          if (options.subject) vc.credentialSubject.id = options.subject;
          return Promise.resolve(didJwtVc.createVerifiableCredentialJwt(vc, issuer, {
            canonicalize: true
          })).then(function (jwt) {
            return new VerifiableCredential(jwt);
          });
        } catch (e) {
          return Promise.reject(e);
        }
      }
      /**
       * Returns the JWT string
       *
       * @returns {string} the JWT string
       */
      toString() {
        return this.jwt;
      }
      /**
       * Returns the JSON string representation of the object - which is the jwt string
       *
       * @description This is used in JSON.stringify(). It is not recommended to use this method directly.
       * Only the jwt is returned, not the full object. This is all that is needed to reconstruct the
       * full object in the constructor, and thus minimizes the size of the JSON string.
       *
       * @override Serializable.toJSON
       * @returns {string} the jwt
       */
      toJSON() {
        return this.toString();
      }
    }
    /**
     * A wrapper that adds a type object to VCs to allow for identification, and presents a simper interface
     *
     * This is the base class. It is expected that extension classes will be created for the different VC types.
     *
     * @inheritdoc sign() is a protected alternative constructor. In child classes, a new alternative constructor
     * should be created which returns the child class type.
     * @inheritdoc protected "type" property should be overridden in child classes with the name of the class
     * @inheritdoc if the payload type requires ad-hoc decoding, override the constructor and decode the payload
     *
     * @example see an example of the above in the LoginRequestMessage class in `../..services/communication/messages.ts`
     */
    class VerifiableCredentialWithType {
      /**
       *
       * @param vc the VC to wrap
       *
       * @inheritdoc override me if the payload type requires ad-hoc decoding
       */
      constructor(vc) {
        this.vc = void 0;
        this.decodedPayload = void 0;
        if (typeof vc === 'string') {
          this.vc = new VerifiableCredential(vc);
        } else if (vc instanceof VerifiableCredentialWithType) {
          this.vc = vc.getVc();
        } else {
          this.vc = vc;
        }
        this.decodedPayload = this.getVc().getCredentialSubject().payload;
      }
      /**
       * Creates a signed VC object
       *
       * @access protected
       *
       * @param {object} payload the payload
       * @param {Issuer} issuer the issuer id
       * @param {VerifiableCredentialOptions} options the options
       *
       * @returns a VC object
       */
      static sign(payload, issuer, options = {}) {
        try {
          const _this2 = this;
          const payloadType = _this2.type;
          if (payloadType === 'VerifiableCredentialWithType' || payloadType === '') {
            throw new Error('class should be a derived class of VerifiableCredentialWithType to use the type property');
          }
          const credentialSubject = Object.assign({}, {
            payload,
            type: payloadType
          });
          const id = 'https://tonomy.foundation/vc/id/' + randomString(10);
          const vcType = ['VerifiableCredential', 'TonomyVerifiableCredentialWithType'];
          if (options.additionalTypes) {
            vcType.push(...options.additionalTypes);
          }
          return Promise.resolve(VerifiableCredential.sign(id, vcType, credentialSubject, issuer, options)).then(function (vc) {
            return new VerifiableCredentialWithType(vc);
          });
        } catch (e) {
          return Promise.reject(e);
        }
      }
      /**
       * Returns the type of the VC
       * @returns {string} the class type of the VC
       */
      static getType() {
        return this.type;
      }
      /**
       * Returns the internal Verifiable Credential
       * @returns {VerifiableCredential} the VC
       */
      getVc() {
        return this.vc;
      }
      /**
       * Returns the issuer of the payload
       * @returns {DIDurl} the payload issuer
       */
      getIssuer() {
        return this.getVc().getIssuer();
      }
      /**
       * Returns the payload
       * @returns {object} the payload
       */
      getPayload() {
        return this.decodedPayload;
      }
      /**
       * Returns the payload type used to determine what kind of payload it is
       * @returns {string | undefined} the payload type
       */
      getType() {
        return this.getVc().getCredentialSubject().type;
      }
      /**
       * Verifies that the VC is signed by the issuer
       *
       * @returns {Promise<boolean>} true if the VC is signed by the issuer
       * @throws {Error} if the VC is not signed by the issuer
       */
      verify() {
        try {
          const _this3 = this;
          return Promise.resolve(_this3.getVc().verify()).then(function (_this3$getVc$verify) {
            return _this3$getVc$verify.verified;
          });
        } catch (e) {
          return Promise.reject(e);
        }
      }
      /**
       * Returns the JWT string
       *
       * @returns {string} the JWT string
       */
      toString() {
        return this.getVc().toString();
      }
      /**
       * Returns the JSON string representation of the object - which is the jwt string
       *
       * @description This is used in JSON.stringify(). It is not recommended to use this method directly.
       * Only the jwt is returned, not the full object. This is all that is needed to reconstruct the
       * full object in the constructor, and thus minimizes the size of the JSON string.
       *
       * @override Serializable.toJSON
       * @returns {string} the jwt
       */
      toJSON() {
        return this.toString();
      }
    }
    VerifiableCredentialWithType.type = 'VerifiableCredentialWithType';

    class WalletRequest extends VerifiableCredentialWithType {
      /**
       * @inheritdoc override me if the payload type requires ad-hoc decoding
       */
      constructor(vc) {
        super(vc);
      }
      /**
       * Alternative constructor that returns type WalletRequest. To be used in derived classes
       *
       * @access protected
       *
       * @param {object} payload the payload
       * @param {Issuer} issuer the issuer id
       * @param {VerifiableCredentialOptions} options the options
       *
       * @returns a WalletRequest object
       */
      static signWalletRequest(payload, issuer, options = {}) {
        try {
          const _this = this,
            _super$sign = super.sign;
          if (_this.type === 'WalletRequest') {
            throw new Error('class should be a derived class of WalletRequest to use the type property');
          }
          return Promise.resolve(_super$sign.call(_this, payload, issuer, options)).then(function (vc) {
            return new WalletRequest(vc);
          });
        } catch (e) {
          return Promise.reject(e);
        }
      }
    }
    WalletRequest.type = 'WalletRequest';
    class LoginRequest extends WalletRequest {
      /**
       * @override the VerifiableCredentialWithType constructor to decode the payload of type LoginRequestPayload
       */
      constructor(vc) {
        super(vc);
        this.decodedPayload.publicKey = antelope.PublicKey.from(super.getPayload().publicKey);
      }
      /**
       * Alternative constructor that returns type LoginRequest
       */
      static signRequest(payload, issuer, options = {}) {
        try {
          const _super$signWalletRequest = super.signWalletRequest,
            _this2 = this;
          return Promise.resolve(_super$signWalletRequest.call(_this2, payload, issuer, options)).then(function (vc) {
            return new LoginRequest(vc);
          });
        } catch (e) {
          return Promise.reject(e);
        }
      }
    }
    LoginRequest.type = 'LoginRequest';
    class DataSharingRequest extends WalletRequest {
      /**
       * Alternative constructor that returns type DataSharingRequest
       */
      static signRequest(payload, issuer, options = {}) {
        try {
          const _super$signWalletRequest2 = super.signWalletRequest,
            _this3 = this;
          return Promise.resolve(_super$signWalletRequest2.call(_this3, payload, issuer, options)).then(function (vc) {
            return new DataSharingRequest(vc);
          });
        } catch (e) {
          return Promise.reject(e);
        }
      }
    }
    DataSharingRequest.type = 'DataSharingRequest';

    function getAccountNameFromDid(did) {
      const parsed = parseDid(did);
      const id = parsed.id.split(':');
      const accountName = id[id.length - 1];
      return antelope.Name.from(accountName);
    }
    function parseDid(did) {
      const parsed = didResolver.parse(did);
      if (!parsed) throw new Error('Invalid DID');
      return parsed;
    }

    exports.AccountType = void 0;
    (function (AccountType) {
      AccountType["PERSON"] = "PERSON";
      AccountType["ORG"] = "ORG";
      AccountType["APP"] = "APP";
      AccountType["GOV"] = "GOV";
    })(exports.AccountType || (exports.AccountType = {}));
    // eslint-disable-next-line @typescript-eslint/no-namespace
    (function (AccountType) {
      /*
       * Returns the index of the enum value
       *
       * @param value The level to get the index of
       */
      function indexFor(value) {
        return Object.keys(AccountType).indexOf(value);
      }
      AccountType.indexFor = indexFor;
      /*
       * Creates an AccountType from a string or index of the level
       *
       * @param value The string or index
       */
      function from(value) {
        let index;
        if (typeof value !== 'number') {
          index = AccountType.indexFor(value);
        } else {
          index = value;
        }
        return Object.values(AccountType)[index];
      }
      AccountType.from = from;
      function getPreSuffix(value) {
        return value.toLowerCase();
      }
      AccountType.getPreSuffix = getPreSuffix;
    })(exports.AccountType || (exports.AccountType = {}));
    class TonomyUsername {
      constructor(username) {
        this.username = void 0;
        this.usernameHash = void 0;
        this.username = username;
        this.usernameHash = sha256(this.username);
      }
      static fromUsername(username, type, suffix) {
        const fullUsername = username.normalize('NFKC').toLowerCase() + '.' + exports.AccountType.getPreSuffix(type) + suffix;
        return new TonomyUsername(fullUsername);
      }
      static fromFullUsername(username) {
        return new TonomyUsername(username);
      }
      getBaseUsername() {
        return this.username?.split('.')[0];
      }
      /**
       * @returns the username hash
       */
      toString() {
        return this.username;
      }
      /**
       * Returns the JSON string representation of the object - which is the username string
       *
       * @description This is used in JSON.stringify(). It is not recommended to use this method directly.
       * Only the username is returned, not the full object. This is all that is needed to reconstruct the
       * full object in the constructor, and thus minimizes the size of the JSON string.
       *
       * @override Serializable.toJSON
       * @returns {string} the username
       */
      toJSON() {
        return this.toString();
      }
    }

    /**
     *
     * @param {string} qrCode - The QR code to validate
     * @returns {string} - the DID of the user if the QR code is valid
     *
     * @throws if QR code is invalid
     */
    function validateQrCode(qrCode) {
      if (!qrCode) {
        throwError('QR code is empty', exports.SdkErrors.InvalidQrCode);
      }
      const schema = getSettings().tonomyIdSchema;
      if (!qrCode.startsWith(schema)) {
        throwError('QR schema does not match app', exports.SdkErrors.InvalidQrCode);
      }
      const path = qrCode.replace(schema, '').split('?')[0];
      const query = qrCode.replace(schema, '').split('?')[1];
      if (path !== 'UserHome') {
        throwError('QR path is not correct', exports.SdkErrors.InvalidQrCode);
      }
      if (!query || query.indexOf('did=') === -1) {
        throwError('QR did param not found', exports.SdkErrors.InvalidQrCode);
      }
      const did = query.split('did=')[1];
      if (!did) {
        throwError('QR did param is empty', exports.SdkErrors.InvalidQrCode);
      }
      return did;
    }
    function createLoginQrCode(did) {
      const schema = getSettings().tonomyIdSchema;
      return schema + 'UserHome?did=' + did;
    }

    exports.CommunicationError = CommunicationError;
    exports.DataSharingRequest = DataSharingRequest;
    exports.HttpError = HttpError;
    exports.LoginRequest = LoginRequest;
    exports.SdkError = SdkError;
    exports.TonomyUsername = TonomyUsername;
    exports.VerifiableCredential = VerifiableCredential;
    exports.VerifiableCredentialWithType = VerifiableCredentialWithType;
    exports.WalletRequest = WalletRequest;
    exports.base64ToStr = base64ToStr;
    exports.base64UrlToObj = base64UrlToObj;
    exports.base64UrlToStr = base64UrlToStr;
    exports.bigintToBytes = bigintToBytes;
    exports.bnToBase64Url = bnToBase64Url;
    exports.bytesToBase64 = bytesToBase64;
    exports.copyObject = copyObject;
    exports.createJWK = createJWK;
    exports.createLoginQrCode = createLoginQrCode;
    exports.createSdkError = createSdkError;
    exports.createSigner = createSigner;
    exports.createVCSigner = createVCSigner;
    exports.decodeHex = decodeHex;
    exports.encodeHex = encodeHex;
    exports.generateAutoSuggestions = generateAutoSuggestions;
    exports.generateRandomKeyPair = generateRandomKeyPair;
    exports.generateRandomKeywords = generateRandomKeywords;
    exports.getAccountNameFromDid = getAccountNameFromDid;
    exports.getResolver = getResolver;
    exports.getSettings = getSettings;
    exports.int2hex = int2hex;
    exports.isKeyword = isKeyword;
    exports.isProduction = isProduction;
    exports.objToBase64Url = objToBase64Url;
    exports.parseDid = parseDid;
    exports.randomBytes = randomBytes;
    exports.randomNumber = randomNumber;
    exports.randomString = randomString;
    exports.resolve = resolve;
    exports.setSettings = setSettings;
    exports.sha256 = sha256;
    exports.sleep = sleep;
    exports.strToBase64 = strToBase64;
    exports.strToBase64Url = strToBase64Url;
    exports.throwError = throwError;
    exports.toDateTime = toDateTime;
    exports.toDid = toDid;
    exports.toDidDocument = toDidDocument;
    exports.toElliptic = toElliptic;
    exports.validateQrCode = validateQrCode;

}));
//# sourceMappingURL=index.umd.js.map
