/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/

var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJS = (cb, mod) => function __require() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// node_modules/.pnpm/deepmerge@4.3.1/node_modules/deepmerge/dist/cjs.js
var require_cjs = __commonJS({
  "node_modules/.pnpm/deepmerge@4.3.1/node_modules/deepmerge/dist/cjs.js"(exports, module2) {
    "use strict";
    var isMergeableObject = function isMergeableObject2(value) {
      return isNonNullObject(value) && !isSpecial(value);
    };
    function isNonNullObject(value) {
      return !!value && typeof value === "object";
    }
    function isSpecial(value) {
      var stringValue = Object.prototype.toString.call(value);
      return stringValue === "[object RegExp]" || stringValue === "[object Date]" || isReactElement(value);
    }
    var canUseSymbol = typeof Symbol === "function" && Symbol.for;
    var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for("react.element") : 60103;
    function isReactElement(value) {
      return value.$$typeof === REACT_ELEMENT_TYPE;
    }
    function emptyTarget(val) {
      return Array.isArray(val) ? [] : {};
    }
    function cloneUnlessOtherwiseSpecified(value, options) {
      return options.clone !== false && options.isMergeableObject(value) ? deepmerge(emptyTarget(value), value, options) : value;
    }
    function defaultArrayMerge(target, source, options) {
      return target.concat(source).map(function(element) {
        return cloneUnlessOtherwiseSpecified(element, options);
      });
    }
    function getMergeFunction(key, options) {
      if (!options.customMerge) {
        return deepmerge;
      }
      var customMerge = options.customMerge(key);
      return typeof customMerge === "function" ? customMerge : deepmerge;
    }
    function getEnumerableOwnPropertySymbols(target) {
      return Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(target).filter(function(symbol) {
        return Object.propertyIsEnumerable.call(target, symbol);
      }) : [];
    }
    function getKeys(target) {
      return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target));
    }
    function propertyIsOnObject(object, property) {
      try {
        return property in object;
      } catch (_) {
        return false;
      }
    }
    function propertyIsUnsafe(target, key) {
      return propertyIsOnObject(target, key) && !(Object.hasOwnProperty.call(target, key) && Object.propertyIsEnumerable.call(target, key));
    }
    function mergeObject(target, source, options) {
      var destination = {};
      if (options.isMergeableObject(target)) {
        getKeys(target).forEach(function(key) {
          destination[key] = cloneUnlessOtherwiseSpecified(target[key], options);
        });
      }
      getKeys(source).forEach(function(key) {
        if (propertyIsUnsafe(target, key)) {
          return;
        }
        if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) {
          destination[key] = getMergeFunction(key, options)(target[key], source[key], options);
        } else {
          destination[key] = cloneUnlessOtherwiseSpecified(source[key], options);
        }
      });
      return destination;
    }
    function deepmerge(target, source, options) {
      options = options || {};
      options.arrayMerge = options.arrayMerge || defaultArrayMerge;
      options.isMergeableObject = options.isMergeableObject || isMergeableObject;
      options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified;
      var sourceIsArray = Array.isArray(source);
      var targetIsArray = Array.isArray(target);
      var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
      if (!sourceAndTargetTypesMatch) {
        return cloneUnlessOtherwiseSpecified(source, options);
      } else if (sourceIsArray) {
        return options.arrayMerge(target, source, options);
      } else {
        return mergeObject(target, source, options);
      }
    }
    deepmerge.all = function deepmergeAll(array, options) {
      if (!Array.isArray(array)) {
        throw new Error("first argument should be an array");
      }
      return array.reduce(function(prev, next) {
        return deepmerge(prev, next, options);
      }, {});
    };
    var deepmerge_1 = deepmerge;
    module2.exports = deepmerge_1;
  }
});

// node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/utils/common.js
var require_common = __commonJS({
  "node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/utils/common.js"(exports) {
    "use strict";
    var TYPED_OK = typeof Uint8Array !== "undefined" && typeof Uint16Array !== "undefined" && typeof Int32Array !== "undefined";
    function _has(obj, key) {
      return Object.prototype.hasOwnProperty.call(obj, key);
    }
    exports.assign = function(obj) {
      var sources = Array.prototype.slice.call(arguments, 1);
      while (sources.length) {
        var source = sources.shift();
        if (!source) {
          continue;
        }
        if (typeof source !== "object") {
          throw new TypeError(source + "must be non-object");
        }
        for (var p in source) {
          if (_has(source, p)) {
            obj[p] = source[p];
          }
        }
      }
      return obj;
    };
    exports.shrinkBuf = function(buf, size) {
      if (buf.length === size) {
        return buf;
      }
      if (buf.subarray) {
        return buf.subarray(0, size);
      }
      buf.length = size;
      return buf;
    };
    var fnTyped = {
      arraySet: function(dest, src, src_offs, len, dest_offs) {
        if (src.subarray && dest.subarray) {
          dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
          return;
        }
        for (var i = 0; i < len; i++) {
          dest[dest_offs + i] = src[src_offs + i];
        }
      },
      // Join array of chunks to single array.
      flattenChunks: function(chunks) {
        var i, l, len, pos, chunk, result;
        len = 0;
        for (i = 0, l = chunks.length; i < l; i++) {
          len += chunks[i].length;
        }
        result = new Uint8Array(len);
        pos = 0;
        for (i = 0, l = chunks.length; i < l; i++) {
          chunk = chunks[i];
          result.set(chunk, pos);
          pos += chunk.length;
        }
        return result;
      }
    };
    var fnUntyped = {
      arraySet: function(dest, src, src_offs, len, dest_offs) {
        for (var i = 0; i < len; i++) {
          dest[dest_offs + i] = src[src_offs + i];
        }
      },
      // Join array of chunks to single array.
      flattenChunks: function(chunks) {
        return [].concat.apply([], chunks);
      }
    };
    exports.setTyped = function(on) {
      if (on) {
        exports.Buf8 = Uint8Array;
        exports.Buf16 = Uint16Array;
        exports.Buf32 = Int32Array;
        exports.assign(exports, fnTyped);
      } else {
        exports.Buf8 = Array;
        exports.Buf16 = Array;
        exports.Buf32 = Array;
        exports.assign(exports, fnUntyped);
      }
    };
    exports.setTyped(TYPED_OK);
  }
});

// node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/trees.js
var require_trees = __commonJS({
  "node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/trees.js"(exports) {
    "use strict";
    var utils = require_common();
    var Z_FIXED = 4;
    var Z_BINARY = 0;
    var Z_TEXT = 1;
    var Z_UNKNOWN = 2;
    function zero(buf) {
      var len = buf.length;
      while (--len >= 0) {
        buf[len] = 0;
      }
    }
    var STORED_BLOCK = 0;
    var STATIC_TREES = 1;
    var DYN_TREES = 2;
    var MIN_MATCH = 3;
    var MAX_MATCH = 258;
    var LENGTH_CODES = 29;
    var LITERALS = 256;
    var L_CODES = LITERALS + 1 + LENGTH_CODES;
    var D_CODES = 30;
    var BL_CODES = 19;
    var HEAP_SIZE = 2 * L_CODES + 1;
    var MAX_BITS = 15;
    var Buf_size = 16;
    var MAX_BL_BITS = 7;
    var END_BLOCK = 256;
    var REP_3_6 = 16;
    var REPZ_3_10 = 17;
    var REPZ_11_138 = 18;
    var extra_lbits = (
      /* extra bits for each length code */
      [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0]
    );
    var extra_dbits = (
      /* extra bits for each distance code */
      [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13]
    );
    var extra_blbits = (
      /* extra bits for each bit length code */
      [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7]
    );
    var bl_order = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
    var DIST_CODE_LEN = 512;
    var static_ltree = new Array((L_CODES + 2) * 2);
    zero(static_ltree);
    var static_dtree = new Array(D_CODES * 2);
    zero(static_dtree);
    var _dist_code = new Array(DIST_CODE_LEN);
    zero(_dist_code);
    var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
    zero(_length_code);
    var base_length = new Array(LENGTH_CODES);
    zero(base_length);
    var base_dist = new Array(D_CODES);
    zero(base_dist);
    function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
      this.static_tree = static_tree;
      this.extra_bits = extra_bits;
      this.extra_base = extra_base;
      this.elems = elems;
      this.max_length = max_length;
      this.has_stree = static_tree && static_tree.length;
    }
    var static_l_desc;
    var static_d_desc;
    var static_bl_desc;
    function TreeDesc(dyn_tree, stat_desc) {
      this.dyn_tree = dyn_tree;
      this.max_code = 0;
      this.stat_desc = stat_desc;
    }
    function d_code(dist) {
      return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
    }
    function put_short(s, w) {
      s.pending_buf[s.pending++] = w & 255;
      s.pending_buf[s.pending++] = w >>> 8 & 255;
    }
    function send_bits(s, value, length) {
      if (s.bi_valid > Buf_size - length) {
        s.bi_buf |= value << s.bi_valid & 65535;
        put_short(s, s.bi_buf);
        s.bi_buf = value >> Buf_size - s.bi_valid;
        s.bi_valid += length - Buf_size;
      } else {
        s.bi_buf |= value << s.bi_valid & 65535;
        s.bi_valid += length;
      }
    }
    function send_code(s, c, tree) {
      send_bits(
        s,
        tree[c * 2],
        tree[c * 2 + 1]
        /*.Len*/
      );
    }
    function bi_reverse(code, len) {
      var res = 0;
      do {
        res |= code & 1;
        code >>>= 1;
        res <<= 1;
      } while (--len > 0);
      return res >>> 1;
    }
    function bi_flush(s) {
      if (s.bi_valid === 16) {
        put_short(s, s.bi_buf);
        s.bi_buf = 0;
        s.bi_valid = 0;
      } else if (s.bi_valid >= 8) {
        s.pending_buf[s.pending++] = s.bi_buf & 255;
        s.bi_buf >>= 8;
        s.bi_valid -= 8;
      }
    }
    function gen_bitlen(s, desc) {
      var tree = desc.dyn_tree;
      var max_code = desc.max_code;
      var stree = desc.stat_desc.static_tree;
      var has_stree = desc.stat_desc.has_stree;
      var extra = desc.stat_desc.extra_bits;
      var base = desc.stat_desc.extra_base;
      var max_length = desc.stat_desc.max_length;
      var h;
      var n, m;
      var bits;
      var xbits;
      var f;
      var overflow = 0;
      for (bits = 0; bits <= MAX_BITS; bits++) {
        s.bl_count[bits] = 0;
      }
      tree[s.heap[s.heap_max] * 2 + 1] = 0;
      for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
        n = s.heap[h];
        bits = tree[tree[n * 2 + 1] * 2 + 1] + 1;
        if (bits > max_length) {
          bits = max_length;
          overflow++;
        }
        tree[n * 2 + 1] = bits;
        if (n > max_code) {
          continue;
        }
        s.bl_count[bits]++;
        xbits = 0;
        if (n >= base) {
          xbits = extra[n - base];
        }
        f = tree[n * 2];
        s.opt_len += f * (bits + xbits);
        if (has_stree) {
          s.static_len += f * (stree[n * 2 + 1] + xbits);
        }
      }
      if (overflow === 0) {
        return;
      }
      do {
        bits = max_length - 1;
        while (s.bl_count[bits] === 0) {
          bits--;
        }
        s.bl_count[bits]--;
        s.bl_count[bits + 1] += 2;
        s.bl_count[max_length]--;
        overflow -= 2;
      } while (overflow > 0);
      for (bits = max_length; bits !== 0; bits--) {
        n = s.bl_count[bits];
        while (n !== 0) {
          m = s.heap[--h];
          if (m > max_code) {
            continue;
          }
          if (tree[m * 2 + 1] !== bits) {
            s.opt_len += (bits - tree[m * 2 + 1]) * tree[m * 2];
            tree[m * 2 + 1] = bits;
          }
          n--;
        }
      }
    }
    function gen_codes(tree, max_code, bl_count) {
      var next_code = new Array(MAX_BITS + 1);
      var code = 0;
      var bits;
      var n;
      for (bits = 1; bits <= MAX_BITS; bits++) {
        next_code[bits] = code = code + bl_count[bits - 1] << 1;
      }
      for (n = 0; n <= max_code; n++) {
        var len = tree[n * 2 + 1];
        if (len === 0) {
          continue;
        }
        tree[n * 2] = bi_reverse(next_code[len]++, len);
      }
    }
    function tr_static_init() {
      var n;
      var bits;
      var length;
      var code;
      var dist;
      var bl_count = new Array(MAX_BITS + 1);
      length = 0;
      for (code = 0; code < LENGTH_CODES - 1; code++) {
        base_length[code] = length;
        for (n = 0; n < 1 << extra_lbits[code]; n++) {
          _length_code[length++] = code;
        }
      }
      _length_code[length - 1] = code;
      dist = 0;
      for (code = 0; code < 16; code++) {
        base_dist[code] = dist;
        for (n = 0; n < 1 << extra_dbits[code]; n++) {
          _dist_code[dist++] = code;
        }
      }
      dist >>= 7;
      for (; code < D_CODES; code++) {
        base_dist[code] = dist << 7;
        for (n = 0; n < 1 << extra_dbits[code] - 7; n++) {
          _dist_code[256 + dist++] = code;
        }
      }
      for (bits = 0; bits <= MAX_BITS; bits++) {
        bl_count[bits] = 0;
      }
      n = 0;
      while (n <= 143) {
        static_ltree[n * 2 + 1] = 8;
        n++;
        bl_count[8]++;
      }
      while (n <= 255) {
        static_ltree[n * 2 + 1] = 9;
        n++;
        bl_count[9]++;
      }
      while (n <= 279) {
        static_ltree[n * 2 + 1] = 7;
        n++;
        bl_count[7]++;
      }
      while (n <= 287) {
        static_ltree[n * 2 + 1] = 8;
        n++;
        bl_count[8]++;
      }
      gen_codes(static_ltree, L_CODES + 1, bl_count);
      for (n = 0; n < D_CODES; n++) {
        static_dtree[n * 2 + 1] = 5;
        static_dtree[n * 2] = bi_reverse(n, 5);
      }
      static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
      static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
      static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
    }
    function init_block(s) {
      var n;
      for (n = 0; n < L_CODES; n++) {
        s.dyn_ltree[n * 2] = 0;
      }
      for (n = 0; n < D_CODES; n++) {
        s.dyn_dtree[n * 2] = 0;
      }
      for (n = 0; n < BL_CODES; n++) {
        s.bl_tree[n * 2] = 0;
      }
      s.dyn_ltree[END_BLOCK * 2] = 1;
      s.opt_len = s.static_len = 0;
      s.last_lit = s.matches = 0;
    }
    function bi_windup(s) {
      if (s.bi_valid > 8) {
        put_short(s, s.bi_buf);
      } else if (s.bi_valid > 0) {
        s.pending_buf[s.pending++] = s.bi_buf;
      }
      s.bi_buf = 0;
      s.bi_valid = 0;
    }
    function copy_block(s, buf, len, header) {
      bi_windup(s);
      if (header) {
        put_short(s, len);
        put_short(s, ~len);
      }
      utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
      s.pending += len;
    }
    function smaller(tree, n, m, depth) {
      var _n2 = n * 2;
      var _m2 = m * 2;
      return tree[_n2] < tree[_m2] || tree[_n2] === tree[_m2] && depth[n] <= depth[m];
    }
    function pqdownheap(s, tree, k) {
      var v = s.heap[k];
      var j = k << 1;
      while (j <= s.heap_len) {
        if (j < s.heap_len && smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
          j++;
        }
        if (smaller(tree, v, s.heap[j], s.depth)) {
          break;
        }
        s.heap[k] = s.heap[j];
        k = j;
        j <<= 1;
      }
      s.heap[k] = v;
    }
    function compress_block(s, ltree, dtree) {
      var dist;
      var lc;
      var lx = 0;
      var code;
      var extra;
      if (s.last_lit !== 0) {
        do {
          dist = s.pending_buf[s.d_buf + lx * 2] << 8 | s.pending_buf[s.d_buf + lx * 2 + 1];
          lc = s.pending_buf[s.l_buf + lx];
          lx++;
          if (dist === 0) {
            send_code(s, lc, ltree);
          } else {
            code = _length_code[lc];
            send_code(s, code + LITERALS + 1, ltree);
            extra = extra_lbits[code];
            if (extra !== 0) {
              lc -= base_length[code];
              send_bits(s, lc, extra);
            }
            dist--;
            code = d_code(dist);
            send_code(s, code, dtree);
            extra = extra_dbits[code];
            if (extra !== 0) {
              dist -= base_dist[code];
              send_bits(s, dist, extra);
            }
          }
        } while (lx < s.last_lit);
      }
      send_code(s, END_BLOCK, ltree);
    }
    function build_tree(s, desc) {
      var tree = desc.dyn_tree;
      var stree = desc.stat_desc.static_tree;
      var has_stree = desc.stat_desc.has_stree;
      var elems = desc.stat_desc.elems;
      var n, m;
      var max_code = -1;
      var node;
      s.heap_len = 0;
      s.heap_max = HEAP_SIZE;
      for (n = 0; n < elems; n++) {
        if (tree[n * 2] !== 0) {
          s.heap[++s.heap_len] = max_code = n;
          s.depth[n] = 0;
        } else {
          tree[n * 2 + 1] = 0;
        }
      }
      while (s.heap_len < 2) {
        node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0;
        tree[node * 2] = 1;
        s.depth[node] = 0;
        s.opt_len--;
        if (has_stree) {
          s.static_len -= stree[node * 2 + 1];
        }
      }
      desc.max_code = max_code;
      for (n = s.heap_len >> 1; n >= 1; n--) {
        pqdownheap(s, tree, n);
      }
      node = elems;
      do {
        n = s.heap[
          1
          /*SMALLEST*/
        ];
        s.heap[
          1
          /*SMALLEST*/
        ] = s.heap[s.heap_len--];
        pqdownheap(
          s,
          tree,
          1
          /*SMALLEST*/
        );
        m = s.heap[
          1
          /*SMALLEST*/
        ];
        s.heap[--s.heap_max] = n;
        s.heap[--s.heap_max] = m;
        tree[node * 2] = tree[n * 2] + tree[m * 2];
        s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
        tree[n * 2 + 1] = tree[m * 2 + 1] = node;
        s.heap[
          1
          /*SMALLEST*/
        ] = node++;
        pqdownheap(
          s,
          tree,
          1
          /*SMALLEST*/
        );
      } while (s.heap_len >= 2);
      s.heap[--s.heap_max] = s.heap[
        1
        /*SMALLEST*/
      ];
      gen_bitlen(s, desc);
      gen_codes(tree, max_code, s.bl_count);
    }
    function scan_tree(s, tree, max_code) {
      var n;
      var prevlen = -1;
      var curlen;
      var nextlen = tree[0 * 2 + 1];
      var count = 0;
      var max_count = 7;
      var min_count = 4;
      if (nextlen === 0) {
        max_count = 138;
        min_count = 3;
      }
      tree[(max_code + 1) * 2 + 1] = 65535;
      for (n = 0; n <= max_code; n++) {
        curlen = nextlen;
        nextlen = tree[(n + 1) * 2 + 1];
        if (++count < max_count && curlen === nextlen) {
          continue;
        } else if (count < min_count) {
          s.bl_tree[curlen * 2] += count;
        } else if (curlen !== 0) {
          if (curlen !== prevlen) {
            s.bl_tree[curlen * 2]++;
          }
          s.bl_tree[REP_3_6 * 2]++;
        } else if (count <= 10) {
          s.bl_tree[REPZ_3_10 * 2]++;
        } else {
          s.bl_tree[REPZ_11_138 * 2]++;
        }
        count = 0;
        prevlen = curlen;
        if (nextlen === 0) {
          max_count = 138;
          min_count = 3;
        } else if (curlen === nextlen) {
          max_count = 6;
          min_count = 3;
        } else {
          max_count = 7;
          min_count = 4;
        }
      }
    }
    function send_tree(s, tree, max_code) {
      var n;
      var prevlen = -1;
      var curlen;
      var nextlen = tree[0 * 2 + 1];
      var count = 0;
      var max_count = 7;
      var min_count = 4;
      if (nextlen === 0) {
        max_count = 138;
        min_count = 3;
      }
      for (n = 0; n <= max_code; n++) {
        curlen = nextlen;
        nextlen = tree[(n + 1) * 2 + 1];
        if (++count < max_count && curlen === nextlen) {
          continue;
        } else if (count < min_count) {
          do {
            send_code(s, curlen, s.bl_tree);
          } while (--count !== 0);
        } else if (curlen !== 0) {
          if (curlen !== prevlen) {
            send_code(s, curlen, s.bl_tree);
            count--;
          }
          send_code(s, REP_3_6, s.bl_tree);
          send_bits(s, count - 3, 2);
        } else if (count <= 10) {
          send_code(s, REPZ_3_10, s.bl_tree);
          send_bits(s, count - 3, 3);
        } else {
          send_code(s, REPZ_11_138, s.bl_tree);
          send_bits(s, count - 11, 7);
        }
        count = 0;
        prevlen = curlen;
        if (nextlen === 0) {
          max_count = 138;
          min_count = 3;
        } else if (curlen === nextlen) {
          max_count = 6;
          min_count = 3;
        } else {
          max_count = 7;
          min_count = 4;
        }
      }
    }
    function build_bl_tree(s) {
      var max_blindex;
      scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
      scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
      build_tree(s, s.bl_desc);
      for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
        if (s.bl_tree[bl_order[max_blindex] * 2 + 1] !== 0) {
          break;
        }
      }
      s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
      return max_blindex;
    }
    function send_all_trees(s, lcodes, dcodes, blcodes) {
      var rank;
      send_bits(s, lcodes - 257, 5);
      send_bits(s, dcodes - 1, 5);
      send_bits(s, blcodes - 4, 4);
      for (rank = 0; rank < blcodes; rank++) {
        send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1], 3);
      }
      send_tree(s, s.dyn_ltree, lcodes - 1);
      send_tree(s, s.dyn_dtree, dcodes - 1);
    }
    function detect_data_type(s) {
      var black_mask = 4093624447;
      var n;
      for (n = 0; n <= 31; n++, black_mask >>>= 1) {
        if (black_mask & 1 && s.dyn_ltree[n * 2] !== 0) {
          return Z_BINARY;
        }
      }
      if (s.dyn_ltree[9 * 2] !== 0 || s.dyn_ltree[10 * 2] !== 0 || s.dyn_ltree[13 * 2] !== 0) {
        return Z_TEXT;
      }
      for (n = 32; n < LITERALS; n++) {
        if (s.dyn_ltree[n * 2] !== 0) {
          return Z_TEXT;
        }
      }
      return Z_BINARY;
    }
    var static_init_done = false;
    function _tr_init(s) {
      if (!static_init_done) {
        tr_static_init();
        static_init_done = true;
      }
      s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
      s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
      s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
      s.bi_buf = 0;
      s.bi_valid = 0;
      init_block(s);
    }
    function _tr_stored_block(s, buf, stored_len, last2) {
      send_bits(s, (STORED_BLOCK << 1) + (last2 ? 1 : 0), 3);
      copy_block(s, buf, stored_len, true);
    }
    function _tr_align(s) {
      send_bits(s, STATIC_TREES << 1, 3);
      send_code(s, END_BLOCK, static_ltree);
      bi_flush(s);
    }
    function _tr_flush_block(s, buf, stored_len, last2) {
      var opt_lenb, static_lenb;
      var max_blindex = 0;
      if (s.level > 0) {
        if (s.strm.data_type === Z_UNKNOWN) {
          s.strm.data_type = detect_data_type(s);
        }
        build_tree(s, s.l_desc);
        build_tree(s, s.d_desc);
        max_blindex = build_bl_tree(s);
        opt_lenb = s.opt_len + 3 + 7 >>> 3;
        static_lenb = s.static_len + 3 + 7 >>> 3;
        if (static_lenb <= opt_lenb) {
          opt_lenb = static_lenb;
        }
      } else {
        opt_lenb = static_lenb = stored_len + 5;
      }
      if (stored_len + 4 <= opt_lenb && buf !== -1) {
        _tr_stored_block(s, buf, stored_len, last2);
      } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
        send_bits(s, (STATIC_TREES << 1) + (last2 ? 1 : 0), 3);
        compress_block(s, static_ltree, static_dtree);
      } else {
        send_bits(s, (DYN_TREES << 1) + (last2 ? 1 : 0), 3);
        send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
        compress_block(s, s.dyn_ltree, s.dyn_dtree);
      }
      init_block(s);
      if (last2) {
        bi_windup(s);
      }
    }
    function _tr_tally(s, dist, lc) {
      s.pending_buf[s.d_buf + s.last_lit * 2] = dist >>> 8 & 255;
      s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 255;
      s.pending_buf[s.l_buf + s.last_lit] = lc & 255;
      s.last_lit++;
      if (dist === 0) {
        s.dyn_ltree[lc * 2]++;
      } else {
        s.matches++;
        dist--;
        s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]++;
        s.dyn_dtree[d_code(dist) * 2]++;
      }
      return s.last_lit === s.lit_bufsize - 1;
    }
    exports._tr_init = _tr_init;
    exports._tr_stored_block = _tr_stored_block;
    exports._tr_flush_block = _tr_flush_block;
    exports._tr_tally = _tr_tally;
    exports._tr_align = _tr_align;
  }
});

// node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/adler32.js
var require_adler32 = __commonJS({
  "node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/adler32.js"(exports, module2) {
    "use strict";
    function adler32(adler, buf, len, pos) {
      var s1 = adler & 65535 | 0, s2 = adler >>> 16 & 65535 | 0, n = 0;
      while (len !== 0) {
        n = len > 2e3 ? 2e3 : len;
        len -= n;
        do {
          s1 = s1 + buf[pos++] | 0;
          s2 = s2 + s1 | 0;
        } while (--n);
        s1 %= 65521;
        s2 %= 65521;
      }
      return s1 | s2 << 16 | 0;
    }
    module2.exports = adler32;
  }
});

// node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/crc32.js
var require_crc32 = __commonJS({
  "node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/crc32.js"(exports, module2) {
    "use strict";
    function makeTable() {
      var c, table = [];
      for (var n = 0; n < 256; n++) {
        c = n;
        for (var k = 0; k < 8; k++) {
          c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
        }
        table[n] = c;
      }
      return table;
    }
    var crcTable = makeTable();
    function crc32(crc, buf, len, pos) {
      var t = crcTable, end = pos + len;
      crc ^= -1;
      for (var i = pos; i < end; i++) {
        crc = crc >>> 8 ^ t[(crc ^ buf[i]) & 255];
      }
      return crc ^ -1;
    }
    module2.exports = crc32;
  }
});

// node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/messages.js
var require_messages = __commonJS({
  "node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/messages.js"(exports, module2) {
    "use strict";
    module2.exports = {
      2: "need dictionary",
      /* Z_NEED_DICT       2  */
      1: "stream end",
      /* Z_STREAM_END      1  */
      0: "",
      /* Z_OK              0  */
      "-1": "file error",
      /* Z_ERRNO         (-1) */
      "-2": "stream error",
      /* Z_STREAM_ERROR  (-2) */
      "-3": "data error",
      /* Z_DATA_ERROR    (-3) */
      "-4": "insufficient memory",
      /* Z_MEM_ERROR     (-4) */
      "-5": "buffer error",
      /* Z_BUF_ERROR     (-5) */
      "-6": "incompatible version"
      /* Z_VERSION_ERROR (-6) */
    };
  }
});

// node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/deflate.js
var require_deflate = __commonJS({
  "node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/deflate.js"(exports) {
    "use strict";
    var utils = require_common();
    var trees = require_trees();
    var adler32 = require_adler32();
    var crc32 = require_crc32();
    var msg = require_messages();
    var Z_NO_FLUSH = 0;
    var Z_PARTIAL_FLUSH = 1;
    var Z_FULL_FLUSH = 3;
    var Z_FINISH = 4;
    var Z_BLOCK = 5;
    var Z_OK = 0;
    var Z_STREAM_END = 1;
    var Z_STREAM_ERROR = -2;
    var Z_DATA_ERROR = -3;
    var Z_BUF_ERROR = -5;
    var Z_DEFAULT_COMPRESSION = -1;
    var Z_FILTERED = 1;
    var Z_HUFFMAN_ONLY = 2;
    var Z_RLE = 3;
    var Z_FIXED = 4;
    var Z_DEFAULT_STRATEGY = 0;
    var Z_UNKNOWN = 2;
    var Z_DEFLATED = 8;
    var MAX_MEM_LEVEL = 9;
    var MAX_WBITS = 15;
    var DEF_MEM_LEVEL = 8;
    var LENGTH_CODES = 29;
    var LITERALS = 256;
    var L_CODES = LITERALS + 1 + LENGTH_CODES;
    var D_CODES = 30;
    var BL_CODES = 19;
    var HEAP_SIZE = 2 * L_CODES + 1;
    var MAX_BITS = 15;
    var MIN_MATCH = 3;
    var MAX_MATCH = 258;
    var MIN_LOOKAHEAD = MAX_MATCH + MIN_MATCH + 1;
    var PRESET_DICT = 32;
    var INIT_STATE = 42;
    var EXTRA_STATE = 69;
    var NAME_STATE = 73;
    var COMMENT_STATE = 91;
    var HCRC_STATE = 103;
    var BUSY_STATE = 113;
    var FINISH_STATE = 666;
    var BS_NEED_MORE = 1;
    var BS_BLOCK_DONE = 2;
    var BS_FINISH_STARTED = 3;
    var BS_FINISH_DONE = 4;
    var OS_CODE = 3;
    function err(strm, errorCode) {
      strm.msg = msg[errorCode];
      return errorCode;
    }
    function rank(f) {
      return (f << 1) - (f > 4 ? 9 : 0);
    }
    function zero(buf) {
      var len = buf.length;
      while (--len >= 0) {
        buf[len] = 0;
      }
    }
    function flush_pending(strm) {
      var s = strm.state;
      var len = s.pending;
      if (len > strm.avail_out) {
        len = strm.avail_out;
      }
      if (len === 0) {
        return;
      }
      utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
      strm.next_out += len;
      s.pending_out += len;
      strm.total_out += len;
      strm.avail_out -= len;
      s.pending -= len;
      if (s.pending === 0) {
        s.pending_out = 0;
      }
    }
    function flush_block_only(s, last2) {
      trees._tr_flush_block(s, s.block_start >= 0 ? s.block_start : -1, s.strstart - s.block_start, last2);
      s.block_start = s.strstart;
      flush_pending(s.strm);
    }
    function put_byte(s, b) {
      s.pending_buf[s.pending++] = b;
    }
    function putShortMSB(s, b) {
      s.pending_buf[s.pending++] = b >>> 8 & 255;
      s.pending_buf[s.pending++] = b & 255;
    }
    function read_buf(strm, buf, start, size) {
      var len = strm.avail_in;
      if (len > size) {
        len = size;
      }
      if (len === 0) {
        return 0;
      }
      strm.avail_in -= len;
      utils.arraySet(buf, strm.input, strm.next_in, len, start);
      if (strm.state.wrap === 1) {
        strm.adler = adler32(strm.adler, buf, len, start);
      } else if (strm.state.wrap === 2) {
        strm.adler = crc32(strm.adler, buf, len, start);
      }
      strm.next_in += len;
      strm.total_in += len;
      return len;
    }
    function longest_match(s, cur_match) {
      var chain_length = s.max_chain_length;
      var scan = s.strstart;
      var match;
      var len;
      var best_len = s.prev_length;
      var nice_match = s.nice_match;
      var limit = s.strstart > s.w_size - MIN_LOOKAHEAD ? s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0;
      var _win = s.window;
      var wmask = s.w_mask;
      var prev = s.prev;
      var strend = s.strstart + MAX_MATCH;
      var scan_end1 = _win[scan + best_len - 1];
      var scan_end = _win[scan + best_len];
      if (s.prev_length >= s.good_match) {
        chain_length >>= 2;
      }
      if (nice_match > s.lookahead) {
        nice_match = s.lookahead;
      }
      do {
        match = cur_match;
        if (_win[match + best_len] !== scan_end || _win[match + best_len - 1] !== scan_end1 || _win[match] !== _win[scan] || _win[++match] !== _win[scan + 1]) {
          continue;
        }
        scan += 2;
        match++;
        do {
        } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && scan < strend);
        len = MAX_MATCH - (strend - scan);
        scan = strend - MAX_MATCH;
        if (len > best_len) {
          s.match_start = cur_match;
          best_len = len;
          if (len >= nice_match) {
            break;
          }
          scan_end1 = _win[scan + best_len - 1];
          scan_end = _win[scan + best_len];
        }
      } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
      if (best_len <= s.lookahead) {
        return best_len;
      }
      return s.lookahead;
    }
    function fill_window(s) {
      var _w_size = s.w_size;
      var p, n, m, more, str;
      do {
        more = s.window_size - s.lookahead - s.strstart;
        if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
          utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
          s.match_start -= _w_size;
          s.strstart -= _w_size;
          s.block_start -= _w_size;
          n = s.hash_size;
          p = n;
          do {
            m = s.head[--p];
            s.head[p] = m >= _w_size ? m - _w_size : 0;
          } while (--n);
          n = _w_size;
          p = n;
          do {
            m = s.prev[--p];
            s.prev[p] = m >= _w_size ? m - _w_size : 0;
          } while (--n);
          more += _w_size;
        }
        if (s.strm.avail_in === 0) {
          break;
        }
        n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
        s.lookahead += n;
        if (s.lookahead + s.insert >= MIN_MATCH) {
          str = s.strstart - s.insert;
          s.ins_h = s.window[str];
          s.ins_h = (s.ins_h << s.hash_shift ^ s.window[str + 1]) & s.hash_mask;
          while (s.insert) {
            s.ins_h = (s.ins_h << s.hash_shift ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
            s.prev[str & s.w_mask] = s.head[s.ins_h];
            s.head[s.ins_h] = str;
            str++;
            s.insert--;
            if (s.lookahead + s.insert < MIN_MATCH) {
              break;
            }
          }
        }
      } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
    }
    function deflate_stored(s, flush) {
      var max_block_size = 65535;
      if (max_block_size > s.pending_buf_size - 5) {
        max_block_size = s.pending_buf_size - 5;
      }
      for (; ; ) {
        if (s.lookahead <= 1) {
          fill_window(s);
          if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
            return BS_NEED_MORE;
          }
          if (s.lookahead === 0) {
            break;
          }
        }
        s.strstart += s.lookahead;
        s.lookahead = 0;
        var max_start = s.block_start + max_block_size;
        if (s.strstart === 0 || s.strstart >= max_start) {
          s.lookahead = s.strstart - max_start;
          s.strstart = max_start;
          flush_block_only(s, false);
          if (s.strm.avail_out === 0) {
            return BS_NEED_MORE;
          }
        }
        if (s.strstart - s.block_start >= s.w_size - MIN_LOOKAHEAD) {
          flush_block_only(s, false);
          if (s.strm.avail_out === 0) {
            return BS_NEED_MORE;
          }
        }
      }
      s.insert = 0;
      if (flush === Z_FINISH) {
        flush_block_only(s, true);
        if (s.strm.avail_out === 0) {
          return BS_FINISH_STARTED;
        }
        return BS_FINISH_DONE;
      }
      if (s.strstart > s.block_start) {
        flush_block_only(s, false);
        if (s.strm.avail_out === 0) {
          return BS_NEED_MORE;
        }
      }
      return BS_NEED_MORE;
    }
    function deflate_fast(s, flush) {
      var hash_head;
      var bflush;
      for (; ; ) {
        if (s.lookahead < MIN_LOOKAHEAD) {
          fill_window(s);
          if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
            return BS_NEED_MORE;
          }
          if (s.lookahead === 0) {
            break;
          }
        }
        hash_head = 0;
        if (s.lookahead >= MIN_MATCH) {
          s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
          hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
          s.head[s.ins_h] = s.strstart;
        }
        if (hash_head !== 0 && s.strstart - hash_head <= s.w_size - MIN_LOOKAHEAD) {
          s.match_length = longest_match(s, hash_head);
        }
        if (s.match_length >= MIN_MATCH) {
          bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
          s.lookahead -= s.match_length;
          if (s.match_length <= s.max_lazy_match && s.lookahead >= MIN_MATCH) {
            s.match_length--;
            do {
              s.strstart++;
              s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
              hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
              s.head[s.ins_h] = s.strstart;
            } while (--s.match_length !== 0);
            s.strstart++;
          } else {
            s.strstart += s.match_length;
            s.match_length = 0;
            s.ins_h = s.window[s.strstart];
            s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + 1]) & s.hash_mask;
          }
        } else {
          bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
          s.lookahead--;
          s.strstart++;
        }
        if (bflush) {
          flush_block_only(s, false);
          if (s.strm.avail_out === 0) {
            return BS_NEED_MORE;
          }
        }
      }
      s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
      if (flush === Z_FINISH) {
        flush_block_only(s, true);
        if (s.strm.avail_out === 0) {
          return BS_FINISH_STARTED;
        }
        return BS_FINISH_DONE;
      }
      if (s.last_lit) {
        flush_block_only(s, false);
        if (s.strm.avail_out === 0) {
          return BS_NEED_MORE;
        }
      }
      return BS_BLOCK_DONE;
    }
    function deflate_slow(s, flush) {
      var hash_head;
      var bflush;
      var max_insert;
      for (; ; ) {
        if (s.lookahead < MIN_LOOKAHEAD) {
          fill_window(s);
          if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
            return BS_NEED_MORE;
          }
          if (s.lookahead === 0) {
            break;
          }
        }
        hash_head = 0;
        if (s.lookahead >= MIN_MATCH) {
          s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
          hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
          s.head[s.ins_h] = s.strstart;
        }
        s.prev_length = s.match_length;
        s.prev_match = s.match_start;
        s.match_length = MIN_MATCH - 1;
        if (hash_head !== 0 && s.prev_length < s.max_lazy_match && s.strstart - hash_head <= s.w_size - MIN_LOOKAHEAD) {
          s.match_length = longest_match(s, hash_head);
          if (s.match_length <= 5 && (s.strategy === Z_FILTERED || s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096)) {
            s.match_length = MIN_MATCH - 1;
          }
        }
        if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
          max_insert = s.strstart + s.lookahead - MIN_MATCH;
          bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
          s.lookahead -= s.prev_length - 1;
          s.prev_length -= 2;
          do {
            if (++s.strstart <= max_insert) {
              s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
              hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
              s.head[s.ins_h] = s.strstart;
            }
          } while (--s.prev_length !== 0);
          s.match_available = 0;
          s.match_length = MIN_MATCH - 1;
          s.strstart++;
          if (bflush) {
            flush_block_only(s, false);
            if (s.strm.avail_out === 0) {
              return BS_NEED_MORE;
            }
          }
        } else if (s.match_available) {
          bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
          if (bflush) {
            flush_block_only(s, false);
          }
          s.strstart++;
          s.lookahead--;
          if (s.strm.avail_out === 0) {
            return BS_NEED_MORE;
          }
        } else {
          s.match_available = 1;
          s.strstart++;
          s.lookahead--;
        }
      }
      if (s.match_available) {
        bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
        s.match_available = 0;
      }
      s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
      if (flush === Z_FINISH) {
        flush_block_only(s, true);
        if (s.strm.avail_out === 0) {
          return BS_FINISH_STARTED;
        }
        return BS_FINISH_DONE;
      }
      if (s.last_lit) {
        flush_block_only(s, false);
        if (s.strm.avail_out === 0) {
          return BS_NEED_MORE;
        }
      }
      return BS_BLOCK_DONE;
    }
    function deflate_rle(s, flush) {
      var bflush;
      var prev;
      var scan, strend;
      var _win = s.window;
      for (; ; ) {
        if (s.lookahead <= MAX_MATCH) {
          fill_window(s);
          if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
            return BS_NEED_MORE;
          }
          if (s.lookahead === 0) {
            break;
          }
        }
        s.match_length = 0;
        if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
          scan = s.strstart - 1;
          prev = _win[scan];
          if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
            strend = s.strstart + MAX_MATCH;
            do {
            } while (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && scan < strend);
            s.match_length = MAX_MATCH - (strend - scan);
            if (s.match_length > s.lookahead) {
              s.match_length = s.lookahead;
            }
          }
        }
        if (s.match_length >= MIN_MATCH) {
          bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
          s.lookahead -= s.match_length;
          s.strstart += s.match_length;
          s.match_length = 0;
        } else {
          bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
          s.lookahead--;
          s.strstart++;
        }
        if (bflush) {
          flush_block_only(s, false);
          if (s.strm.avail_out === 0) {
            return BS_NEED_MORE;
          }
        }
      }
      s.insert = 0;
      if (flush === Z_FINISH) {
        flush_block_only(s, true);
        if (s.strm.avail_out === 0) {
          return BS_FINISH_STARTED;
        }
        return BS_FINISH_DONE;
      }
      if (s.last_lit) {
        flush_block_only(s, false);
        if (s.strm.avail_out === 0) {
          return BS_NEED_MORE;
        }
      }
      return BS_BLOCK_DONE;
    }
    function deflate_huff(s, flush) {
      var bflush;
      for (; ; ) {
        if (s.lookahead === 0) {
          fill_window(s);
          if (s.lookahead === 0) {
            if (flush === Z_NO_FLUSH) {
              return BS_NEED_MORE;
            }
            break;
          }
        }
        s.match_length = 0;
        bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
        s.lookahead--;
        s.strstart++;
        if (bflush) {
          flush_block_only(s, false);
          if (s.strm.avail_out === 0) {
            return BS_NEED_MORE;
          }
        }
      }
      s.insert = 0;
      if (flush === Z_FINISH) {
        flush_block_only(s, true);
        if (s.strm.avail_out === 0) {
          return BS_FINISH_STARTED;
        }
        return BS_FINISH_DONE;
      }
      if (s.last_lit) {
        flush_block_only(s, false);
        if (s.strm.avail_out === 0) {
          return BS_NEED_MORE;
        }
      }
      return BS_BLOCK_DONE;
    }
    function Config(good_length, max_lazy, nice_length, max_chain, func) {
      this.good_length = good_length;
      this.max_lazy = max_lazy;
      this.nice_length = nice_length;
      this.max_chain = max_chain;
      this.func = func;
    }
    var configuration_table;
    configuration_table = [
      /*      good lazy nice chain */
      new Config(0, 0, 0, 0, deflate_stored),
      /* 0 store only */
      new Config(4, 4, 8, 4, deflate_fast),
      /* 1 max speed, no lazy matches */
      new Config(4, 5, 16, 8, deflate_fast),
      /* 2 */
      new Config(4, 6, 32, 32, deflate_fast),
      /* 3 */
      new Config(4, 4, 16, 16, deflate_slow),
      /* 4 lazy matches */
      new Config(8, 16, 32, 32, deflate_slow),
      /* 5 */
      new Config(8, 16, 128, 128, deflate_slow),
      /* 6 */
      new Config(8, 32, 128, 256, deflate_slow),
      /* 7 */
      new Config(32, 128, 258, 1024, deflate_slow),
      /* 8 */
      new Config(32, 258, 258, 4096, deflate_slow)
      /* 9 max compression */
    ];
    function lm_init(s) {
      s.window_size = 2 * s.w_size;
      zero(s.head);
      s.max_lazy_match = configuration_table[s.level].max_lazy;
      s.good_match = configuration_table[s.level].good_length;
      s.nice_match = configuration_table[s.level].nice_length;
      s.max_chain_length = configuration_table[s.level].max_chain;
      s.strstart = 0;
      s.block_start = 0;
      s.lookahead = 0;
      s.insert = 0;
      s.match_length = s.prev_length = MIN_MATCH - 1;
      s.match_available = 0;
      s.ins_h = 0;
    }
    function DeflateState() {
      this.strm = null;
      this.status = 0;
      this.pending_buf = null;
      this.pending_buf_size = 0;
      this.pending_out = 0;
      this.pending = 0;
      this.wrap = 0;
      this.gzhead = null;
      this.gzindex = 0;
      this.method = Z_DEFLATED;
      this.last_flush = -1;
      this.w_size = 0;
      this.w_bits = 0;
      this.w_mask = 0;
      this.window = null;
      this.window_size = 0;
      this.prev = null;
      this.head = null;
      this.ins_h = 0;
      this.hash_size = 0;
      this.hash_bits = 0;
      this.hash_mask = 0;
      this.hash_shift = 0;
      this.block_start = 0;
      this.match_length = 0;
      this.prev_match = 0;
      this.match_available = 0;
      this.strstart = 0;
      this.match_start = 0;
      this.lookahead = 0;
      this.prev_length = 0;
      this.max_chain_length = 0;
      this.max_lazy_match = 0;
      this.level = 0;
      this.strategy = 0;
      this.good_match = 0;
      this.nice_match = 0;
      this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
      this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);
      this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);
      zero(this.dyn_ltree);
      zero(this.dyn_dtree);
      zero(this.bl_tree);
      this.l_desc = null;
      this.d_desc = null;
      this.bl_desc = null;
      this.bl_count = new utils.Buf16(MAX_BITS + 1);
      this.heap = new utils.Buf16(2 * L_CODES + 1);
      zero(this.heap);
      this.heap_len = 0;
      this.heap_max = 0;
      this.depth = new utils.Buf16(2 * L_CODES + 1);
      zero(this.depth);
      this.l_buf = 0;
      this.lit_bufsize = 0;
      this.last_lit = 0;
      this.d_buf = 0;
      this.opt_len = 0;
      this.static_len = 0;
      this.matches = 0;
      this.insert = 0;
      this.bi_buf = 0;
      this.bi_valid = 0;
    }
    function deflateResetKeep(strm) {
      var s;
      if (!strm || !strm.state) {
        return err(strm, Z_STREAM_ERROR);
      }
      strm.total_in = strm.total_out = 0;
      strm.data_type = Z_UNKNOWN;
      s = strm.state;
      s.pending = 0;
      s.pending_out = 0;
      if (s.wrap < 0) {
        s.wrap = -s.wrap;
      }
      s.status = s.wrap ? INIT_STATE : BUSY_STATE;
      strm.adler = s.wrap === 2 ? 0 : 1;
      s.last_flush = Z_NO_FLUSH;
      trees._tr_init(s);
      return Z_OK;
    }
    function deflateReset(strm) {
      var ret = deflateResetKeep(strm);
      if (ret === Z_OK) {
        lm_init(strm.state);
      }
      return ret;
    }
    function deflateSetHeader(strm, head) {
      if (!strm || !strm.state) {
        return Z_STREAM_ERROR;
      }
      if (strm.state.wrap !== 2) {
        return Z_STREAM_ERROR;
      }
      strm.state.gzhead = head;
      return Z_OK;
    }
    function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
      if (!strm) {
        return Z_STREAM_ERROR;
      }
      var wrap = 1;
      if (level === Z_DEFAULT_COMPRESSION) {
        level = 6;
      }
      if (windowBits < 0) {
        wrap = 0;
        windowBits = -windowBits;
      } else if (windowBits > 15) {
        wrap = 2;
        windowBits -= 16;
      }
      if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
        return err(strm, Z_STREAM_ERROR);
      }
      if (windowBits === 8) {
        windowBits = 9;
      }
      var s = new DeflateState();
      strm.state = s;
      s.strm = strm;
      s.wrap = wrap;
      s.gzhead = null;
      s.w_bits = windowBits;
      s.w_size = 1 << s.w_bits;
      s.w_mask = s.w_size - 1;
      s.hash_bits = memLevel + 7;
      s.hash_size = 1 << s.hash_bits;
      s.hash_mask = s.hash_size - 1;
      s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
      s.window = new utils.Buf8(s.w_size * 2);
      s.head = new utils.Buf16(s.hash_size);
      s.prev = new utils.Buf16(s.w_size);
      s.lit_bufsize = 1 << memLevel + 6;
      s.pending_buf_size = s.lit_bufsize * 4;
      s.pending_buf = new utils.Buf8(s.pending_buf_size);
      s.d_buf = 1 * s.lit_bufsize;
      s.l_buf = (1 + 2) * s.lit_bufsize;
      s.level = level;
      s.strategy = strategy;
      s.method = method;
      return deflateReset(strm);
    }
    function deflateInit(strm, level) {
      return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
    }
    function deflate(strm, flush) {
      var old_flush, s;
      var beg, val;
      if (!strm || !strm.state || flush > Z_BLOCK || flush < 0) {
        return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
      }
      s = strm.state;
      if (!strm.output || !strm.input && strm.avail_in !== 0 || s.status === FINISH_STATE && flush !== Z_FINISH) {
        return err(strm, strm.avail_out === 0 ? Z_BUF_ERROR : Z_STREAM_ERROR);
      }
      s.strm = strm;
      old_flush = s.last_flush;
      s.last_flush = flush;
      if (s.status === INIT_STATE) {
        if (s.wrap === 2) {
          strm.adler = 0;
          put_byte(s, 31);
          put_byte(s, 139);
          put_byte(s, 8);
          if (!s.gzhead) {
            put_byte(s, 0);
            put_byte(s, 0);
            put_byte(s, 0);
            put_byte(s, 0);
            put_byte(s, 0);
            put_byte(s, s.level === 9 ? 2 : s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0);
            put_byte(s, OS_CODE);
            s.status = BUSY_STATE;
          } else {
            put_byte(
              s,
              (s.gzhead.text ? 1 : 0) + (s.gzhead.hcrc ? 2 : 0) + (!s.gzhead.extra ? 0 : 4) + (!s.gzhead.name ? 0 : 8) + (!s.gzhead.comment ? 0 : 16)
            );
            put_byte(s, s.gzhead.time & 255);
            put_byte(s, s.gzhead.time >> 8 & 255);
            put_byte(s, s.gzhead.time >> 16 & 255);
            put_byte(s, s.gzhead.time >> 24 & 255);
            put_byte(s, s.level === 9 ? 2 : s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0);
            put_byte(s, s.gzhead.os & 255);
            if (s.gzhead.extra && s.gzhead.extra.length) {
              put_byte(s, s.gzhead.extra.length & 255);
              put_byte(s, s.gzhead.extra.length >> 8 & 255);
            }
            if (s.gzhead.hcrc) {
              strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
            }
            s.gzindex = 0;
            s.status = EXTRA_STATE;
          }
        } else {
          var header = Z_DEFLATED + (s.w_bits - 8 << 4) << 8;
          var level_flags = -1;
          if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
            level_flags = 0;
          } else if (s.level < 6) {
            level_flags = 1;
          } else if (s.level === 6) {
            level_flags = 2;
          } else {
            level_flags = 3;
          }
          header |= level_flags << 6;
          if (s.strstart !== 0) {
            header |= PRESET_DICT;
          }
          header += 31 - header % 31;
          s.status = BUSY_STATE;
          putShortMSB(s, header);
          if (s.strstart !== 0) {
            putShortMSB(s, strm.adler >>> 16);
            putShortMSB(s, strm.adler & 65535);
          }
          strm.adler = 1;
        }
      }
      if (s.status === EXTRA_STATE) {
        if (s.gzhead.extra) {
          beg = s.pending;
          while (s.gzindex < (s.gzhead.extra.length & 65535)) {
            if (s.pending === s.pending_buf_size) {
              if (s.gzhead.hcrc && s.pending > beg) {
                strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
              }
              flush_pending(strm);
              beg = s.pending;
              if (s.pending === s.pending_buf_size) {
                break;
              }
            }
            put_byte(s, s.gzhead.extra[s.gzindex] & 255);
            s.gzindex++;
          }
          if (s.gzhead.hcrc && s.pending > beg) {
            strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
          }
          if (s.gzindex === s.gzhead.extra.length) {
            s.gzindex = 0;
            s.status = NAME_STATE;
          }
        } else {
          s.status = NAME_STATE;
        }
      }
      if (s.status === NAME_STATE) {
        if (s.gzhead.name) {
          beg = s.pending;
          do {
            if (s.pending === s.pending_buf_size) {
              if (s.gzhead.hcrc && s.pending > beg) {
                strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
              }
              flush_pending(strm);
              beg = s.pending;
              if (s.pending === s.pending_buf_size) {
                val = 1;
                break;
              }
            }
            if (s.gzindex < s.gzhead.name.length) {
              val = s.gzhead.name.charCodeAt(s.gzindex++) & 255;
            } else {
              val = 0;
            }
            put_byte(s, val);
          } while (val !== 0);
          if (s.gzhead.hcrc && s.pending > beg) {
            strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
          }
          if (val === 0) {
            s.gzindex = 0;
            s.status = COMMENT_STATE;
          }
        } else {
          s.status = COMMENT_STATE;
        }
      }
      if (s.status === COMMENT_STATE) {
        if (s.gzhead.comment) {
          beg = s.pending;
          do {
            if (s.pending === s.pending_buf_size) {
              if (s.gzhead.hcrc && s.pending > beg) {
                strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
              }
              flush_pending(strm);
              beg = s.pending;
              if (s.pending === s.pending_buf_size) {
                val = 1;
                break;
              }
            }
            if (s.gzindex < s.gzhead.comment.length) {
              val = s.gzhead.comment.charCodeAt(s.gzindex++) & 255;
            } else {
              val = 0;
            }
            put_byte(s, val);
          } while (val !== 0);
          if (s.gzhead.hcrc && s.pending > beg) {
            strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
          }
          if (val === 0) {
            s.status = HCRC_STATE;
          }
        } else {
          s.status = HCRC_STATE;
        }
      }
      if (s.status === HCRC_STATE) {
        if (s.gzhead.hcrc) {
          if (s.pending + 2 > s.pending_buf_size) {
            flush_pending(strm);
          }
          if (s.pending + 2 <= s.pending_buf_size) {
            put_byte(s, strm.adler & 255);
            put_byte(s, strm.adler >> 8 & 255);
            strm.adler = 0;
            s.status = BUSY_STATE;
          }
        } else {
          s.status = BUSY_STATE;
        }
      }
      if (s.pending !== 0) {
        flush_pending(strm);
        if (strm.avail_out === 0) {
          s.last_flush = -1;
          return Z_OK;
        }
      } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && flush !== Z_FINISH) {
        return err(strm, Z_BUF_ERROR);
      }
      if (s.status === FINISH_STATE && strm.avail_in !== 0) {
        return err(strm, Z_BUF_ERROR);
      }
      if (strm.avail_in !== 0 || s.lookahead !== 0 || flush !== Z_NO_FLUSH && s.status !== FINISH_STATE) {
        var bstate = s.strategy === Z_HUFFMAN_ONLY ? deflate_huff(s, flush) : s.strategy === Z_RLE ? deflate_rle(s, flush) : configuration_table[s.level].func(s, flush);
        if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
          s.status = FINISH_STATE;
        }
        if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
          if (strm.avail_out === 0) {
            s.last_flush = -1;
          }
          return Z_OK;
        }
        if (bstate === BS_BLOCK_DONE) {
          if (flush === Z_PARTIAL_FLUSH) {
            trees._tr_align(s);
          } else if (flush !== Z_BLOCK) {
            trees._tr_stored_block(s, 0, 0, false);
            if (flush === Z_FULL_FLUSH) {
              zero(s.head);
              if (s.lookahead === 0) {
                s.strstart = 0;
                s.block_start = 0;
                s.insert = 0;
              }
            }
          }
          flush_pending(strm);
          if (strm.avail_out === 0) {
            s.last_flush = -1;
            return Z_OK;
          }
        }
      }
      if (flush !== Z_FINISH) {
        return Z_OK;
      }
      if (s.wrap <= 0) {
        return Z_STREAM_END;
      }
      if (s.wrap === 2) {
        put_byte(s, strm.adler & 255);
        put_byte(s, strm.adler >> 8 & 255);
        put_byte(s, strm.adler >> 16 & 255);
        put_byte(s, strm.adler >> 24 & 255);
        put_byte(s, strm.total_in & 255);
        put_byte(s, strm.total_in >> 8 & 255);
        put_byte(s, strm.total_in >> 16 & 255);
        put_byte(s, strm.total_in >> 24 & 255);
      } else {
        putShortMSB(s, strm.adler >>> 16);
        putShortMSB(s, strm.adler & 65535);
      }
      flush_pending(strm);
      if (s.wrap > 0) {
        s.wrap = -s.wrap;
      }
      return s.pending !== 0 ? Z_OK : Z_STREAM_END;
    }
    function deflateEnd(strm) {
      var status;
      if (!strm || !strm.state) {
        return Z_STREAM_ERROR;
      }
      status = strm.state.status;
      if (status !== INIT_STATE && status !== EXTRA_STATE && status !== NAME_STATE && status !== COMMENT_STATE && status !== HCRC_STATE && status !== BUSY_STATE && status !== FINISH_STATE) {
        return err(strm, Z_STREAM_ERROR);
      }
      strm.state = null;
      return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
    }
    function deflateSetDictionary(strm, dictionary) {
      var dictLength = dictionary.length;
      var s;
      var str, n;
      var wrap;
      var avail;
      var next;
      var input;
      var tmpDict;
      if (!strm || !strm.state) {
        return Z_STREAM_ERROR;
      }
      s = strm.state;
      wrap = s.wrap;
      if (wrap === 2 || wrap === 1 && s.status !== INIT_STATE || s.lookahead) {
        return Z_STREAM_ERROR;
      }
      if (wrap === 1) {
        strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
      }
      s.wrap = 0;
      if (dictLength >= s.w_size) {
        if (wrap === 0) {
          zero(s.head);
          s.strstart = 0;
          s.block_start = 0;
          s.insert = 0;
        }
        tmpDict = new utils.Buf8(s.w_size);
        utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
        dictionary = tmpDict;
        dictLength = s.w_size;
      }
      avail = strm.avail_in;
      next = strm.next_in;
      input = strm.input;
      strm.avail_in = dictLength;
      strm.next_in = 0;
      strm.input = dictionary;
      fill_window(s);
      while (s.lookahead >= MIN_MATCH) {
        str = s.strstart;
        n = s.lookahead - (MIN_MATCH - 1);
        do {
          s.ins_h = (s.ins_h << s.hash_shift ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
          s.prev[str & s.w_mask] = s.head[s.ins_h];
          s.head[s.ins_h] = str;
          str++;
        } while (--n);
        s.strstart = str;
        s.lookahead = MIN_MATCH - 1;
        fill_window(s);
      }
      s.strstart += s.lookahead;
      s.block_start = s.strstart;
      s.insert = s.lookahead;
      s.lookahead = 0;
      s.match_length = s.prev_length = MIN_MATCH - 1;
      s.match_available = 0;
      strm.next_in = next;
      strm.input = input;
      strm.avail_in = avail;
      s.wrap = wrap;
      return Z_OK;
    }
    exports.deflateInit = deflateInit;
    exports.deflateInit2 = deflateInit2;
    exports.deflateReset = deflateReset;
    exports.deflateResetKeep = deflateResetKeep;
    exports.deflateSetHeader = deflateSetHeader;
    exports.deflate = deflate;
    exports.deflateEnd = deflateEnd;
    exports.deflateSetDictionary = deflateSetDictionary;
    exports.deflateInfo = "pako deflate (from Nodeca project)";
  }
});

// node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/utils/strings.js
var require_strings = __commonJS({
  "node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/utils/strings.js"(exports) {
    "use strict";
    var utils = require_common();
    var STR_APPLY_OK = true;
    var STR_APPLY_UIA_OK = true;
    try {
      String.fromCharCode.apply(null, [0]);
    } catch (__) {
      STR_APPLY_OK = false;
    }
    try {
      String.fromCharCode.apply(null, new Uint8Array(1));
    } catch (__) {
      STR_APPLY_UIA_OK = false;
    }
    var _utf8len = new utils.Buf8(256);
    for (q = 0; q < 256; q++) {
      _utf8len[q] = q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1;
    }
    var q;
    _utf8len[254] = _utf8len[254] = 1;
    exports.string2buf = function(str) {
      var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
      for (m_pos = 0; m_pos < str_len; m_pos++) {
        c = str.charCodeAt(m_pos);
        if ((c & 64512) === 55296 && m_pos + 1 < str_len) {
          c2 = str.charCodeAt(m_pos + 1);
          if ((c2 & 64512) === 56320) {
            c = 65536 + (c - 55296 << 10) + (c2 - 56320);
            m_pos++;
          }
        }
        buf_len += c < 128 ? 1 : c < 2048 ? 2 : c < 65536 ? 3 : 4;
      }
      buf = new utils.Buf8(buf_len);
      for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
        c = str.charCodeAt(m_pos);
        if ((c & 64512) === 55296 && m_pos + 1 < str_len) {
          c2 = str.charCodeAt(m_pos + 1);
          if ((c2 & 64512) === 56320) {
            c = 65536 + (c - 55296 << 10) + (c2 - 56320);
            m_pos++;
          }
        }
        if (c < 128) {
          buf[i++] = c;
        } else if (c < 2048) {
          buf[i++] = 192 | c >>> 6;
          buf[i++] = 128 | c & 63;
        } else if (c < 65536) {
          buf[i++] = 224 | c >>> 12;
          buf[i++] = 128 | c >>> 6 & 63;
          buf[i++] = 128 | c & 63;
        } else {
          buf[i++] = 240 | c >>> 18;
          buf[i++] = 128 | c >>> 12 & 63;
          buf[i++] = 128 | c >>> 6 & 63;
          buf[i++] = 128 | c & 63;
        }
      }
      return buf;
    };
    function buf2binstring(buf, len) {
      if (len < 65534) {
        if (buf.subarray && STR_APPLY_UIA_OK || !buf.subarray && STR_APPLY_OK) {
          return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
        }
      }
      var result = "";
      for (var i = 0; i < len; i++) {
        result += String.fromCharCode(buf[i]);
      }
      return result;
    }
    exports.buf2binstring = function(buf) {
      return buf2binstring(buf, buf.length);
    };
    exports.binstring2buf = function(str) {
      var buf = new utils.Buf8(str.length);
      for (var i = 0, len = buf.length; i < len; i++) {
        buf[i] = str.charCodeAt(i);
      }
      return buf;
    };
    exports.buf2string = function(buf, max) {
      var i, out, c, c_len;
      var len = max || buf.length;
      var utf16buf = new Array(len * 2);
      for (out = 0, i = 0; i < len; ) {
        c = buf[i++];
        if (c < 128) {
          utf16buf[out++] = c;
          continue;
        }
        c_len = _utf8len[c];
        if (c_len > 4) {
          utf16buf[out++] = 65533;
          i += c_len - 1;
          continue;
        }
        c &= c_len === 2 ? 31 : c_len === 3 ? 15 : 7;
        while (c_len > 1 && i < len) {
          c = c << 6 | buf[i++] & 63;
          c_len--;
        }
        if (c_len > 1) {
          utf16buf[out++] = 65533;
          continue;
        }
        if (c < 65536) {
          utf16buf[out++] = c;
        } else {
          c -= 65536;
          utf16buf[out++] = 55296 | c >> 10 & 1023;
          utf16buf[out++] = 56320 | c & 1023;
        }
      }
      return buf2binstring(utf16buf, out);
    };
    exports.utf8border = function(buf, max) {
      var pos;
      max = max || buf.length;
      if (max > buf.length) {
        max = buf.length;
      }
      pos = max - 1;
      while (pos >= 0 && (buf[pos] & 192) === 128) {
        pos--;
      }
      if (pos < 0) {
        return max;
      }
      if (pos === 0) {
        return max;
      }
      return pos + _utf8len[buf[pos]] > max ? pos : max;
    };
  }
});

// node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/zstream.js
var require_zstream = __commonJS({
  "node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/zstream.js"(exports, module2) {
    "use strict";
    function ZStream() {
      this.input = null;
      this.next_in = 0;
      this.avail_in = 0;
      this.total_in = 0;
      this.output = null;
      this.next_out = 0;
      this.avail_out = 0;
      this.total_out = 0;
      this.msg = "";
      this.state = null;
      this.data_type = 2;
      this.adler = 0;
    }
    module2.exports = ZStream;
  }
});

// node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/deflate.js
var require_deflate2 = __commonJS({
  "node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/deflate.js"(exports) {
    "use strict";
    var zlib_deflate = require_deflate();
    var utils = require_common();
    var strings = require_strings();
    var msg = require_messages();
    var ZStream = require_zstream();
    var toString = Object.prototype.toString;
    var Z_NO_FLUSH = 0;
    var Z_FINISH = 4;
    var Z_OK = 0;
    var Z_STREAM_END = 1;
    var Z_SYNC_FLUSH = 2;
    var Z_DEFAULT_COMPRESSION = -1;
    var Z_DEFAULT_STRATEGY = 0;
    var Z_DEFLATED = 8;
    function Deflate(options) {
      if (!(this instanceof Deflate)) return new Deflate(options);
      this.options = utils.assign({
        level: Z_DEFAULT_COMPRESSION,
        method: Z_DEFLATED,
        chunkSize: 16384,
        windowBits: 15,
        memLevel: 8,
        strategy: Z_DEFAULT_STRATEGY,
        to: ""
      }, options || {});
      var opt = this.options;
      if (opt.raw && opt.windowBits > 0) {
        opt.windowBits = -opt.windowBits;
      } else if (opt.gzip && opt.windowBits > 0 && opt.windowBits < 16) {
        opt.windowBits += 16;
      }
      this.err = 0;
      this.msg = "";
      this.ended = false;
      this.chunks = [];
      this.strm = new ZStream();
      this.strm.avail_out = 0;
      var status = zlib_deflate.deflateInit2(
        this.strm,
        opt.level,
        opt.method,
        opt.windowBits,
        opt.memLevel,
        opt.strategy
      );
      if (status !== Z_OK) {
        throw new Error(msg[status]);
      }
      if (opt.header) {
        zlib_deflate.deflateSetHeader(this.strm, opt.header);
      }
      if (opt.dictionary) {
        var dict;
        if (typeof opt.dictionary === "string") {
          dict = strings.string2buf(opt.dictionary);
        } else if (toString.call(opt.dictionary) === "[object ArrayBuffer]") {
          dict = new Uint8Array(opt.dictionary);
        } else {
          dict = opt.dictionary;
        }
        status = zlib_deflate.deflateSetDictionary(this.strm, dict);
        if (status !== Z_OK) {
          throw new Error(msg[status]);
        }
        this._dict_set = true;
      }
    }
    Deflate.prototype.push = function(data, mode) {
      var strm = this.strm;
      var chunkSize = this.options.chunkSize;
      var status, _mode;
      if (this.ended) {
        return false;
      }
      _mode = mode === ~~mode ? mode : mode === true ? Z_FINISH : Z_NO_FLUSH;
      if (typeof data === "string") {
        strm.input = strings.string2buf(data);
      } else if (toString.call(data) === "[object ArrayBuffer]") {
        strm.input = new Uint8Array(data);
      } else {
        strm.input = data;
      }
      strm.next_in = 0;
      strm.avail_in = strm.input.length;
      do {
        if (strm.avail_out === 0) {
          strm.output = new utils.Buf8(chunkSize);
          strm.next_out = 0;
          strm.avail_out = chunkSize;
        }
        status = zlib_deflate.deflate(strm, _mode);
        if (status !== Z_STREAM_END && status !== Z_OK) {
          this.onEnd(status);
          this.ended = true;
          return false;
        }
        if (strm.avail_out === 0 || strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH)) {
          if (this.options.to === "string") {
            this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
          } else {
            this.onData(utils.shrinkBuf(strm.output, strm.next_out));
          }
        }
      } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
      if (_mode === Z_FINISH) {
        status = zlib_deflate.deflateEnd(this.strm);
        this.onEnd(status);
        this.ended = true;
        return status === Z_OK;
      }
      if (_mode === Z_SYNC_FLUSH) {
        this.onEnd(Z_OK);
        strm.avail_out = 0;
        return true;
      }
      return true;
    };
    Deflate.prototype.onData = function(chunk) {
      this.chunks.push(chunk);
    };
    Deflate.prototype.onEnd = function(status) {
      if (status === Z_OK) {
        if (this.options.to === "string") {
          this.result = this.chunks.join("");
        } else {
          this.result = utils.flattenChunks(this.chunks);
        }
      }
      this.chunks = [];
      this.err = status;
      this.msg = this.strm.msg;
    };
    function deflate(input, options) {
      var deflator = new Deflate(options);
      deflator.push(input, true);
      if (deflator.err) {
        throw deflator.msg || msg[deflator.err];
      }
      return deflator.result;
    }
    function deflateRaw(input, options) {
      options = options || {};
      options.raw = true;
      return deflate(input, options);
    }
    function gzip(input, options) {
      options = options || {};
      options.gzip = true;
      return deflate(input, options);
    }
    exports.Deflate = Deflate;
    exports.deflate = deflate;
    exports.deflateRaw = deflateRaw;
    exports.gzip = gzip;
  }
});

// node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/inffast.js
var require_inffast = __commonJS({
  "node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/inffast.js"(exports, module2) {
    "use strict";
    var BAD = 30;
    var TYPE = 12;
    module2.exports = function inflate_fast(strm, start) {
      var state;
      var _in;
      var last2;
      var _out;
      var beg;
      var end;
      var dmax;
      var wsize;
      var whave;
      var wnext;
      var s_window;
      var hold;
      var bits;
      var lcode;
      var dcode;
      var lmask;
      var dmask;
      var here;
      var op;
      var len;
      var dist;
      var from;
      var from_source;
      var input, output;
      state = strm.state;
      _in = strm.next_in;
      input = strm.input;
      last2 = _in + (strm.avail_in - 5);
      _out = strm.next_out;
      output = strm.output;
      beg = _out - (start - strm.avail_out);
      end = _out + (strm.avail_out - 257);
      dmax = state.dmax;
      wsize = state.wsize;
      whave = state.whave;
      wnext = state.wnext;
      s_window = state.window;
      hold = state.hold;
      bits = state.bits;
      lcode = state.lencode;
      dcode = state.distcode;
      lmask = (1 << state.lenbits) - 1;
      dmask = (1 << state.distbits) - 1;
      top:
        do {
          if (bits < 15) {
            hold += input[_in++] << bits;
            bits += 8;
            hold += input[_in++] << bits;
            bits += 8;
          }
          here = lcode[hold & lmask];
          dolen:
            for (; ; ) {
              op = here >>> 24;
              hold >>>= op;
              bits -= op;
              op = here >>> 16 & 255;
              if (op === 0) {
                output[_out++] = here & 65535;
              } else if (op & 16) {
                len = here & 65535;
                op &= 15;
                if (op) {
                  if (bits < op) {
                    hold += input[_in++] << bits;
                    bits += 8;
                  }
                  len += hold & (1 << op) - 1;
                  hold >>>= op;
                  bits -= op;
                }
                if (bits < 15) {
                  hold += input[_in++] << bits;
                  bits += 8;
                  hold += input[_in++] << bits;
                  bits += 8;
                }
                here = dcode[hold & dmask];
                dodist:
                  for (; ; ) {
                    op = here >>> 24;
                    hold >>>= op;
                    bits -= op;
                    op = here >>> 16 & 255;
                    if (op & 16) {
                      dist = here & 65535;
                      op &= 15;
                      if (bits < op) {
                        hold += input[_in++] << bits;
                        bits += 8;
                        if (bits < op) {
                          hold += input[_in++] << bits;
                          bits += 8;
                        }
                      }
                      dist += hold & (1 << op) - 1;
                      if (dist > dmax) {
                        strm.msg = "invalid distance too far back";
                        state.mode = BAD;
                        break top;
                      }
                      hold >>>= op;
                      bits -= op;
                      op = _out - beg;
                      if (dist > op) {
                        op = dist - op;
                        if (op > whave) {
                          if (state.sane) {
                            strm.msg = "invalid distance too far back";
                            state.mode = BAD;
                            break top;
                          }
                        }
                        from = 0;
                        from_source = s_window;
                        if (wnext === 0) {
                          from += wsize - op;
                          if (op < len) {
                            len -= op;
                            do {
                              output[_out++] = s_window[from++];
                            } while (--op);
                            from = _out - dist;
                            from_source = output;
                          }
                        } else if (wnext < op) {
                          from += wsize + wnext - op;
                          op -= wnext;
                          if (op < len) {
                            len -= op;
                            do {
                              output[_out++] = s_window[from++];
                            } while (--op);
                            from = 0;
                            if (wnext < len) {
                              op = wnext;
                              len -= op;
                              do {
                                output[_out++] = s_window[from++];
                              } while (--op);
                              from = _out - dist;
                              from_source = output;
                            }
                          }
                        } else {
                          from += wnext - op;
                          if (op < len) {
                            len -= op;
                            do {
                              output[_out++] = s_window[from++];
                            } while (--op);
                            from = _out - dist;
                            from_source = output;
                          }
                        }
                        while (len > 2) {
                          output[_out++] = from_source[from++];
                          output[_out++] = from_source[from++];
                          output[_out++] = from_source[from++];
                          len -= 3;
                        }
                        if (len) {
                          output[_out++] = from_source[from++];
                          if (len > 1) {
                            output[_out++] = from_source[from++];
                          }
                        }
                      } else {
                        from = _out - dist;
                        do {
                          output[_out++] = output[from++];
                          output[_out++] = output[from++];
                          output[_out++] = output[from++];
                          len -= 3;
                        } while (len > 2);
                        if (len) {
                          output[_out++] = output[from++];
                          if (len > 1) {
                            output[_out++] = output[from++];
                          }
                        }
                      }
                    } else if ((op & 64) === 0) {
                      here = dcode[(here & 65535) + (hold & (1 << op) - 1)];
                      continue dodist;
                    } else {
                      strm.msg = "invalid distance code";
                      state.mode = BAD;
                      break top;
                    }
                    break;
                  }
              } else if ((op & 64) === 0) {
                here = lcode[(here & 65535) + (hold & (1 << op) - 1)];
                continue dolen;
              } else if (op & 32) {
                state.mode = TYPE;
                break top;
              } else {
                strm.msg = "invalid literal/length code";
                state.mode = BAD;
                break top;
              }
              break;
            }
        } while (_in < last2 && _out < end);
      len = bits >> 3;
      _in -= len;
      bits -= len << 3;
      hold &= (1 << bits) - 1;
      strm.next_in = _in;
      strm.next_out = _out;
      strm.avail_in = _in < last2 ? 5 + (last2 - _in) : 5 - (_in - last2);
      strm.avail_out = _out < end ? 257 + (end - _out) : 257 - (_out - end);
      state.hold = hold;
      state.bits = bits;
      return;
    };
  }
});

// node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/inftrees.js
var require_inftrees = __commonJS({
  "node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/inftrees.js"(exports, module2) {
    "use strict";
    var utils = require_common();
    var MAXBITS = 15;
    var ENOUGH_LENS = 852;
    var ENOUGH_DISTS = 592;
    var CODES = 0;
    var LENS = 1;
    var DISTS = 2;
    var lbase = [
      /* Length codes 257..285 base */
      3,
      4,
      5,
      6,
      7,
      8,
      9,
      10,
      11,
      13,
      15,
      17,
      19,
      23,
      27,
      31,
      35,
      43,
      51,
      59,
      67,
      83,
      99,
      115,
      131,
      163,
      195,
      227,
      258,
      0,
      0
    ];
    var lext = [
      /* Length codes 257..285 extra */
      16,
      16,
      16,
      16,
      16,
      16,
      16,
      16,
      17,
      17,
      17,
      17,
      18,
      18,
      18,
      18,
      19,
      19,
      19,
      19,
      20,
      20,
      20,
      20,
      21,
      21,
      21,
      21,
      16,
      72,
      78
    ];
    var dbase = [
      /* Distance codes 0..29 base */
      1,
      2,
      3,
      4,
      5,
      7,
      9,
      13,
      17,
      25,
      33,
      49,
      65,
      97,
      129,
      193,
      257,
      385,
      513,
      769,
      1025,
      1537,
      2049,
      3073,
      4097,
      6145,
      8193,
      12289,
      16385,
      24577,
      0,
      0
    ];
    var dext = [
      /* Distance codes 0..29 extra */
      16,
      16,
      16,
      16,
      17,
      17,
      18,
      18,
      19,
      19,
      20,
      20,
      21,
      21,
      22,
      22,
      23,
      23,
      24,
      24,
      25,
      25,
      26,
      26,
      27,
      27,
      28,
      28,
      29,
      29,
      64,
      64
    ];
    module2.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) {
      var bits = opts.bits;
      var len = 0;
      var sym = 0;
      var min = 0, max = 0;
      var root = 0;
      var curr = 0;
      var drop = 0;
      var left = 0;
      var used = 0;
      var huff = 0;
      var incr;
      var fill2;
      var low;
      var mask;
      var next;
      var base = null;
      var base_index = 0;
      var end;
      var count = new utils.Buf16(MAXBITS + 1);
      var offs = new utils.Buf16(MAXBITS + 1);
      var extra = null;
      var extra_index = 0;
      var here_bits, here_op, here_val;
      for (len = 0; len <= MAXBITS; len++) {
        count[len] = 0;
      }
      for (sym = 0; sym < codes; sym++) {
        count[lens[lens_index + sym]]++;
      }
      root = bits;
      for (max = MAXBITS; max >= 1; max--) {
        if (count[max] !== 0) {
          break;
        }
      }
      if (root > max) {
        root = max;
      }
      if (max === 0) {
        table[table_index++] = 1 << 24 | 64 << 16 | 0;
        table[table_index++] = 1 << 24 | 64 << 16 | 0;
        opts.bits = 1;
        return 0;
      }
      for (min = 1; min < max; min++) {
        if (count[min] !== 0) {
          break;
        }
      }
      if (root < min) {
        root = min;
      }
      left = 1;
      for (len = 1; len <= MAXBITS; len++) {
        left <<= 1;
        left -= count[len];
        if (left < 0) {
          return -1;
        }
      }
      if (left > 0 && (type === CODES || max !== 1)) {
        return -1;
      }
      offs[1] = 0;
      for (len = 1; len < MAXBITS; len++) {
        offs[len + 1] = offs[len] + count[len];
      }
      for (sym = 0; sym < codes; sym++) {
        if (lens[lens_index + sym] !== 0) {
          work[offs[lens[lens_index + sym]]++] = sym;
        }
      }
      if (type === CODES) {
        base = extra = work;
        end = 19;
      } else if (type === LENS) {
        base = lbase;
        base_index -= 257;
        extra = lext;
        extra_index -= 257;
        end = 256;
      } else {
        base = dbase;
        extra = dext;
        end = -1;
      }
      huff = 0;
      sym = 0;
      len = min;
      next = table_index;
      curr = root;
      drop = 0;
      low = -1;
      used = 1 << root;
      mask = used - 1;
      if (type === LENS && used > ENOUGH_LENS || type === DISTS && used > ENOUGH_DISTS) {
        return 1;
      }
      for (; ; ) {
        here_bits = len - drop;
        if (work[sym] < end) {
          here_op = 0;
          here_val = work[sym];
        } else if (work[sym] > end) {
          here_op = extra[extra_index + work[sym]];
          here_val = base[base_index + work[sym]];
        } else {
          here_op = 32 + 64;
          here_val = 0;
        }
        incr = 1 << len - drop;
        fill2 = 1 << curr;
        min = fill2;
        do {
          fill2 -= incr;
          table[next + (huff >> drop) + fill2] = here_bits << 24 | here_op << 16 | here_val | 0;
        } while (fill2 !== 0);
        incr = 1 << len - 1;
        while (huff & incr) {
          incr >>= 1;
        }
        if (incr !== 0) {
          huff &= incr - 1;
          huff += incr;
        } else {
          huff = 0;
        }
        sym++;
        if (--count[len] === 0) {
          if (len === max) {
            break;
          }
          len = lens[lens_index + work[sym]];
        }
        if (len > root && (huff & mask) !== low) {
          if (drop === 0) {
            drop = root;
          }
          next += min;
          curr = len - drop;
          left = 1 << curr;
          while (curr + drop < max) {
            left -= count[curr + drop];
            if (left <= 0) {
              break;
            }
            curr++;
            left <<= 1;
          }
          used += 1 << curr;
          if (type === LENS && used > ENOUGH_LENS || type === DISTS && used > ENOUGH_DISTS) {
            return 1;
          }
          low = huff & mask;
          table[low] = root << 24 | curr << 16 | next - table_index | 0;
        }
      }
      if (huff !== 0) {
        table[next + huff] = len - drop << 24 | 64 << 16 | 0;
      }
      opts.bits = root;
      return 0;
    };
  }
});

// node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/inflate.js
var require_inflate = __commonJS({
  "node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/inflate.js"(exports) {
    "use strict";
    var utils = require_common();
    var adler32 = require_adler32();
    var crc32 = require_crc32();
    var inflate_fast = require_inffast();
    var inflate_table = require_inftrees();
    var CODES = 0;
    var LENS = 1;
    var DISTS = 2;
    var Z_FINISH = 4;
    var Z_BLOCK = 5;
    var Z_TREES = 6;
    var Z_OK = 0;
    var Z_STREAM_END = 1;
    var Z_NEED_DICT = 2;
    var Z_STREAM_ERROR = -2;
    var Z_DATA_ERROR = -3;
    var Z_MEM_ERROR = -4;
    var Z_BUF_ERROR = -5;
    var Z_DEFLATED = 8;
    var HEAD = 1;
    var FLAGS = 2;
    var TIME = 3;
    var OS = 4;
    var EXLEN = 5;
    var EXTRA = 6;
    var NAME = 7;
    var COMMENT = 8;
    var HCRC = 9;
    var DICTID = 10;
    var DICT = 11;
    var TYPE = 12;
    var TYPEDO = 13;
    var STORED = 14;
    var COPY_ = 15;
    var COPY = 16;
    var TABLE = 17;
    var LENLENS = 18;
    var CODELENS = 19;
    var LEN_ = 20;
    var LEN = 21;
    var LENEXT = 22;
    var DIST = 23;
    var DISTEXT = 24;
    var MATCH = 25;
    var LIT = 26;
    var CHECK = 27;
    var LENGTH = 28;
    var DONE = 29;
    var BAD = 30;
    var MEM = 31;
    var SYNC = 32;
    var ENOUGH_LENS = 852;
    var ENOUGH_DISTS = 592;
    var MAX_WBITS = 15;
    var DEF_WBITS = MAX_WBITS;
    function zswap32(q) {
      return (q >>> 24 & 255) + (q >>> 8 & 65280) + ((q & 65280) << 8) + ((q & 255) << 24);
    }
    function InflateState() {
      this.mode = 0;
      this.last = false;
      this.wrap = 0;
      this.havedict = false;
      this.flags = 0;
      this.dmax = 0;
      this.check = 0;
      this.total = 0;
      this.head = null;
      this.wbits = 0;
      this.wsize = 0;
      this.whave = 0;
      this.wnext = 0;
      this.window = null;
      this.hold = 0;
      this.bits = 0;
      this.length = 0;
      this.offset = 0;
      this.extra = 0;
      this.lencode = null;
      this.distcode = null;
      this.lenbits = 0;
      this.distbits = 0;
      this.ncode = 0;
      this.nlen = 0;
      this.ndist = 0;
      this.have = 0;
      this.next = null;
      this.lens = new utils.Buf16(320);
      this.work = new utils.Buf16(288);
      this.lendyn = null;
      this.distdyn = null;
      this.sane = 0;
      this.back = 0;
      this.was = 0;
    }
    function inflateResetKeep(strm) {
      var state;
      if (!strm || !strm.state) {
        return Z_STREAM_ERROR;
      }
      state = strm.state;
      strm.total_in = strm.total_out = state.total = 0;
      strm.msg = "";
      if (state.wrap) {
        strm.adler = state.wrap & 1;
      }
      state.mode = HEAD;
      state.last = 0;
      state.havedict = 0;
      state.dmax = 32768;
      state.head = null;
      state.hold = 0;
      state.bits = 0;
      state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
      state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
      state.sane = 1;
      state.back = -1;
      return Z_OK;
    }
    function inflateReset(strm) {
      var state;
      if (!strm || !strm.state) {
        return Z_STREAM_ERROR;
      }
      state = strm.state;
      state.wsize = 0;
      state.whave = 0;
      state.wnext = 0;
      return inflateResetKeep(strm);
    }
    function inflateReset2(strm, windowBits) {
      var wrap;
      var state;
      if (!strm || !strm.state) {
        return Z_STREAM_ERROR;
      }
      state = strm.state;
      if (windowBits < 0) {
        wrap = 0;
        windowBits = -windowBits;
      } else {
        wrap = (windowBits >> 4) + 1;
        if (windowBits < 48) {
          windowBits &= 15;
        }
      }
      if (windowBits && (windowBits < 8 || windowBits > 15)) {
        return Z_STREAM_ERROR;
      }
      if (state.window !== null && state.wbits !== windowBits) {
        state.window = null;
      }
      state.wrap = wrap;
      state.wbits = windowBits;
      return inflateReset(strm);
    }
    function inflateInit2(strm, windowBits) {
      var ret;
      var state;
      if (!strm) {
        return Z_STREAM_ERROR;
      }
      state = new InflateState();
      strm.state = state;
      state.window = null;
      ret = inflateReset2(strm, windowBits);
      if (ret !== Z_OK) {
        strm.state = null;
      }
      return ret;
    }
    function inflateInit(strm) {
      return inflateInit2(strm, DEF_WBITS);
    }
    var virgin = true;
    var lenfix;
    var distfix;
    function fixedtables(state) {
      if (virgin) {
        var sym;
        lenfix = new utils.Buf32(512);
        distfix = new utils.Buf32(32);
        sym = 0;
        while (sym < 144) {
          state.lens[sym++] = 8;
        }
        while (sym < 256) {
          state.lens[sym++] = 9;
        }
        while (sym < 280) {
          state.lens[sym++] = 7;
        }
        while (sym < 288) {
          state.lens[sym++] = 8;
        }
        inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });
        sym = 0;
        while (sym < 32) {
          state.lens[sym++] = 5;
        }
        inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });
        virgin = false;
      }
      state.lencode = lenfix;
      state.lenbits = 9;
      state.distcode = distfix;
      state.distbits = 5;
    }
    function updatewindow(strm, src, end, copy) {
      var dist;
      var state = strm.state;
      if (state.window === null) {
        state.wsize = 1 << state.wbits;
        state.wnext = 0;
        state.whave = 0;
        state.window = new utils.Buf8(state.wsize);
      }
      if (copy >= state.wsize) {
        utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
        state.wnext = 0;
        state.whave = state.wsize;
      } else {
        dist = state.wsize - state.wnext;
        if (dist > copy) {
          dist = copy;
        }
        utils.arraySet(state.window, src, end - copy, dist, state.wnext);
        copy -= dist;
        if (copy) {
          utils.arraySet(state.window, src, end - copy, copy, 0);
          state.wnext = copy;
          state.whave = state.wsize;
        } else {
          state.wnext += dist;
          if (state.wnext === state.wsize) {
            state.wnext = 0;
          }
          if (state.whave < state.wsize) {
            state.whave += dist;
          }
        }
      }
      return 0;
    }
    function inflate(strm, flush) {
      var state;
      var input, output;
      var next;
      var put;
      var have, left;
      var hold;
      var bits;
      var _in, _out;
      var copy;
      var from;
      var from_source;
      var here = 0;
      var here_bits, here_op, here_val;
      var last_bits, last_op, last_val;
      var len;
      var ret;
      var hbuf = new utils.Buf8(4);
      var opts;
      var n;
      var order = (
        /* permutation of code lengths */
        [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]
      );
      if (!strm || !strm.state || !strm.output || !strm.input && strm.avail_in !== 0) {
        return Z_STREAM_ERROR;
      }
      state = strm.state;
      if (state.mode === TYPE) {
        state.mode = TYPEDO;
      }
      put = strm.next_out;
      output = strm.output;
      left = strm.avail_out;
      next = strm.next_in;
      input = strm.input;
      have = strm.avail_in;
      hold = state.hold;
      bits = state.bits;
      _in = have;
      _out = left;
      ret = Z_OK;
      inf_leave:
        for (; ; ) {
          switch (state.mode) {
            case HEAD:
              if (state.wrap === 0) {
                state.mode = TYPEDO;
                break;
              }
              while (bits < 16) {
                if (have === 0) {
                  break inf_leave;
                }
                have--;
                hold += input[next++] << bits;
                bits += 8;
              }
              if (state.wrap & 2 && hold === 35615) {
                state.check = 0;
                hbuf[0] = hold & 255;
                hbuf[1] = hold >>> 8 & 255;
                state.check = crc32(state.check, hbuf, 2, 0);
                hold = 0;
                bits = 0;
                state.mode = FLAGS;
                break;
              }
              state.flags = 0;
              if (state.head) {
                state.head.done = false;
              }
              if (!(state.wrap & 1) || /* check if zlib header allowed */
              (((hold & 255) << 8) + (hold >> 8)) % 31) {
                strm.msg = "incorrect header check";
                state.mode = BAD;
                break;
              }
              if ((hold & 15) !== Z_DEFLATED) {
                strm.msg = "unknown compression method";
                state.mode = BAD;
                break;
              }
              hold >>>= 4;
              bits -= 4;
              len = (hold & 15) + 8;
              if (state.wbits === 0) {
                state.wbits = len;
              } else if (len > state.wbits) {
                strm.msg = "invalid window size";
                state.mode = BAD;
                break;
              }
              state.dmax = 1 << len;
              strm.adler = state.check = 1;
              state.mode = hold & 512 ? DICTID : TYPE;
              hold = 0;
              bits = 0;
              break;
            case FLAGS:
              while (bits < 16) {
                if (have === 0) {
                  break inf_leave;
                }
                have--;
                hold += input[next++] << bits;
                bits += 8;
              }
              state.flags = hold;
              if ((state.flags & 255) !== Z_DEFLATED) {
                strm.msg = "unknown compression method";
                state.mode = BAD;
                break;
              }
              if (state.flags & 57344) {
                strm.msg = "unknown header flags set";
                state.mode = BAD;
                break;
              }
              if (state.head) {
                state.head.text = hold >> 8 & 1;
              }
              if (state.flags & 512) {
                hbuf[0] = hold & 255;
                hbuf[1] = hold >>> 8 & 255;
                state.check = crc32(state.check, hbuf, 2, 0);
              }
              hold = 0;
              bits = 0;
              state.mode = TIME;
            case TIME:
              while (bits < 32) {
                if (have === 0) {
                  break inf_leave;
                }
                have--;
                hold += input[next++] << bits;
                bits += 8;
              }
              if (state.head) {
                state.head.time = hold;
              }
              if (state.flags & 512) {
                hbuf[0] = hold & 255;
                hbuf[1] = hold >>> 8 & 255;
                hbuf[2] = hold >>> 16 & 255;
                hbuf[3] = hold >>> 24 & 255;
                state.check = crc32(state.check, hbuf, 4, 0);
              }
              hold = 0;
              bits = 0;
              state.mode = OS;
            case OS:
              while (bits < 16) {
                if (have === 0) {
                  break inf_leave;
                }
                have--;
                hold += input[next++] << bits;
                bits += 8;
              }
              if (state.head) {
                state.head.xflags = hold & 255;
                state.head.os = hold >> 8;
              }
              if (state.flags & 512) {
                hbuf[0] = hold & 255;
                hbuf[1] = hold >>> 8 & 255;
                state.check = crc32(state.check, hbuf, 2, 0);
              }
              hold = 0;
              bits = 0;
              state.mode = EXLEN;
            case EXLEN:
              if (state.flags & 1024) {
                while (bits < 16) {
                  if (have === 0) {
                    break inf_leave;
                  }
                  have--;
                  hold += input[next++] << bits;
                  bits += 8;
                }
                state.length = hold;
                if (state.head) {
                  state.head.extra_len = hold;
                }
                if (state.flags & 512) {
                  hbuf[0] = hold & 255;
                  hbuf[1] = hold >>> 8 & 255;
                  state.check = crc32(state.check, hbuf, 2, 0);
                }
                hold = 0;
                bits = 0;
              } else if (state.head) {
                state.head.extra = null;
              }
              state.mode = EXTRA;
            case EXTRA:
              if (state.flags & 1024) {
                copy = state.length;
                if (copy > have) {
                  copy = have;
                }
                if (copy) {
                  if (state.head) {
                    len = state.head.extra_len - state.length;
                    if (!state.head.extra) {
                      state.head.extra = new Array(state.head.extra_len);
                    }
                    utils.arraySet(
                      state.head.extra,
                      input,
                      next,
                      // extra field is limited to 65536 bytes
                      // - no need for additional size check
                      copy,
                      /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
                      len
                    );
                  }
                  if (state.flags & 512) {
                    state.check = crc32(state.check, input, copy, next);
                  }
                  have -= copy;
                  next += copy;
                  state.length -= copy;
                }
                if (state.length) {
                  break inf_leave;
                }
              }
              state.length = 0;
              state.mode = NAME;
            case NAME:
              if (state.flags & 2048) {
                if (have === 0) {
                  break inf_leave;
                }
                copy = 0;
                do {
                  len = input[next + copy++];
                  if (state.head && len && state.length < 65536) {
                    state.head.name += String.fromCharCode(len);
                  }
                } while (len && copy < have);
                if (state.flags & 512) {
                  state.check = crc32(state.check, input, copy, next);
                }
                have -= copy;
                next += copy;
                if (len) {
                  break inf_leave;
                }
              } else if (state.head) {
                state.head.name = null;
              }
              state.length = 0;
              state.mode = COMMENT;
            case COMMENT:
              if (state.flags & 4096) {
                if (have === 0) {
                  break inf_leave;
                }
                copy = 0;
                do {
                  len = input[next + copy++];
                  if (state.head && len && state.length < 65536) {
                    state.head.comment += String.fromCharCode(len);
                  }
                } while (len && copy < have);
                if (state.flags & 512) {
                  state.check = crc32(state.check, input, copy, next);
                }
                have -= copy;
                next += copy;
                if (len) {
                  break inf_leave;
                }
              } else if (state.head) {
                state.head.comment = null;
              }
              state.mode = HCRC;
            case HCRC:
              if (state.flags & 512) {
                while (bits < 16) {
                  if (have === 0) {
                    break inf_leave;
                  }
                  have--;
                  hold += input[next++] << bits;
                  bits += 8;
                }
                if (hold !== (state.check & 65535)) {
                  strm.msg = "header crc mismatch";
                  state.mode = BAD;
                  break;
                }
                hold = 0;
                bits = 0;
              }
              if (state.head) {
                state.head.hcrc = state.flags >> 9 & 1;
                state.head.done = true;
              }
              strm.adler = state.check = 0;
              state.mode = TYPE;
              break;
            case DICTID:
              while (bits < 32) {
                if (have === 0) {
                  break inf_leave;
                }
                have--;
                hold += input[next++] << bits;
                bits += 8;
              }
              strm.adler = state.check = zswap32(hold);
              hold = 0;
              bits = 0;
              state.mode = DICT;
            case DICT:
              if (state.havedict === 0) {
                strm.next_out = put;
                strm.avail_out = left;
                strm.next_in = next;
                strm.avail_in = have;
                state.hold = hold;
                state.bits = bits;
                return Z_NEED_DICT;
              }
              strm.adler = state.check = 1;
              state.mode = TYPE;
            case TYPE:
              if (flush === Z_BLOCK || flush === Z_TREES) {
                break inf_leave;
              }
            case TYPEDO:
              if (state.last) {
                hold >>>= bits & 7;
                bits -= bits & 7;
                state.mode = CHECK;
                break;
              }
              while (bits < 3) {
                if (have === 0) {
                  break inf_leave;
                }
                have--;
                hold += input[next++] << bits;
                bits += 8;
              }
              state.last = hold & 1;
              hold >>>= 1;
              bits -= 1;
              switch (hold & 3) {
                case 0:
                  state.mode = STORED;
                  break;
                case 1:
                  fixedtables(state);
                  state.mode = LEN_;
                  if (flush === Z_TREES) {
                    hold >>>= 2;
                    bits -= 2;
                    break inf_leave;
                  }
                  break;
                case 2:
                  state.mode = TABLE;
                  break;
                case 3:
                  strm.msg = "invalid block type";
                  state.mode = BAD;
              }
              hold >>>= 2;
              bits -= 2;
              break;
            case STORED:
              hold >>>= bits & 7;
              bits -= bits & 7;
              while (bits < 32) {
                if (have === 0) {
                  break inf_leave;
                }
                have--;
                hold += input[next++] << bits;
                bits += 8;
              }
              if ((hold & 65535) !== (hold >>> 16 ^ 65535)) {
                strm.msg = "invalid stored block lengths";
                state.mode = BAD;
                break;
              }
              state.length = hold & 65535;
              hold = 0;
              bits = 0;
              state.mode = COPY_;
              if (flush === Z_TREES) {
                break inf_leave;
              }
            case COPY_:
              state.mode = COPY;
            case COPY:
              copy = state.length;
              if (copy) {
                if (copy > have) {
                  copy = have;
                }
                if (copy > left) {
                  copy = left;
                }
                if (copy === 0) {
                  break inf_leave;
                }
                utils.arraySet(output, input, next, copy, put);
                have -= copy;
                next += copy;
                left -= copy;
                put += copy;
                state.length -= copy;
                break;
              }
              state.mode = TYPE;
              break;
            case TABLE:
              while (bits < 14) {
                if (have === 0) {
                  break inf_leave;
                }
                have--;
                hold += input[next++] << bits;
                bits += 8;
              }
              state.nlen = (hold & 31) + 257;
              hold >>>= 5;
              bits -= 5;
              state.ndist = (hold & 31) + 1;
              hold >>>= 5;
              bits -= 5;
              state.ncode = (hold & 15) + 4;
              hold >>>= 4;
              bits -= 4;
              if (state.nlen > 286 || state.ndist > 30) {
                strm.msg = "too many length or distance symbols";
                state.mode = BAD;
                break;
              }
              state.have = 0;
              state.mode = LENLENS;
            case LENLENS:
              while (state.have < state.ncode) {
                while (bits < 3) {
                  if (have === 0) {
                    break inf_leave;
                  }
                  have--;
                  hold += input[next++] << bits;
                  bits += 8;
                }
                state.lens[order[state.have++]] = hold & 7;
                hold >>>= 3;
                bits -= 3;
              }
              while (state.have < 19) {
                state.lens[order[state.have++]] = 0;
              }
              state.lencode = state.lendyn;
              state.lenbits = 7;
              opts = { bits: state.lenbits };
              ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
              state.lenbits = opts.bits;
              if (ret) {
                strm.msg = "invalid code lengths set";
                state.mode = BAD;
                break;
              }
              state.have = 0;
              state.mode = CODELENS;
            case CODELENS:
              while (state.have < state.nlen + state.ndist) {
                for (; ; ) {
                  here = state.lencode[hold & (1 << state.lenbits) - 1];
                  here_bits = here >>> 24;
                  here_op = here >>> 16 & 255;
                  here_val = here & 65535;
                  if (here_bits <= bits) {
                    break;
                  }
                  if (have === 0) {
                    break inf_leave;
                  }
                  have--;
                  hold += input[next++] << bits;
                  bits += 8;
                }
                if (here_val < 16) {
                  hold >>>= here_bits;
                  bits -= here_bits;
                  state.lens[state.have++] = here_val;
                } else {
                  if (here_val === 16) {
                    n = here_bits + 2;
                    while (bits < n) {
                      if (have === 0) {
                        break inf_leave;
                      }
                      have--;
                      hold += input[next++] << bits;
                      bits += 8;
                    }
                    hold >>>= here_bits;
                    bits -= here_bits;
                    if (state.have === 0) {
                      strm.msg = "invalid bit length repeat";
                      state.mode = BAD;
                      break;
                    }
                    len = state.lens[state.have - 1];
                    copy = 3 + (hold & 3);
                    hold >>>= 2;
                    bits -= 2;
                  } else if (here_val === 17) {
                    n = here_bits + 3;
                    while (bits < n) {
                      if (have === 0) {
                        break inf_leave;
                      }
                      have--;
                      hold += input[next++] << bits;
                      bits += 8;
                    }
                    hold >>>= here_bits;
                    bits -= here_bits;
                    len = 0;
                    copy = 3 + (hold & 7);
                    hold >>>= 3;
                    bits -= 3;
                  } else {
                    n = here_bits + 7;
                    while (bits < n) {
                      if (have === 0) {
                        break inf_leave;
                      }
                      have--;
                      hold += input[next++] << bits;
                      bits += 8;
                    }
                    hold >>>= here_bits;
                    bits -= here_bits;
                    len = 0;
                    copy = 11 + (hold & 127);
                    hold >>>= 7;
                    bits -= 7;
                  }
                  if (state.have + copy > state.nlen + state.ndist) {
                    strm.msg = "invalid bit length repeat";
                    state.mode = BAD;
                    break;
                  }
                  while (copy--) {
                    state.lens[state.have++] = len;
                  }
                }
              }
              if (state.mode === BAD) {
                break;
              }
              if (state.lens[256] === 0) {
                strm.msg = "invalid code -- missing end-of-block";
                state.mode = BAD;
                break;
              }
              state.lenbits = 9;
              opts = { bits: state.lenbits };
              ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
              state.lenbits = opts.bits;
              if (ret) {
                strm.msg = "invalid literal/lengths set";
                state.mode = BAD;
                break;
              }
              state.distbits = 6;
              state.distcode = state.distdyn;
              opts = { bits: state.distbits };
              ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
              state.distbits = opts.bits;
              if (ret) {
                strm.msg = "invalid distances set";
                state.mode = BAD;
                break;
              }
              state.mode = LEN_;
              if (flush === Z_TREES) {
                break inf_leave;
              }
            case LEN_:
              state.mode = LEN;
            case LEN:
              if (have >= 6 && left >= 258) {
                strm.next_out = put;
                strm.avail_out = left;
                strm.next_in = next;
                strm.avail_in = have;
                state.hold = hold;
                state.bits = bits;
                inflate_fast(strm, _out);
                put = strm.next_out;
                output = strm.output;
                left = strm.avail_out;
                next = strm.next_in;
                input = strm.input;
                have = strm.avail_in;
                hold = state.hold;
                bits = state.bits;
                if (state.mode === TYPE) {
                  state.back = -1;
                }
                break;
              }
              state.back = 0;
              for (; ; ) {
                here = state.lencode[hold & (1 << state.lenbits) - 1];
                here_bits = here >>> 24;
                here_op = here >>> 16 & 255;
                here_val = here & 65535;
                if (here_bits <= bits) {
                  break;
                }
                if (have === 0) {
                  break inf_leave;
                }
                have--;
                hold += input[next++] << bits;
                bits += 8;
              }
              if (here_op && (here_op & 240) === 0) {
                last_bits = here_bits;
                last_op = here_op;
                last_val = here_val;
                for (; ; ) {
                  here = state.lencode[last_val + ((hold & (1 << last_bits + last_op) - 1) >> last_bits)];
                  here_bits = here >>> 24;
                  here_op = here >>> 16 & 255;
                  here_val = here & 65535;
                  if (last_bits + here_bits <= bits) {
                    break;
                  }
                  if (have === 0) {
                    break inf_leave;
                  }
                  have--;
                  hold += input[next++] << bits;
                  bits += 8;
                }
                hold >>>= last_bits;
                bits -= last_bits;
                state.back += last_bits;
              }
              hold >>>= here_bits;
              bits -= here_bits;
              state.back += here_bits;
              state.length = here_val;
              if (here_op === 0) {
                state.mode = LIT;
                break;
              }
              if (here_op & 32) {
                state.back = -1;
                state.mode = TYPE;
                break;
              }
              if (here_op & 64) {
                strm.msg = "invalid literal/length code";
                state.mode = BAD;
                break;
              }
              state.extra = here_op & 15;
              state.mode = LENEXT;
            case LENEXT:
              if (state.extra) {
                n = state.extra;
                while (bits < n) {
                  if (have === 0) {
                    break inf_leave;
                  }
                  have--;
                  hold += input[next++] << bits;
                  bits += 8;
                }
                state.length += hold & (1 << state.extra) - 1;
                hold >>>= state.extra;
                bits -= state.extra;
                state.back += state.extra;
              }
              state.was = state.length;
              state.mode = DIST;
            case DIST:
              for (; ; ) {
                here = state.distcode[hold & (1 << state.distbits) - 1];
                here_bits = here >>> 24;
                here_op = here >>> 16 & 255;
                here_val = here & 65535;
                if (here_bits <= bits) {
                  break;
                }
                if (have === 0) {
                  break inf_leave;
                }
                have--;
                hold += input[next++] << bits;
                bits += 8;
              }
              if ((here_op & 240) === 0) {
                last_bits = here_bits;
                last_op = here_op;
                last_val = here_val;
                for (; ; ) {
                  here = state.distcode[last_val + ((hold & (1 << last_bits + last_op) - 1) >> last_bits)];
                  here_bits = here >>> 24;
                  here_op = here >>> 16 & 255;
                  here_val = here & 65535;
                  if (last_bits + here_bits <= bits) {
                    break;
                  }
                  if (have === 0) {
                    break inf_leave;
                  }
                  have--;
                  hold += input[next++] << bits;
                  bits += 8;
                }
                hold >>>= last_bits;
                bits -= last_bits;
                state.back += last_bits;
              }
              hold >>>= here_bits;
              bits -= here_bits;
              state.back += here_bits;
              if (here_op & 64) {
                strm.msg = "invalid distance code";
                state.mode = BAD;
                break;
              }
              state.offset = here_val;
              state.extra = here_op & 15;
              state.mode = DISTEXT;
            case DISTEXT:
              if (state.extra) {
                n = state.extra;
                while (bits < n) {
                  if (have === 0) {
                    break inf_leave;
                  }
                  have--;
                  hold += input[next++] << bits;
                  bits += 8;
                }
                state.offset += hold & (1 << state.extra) - 1;
                hold >>>= state.extra;
                bits -= state.extra;
                state.back += state.extra;
              }
              if (state.offset > state.dmax) {
                strm.msg = "invalid distance too far back";
                state.mode = BAD;
                break;
              }
              state.mode = MATCH;
            case MATCH:
              if (left === 0) {
                break inf_leave;
              }
              copy = _out - left;
              if (state.offset > copy) {
                copy = state.offset - copy;
                if (copy > state.whave) {
                  if (state.sane) {
                    strm.msg = "invalid distance too far back";
                    state.mode = BAD;
                    break;
                  }
                }
                if (copy > state.wnext) {
                  copy -= state.wnext;
                  from = state.wsize - copy;
                } else {
                  from = state.wnext - copy;
                }
                if (copy > state.length) {
                  copy = state.length;
                }
                from_source = state.window;
              } else {
                from_source = output;
                from = put - state.offset;
                copy = state.length;
              }
              if (copy > left) {
                copy = left;
              }
              left -= copy;
              state.length -= copy;
              do {
                output[put++] = from_source[from++];
              } while (--copy);
              if (state.length === 0) {
                state.mode = LEN;
              }
              break;
            case LIT:
              if (left === 0) {
                break inf_leave;
              }
              output[put++] = state.length;
              left--;
              state.mode = LEN;
              break;
            case CHECK:
              if (state.wrap) {
                while (bits < 32) {
                  if (have === 0) {
                    break inf_leave;
                  }
                  have--;
                  hold |= input[next++] << bits;
                  bits += 8;
                }
                _out -= left;
                strm.total_out += _out;
                state.total += _out;
                if (_out) {
                  strm.adler = state.check = /*UPDATE(state.check, put - _out, _out);*/
                  state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out);
                }
                _out = left;
                if ((state.flags ? hold : zswap32(hold)) !== state.check) {
                  strm.msg = "incorrect data check";
                  state.mode = BAD;
                  break;
                }
                hold = 0;
                bits = 0;
              }
              state.mode = LENGTH;
            case LENGTH:
              if (state.wrap && state.flags) {
                while (bits < 32) {
                  if (have === 0) {
                    break inf_leave;
                  }
                  have--;
                  hold += input[next++] << bits;
                  bits += 8;
                }
                if (hold !== (state.total & 4294967295)) {
                  strm.msg = "incorrect length check";
                  state.mode = BAD;
                  break;
                }
                hold = 0;
                bits = 0;
              }
              state.mode = DONE;
            case DONE:
              ret = Z_STREAM_END;
              break inf_leave;
            case BAD:
              ret = Z_DATA_ERROR;
              break inf_leave;
            case MEM:
              return Z_MEM_ERROR;
            case SYNC:
            default:
              return Z_STREAM_ERROR;
          }
        }
      strm.next_out = put;
      strm.avail_out = left;
      strm.next_in = next;
      strm.avail_in = have;
      state.hold = hold;
      state.bits = bits;
      if (state.wsize || _out !== strm.avail_out && state.mode < BAD && (state.mode < CHECK || flush !== Z_FINISH)) {
        if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
          state.mode = MEM;
          return Z_MEM_ERROR;
        }
      }
      _in -= strm.avail_in;
      _out -= strm.avail_out;
      strm.total_in += _in;
      strm.total_out += _out;
      state.total += _out;
      if (state.wrap && _out) {
        strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
        state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out);
      }
      strm.data_type = state.bits + (state.last ? 64 : 0) + (state.mode === TYPE ? 128 : 0) + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
      if ((_in === 0 && _out === 0 || flush === Z_FINISH) && ret === Z_OK) {
        ret = Z_BUF_ERROR;
      }
      return ret;
    }
    function inflateEnd(strm) {
      if (!strm || !strm.state) {
        return Z_STREAM_ERROR;
      }
      var state = strm.state;
      if (state.window) {
        state.window = null;
      }
      strm.state = null;
      return Z_OK;
    }
    function inflateGetHeader(strm, head) {
      var state;
      if (!strm || !strm.state) {
        return Z_STREAM_ERROR;
      }
      state = strm.state;
      if ((state.wrap & 2) === 0) {
        return Z_STREAM_ERROR;
      }
      state.head = head;
      head.done = false;
      return Z_OK;
    }
    function inflateSetDictionary(strm, dictionary) {
      var dictLength = dictionary.length;
      var state;
      var dictid;
      var ret;
      if (!strm || !strm.state) {
        return Z_STREAM_ERROR;
      }
      state = strm.state;
      if (state.wrap !== 0 && state.mode !== DICT) {
        return Z_STREAM_ERROR;
      }
      if (state.mode === DICT) {
        dictid = 1;
        dictid = adler32(dictid, dictionary, dictLength, 0);
        if (dictid !== state.check) {
          return Z_DATA_ERROR;
        }
      }
      ret = updatewindow(strm, dictionary, dictLength, dictLength);
      if (ret) {
        state.mode = MEM;
        return Z_MEM_ERROR;
      }
      state.havedict = 1;
      return Z_OK;
    }
    exports.inflateReset = inflateReset;
    exports.inflateReset2 = inflateReset2;
    exports.inflateResetKeep = inflateResetKeep;
    exports.inflateInit = inflateInit;
    exports.inflateInit2 = inflateInit2;
    exports.inflate = inflate;
    exports.inflateEnd = inflateEnd;
    exports.inflateGetHeader = inflateGetHeader;
    exports.inflateSetDictionary = inflateSetDictionary;
    exports.inflateInfo = "pako inflate (from Nodeca project)";
  }
});

// node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/constants.js
var require_constants = __commonJS({
  "node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/constants.js"(exports, module2) {
    "use strict";
    module2.exports = {
      /* Allowed flush values; see deflate() and inflate() below for details */
      Z_NO_FLUSH: 0,
      Z_PARTIAL_FLUSH: 1,
      Z_SYNC_FLUSH: 2,
      Z_FULL_FLUSH: 3,
      Z_FINISH: 4,
      Z_BLOCK: 5,
      Z_TREES: 6,
      /* Return codes for the compression/decompression functions. Negative values
      * are errors, positive values are used for special but normal events.
      */
      Z_OK: 0,
      Z_STREAM_END: 1,
      Z_NEED_DICT: 2,
      Z_ERRNO: -1,
      Z_STREAM_ERROR: -2,
      Z_DATA_ERROR: -3,
      //Z_MEM_ERROR:     -4,
      Z_BUF_ERROR: -5,
      //Z_VERSION_ERROR: -6,
      /* compression levels */
      Z_NO_COMPRESSION: 0,
      Z_BEST_SPEED: 1,
      Z_BEST_COMPRESSION: 9,
      Z_DEFAULT_COMPRESSION: -1,
      Z_FILTERED: 1,
      Z_HUFFMAN_ONLY: 2,
      Z_RLE: 3,
      Z_FIXED: 4,
      Z_DEFAULT_STRATEGY: 0,
      /* Possible values of the data_type field (though see inflate()) */
      Z_BINARY: 0,
      Z_TEXT: 1,
      //Z_ASCII:                1, // = Z_TEXT (deprecated)
      Z_UNKNOWN: 2,
      /* The deflate compression method */
      Z_DEFLATED: 8
      //Z_NULL:                 null // Use -1 or null inline, depending on var type
    };
  }
});

// node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/gzheader.js
var require_gzheader = __commonJS({
  "node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/gzheader.js"(exports, module2) {
    "use strict";
    function GZheader() {
      this.text = 0;
      this.time = 0;
      this.xflags = 0;
      this.os = 0;
      this.extra = null;
      this.extra_len = 0;
      this.name = "";
      this.comment = "";
      this.hcrc = 0;
      this.done = false;
    }
    module2.exports = GZheader;
  }
});

// node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/inflate.js
var require_inflate2 = __commonJS({
  "node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/inflate.js"(exports) {
    "use strict";
    var zlib_inflate = require_inflate();
    var utils = require_common();
    var strings = require_strings();
    var c = require_constants();
    var msg = require_messages();
    var ZStream = require_zstream();
    var GZheader = require_gzheader();
    var toString = Object.prototype.toString;
    function Inflate(options) {
      if (!(this instanceof Inflate)) return new Inflate(options);
      this.options = utils.assign({
        chunkSize: 16384,
        windowBits: 0,
        to: ""
      }, options || {});
      var opt = this.options;
      if (opt.raw && opt.windowBits >= 0 && opt.windowBits < 16) {
        opt.windowBits = -opt.windowBits;
        if (opt.windowBits === 0) {
          opt.windowBits = -15;
        }
      }
      if (opt.windowBits >= 0 && opt.windowBits < 16 && !(options && options.windowBits)) {
        opt.windowBits += 32;
      }
      if (opt.windowBits > 15 && opt.windowBits < 48) {
        if ((opt.windowBits & 15) === 0) {
          opt.windowBits |= 15;
        }
      }
      this.err = 0;
      this.msg = "";
      this.ended = false;
      this.chunks = [];
      this.strm = new ZStream();
      this.strm.avail_out = 0;
      var status = zlib_inflate.inflateInit2(
        this.strm,
        opt.windowBits
      );
      if (status !== c.Z_OK) {
        throw new Error(msg[status]);
      }
      this.header = new GZheader();
      zlib_inflate.inflateGetHeader(this.strm, this.header);
      if (opt.dictionary) {
        if (typeof opt.dictionary === "string") {
          opt.dictionary = strings.string2buf(opt.dictionary);
        } else if (toString.call(opt.dictionary) === "[object ArrayBuffer]") {
          opt.dictionary = new Uint8Array(opt.dictionary);
        }
        if (opt.raw) {
          status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary);
          if (status !== c.Z_OK) {
            throw new Error(msg[status]);
          }
        }
      }
    }
    Inflate.prototype.push = function(data, mode) {
      var strm = this.strm;
      var chunkSize = this.options.chunkSize;
      var dictionary = this.options.dictionary;
      var status, _mode;
      var next_out_utf8, tail, utf8str;
      var allowBufError = false;
      if (this.ended) {
        return false;
      }
      _mode = mode === ~~mode ? mode : mode === true ? c.Z_FINISH : c.Z_NO_FLUSH;
      if (typeof data === "string") {
        strm.input = strings.binstring2buf(data);
      } else if (toString.call(data) === "[object ArrayBuffer]") {
        strm.input = new Uint8Array(data);
      } else {
        strm.input = data;
      }
      strm.next_in = 0;
      strm.avail_in = strm.input.length;
      do {
        if (strm.avail_out === 0) {
          strm.output = new utils.Buf8(chunkSize);
          strm.next_out = 0;
          strm.avail_out = chunkSize;
        }
        status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH);
        if (status === c.Z_NEED_DICT && dictionary) {
          status = zlib_inflate.inflateSetDictionary(this.strm, dictionary);
        }
        if (status === c.Z_BUF_ERROR && allowBufError === true) {
          status = c.Z_OK;
          allowBufError = false;
        }
        if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
          this.onEnd(status);
          this.ended = true;
          return false;
        }
        if (strm.next_out) {
          if (strm.avail_out === 0 || status === c.Z_STREAM_END || strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH)) {
            if (this.options.to === "string") {
              next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
              tail = strm.next_out - next_out_utf8;
              utf8str = strings.buf2string(strm.output, next_out_utf8);
              strm.next_out = tail;
              strm.avail_out = chunkSize - tail;
              if (tail) {
                utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0);
              }
              this.onData(utf8str);
            } else {
              this.onData(utils.shrinkBuf(strm.output, strm.next_out));
            }
          }
        }
        if (strm.avail_in === 0 && strm.avail_out === 0) {
          allowBufError = true;
        }
      } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
      if (status === c.Z_STREAM_END) {
        _mode = c.Z_FINISH;
      }
      if (_mode === c.Z_FINISH) {
        status = zlib_inflate.inflateEnd(this.strm);
        this.onEnd(status);
        this.ended = true;
        return status === c.Z_OK;
      }
      if (_mode === c.Z_SYNC_FLUSH) {
        this.onEnd(c.Z_OK);
        strm.avail_out = 0;
        return true;
      }
      return true;
    };
    Inflate.prototype.onData = function(chunk) {
      this.chunks.push(chunk);
    };
    Inflate.prototype.onEnd = function(status) {
      if (status === c.Z_OK) {
        if (this.options.to === "string") {
          this.result = this.chunks.join("");
        } else {
          this.result = utils.flattenChunks(this.chunks);
        }
      }
      this.chunks = [];
      this.err = status;
      this.msg = this.strm.msg;
    };
    function inflate(input, options) {
      var inflator = new Inflate(options);
      inflator.push(input, true);
      if (inflator.err) {
        throw inflator.msg || msg[inflator.err];
      }
      return inflator.result;
    }
    function inflateRaw(input, options) {
      options = options || {};
      options.raw = true;
      return inflate(input, options);
    }
    exports.Inflate = Inflate;
    exports.inflate = inflate;
    exports.inflateRaw = inflateRaw;
    exports.ungzip = inflate;
  }
});

// node_modules/.pnpm/pako@1.0.11/node_modules/pako/index.js
var require_pako = __commonJS({
  "node_modules/.pnpm/pako@1.0.11/node_modules/pako/index.js"(exports, module2) {
    "use strict";
    var assign = require_common().assign;
    var deflate = require_deflate2();
    var inflate = require_inflate2();
    var constants = require_constants();
    var pako5 = {};
    assign(pako5, deflate, inflate, constants);
    module2.exports = pako5;
  }
});

// src/main.ts
var main_exports = {};
__export(main_exports, {
  default: () => BetterExportPdfPlugin
});
module.exports = __toCommonJS(main_exports);
var import_obsidian5 = require("obsidian");

// src/i18n/index.ts
var import_deepmerge = __toESM(require_cjs());

// src/i18n/en.ts
var en_default = {
  exportCurrentFile: "Export current file to PDF",
  exportCurrentFileWithPrevious: "Export to PDF with previous Settings",
  exportDialog: {
    filenameAsTitle: "Include file name as title",
    pageSize: "Page Size",
    margin: "Margin",
    downscalePercent: "Downscale Percent",
    landscape: "Landscape",
    displayHeader: "Display Header",
    displayFooter: "Display Footer",
    openAfterExport: "Open after export",
    cssSnippets: "CSS snippets"
  },
  settings: {
    showTitle: "Add file name as title",
    displayHeader: "Display headers",
    displayFooter: "Display footer",
    printBackground: "Print background",
    maxLevel: "Max headings level of the outline",
    displayMetadata: "PDF metadata",
    headerTemplate: "Header Template",
    footerTemplate: "Footer Template",
    isTimestamp: "Add timestamp",
    enabledCss: "Enable select css snippets",
    debugMode: "Debug Mode"
  }
};

// src/i18n/zh.ts
var zh_default = {
  exportCurrentFile: "\u5BFC\u51FA\u5F53\u524D\u6587\u4EF6\u4E3APDF",
  exportCurrentFileWithPrevious: "\u4F7F\u7528\u4E0A\u4E00\u6B21\u8BBE\u7F6E\u5BFC\u51FA\u4E3APDF",
  exportDialog: {
    filenameAsTitle: "\u5C06\u7B14\u8BB0\u540D\u4F5C\u4E3A\u6807\u9898",
    pageSize: "\u7EB8\u5F20\u5C3A\u5BF8",
    margin: "\u9875\u8FB9\u8DDD",
    downscalePercent: "\u7F29\u653E",
    landscape: "\u6A2A\u5411\u6253\u5370",
    displayHeader: "\u9875\u7709",
    displayFooter: "\u9875\u811A",
    openAfterExport: "\u5BFC\u51FA\u540E\u6253\u5F00",
    cssSnippets: "CSS\u4EE3\u7801\u7247\u6BB5"
  },
  settings: {
    showTitle: "\u5C06\u7B14\u8BB0\u540D\u4F5C\u4E3A\u6807\u9898",
    displayHeader: "\u663E\u793A\u9875\u7709",
    displayFooter: "\u663E\u793A\u9875\u811A",
    printBackground: "\u6253\u5370\u80CC\u666F",
    maxLevel: "\u6700\u5927\u6807\u9898\u7EA7\u522B",
    displayMetadata: "PDF\u5143\u6570\u636E",
    headerTemplate: "\u9875\u7709\u6A21\u677F",
    footerTemplate: "\u9875\u811A\u6A21\u677F",
    isTimestamp: "\u6587\u4EF6\u540D\u6DFB\u52A0\u65F6\u95F4\u6233",
    enabledCss: "\u542F\u7528CSS\u7247\u6BB5\u9009\u62E9",
    debugMode: "\u8C03\u8BD5\u6A21\u5F0F"
  }
};

// src/i18n/index.ts
var i18n_default = {
  i18n: {
    en: en_default,
    zh: zh_default
  },
  get current() {
    var _a, _b;
    const lang = (_a = window.localStorage.getItem("language")) != null ? _a : "en";
    return (0, import_deepmerge.default)(this.i18n.en, (_b = this.i18n[lang]) != null ? _b : {});
  }
};

// src/modal.ts
var fs2 = __toESM(require("fs/promises"));
var import_obsidian3 = require("obsidian");
var import_path = __toESM(require("path"));

// src/constant.ts
var PageSize = {
  A0: [841, 1189],
  A1: [594, 841],
  A2: [420, 594],
  A3: [297, 420],
  A4: [210, 297],
  A5: [148, 210],
  A6: [105, 148],
  Legal: [216, 356],
  Letter: [216, 279],
  Tabloid: [279, 432],
  Ledger: [432, 279]
};

// src/pdf.ts
var import_electron = __toESM(require("electron"));
var fs = __toESM(require("fs/promises"));

// node_modules/.pnpm/tslib@1.14.1/node_modules/tslib/tslib.es6.js
var extendStatics = function(d, b) {
  extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
    d2.__proto__ = b2;
  } || function(d2, b2) {
    for (var p in b2) if (b2.hasOwnProperty(p)) d2[p] = b2[p];
  };
  return extendStatics(d, b);
};
function __extends(d, b) {
  extendStatics(d, b);
  function __() {
    this.constructor = d;
  }
  d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
  __assign = Object.assign || function __assign2(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
      s = arguments[i];
      for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
    }
    return t;
  };
  return __assign.apply(this, arguments);
};
function __rest(s, e) {
  var t = {};
  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
    t[p] = s[p];
  if (s != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
      if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
        t[p[i]] = s[p[i]];
    }
  return t;
}
function __awaiter(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve) {
      resolve(value);
    });
  }
  return new (P || (P = Promise))(function(resolve, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e) {
        reject(e);
      }
    }
    function step(result) {
      result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
}
function __generator(thisArg, body) {
  var _ = { label: 0, sent: function() {
    if (t[0] & 1) throw t[1];
    return t[1];
  }, trys: [], ops: [] }, f, y, t, g;
  return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
    return this;
  }), g;
  function verb(n) {
    return function(v) {
      return step([n, v]);
    };
  }
  function step(op) {
    if (f) throw new TypeError("Generator is already executing.");
    while (_) try {
      if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
      if (y = 0, t) op = [op[0] & 2, t.value];
      switch (op[0]) {
        case 0:
        case 1:
          t = op;
          break;
        case 4:
          _.label++;
          return { value: op[1], done: false };
        case 5:
          _.label++;
          y = op[1];
          op = [0];
          continue;
        case 7:
          op = _.ops.pop();
          _.trys.pop();
          continue;
        default:
          if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
            _ = 0;
            continue;
          }
          if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
            _.label = op[1];
            break;
          }
          if (op[0] === 6 && _.label < t[1]) {
            _.label = t[1];
            t = op;
            break;
          }
          if (t && _.label < t[2]) {
            _.label = t[2];
            _.ops.push(op);
            break;
          }
          if (t[2]) _.ops.pop();
          _.trys.pop();
          continue;
      }
      op = body.call(thisArg, _);
    } catch (e) {
      op = [6, e];
      y = 0;
    } finally {
      f = t = 0;
    }
    if (op[0] & 5) throw op[1];
    return { value: op[0] ? op[1] : void 0, done: true };
  }
}
function __spreadArrays() {
  for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
  for (var r = Array(s), k = 0, i = 0; i < il; i++)
    for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
      r[k] = a[j];
  return r;
}

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/utils/base64.js
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var lookup = new Uint8Array(256);
for (i = 0; i < chars.length; i++) {
  lookup[chars.charCodeAt(i)] = i;
}
var i;
var encodeToBase64 = function(bytes) {
  var base64 = "";
  var len = bytes.length;
  for (var i = 0; i < len; i += 3) {
    base64 += chars[bytes[i] >> 2];
    base64 += chars[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];
    base64 += chars[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];
    base64 += chars[bytes[i + 2] & 63];
  }
  if (len % 3 === 2) {
    base64 = base64.substring(0, base64.length - 1) + "=";
  } else if (len % 3 === 1) {
    base64 = base64.substring(0, base64.length - 2) + "==";
  }
  return base64;
};
var decodeFromBase64 = function(base64) {
  var bufferLength = base64.length * 0.75;
  var len = base64.length;
  var i;
  var p = 0;
  var encoded1;
  var encoded2;
  var encoded3;
  var encoded4;
  if (base64[base64.length - 1] === "=") {
    bufferLength--;
    if (base64[base64.length - 2] === "=") {
      bufferLength--;
    }
  }
  var bytes = new Uint8Array(bufferLength);
  for (i = 0; i < len; i += 4) {
    encoded1 = lookup[base64.charCodeAt(i)];
    encoded2 = lookup[base64.charCodeAt(i + 1)];
    encoded3 = lookup[base64.charCodeAt(i + 2)];
    encoded4 = lookup[base64.charCodeAt(i + 3)];
    bytes[p++] = encoded1 << 2 | encoded2 >> 4;
    bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
    bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
  }
  return bytes;
};
var DATA_URI_PREFIX_REGEX = /^(data)?:?([\w\/\+]+)?;?(charset=[\w-]+|base64)?.*,/i;
var decodeFromBase64DataUri = function(dataUri) {
  var trimmedUri = dataUri.trim();
  var prefix = trimmedUri.substring(0, 100);
  var res = prefix.match(DATA_URI_PREFIX_REGEX);
  if (!res)
    return decodeFromBase64(trimmedUri);
  var fullMatch = res[0];
  var data = trimmedUri.substring(fullMatch.length);
  return decodeFromBase64(data);
};

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/utils/strings.js
var toCharCode = function(character) {
  return character.charCodeAt(0);
};
var toCodePoint = function(character) {
  return character.codePointAt(0);
};
var toHexStringOfMinLength = function(num, minLength) {
  return padStart(num.toString(16), minLength, "0").toUpperCase();
};
var toHexString = function(num) {
  return toHexStringOfMinLength(num, 2);
};
var charFromCode = function(code) {
  return String.fromCharCode(code);
};
var charFromHexCode = function(hex) {
  return charFromCode(parseInt(hex, 16));
};
var padStart = function(value, length, padChar) {
  var padding = "";
  for (var idx = 0, len = length - value.length; idx < len; idx++) {
    padding += padChar;
  }
  return padding + value;
};
var copyStringIntoBuffer = function(str, buffer, offset) {
  var length = str.length;
  for (var idx = 0; idx < length; idx++) {
    buffer[offset++] = str.charCodeAt(idx);
  }
  return length;
};
var escapeRegExp = function(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
};
var cleanText = function(text) {
  return text.replace(/\t|\u0085|\u2028|\u2029/g, "    ").replace(/[\b\v]/g, "");
};
var escapedNewlineChars = ["\\n", "\\f", "\\r", "\\u000B"];
var isNewlineChar = function(text) {
  return /^[\n\f\r\u000B]$/.test(text);
};
var lineSplit = function(text) {
  return text.split(/[\n\f\r\u000B]/);
};
var mergeLines = function(text) {
  return text.replace(/[\n\f\r\u000B]/g, " ");
};
var charAtIndex = function(text, index) {
  var cuFirst = text.charCodeAt(index);
  var cuSecond;
  var nextIndex = index + 1;
  var length = 1;
  if (
    // Check if it's the start of a surrogate pair.
    cuFirst >= 55296 && cuFirst <= 56319 && // high surrogate
    text.length > nextIndex
  ) {
    cuSecond = text.charCodeAt(nextIndex);
    if (cuSecond >= 56320 && cuSecond <= 57343)
      length = 2;
  }
  return [text.slice(index, index + length), length];
};
var charSplit = function(text) {
  var chars3 = [];
  for (var idx = 0, len = text.length; idx < len; ) {
    var _a = charAtIndex(text, idx), c = _a[0], cLen = _a[1];
    chars3.push(c);
    idx += cLen;
  }
  return chars3;
};
var buildWordBreakRegex = function(wordBreaks) {
  var newlineCharUnion = escapedNewlineChars.join("|");
  var escapedRules = ["$"];
  for (var idx = 0, len = wordBreaks.length; idx < len; idx++) {
    var wordBreak = wordBreaks[idx];
    if (isNewlineChar(wordBreak)) {
      throw new TypeError("`wordBreak` must not include " + newlineCharUnion);
    }
    escapedRules.push(wordBreak === "" ? "." : escapeRegExp(wordBreak));
  }
  var breakRules = escapedRules.join("|");
  return new RegExp("(" + newlineCharUnion + ")|((.*?)(" + breakRules + "))", "gm");
};
var breakTextIntoLines = function(text, wordBreaks, maxWidth, computeWidthOfText) {
  var regex = buildWordBreakRegex(wordBreaks);
  var words = cleanText(text).match(regex);
  var currLine = "";
  var currWidth = 0;
  var lines = [];
  var pushCurrLine = function() {
    if (currLine !== "")
      lines.push(currLine);
    currLine = "";
    currWidth = 0;
  };
  for (var idx = 0, len = words.length; idx < len; idx++) {
    var word = words[idx];
    if (isNewlineChar(word)) {
      pushCurrLine();
    } else {
      var width = computeWidthOfText(word);
      if (currWidth + width > maxWidth)
        pushCurrLine();
      currLine += word;
      currWidth += width;
    }
  }
  pushCurrLine();
  return lines;
};
var dateRegex = /^D:(\d\d\d\d)(\d\d)?(\d\d)?(\d\d)?(\d\d)?(\d\d)?([+\-Z])?(\d\d)?'?(\d\d)?'?$/;
var parseDate = function(dateStr) {
  var match = dateStr.match(dateRegex);
  if (!match)
    return void 0;
  var year = match[1], _a = match[2], month = _a === void 0 ? "01" : _a, _b = match[3], day = _b === void 0 ? "01" : _b, _c = match[4], hours = _c === void 0 ? "00" : _c, _d = match[5], mins = _d === void 0 ? "00" : _d, _e = match[6], secs = _e === void 0 ? "00" : _e, _f = match[7], offsetSign = _f === void 0 ? "Z" : _f, _g = match[8], offsetHours = _g === void 0 ? "00" : _g, _h = match[9], offsetMins = _h === void 0 ? "00" : _h;
  var tzOffset = offsetSign === "Z" ? "Z" : "" + offsetSign + offsetHours + ":" + offsetMins;
  var date = /* @__PURE__ */ new Date(year + "-" + month + "-" + day + "T" + hours + ":" + mins + ":" + secs + tzOffset);
  return date;
};
var findLastMatch = function(value, regex) {
  var _a;
  var position = 0;
  var lastMatch;
  while (position < value.length) {
    var match = value.substring(position).match(regex);
    if (!match)
      return { match: lastMatch, pos: position };
    lastMatch = match;
    position += ((_a = match.index) !== null && _a !== void 0 ? _a : 0) + match[0].length;
  }
  return { match: lastMatch, pos: position };
};

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/utils/arrays.js
var last = function(array) {
  return array[array.length - 1];
};
var typedArrayFor = function(value) {
  if (value instanceof Uint8Array)
    return value;
  var length = value.length;
  var typedArray = new Uint8Array(length);
  for (var idx = 0; idx < length; idx++) {
    typedArray[idx] = value.charCodeAt(idx);
  }
  return typedArray;
};
var mergeIntoTypedArray = function() {
  var arrays = [];
  for (var _i = 0; _i < arguments.length; _i++) {
    arrays[_i] = arguments[_i];
  }
  var arrayCount = arrays.length;
  var typedArrays = [];
  for (var idx = 0; idx < arrayCount; idx++) {
    var element = arrays[idx];
    typedArrays[idx] = element instanceof Uint8Array ? element : typedArrayFor(element);
  }
  var totalSize = 0;
  for (var idx = 0; idx < arrayCount; idx++) {
    totalSize += arrays[idx].length;
  }
  var merged = new Uint8Array(totalSize);
  var offset = 0;
  for (var arrIdx = 0; arrIdx < arrayCount; arrIdx++) {
    var arr = typedArrays[arrIdx];
    for (var byteIdx = 0, arrLen = arr.length; byteIdx < arrLen; byteIdx++) {
      merged[offset++] = arr[byteIdx];
    }
  }
  return merged;
};
var mergeUint8Arrays = function(arrays) {
  var totalSize = 0;
  for (var idx = 0, len = arrays.length; idx < len; idx++) {
    totalSize += arrays[idx].length;
  }
  var mergedBuffer = new Uint8Array(totalSize);
  var offset = 0;
  for (var idx = 0, len = arrays.length; idx < len; idx++) {
    var array = arrays[idx];
    mergedBuffer.set(array, offset);
    offset += array.length;
  }
  return mergedBuffer;
};
var arrayAsString = function(array) {
  var str = "";
  for (var idx = 0, len = array.length; idx < len; idx++) {
    str += charFromCode(array[idx]);
  }
  return str;
};
var byAscendingId = function(a, b) {
  return a.id - b.id;
};
var sortedUniq = function(array, indexer) {
  var uniq = [];
  for (var idx = 0, len = array.length; idx < len; idx++) {
    var curr = array[idx];
    var prev = array[idx - 1];
    if (idx === 0 || indexer(curr) !== indexer(prev)) {
      uniq.push(curr);
    }
  }
  return uniq;
};
var reverseArray = function(array) {
  var arrayLen = array.length;
  for (var idx = 0, len = Math.floor(arrayLen / 2); idx < len; idx++) {
    var leftIdx = idx;
    var rightIdx = arrayLen - idx - 1;
    var temp = array[idx];
    array[leftIdx] = array[rightIdx];
    array[rightIdx] = temp;
  }
  return array;
};
var sum = function(array) {
  var total = 0;
  for (var idx = 0, len = array.length; idx < len; idx++) {
    total += array[idx];
  }
  return total;
};
var range = function(start, end) {
  var arr = new Array(end - start);
  for (var idx = 0, len = arr.length; idx < len; idx++) {
    arr[idx] = start + idx;
  }
  return arr;
};
var pluckIndices = function(arr, indices) {
  var plucked = new Array(indices.length);
  for (var idx = 0, len = indices.length; idx < len; idx++) {
    plucked[idx] = arr[indices[idx]];
  }
  return plucked;
};
var canBeConvertedToUint8Array = function(input) {
  return input instanceof Uint8Array || input instanceof ArrayBuffer || typeof input === "string";
};
var toUint8Array = function(input) {
  if (typeof input === "string") {
    return decodeFromBase64DataUri(input);
  } else if (input instanceof ArrayBuffer) {
    return new Uint8Array(input);
  } else if (input instanceof Uint8Array) {
    return input;
  } else {
    throw new TypeError("`input` must be one of `string | ArrayBuffer | Uint8Array`");
  }
};

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/utils/async.js
var waitForTick = function() {
  return new Promise(function(resolve) {
    setTimeout(function() {
      return resolve();
    }, 0);
  });
};

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/utils/unicode.js
var utf16Encode = function(input, byteOrderMark) {
  if (byteOrderMark === void 0) {
    byteOrderMark = true;
  }
  var encoded = [];
  if (byteOrderMark)
    encoded.push(65279);
  for (var idx = 0, len = input.length; idx < len; ) {
    var codePoint = input.codePointAt(idx);
    if (codePoint < 65536) {
      encoded.push(codePoint);
      idx += 1;
    } else if (codePoint < 1114112) {
      encoded.push(highSurrogate(codePoint), lowSurrogate(codePoint));
      idx += 2;
    } else
      throw new Error("Invalid code point: 0x" + toHexString(codePoint));
  }
  return new Uint16Array(encoded);
};
var isWithinBMP = function(codePoint) {
  return codePoint >= 0 && codePoint <= 65535;
};
var hasSurrogates = function(codePoint) {
  return codePoint >= 65536 && codePoint <= 1114111;
};
var highSurrogate = function(codePoint) {
  return Math.floor((codePoint - 65536) / 1024) + 55296;
};
var lowSurrogate = function(codePoint) {
  return (codePoint - 65536) % 1024 + 56320;
};
var ByteOrder;
(function(ByteOrder2) {
  ByteOrder2["BigEndian"] = "BigEndian";
  ByteOrder2["LittleEndian"] = "LittleEndian";
})(ByteOrder || (ByteOrder = {}));
var REPLACEMENT = "\uFFFD".codePointAt(0);
var utf16Decode = function(input, byteOrderMark) {
  if (byteOrderMark === void 0) {
    byteOrderMark = true;
  }
  if (input.length <= 1)
    return String.fromCodePoint(REPLACEMENT);
  var byteOrder = byteOrderMark ? readBOM(input) : ByteOrder.BigEndian;
  var idx = byteOrderMark ? 2 : 0;
  var codePoints = [];
  while (input.length - idx >= 2) {
    var first = decodeValues(input[idx++], input[idx++], byteOrder);
    if (isHighSurrogate(first)) {
      if (input.length - idx < 2) {
        codePoints.push(REPLACEMENT);
      } else {
        var second = decodeValues(input[idx++], input[idx++], byteOrder);
        if (isLowSurrogate(second)) {
          codePoints.push(first, second);
        } else {
          codePoints.push(REPLACEMENT);
        }
      }
    } else if (isLowSurrogate(first)) {
      idx += 2;
      codePoints.push(REPLACEMENT);
    } else {
      codePoints.push(first);
    }
  }
  if (idx < input.length)
    codePoints.push(REPLACEMENT);
  return String.fromCodePoint.apply(String, codePoints);
};
var isHighSurrogate = function(codePoint) {
  return codePoint >= 55296 && codePoint <= 56319;
};
var isLowSurrogate = function(codePoint) {
  return codePoint >= 56320 && codePoint <= 57343;
};
var decodeValues = function(first, second, byteOrder) {
  if (byteOrder === ByteOrder.LittleEndian)
    return second << 8 | first;
  if (byteOrder === ByteOrder.BigEndian)
    return first << 8 | second;
  throw new Error("Invalid byteOrder: " + byteOrder);
};
var readBOM = function(bytes) {
  return hasUtf16BigEndianBOM(bytes) ? ByteOrder.BigEndian : hasUtf16LittleEndianBOM(bytes) ? ByteOrder.LittleEndian : ByteOrder.BigEndian;
};
var hasUtf16BigEndianBOM = function(bytes) {
  return bytes[0] === 254 && bytes[1] === 255;
};
var hasUtf16LittleEndianBOM = function(bytes) {
  return bytes[0] === 255 && bytes[1] === 254;
};
var hasUtf16BOM = function(bytes) {
  return hasUtf16BigEndianBOM(bytes) || hasUtf16LittleEndianBOM(bytes);
};

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/utils/numbers.js
var numberToString = function(num) {
  var numStr = String(num);
  if (Math.abs(num) < 1) {
    var e = parseInt(num.toString().split("e-")[1]);
    if (e) {
      var negative = num < 0;
      if (negative)
        num *= -1;
      num *= Math.pow(10, e - 1);
      numStr = "0." + new Array(e).join("0") + num.toString().substring(2);
      if (negative)
        numStr = "-" + numStr;
    }
  } else {
    var e = parseInt(num.toString().split("+")[1]);
    if (e > 20) {
      e -= 20;
      num /= Math.pow(10, e);
      numStr = num.toString() + new Array(e + 1).join("0");
    }
  }
  return numStr;
};
var sizeInBytes = function(n) {
  return Math.ceil(n.toString(2).length / 8);
};
var bytesFor = function(n) {
  var bytes = new Uint8Array(sizeInBytes(n));
  for (var i = 1; i <= bytes.length; i++) {
    bytes[i - 1] = n >> (bytes.length - i) * 8;
  }
  return bytes;
};

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/utils/errors.js
var error = function(msg) {
  throw new Error(msg);
};

// node_modules/.pnpm/@pdf-lib+standard-fonts@1.0.0/node_modules/@pdf-lib/standard-fonts/es/utils.js
var import_pako = __toESM(require_pako());
var chars2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var lookup2 = new Uint8Array(256);
for (i = 0; i < chars2.length; i++) {
  lookup2[chars2.charCodeAt(i)] = i;
}
var i;
var decodeFromBase642 = function(base64) {
  var bufferLength = base64.length * 0.75;
  var len = base64.length;
  var i;
  var p = 0;
  var encoded1;
  var encoded2;
  var encoded3;
  var encoded4;
  if (base64[base64.length - 1] === "=") {
    bufferLength--;
    if (base64[base64.length - 2] === "=") {
      bufferLength--;
    }
  }
  var bytes = new Uint8Array(bufferLength);
  for (i = 0; i < len; i += 4) {
    encoded1 = lookup2[base64.charCodeAt(i)];
    encoded2 = lookup2[base64.charCodeAt(i + 1)];
    encoded3 = lookup2[base64.charCodeAt(i + 2)];
    encoded4 = lookup2[base64.charCodeAt(i + 3)];
    bytes[p++] = encoded1 << 2 | encoded2 >> 4;
    bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
    bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
  }
  return bytes;
};
var arrayToString = function(array) {
  var str = "";
  for (var i = 0; i < array.length; i++) {
    str += String.fromCharCode(array[i]);
  }
  return str;
};
var decompressJson = function(compressedJson) {
  return arrayToString(import_pako.default.inflate(decodeFromBase642(compressedJson)));
};
var padStart2 = function(value, length, padChar) {
  var padding = "";
  for (var idx = 0, len = length - value.length; idx < len; idx++) {
    padding += padChar;
  }
  return padding + value;
};

// node_modules/.pnpm/@pdf-lib+standard-fonts@1.0.0/node_modules/@pdf-lib/standard-fonts/es/Courier-Bold.compressed.json
var Courier_Bold_compressed_default = "eJyFWdtyGjkQ/RVqnnar8Bb4lpg3jEnCxgEvGDtxKg9iphm01oyILrZxKv++mrGd3az6KC8UnNa0+nrUGr5lI11VVLtskF198FaU1Dns9w9OOkf7/ePDrJu90bWbiorCgpH2RpLZO9WqaCReqZ8lnReJqKTa/SwL8DXJctPs9Lxs4oSS+bAuVVjXC7/tG/lAxYV0+SYbOOOpm402wojckVlQ8+T4wVFdUDHXlaifrTs91Q/Z4PNeMLu7t3/U6746POm+7vW/dLNlWGuUrOlCW+mkrrPBXr/X+4/gciPz25qszQbhyeyKjG2XZb3ewR+9Xi/sMdVO5k+ebHemcaHzW/57p3/y+qQbPk967We//TxoP191hoVeUWexs44q25nUuTZbbYSj4o9OZ6hUZ97osZ05WTJ3AQ37jMOqQtblIt9QG7lWycKJuhCmeJGGhSOxffccyqPj/W728eXX4cFJNxvavAmRyQbH++HnGf34vdc/etXNFq54d50NXh+2X6/C137v+CnQH8gZmYdQfP6WXX8MCppQTYMlditCBL53/wfTQ65EFeNfvQ6erlQsqX21akJc1rGs0EoJE+NbMnlToZFAVEFkQ3iABW2uGH3CUK1ojUTgMWEbjfaWeUp5G6N5aCwRw5vddkOM98EVqRlPrBJ2E8OPZHSM6prJkrtnVrqNIWbtOjQrg8o7Zq2VDwxId5x3xMe0lpzBuVaa0WGpkkCkmgaON/3qBVODpaHQiIybXz3ZliTi3DO2D2PoNIZGMXQWQ+MYehNDb2PoXQxNYujPGHofQ+cx9CGGpjE0i6GLGPorhuYxtIihyxhaxtBVDF3H0McY+hRDNzG0CqfQLTmeNlZBBvr0+TnIKbmUuTS5Z1jUN6xtw8nBtEjLb7wxDOesmB5j+JfpIIYLmIZiWC6GZAz9HUMMvTItzESL6VqG9rZMKGOI4QaGXpjY+xi6i6H7GGKYdMeQPl9foBBW3GHark9Vo5OqgEd9oe+ZOPOnc3NcqmZgiUuomehYnt1xZ8daaSPZ8wBoyb0Jx3jOBLBtGyvbiRNOLXw0Sy+DpNKAAhpxq/gXYhD6NdMda6bwwyTH0kwhypI70p5wdhR7Gjia3JEhpvfDLCRKI7YcqYXJnxgv/g3vSthEhNNSEKIfCQByUkpurWQaNXjqNtqjSfHp0OdLOwSAG31E7h03uLRMvlbEtDPoq0rkhqvhlSFu40I7kfP9VoRLFrH+G7YLcypCQLkJ1delML5SwjPb6DIMmQxL54L1gyq+YIfMyKNNsQ4zHj8UnoMDdoZwfoMqkJxX7A6Cj3czWzLdqcC+GuGM9tCa4RobSp5J2gTnk0D5CVA0Pp1RAqn7hC0o5J3kqvkTsGyY6gwBHlqmHtqBh2x77UI9QimVS75PljgMAjXDEljn0QNjvMlZIAju/pF0NH95VcFshSgnB3Ug+LhMkwYoVKOAUS+T2kZIG2DVcYInLXDTQkKUYHelH6kuGcEcbPE26aRPNklKOEQpNcCQHPp6k4jc5UYbRtkM7T4HcVsAvADWLtEGnq/M9t2G9e2Aw8xEM1CCQ4QDWq28cnKrmDHTAwcvgYNh1HJSqEKumdvVDlPDFOwjU8UyTpZZ4tTBohzYUSMaRAmdggBNgKLmzVsYGLjXbyujb6lm70CGSmnB1PsWJHuSYhQfupq/ioxBTRngkEaRuQEP3ICIPb/kAq/Axo6ZUEaQFFSStxwa/eDpiARDND4kqhIE+BG1Btp7hjKCjh6UKYt2xk7MkmMJ8PCMlGNy5XiSdvc6wYjYtIp5pSGBRTo9Z45R6Asw4bQ8HgrYhEJmTFsk6pWvyPfJOj4HiXNGFFQJw1hOCVaYgChNUOGcA6tD0DZCMSdDczMBDa5TFVWDqWn5i/yB+BByqARcGhx6ziqXVD4Ii2TqZmnLi8AS3L8dGqRoBIzwkM0LmXNpOAOKTNKbKciPBvg8XdZJ6RDoHEKO5meuGdDzmOiQMTrt0d63SVfAIDBJtgIwwaUvN7ps8l1r7v0I5lKPRUEV+rcqfaHlDvJH4FSdVBVCjk8IiXp87Jv/Ib90s/dk6gshTfPv8Zfv/wDUfBK2";

// node_modules/.pnpm/@pdf-lib+standard-fonts@1.0.0/node_modules/@pdf-lib/standard-fonts/es/Courier-BoldOblique.compressed.json
var Courier_BoldOblique_compressed_default = "eJyFWdtyGjkQ/RVqnnarcAo7vuE3jEnCxgEvGDtxKg9iRgxaa0ZEF9s4lX/fnrGdTVZ9lBcKTmvU96PW8C0bmqqStc9OsqsPwYlSdnaPDvb6naP+3v5+1s3emNpPRCVpwdAEq6TdOTW6mC61+hpksyBo/euCTrOg89MKUSm9/XUNwddSletGcbOcfo+90Cof1KWmdTu7e4S4N+pBFhfK5+vsxNsgu9lwLazIvbRz2Tw7evCyLmQxM5Won809PTUP2cnnnYOj7s7eQa97fNjvHvd2v3SzBS21WtXywjjllakbRb3eT4LLtcpva+lcdkJPZlfSunZZ1uu9ftXr9UjFxHiVP7my2drGh84f+Z+d3f5xv0uf/V77udt+vm4/jzqDwixlZ751XlauM65zYzfGCi+LV53OQOvOrNnHdWbSSXtHKOkZ0apC1eU8X8s2dO0mcy/qQtjiRUoLh2Lz7jmWB4cUto8vv/Zf97vZwOVNhGx2crhHP8/kj987uxShbO6Ld9fZyfF++/WKvu72Dp/i/EF6q3IKxedv2fVH2qAJ1YQscRtBEfje/R8sH3Itqhj/Ggx5utSxpA7VsglxWceywmgtbIxvpM2bio0EoiKRo/AAC9pcMfsJK2stV0gEHhOu2dHdMk/p4GI0p0YTMbzebtaS8Z5cUYbxxGnh1jH8KK2JUVMzWfL3zEq/tpJZu6JuZVB1x6x16oEB5R3nneRjWivO4Nxow+zhZKWASDcNHCv9GgRTg6WV1IiMm8ReriWJOPeM7YMYOo2hYQydxdAoht7E0NsYehdD4xj6K4bex9B5DH2IoUkMTWPoIob+jqFZDM1j6DKGFjF0FUPXMfQxhj7F0E0MLekQupWep40lyUCfPj8HOSVXKlc2DwyLhoa1HZ0cTIu0/MYbw3DOkukxhn+ZDmK4gGkohuViSMXQPzHE0CvTwky0mK5laG/DhDKGGG5g6IWJfYihuxi6jyGGSbcM6fP1BQphyR2m7fpUNXqlC3jUF+aeiTN/OjfHpW4GlriEmoGO5dktd3astLGKPQ/ALnmwdIznTADbtnGqHTnh1MJHswyKJJUBFNCI241/IwahXzHdsWIKnyY5lmYKUZbckfaEs6PY08DR5E5ayfQ+zUKitGLDkRpdASTjxX/hXQqXiHBaCkL0IwFALrVWG6eYRiVP/doENCk+Hfp8aVMAuNFH5MFzg0vL5CstmXYGfVWJ3HI1vLSSU1wYL3K+3wq6ZUnWf8t2YS4LCig3oYa6FDZUWgRGjSlpyGRYOhesH7LiC3bAjDzGFiua8fih8BwcsFOE8woqIrmgWQ2Cj3czWzLdqYFeg3Bmd2pNusVSyTNJG+N8SlB+AhRNSGdUgtR9whYU6k5x1fwJWDZIdYYADy1SD23BQ669dqEekaktF3yfLHAYBGqGBbAuoAdGWMkZEQR3/0g6mr+8qmBUIcrJQR0IPi6TpAEa1Shg1MvkbkO0G2DVUYInHXDTQUJUQLs2j7IuGcEMqHibdDIkmyQlHKCUWmBIDn29SUTucm0ss9kUaZ+BuM0BXgBrF0hB4CuzfbfhQjvgMDPRFJTgAOGAVqugvdpoZswMwMFL4CCNWl4JXagVc7vaYmqYAD0qVSyjZJklTh0syoEdNaJBlNAJCNAYbNS8eaOBgXv9trTmVtbsHcjKUjkw9b4FyR6nGCVQV/NXkRGoKQscMigyN+CBGxCx55dc4BXYyDMTyhCSgk7ylkejHzwdkWCAxodEVYIAP6LWQLqnKCPo6EGZckgzdmKaHEuAh2dSeyZXnidpf28SjIhNq5hXGgpYZNJz5giFvgATTsvjVMCWCpkxbZ6oV74i3yfr+BwkzltRyEpYxnKZYIUxiNIYFc45sJqCthaaORmamwlocJOqqBpMTYvf5A/ERyKHSsCl5NBzVrmk8kGYJ1M3TVteEEtw/3YYkKIhMCJANi9UzqXhDGxkk95MQH4MwGfpsk5KB2DPAeRofuaagn0eEx0yQqc90n2bdAUMAuNkKwATfPpyY8om37Xh3o9gLg1YRFuhf6vSF1ruIH8ETtXJrSjk+IRQqMdHofkf8ks3ey9tfSGUbf49/vL9XxrnGMA=";

// node_modules/.pnpm/@pdf-lib+standard-fonts@1.0.0/node_modules/@pdf-lib/standard-fonts/es/Courier-Oblique.compressed.json
var Courier_Oblique_compressed_default = "eJyFWVtT2zgU/isZP+3OhE5Iy/UtDaHNFhI2IdDS4UGxFUeLbKW6AKHT/77Hhnbb1fnUFw98x9K5fzpyvmZDU1Wy9tlxdnUenChlZ3e//+awc7B32D/Kutmpqf1EVJJeGJpglbQ706VWX4JshEHrX4Wdn4SiUnr7q5jga6nKdaPvXBYqVISMvdAqH9Slpjd3dvuEuFP1KIsL5fN1duxtkN1suBZW5F7auWxWjx69rAtZzEwl6hc73741j9nx553+QXenv9frHr456h729m672YJetVrV8sI45ZWpG0W93k+Cy7XK72rpXHZMK7MraV37WtbrvX7V6/VIxcR4lT87s9naxovOH/mfnd2jw6MuPY967XO3ffbb5+v2edAZFGYpO/Ot87JynXGdG7sxVnhZvOp0Blp3Zs1urjOTTtp7QknbiN4qVF3O87VsQ9huMveiLoQtvkvpxaHYvH+J6d4+Be/j9//e9Pe72cDlTZxsdrzfP+pmJ/LH/zu7ewfdbO6L99e0crf98+rlzybY59JblVM8Pn/Nrj/S+iZeEzLEbQSF4Vv3f7B8zLWoYvxLMOToUseSOlTLJs5lHcsKo7WwMb6RNm/qNRKIikSOogMsaBPG7CesrLVcIRFYJlyzo7tjVungYjSnNhMxvN5u1pLxnlxRhvHEaeHWMfwkrYlRUzNZ8g/Mm35tJfPuipqWQdU9865Tjwwo7znvJB/TWnEG50YbZg8nKwVEuuniWOmXIJgaLK2kPmTcJBJzLVPEuWdsH8TQ2xgaxtBJDI1i6DSG3sXQ+xgax9BfMfQhhs5i6DyGJjE0jaGLGPo7hmYxNI+hyxhaxNBVDF3H0McY+hRDNzG0pJPoTnqeNpYkA336sg5ySq5UrmweGBYNDWk7OjiYFmn5jTeG4Zwl02MM/zIdxHAB01AMy8WQiqF/YoihV6aFmWgxXcvQ3oYJZQwx3MDQCxP7EEP3MfQQQwyTbhnS5+sLFMKSO0zb91PV6JUu4FFfmAcmzvzp3ByXuplX4hJqpjqWZ7fc2bHSxir2PAC75MHSMZ4zAWzbxql27oRTCx/NMiiSVAZQQCNuN/6NGIR+xXTHiil8GuRYmilEWXJH2jPOjmLPA0eTO2kl0/s0C4nSig1HanQJkIwX/4V3KVwiwmkpCNGPBAC51FptnGIalTz1axPQpPh86POlTQHgRh+RB88NLi2Tr7Rk2hn0VSVyy9Xw0kpOcWG8yPl+K+iyJVn/LduFOV3GaOBmuDvUpbCh0iIwakxJQybD0rlg/ZAVX7ADZuQxtljRjMcPhWfggJ0inFdQEckFzWoQfLyb2ZLpTg30GoQzu1Nr0lWWSp5J2hjnU4LyE6BoQjqjEqTuE7agUPeKq+ZPwLJBqjMEWLRILdqCRa69dqEekaktF3yfLHAYBGqGBbAuoAUjrOSECIK7fyQdzb9/r2BUIcrJQR0IPi6TpAEa1Shg1MvkbkO0G2DVUYInHXDTQUJUQLs2T7IuGcEMqHiXdDIkmyQlHKCUWmBIDn29SUTucm0ss9kUaZ+BuM0BXgBrF0hB4Cuz/bbhQjvgMDPRFJTgAOGAVqugvdpoZswMwMFL4CCNWl4JXagVc7vaYmqYAD0qVSyjZJklTh0syoEdNaJBlNAJCNAYbNR8eaOBgfv8trTmTtbsHcjKUjkw9b4DyR6nGCVQV/NXkRGoKQscMigyN2DBDYjYy0cu8Als5JkJZQhJQSd5y6PRD56OSDBA40OiKkGAn1BrIN1TlBF09KBMOaQZOzFNjiXAwxOpPZMrz5O0fzAJRsSmVcwnDQUsMuk5c4RCX4AJp+VxKmBLhcyYNk/UK1+RH5J1fAYS560oZCUsY7lMsMIYRGmMCucMWE1BWwvNnAzNzQQ0uElVVA2mpsVv8gfiI5FDJeBScuglq1xS+SDMk6mbpi0viCW4XzsMSNEQGBEgmxcq59JwAjaySW8mID8G4LN0WSelA7DnAHI0P3NNwT5PiQ4ZodMe6b5LugIGgXGyFYAJPn25MWWT79pw30cwlwYsoq3Qr1XpCy13kD8Bp+rkVhRyfEIo1OOj0PwOedvNPkhbXwhlm1+Pb7/9C/NFF2U=";

// node_modules/.pnpm/@pdf-lib+standard-fonts@1.0.0/node_modules/@pdf-lib/standard-fonts/es/Courier.compressed.json
var Courier_compressed_default = "eJyFWdtSGzkQ/RXXPO1WmZSBEAJvjnESb8AmGENCKg+ypj3Wohk5ugAmlX9fzUCyW6s+ysuUfVqXvh61Zr4XI1PX1PjiuLg6C05U1Ns/Ojx42TsYHB4eFf3irWn8VNQUB4xMsIpsCwatU1DUSm8T+JpUtW7XP6NShToiEy+0ksOm0nHkIP53b9UDlefKy3Vx7G2gfjFaCyukJzundu74wVNTUnlhatE8a/XmjXkojr/s7O33d/YOBv3D3YP+68HB136xiEOtVg2dG6e8Mk1xvLM7GPxHcLlW8rYh54rjOLO4Iuu6YcVgsP9iMBjELabGK/lkymZrWxt6f8g/e7tHr4/68Xk06J673XOve+53z8PesDRL6s23zlPtepNGGrsxVngqX/R6Q617F+1qrndBjuxdRONu4ziqVE01l2vqHNgtMveiKYUtf0rjwJHYvH/26MGrvX7x6ee/l3uv+sXQydZPtjh+tXfUL07o1/+d3YPDfjH35fvrOHO3+3n1/LN19hl5q2T0x5fvxfWnOL/11zQq4jYiuuFH/38wPUgt6hT/Fkw0dKlTSRPqZevnqkllpdFa2BTfkJVtdiYCUUeRi94BGnQBY9YTlhpNKyQC04RrV3S3zCwdXIrKWFQihdfbzZoY66MpyjCWOC3cOoUfyZoUNQ0TJX/PjPRrS8zYVSxZBlV3zFinHhiQ7jjriPdpoziFpdGGWcNRrYBIt1WcbvotCCYHK0uxDhkzvwVyHVOksWd0H6bQmxQapdBJCo1T6G0KvUuh9yk0SaG/UuhDCp2m0FkKTVNolkLnKfQxhS5SaJ5Clym0SKGrFLpOoU8p9DmFblJoGU+iW/I8bSyjDNTp8zzIKVIpqawMDIuGlrRdPDiYEun4jVeG4ZwlU2MM/zIVxHABU1AMy6WQSqG/U4ihV6aEGW8xVcvQ3oZxZQox3MDQC+P7kEJ3KXSfQgyTbhnS5/MLJMKSO0y78bls9EqX8KgvzT3jZ/50bo9L3fYraQq1XR3Ls1vu7FhpYxV7HoBVZLDxGJeMA7uycarrOmHXwnuzCipKagMooBV3C/9GDFy/YqpjxSR+bORYmilFVXFH2hPOtmJPDUcbO7LE1H7shURlxYYjtdj6E2PFv+5dCpfxcF4KXPQrAEBOWquNU0yhRkv92gTUKT4d+nxqRwdwrY+QwXONS8fkK01MOYO6qoW0XA4vLXEbl8YLyddbGa9axNpv2SqU8SoWG26Gu0NTCRtqLQKzjalik8mwtBSsHVTzCTtkWh5jy1Xs8fim8BQcsDOE8xvUkeSCZncQvL/b3pKpTg32NQhnVo+lGa+yMeWZoE1wPAmknwBJE/IRJRC6z1iDUt0pLps/A82GucoQYNIiN2kLJrnu2oVqhHJLLvg6WWA3CFQMC6BdQBPGeJOTSBDc/SNrqPz5voLZClGOBHkgeL9MswpolKOAUS+zq43QaoBVxxmedMBMBwlRgd21eaSmYgQXYIt3WSNDtkhywiEKqQWKSGjrTcZzl2tjmcVmaPcL4Lc5wEug7QJtEPjM7N5tuNA1OExPNAMpOEQ4oNU6aK82mmkzAzDwEhgYWy2vhC7VirldbTE1TME+Kpcs42yaZU4dLJJAjwbRIAroFDhoAhZq37zFhoF7/ba05pYa9g5kqVIOdL3vQLAnOUYJsar5q8gY5JQFBhnkmRsw4QZ47PklF3gFNvZMhzKCpKCzvOVR6wdPRyQYovYhk5XAwY+oNNDeMxQRdPSgSDm0MzZilm1LgIUnpD0TK8+TtL83GUbEqtXMKw0FNDL5PnOMXF+CDqfj8ZjANiYyo9o8k698Rn7I5vEpCJy3oqRaWEZzyrDCBHhpghLnFGgdnbYWmjkZ2psJKHCTy6gGdE2L38QP+IeQQRXg0mjQc1S5oPJOmGdDN8trXkaW4L52GBCiEVAiQDYvleTCcAIWsllrpiA+BuAX+bTOSodgzSHkaL7nmoF1HjMVMkanPdr7NmsKaAQm2VIAKvj85cZUbbwbw70fwVwasCguhb5W5S+03EH+CIxqsktFl+MTQqEaH4f2O+TXfvGBbHMulG2/Hn/98Q/b2xEO";

// node_modules/.pnpm/@pdf-lib+standard-fonts@1.0.0/node_modules/@pdf-lib/standard-fonts/es/Helvetica-Bold.compressed.json
var Helvetica_Bold_compressed_default = " ";

// node_modules/.pnpm/@pdf-lib+standard-fonts@1.0.0/node_modules/@pdf-lib/standard-fonts/es/Helvetica-BoldOblique.compressed.json
var Helvetica_BoldOblique_compressed_default = " ";

// node_modules/.pnpm/@pdf-lib+standard-fonts@1.0.0/node_modules/@pdf-lib/standard-fonts/es/Helvetica-Oblique.compressed.json
var Helvetica_Oblique_compressed_default = " ";

// node_modules/.pnpm/@pdf-lib+standard-fonts@1.0.0/node_modules/@pdf-lib/standard-fonts/es/Helvetica.compressed.json
var Helvetica_compressed_default = " ";

// node_modules/.pnpm/@pdf-lib+standard-fonts@1.0.0/node_modules/@pdf-lib/standard-fonts/es/Times-Bold.compressed.json
var Times_Bold_compressed_default = " ";

// node_modules/.pnpm/@pdf-lib+standard-fonts@1.0.0/node_modules/@pdf-lib/standard-fonts/es/Times-BoldItalic.compressed.json
var Times_BoldItalic_compressed_default = " ";

// node_modules/.pnpm/@pdf-lib+standard-fonts@1.0.0/node_modules/@pdf-lib/standard-fonts/es/Times-Italic.compressed.json
var Times_Italic_compressed_default = " ";

// node_modules/.pnpm/@pdf-lib+standard-fonts@1.0.0/node_modules/@pdf-lib/standard-fonts/es/Times-Roman.compressed.json
var Times_Roman_compressed_default = " ";

// node_modules/.pnpm/@pdf-lib+standard-fonts@1.0.0/node_modules/@pdf-lib/standard-fonts/es/Symbol.compressed.json
var Symbol_compressed_default = "eJx9WFlv2zgQ/iuGnnYBt5DkS85bmk13g27SoEkPbNEHWqIlIhSpklSuov99R7JIkSLtFyGZjxzN8c0h/4oueF1jpqKz6Mt1K1GJZ4s4S+PZYrvdbqJ59J4zdYNqDAfuXuodp52spdSToZrQl6n0KyZl1Sm/xgVpa5BcKURJfs5KCgdj+F++J8+4uCUqr6IzJVo8jy4qJFCusLjD3d27BucE0cGYd+/4c3T2/U2SxfM36XYxT+JtDI8k/jGPPrMCC0oYvuWSKMJZdPYmiWMLuK9I/sCwlNHZCuRfsJD9sSiOk7dxnMFbbrgieefGBW9eROfA7I/8z1myzVbz7rnpn9vuCW/unpvZecF3eHb3IhWu5eyK5Vw0XCCFi7ezc0pnvRo5E1hi8QhCeM0lHCoIK+/yCvdR67zrfd2THPA7VfzzNTrbpv2fX+BPeH8fm2usBMnBg++/oq/forO08+QGNMgGgeG/5wfxYrE4iPFzTlFt5JtkkLeMPIL/EFoNreJBE2vrXReako3YcqvVEXCTKWJdzPS7Gizyjk/mZZvsAKC66d7FCgMtF4NC2eaVqpDyLW+QwIzi/TGoD6tvPQL7BJEPNVKVb39DW2mkJnY5FALyD9eEhU6DL4SPrqTaS0mRrHyDXrHgvpQz7AvVU+CkqgQOnN3zVgSkkFVfKslzQIgfMfPFOBxWRiyDjcs5p5wFIoFr4kImprQrP59WP1ubiVpcCgxlNLq5XC4PwM8Wy77EvSs5ZyU0EpuFaXqAzmlTjVlerzcH8TuskH/4oiLj0WQQ/oWpdXadJAfxZSOJ7exmPfD01lYSD8K/kU0288JLS7Mh+hW337dINCPA5MRX8QE1jXU8Wx/E/6J6V4zyLBtCdd36Km4Cso+QTOG4N6T5dvRusxxsu6/scK5Wgw2fKovZ20HxHSnrQDjv0WjEejvw7/MkxmMD6ZQkvnEfa1xayperg/ibZfN2kN1K4lvxHw4lZAfD6QErpy1lOt2QF4H3XATa8HDP7VnrVWY6SoNZQfKWokBRt90Ak7mt2GACwTVE8bNPE+Tw3VTIzkmQqRuLqsvtUGaFw3cTcjzJxSod3tjYSnQgS4fvpgyc8KaDZuLwXR8FtYlv8YPD9rHBuGxfbQYG1q1vL2v9+3zC9nF0EF+BqoLBFBbbjRfSYbsJprLYboxtpx1Fj23esXoMhqlx7rB9uR2OPxP/aCMDmX61/Vhm8cha7HA91bzbWUR1z0/m8tLUKSyJ1qWNHqeXrTUf16lb76Or6XIzTmWFA4mHyeLOkUS3+H23UpJQPAnbE0bUS2CSUi6IdWM13Mhpu/OlBUE1t/YbA1QYCeWLYVsrRh+SeDm0RCQEf9pxa3Xpds4RcpJhqNVDbXPkzqTpOJcK/mT1VO17gUtn57C3J3cpMlUucW77Px3hRwZ83VJFGvriJ6YRHJboLmnWPUNXWAC7FbQg+/0IrjUL4RMFBxhYkEdSBLxiXB0xD8TkEZorywPXoP0I/jxhXGzWKEoJUFgeiTvs3srq2eO9Hq2Aeq92S9eDIgeYwIeawKoVY+KyVOumuBmpY0r+CgrgQVn7ohl9n6aIoc4TJjB0lEDWvmaGa05ETrGfPRd3lm1jI64b9SKtBJlbhAFTgEhuqWoUvlhCFdwRBW613cNWqnGYyDAdj+OQfdnugpBWHUa14jAKbbN2tlDrfR6mXUT9p7F3peyGvHNBb0UCl933GHgmyN6Hc/0R6+KZxiG7Ba6ReJjg6RiAos0DpTRsHWNz1s284Mr58DI+UF52N8B7vyIGzP4+nGJcWLXiNMtiR0/0S0BPtExAj3ZNwE42zh11e6duTZS/YlZaK6DebfrkOsb4aURMnsqiA+viHpPowDrwsoX1y6moRTZ20cMXtmpOgFYf8sGd8kFrRw4ptuCQagu2lJvwmpXEUu2DNSlOoEf12vY4aXOZkG6WY8OC4hzrwHRcjVhWepjd4KdYKK7jrx5H89WjRxPWoycydlS3jZ/I2VS/G9yp9gB6PG1T1aY4YAp3LfPHPPqABbtFRHS/jf34/T82FAfb";

// node_modules/.pnpm/@pdf-lib+standard-fonts@1.0.0/node_modules/@pdf-lib/standard-fonts/es/ZapfDingbats.compressed.json
var ZapfDingbats_compressed_default = "eJxtmNtu20YQhl+F4FULyMGeD7pz3AY1ChtG7NpFA18w1NomIlECSRcxgrx7SVk7+wOdG8H5OJydf2Z2d5gf9cV+t0v9VK/r+6vXsXlOlbHe28paq229qj/t++m62aXZ4J/m8PRb1z9/baZxefK63Z6eXN5dVMvTCh83u277xr/6kLrnl2XNq7TpXnczuZyabdee98/b2VzM/x4/dd/T5qab2pd6PQ2vaVVfvDRD005puE3Lu7eH1HbN9hTjx4/77/X6y5lcnUmjVzHIVVDicVX/1W/SsO36dLMfu6nb9/X6TAoBD+5euvZbn8axXtuZ36dhPJrVQqgPQoh5hev91LWLkIv94W1Ygq9+aX+tZAx2tfz64284/sblN/rqfLP/mqrbt3FKu7G67Nv9cNgPzZQ2H6rz7bb6vLgZq89pTMO/M/xfEqturJpqSM/d7GJIm2oamk3aNcO3av80O5xh3yyKmm1193ZIT02bqovTKjP+MAf++7zsZvZ3276kYyWWXB0z99S18/PbafPHQ71W4fjn/fxnFO+ZvkrT0LVzTr78qB/+nk38bHM9exgP8zr1z9U7jt6840YW5uSJKcZOCaBBnKgm5mU8MVNYyMwWFvO7Ukagkmgg6sDWQ5yFFqjzUrLEaQ3BEmiwNsMSaZS0vgWfOkPHWQowNeTUc0kumnxZvsgPxlGai6VTGUqAVCTQ6QkWnc77DKEiLktSUBJKqHIQZ86d8gCpHYoiEzMsb1ubYy8vW50DChB5ZhGqrijD0EqUIeiaEHIfCg5Kpuu0ApiToaGPSY0uaQsyr65L2oKi1yFt1PLaQ3lzfXTgXodGoJYzglndSLDMPg1sTPJpQJHJigw0QrGERqD9YhyTOgONQDUyuF1zaxuokc/BW2ztXCMrGZ9WMW1oQZHIXWNBkSCfRZEL5BMUiZw6CzVSFCfUSGZFNjIldoKDkonTKQiJIGzWmFd3BizJJ9SINoLDriOfUCOZS+zg+KGD1qGiLNMLxtJD1/ns00ON6EzyUCM6vbxhoBKaqbG3DFQCNiL1iHccBPV0DHhQH/JW8EW90dkyFKGywCJU0WkVSvSGeiSUODWFFD0HYdPQVoiRgfPMA+/nnRgiAyNYSjpWNQcNSMrtFCUH4ZIRpSCWocFCSuhCEY6hoUClc0WC52BJlCYYLQdhN+hygRRRlo5BKRRLS6oihSqh+ZzzRGG1Mo4Iz1LoP0qsxDGFzk0JE42ji0jCPejomJKCuwil4m5CiRMEUMVSzVLDUstSx1Juc0oVWMpqY295qVltmtWmWW2a1aZZbZrVplltmtWmWW2G1WZYbYbVZlhthtVmWG2G1WZYbYbVZlhtltVmWW2W1WZZbZbVZlltltVmWW2W1QYjQCh7E2aAQHeGhCFgPoNoy8KNb2wxBhmGKBxoUZXlLGsLI6AsftEDHV0wIURVbANLcTKlGGBIKPOAxCmhePCKUwFzAmpDFRQvjA9R06Hq8TONvshgKDCuRAZTXigUxjxNFfKRo3CLhnIJBMFRvMZpqpNBMlQJzGT5WFQMVQI/AikPMIhEU1aDjqJvQwmjSHB05cC9jbYwc5UtAHNLhDw41ha+lEqF4JaH3gmB61SYcqInxTDmQK8v08vjqv4zDf1N0w3Lf4A8/vwPpfK11w==";

// node_modules/.pnpm/@pdf-lib+standard-fonts@1.0.0/node_modules/@pdf-lib/standard-fonts/es/Font.js
var compressedJsonForFontName = {
  "Courier": Courier_compressed_default,
  "Courier-Bold": Courier_Bold_compressed_default,
  "Courier-Oblique": Courier_Oblique_compressed_default,
  "Courier-BoldOblique": Courier_BoldOblique_compressed_default,
  "Helvetica": Helvetica_compressed_default,
  "Helvetica-Bold": Helvetica_Bold_compressed_default,
  "Helvetica-Oblique": Helvetica_Oblique_compressed_default,
  "Helvetica-BoldOblique": Helvetica_BoldOblique_compressed_default,
  "Times-Roman": Times_Roman_compressed_default,
  "Times-Bold": Times_Bold_compressed_default,
  "Times-Italic": Times_Italic_compressed_default,
  "Times-BoldItalic": Times_BoldItalic_compressed_default,
  "Symbol": Symbol_compressed_default,
  "ZapfDingbats": ZapfDingbats_compressed_default
};
var FontNames;
(function(FontNames2) {
  FontNames2["Courier"] = "Courier";
  FontNames2["CourierBold"] = "Courier-Bold";
  FontNames2["CourierOblique"] = "Courier-Oblique";
  FontNames2["CourierBoldOblique"] = "Courier-BoldOblique";
  FontNames2["Helvetica"] = "Helvetica";
  FontNames2["HelveticaBold"] = "Helvetica-Bold";
  FontNames2["HelveticaOblique"] = "Helvetica-Oblique";
  FontNames2["HelveticaBoldOblique"] = "Helvetica-BoldOblique";
  FontNames2["TimesRoman"] = "Times-Roman";
  FontNames2["TimesRomanBold"] = "Times-Bold";
  FontNames2["TimesRomanItalic"] = "Times-Italic";
  FontNames2["TimesRomanBoldItalic"] = "Times-BoldItalic";
  FontNames2["Symbol"] = "Symbol";
  FontNames2["ZapfDingbats"] = "ZapfDingbats";
})(FontNames || (FontNames = {}));
var fontCache = {};
var Font = (
  /** @class */
  function() {
    function Font2() {
      var _this = this;
      this.getWidthOfGlyph = function(glyphName) {
        return _this.CharWidths[glyphName];
      };
      this.getXAxisKerningForPair = function(leftGlyphName, rightGlyphName) {
        return (_this.KernPairXAmounts[leftGlyphName] || {})[rightGlyphName];
      };
    }
    Font2.load = function(fontName) {
      var cachedFont = fontCache[fontName];
      if (cachedFont)
        return cachedFont;
      var json = decompressJson(compressedJsonForFontName[fontName]);
      var font = Object.assign(new Font2(), JSON.parse(json));
      font.CharWidths = font.CharMetrics.reduce(function(acc, metric) {
        acc[metric.N] = metric.WX;
        return acc;
      }, {});
      font.KernPairXAmounts = font.KernPairs.reduce(function(acc, _a) {
        var name1 = _a[0], name2 = _a[1], width = _a[2];
        if (!acc[name1])
          acc[name1] = {};
        acc[name1][name2] = width;
        return acc;
      }, {});
      fontCache[fontName] = font;
      return font;
    };
    return Font2;
  }()
);

// node_modules/.pnpm/@pdf-lib+standard-fonts@1.0.0/node_modules/@pdf-lib/standard-fonts/es/all-encodings.compressed.json
var all_encodings_compressed_default = " ";

// node_modules/.pnpm/@pdf-lib+standard-fonts@1.0.0/node_modules/@pdf-lib/standard-fonts/es/Encoding.js
var decompressedEncodings = decompressJson(all_encodings_compressed_default);
var allUnicodeMappings = JSON.parse(decompressedEncodings);
var Encoding = (
  /** @class */
  /* @__PURE__ */ function() {
    function Encoding2(name, unicodeMappings) {
      var _this = this;
      this.canEncodeUnicodeCodePoint = function(codePoint) {
        return codePoint in _this.unicodeMappings;
      };
      this.encodeUnicodeCodePoint = function(codePoint) {
        var mapped = _this.unicodeMappings[codePoint];
        if (!mapped) {
          var str = String.fromCharCode(codePoint);
          var hexCode = "0x" + padStart2(codePoint.toString(16), 4, "0");
          var msg = _this.name + ' cannot encode "' + str + '" (' + hexCode + ")";
          throw new Error(msg);
        }
        return { code: mapped[0], name: mapped[1] };
      };
      this.name = name;
      this.supportedCodePoints = Object.keys(unicodeMappings).map(Number).sort(function(a, b) {
        return a - b;
      });
      this.unicodeMappings = unicodeMappings;
    }
    return Encoding2;
  }()
);
var Encodings = {
  Symbol: new Encoding("Symbol", allUnicodeMappings.symbol),
  ZapfDingbats: new Encoding("ZapfDingbats", allUnicodeMappings.zapfdingbats),
  WinAnsi: new Encoding("WinAnsi", allUnicodeMappings.win1252)
};

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/utils/objects.js
var values = function(obj) {
  return Object.keys(obj).map(function(k) {
    return obj[k];
  });
};
var StandardFontValues = values(FontNames);
var isStandardFont = function(input) {
  return StandardFontValues.includes(input);
};
var rectanglesAreEqual = function(a, b) {
  return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;
};

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/utils/validators.js
var backtick = function(val) {
  return "`" + val + "`";
};
var singleQuote = function(val) {
  return "'" + val + "'";
};
var formatValue = function(value) {
  var type = typeof value;
  if (type === "string")
    return singleQuote(value);
  else if (type === "undefined")
    return backtick(value);
  else
    return value;
};
var createValueErrorMsg = function(value, valueName, values2) {
  var allowedValues = new Array(values2.length);
  for (var idx = 0, len = values2.length; idx < len; idx++) {
    var v = values2[idx];
    allowedValues[idx] = formatValue(v);
  }
  var joinedValues = allowedValues.join(" or ");
  return backtick(valueName) + " must be one of " + joinedValues + ", but was actually " + formatValue(value);
};
var assertIsOneOf = function(value, valueName, allowedValues) {
  if (!Array.isArray(allowedValues)) {
    allowedValues = values(allowedValues);
  }
  for (var idx = 0, len = allowedValues.length; idx < len; idx++) {
    if (value === allowedValues[idx])
      return;
  }
  throw new TypeError(createValueErrorMsg(value, valueName, allowedValues));
};
var assertIsOneOfOrUndefined = function(value, valueName, allowedValues) {
  if (!Array.isArray(allowedValues)) {
    allowedValues = values(allowedValues);
  }
  assertIsOneOf(value, valueName, allowedValues.concat(void 0));
};
var assertIsSubset = function(values2, valueName, allowedValues) {
  if (!Array.isArray(allowedValues)) {
    allowedValues = values(allowedValues);
  }
  for (var idx = 0, len = values2.length; idx < len; idx++) {
    assertIsOneOf(values2[idx], valueName, allowedValues);
  }
};
var getType = function(val) {
  if (val === null)
    return "null";
  if (val === void 0)
    return "undefined";
  if (typeof val === "string")
    return "string";
  if (isNaN(val))
    return "NaN";
  if (typeof val === "number")
    return "number";
  if (typeof val === "boolean")
    return "boolean";
  if (typeof val === "symbol")
    return "symbol";
  if (typeof val === "bigint")
    return "bigint";
  if (val.constructor && val.constructor.name)
    return val.constructor.name;
  if (val.name)
    return val.name;
  if (val.constructor)
    return String(val.constructor);
  return String(val);
};
var isType = function(value, type) {
  if (type === "null")
    return value === null;
  if (type === "undefined")
    return value === void 0;
  if (type === "string")
    return typeof value === "string";
  if (type === "number")
    return typeof value === "number" && !isNaN(value);
  if (type === "boolean")
    return typeof value === "boolean";
  if (type === "symbol")
    return typeof value === "symbol";
  if (type === "bigint")
    return typeof value === "bigint";
  if (type === Date)
    return value instanceof Date;
  if (type === Array)
    return value instanceof Array;
  if (type === Uint8Array)
    return value instanceof Uint8Array;
  if (type === ArrayBuffer)
    return value instanceof ArrayBuffer;
  if (type === Function)
    return value instanceof Function;
  return value instanceof type[0];
};
var createTypeErrorMsg = function(value, valueName, types) {
  var allowedTypes = new Array(types.length);
  for (var idx = 0, len = types.length; idx < len; idx++) {
    var type = types[idx];
    if (type === "null")
      allowedTypes[idx] = backtick("null");
    if (type === "undefined")
      allowedTypes[idx] = backtick("undefined");
    if (type === "string")
      allowedTypes[idx] = backtick("string");
    else if (type === "number")
      allowedTypes[idx] = backtick("number");
    else if (type === "boolean")
      allowedTypes[idx] = backtick("boolean");
    else if (type === "symbol")
      allowedTypes[idx] = backtick("symbol");
    else if (type === "bigint")
      allowedTypes[idx] = backtick("bigint");
    else if (type === Array)
      allowedTypes[idx] = backtick("Array");
    else if (type === Uint8Array)
      allowedTypes[idx] = backtick("Uint8Array");
    else if (type === ArrayBuffer)
      allowedTypes[idx] = backtick("ArrayBuffer");
    else
      allowedTypes[idx] = backtick(type[1]);
  }
  var joinedTypes = allowedTypes.join(" or ");
  return backtick(valueName) + " must be of type " + joinedTypes + ", but was actually of type " + backtick(getType(value));
};
var assertIs = function(value, valueName, types) {
  for (var idx = 0, len = types.length; idx < len; idx++) {
    if (isType(value, types[idx]))
      return;
  }
  throw new TypeError(createTypeErrorMsg(value, valueName, types));
};
var assertOrUndefined = function(value, valueName, types) {
  assertIs(value, valueName, types.concat("undefined"));
};
var assertEachIs = function(values2, valueName, types) {
  for (var idx = 0, len = values2.length; idx < len; idx++) {
    assertIs(values2[idx], valueName, types);
  }
};
var assertRange = function(value, valueName, min, max) {
  assertIs(value, valueName, ["number"]);
  assertIs(min, "min", ["number"]);
  assertIs(max, "max", ["number"]);
  max = Math.max(min, max);
  if (value < min || value > max) {
    throw new Error(backtick(valueName) + " must be at least " + min + " and at most " + max + ", but was actually " + value);
  }
};
var assertRangeOrUndefined = function(value, valueName, min, max) {
  assertIs(value, valueName, ["number", "undefined"]);
  if (typeof value === "number")
    assertRange(value, valueName, min, max);
};
var assertMultiple = function(value, valueName, multiplier) {
  assertIs(value, valueName, ["number"]);
  if (value % multiplier !== 0) {
    throw new Error(backtick(valueName) + " must be a multiple of " + multiplier + ", but was actually " + value);
  }
};
var assertInteger = function(value, valueName) {
  if (!Number.isInteger(value)) {
    throw new Error(backtick(valueName) + " must be an integer, but was actually " + value);
  }
};
var assertPositive = function(value, valueName) {
  if (![1, 0].includes(Math.sign(value))) {
    throw new Error(backtick(valueName) + " must be a positive number or 0, but was actually " + value);
  }
};

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/utils/pdfDocEncoding.js
var pdfDocEncodingToUnicode = new Uint16Array(256);
for (idx = 0; idx < 256; idx++) {
  pdfDocEncodingToUnicode[idx] = idx;
}
var idx;
pdfDocEncodingToUnicode[22] = toCharCode("");
pdfDocEncodingToUnicode[24] = toCharCode("\u02D8");
pdfDocEncodingToUnicode[25] = toCharCode("\u02C7");
pdfDocEncodingToUnicode[26] = toCharCode("\u02C6");
pdfDocEncodingToUnicode[27] = toCharCode("\u02D9");
pdfDocEncodingToUnicode[28] = toCharCode("\u02DD");
pdfDocEncodingToUnicode[29] = toCharCode("\u02DB");
pdfDocEncodingToUnicode[30] = toCharCode("\u02DA");
pdfDocEncodingToUnicode[31] = toCharCode("\u02DC");
pdfDocEncodingToUnicode[127] = toCharCode("\uFFFD");
pdfDocEncodingToUnicode[128] = toCharCode("\u2022");
pdfDocEncodingToUnicode[129] = toCharCode("\u2020");
pdfDocEncodingToUnicode[130] = toCharCode("\u2021");
pdfDocEncodingToUnicode[131] = toCharCode("\u2026");
pdfDocEncodingToUnicode[132] = toCharCode("\u2014");
pdfDocEncodingToUnicode[133] = toCharCode("\u2013");
pdfDocEncodingToUnicode[134] = toCharCode("\u0192");
pdfDocEncodingToUnicode[135] = toCharCode("\u2044");
pdfDocEncodingToUnicode[136] = toCharCode("\u2039");
pdfDocEncodingToUnicode[137] = toCharCode("\u203A");
pdfDocEncodingToUnicode[138] = toCharCode("\u2212");
pdfDocEncodingToUnicode[139] = toCharCode("\u2030");
pdfDocEncodingToUnicode[140] = toCharCode("\u201E");
pdfDocEncodingToUnicode[141] = toCharCode("\u201C");
pdfDocEncodingToUnicode[142] = toCharCode("\u201D");
pdfDocEncodingToUnicode[143] = toCharCode("\u2018");
pdfDocEncodingToUnicode[144] = toCharCode("\u2019");
pdfDocEncodingToUnicode[145] = toCharCode("\u201A");
pdfDocEncodingToUnicode[146] = toCharCode("\u2122");
pdfDocEncodingToUnicode[147] = toCharCode("\uFB01");
pdfDocEncodingToUnicode[148] = toCharCode("\uFB02");
pdfDocEncodingToUnicode[149] = toCharCode("\u0141");
pdfDocEncodingToUnicode[150] = toCharCode("\u0152");
pdfDocEncodingToUnicode[151] = toCharCode("\u0160");
pdfDocEncodingToUnicode[152] = toCharCode("\u0178");
pdfDocEncodingToUnicode[153] = toCharCode("\u017D");
pdfDocEncodingToUnicode[154] = toCharCode("\u0131");
pdfDocEncodingToUnicode[155] = toCharCode("\u0142");
pdfDocEncodingToUnicode[156] = toCharCode("\u0153");
pdfDocEncodingToUnicode[157] = toCharCode("\u0161");
pdfDocEncodingToUnicode[158] = toCharCode("\u017E");
pdfDocEncodingToUnicode[159] = toCharCode("\uFFFD");
pdfDocEncodingToUnicode[160] = toCharCode("\u20AC");
pdfDocEncodingToUnicode[173] = toCharCode("\uFFFD");
var pdfDocEncodingDecode = function(bytes) {
  var codePoints = new Array(bytes.length);
  for (var idx = 0, len = bytes.length; idx < len; idx++) {
    codePoints[idx] = pdfDocEncodingToUnicode[bytes[idx]];
  }
  return String.fromCodePoint.apply(String, codePoints);
};

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/utils/Cache.js
var Cache = (
  /** @class */
  function() {
    function Cache2(populate) {
      this.populate = populate;
      this.value = void 0;
    }
    Cache2.prototype.getValue = function() {
      return this.value;
    };
    Cache2.prototype.access = function() {
      if (!this.value)
        this.value = this.populate();
      return this.value;
    };
    Cache2.prototype.invalidate = function() {
      this.value = void 0;
    };
    Cache2.populatedBy = function(populate) {
      return new Cache2(populate);
    };
    return Cache2;
  }()
);
var Cache_default = Cache;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/errors.js
var MethodNotImplementedError = (
  /** @class */
  function(_super) {
    __extends(MethodNotImplementedError2, _super);
    function MethodNotImplementedError2(className, methodName) {
      var _this = this;
      var msg = "Method " + className + "." + methodName + "() not implemented";
      _this = _super.call(this, msg) || this;
      return _this;
    }
    return MethodNotImplementedError2;
  }(Error)
);
var PrivateConstructorError = (
  /** @class */
  function(_super) {
    __extends(PrivateConstructorError2, _super);
    function PrivateConstructorError2(className) {
      var _this = this;
      var msg = "Cannot construct " + className + " - it has a private constructor";
      _this = _super.call(this, msg) || this;
      return _this;
    }
    return PrivateConstructorError2;
  }(Error)
);
var UnexpectedObjectTypeError = (
  /** @class */
  function(_super) {
    __extends(UnexpectedObjectTypeError2, _super);
    function UnexpectedObjectTypeError2(expected, actual) {
      var _this = this;
      var name = function(t) {
        var _a, _b;
        return (_a = t === null || t === void 0 ? void 0 : t.name) !== null && _a !== void 0 ? _a : (_b = t === null || t === void 0 ? void 0 : t.constructor) === null || _b === void 0 ? void 0 : _b.name;
      };
      var expectedTypes = Array.isArray(expected) ? expected.map(name) : [name(expected)];
      var msg = "Expected instance of " + expectedTypes.join(" or ") + ", " + ("but got instance of " + (actual ? name(actual) : actual));
      _this = _super.call(this, msg) || this;
      return _this;
    }
    return UnexpectedObjectTypeError2;
  }(Error)
);
var UnsupportedEncodingError = (
  /** @class */
  function(_super) {
    __extends(UnsupportedEncodingError2, _super);
    function UnsupportedEncodingError2(encoding) {
      var _this = this;
      var msg = encoding + " stream encoding not supported";
      _this = _super.call(this, msg) || this;
      return _this;
    }
    return UnsupportedEncodingError2;
  }(Error)
);
var ReparseError = (
  /** @class */
  function(_super) {
    __extends(ReparseError2, _super);
    function ReparseError2(className, methodName) {
      var _this = this;
      var msg = "Cannot call " + className + "." + methodName + "() more than once";
      _this = _super.call(this, msg) || this;
      return _this;
    }
    return ReparseError2;
  }(Error)
);
var MissingCatalogError = (
  /** @class */
  function(_super) {
    __extends(MissingCatalogError2, _super);
    function MissingCatalogError2(ref) {
      var _this = this;
      var msg = "Missing catalog (ref=" + ref + ")";
      _this = _super.call(this, msg) || this;
      return _this;
    }
    return MissingCatalogError2;
  }(Error)
);
var MissingPageContentsEmbeddingError = (
  /** @class */
  function(_super) {
    __extends(MissingPageContentsEmbeddingError2, _super);
    function MissingPageContentsEmbeddingError2() {
      var _this = this;
      var msg = "Can't embed page with missing Contents";
      _this = _super.call(this, msg) || this;
      return _this;
    }
    return MissingPageContentsEmbeddingError2;
  }(Error)
);
var UnrecognizedStreamTypeError = (
  /** @class */
  function(_super) {
    __extends(UnrecognizedStreamTypeError2, _super);
    function UnrecognizedStreamTypeError2(stream2) {
      var _a, _b, _c;
      var _this = this;
      var streamType = (_c = (_b = (_a = stream2 === null || stream2 === void 0 ? void 0 : stream2.contructor) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : stream2 === null || stream2 === void 0 ? void 0 : stream2.name) !== null && _c !== void 0 ? _c : stream2;
      var msg = "Unrecognized stream type: " + streamType;
      _this = _super.call(this, msg) || this;
      return _this;
    }
    return UnrecognizedStreamTypeError2;
  }(Error)
);
var PageEmbeddingMismatchedContextError = (
  /** @class */
  function(_super) {
    __extends(PageEmbeddingMismatchedContextError2, _super);
    function PageEmbeddingMismatchedContextError2() {
      var _this = this;
      var msg = "Found mismatched contexts while embedding pages. All pages in the array passed to `PDFDocument.embedPages()` must be from the same document.";
      _this = _super.call(this, msg) || this;
      return _this;
    }
    return PageEmbeddingMismatchedContextError2;
  }(Error)
);
var PDFArrayIsNotRectangleError = (
  /** @class */
  function(_super) {
    __extends(PDFArrayIsNotRectangleError2, _super);
    function PDFArrayIsNotRectangleError2(size) {
      var _this = this;
      var msg = "Attempted to convert PDFArray with " + size + " elements to rectangle, but must have exactly 4 elements.";
      _this = _super.call(this, msg) || this;
      return _this;
    }
    return PDFArrayIsNotRectangleError2;
  }(Error)
);
var InvalidPDFDateStringError = (
  /** @class */
  function(_super) {
    __extends(InvalidPDFDateStringError2, _super);
    function InvalidPDFDateStringError2(value) {
      var _this = this;
      var msg = 'Attempted to convert "' + value + '" to a date, but it does not match the PDF date string format.';
      _this = _super.call(this, msg) || this;
      return _this;
    }
    return InvalidPDFDateStringError2;
  }(Error)
);
var InvalidTargetIndexError = (
  /** @class */
  function(_super) {
    __extends(InvalidTargetIndexError2, _super);
    function InvalidTargetIndexError2(targetIndex, Count) {
      var _this = this;
      var msg = "Invalid targetIndex specified: targetIndex=" + targetIndex + " must be less than Count=" + Count;
      _this = _super.call(this, msg) || this;
      return _this;
    }
    return InvalidTargetIndexError2;
  }(Error)
);
var CorruptPageTreeError = (
  /** @class */
  function(_super) {
    __extends(CorruptPageTreeError2, _super);
    function CorruptPageTreeError2(targetIndex, operation) {
      var _this = this;
      var msg = "Failed to " + operation + " at targetIndex=" + targetIndex + " due to corrupt page tree: It is likely that one or more 'Count' entries are invalid";
      _this = _super.call(this, msg) || this;
      return _this;
    }
    return CorruptPageTreeError2;
  }(Error)
);
var IndexOutOfBoundsError = (
  /** @class */
  function(_super) {
    __extends(IndexOutOfBoundsError2, _super);
    function IndexOutOfBoundsError2(index, min, max) {
      var _this = this;
      var msg = "index should be at least " + min + " and at most " + max + ", but was actually " + index;
      _this = _super.call(this, msg) || this;
      return _this;
    }
    return IndexOutOfBoundsError2;
  }(Error)
);
var InvalidAcroFieldValueError = (
  /** @class */
  function(_super) {
    __extends(InvalidAcroFieldValueError2, _super);
    function InvalidAcroFieldValueError2() {
      var _this = this;
      var msg = "Attempted to set invalid field value";
      _this = _super.call(this, msg) || this;
      return _this;
    }
    return InvalidAcroFieldValueError2;
  }(Error)
);
var MultiSelectValueError = (
  /** @class */
  function(_super) {
    __extends(MultiSelectValueError2, _super);
    function MultiSelectValueError2() {
      var _this = this;
      var msg = "Attempted to select multiple values for single-select field";
      _this = _super.call(this, msg) || this;
      return _this;
    }
    return MultiSelectValueError2;
  }(Error)
);
var MissingDAEntryError = (
  /** @class */
  function(_super) {
    __extends(MissingDAEntryError2, _super);
    function MissingDAEntryError2(fieldName) {
      var _this = this;
      var msg = "No /DA (default appearance) entry found for field: " + fieldName;
      _this = _super.call(this, msg) || this;
      return _this;
    }
    return MissingDAEntryError2;
  }(Error)
);
var MissingTfOperatorError = (
  /** @class */
  function(_super) {
    __extends(MissingTfOperatorError2, _super);
    function MissingTfOperatorError2(fieldName) {
      var _this = this;
      var msg = "No Tf operator found for DA of field: " + fieldName;
      _this = _super.call(this, msg) || this;
      return _this;
    }
    return MissingTfOperatorError2;
  }(Error)
);
var NumberParsingError = (
  /** @class */
  function(_super) {
    __extends(NumberParsingError2, _super);
    function NumberParsingError2(pos, value) {
      var _this = this;
      var msg = "Failed to parse number " + ("(line:" + pos.line + " col:" + pos.column + " offset=" + pos.offset + '): "' + value + '"');
      _this = _super.call(this, msg) || this;
      return _this;
    }
    return NumberParsingError2;
  }(Error)
);
var PDFParsingError = (
  /** @class */
  function(_super) {
    __extends(PDFParsingError2, _super);
    function PDFParsingError2(pos, details) {
      var _this = this;
      var msg = "Failed to parse PDF document " + ("(line:" + pos.line + " col:" + pos.column + " offset=" + pos.offset + "): " + details);
      _this = _super.call(this, msg) || this;
      return _this;
    }
    return PDFParsingError2;
  }(Error)
);
var NextByteAssertionError = (
  /** @class */
  function(_super) {
    __extends(NextByteAssertionError2, _super);
    function NextByteAssertionError2(pos, expectedByte, actualByte) {
      var _this = this;
      var msg = "Expected next byte to be " + expectedByte + " but it was actually " + actualByte;
      _this = _super.call(this, pos, msg) || this;
      return _this;
    }
    return NextByteAssertionError2;
  }(PDFParsingError)
);
var PDFObjectParsingError = (
  /** @class */
  function(_super) {
    __extends(PDFObjectParsingError2, _super);
    function PDFObjectParsingError2(pos, byte) {
      var _this = this;
      var msg = "Failed to parse PDF object starting with the following byte: " + byte;
      _this = _super.call(this, pos, msg) || this;
      return _this;
    }
    return PDFObjectParsingError2;
  }(PDFParsingError)
);
var PDFInvalidObjectParsingError = (
  /** @class */
  function(_super) {
    __extends(PDFInvalidObjectParsingError2, _super);
    function PDFInvalidObjectParsingError2(pos) {
      var _this = this;
      var msg = "Failed to parse invalid PDF object";
      _this = _super.call(this, pos, msg) || this;
      return _this;
    }
    return PDFInvalidObjectParsingError2;
  }(PDFParsingError)
);
var PDFStreamParsingError = (
  /** @class */
  function(_super) {
    __extends(PDFStreamParsingError2, _super);
    function PDFStreamParsingError2(pos) {
      var _this = this;
      var msg = "Failed to parse PDF stream";
      _this = _super.call(this, pos, msg) || this;
      return _this;
    }
    return PDFStreamParsingError2;
  }(PDFParsingError)
);
var UnbalancedParenthesisError = (
  /** @class */
  function(_super) {
    __extends(UnbalancedParenthesisError2, _super);
    function UnbalancedParenthesisError2(pos) {
      var _this = this;
      var msg = "Failed to parse PDF literal string due to unbalanced parenthesis";
      _this = _super.call(this, pos, msg) || this;
      return _this;
    }
    return UnbalancedParenthesisError2;
  }(PDFParsingError)
);
var StalledParserError = (
  /** @class */
  function(_super) {
    __extends(StalledParserError2, _super);
    function StalledParserError2(pos) {
      var _this = this;
      var msg = "Parser stalled";
      _this = _super.call(this, pos, msg) || this;
      return _this;
    }
    return StalledParserError2;
  }(PDFParsingError)
);
var MissingPDFHeaderError = (
  /** @class */
  function(_super) {
    __extends(MissingPDFHeaderError2, _super);
    function MissingPDFHeaderError2(pos) {
      var _this = this;
      var msg = "No PDF header found";
      _this = _super.call(this, pos, msg) || this;
      return _this;
    }
    return MissingPDFHeaderError2;
  }(PDFParsingError)
);
var MissingKeywordError = (
  /** @class */
  function(_super) {
    __extends(MissingKeywordError2, _super);
    function MissingKeywordError2(pos, keyword) {
      var _this = this;
      var msg = "Did not find expected keyword '" + arrayAsString(keyword) + "'";
      _this = _super.call(this, pos, msg) || this;
      return _this;
    }
    return MissingKeywordError2;
  }(PDFParsingError)
);

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/syntax/CharCodes.js
var CharCodes;
(function(CharCodes2) {
  CharCodes2[CharCodes2["Null"] = 0] = "Null";
  CharCodes2[CharCodes2["Backspace"] = 8] = "Backspace";
  CharCodes2[CharCodes2["Tab"] = 9] = "Tab";
  CharCodes2[CharCodes2["Newline"] = 10] = "Newline";
  CharCodes2[CharCodes2["FormFeed"] = 12] = "FormFeed";
  CharCodes2[CharCodes2["CarriageReturn"] = 13] = "CarriageReturn";
  CharCodes2[CharCodes2["Space"] = 32] = "Space";
  CharCodes2[CharCodes2["ExclamationPoint"] = 33] = "ExclamationPoint";
  CharCodes2[CharCodes2["Hash"] = 35] = "Hash";
  CharCodes2[CharCodes2["Percent"] = 37] = "Percent";
  CharCodes2[CharCodes2["LeftParen"] = 40] = "LeftParen";
  CharCodes2[CharCodes2["RightParen"] = 41] = "RightParen";
  CharCodes2[CharCodes2["Plus"] = 43] = "Plus";
  CharCodes2[CharCodes2["Minus"] = 45] = "Minus";
  CharCodes2[CharCodes2["Dash"] = 45] = "Dash";
  CharCodes2[CharCodes2["Period"] = 46] = "Period";
  CharCodes2[CharCodes2["ForwardSlash"] = 47] = "ForwardSlash";
  CharCodes2[CharCodes2["Zero"] = 48] = "Zero";
  CharCodes2[CharCodes2["One"] = 49] = "One";
  CharCodes2[CharCodes2["Two"] = 50] = "Two";
  CharCodes2[CharCodes2["Three"] = 51] = "Three";
  CharCodes2[CharCodes2["Four"] = 52] = "Four";
  CharCodes2[CharCodes2["Five"] = 53] = "Five";
  CharCodes2[CharCodes2["Six"] = 54] = "Six";
  CharCodes2[CharCodes2["Seven"] = 55] = "Seven";
  CharCodes2[CharCodes2["Eight"] = 56] = "Eight";
  CharCodes2[CharCodes2["Nine"] = 57] = "Nine";
  CharCodes2[CharCodes2["LessThan"] = 60] = "LessThan";
  CharCodes2[CharCodes2["GreaterThan"] = 62] = "GreaterThan";
  CharCodes2[CharCodes2["A"] = 65] = "A";
  CharCodes2[CharCodes2["D"] = 68] = "D";
  CharCodes2[CharCodes2["E"] = 69] = "E";
  CharCodes2[CharCodes2["F"] = 70] = "F";
  CharCodes2[CharCodes2["O"] = 79] = "O";
  CharCodes2[CharCodes2["P"] = 80] = "P";
  CharCodes2[CharCodes2["R"] = 82] = "R";
  CharCodes2[CharCodes2["LeftSquareBracket"] = 91] = "LeftSquareBracket";
  CharCodes2[CharCodes2["BackSlash"] = 92] = "BackSlash";
  CharCodes2[CharCodes2["RightSquareBracket"] = 93] = "RightSquareBracket";
  CharCodes2[CharCodes2["a"] = 97] = "a";
  CharCodes2[CharCodes2["b"] = 98] = "b";
  CharCodes2[CharCodes2["d"] = 100] = "d";
  CharCodes2[CharCodes2["e"] = 101] = "e";
  CharCodes2[CharCodes2["f"] = 102] = "f";
  CharCodes2[CharCodes2["i"] = 105] = "i";
  CharCodes2[CharCodes2["j"] = 106] = "j";
  CharCodes2[CharCodes2["l"] = 108] = "l";
  CharCodes2[CharCodes2["m"] = 109] = "m";
  CharCodes2[CharCodes2["n"] = 110] = "n";
  CharCodes2[CharCodes2["o"] = 111] = "o";
  CharCodes2[CharCodes2["r"] = 114] = "r";
  CharCodes2[CharCodes2["s"] = 115] = "s";
  CharCodes2[CharCodes2["t"] = 116] = "t";
  CharCodes2[CharCodes2["u"] = 117] = "u";
  CharCodes2[CharCodes2["x"] = 120] = "x";
  CharCodes2[CharCodes2["LeftCurly"] = 123] = "LeftCurly";
  CharCodes2[CharCodes2["RightCurly"] = 125] = "RightCurly";
  CharCodes2[CharCodes2["Tilde"] = 126] = "Tilde";
})(CharCodes || (CharCodes = {}));
var CharCodes_default = CharCodes;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/PDFContext.js
var import_pako3 = __toESM(require_pako());

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/document/PDFHeader.js
var PDFHeader = (
  /** @class */
  function() {
    function PDFHeader2(major, minor) {
      this.major = String(major);
      this.minor = String(minor);
    }
    PDFHeader2.prototype.toString = function() {
      var bc = charFromCode(129);
      return "%PDF-" + this.major + "." + this.minor + "\n%" + bc + bc + bc + bc;
    };
    PDFHeader2.prototype.sizeInBytes = function() {
      return 12 + this.major.length + this.minor.length;
    };
    PDFHeader2.prototype.copyBytesInto = function(buffer, offset) {
      var initialOffset = offset;
      buffer[offset++] = CharCodes_default.Percent;
      buffer[offset++] = CharCodes_default.P;
      buffer[offset++] = CharCodes_default.D;
      buffer[offset++] = CharCodes_default.F;
      buffer[offset++] = CharCodes_default.Dash;
      offset += copyStringIntoBuffer(this.major, buffer, offset);
      buffer[offset++] = CharCodes_default.Period;
      offset += copyStringIntoBuffer(this.minor, buffer, offset);
      buffer[offset++] = CharCodes_default.Newline;
      buffer[offset++] = CharCodes_default.Percent;
      buffer[offset++] = 129;
      buffer[offset++] = 129;
      buffer[offset++] = 129;
      buffer[offset++] = 129;
      return offset - initialOffset;
    };
    PDFHeader2.forVersion = function(major, minor) {
      return new PDFHeader2(major, minor);
    };
    return PDFHeader2;
  }()
);
var PDFHeader_default = PDFHeader;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/objects/PDFObject.js
var PDFObject = (
  /** @class */
  function() {
    function PDFObject2() {
    }
    PDFObject2.prototype.clone = function(_context) {
      throw new MethodNotImplementedError(this.constructor.name, "clone");
    };
    PDFObject2.prototype.toString = function() {
      throw new MethodNotImplementedError(this.constructor.name, "toString");
    };
    PDFObject2.prototype.sizeInBytes = function() {
      throw new MethodNotImplementedError(this.constructor.name, "sizeInBytes");
    };
    PDFObject2.prototype.copyBytesInto = function(_buffer, _offset) {
      throw new MethodNotImplementedError(this.constructor.name, "copyBytesInto");
    };
    return PDFObject2;
  }()
);
var PDFObject_default = PDFObject;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/objects/PDFNumber.js
var PDFNumber = (
  /** @class */
  function(_super) {
    __extends(PDFNumber2, _super);
    function PDFNumber2(value) {
      var _this = _super.call(this) || this;
      _this.numberValue = value;
      _this.stringValue = numberToString(value);
      return _this;
    }
    PDFNumber2.prototype.asNumber = function() {
      return this.numberValue;
    };
    PDFNumber2.prototype.value = function() {
      return this.numberValue;
    };
    PDFNumber2.prototype.clone = function() {
      return PDFNumber2.of(this.numberValue);
    };
    PDFNumber2.prototype.toString = function() {
      return this.stringValue;
    };
    PDFNumber2.prototype.sizeInBytes = function() {
      return this.stringValue.length;
    };
    PDFNumber2.prototype.copyBytesInto = function(buffer, offset) {
      offset += copyStringIntoBuffer(this.stringValue, buffer, offset);
      return this.stringValue.length;
    };
    PDFNumber2.of = function(value) {
      return new PDFNumber2(value);
    };
    return PDFNumber2;
  }(PDFObject_default)
);
var PDFNumber_default = PDFNumber;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/objects/PDFArray.js
var PDFArray = (
  /** @class */
  function(_super) {
    __extends(PDFArray3, _super);
    function PDFArray3(context) {
      var _this = _super.call(this) || this;
      _this.array = [];
      _this.context = context;
      return _this;
    }
    PDFArray3.prototype.size = function() {
      return this.array.length;
    };
    PDFArray3.prototype.push = function(object) {
      this.array.push(object);
    };
    PDFArray3.prototype.insert = function(index, object) {
      this.array.splice(index, 0, object);
    };
    PDFArray3.prototype.indexOf = function(object) {
      var index = this.array.indexOf(object);
      return index === -1 ? void 0 : index;
    };
    PDFArray3.prototype.remove = function(index) {
      this.array.splice(index, 1);
    };
    PDFArray3.prototype.set = function(idx, object) {
      this.array[idx] = object;
    };
    PDFArray3.prototype.get = function(index) {
      return this.array[index];
    };
    PDFArray3.prototype.lookupMaybe = function(index) {
      var _a;
      var types = [];
      for (var _i = 1; _i < arguments.length; _i++) {
        types[_i - 1] = arguments[_i];
      }
      return (_a = this.context).lookupMaybe.apply(_a, __spreadArrays([this.get(index)], types));
    };
    PDFArray3.prototype.lookup = function(index) {
      var _a;
      var types = [];
      for (var _i = 1; _i < arguments.length; _i++) {
        types[_i - 1] = arguments[_i];
      }
      return (_a = this.context).lookup.apply(_a, __spreadArrays([this.get(index)], types));
    };
    PDFArray3.prototype.asRectangle = function() {
      if (this.size() !== 4)
        throw new PDFArrayIsNotRectangleError(this.size());
      var lowerLeftX = this.lookup(0, PDFNumber_default).asNumber();
      var lowerLeftY = this.lookup(1, PDFNumber_default).asNumber();
      var upperRightX = this.lookup(2, PDFNumber_default).asNumber();
      var upperRightY = this.lookup(3, PDFNumber_default).asNumber();
      var x = lowerLeftX;
      var y = lowerLeftY;
      var width = upperRightX - lowerLeftX;
      var height = upperRightY - lowerLeftY;
      return { x, y, width, height };
    };
    PDFArray3.prototype.asArray = function() {
      return this.array.slice();
    };
    PDFArray3.prototype.clone = function(context) {
      var clone = PDFArray3.withContext(context || this.context);
      for (var idx = 0, len = this.size(); idx < len; idx++) {
        clone.push(this.array[idx]);
      }
      return clone;
    };
    PDFArray3.prototype.toString = function() {
      var arrayString = "[ ";
      for (var idx = 0, len = this.size(); idx < len; idx++) {
        arrayString += this.get(idx).toString();
        arrayString += " ";
      }
      arrayString += "]";
      return arrayString;
    };
    PDFArray3.prototype.sizeInBytes = function() {
      var size = 3;
      for (var idx = 0, len = this.size(); idx < len; idx++) {
        size += this.get(idx).sizeInBytes() + 1;
      }
      return size;
    };
    PDFArray3.prototype.copyBytesInto = function(buffer, offset) {
      var initialOffset = offset;
      buffer[offset++] = CharCodes_default.LeftSquareBracket;
      buffer[offset++] = CharCodes_default.Space;
      for (var idx = 0, len = this.size(); idx < len; idx++) {
        offset += this.get(idx).copyBytesInto(buffer, offset);
        buffer[offset++] = CharCodes_default.Space;
      }
      buffer[offset++] = CharCodes_default.RightSquareBracket;
      return offset - initialOffset;
    };
    PDFArray3.prototype.scalePDFNumbers = function(x, y) {
      for (var idx = 0, len = this.size(); idx < len; idx++) {
        var el = this.lookup(idx);
        if (el instanceof PDFNumber_default) {
          var factor = idx % 2 === 0 ? x : y;
          this.set(idx, PDFNumber_default.of(el.asNumber() * factor));
        }
      }
    };
    PDFArray3.withContext = function(context) {
      return new PDFArray3(context);
    };
    return PDFArray3;
  }(PDFObject_default)
);
var PDFArray_default = PDFArray;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/objects/PDFBool.js
var ENFORCER = {};
var PDFBool = (
  /** @class */
  function(_super) {
    __extends(PDFBool2, _super);
    function PDFBool2(enforcer, value) {
      var _this = this;
      if (enforcer !== ENFORCER)
        throw new PrivateConstructorError("PDFBool");
      _this = _super.call(this) || this;
      _this.value = value;
      return _this;
    }
    PDFBool2.prototype.asBoolean = function() {
      return this.value;
    };
    PDFBool2.prototype.clone = function() {
      return this;
    };
    PDFBool2.prototype.toString = function() {
      return String(this.value);
    };
    PDFBool2.prototype.sizeInBytes = function() {
      return this.value ? 4 : 5;
    };
    PDFBool2.prototype.copyBytesInto = function(buffer, offset) {
      if (this.value) {
        buffer[offset++] = CharCodes_default.t;
        buffer[offset++] = CharCodes_default.r;
        buffer[offset++] = CharCodes_default.u;
        buffer[offset++] = CharCodes_default.e;
        return 4;
      } else {
        buffer[offset++] = CharCodes_default.f;
        buffer[offset++] = CharCodes_default.a;
        buffer[offset++] = CharCodes_default.l;
        buffer[offset++] = CharCodes_default.s;
        buffer[offset++] = CharCodes_default.e;
        return 5;
      }
    };
    PDFBool2.True = new PDFBool2(ENFORCER, true);
    PDFBool2.False = new PDFBool2(ENFORCER, false);
    return PDFBool2;
  }(PDFObject_default)
);
var PDFBool_default = PDFBool;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/syntax/Delimiters.js
var IsDelimiter = new Uint8Array(256);
IsDelimiter[CharCodes_default.LeftParen] = 1;
IsDelimiter[CharCodes_default.RightParen] = 1;
IsDelimiter[CharCodes_default.LessThan] = 1;
IsDelimiter[CharCodes_default.GreaterThan] = 1;
IsDelimiter[CharCodes_default.LeftSquareBracket] = 1;
IsDelimiter[CharCodes_default.RightSquareBracket] = 1;
IsDelimiter[CharCodes_default.LeftCurly] = 1;
IsDelimiter[CharCodes_default.RightCurly] = 1;
IsDelimiter[CharCodes_default.ForwardSlash] = 1;
IsDelimiter[CharCodes_default.Percent] = 1;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/syntax/Whitespace.js
var IsWhitespace = new Uint8Array(256);
IsWhitespace[CharCodes_default.Null] = 1;
IsWhitespace[CharCodes_default.Tab] = 1;
IsWhitespace[CharCodes_default.Newline] = 1;
IsWhitespace[CharCodes_default.FormFeed] = 1;
IsWhitespace[CharCodes_default.CarriageReturn] = 1;
IsWhitespace[CharCodes_default.Space] = 1;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/syntax/Irregular.js
var IsIrregular = new Uint8Array(256);
for (idx = 0, len = 256; idx < len; idx++) {
  IsIrregular[idx] = IsWhitespace[idx] || IsDelimiter[idx] ? 1 : 0;
}
var idx;
var len;
IsIrregular[CharCodes_default.Hash] = 1;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/objects/PDFName.js
var decodeName = function(name) {
  return name.replace(/#([\dABCDEF]{2})/g, function(_, hex) {
    return charFromHexCode(hex);
  });
};
var isRegularChar = function(charCode) {
  return charCode >= CharCodes_default.ExclamationPoint && charCode <= CharCodes_default.Tilde && !IsIrregular[charCode];
};
var ENFORCER2 = {};
var pool = /* @__PURE__ */ new Map();
var PDFName = (
  /** @class */
  function(_super) {
    __extends(PDFName2, _super);
    function PDFName2(enforcer, name) {
      var _this = this;
      if (enforcer !== ENFORCER2)
        throw new PrivateConstructorError("PDFName");
      _this = _super.call(this) || this;
      var encodedName = "/";
      for (var idx = 0, len = name.length; idx < len; idx++) {
        var character = name[idx];
        var code = toCharCode(character);
        encodedName += isRegularChar(code) ? character : "#" + toHexString(code);
      }
      _this.encodedName = encodedName;
      return _this;
    }
    PDFName2.prototype.asBytes = function() {
      var bytes = [];
      var hex = "";
      var escaped = false;
      var pushByte = function(byte2) {
        if (byte2 !== void 0)
          bytes.push(byte2);
        escaped = false;
      };
      for (var idx = 1, len = this.encodedName.length; idx < len; idx++) {
        var char = this.encodedName[idx];
        var byte = toCharCode(char);
        var nextChar = this.encodedName[idx + 1];
        if (!escaped) {
          if (byte === CharCodes_default.Hash)
            escaped = true;
          else
            pushByte(byte);
        } else {
          if (byte >= CharCodes_default.Zero && byte <= CharCodes_default.Nine || byte >= CharCodes_default.a && byte <= CharCodes_default.f || byte >= CharCodes_default.A && byte <= CharCodes_default.F) {
            hex += char;
            if (hex.length === 2 || !(nextChar >= "0" && nextChar <= "9" || nextChar >= "a" && nextChar <= "f" || nextChar >= "A" && nextChar <= "F")) {
              pushByte(parseInt(hex, 16));
              hex = "";
            }
          } else {
            pushByte(byte);
          }
        }
      }
      return new Uint8Array(bytes);
    };
    PDFName2.prototype.decodeText = function() {
      var bytes = this.asBytes();
      return String.fromCharCode.apply(String, Array.from(bytes));
    };
    PDFName2.prototype.asString = function() {
      return this.encodedName;
    };
    PDFName2.prototype.value = function() {
      return this.encodedName;
    };
    PDFName2.prototype.clone = function() {
      return this;
    };
    PDFName2.prototype.toString = function() {
      return this.encodedName;
    };
    PDFName2.prototype.sizeInBytes = function() {
      return this.encodedName.length;
    };
    PDFName2.prototype.copyBytesInto = function(buffer, offset) {
      offset += copyStringIntoBuffer(this.encodedName, buffer, offset);
      return this.encodedName.length;
    };
    PDFName2.of = function(name) {
      var decodedValue = decodeName(name);
      var instance = pool.get(decodedValue);
      if (!instance) {
        instance = new PDFName2(ENFORCER2, decodedValue);
        pool.set(decodedValue, instance);
      }
      return instance;
    };
    PDFName2.Length = PDFName2.of("Length");
    PDFName2.FlateDecode = PDFName2.of("FlateDecode");
    PDFName2.Resources = PDFName2.of("Resources");
    PDFName2.Font = PDFName2.of("Font");
    PDFName2.XObject = PDFName2.of("XObject");
    PDFName2.ExtGState = PDFName2.of("ExtGState");
    PDFName2.Contents = PDFName2.of("Contents");
    PDFName2.Type = PDFName2.of("Type");
    PDFName2.Parent = PDFName2.of("Parent");
    PDFName2.MediaBox = PDFName2.of("MediaBox");
    PDFName2.Page = PDFName2.of("Page");
    PDFName2.Annots = PDFName2.of("Annots");
    PDFName2.TrimBox = PDFName2.of("TrimBox");
    PDFName2.ArtBox = PDFName2.of("ArtBox");
    PDFName2.BleedBox = PDFName2.of("BleedBox");
    PDFName2.CropBox = PDFName2.of("CropBox");
    PDFName2.Rotate = PDFName2.of("Rotate");
    PDFName2.Title = PDFName2.of("Title");
    PDFName2.Author = PDFName2.of("Author");
    PDFName2.Subject = PDFName2.of("Subject");
    PDFName2.Creator = PDFName2.of("Creator");
    PDFName2.Keywords = PDFName2.of("Keywords");
    PDFName2.Producer = PDFName2.of("Producer");
    PDFName2.CreationDate = PDFName2.of("CreationDate");
    PDFName2.ModDate = PDFName2.of("ModDate");
    return PDFName2;
  }(PDFObject_default)
);
var PDFName_default = PDFName;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/objects/PDFNull.js
var PDFNull = (
  /** @class */
  function(_super) {
    __extends(PDFNull2, _super);
    function PDFNull2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    PDFNull2.prototype.asNull = function() {
      return null;
    };
    PDFNull2.prototype.clone = function() {
      return this;
    };
    PDFNull2.prototype.toString = function() {
      return "null";
    };
    PDFNull2.prototype.sizeInBytes = function() {
      return 4;
    };
    PDFNull2.prototype.copyBytesInto = function(buffer, offset) {
      buffer[offset++] = CharCodes_default.n;
      buffer[offset++] = CharCodes_default.u;
      buffer[offset++] = CharCodes_default.l;
      buffer[offset++] = CharCodes_default.l;
      return 4;
    };
    return PDFNull2;
  }(PDFObject_default)
);
var PDFNull_default = new PDFNull();

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/objects/PDFDict.js
var PDFDict = (
  /** @class */
  function(_super) {
    __extends(PDFDict2, _super);
    function PDFDict2(map, context) {
      var _this = _super.call(this) || this;
      _this.dict = map;
      _this.context = context;
      return _this;
    }
    PDFDict2.prototype.keys = function() {
      return Array.from(this.dict.keys());
    };
    PDFDict2.prototype.values = function() {
      return Array.from(this.dict.values());
    };
    PDFDict2.prototype.entries = function() {
      return Array.from(this.dict.entries());
    };
    PDFDict2.prototype.set = function(key, value) {
      this.dict.set(key, value);
    };
    PDFDict2.prototype.get = function(key, preservePDFNull) {
      if (preservePDFNull === void 0) {
        preservePDFNull = false;
      }
      var value = this.dict.get(key);
      if (value === PDFNull_default && !preservePDFNull)
        return void 0;
      return value;
    };
    PDFDict2.prototype.has = function(key) {
      var value = this.dict.get(key);
      return value !== void 0 && value !== PDFNull_default;
    };
    PDFDict2.prototype.lookupMaybe = function(key) {
      var _a;
      var types = [];
      for (var _i = 1; _i < arguments.length; _i++) {
        types[_i - 1] = arguments[_i];
      }
      var preservePDFNull = types.includes(PDFNull_default);
      var value = (_a = this.context).lookupMaybe.apply(_a, __spreadArrays([this.get(key, preservePDFNull)], types));
      if (value === PDFNull_default && !preservePDFNull)
        return void 0;
      return value;
    };
    PDFDict2.prototype.lookup = function(key) {
      var _a;
      var types = [];
      for (var _i = 1; _i < arguments.length; _i++) {
        types[_i - 1] = arguments[_i];
      }
      var preservePDFNull = types.includes(PDFNull_default);
      var value = (_a = this.context).lookup.apply(_a, __spreadArrays([this.get(key, preservePDFNull)], types));
      if (value === PDFNull_default && !preservePDFNull)
        return void 0;
      return value;
    };
    PDFDict2.prototype.delete = function(key) {
      return this.dict.delete(key);
    };
    PDFDict2.prototype.asMap = function() {
      return new Map(this.dict);
    };
    PDFDict2.prototype.uniqueKey = function(tag) {
      if (tag === void 0) {
        tag = "";
      }
      var existingKeys = this.keys();
      var key = PDFName_default.of(this.context.addRandomSuffix(tag, 10));
      while (existingKeys.includes(key)) {
        key = PDFName_default.of(this.context.addRandomSuffix(tag, 10));
      }
      return key;
    };
    PDFDict2.prototype.clone = function(context) {
      var clone = PDFDict2.withContext(context || this.context);
      var entries = this.entries();
      for (var idx = 0, len = entries.length; idx < len; idx++) {
        var _a = entries[idx], key = _a[0], value = _a[1];
        clone.set(key, value);
      }
      return clone;
    };
    PDFDict2.prototype.toString = function() {
      var dictString = "<<\n";
      var entries = this.entries();
      for (var idx = 0, len = entries.length; idx < len; idx++) {
        var _a = entries[idx], key = _a[0], value = _a[1];
        dictString += key.toString() + " " + value.toString() + "\n";
      }
      dictString += ">>";
      return dictString;
    };
    PDFDict2.prototype.sizeInBytes = function() {
      var size = 5;
      var entries = this.entries();
      for (var idx = 0, len = entries.length; idx < len; idx++) {
        var _a = entries[idx], key = _a[0], value = _a[1];
        size += key.sizeInBytes() + value.sizeInBytes() + 2;
      }
      return size;
    };
    PDFDict2.prototype.copyBytesInto = function(buffer, offset) {
      var initialOffset = offset;
      buffer[offset++] = CharCodes_default.LessThan;
      buffer[offset++] = CharCodes_default.LessThan;
      buffer[offset++] = CharCodes_default.Newline;
      var entries = this.entries();
      for (var idx = 0, len = entries.length; idx < len; idx++) {
        var _a = entries[idx], key = _a[0], value = _a[1];
        offset += key.copyBytesInto(buffer, offset);
        buffer[offset++] = CharCodes_default.Space;
        offset += value.copyBytesInto(buffer, offset);
        buffer[offset++] = CharCodes_default.Newline;
      }
      buffer[offset++] = CharCodes_default.GreaterThan;
      buffer[offset++] = CharCodes_default.GreaterThan;
      return offset - initialOffset;
    };
    PDFDict2.withContext = function(context) {
      return new PDFDict2(/* @__PURE__ */ new Map(), context);
    };
    PDFDict2.fromMapWithContext = function(map, context) {
      return new PDFDict2(map, context);
    };
    return PDFDict2;
  }(PDFObject_default)
);
var PDFDict_default = PDFDict;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/objects/PDFStream.js
var PDFStream = (
  /** @class */
  function(_super) {
    __extends(PDFStream2, _super);
    function PDFStream2(dict) {
      var _this = _super.call(this) || this;
      _this.dict = dict;
      return _this;
    }
    PDFStream2.prototype.clone = function(_context) {
      throw new MethodNotImplementedError(this.constructor.name, "clone");
    };
    PDFStream2.prototype.getContentsString = function() {
      throw new MethodNotImplementedError(this.constructor.name, "getContentsString");
    };
    PDFStream2.prototype.getContents = function() {
      throw new MethodNotImplementedError(this.constructor.name, "getContents");
    };
    PDFStream2.prototype.getContentsSize = function() {
      throw new MethodNotImplementedError(this.constructor.name, "getContentsSize");
    };
    PDFStream2.prototype.updateDict = function() {
      var contentsSize = this.getContentsSize();
      this.dict.set(PDFName_default.Length, PDFNumber_default.of(contentsSize));
    };
    PDFStream2.prototype.sizeInBytes = function() {
      this.updateDict();
      return this.dict.sizeInBytes() + this.getContentsSize() + 18;
    };
    PDFStream2.prototype.toString = function() {
      this.updateDict();
      var streamString = this.dict.toString();
      streamString += "\nstream\n";
      streamString += this.getContentsString();
      streamString += "\nendstream";
      return streamString;
    };
    PDFStream2.prototype.copyBytesInto = function(buffer, offset) {
      this.updateDict();
      var initialOffset = offset;
      offset += this.dict.copyBytesInto(buffer, offset);
      buffer[offset++] = CharCodes_default.Newline;
      buffer[offset++] = CharCodes_default.s;
      buffer[offset++] = CharCodes_default.t;
      buffer[offset++] = CharCodes_default.r;
      buffer[offset++] = CharCodes_default.e;
      buffer[offset++] = CharCodes_default.a;
      buffer[offset++] = CharCodes_default.m;
      buffer[offset++] = CharCodes_default.Newline;
      var contents = this.getContents();
      for (var idx = 0, len = contents.length; idx < len; idx++) {
        buffer[offset++] = contents[idx];
      }
      buffer[offset++] = CharCodes_default.Newline;
      buffer[offset++] = CharCodes_default.e;
      buffer[offset++] = CharCodes_default.n;
      buffer[offset++] = CharCodes_default.d;
      buffer[offset++] = CharCodes_default.s;
      buffer[offset++] = CharCodes_default.t;
      buffer[offset++] = CharCodes_default.r;
      buffer[offset++] = CharCodes_default.e;
      buffer[offset++] = CharCodes_default.a;
      buffer[offset++] = CharCodes_default.m;
      return offset - initialOffset;
    };
    return PDFStream2;
  }(PDFObject_default)
);
var PDFStream_default = PDFStream;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/objects/PDFRawStream.js
var PDFRawStream = (
  /** @class */
  function(_super) {
    __extends(PDFRawStream2, _super);
    function PDFRawStream2(dict, contents) {
      var _this = _super.call(this, dict) || this;
      _this.contents = contents;
      return _this;
    }
    PDFRawStream2.prototype.asUint8Array = function() {
      return this.contents.slice();
    };
    PDFRawStream2.prototype.clone = function(context) {
      return PDFRawStream2.of(this.dict.clone(context), this.contents.slice());
    };
    PDFRawStream2.prototype.getContentsString = function() {
      return arrayAsString(this.contents);
    };
    PDFRawStream2.prototype.getContents = function() {
      return this.contents;
    };
    PDFRawStream2.prototype.getContentsSize = function() {
      return this.contents.length;
    };
    PDFRawStream2.of = function(dict, contents) {
      return new PDFRawStream2(dict, contents);
    };
    return PDFRawStream2;
  }(PDFStream_default)
);
var PDFRawStream_default = PDFRawStream;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/objects/PDFRef.js
var ENFORCER3 = {};
var pool2 = /* @__PURE__ */ new Map();
var PDFRef = (
  /** @class */
  function(_super) {
    __extends(PDFRef3, _super);
    function PDFRef3(enforcer, objectNumber, generationNumber) {
      var _this = this;
      if (enforcer !== ENFORCER3)
        throw new PrivateConstructorError("PDFRef");
      _this = _super.call(this) || this;
      _this.objectNumber = objectNumber;
      _this.generationNumber = generationNumber;
      _this.tag = objectNumber + " " + generationNumber + " R";
      return _this;
    }
    PDFRef3.prototype.clone = function() {
      return this;
    };
    PDFRef3.prototype.toString = function() {
      return this.tag;
    };
    PDFRef3.prototype.sizeInBytes = function() {
      return this.tag.length;
    };
    PDFRef3.prototype.copyBytesInto = function(buffer, offset) {
      offset += copyStringIntoBuffer(this.tag, buffer, offset);
      return this.tag.length;
    };
    PDFRef3.of = function(objectNumber, generationNumber) {
      if (generationNumber === void 0) {
        generationNumber = 0;
      }
      var tag = objectNumber + " " + generationNumber + " R";
      var instance = pool2.get(tag);
      if (!instance) {
        instance = new PDFRef3(ENFORCER3, objectNumber, generationNumber);
        pool2.set(tag, instance);
      }
      return instance;
    };
    return PDFRef3;
  }(PDFObject_default)
);
var PDFRef_default = PDFRef;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/operators/PDFOperator.js
var PDFOperator = (
  /** @class */
  function() {
    function PDFOperator2(name, args) {
      this.name = name;
      this.args = args || [];
    }
    PDFOperator2.prototype.clone = function(context) {
      var args = new Array(this.args.length);
      for (var idx = 0, len = args.length; idx < len; idx++) {
        var arg = this.args[idx];
        args[idx] = arg instanceof PDFObject_default ? arg.clone(context) : arg;
      }
      return PDFOperator2.of(this.name, args);
    };
    PDFOperator2.prototype.toString = function() {
      var value = "";
      for (var idx = 0, len = this.args.length; idx < len; idx++) {
        value += String(this.args[idx]) + " ";
      }
      value += this.name;
      return value;
    };
    PDFOperator2.prototype.sizeInBytes = function() {
      var size = 0;
      for (var idx = 0, len = this.args.length; idx < len; idx++) {
        var arg = this.args[idx];
        size += (arg instanceof PDFObject_default ? arg.sizeInBytes() : arg.length) + 1;
      }
      size += this.name.length;
      return size;
    };
    PDFOperator2.prototype.copyBytesInto = function(buffer, offset) {
      var initialOffset = offset;
      for (var idx = 0, len = this.args.length; idx < len; idx++) {
        var arg = this.args[idx];
        if (arg instanceof PDFObject_default) {
          offset += arg.copyBytesInto(buffer, offset);
        } else {
          offset += copyStringIntoBuffer(arg, buffer, offset);
        }
        buffer[offset++] = CharCodes_default.Space;
      }
      offset += copyStringIntoBuffer(this.name, buffer, offset);
      return offset - initialOffset;
    };
    PDFOperator2.of = function(name, args) {
      return new PDFOperator2(name, args);
    };
    return PDFOperator2;
  }()
);
var PDFOperator_default = PDFOperator;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/operators/PDFOperatorNames.js
var PDFOperatorNames;
(function(PDFOperatorNames2) {
  PDFOperatorNames2["NonStrokingColor"] = "sc";
  PDFOperatorNames2["NonStrokingColorN"] = "scn";
  PDFOperatorNames2["NonStrokingColorRgb"] = "rg";
  PDFOperatorNames2["NonStrokingColorGray"] = "g";
  PDFOperatorNames2["NonStrokingColorCmyk"] = "k";
  PDFOperatorNames2["NonStrokingColorspace"] = "cs";
  PDFOperatorNames2["StrokingColor"] = "SC";
  PDFOperatorNames2["StrokingColorN"] = "SCN";
  PDFOperatorNames2["StrokingColorRgb"] = "RG";
  PDFOperatorNames2["StrokingColorGray"] = "G";
  PDFOperatorNames2["StrokingColorCmyk"] = "K";
  PDFOperatorNames2["StrokingColorspace"] = "CS";
  PDFOperatorNames2["BeginMarkedContentSequence"] = "BDC";
  PDFOperatorNames2["BeginMarkedContent"] = "BMC";
  PDFOperatorNames2["EndMarkedContent"] = "EMC";
  PDFOperatorNames2["MarkedContentPointWithProps"] = "DP";
  PDFOperatorNames2["MarkedContentPoint"] = "MP";
  PDFOperatorNames2["DrawObject"] = "Do";
  PDFOperatorNames2["ConcatTransformationMatrix"] = "cm";
  PDFOperatorNames2["PopGraphicsState"] = "Q";
  PDFOperatorNames2["PushGraphicsState"] = "q";
  PDFOperatorNames2["SetFlatness"] = "i";
  PDFOperatorNames2["SetGraphicsStateParams"] = "gs";
  PDFOperatorNames2["SetLineCapStyle"] = "J";
  PDFOperatorNames2["SetLineDashPattern"] = "d";
  PDFOperatorNames2["SetLineJoinStyle"] = "j";
  PDFOperatorNames2["SetLineMiterLimit"] = "M";
  PDFOperatorNames2["SetLineWidth"] = "w";
  PDFOperatorNames2["SetTextMatrix"] = "Tm";
  PDFOperatorNames2["SetRenderingIntent"] = "ri";
  PDFOperatorNames2["AppendRectangle"] = "re";
  PDFOperatorNames2["BeginInlineImage"] = "BI";
  PDFOperatorNames2["BeginInlineImageData"] = "ID";
  PDFOperatorNames2["EndInlineImage"] = "EI";
  PDFOperatorNames2["ClipEvenOdd"] = "W*";
  PDFOperatorNames2["ClipNonZero"] = "W";
  PDFOperatorNames2["CloseAndStroke"] = "s";
  PDFOperatorNames2["CloseFillEvenOddAndStroke"] = "b*";
  PDFOperatorNames2["CloseFillNonZeroAndStroke"] = "b";
  PDFOperatorNames2["ClosePath"] = "h";
  PDFOperatorNames2["AppendBezierCurve"] = "c";
  PDFOperatorNames2["CurveToReplicateFinalPoint"] = "y";
  PDFOperatorNames2["CurveToReplicateInitialPoint"] = "v";
  PDFOperatorNames2["EndPath"] = "n";
  PDFOperatorNames2["FillEvenOddAndStroke"] = "B*";
  PDFOperatorNames2["FillEvenOdd"] = "f*";
  PDFOperatorNames2["FillNonZeroAndStroke"] = "B";
  PDFOperatorNames2["FillNonZero"] = "f";
  PDFOperatorNames2["LegacyFillNonZero"] = "F";
  PDFOperatorNames2["LineTo"] = "l";
  PDFOperatorNames2["MoveTo"] = "m";
  PDFOperatorNames2["ShadingFill"] = "sh";
  PDFOperatorNames2["StrokePath"] = "S";
  PDFOperatorNames2["BeginText"] = "BT";
  PDFOperatorNames2["EndText"] = "ET";
  PDFOperatorNames2["MoveText"] = "Td";
  PDFOperatorNames2["MoveTextSetLeading"] = "TD";
  PDFOperatorNames2["NextLine"] = "T*";
  PDFOperatorNames2["SetCharacterSpacing"] = "Tc";
  PDFOperatorNames2["SetFontAndSize"] = "Tf";
  PDFOperatorNames2["SetTextHorizontalScaling"] = "Tz";
  PDFOperatorNames2["SetTextLineHeight"] = "TL";
  PDFOperatorNames2["SetTextRenderingMode"] = "Tr";
  PDFOperatorNames2["SetTextRise"] = "Ts";
  PDFOperatorNames2["SetWordSpacing"] = "Tw";
  PDFOperatorNames2["ShowText"] = "Tj";
  PDFOperatorNames2["ShowTextAdjusted"] = "TJ";
  PDFOperatorNames2["ShowTextLine"] = "'";
  PDFOperatorNames2["ShowTextLineAndSpace"] = '"';
  PDFOperatorNames2["Type3D0"] = "d0";
  PDFOperatorNames2["Type3D1"] = "d1";
  PDFOperatorNames2["BeginCompatibilitySection"] = "BX";
  PDFOperatorNames2["EndCompatibilitySection"] = "EX";
})(PDFOperatorNames || (PDFOperatorNames = {}));
var PDFOperatorNames_default = PDFOperatorNames;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/structures/PDFFlateStream.js
var import_pako2 = __toESM(require_pako());
var PDFFlateStream = (
  /** @class */
  function(_super) {
    __extends(PDFFlateStream2, _super);
    function PDFFlateStream2(dict, encode) {
      var _this = _super.call(this, dict) || this;
      _this.computeContents = function() {
        var unencodedContents = _this.getUnencodedContents();
        return _this.encode ? import_pako2.default.deflate(unencodedContents) : unencodedContents;
      };
      _this.encode = encode;
      if (encode)
        dict.set(PDFName_default.of("Filter"), PDFName_default.of("FlateDecode"));
      _this.contentsCache = Cache_default.populatedBy(_this.computeContents);
      return _this;
    }
    PDFFlateStream2.prototype.getContents = function() {
      return this.contentsCache.access();
    };
    PDFFlateStream2.prototype.getContentsSize = function() {
      return this.contentsCache.access().length;
    };
    PDFFlateStream2.prototype.getUnencodedContents = function() {
      throw new MethodNotImplementedError(this.constructor.name, "getUnencodedContents");
    };
    return PDFFlateStream2;
  }(PDFStream_default)
);
var PDFFlateStream_default = PDFFlateStream;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/structures/PDFContentStream.js
var PDFContentStream = (
  /** @class */
  function(_super) {
    __extends(PDFContentStream2, _super);
    function PDFContentStream2(dict, operators, encode) {
      if (encode === void 0) {
        encode = true;
      }
      var _this = _super.call(this, dict, encode) || this;
      _this.operators = operators;
      return _this;
    }
    PDFContentStream2.prototype.push = function() {
      var _a;
      var operators = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        operators[_i] = arguments[_i];
      }
      (_a = this.operators).push.apply(_a, operators);
    };
    PDFContentStream2.prototype.clone = function(context) {
      var operators = new Array(this.operators.length);
      for (var idx = 0, len = this.operators.length; idx < len; idx++) {
        operators[idx] = this.operators[idx].clone(context);
      }
      var _a = this, dict = _a.dict, encode = _a.encode;
      return PDFContentStream2.of(dict.clone(context), operators, encode);
    };
    PDFContentStream2.prototype.getContentsString = function() {
      var value = "";
      for (var idx = 0, len = this.operators.length; idx < len; idx++) {
        value += this.operators[idx] + "\n";
      }
      return value;
    };
    PDFContentStream2.prototype.getUnencodedContents = function() {
      var buffer = new Uint8Array(this.getUnencodedContentsSize());
      var offset = 0;
      for (var idx = 0, len = this.operators.length; idx < len; idx++) {
        offset += this.operators[idx].copyBytesInto(buffer, offset);
        buffer[offset++] = CharCodes_default.Newline;
      }
      return buffer;
    };
    PDFContentStream2.prototype.getUnencodedContentsSize = function() {
      var size = 0;
      for (var idx = 0, len = this.operators.length; idx < len; idx++) {
        size += this.operators[idx].sizeInBytes() + 1;
      }
      return size;
    };
    PDFContentStream2.of = function(dict, operators, encode) {
      if (encode === void 0) {
        encode = true;
      }
      return new PDFContentStream2(dict, operators, encode);
    };
    return PDFContentStream2;
  }(PDFFlateStream_default)
);
var PDFContentStream_default = PDFContentStream;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/utils/rng.js
var SimpleRNG = (
  /** @class */
  function() {
    function SimpleRNG2(seed) {
      this.seed = seed;
    }
    SimpleRNG2.prototype.nextInt = function() {
      var x = Math.sin(this.seed++) * 1e4;
      return x - Math.floor(x);
    };
    SimpleRNG2.withSeed = function(seed) {
      return new SimpleRNG2(seed);
    };
    return SimpleRNG2;
  }()
);

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/PDFContext.js
var byAscendingObjectNumber = function(_a, _b) {
  var a = _a[0];
  var b = _b[0];
  return a.objectNumber - b.objectNumber;
};
var PDFContext = (
  /** @class */
  function() {
    function PDFContext2() {
      this.largestObjectNumber = 0;
      this.header = PDFHeader_default.forVersion(1, 7);
      this.trailerInfo = {};
      this.indirectObjects = /* @__PURE__ */ new Map();
      this.rng = SimpleRNG.withSeed(1);
    }
    PDFContext2.prototype.assign = function(ref, object) {
      this.indirectObjects.set(ref, object);
      if (ref.objectNumber > this.largestObjectNumber) {
        this.largestObjectNumber = ref.objectNumber;
      }
    };
    PDFContext2.prototype.nextRef = function() {
      this.largestObjectNumber += 1;
      return PDFRef_default.of(this.largestObjectNumber);
    };
    PDFContext2.prototype.register = function(object) {
      var ref = this.nextRef();
      this.assign(ref, object);
      return ref;
    };
    PDFContext2.prototype.delete = function(ref) {
      return this.indirectObjects.delete(ref);
    };
    PDFContext2.prototype.lookupMaybe = function(ref) {
      var types = [];
      for (var _i = 1; _i < arguments.length; _i++) {
        types[_i - 1] = arguments[_i];
      }
      var preservePDFNull = types.includes(PDFNull_default);
      var result = ref instanceof PDFRef_default ? this.indirectObjects.get(ref) : ref;
      if (!result || result === PDFNull_default && !preservePDFNull)
        return void 0;
      for (var idx = 0, len = types.length; idx < len; idx++) {
        var type = types[idx];
        if (type === PDFNull_default) {
          if (result === PDFNull_default)
            return result;
        } else {
          if (result instanceof type)
            return result;
        }
      }
      throw new UnexpectedObjectTypeError(types, result);
    };
    PDFContext2.prototype.lookup = function(ref) {
      var types = [];
      for (var _i = 1; _i < arguments.length; _i++) {
        types[_i - 1] = arguments[_i];
      }
      var result = ref instanceof PDFRef_default ? this.indirectObjects.get(ref) : ref;
      if (types.length === 0)
        return result;
      for (var idx = 0, len = types.length; idx < len; idx++) {
        var type = types[idx];
        if (type === PDFNull_default) {
          if (result === PDFNull_default)
            return result;
        } else {
          if (result instanceof type)
            return result;
        }
      }
      throw new UnexpectedObjectTypeError(types, result);
    };
    PDFContext2.prototype.getObjectRef = function(pdfObject) {
      var entries = Array.from(this.indirectObjects.entries());
      for (var idx = 0, len = entries.length; idx < len; idx++) {
        var _a = entries[idx], ref = _a[0], object = _a[1];
        if (object === pdfObject) {
          return ref;
        }
      }
      return void 0;
    };
    PDFContext2.prototype.enumerateIndirectObjects = function() {
      return Array.from(this.indirectObjects.entries()).sort(byAscendingObjectNumber);
    };
    PDFContext2.prototype.obj = function(literal) {
      if (literal instanceof PDFObject_default) {
        return literal;
      } else if (literal === null || literal === void 0) {
        return PDFNull_default;
      } else if (typeof literal === "string") {
        return PDFName_default.of(literal);
      } else if (typeof literal === "number") {
        return PDFNumber_default.of(literal);
      } else if (typeof literal === "boolean") {
        return literal ? PDFBool_default.True : PDFBool_default.False;
      } else if (Array.isArray(literal)) {
        var array = PDFArray_default.withContext(this);
        for (var idx = 0, len = literal.length; idx < len; idx++) {
          array.push(this.obj(literal[idx]));
        }
        return array;
      } else {
        var dict = PDFDict_default.withContext(this);
        var keys = Object.keys(literal);
        for (var idx = 0, len = keys.length; idx < len; idx++) {
          var key = keys[idx];
          var value = literal[key];
          if (value !== void 0)
            dict.set(PDFName_default.of(key), this.obj(value));
        }
        return dict;
      }
    };
    PDFContext2.prototype.stream = function(contents, dict) {
      if (dict === void 0) {
        dict = {};
      }
      return PDFRawStream_default.of(this.obj(dict), typedArrayFor(contents));
    };
    PDFContext2.prototype.flateStream = function(contents, dict) {
      if (dict === void 0) {
        dict = {};
      }
      return this.stream(import_pako3.default.deflate(typedArrayFor(contents)), __assign(__assign({}, dict), { Filter: "FlateDecode" }));
    };
    PDFContext2.prototype.contentStream = function(operators, dict) {
      if (dict === void 0) {
        dict = {};
      }
      return PDFContentStream_default.of(this.obj(dict), operators);
    };
    PDFContext2.prototype.formXObject = function(operators, dict) {
      if (dict === void 0) {
        dict = {};
      }
      return this.contentStream(operators, __assign(__assign({ BBox: this.obj([0, 0, 0, 0]), Matrix: this.obj([1, 0, 0, 1, 0, 0]) }, dict), { Type: "XObject", Subtype: "Form" }));
    };
    PDFContext2.prototype.getPushGraphicsStateContentStream = function() {
      if (this.pushGraphicsStateContentStreamRef) {
        return this.pushGraphicsStateContentStreamRef;
      }
      var dict = this.obj({});
      var op = PDFOperator_default.of(PDFOperatorNames_default.PushGraphicsState);
      var stream2 = PDFContentStream_default.of(dict, [op]);
      this.pushGraphicsStateContentStreamRef = this.register(stream2);
      return this.pushGraphicsStateContentStreamRef;
    };
    PDFContext2.prototype.getPopGraphicsStateContentStream = function() {
      if (this.popGraphicsStateContentStreamRef) {
        return this.popGraphicsStateContentStreamRef;
      }
      var dict = this.obj({});
      var op = PDFOperator_default.of(PDFOperatorNames_default.PopGraphicsState);
      var stream2 = PDFContentStream_default.of(dict, [op]);
      this.popGraphicsStateContentStreamRef = this.register(stream2);
      return this.popGraphicsStateContentStreamRef;
    };
    PDFContext2.prototype.addRandomSuffix = function(prefix, suffixLength) {
      if (suffixLength === void 0) {
        suffixLength = 4;
      }
      return prefix + "-" + Math.floor(this.rng.nextInt() * Math.pow(10, suffixLength));
    };
    PDFContext2.create = function() {
      return new PDFContext2();
    };
    return PDFContext2;
  }()
);
var PDFContext_default = PDFContext;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/structures/PDFPageLeaf.js
var PDFPageLeaf = (
  /** @class */
  function(_super) {
    __extends(PDFPageLeaf2, _super);
    function PDFPageLeaf2(map, context, autoNormalizeCTM) {
      if (autoNormalizeCTM === void 0) {
        autoNormalizeCTM = true;
      }
      var _this = _super.call(this, map, context) || this;
      _this.normalized = false;
      _this.autoNormalizeCTM = autoNormalizeCTM;
      return _this;
    }
    PDFPageLeaf2.prototype.clone = function(context) {
      var clone = PDFPageLeaf2.fromMapWithContext(/* @__PURE__ */ new Map(), context || this.context, this.autoNormalizeCTM);
      var entries = this.entries();
      for (var idx = 0, len = entries.length; idx < len; idx++) {
        var _a = entries[idx], key = _a[0], value = _a[1];
        clone.set(key, value);
      }
      return clone;
    };
    PDFPageLeaf2.prototype.Parent = function() {
      return this.lookupMaybe(PDFName_default.Parent, PDFDict_default);
    };
    PDFPageLeaf2.prototype.Contents = function() {
      return this.lookup(PDFName_default.of("Contents"));
    };
    PDFPageLeaf2.prototype.Annots = function() {
      return this.lookupMaybe(PDFName_default.Annots, PDFArray_default);
    };
    PDFPageLeaf2.prototype.BleedBox = function() {
      return this.lookupMaybe(PDFName_default.BleedBox, PDFArray_default);
    };
    PDFPageLeaf2.prototype.TrimBox = function() {
      return this.lookupMaybe(PDFName_default.TrimBox, PDFArray_default);
    };
    PDFPageLeaf2.prototype.ArtBox = function() {
      return this.lookupMaybe(PDFName_default.ArtBox, PDFArray_default);
    };
    PDFPageLeaf2.prototype.Resources = function() {
      var dictOrRef = this.getInheritableAttribute(PDFName_default.Resources);
      return this.context.lookupMaybe(dictOrRef, PDFDict_default);
    };
    PDFPageLeaf2.prototype.MediaBox = function() {
      var arrayOrRef = this.getInheritableAttribute(PDFName_default.MediaBox);
      return this.context.lookup(arrayOrRef, PDFArray_default);
    };
    PDFPageLeaf2.prototype.CropBox = function() {
      var arrayOrRef = this.getInheritableAttribute(PDFName_default.CropBox);
      return this.context.lookupMaybe(arrayOrRef, PDFArray_default);
    };
    PDFPageLeaf2.prototype.Rotate = function() {
      var numberOrRef = this.getInheritableAttribute(PDFName_default.Rotate);
      return this.context.lookupMaybe(numberOrRef, PDFNumber_default);
    };
    PDFPageLeaf2.prototype.getInheritableAttribute = function(name) {
      var attribute;
      this.ascend(function(node) {
        if (!attribute)
          attribute = node.get(name);
      });
      return attribute;
    };
    PDFPageLeaf2.prototype.setParent = function(parentRef) {
      this.set(PDFName_default.Parent, parentRef);
    };
    PDFPageLeaf2.prototype.addContentStream = function(contentStreamRef) {
      var Contents = this.normalizedEntries().Contents || this.context.obj([]);
      this.set(PDFName_default.Contents, Contents);
      Contents.push(contentStreamRef);
    };
    PDFPageLeaf2.prototype.wrapContentStreams = function(startStream, endStream) {
      var Contents = this.Contents();
      if (Contents instanceof PDFArray_default) {
        Contents.insert(0, startStream);
        Contents.push(endStream);
        return true;
      }
      return false;
    };
    PDFPageLeaf2.prototype.addAnnot = function(annotRef) {
      var Annots = this.normalizedEntries().Annots;
      Annots.push(annotRef);
    };
    PDFPageLeaf2.prototype.removeAnnot = function(annotRef) {
      var Annots = this.normalizedEntries().Annots;
      var index = Annots.indexOf(annotRef);
      if (index !== void 0) {
        Annots.remove(index);
      }
    };
    PDFPageLeaf2.prototype.setFontDictionary = function(name, fontDictRef) {
      var Font2 = this.normalizedEntries().Font;
      Font2.set(name, fontDictRef);
    };
    PDFPageLeaf2.prototype.newFontDictionaryKey = function(tag) {
      var Font2 = this.normalizedEntries().Font;
      return Font2.uniqueKey(tag);
    };
    PDFPageLeaf2.prototype.newFontDictionary = function(tag, fontDictRef) {
      var key = this.newFontDictionaryKey(tag);
      this.setFontDictionary(key, fontDictRef);
      return key;
    };
    PDFPageLeaf2.prototype.setXObject = function(name, xObjectRef) {
      var XObject = this.normalizedEntries().XObject;
      XObject.set(name, xObjectRef);
    };
    PDFPageLeaf2.prototype.newXObjectKey = function(tag) {
      var XObject = this.normalizedEntries().XObject;
      return XObject.uniqueKey(tag);
    };
    PDFPageLeaf2.prototype.newXObject = function(tag, xObjectRef) {
      var key = this.newXObjectKey(tag);
      this.setXObject(key, xObjectRef);
      return key;
    };
    PDFPageLeaf2.prototype.setExtGState = function(name, extGStateRef) {
      var ExtGState = this.normalizedEntries().ExtGState;
      ExtGState.set(name, extGStateRef);
    };
    PDFPageLeaf2.prototype.newExtGStateKey = function(tag) {
      var ExtGState = this.normalizedEntries().ExtGState;
      return ExtGState.uniqueKey(tag);
    };
    PDFPageLeaf2.prototype.newExtGState = function(tag, extGStateRef) {
      var key = this.newExtGStateKey(tag);
      this.setExtGState(key, extGStateRef);
      return key;
    };
    PDFPageLeaf2.prototype.ascend = function(visitor) {
      visitor(this);
      var Parent = this.Parent();
      if (Parent)
        Parent.ascend(visitor);
    };
    PDFPageLeaf2.prototype.normalize = function() {
      if (this.normalized)
        return;
      var context = this.context;
      var contentsRef = this.get(PDFName_default.Contents);
      var contents = this.context.lookup(contentsRef);
      if (contents instanceof PDFStream_default) {
        this.set(PDFName_default.Contents, context.obj([contentsRef]));
      }
      if (this.autoNormalizeCTM) {
        this.wrapContentStreams(this.context.getPushGraphicsStateContentStream(), this.context.getPopGraphicsStateContentStream());
      }
      var dictOrRef = this.getInheritableAttribute(PDFName_default.Resources);
      var Resources = context.lookupMaybe(dictOrRef, PDFDict_default) || context.obj({});
      this.set(PDFName_default.Resources, Resources);
      var Font2 = Resources.lookupMaybe(PDFName_default.Font, PDFDict_default) || context.obj({});
      Resources.set(PDFName_default.Font, Font2);
      var XObject = Resources.lookupMaybe(PDFName_default.XObject, PDFDict_default) || context.obj({});
      Resources.set(PDFName_default.XObject, XObject);
      var ExtGState = Resources.lookupMaybe(PDFName_default.ExtGState, PDFDict_default) || context.obj({});
      Resources.set(PDFName_default.ExtGState, ExtGState);
      var Annots = this.Annots() || context.obj([]);
      this.set(PDFName_default.Annots, Annots);
      this.normalized = true;
    };
    PDFPageLeaf2.prototype.normalizedEntries = function() {
      this.normalize();
      var Annots = this.Annots();
      var Resources = this.Resources();
      var Contents = this.Contents();
      return {
        Annots,
        Resources,
        Contents,
        Font: Resources.lookup(PDFName_default.Font, PDFDict_default),
        XObject: Resources.lookup(PDFName_default.XObject, PDFDict_default),
        ExtGState: Resources.lookup(PDFName_default.ExtGState, PDFDict_default)
      };
    };
    PDFPageLeaf2.InheritableEntries = [
      "Resources",
      "MediaBox",
      "CropBox",
      "Rotate"
    ];
    PDFPageLeaf2.withContextAndParent = function(context, parent) {
      var dict = /* @__PURE__ */ new Map();
      dict.set(PDFName_default.Type, PDFName_default.Page);
      dict.set(PDFName_default.Parent, parent);
      dict.set(PDFName_default.Resources, context.obj({}));
      dict.set(PDFName_default.MediaBox, context.obj([0, 0, 612, 792]));
      return new PDFPageLeaf2(dict, context, false);
    };
    PDFPageLeaf2.fromMapWithContext = function(map, context, autoNormalizeCTM) {
      if (autoNormalizeCTM === void 0) {
        autoNormalizeCTM = true;
      }
      return new PDFPageLeaf2(map, context, autoNormalizeCTM);
    };
    return PDFPageLeaf2;
  }(PDFDict_default)
);
var PDFPageLeaf_default = PDFPageLeaf;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/PDFObjectCopier.js
var PDFObjectCopier = (
  /** @class */
  function() {
    function PDFObjectCopier2(src, dest) {
      var _this = this;
      this.traversedObjects = /* @__PURE__ */ new Map();
      this.copy = function(object) {
        return object instanceof PDFPageLeaf_default ? _this.copyPDFPage(object) : object instanceof PDFDict_default ? _this.copyPDFDict(object) : object instanceof PDFArray_default ? _this.copyPDFArray(object) : object instanceof PDFStream_default ? _this.copyPDFStream(object) : object instanceof PDFRef_default ? _this.copyPDFIndirectObject(object) : object.clone();
      };
      this.copyPDFPage = function(originalPage) {
        var clonedPage = originalPage.clone();
        var InheritableEntries = PDFPageLeaf_default.InheritableEntries;
        for (var idx = 0, len = InheritableEntries.length; idx < len; idx++) {
          var key = PDFName_default.of(InheritableEntries[idx]);
          var value = clonedPage.getInheritableAttribute(key);
          if (!clonedPage.get(key) && value)
            clonedPage.set(key, value);
        }
        clonedPage.delete(PDFName_default.of("Parent"));
        return _this.copyPDFDict(clonedPage);
      };
      this.copyPDFDict = function(originalDict) {
        if (_this.traversedObjects.has(originalDict)) {
          return _this.traversedObjects.get(originalDict);
        }
        var clonedDict = originalDict.clone(_this.dest);
        _this.traversedObjects.set(originalDict, clonedDict);
        var entries = originalDict.entries();
        for (var idx = 0, len = entries.length; idx < len; idx++) {
          var _a = entries[idx], key = _a[0], value = _a[1];
          clonedDict.set(key, _this.copy(value));
        }
        return clonedDict;
      };
      this.copyPDFArray = function(originalArray) {
        if (_this.traversedObjects.has(originalArray)) {
          return _this.traversedObjects.get(originalArray);
        }
        var clonedArray = originalArray.clone(_this.dest);
        _this.traversedObjects.set(originalArray, clonedArray);
        for (var idx = 0, len = originalArray.size(); idx < len; idx++) {
          var value = originalArray.get(idx);
          clonedArray.set(idx, _this.copy(value));
        }
        return clonedArray;
      };
      this.copyPDFStream = function(originalStream) {
        if (_this.traversedObjects.has(originalStream)) {
          return _this.traversedObjects.get(originalStream);
        }
        var clonedStream = originalStream.clone(_this.dest);
        _this.traversedObjects.set(originalStream, clonedStream);
        var entries = originalStream.dict.entries();
        for (var idx = 0, len = entries.length; idx < len; idx++) {
          var _a = entries[idx], key = _a[0], value = _a[1];
          clonedStream.dict.set(key, _this.copy(value));
        }
        return clonedStream;
      };
      this.copyPDFIndirectObject = function(ref) {
        var alreadyMapped = _this.traversedObjects.has(ref);
        if (!alreadyMapped) {
          var newRef = _this.dest.nextRef();
          _this.traversedObjects.set(ref, newRef);
          var dereferencedValue = _this.src.lookup(ref);
          if (dereferencedValue) {
            var cloned = _this.copy(dereferencedValue);
            _this.dest.assign(newRef, cloned);
          }
        }
        return _this.traversedObjects.get(ref);
      };
      this.src = src;
      this.dest = dest;
    }
    PDFObjectCopier2.for = function(src, dest) {
      return new PDFObjectCopier2(src, dest);
    };
    return PDFObjectCopier2;
  }()
);
var PDFObjectCopier_default = PDFObjectCopier;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/document/PDFCrossRefSection.js
var PDFCrossRefSection = (
  /** @class */
  function() {
    function PDFCrossRefSection2(firstEntry) {
      this.subsections = firstEntry ? [[firstEntry]] : [];
      this.chunkIdx = 0;
      this.chunkLength = firstEntry ? 1 : 0;
    }
    PDFCrossRefSection2.prototype.addEntry = function(ref, offset) {
      this.append({ ref, offset, deleted: false });
    };
    PDFCrossRefSection2.prototype.addDeletedEntry = function(ref, nextFreeObjectNumber) {
      this.append({ ref, offset: nextFreeObjectNumber, deleted: true });
    };
    PDFCrossRefSection2.prototype.toString = function() {
      var section = "xref\n";
      for (var rangeIdx = 0, rangeLen = this.subsections.length; rangeIdx < rangeLen; rangeIdx++) {
        var range2 = this.subsections[rangeIdx];
        section += range2[0].ref.objectNumber + " " + range2.length + "\n";
        for (var entryIdx = 0, entryLen = range2.length; entryIdx < entryLen; entryIdx++) {
          var entry = range2[entryIdx];
          section += padStart(String(entry.offset), 10, "0");
          section += " ";
          section += padStart(String(entry.ref.generationNumber), 5, "0");
          section += " ";
          section += entry.deleted ? "f" : "n";
          section += " \n";
        }
      }
      return section;
    };
    PDFCrossRefSection2.prototype.sizeInBytes = function() {
      var size = 5;
      for (var idx = 0, len = this.subsections.length; idx < len; idx++) {
        var subsection = this.subsections[idx];
        var subsectionLength = subsection.length;
        var firstEntry = subsection[0];
        size += 2;
        size += String(firstEntry.ref.objectNumber).length;
        size += String(subsectionLength).length;
        size += 20 * subsectionLength;
      }
      return size;
    };
    PDFCrossRefSection2.prototype.copyBytesInto = function(buffer, offset) {
      var initialOffset = offset;
      buffer[offset++] = CharCodes_default.x;
      buffer[offset++] = CharCodes_default.r;
      buffer[offset++] = CharCodes_default.e;
      buffer[offset++] = CharCodes_default.f;
      buffer[offset++] = CharCodes_default.Newline;
      offset += this.copySubsectionsIntoBuffer(this.subsections, buffer, offset);
      return offset - initialOffset;
    };
    PDFCrossRefSection2.prototype.copySubsectionsIntoBuffer = function(subsections, buffer, offset) {
      var initialOffset = offset;
      var length = subsections.length;
      for (var idx = 0; idx < length; idx++) {
        var subsection = this.subsections[idx];
        var firstObjectNumber = String(subsection[0].ref.objectNumber);
        offset += copyStringIntoBuffer(firstObjectNumber, buffer, offset);
        buffer[offset++] = CharCodes_default.Space;
        var rangeLength = String(subsection.length);
        offset += copyStringIntoBuffer(rangeLength, buffer, offset);
        buffer[offset++] = CharCodes_default.Newline;
        offset += this.copyEntriesIntoBuffer(subsection, buffer, offset);
      }
      return offset - initialOffset;
    };
    PDFCrossRefSection2.prototype.copyEntriesIntoBuffer = function(entries, buffer, offset) {
      var length = entries.length;
      for (var idx = 0; idx < length; idx++) {
        var entry = entries[idx];
        var entryOffset = padStart(String(entry.offset), 10, "0");
        offset += copyStringIntoBuffer(entryOffset, buffer, offset);
        buffer[offset++] = CharCodes_default.Space;
        var entryGen = padStart(String(entry.ref.generationNumber), 5, "0");
        offset += copyStringIntoBuffer(entryGen, buffer, offset);
        buffer[offset++] = CharCodes_default.Space;
        buffer[offset++] = entry.deleted ? CharCodes_default.f : CharCodes_default.n;
        buffer[offset++] = CharCodes_default.Space;
        buffer[offset++] = CharCodes_default.Newline;
      }
      return 20 * length;
    };
    PDFCrossRefSection2.prototype.append = function(currEntry) {
      if (this.chunkLength === 0) {
        this.subsections.push([currEntry]);
        this.chunkIdx = 0;
        this.chunkLength = 1;
        return;
      }
      var chunk = this.subsections[this.chunkIdx];
      var prevEntry = chunk[this.chunkLength - 1];
      if (currEntry.ref.objectNumber - prevEntry.ref.objectNumber > 1) {
        this.subsections.push([currEntry]);
        this.chunkIdx += 1;
        this.chunkLength = 1;
      } else {
        chunk.push(currEntry);
        this.chunkLength += 1;
      }
    };
    PDFCrossRefSection2.create = function() {
      return new PDFCrossRefSection2({
        ref: PDFRef_default.of(0, 65535),
        offset: 0,
        deleted: true
      });
    };
    PDFCrossRefSection2.createEmpty = function() {
      return new PDFCrossRefSection2();
    };
    return PDFCrossRefSection2;
  }()
);
var PDFCrossRefSection_default = PDFCrossRefSection;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/document/PDFTrailer.js
var PDFTrailer = (
  /** @class */
  function() {
    function PDFTrailer2(lastXRefOffset) {
      this.lastXRefOffset = String(lastXRefOffset);
    }
    PDFTrailer2.prototype.toString = function() {
      return "startxref\n" + this.lastXRefOffset + "\n%%EOF";
    };
    PDFTrailer2.prototype.sizeInBytes = function() {
      return 16 + this.lastXRefOffset.length;
    };
    PDFTrailer2.prototype.copyBytesInto = function(buffer, offset) {
      var initialOffset = offset;
      buffer[offset++] = CharCodes_default.s;
      buffer[offset++] = CharCodes_default.t;
      buffer[offset++] = CharCodes_default.a;
      buffer[offset++] = CharCodes_default.r;
      buffer[offset++] = CharCodes_default.t;
      buffer[offset++] = CharCodes_default.x;
      buffer[offset++] = CharCodes_default.r;
      buffer[offset++] = CharCodes_default.e;
      buffer[offset++] = CharCodes_default.f;
      buffer[offset++] = CharCodes_default.Newline;
      offset += copyStringIntoBuffer(this.lastXRefOffset, buffer, offset);
      buffer[offset++] = CharCodes_default.Newline;
      buffer[offset++] = CharCodes_default.Percent;
      buffer[offset++] = CharCodes_default.Percent;
      buffer[offset++] = CharCodes_default.E;
      buffer[offset++] = CharCodes_default.O;
      buffer[offset++] = CharCodes_default.F;
      return offset - initialOffset;
    };
    PDFTrailer2.forLastCrossRefSectionOffset = function(offset) {
      return new PDFTrailer2(offset);
    };
    return PDFTrailer2;
  }()
);
var PDFTrailer_default = PDFTrailer;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/document/PDFTrailerDict.js
var PDFTrailerDict = (
  /** @class */
  function() {
    function PDFTrailerDict2(dict) {
      this.dict = dict;
    }
    PDFTrailerDict2.prototype.toString = function() {
      return "trailer\n" + this.dict.toString();
    };
    PDFTrailerDict2.prototype.sizeInBytes = function() {
      return 8 + this.dict.sizeInBytes();
    };
    PDFTrailerDict2.prototype.copyBytesInto = function(buffer, offset) {
      var initialOffset = offset;
      buffer[offset++] = CharCodes_default.t;
      buffer[offset++] = CharCodes_default.r;
      buffer[offset++] = CharCodes_default.a;
      buffer[offset++] = CharCodes_default.i;
      buffer[offset++] = CharCodes_default.l;
      buffer[offset++] = CharCodes_default.e;
      buffer[offset++] = CharCodes_default.r;
      buffer[offset++] = CharCodes_default.Newline;
      offset += this.dict.copyBytesInto(buffer, offset);
      return offset - initialOffset;
    };
    PDFTrailerDict2.of = function(dict) {
      return new PDFTrailerDict2(dict);
    };
    return PDFTrailerDict2;
  }()
);
var PDFTrailerDict_default = PDFTrailerDict;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/structures/PDFObjectStream.js
var PDFObjectStream = (
  /** @class */
  function(_super) {
    __extends(PDFObjectStream2, _super);
    function PDFObjectStream2(context, objects, encode) {
      if (encode === void 0) {
        encode = true;
      }
      var _this = _super.call(this, context.obj({}), encode) || this;
      _this.objects = objects;
      _this.offsets = _this.computeObjectOffsets();
      _this.offsetsString = _this.computeOffsetsString();
      _this.dict.set(PDFName_default.of("Type"), PDFName_default.of("ObjStm"));
      _this.dict.set(PDFName_default.of("N"), PDFNumber_default.of(_this.objects.length));
      _this.dict.set(PDFName_default.of("First"), PDFNumber_default.of(_this.offsetsString.length));
      return _this;
    }
    PDFObjectStream2.prototype.getObjectsCount = function() {
      return this.objects.length;
    };
    PDFObjectStream2.prototype.clone = function(context) {
      return PDFObjectStream2.withContextAndObjects(context || this.dict.context, this.objects.slice(), this.encode);
    };
    PDFObjectStream2.prototype.getContentsString = function() {
      var value = this.offsetsString;
      for (var idx = 0, len = this.objects.length; idx < len; idx++) {
        var _a = this.objects[idx], object = _a[1];
        value += object + "\n";
      }
      return value;
    };
    PDFObjectStream2.prototype.getUnencodedContents = function() {
      var buffer = new Uint8Array(this.getUnencodedContentsSize());
      var offset = copyStringIntoBuffer(this.offsetsString, buffer, 0);
      for (var idx = 0, len = this.objects.length; idx < len; idx++) {
        var _a = this.objects[idx], object = _a[1];
        offset += object.copyBytesInto(buffer, offset);
        buffer[offset++] = CharCodes_default.Newline;
      }
      return buffer;
    };
    PDFObjectStream2.prototype.getUnencodedContentsSize = function() {
      return this.offsetsString.length + last(this.offsets)[1] + last(this.objects)[1].sizeInBytes() + 1;
    };
    PDFObjectStream2.prototype.computeOffsetsString = function() {
      var offsetsString = "";
      for (var idx = 0, len = this.offsets.length; idx < len; idx++) {
        var _a = this.offsets[idx], objectNumber = _a[0], offset = _a[1];
        offsetsString += objectNumber + " " + offset + " ";
      }
      return offsetsString;
    };
    PDFObjectStream2.prototype.computeObjectOffsets = function() {
      var offset = 0;
      var offsets = new Array(this.objects.length);
      for (var idx = 0, len = this.objects.length; idx < len; idx++) {
        var _a = this.objects[idx], ref = _a[0], object = _a[1];
        offsets[idx] = [ref.objectNumber, offset];
        offset += object.sizeInBytes() + 1;
      }
      return offsets;
    };
    PDFObjectStream2.withContextAndObjects = function(context, objects, encode) {
      if (encode === void 0) {
        encode = true;
      }
      return new PDFObjectStream2(context, objects, encode);
    };
    return PDFObjectStream2;
  }(PDFFlateStream_default)
);
var PDFObjectStream_default = PDFObjectStream;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/writers/PDFWriter.js
var PDFWriter = (
  /** @class */
  function() {
    function PDFWriter2(context, objectsPerTick) {
      var _this = this;
      this.parsedObjects = 0;
      this.shouldWaitForTick = function(n) {
        _this.parsedObjects += n;
        return _this.parsedObjects % _this.objectsPerTick === 0;
      };
      this.context = context;
      this.objectsPerTick = objectsPerTick;
    }
    PDFWriter2.prototype.serializeToBuffer = function() {
      return __awaiter(this, void 0, void 0, function() {
        var _a, size, header, indirectObjects, xref, trailerDict, trailer, offset, buffer, idx, len, _b, ref, object, objectNumber, generationNumber, n;
        return __generator(this, function(_c) {
          switch (_c.label) {
            case 0:
              return [4, this.computeBufferSize()];
            case 1:
              _a = _c.sent(), size = _a.size, header = _a.header, indirectObjects = _a.indirectObjects, xref = _a.xref, trailerDict = _a.trailerDict, trailer = _a.trailer;
              offset = 0;
              buffer = new Uint8Array(size);
              offset += header.copyBytesInto(buffer, offset);
              buffer[offset++] = CharCodes_default.Newline;
              buffer[offset++] = CharCodes_default.Newline;
              idx = 0, len = indirectObjects.length;
              _c.label = 2;
            case 2:
              if (!(idx < len)) return [3, 5];
              _b = indirectObjects[idx], ref = _b[0], object = _b[1];
              objectNumber = String(ref.objectNumber);
              offset += copyStringIntoBuffer(objectNumber, buffer, offset);
              buffer[offset++] = CharCodes_default.Space;
              generationNumber = String(ref.generationNumber);
              offset += copyStringIntoBuffer(generationNumber, buffer, offset);
              buffer[offset++] = CharCodes_default.Space;
              buffer[offset++] = CharCodes_default.o;
              buffer[offset++] = CharCodes_default.b;
              buffer[offset++] = CharCodes_default.j;
              buffer[offset++] = CharCodes_default.Newline;
              offset += object.copyBytesInto(buffer, offset);
              buffer[offset++] = CharCodes_default.Newline;
              buffer[offset++] = CharCodes_default.e;
              buffer[offset++] = CharCodes_default.n;
              buffer[offset++] = CharCodes_default.d;
              buffer[offset++] = CharCodes_default.o;
              buffer[offset++] = CharCodes_default.b;
              buffer[offset++] = CharCodes_default.j;
              buffer[offset++] = CharCodes_default.Newline;
              buffer[offset++] = CharCodes_default.Newline;
              n = object instanceof PDFObjectStream_default ? object.getObjectsCount() : 1;
              if (!this.shouldWaitForTick(n)) return [3, 4];
              return [4, waitForTick()];
            case 3:
              _c.sent();
              _c.label = 4;
            case 4:
              idx++;
              return [3, 2];
            case 5:
              if (xref) {
                offset += xref.copyBytesInto(buffer, offset);
                buffer[offset++] = CharCodes_default.Newline;
              }
              if (trailerDict) {
                offset += trailerDict.copyBytesInto(buffer, offset);
                buffer[offset++] = CharCodes_default.Newline;
                buffer[offset++] = CharCodes_default.Newline;
              }
              offset += trailer.copyBytesInto(buffer, offset);
              return [2, buffer];
          }
        });
      });
    };
    PDFWriter2.prototype.computeIndirectObjectSize = function(_a) {
      var ref = _a[0], object = _a[1];
      var refSize = ref.sizeInBytes() + 3;
      var objectSize = object.sizeInBytes() + 9;
      return refSize + objectSize;
    };
    PDFWriter2.prototype.createTrailerDict = function() {
      return this.context.obj({
        Size: this.context.largestObjectNumber + 1,
        Root: this.context.trailerInfo.Root,
        Encrypt: this.context.trailerInfo.Encrypt,
        Info: this.context.trailerInfo.Info,
        ID: this.context.trailerInfo.ID
      });
    };
    PDFWriter2.prototype.computeBufferSize = function() {
      return __awaiter(this, void 0, void 0, function() {
        var header, size, xref, indirectObjects, idx, len, indirectObject, ref, xrefOffset, trailerDict, trailer;
        return __generator(this, function(_a) {
          switch (_a.label) {
            case 0:
              header = PDFHeader_default.forVersion(1, 7);
              size = header.sizeInBytes() + 2;
              xref = PDFCrossRefSection_default.create();
              indirectObjects = this.context.enumerateIndirectObjects();
              idx = 0, len = indirectObjects.length;
              _a.label = 1;
            case 1:
              if (!(idx < len)) return [3, 4];
              indirectObject = indirectObjects[idx];
              ref = indirectObject[0];
              xref.addEntry(ref, size);
              size += this.computeIndirectObjectSize(indirectObject);
              if (!this.shouldWaitForTick(1)) return [3, 3];
              return [4, waitForTick()];
            case 2:
              _a.sent();
              _a.label = 3;
            case 3:
              idx++;
              return [3, 1];
            case 4:
              xrefOffset = size;
              size += xref.sizeInBytes() + 1;
              trailerDict = PDFTrailerDict_default.of(this.createTrailerDict());
              size += trailerDict.sizeInBytes() + 2;
              trailer = PDFTrailer_default.forLastCrossRefSectionOffset(xrefOffset);
              size += trailer.sizeInBytes();
              return [2, { size, header, indirectObjects, xref, trailerDict, trailer }];
          }
        });
      });
    };
    PDFWriter2.forContext = function(context, objectsPerTick) {
      return new PDFWriter2(context, objectsPerTick);
    };
    return PDFWriter2;
  }()
);
var PDFWriter_default = PDFWriter;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/objects/PDFInvalidObject.js
var PDFInvalidObject = (
  /** @class */
  function(_super) {
    __extends(PDFInvalidObject2, _super);
    function PDFInvalidObject2(data) {
      var _this = _super.call(this) || this;
      _this.data = data;
      return _this;
    }
    PDFInvalidObject2.prototype.clone = function() {
      return PDFInvalidObject2.of(this.data.slice());
    };
    PDFInvalidObject2.prototype.toString = function() {
      return "PDFInvalidObject(" + this.data.length + " bytes)";
    };
    PDFInvalidObject2.prototype.sizeInBytes = function() {
      return this.data.length;
    };
    PDFInvalidObject2.prototype.copyBytesInto = function(buffer, offset) {
      var length = this.data.length;
      for (var idx = 0; idx < length; idx++) {
        buffer[offset++] = this.data[idx];
      }
      return length;
    };
    PDFInvalidObject2.of = function(data) {
      return new PDFInvalidObject2(data);
    };
    return PDFInvalidObject2;
  }(PDFObject_default)
);
var PDFInvalidObject_default = PDFInvalidObject;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/structures/PDFCrossRefStream.js
var EntryType;
(function(EntryType2) {
  EntryType2[EntryType2["Deleted"] = 0] = "Deleted";
  EntryType2[EntryType2["Uncompressed"] = 1] = "Uncompressed";
  EntryType2[EntryType2["Compressed"] = 2] = "Compressed";
})(EntryType || (EntryType = {}));
var PDFCrossRefStream = (
  /** @class */
  function(_super) {
    __extends(PDFCrossRefStream2, _super);
    function PDFCrossRefStream2(dict, entries, encode) {
      if (encode === void 0) {
        encode = true;
      }
      var _this = _super.call(this, dict, encode) || this;
      _this.computeIndex = function() {
        var subsections = [];
        var subsectionLength = 0;
        for (var idx = 0, len = _this.entries.length; idx < len; idx++) {
          var currEntry = _this.entries[idx];
          var prevEntry = _this.entries[idx - 1];
          if (idx === 0) {
            subsections.push(currEntry.ref.objectNumber);
          } else if (currEntry.ref.objectNumber - prevEntry.ref.objectNumber > 1) {
            subsections.push(subsectionLength);
            subsections.push(currEntry.ref.objectNumber);
            subsectionLength = 0;
          }
          subsectionLength += 1;
        }
        subsections.push(subsectionLength);
        return subsections;
      };
      _this.computeEntryTuples = function() {
        var entryTuples = new Array(_this.entries.length);
        for (var idx = 0, len = _this.entries.length; idx < len; idx++) {
          var entry = _this.entries[idx];
          if (entry.type === EntryType.Deleted) {
            var type = entry.type, nextFreeObjectNumber = entry.nextFreeObjectNumber, ref = entry.ref;
            entryTuples[idx] = [type, nextFreeObjectNumber, ref.generationNumber];
          }
          if (entry.type === EntryType.Uncompressed) {
            var type = entry.type, offset = entry.offset, ref = entry.ref;
            entryTuples[idx] = [type, offset, ref.generationNumber];
          }
          if (entry.type === EntryType.Compressed) {
            var type = entry.type, objectStreamRef = entry.objectStreamRef, index = entry.index;
            entryTuples[idx] = [type, objectStreamRef.objectNumber, index];
          }
        }
        return entryTuples;
      };
      _this.computeMaxEntryByteWidths = function() {
        var entryTuples = _this.entryTuplesCache.access();
        var widths = [0, 0, 0];
        for (var idx = 0, len = entryTuples.length; idx < len; idx++) {
          var _a = entryTuples[idx], first = _a[0], second = _a[1], third = _a[2];
          var firstSize = sizeInBytes(first);
          var secondSize = sizeInBytes(second);
          var thirdSize = sizeInBytes(third);
          if (firstSize > widths[0])
            widths[0] = firstSize;
          if (secondSize > widths[1])
            widths[1] = secondSize;
          if (thirdSize > widths[2])
            widths[2] = thirdSize;
        }
        return widths;
      };
      _this.entries = entries || [];
      _this.entryTuplesCache = Cache_default.populatedBy(_this.computeEntryTuples);
      _this.maxByteWidthsCache = Cache_default.populatedBy(_this.computeMaxEntryByteWidths);
      _this.indexCache = Cache_default.populatedBy(_this.computeIndex);
      dict.set(PDFName_default.of("Type"), PDFName_default.of("XRef"));
      return _this;
    }
    PDFCrossRefStream2.prototype.addDeletedEntry = function(ref, nextFreeObjectNumber) {
      var type = EntryType.Deleted;
      this.entries.push({ type, ref, nextFreeObjectNumber });
      this.entryTuplesCache.invalidate();
      this.maxByteWidthsCache.invalidate();
      this.indexCache.invalidate();
      this.contentsCache.invalidate();
    };
    PDFCrossRefStream2.prototype.addUncompressedEntry = function(ref, offset) {
      var type = EntryType.Uncompressed;
      this.entries.push({ type, ref, offset });
      this.entryTuplesCache.invalidate();
      this.maxByteWidthsCache.invalidate();
      this.indexCache.invalidate();
      this.contentsCache.invalidate();
    };
    PDFCrossRefStream2.prototype.addCompressedEntry = function(ref, objectStreamRef, index) {
      var type = EntryType.Compressed;
      this.entries.push({ type, ref, objectStreamRef, index });
      this.entryTuplesCache.invalidate();
      this.maxByteWidthsCache.invalidate();
      this.indexCache.invalidate();
      this.contentsCache.invalidate();
    };
    PDFCrossRefStream2.prototype.clone = function(context) {
      var _a = this, dict = _a.dict, entries = _a.entries, encode = _a.encode;
      return PDFCrossRefStream2.of(dict.clone(context), entries.slice(), encode);
    };
    PDFCrossRefStream2.prototype.getContentsString = function() {
      var entryTuples = this.entryTuplesCache.access();
      var byteWidths = this.maxByteWidthsCache.access();
      var value = "";
      for (var entryIdx = 0, entriesLen = entryTuples.length; entryIdx < entriesLen; entryIdx++) {
        var _a = entryTuples[entryIdx], first = _a[0], second = _a[1], third = _a[2];
        var firstBytes = reverseArray(bytesFor(first));
        var secondBytes = reverseArray(bytesFor(second));
        var thirdBytes = reverseArray(bytesFor(third));
        for (var idx = byteWidths[0] - 1; idx >= 0; idx--) {
          value += (firstBytes[idx] || 0).toString(2);
        }
        for (var idx = byteWidths[1] - 1; idx >= 0; idx--) {
          value += (secondBytes[idx] || 0).toString(2);
        }
        for (var idx = byteWidths[2] - 1; idx >= 0; idx--) {
          value += (thirdBytes[idx] || 0).toString(2);
        }
      }
      return value;
    };
    PDFCrossRefStream2.prototype.getUnencodedContents = function() {
      var entryTuples = this.entryTuplesCache.access();
      var byteWidths = this.maxByteWidthsCache.access();
      var buffer = new Uint8Array(this.getUnencodedContentsSize());
      var offset = 0;
      for (var entryIdx = 0, entriesLen = entryTuples.length; entryIdx < entriesLen; entryIdx++) {
        var _a = entryTuples[entryIdx], first = _a[0], second = _a[1], third = _a[2];
        var firstBytes = reverseArray(bytesFor(first));
        var secondBytes = reverseArray(bytesFor(second));
        var thirdBytes = reverseArray(bytesFor(third));
        for (var idx = byteWidths[0] - 1; idx >= 0; idx--) {
          buffer[offset++] = firstBytes[idx] || 0;
        }
        for (var idx = byteWidths[1] - 1; idx >= 0; idx--) {
          buffer[offset++] = secondBytes[idx] || 0;
        }
        for (var idx = byteWidths[2] - 1; idx >= 0; idx--) {
          buffer[offset++] = thirdBytes[idx] || 0;
        }
      }
      return buffer;
    };
    PDFCrossRefStream2.prototype.getUnencodedContentsSize = function() {
      var byteWidths = this.maxByteWidthsCache.access();
      var entryWidth = sum(byteWidths);
      return entryWidth * this.entries.length;
    };
    PDFCrossRefStream2.prototype.updateDict = function() {
      _super.prototype.updateDict.call(this);
      var byteWidths = this.maxByteWidthsCache.access();
      var index = this.indexCache.access();
      var context = this.dict.context;
      this.dict.set(PDFName_default.of("W"), context.obj(byteWidths));
      this.dict.set(PDFName_default.of("Index"), context.obj(index));
    };
    PDFCrossRefStream2.create = function(dict, encode) {
      if (encode === void 0) {
        encode = true;
      }
      var stream2 = new PDFCrossRefStream2(dict, [], encode);
      stream2.addDeletedEntry(PDFRef_default.of(0, 65535), 0);
      return stream2;
    };
    PDFCrossRefStream2.of = function(dict, entries, encode) {
      if (encode === void 0) {
        encode = true;
      }
      return new PDFCrossRefStream2(dict, entries, encode);
    };
    return PDFCrossRefStream2;
  }(PDFFlateStream_default)
);
var PDFCrossRefStream_default = PDFCrossRefStream;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/writers/PDFStreamWriter.js
var PDFStreamWriter = (
  /** @class */
  function(_super) {
    __extends(PDFStreamWriter2, _super);
    function PDFStreamWriter2(context, objectsPerTick, encodeStreams, objectsPerStream) {
      var _this = _super.call(this, context, objectsPerTick) || this;
      _this.encodeStreams = encodeStreams;
      _this.objectsPerStream = objectsPerStream;
      return _this;
    }
    PDFStreamWriter2.prototype.computeBufferSize = function() {
      return __awaiter(this, void 0, void 0, function() {
        var objectNumber, header, size, xrefStream, uncompressedObjects, compressedObjects, objectStreamRefs, indirectObjects, idx, len, indirectObject, ref, object, shouldNotCompress, chunk, objectStreamRef, idx, len, chunk, ref, objectStream, xrefStreamRef, xrefOffset, trailer;
        return __generator(this, function(_a) {
          switch (_a.label) {
            case 0:
              objectNumber = this.context.largestObjectNumber + 1;
              header = PDFHeader_default.forVersion(1, 7);
              size = header.sizeInBytes() + 2;
              xrefStream = PDFCrossRefStream_default.create(this.createTrailerDict(), this.encodeStreams);
              uncompressedObjects = [];
              compressedObjects = [];
              objectStreamRefs = [];
              indirectObjects = this.context.enumerateIndirectObjects();
              idx = 0, len = indirectObjects.length;
              _a.label = 1;
            case 1:
              if (!(idx < len)) return [3, 6];
              indirectObject = indirectObjects[idx];
              ref = indirectObject[0], object = indirectObject[1];
              shouldNotCompress = ref === this.context.trailerInfo.Encrypt || object instanceof PDFStream_default || object instanceof PDFInvalidObject_default || ref.generationNumber !== 0;
              if (!shouldNotCompress) return [3, 4];
              uncompressedObjects.push(indirectObject);
              xrefStream.addUncompressedEntry(ref, size);
              size += this.computeIndirectObjectSize(indirectObject);
              if (!this.shouldWaitForTick(1)) return [3, 3];
              return [4, waitForTick()];
            case 2:
              _a.sent();
              _a.label = 3;
            case 3:
              return [3, 5];
            case 4:
              chunk = last(compressedObjects);
              objectStreamRef = last(objectStreamRefs);
              if (!chunk || chunk.length % this.objectsPerStream === 0) {
                chunk = [];
                compressedObjects.push(chunk);
                objectStreamRef = PDFRef_default.of(objectNumber++);
                objectStreamRefs.push(objectStreamRef);
              }
              xrefStream.addCompressedEntry(ref, objectStreamRef, chunk.length);
              chunk.push(indirectObject);
              _a.label = 5;
            case 5:
              idx++;
              return [3, 1];
            case 6:
              idx = 0, len = compressedObjects.length;
              _a.label = 7;
            case 7:
              if (!(idx < len)) return [3, 10];
              chunk = compressedObjects[idx];
              ref = objectStreamRefs[idx];
              objectStream = PDFObjectStream_default.withContextAndObjects(this.context, chunk, this.encodeStreams);
              xrefStream.addUncompressedEntry(ref, size);
              size += this.computeIndirectObjectSize([ref, objectStream]);
              uncompressedObjects.push([ref, objectStream]);
              if (!this.shouldWaitForTick(chunk.length)) return [3, 9];
              return [4, waitForTick()];
            case 8:
              _a.sent();
              _a.label = 9;
            case 9:
              idx++;
              return [3, 7];
            case 10:
              xrefStreamRef = PDFRef_default.of(objectNumber++);
              xrefStream.dict.set(PDFName_default.of("Size"), PDFNumber_default.of(objectNumber));
              xrefStream.addUncompressedEntry(xrefStreamRef, size);
              xrefOffset = size;
              size += this.computeIndirectObjectSize([xrefStreamRef, xrefStream]);
              uncompressedObjects.push([xrefStreamRef, xrefStream]);
              trailer = PDFTrailer_default.forLastCrossRefSectionOffset(xrefOffset);
              size += trailer.sizeInBytes();
              return [2, { size, header, indirectObjects: uncompressedObjects, trailer }];
          }
        });
      });
    };
    PDFStreamWriter2.forContext = function(context, objectsPerTick, encodeStreams, objectsPerStream) {
      if (encodeStreams === void 0) {
        encodeStreams = true;
      }
      if (objectsPerStream === void 0) {
        objectsPerStream = 50;
      }
      return new PDFStreamWriter2(context, objectsPerTick, encodeStreams, objectsPerStream);
    };
    return PDFStreamWriter2;
  }(PDFWriter_default)
);
var PDFStreamWriter_default = PDFStreamWriter;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/objects/PDFHexString.js
var PDFHexString = (
  /** @class */
  function(_super) {
    __extends(PDFHexString2, _super);
    function PDFHexString2(value) {
      var _this = _super.call(this) || this;
      _this.value = value;
      return _this;
    }
    PDFHexString2.prototype.asBytes = function() {
      var hex = this.value + (this.value.length % 2 === 1 ? "0" : "");
      var hexLength = hex.length;
      var bytes = new Uint8Array(hex.length / 2);
      var hexOffset = 0;
      var bytesOffset = 0;
      while (hexOffset < hexLength) {
        var byte = parseInt(hex.substring(hexOffset, hexOffset + 2), 16);
        bytes[bytesOffset] = byte;
        hexOffset += 2;
        bytesOffset += 1;
      }
      return bytes;
    };
    PDFHexString2.prototype.decodeText = function() {
      var bytes = this.asBytes();
      if (hasUtf16BOM(bytes))
        return utf16Decode(bytes);
      return pdfDocEncodingDecode(bytes);
    };
    PDFHexString2.prototype.decodeDate = function() {
      var text = this.decodeText();
      var date = parseDate(text);
      if (!date)
        throw new InvalidPDFDateStringError(text);
      return date;
    };
    PDFHexString2.prototype.asString = function() {
      return this.value;
    };
    PDFHexString2.prototype.clone = function() {
      return PDFHexString2.of(this.value);
    };
    PDFHexString2.prototype.toString = function() {
      return "<" + this.value + ">";
    };
    PDFHexString2.prototype.sizeInBytes = function() {
      return this.value.length + 2;
    };
    PDFHexString2.prototype.copyBytesInto = function(buffer, offset) {
      buffer[offset++] = CharCodes_default.LessThan;
      offset += copyStringIntoBuffer(this.value, buffer, offset);
      buffer[offset++] = CharCodes_default.GreaterThan;
      return this.value.length + 2;
    };
    PDFHexString2.of = function(value) {
      return new PDFHexString2(value);
    };
    PDFHexString2.fromText = function(value) {
      var encoded = utf16Encode(value);
      var hex = "";
      for (var idx = 0, len = encoded.length; idx < len; idx++) {
        hex += toHexStringOfMinLength(encoded[idx], 4);
      }
      return new PDFHexString2(hex);
    };
    return PDFHexString2;
  }(PDFObject_default)
);
var PDFHexString_default = PDFHexString;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/embedders/StandardFontEmbedder.js
var StandardFontEmbedder = (
  /** @class */
  function() {
    function StandardFontEmbedder2(fontName, customName) {
      this.encoding = fontName === FontNames.ZapfDingbats ? Encodings.ZapfDingbats : fontName === FontNames.Symbol ? Encodings.Symbol : Encodings.WinAnsi;
      this.font = Font.load(fontName);
      this.fontName = this.font.FontName;
      this.customName = customName;
    }
    StandardFontEmbedder2.prototype.encodeText = function(text) {
      var glyphs = this.encodeTextAsGlyphs(text);
      var hexCodes = new Array(glyphs.length);
      for (var idx = 0, len = glyphs.length; idx < len; idx++) {
        hexCodes[idx] = toHexString(glyphs[idx].code);
      }
      return PDFHexString_default.of(hexCodes.join(""));
    };
    StandardFontEmbedder2.prototype.widthOfTextAtSize = function(text, size) {
      var glyphs = this.encodeTextAsGlyphs(text);
      var totalWidth = 0;
      for (var idx = 0, len = glyphs.length; idx < len; idx++) {
        var left = glyphs[idx].name;
        var right = (glyphs[idx + 1] || {}).name;
        var kernAmount = this.font.getXAxisKerningForPair(left, right) || 0;
        totalWidth += this.widthOfGlyph(left) + kernAmount;
      }
      var scale2 = size / 1e3;
      return totalWidth * scale2;
    };
    StandardFontEmbedder2.prototype.heightOfFontAtSize = function(size, options) {
      if (options === void 0) {
        options = {};
      }
      var _a = options.descender, descender = _a === void 0 ? true : _a;
      var _b = this.font, Ascender = _b.Ascender, Descender = _b.Descender, FontBBox = _b.FontBBox;
      var yTop = Ascender || FontBBox[3];
      var yBottom = Descender || FontBBox[1];
      var height = yTop - yBottom;
      if (!descender)
        height += Descender || 0;
      return height / 1e3 * size;
    };
    StandardFontEmbedder2.prototype.sizeOfFontAtHeight = function(height) {
      var _a = this.font, Ascender = _a.Ascender, Descender = _a.Descender, FontBBox = _a.FontBBox;
      var yTop = Ascender || FontBBox[3];
      var yBottom = Descender || FontBBox[1];
      return 1e3 * height / (yTop - yBottom);
    };
    StandardFontEmbedder2.prototype.embedIntoContext = function(context, ref) {
      var fontDict = context.obj({
        Type: "Font",
        Subtype: "Type1",
        BaseFont: this.customName || this.fontName,
        Encoding: this.encoding === Encodings.WinAnsi ? "WinAnsiEncoding" : void 0
      });
      if (ref) {
        context.assign(ref, fontDict);
        return ref;
      } else {
        return context.register(fontDict);
      }
    };
    StandardFontEmbedder2.prototype.widthOfGlyph = function(glyphName) {
      return this.font.getWidthOfGlyph(glyphName) || 250;
    };
    StandardFontEmbedder2.prototype.encodeTextAsGlyphs = function(text) {
      var codePoints = Array.from(text);
      var glyphs = new Array(codePoints.length);
      for (var idx = 0, len = codePoints.length; idx < len; idx++) {
        var codePoint = toCodePoint(codePoints[idx]);
        glyphs[idx] = this.encoding.encodeUnicodeCodePoint(codePoint);
      }
      return glyphs;
    };
    StandardFontEmbedder2.for = function(fontName, customName) {
      return new StandardFontEmbedder2(fontName, customName);
    };
    return StandardFontEmbedder2;
  }()
);
var StandardFontEmbedder_default = StandardFontEmbedder;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/embedders/CMap.js
var createCmap = function(glyphs, glyphId) {
  var bfChars = new Array(glyphs.length);
  for (var idx = 0, len = glyphs.length; idx < len; idx++) {
    var glyph = glyphs[idx];
    var id = cmapHexFormat(cmapHexString(glyphId(glyph)));
    var unicode = cmapHexFormat.apply(void 0, glyph.codePoints.map(cmapCodePointFormat));
    bfChars[idx] = [id, unicode];
  }
  return fillCmapTemplate(bfChars);
};
var fillCmapTemplate = function(bfChars) {
  return "/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n/CIDSystemInfo <<\n  /Registry (Adobe)\n  /Ordering (UCS)\n  /Supplement 0\n>> def\n/CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n1 begincodespacerange\n<0000><ffff>\nendcodespacerange\n" + bfChars.length + " beginbfchar\n" + bfChars.map(function(_a) {
    var glyphId = _a[0], codePoint = _a[1];
    return glyphId + " " + codePoint;
  }).join("\n") + "\nendbfchar\nendcmap\nCMapName currentdict /CMap defineresource pop\nend\nend";
};
var cmapHexFormat = function() {
  var values2 = [];
  for (var _i = 0; _i < arguments.length; _i++) {
    values2[_i] = arguments[_i];
  }
  return "<" + values2.join("") + ">";
};
var cmapHexString = function(value) {
  return toHexStringOfMinLength(value, 4);
};
var cmapCodePointFormat = function(codePoint) {
  if (isWithinBMP(codePoint))
    return cmapHexString(codePoint);
  if (hasSurrogates(codePoint)) {
    var hs = highSurrogate(codePoint);
    var ls = lowSurrogate(codePoint);
    return "" + cmapHexString(hs) + cmapHexString(ls);
  }
  var hex = toHexString(codePoint);
  var msg = "0x" + hex + " is not a valid UTF-8 or UTF-16 codepoint.";
  throw new Error(msg);
};

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/embedders/FontFlags.js
var makeFontFlags = function(options) {
  var flags = 0;
  var flipBit = function(bit) {
    flags |= 1 << bit - 1;
  };
  if (options.fixedPitch)
    flipBit(1);
  if (options.serif)
    flipBit(2);
  if (options.symbolic)
    flipBit(3);
  if (options.script)
    flipBit(4);
  if (options.nonsymbolic)
    flipBit(6);
  if (options.italic)
    flipBit(7);
  if (options.allCap)
    flipBit(17);
  if (options.smallCap)
    flipBit(18);
  if (options.forceBold)
    flipBit(19);
  return flags;
};
var deriveFontFlags = function(font) {
  var familyClass = font["OS/2"] ? font["OS/2"].sFamilyClass : 0;
  var flags = makeFontFlags({
    fixedPitch: font.post.isFixedPitch,
    serif: 1 <= familyClass && familyClass <= 7,
    symbolic: true,
    script: familyClass === 10,
    italic: font.head.macStyle.italic
  });
  return flags;
};

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/objects/PDFString.js
var PDFString = (
  /** @class */
  function(_super) {
    __extends(PDFString2, _super);
    function PDFString2(value) {
      var _this = _super.call(this) || this;
      _this.value = value;
      return _this;
    }
    PDFString2.prototype.asBytes = function() {
      var bytes = [];
      var octal = "";
      var escaped = false;
      var pushByte = function(byte2) {
        if (byte2 !== void 0)
          bytes.push(byte2);
        escaped = false;
      };
      for (var idx = 0, len = this.value.length; idx < len; idx++) {
        var char = this.value[idx];
        var byte = toCharCode(char);
        var nextChar = this.value[idx + 1];
        if (!escaped) {
          if (byte === CharCodes_default.BackSlash)
            escaped = true;
          else
            pushByte(byte);
        } else {
          if (byte === CharCodes_default.Newline)
            pushByte();
          else if (byte === CharCodes_default.CarriageReturn)
            pushByte();
          else if (byte === CharCodes_default.n)
            pushByte(CharCodes_default.Newline);
          else if (byte === CharCodes_default.r)
            pushByte(CharCodes_default.CarriageReturn);
          else if (byte === CharCodes_default.t)
            pushByte(CharCodes_default.Tab);
          else if (byte === CharCodes_default.b)
            pushByte(CharCodes_default.Backspace);
          else if (byte === CharCodes_default.f)
            pushByte(CharCodes_default.FormFeed);
          else if (byte === CharCodes_default.LeftParen)
            pushByte(CharCodes_default.LeftParen);
          else if (byte === CharCodes_default.RightParen)
            pushByte(CharCodes_default.RightParen);
          else if (byte === CharCodes_default.Backspace)
            pushByte(CharCodes_default.BackSlash);
          else if (byte >= CharCodes_default.Zero && byte <= CharCodes_default.Seven) {
            octal += char;
            if (octal.length === 3 || !(nextChar >= "0" && nextChar <= "7")) {
              pushByte(parseInt(octal, 8));
              octal = "";
            }
          } else {
            pushByte(byte);
          }
        }
      }
      return new Uint8Array(bytes);
    };
    PDFString2.prototype.decodeText = function() {
      var bytes = this.asBytes();
      if (hasUtf16BOM(bytes))
        return utf16Decode(bytes);
      return pdfDocEncodingDecode(bytes);
    };
    PDFString2.prototype.decodeDate = function() {
      var text = this.decodeText();
      var date = parseDate(text);
      if (!date)
        throw new InvalidPDFDateStringError(text);
      return date;
    };
    PDFString2.prototype.asString = function() {
      return this.value;
    };
    PDFString2.prototype.clone = function() {
      return PDFString2.of(this.value);
    };
    PDFString2.prototype.toString = function() {
      return "(" + this.value + ")";
    };
    PDFString2.prototype.sizeInBytes = function() {
      return this.value.length + 2;
    };
    PDFString2.prototype.copyBytesInto = function(buffer, offset) {
      buffer[offset++] = CharCodes_default.LeftParen;
      offset += copyStringIntoBuffer(this.value, buffer, offset);
      buffer[offset++] = CharCodes_default.RightParen;
      return this.value.length + 2;
    };
    PDFString2.of = function(value) {
      return new PDFString2(value);
    };
    PDFString2.fromDate = function(date) {
      var year = padStart(String(date.getUTCFullYear()), 4, "0");
      var month = padStart(String(date.getUTCMonth() + 1), 2, "0");
      var day = padStart(String(date.getUTCDate()), 2, "0");
      var hours = padStart(String(date.getUTCHours()), 2, "0");
      var mins = padStart(String(date.getUTCMinutes()), 2, "0");
      var secs = padStart(String(date.getUTCSeconds()), 2, "0");
      return new PDFString2("D:" + year + month + day + hours + mins + secs + "Z");
    };
    return PDFString2;
  }(PDFObject_default)
);
var PDFString_default = PDFString;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/embedders/CustomFontEmbedder.js
var CustomFontEmbedder = (
  /** @class */
  function() {
    function CustomFontEmbedder2(font, fontData, customName, fontFeatures) {
      var _this = this;
      this.allGlyphsInFontSortedById = function() {
        var glyphs = new Array(_this.font.characterSet.length);
        for (var idx = 0, len = glyphs.length; idx < len; idx++) {
          var codePoint = _this.font.characterSet[idx];
          glyphs[idx] = _this.font.glyphForCodePoint(codePoint);
        }
        return sortedUniq(glyphs.sort(byAscendingId), function(g) {
          return g.id;
        });
      };
      this.font = font;
      this.scale = 1e3 / this.font.unitsPerEm;
      this.fontData = fontData;
      this.fontName = this.font.postscriptName || "Font";
      this.customName = customName;
      this.fontFeatures = fontFeatures;
      this.baseFontName = "";
      this.glyphCache = Cache_default.populatedBy(this.allGlyphsInFontSortedById);
    }
    CustomFontEmbedder2.for = function(fontkit, fontData, customName, fontFeatures) {
      return __awaiter(this, void 0, void 0, function() {
        var font;
        return __generator(this, function(_a) {
          switch (_a.label) {
            case 0:
              return [4, fontkit.create(fontData)];
            case 1:
              font = _a.sent();
              return [2, new CustomFontEmbedder2(font, fontData, customName, fontFeatures)];
          }
        });
      });
    };
    CustomFontEmbedder2.prototype.encodeText = function(text) {
      var glyphs = this.font.layout(text, this.fontFeatures).glyphs;
      var hexCodes = new Array(glyphs.length);
      for (var idx = 0, len = glyphs.length; idx < len; idx++) {
        hexCodes[idx] = toHexStringOfMinLength(glyphs[idx].id, 4);
      }
      return PDFHexString_default.of(hexCodes.join(""));
    };
    CustomFontEmbedder2.prototype.widthOfTextAtSize = function(text, size) {
      var glyphs = this.font.layout(text, this.fontFeatures).glyphs;
      var totalWidth = 0;
      for (var idx = 0, len = glyphs.length; idx < len; idx++) {
        totalWidth += glyphs[idx].advanceWidth * this.scale;
      }
      var scale2 = size / 1e3;
      return totalWidth * scale2;
    };
    CustomFontEmbedder2.prototype.heightOfFontAtSize = function(size, options) {
      if (options === void 0) {
        options = {};
      }
      var _a = options.descender, descender = _a === void 0 ? true : _a;
      var _b = this.font, ascent = _b.ascent, descent = _b.descent, bbox = _b.bbox;
      var yTop = (ascent || bbox.maxY) * this.scale;
      var yBottom = (descent || bbox.minY) * this.scale;
      var height = yTop - yBottom;
      if (!descender)
        height -= Math.abs(descent) || 0;
      return height / 1e3 * size;
    };
    CustomFontEmbedder2.prototype.sizeOfFontAtHeight = function(height) {
      var _a = this.font, ascent = _a.ascent, descent = _a.descent, bbox = _a.bbox;
      var yTop = (ascent || bbox.maxY) * this.scale;
      var yBottom = (descent || bbox.minY) * this.scale;
      return 1e3 * height / (yTop - yBottom);
    };
    CustomFontEmbedder2.prototype.embedIntoContext = function(context, ref) {
      this.baseFontName = this.customName || context.addRandomSuffix(this.fontName);
      return this.embedFontDict(context, ref);
    };
    CustomFontEmbedder2.prototype.embedFontDict = function(context, ref) {
      return __awaiter(this, void 0, void 0, function() {
        var cidFontDictRef, unicodeCMapRef, fontDict;
        return __generator(this, function(_a) {
          switch (_a.label) {
            case 0:
              return [4, this.embedCIDFontDict(context)];
            case 1:
              cidFontDictRef = _a.sent();
              unicodeCMapRef = this.embedUnicodeCmap(context);
              fontDict = context.obj({
                Type: "Font",
                Subtype: "Type0",
                BaseFont: this.baseFontName,
                Encoding: "Identity-H",
                DescendantFonts: [cidFontDictRef],
                ToUnicode: unicodeCMapRef
              });
              if (ref) {
                context.assign(ref, fontDict);
                return [2, ref];
              } else {
                return [2, context.register(fontDict)];
              }
              return [
                2
                /*return*/
              ];
          }
        });
      });
    };
    CustomFontEmbedder2.prototype.isCFF = function() {
      return this.font.cff;
    };
    CustomFontEmbedder2.prototype.embedCIDFontDict = function(context) {
      return __awaiter(this, void 0, void 0, function() {
        var fontDescriptorRef, cidFontDict;
        return __generator(this, function(_a) {
          switch (_a.label) {
            case 0:
              return [4, this.embedFontDescriptor(context)];
            case 1:
              fontDescriptorRef = _a.sent();
              cidFontDict = context.obj({
                Type: "Font",
                Subtype: this.isCFF() ? "CIDFontType0" : "CIDFontType2",
                CIDToGIDMap: "Identity",
                BaseFont: this.baseFontName,
                CIDSystemInfo: {
                  Registry: PDFString_default.of("Adobe"),
                  Ordering: PDFString_default.of("Identity"),
                  Supplement: 0
                },
                FontDescriptor: fontDescriptorRef,
                W: this.computeWidths()
              });
              return [2, context.register(cidFontDict)];
          }
        });
      });
    };
    CustomFontEmbedder2.prototype.embedFontDescriptor = function(context) {
      return __awaiter(this, void 0, void 0, function() {
        var fontStreamRef, scale2, _a, italicAngle, ascent, descent, capHeight, xHeight, _b, minX, minY, maxX, maxY, fontDescriptor;
        var _c;
        return __generator(this, function(_d) {
          switch (_d.label) {
            case 0:
              return [4, this.embedFontStream(context)];
            case 1:
              fontStreamRef = _d.sent();
              scale2 = this.scale;
              _a = this.font, italicAngle = _a.italicAngle, ascent = _a.ascent, descent = _a.descent, capHeight = _a.capHeight, xHeight = _a.xHeight;
              _b = this.font.bbox, minX = _b.minX, minY = _b.minY, maxX = _b.maxX, maxY = _b.maxY;
              fontDescriptor = context.obj((_c = {
                Type: "FontDescriptor",
                FontName: this.baseFontName,
                Flags: deriveFontFlags(this.font),
                FontBBox: [minX * scale2, minY * scale2, maxX * scale2, maxY * scale2],
                ItalicAngle: italicAngle,
                Ascent: ascent * scale2,
                Descent: descent * scale2,
                CapHeight: (capHeight || ascent) * scale2,
                XHeight: (xHeight || 0) * scale2,
                // Not sure how to compute/find this, nor is anybody else really:
                // https://stackoverflow.com/questions/35485179/stemv-value-of-the-truetype-font
                StemV: 0
              }, _c[this.isCFF() ? "FontFile3" : "FontFile2"] = fontStreamRef, _c));
              return [2, context.register(fontDescriptor)];
          }
        });
      });
    };
    CustomFontEmbedder2.prototype.serializeFont = function() {
      return __awaiter(this, void 0, void 0, function() {
        return __generator(this, function(_a) {
          return [2, this.fontData];
        });
      });
    };
    CustomFontEmbedder2.prototype.embedFontStream = function(context) {
      return __awaiter(this, void 0, void 0, function() {
        var fontStream, _a, _b;
        return __generator(this, function(_c) {
          switch (_c.label) {
            case 0:
              _b = (_a = context).flateStream;
              return [4, this.serializeFont()];
            case 1:
              fontStream = _b.apply(_a, [_c.sent(), {
                Subtype: this.isCFF() ? "CIDFontType0C" : void 0
              }]);
              return [2, context.register(fontStream)];
          }
        });
      });
    };
    CustomFontEmbedder2.prototype.embedUnicodeCmap = function(context) {
      var cmap = createCmap(this.glyphCache.access(), this.glyphId.bind(this));
      var cmapStream = context.flateStream(cmap);
      return context.register(cmapStream);
    };
    CustomFontEmbedder2.prototype.glyphId = function(glyph) {
      return glyph ? glyph.id : -1;
    };
    CustomFontEmbedder2.prototype.computeWidths = function() {
      var glyphs = this.glyphCache.access();
      var widths = [];
      var currSection = [];
      for (var idx = 0, len = glyphs.length; idx < len; idx++) {
        var currGlyph = glyphs[idx];
        var prevGlyph = glyphs[idx - 1];
        var currGlyphId = this.glyphId(currGlyph);
        var prevGlyphId = this.glyphId(prevGlyph);
        if (idx === 0) {
          widths.push(currGlyphId);
        } else if (currGlyphId - prevGlyphId !== 1) {
          widths.push(currSection);
          widths.push(currGlyphId);
          currSection = [];
        }
        currSection.push(currGlyph.advanceWidth * this.scale);
      }
      widths.push(currSection);
      return widths;
    };
    return CustomFontEmbedder2;
  }()
);
var CustomFontEmbedder_default = CustomFontEmbedder;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/embedders/CustomFontSubsetEmbedder.js
var CustomFontSubsetEmbedder = (
  /** @class */
  function(_super) {
    __extends(CustomFontSubsetEmbedder2, _super);
    function CustomFontSubsetEmbedder2(font, fontData, customFontName, fontFeatures) {
      var _this = _super.call(this, font, fontData, customFontName, fontFeatures) || this;
      _this.subset = _this.font.createSubset();
      _this.glyphs = [];
      _this.glyphCache = Cache_default.populatedBy(function() {
        return _this.glyphs;
      });
      _this.glyphIdMap = /* @__PURE__ */ new Map();
      return _this;
    }
    CustomFontSubsetEmbedder2.for = function(fontkit, fontData, customFontName, fontFeatures) {
      return __awaiter(this, void 0, void 0, function() {
        var font;
        return __generator(this, function(_a) {
          switch (_a.label) {
            case 0:
              return [4, fontkit.create(fontData)];
            case 1:
              font = _a.sent();
              return [2, new CustomFontSubsetEmbedder2(font, fontData, customFontName, fontFeatures)];
          }
        });
      });
    };
    CustomFontSubsetEmbedder2.prototype.encodeText = function(text) {
      var glyphs = this.font.layout(text, this.fontFeatures).glyphs;
      var hexCodes = new Array(glyphs.length);
      for (var idx = 0, len = glyphs.length; idx < len; idx++) {
        var glyph = glyphs[idx];
        var subsetGlyphId = this.subset.includeGlyph(glyph);
        this.glyphs[subsetGlyphId - 1] = glyph;
        this.glyphIdMap.set(glyph.id, subsetGlyphId);
        hexCodes[idx] = toHexStringOfMinLength(subsetGlyphId, 4);
      }
      this.glyphCache.invalidate();
      return PDFHexString_default.of(hexCodes.join(""));
    };
    CustomFontSubsetEmbedder2.prototype.isCFF = function() {
      return this.subset.cff;
    };
    CustomFontSubsetEmbedder2.prototype.glyphId = function(glyph) {
      return glyph ? this.glyphIdMap.get(glyph.id) : -1;
    };
    CustomFontSubsetEmbedder2.prototype.serializeFont = function() {
      var _this = this;
      return new Promise(function(resolve, reject) {
        var parts = [];
        _this.subset.encodeStream().on("data", function(bytes) {
          return parts.push(bytes);
        }).on("end", function() {
          return resolve(mergeUint8Arrays(parts));
        }).on("error", function(err) {
          return reject(err);
        });
      });
    };
    return CustomFontSubsetEmbedder2;
  }(CustomFontEmbedder_default)
);
var CustomFontSubsetEmbedder_default = CustomFontSubsetEmbedder;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/embedders/FileEmbedder.js
var AFRelationship;
(function(AFRelationship2) {
  AFRelationship2["Source"] = "Source";
  AFRelationship2["Data"] = "Data";
  AFRelationship2["Alternative"] = "Alternative";
  AFRelationship2["Supplement"] = "Supplement";
  AFRelationship2["EncryptedPayload"] = "EncryptedPayload";
  AFRelationship2["FormData"] = "EncryptedPayload";
  AFRelationship2["Schema"] = "Schema";
  AFRelationship2["Unspecified"] = "Unspecified";
})(AFRelationship || (AFRelationship = {}));
var FileEmbedder = (
  /** @class */
  function() {
    function FileEmbedder2(fileData, fileName, options) {
      if (options === void 0) {
        options = {};
      }
      this.fileData = fileData;
      this.fileName = fileName;
      this.options = options;
    }
    FileEmbedder2.for = function(bytes, fileName, options) {
      if (options === void 0) {
        options = {};
      }
      return new FileEmbedder2(bytes, fileName, options);
    };
    FileEmbedder2.prototype.embedIntoContext = function(context, ref) {
      return __awaiter(this, void 0, void 0, function() {
        var _a, mimeType, description, creationDate, modificationDate, afRelationship, embeddedFileStream, embeddedFileStreamRef, fileSpecDict;
        return __generator(this, function(_b) {
          _a = this.options, mimeType = _a.mimeType, description = _a.description, creationDate = _a.creationDate, modificationDate = _a.modificationDate, afRelationship = _a.afRelationship;
          embeddedFileStream = context.flateStream(this.fileData, {
            Type: "EmbeddedFile",
            Subtype: mimeType !== null && mimeType !== void 0 ? mimeType : void 0,
            Params: {
              Size: this.fileData.length,
              CreationDate: creationDate ? PDFString_default.fromDate(creationDate) : void 0,
              ModDate: modificationDate ? PDFString_default.fromDate(modificationDate) : void 0
            }
          });
          embeddedFileStreamRef = context.register(embeddedFileStream);
          fileSpecDict = context.obj({
            Type: "Filespec",
            F: PDFString_default.of(this.fileName),
            UF: PDFHexString_default.fromText(this.fileName),
            EF: { F: embeddedFileStreamRef },
            Desc: description ? PDFHexString_default.fromText(description) : void 0,
            AFRelationship: afRelationship !== null && afRelationship !== void 0 ? afRelationship : void 0
          });
          if (ref) {
            context.assign(ref, fileSpecDict);
            return [2, ref];
          } else {
            return [2, context.register(fileSpecDict)];
          }
          return [
            2
            /*return*/
          ];
        });
      });
    };
    return FileEmbedder2;
  }()
);
var FileEmbedder_default = FileEmbedder;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/embedders/JpegEmbedder.js
var MARKERS = [
  65472,
  65473,
  65474,
  65475,
  65477,
  65478,
  65479,
  65480,
  65481,
  65482,
  65483,
  65484,
  65485,
  65486,
  65487
];
var ColorSpace;
(function(ColorSpace2) {
  ColorSpace2["DeviceGray"] = "DeviceGray";
  ColorSpace2["DeviceRGB"] = "DeviceRGB";
  ColorSpace2["DeviceCMYK"] = "DeviceCMYK";
})(ColorSpace || (ColorSpace = {}));
var ChannelToColorSpace = {
  1: ColorSpace.DeviceGray,
  3: ColorSpace.DeviceRGB,
  4: ColorSpace.DeviceCMYK
};
var JpegEmbedder = (
  /** @class */
  function() {
    function JpegEmbedder2(imageData, bitsPerComponent, width, height, colorSpace) {
      this.imageData = imageData;
      this.bitsPerComponent = bitsPerComponent;
      this.width = width;
      this.height = height;
      this.colorSpace = colorSpace;
    }
    JpegEmbedder2.for = function(imageData) {
      return __awaiter(this, void 0, void 0, function() {
        var dataView, soi, pos, marker, bitsPerComponent, height, width, channelByte, channelName, colorSpace;
        return __generator(this, function(_a) {
          dataView = new DataView(imageData.buffer);
          soi = dataView.getUint16(0);
          if (soi !== 65496)
            throw new Error("SOI not found in JPEG");
          pos = 2;
          while (pos < dataView.byteLength) {
            marker = dataView.getUint16(pos);
            pos += 2;
            if (MARKERS.includes(marker))
              break;
            pos += dataView.getUint16(pos);
          }
          if (!MARKERS.includes(marker))
            throw new Error("Invalid JPEG");
          pos += 2;
          bitsPerComponent = dataView.getUint8(pos++);
          height = dataView.getUint16(pos);
          pos += 2;
          width = dataView.getUint16(pos);
          pos += 2;
          channelByte = dataView.getUint8(pos++);
          channelName = ChannelToColorSpace[channelByte];
          if (!channelName)
            throw new Error("Unknown JPEG channel.");
          colorSpace = channelName;
          return [2, new JpegEmbedder2(imageData, bitsPerComponent, width, height, colorSpace)];
        });
      });
    };
    JpegEmbedder2.prototype.embedIntoContext = function(context, ref) {
      return __awaiter(this, void 0, void 0, function() {
        var xObject;
        return __generator(this, function(_a) {
          xObject = context.stream(this.imageData, {
            Type: "XObject",
            Subtype: "Image",
            BitsPerComponent: this.bitsPerComponent,
            Width: this.width,
            Height: this.height,
            ColorSpace: this.colorSpace,
            Filter: "DCTDecode",
            // CMYK JPEG streams in PDF are typically stored complemented,
            // with 1 as 'off' and 0 as 'on' (PDF 32000-1:2008, 8.6.4.4).
            //
            // Standalone CMYK JPEG (usually exported by Photoshop) are
            // stored inverse, with 0 as 'off' and 1 as 'on', like RGB.
            //
            // Applying a swap here as a hedge that most bytes passing
            // through this method will benefit from it.
            Decode: this.colorSpace === ColorSpace.DeviceCMYK ? [1, 0, 1, 0, 1, 0, 1, 0] : void 0
          });
          if (ref) {
            context.assign(ref, xObject);
            return [2, ref];
          } else {
            return [2, context.register(xObject)];
          }
          return [
            2
            /*return*/
          ];
        });
      });
    };
    return JpegEmbedder2;
  }()
);
var JpegEmbedder_default = JpegEmbedder;

// node_modules/.pnpm/@pdf-lib+upng@1.0.1/node_modules/@pdf-lib/upng/UPNG.js
var import_pako4 = __toESM(require_pako());
var UPNG = {};
UPNG.toRGBA8 = function(out) {
  var w = out.width, h = out.height;
  if (out.tabs.acTL == null) return [UPNG.toRGBA8.decodeImage(out.data, w, h, out).buffer];
  var frms = [];
  if (out.frames[0].data == null) out.frames[0].data = out.data;
  var len = w * h * 4, img = new Uint8Array(len), empty = new Uint8Array(len), prev = new Uint8Array(len);
  for (var i = 0; i < out.frames.length; i++) {
    var frm = out.frames[i];
    var fx = frm.rect.x, fy = frm.rect.y, fw = frm.rect.width, fh = frm.rect.height;
    var fdata = UPNG.toRGBA8.decodeImage(frm.data, fw, fh, out);
    if (i != 0) for (var j = 0; j < len; j++) prev[j] = img[j];
    if (frm.blend == 0) UPNG._copyTile(fdata, fw, fh, img, w, h, fx, fy, 0);
    else if (frm.blend == 1) UPNG._copyTile(fdata, fw, fh, img, w, h, fx, fy, 1);
    frms.push(img.buffer.slice(0));
    if (frm.dispose == 0) {
    } else if (frm.dispose == 1) UPNG._copyTile(empty, fw, fh, img, w, h, fx, fy, 0);
    else if (frm.dispose == 2) for (var j = 0; j < len; j++) img[j] = prev[j];
  }
  return frms;
};
UPNG.toRGBA8.decodeImage = function(data, w, h, out) {
  var area = w * h, bpp = UPNG.decode._getBPP(out);
  var bpl = Math.ceil(w * bpp / 8);
  var bf = new Uint8Array(area * 4), bf32 = new Uint32Array(bf.buffer);
  var ctype = out.ctype, depth = out.depth;
  var rs = UPNG._bin.readUshort;
  var time = Date.now();
  if (ctype == 6) {
    var qarea = area << 2;
    if (depth == 8) for (var i = 0; i < qarea; i += 4) {
      bf[i] = data[i];
      bf[i + 1] = data[i + 1];
      bf[i + 2] = data[i + 2];
      bf[i + 3] = data[i + 3];
    }
    if (depth == 16) for (var i = 0; i < qarea; i++) {
      bf[i] = data[i << 1];
    }
  } else if (ctype == 2) {
    var ts = out.tabs["tRNS"];
    if (ts == null) {
      if (depth == 8) for (var i = 0; i < area; i++) {
        var ti = i * 3;
        bf32[i] = 255 << 24 | data[ti + 2] << 16 | data[ti + 1] << 8 | data[ti];
      }
      if (depth == 16) for (var i = 0; i < area; i++) {
        var ti = i * 6;
        bf32[i] = 255 << 24 | data[ti + 4] << 16 | data[ti + 2] << 8 | data[ti];
      }
    } else {
      var tr = ts[0], tg = ts[1], tb = ts[2];
      if (depth == 8) for (var i = 0; i < area; i++) {
        var qi = i << 2, ti = i * 3;
        bf32[i] = 255 << 24 | data[ti + 2] << 16 | data[ti + 1] << 8 | data[ti];
        if (data[ti] == tr && data[ti + 1] == tg && data[ti + 2] == tb) bf[qi + 3] = 0;
      }
      if (depth == 16) for (var i = 0; i < area; i++) {
        var qi = i << 2, ti = i * 6;
        bf32[i] = 255 << 24 | data[ti + 4] << 16 | data[ti + 2] << 8 | data[ti];
        if (rs(data, ti) == tr && rs(data, ti + 2) == tg && rs(data, ti + 4) == tb) bf[qi + 3] = 0;
      }
    }
  } else if (ctype == 3) {
    var p = out.tabs["PLTE"], ap = out.tabs["tRNS"], tl = ap ? ap.length : 0;
    if (depth == 1) for (var y = 0; y < h; y++) {
      var s0 = y * bpl, t0 = y * w;
      for (var i = 0; i < w; i++) {
        var qi = t0 + i << 2, j = data[s0 + (i >> 3)] >> 7 - ((i & 7) << 0) & 1, cj = 3 * j;
        bf[qi] = p[cj];
        bf[qi + 1] = p[cj + 1];
        bf[qi + 2] = p[cj + 2];
        bf[qi + 3] = j < tl ? ap[j] : 255;
      }
    }
    if (depth == 2) for (var y = 0; y < h; y++) {
      var s0 = y * bpl, t0 = y * w;
      for (var i = 0; i < w; i++) {
        var qi = t0 + i << 2, j = data[s0 + (i >> 2)] >> 6 - ((i & 3) << 1) & 3, cj = 3 * j;
        bf[qi] = p[cj];
        bf[qi + 1] = p[cj + 1];
        bf[qi + 2] = p[cj + 2];
        bf[qi + 3] = j < tl ? ap[j] : 255;
      }
    }
    if (depth == 4) for (var y = 0; y < h; y++) {
      var s0 = y * bpl, t0 = y * w;
      for (var i = 0; i < w; i++) {
        var qi = t0 + i << 2, j = data[s0 + (i >> 1)] >> 4 - ((i & 1) << 2) & 15, cj = 3 * j;
        bf[qi] = p[cj];
        bf[qi + 1] = p[cj + 1];
        bf[qi + 2] = p[cj + 2];
        bf[qi + 3] = j < tl ? ap[j] : 255;
      }
    }
    if (depth == 8) for (var i = 0; i < area; i++) {
      var qi = i << 2, j = data[i], cj = 3 * j;
      bf[qi] = p[cj];
      bf[qi + 1] = p[cj + 1];
      bf[qi + 2] = p[cj + 2];
      bf[qi + 3] = j < tl ? ap[j] : 255;
    }
  } else if (ctype == 4) {
    if (depth == 8) for (var i = 0; i < area; i++) {
      var qi = i << 2, di = i << 1, gr = data[di];
      bf[qi] = gr;
      bf[qi + 1] = gr;
      bf[qi + 2] = gr;
      bf[qi + 3] = data[di + 1];
    }
    if (depth == 16) for (var i = 0; i < area; i++) {
      var qi = i << 2, di = i << 2, gr = data[di];
      bf[qi] = gr;
      bf[qi + 1] = gr;
      bf[qi + 2] = gr;
      bf[qi + 3] = data[di + 2];
    }
  } else if (ctype == 0) {
    var tr = out.tabs["tRNS"] ? out.tabs["tRNS"] : -1;
    for (var y = 0; y < h; y++) {
      var off = y * bpl, to = y * w;
      if (depth == 1) for (var x = 0; x < w; x++) {
        var gr = 255 * (data[off + (x >>> 3)] >>> 7 - (x & 7) & 1), al = gr == tr * 255 ? 0 : 255;
        bf32[to + x] = al << 24 | gr << 16 | gr << 8 | gr;
      }
      else if (depth == 2) for (var x = 0; x < w; x++) {
        var gr = 85 * (data[off + (x >>> 2)] >>> 6 - ((x & 3) << 1) & 3), al = gr == tr * 85 ? 0 : 255;
        bf32[to + x] = al << 24 | gr << 16 | gr << 8 | gr;
      }
      else if (depth == 4) for (var x = 0; x < w; x++) {
        var gr = 17 * (data[off + (x >>> 1)] >>> 4 - ((x & 1) << 2) & 15), al = gr == tr * 17 ? 0 : 255;
        bf32[to + x] = al << 24 | gr << 16 | gr << 8 | gr;
      }
      else if (depth == 8) for (var x = 0; x < w; x++) {
        var gr = data[off + x], al = gr == tr ? 0 : 255;
        bf32[to + x] = al << 24 | gr << 16 | gr << 8 | gr;
      }
      else if (depth == 16) for (var x = 0; x < w; x++) {
        var gr = data[off + (x << 1)], al = rs(data, off + (x << i)) == tr ? 0 : 255;
        bf32[to + x] = al << 24 | gr << 16 | gr << 8 | gr;
      }
    }
  }
  return bf;
};
UPNG.decode = function(buff) {
  var data = new Uint8Array(buff), offset = 8, bin = UPNG._bin, rUs = bin.readUshort, rUi = bin.readUint;
  var out = { tabs: {}, frames: [] };
  var dd = new Uint8Array(data.length), doff = 0;
  var fd, foff = 0;
  var mgck = [137, 80, 78, 71, 13, 10, 26, 10];
  for (var i = 0; i < 8; i++) if (data[i] != mgck[i]) throw "The input is not a PNG file!";
  while (offset < data.length) {
    var len = bin.readUint(data, offset);
    offset += 4;
    var type = bin.readASCII(data, offset, 4);
    offset += 4;
    if (type == "IHDR") {
      UPNG.decode._IHDR(data, offset, out);
    } else if (type == "IDAT") {
      for (var i = 0; i < len; i++) dd[doff + i] = data[offset + i];
      doff += len;
    } else if (type == "acTL") {
      out.tabs[type] = { num_frames: rUi(data, offset), num_plays: rUi(data, offset + 4) };
      fd = new Uint8Array(data.length);
    } else if (type == "fcTL") {
      if (foff != 0) {
        var fr = out.frames[out.frames.length - 1];
        fr.data = UPNG.decode._decompress(out, fd.slice(0, foff), fr.rect.width, fr.rect.height);
        foff = 0;
      }
      var rct = { x: rUi(data, offset + 12), y: rUi(data, offset + 16), width: rUi(data, offset + 4), height: rUi(data, offset + 8) };
      var del = rUs(data, offset + 22);
      del = rUs(data, offset + 20) / (del == 0 ? 100 : del);
      var frm = { rect: rct, delay: Math.round(del * 1e3), dispose: data[offset + 24], blend: data[offset + 25] };
      out.frames.push(frm);
    } else if (type == "fdAT") {
      for (var i = 0; i < len - 4; i++) fd[foff + i] = data[offset + i + 4];
      foff += len - 4;
    } else if (type == "pHYs") {
      out.tabs[type] = [bin.readUint(data, offset), bin.readUint(data, offset + 4), data[offset + 8]];
    } else if (type == "cHRM") {
      out.tabs[type] = [];
      for (var i = 0; i < 8; i++) out.tabs[type].push(bin.readUint(data, offset + i * 4));
    } else if (type == "tEXt") {
      if (out.tabs[type] == null) out.tabs[type] = {};
      var nz = bin.nextZero(data, offset);
      var keyw = bin.readASCII(data, offset, nz - offset);
      var text = bin.readASCII(data, nz + 1, offset + len - nz - 1);
      out.tabs[type][keyw] = text;
    } else if (type == "iTXt") {
      if (out.tabs[type] == null) out.tabs[type] = {};
      var nz = 0, off = offset;
      nz = bin.nextZero(data, off);
      var keyw = bin.readASCII(data, off, nz - off);
      off = nz + 1;
      var cflag = data[off], cmeth = data[off + 1];
      off += 2;
      nz = bin.nextZero(data, off);
      var ltag = bin.readASCII(data, off, nz - off);
      off = nz + 1;
      nz = bin.nextZero(data, off);
      var tkeyw = bin.readUTF8(data, off, nz - off);
      off = nz + 1;
      var text = bin.readUTF8(data, off, len - (off - offset));
      out.tabs[type][keyw] = text;
    } else if (type == "PLTE") {
      out.tabs[type] = bin.readBytes(data, offset, len);
    } else if (type == "hIST") {
      var pl = out.tabs["PLTE"].length / 3;
      out.tabs[type] = [];
      for (var i = 0; i < pl; i++) out.tabs[type].push(rUs(data, offset + i * 2));
    } else if (type == "tRNS") {
      if (out.ctype == 3) out.tabs[type] = bin.readBytes(data, offset, len);
      else if (out.ctype == 0) out.tabs[type] = rUs(data, offset);
      else if (out.ctype == 2) out.tabs[type] = [rUs(data, offset), rUs(data, offset + 2), rUs(data, offset + 4)];
    } else if (type == "gAMA") out.tabs[type] = bin.readUint(data, offset) / 1e5;
    else if (type == "sRGB") out.tabs[type] = data[offset];
    else if (type == "bKGD") {
      if (out.ctype == 0 || out.ctype == 4) out.tabs[type] = [rUs(data, offset)];
      else if (out.ctype == 2 || out.ctype == 6) out.tabs[type] = [rUs(data, offset), rUs(data, offset + 2), rUs(data, offset + 4)];
      else if (out.ctype == 3) out.tabs[type] = data[offset];
    } else if (type == "IEND") {
      break;
    }
    offset += len;
    var crc = bin.readUint(data, offset);
    offset += 4;
  }
  if (foff != 0) {
    var fr = out.frames[out.frames.length - 1];
    fr.data = UPNG.decode._decompress(out, fd.slice(0, foff), fr.rect.width, fr.rect.height);
    foff = 0;
  }
  out.data = UPNG.decode._decompress(out, dd, out.width, out.height);
  delete out.compress;
  delete out.interlace;
  delete out.filter;
  return out;
};
UPNG.decode._decompress = function(out, dd, w, h) {
  var time = Date.now();
  var bpp = UPNG.decode._getBPP(out), bpl = Math.ceil(w * bpp / 8), buff = new Uint8Array((bpl + 1 + out.interlace) * h);
  dd = UPNG.decode._inflate(dd, buff);
  var time = Date.now();
  if (out.interlace == 0) dd = UPNG.decode._filterZero(dd, out, 0, w, h);
  else if (out.interlace == 1) dd = UPNG.decode._readInterlace(dd, out);
  return dd;
};
UPNG.decode._inflate = function(data, buff) {
  var out = UPNG["inflateRaw"](new Uint8Array(data.buffer, 2, data.length - 6), buff);
  return out;
};
UPNG.inflateRaw = function() {
  var H = {};
  H.H = {};
  H.H.N = function(N, W) {
    var R = Uint8Array, i = 0, m = 0, J = 0, h = 0, Q = 0, X = 0, u = 0, w = 0, d = 0, v, C;
    if (N[0] == 3 && N[1] == 0) return W ? W : new R(0);
    var V = H.H, n = V.b, A = V.e, l = V.R, M = V.n, I = V.A, e = V.Z, b = V.m, Z = W == null;
    if (Z) W = new R(N.length >>> 2 << 3);
    while (i == 0) {
      i = n(N, d, 1);
      m = n(N, d + 1, 2);
      d += 3;
      if (m == 0) {
        if ((d & 7) != 0) d += 8 - (d & 7);
        var D = (d >>> 3) + 4, q = N[D - 4] | N[D - 3] << 8;
        if (Z) W = H.H.W(W, w + q);
        W.set(new R(N.buffer, N.byteOffset + D, q), w);
        d = D + q << 3;
        w += q;
        continue;
      }
      if (Z) W = H.H.W(W, w + (1 << 17));
      if (m == 1) {
        v = b.J;
        C = b.h;
        X = (1 << 9) - 1;
        u = (1 << 5) - 1;
      }
      if (m == 2) {
        J = A(N, d, 5) + 257;
        h = A(N, d + 5, 5) + 1;
        Q = A(N, d + 10, 4) + 4;
        d += 14;
        var E = d, j = 1;
        for (var c = 0; c < 38; c += 2) {
          b.Q[c] = 0;
          b.Q[c + 1] = 0;
        }
        for (var c = 0; c < Q; c++) {
          var K = A(N, d + c * 3, 3);
          b.Q[(b.X[c] << 1) + 1] = K;
          if (K > j) j = K;
        }
        d += 3 * Q;
        M(b.Q, j);
        I(b.Q, j, b.u);
        v = b.w;
        C = b.d;
        d = l(b.u, (1 << j) - 1, J + h, N, d, b.v);
        var r = V.V(b.v, 0, J, b.C);
        X = (1 << r) - 1;
        var S = V.V(b.v, J, h, b.D);
        u = (1 << S) - 1;
        M(b.C, r);
        I(b.C, r, v);
        M(b.D, S);
        I(b.D, S, C);
      }
      while (true) {
        var T = v[e(N, d) & X];
        d += T & 15;
        var p = T >>> 4;
        if (p >>> 8 == 0) {
          W[w++] = p;
        } else if (p == 256) {
          break;
        } else {
          var z = w + p - 254;
          if (p > 264) {
            var _ = b.q[p - 257];
            z = w + (_ >>> 3) + A(N, d, _ & 7);
            d += _ & 7;
          }
          var $ = C[e(N, d) & u];
          d += $ & 15;
          var s = $ >>> 4, Y = b.c[s], a = (Y >>> 4) + n(N, d, Y & 15);
          d += Y & 15;
          while (w < z) {
            W[w] = W[w++ - a];
            W[w] = W[w++ - a];
            W[w] = W[w++ - a];
            W[w] = W[w++ - a];
          }
          w = z;
        }
      }
    }
    return W.length == w ? W : W.slice(0, w);
  };
  H.H.W = function(N, W) {
    var R = N.length;
    if (W <= R) return N;
    var V = new Uint8Array(R << 1);
    V.set(N, 0);
    return V;
  };
  H.H.R = function(N, W, R, V, n, A) {
    var l = H.H.e, M = H.H.Z, I = 0;
    while (I < R) {
      var e = N[M(V, n) & W];
      n += e & 15;
      var b = e >>> 4;
      if (b <= 15) {
        A[I] = b;
        I++;
      } else {
        var Z = 0, m = 0;
        if (b == 16) {
          m = 3 + l(V, n, 2);
          n += 2;
          Z = A[I - 1];
        } else if (b == 17) {
          m = 3 + l(V, n, 3);
          n += 3;
        } else if (b == 18) {
          m = 11 + l(V, n, 7);
          n += 7;
        }
        var J = I + m;
        while (I < J) {
          A[I] = Z;
          I++;
        }
      }
    }
    return n;
  };
  H.H.V = function(N, W, R, V) {
    var n = 0, A = 0, l = V.length >>> 1;
    while (A < R) {
      var M = N[A + W];
      V[A << 1] = 0;
      V[(A << 1) + 1] = M;
      if (M > n) n = M;
      A++;
    }
    while (A < l) {
      V[A << 1] = 0;
      V[(A << 1) + 1] = 0;
      A++;
    }
    return n;
  };
  H.H.n = function(N, W) {
    var R = H.H.m, V = N.length, n, A, l, M, I, e = R.j;
    for (var M = 0; M <= W; M++) e[M] = 0;
    for (M = 1; M < V; M += 2) e[N[M]]++;
    var b = R.K;
    n = 0;
    e[0] = 0;
    for (A = 1; A <= W; A++) {
      n = n + e[A - 1] << 1;
      b[A] = n;
    }
    for (l = 0; l < V; l += 2) {
      I = N[l + 1];
      if (I != 0) {
        N[l] = b[I];
        b[I]++;
      }
    }
  };
  H.H.A = function(N, W, R) {
    var V = N.length, n = H.H.m, A = n.r;
    for (var l = 0; l < V; l += 2) if (N[l + 1] != 0) {
      var M = l >> 1, I = N[l + 1], e = M << 4 | I, b = W - I, Z = N[l] << b, m = Z + (1 << b);
      while (Z != m) {
        var J = A[Z] >>> 15 - W;
        R[J] = e;
        Z++;
      }
    }
  };
  H.H.l = function(N, W) {
    var R = H.H.m.r, V = 15 - W;
    for (var n = 0; n < N.length; n += 2) {
      var A = N[n] << W - N[n + 1];
      N[n] = R[A] >>> V;
    }
  };
  H.H.M = function(N, W, R) {
    R = R << (W & 7);
    var V = W >>> 3;
    N[V] |= R;
    N[V + 1] |= R >>> 8;
  };
  H.H.I = function(N, W, R) {
    R = R << (W & 7);
    var V = W >>> 3;
    N[V] |= R;
    N[V + 1] |= R >>> 8;
    N[V + 2] |= R >>> 16;
  };
  H.H.e = function(N, W, R) {
    return (N[W >>> 3] | N[(W >>> 3) + 1] << 8) >>> (W & 7) & (1 << R) - 1;
  };
  H.H.b = function(N, W, R) {
    return (N[W >>> 3] | N[(W >>> 3) + 1] << 8 | N[(W >>> 3) + 2] << 16) >>> (W & 7) & (1 << R) - 1;
  };
  H.H.Z = function(N, W) {
    return (N[W >>> 3] | N[(W >>> 3) + 1] << 8 | N[(W >>> 3) + 2] << 16) >>> (W & 7);
  };
  H.H.i = function(N, W) {
    return (N[W >>> 3] | N[(W >>> 3) + 1] << 8 | N[(W >>> 3) + 2] << 16 | N[(W >>> 3) + 3] << 24) >>> (W & 7);
  };
  H.H.m = function() {
    var N = Uint16Array, W = Uint32Array;
    return { K: new N(16), j: new N(16), X: [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15], S: [3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 999, 999, 999], T: [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0, 0], q: new N(32), p: [1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 65535, 65535], z: [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 0, 0], c: new W(32), J: new N(512), _: [], h: new N(32), $: [], w: new N(32768), C: [], v: [], d: new N(32768), D: [], u: new N(512), Q: [], r: new N(1 << 15), s: new W(286), Y: new W(30), a: new W(19), t: new W(15e3), k: new N(1 << 16), g: new N(1 << 15) };
  }();
  (function() {
    var N = H.H.m, W = 1 << 15;
    for (var R = 0; R < W; R++) {
      var V = R;
      V = (V & 2863311530) >>> 1 | (V & 1431655765) << 1;
      V = (V & 3435973836) >>> 2 | (V & 858993459) << 2;
      V = (V & 4042322160) >>> 4 | (V & 252645135) << 4;
      V = (V & 4278255360) >>> 8 | (V & 16711935) << 8;
      N.r[R] = (V >>> 16 | V << 16) >>> 17;
    }
    function n(A, l, M) {
      while (l-- != 0) A.push(0, M);
    }
    for (var R = 0; R < 32; R++) {
      N.q[R] = N.S[R] << 3 | N.T[R];
      N.c[R] = N.p[R] << 4 | N.z[R];
    }
    n(N._, 144, 8);
    n(N._, 255 - 143, 9);
    n(N._, 279 - 255, 7);
    n(N._, 287 - 279, 8);
    H.H.n(N._, 9);
    H.H.A(N._, 9, N.J);
    H.H.l(N._, 9);
    n(N.$, 32, 5);
    H.H.n(N.$, 5);
    H.H.A(N.$, 5, N.h);
    H.H.l(N.$, 5);
    n(N.Q, 19, 0);
    n(N.C, 286, 0);
    n(N.D, 30, 0);
    n(N.v, 320, 0);
  })();
  return H.H.N;
}();
UPNG.decode._readInterlace = function(data, out) {
  var w = out.width, h = out.height;
  var bpp = UPNG.decode._getBPP(out), cbpp = bpp >> 3, bpl = Math.ceil(w * bpp / 8);
  var img = new Uint8Array(h * bpl);
  var di = 0;
  var starting_row = [0, 0, 4, 0, 2, 0, 1];
  var starting_col = [0, 4, 0, 2, 0, 1, 0];
  var row_increment = [8, 8, 8, 4, 4, 2, 2];
  var col_increment = [8, 8, 4, 4, 2, 2, 1];
  var pass = 0;
  while (pass < 7) {
    var ri = row_increment[pass], ci = col_increment[pass];
    var sw = 0, sh = 0;
    var cr = starting_row[pass];
    while (cr < h) {
      cr += ri;
      sh++;
    }
    var cc = starting_col[pass];
    while (cc < w) {
      cc += ci;
      sw++;
    }
    var bpll = Math.ceil(sw * bpp / 8);
    UPNG.decode._filterZero(data, out, di, sw, sh);
    var y = 0, row = starting_row[pass];
    while (row < h) {
      var col = starting_col[pass];
      var cdi = di + y * bpll << 3;
      while (col < w) {
        if (bpp == 1) {
          var val = data[cdi >> 3];
          val = val >> 7 - (cdi & 7) & 1;
          img[row * bpl + (col >> 3)] |= val << 7 - ((col & 7) << 0);
        }
        if (bpp == 2) {
          var val = data[cdi >> 3];
          val = val >> 6 - (cdi & 7) & 3;
          img[row * bpl + (col >> 2)] |= val << 6 - ((col & 3) << 1);
        }
        if (bpp == 4) {
          var val = data[cdi >> 3];
          val = val >> 4 - (cdi & 7) & 15;
          img[row * bpl + (col >> 1)] |= val << 4 - ((col & 1) << 2);
        }
        if (bpp >= 8) {
          var ii = row * bpl + col * cbpp;
          for (var j = 0; j < cbpp; j++) img[ii + j] = data[(cdi >> 3) + j];
        }
        cdi += bpp;
        col += ci;
      }
      y++;
      row += ri;
    }
    if (sw * sh != 0) di += sh * (1 + bpll);
    pass = pass + 1;
  }
  return img;
};
UPNG.decode._getBPP = function(out) {
  var noc = [1, null, 3, 1, 2, null, 4][out.ctype];
  return noc * out.depth;
};
UPNG.decode._filterZero = function(data, out, off, w, h) {
  var bpp = UPNG.decode._getBPP(out), bpl = Math.ceil(w * bpp / 8), paeth = UPNG.decode._paeth;
  bpp = Math.ceil(bpp / 8);
  var i = 0, di = 1, type = data[off], x = 0;
  if (type > 1) data[off] = [0, 0, 1][type - 2];
  if (type == 3) for (x = bpp; x < bpl; x++) data[x + 1] = data[x + 1] + (data[x + 1 - bpp] >>> 1) & 255;
  for (var y = 0; y < h; y++) {
    i = off + y * bpl;
    di = i + y + 1;
    type = data[di - 1];
    x = 0;
    if (type == 0) for (; x < bpl; x++) data[i + x] = data[di + x];
    else if (type == 1) {
      for (; x < bpp; x++) data[i + x] = data[di + x];
      for (; x < bpl; x++) data[i + x] = data[di + x] + data[i + x - bpp];
    } else if (type == 2) {
      for (; x < bpl; x++) data[i + x] = data[di + x] + data[i + x - bpl];
    } else if (type == 3) {
      for (; x < bpp; x++) data[i + x] = data[di + x] + (data[i + x - bpl] >>> 1);
      for (; x < bpl; x++) data[i + x] = data[di + x] + (data[i + x - bpl] + data[i + x - bpp] >>> 1);
    } else {
      for (; x < bpp; x++) data[i + x] = data[di + x] + paeth(0, data[i + x - bpl], 0);
      for (; x < bpl; x++) data[i + x] = data[di + x] + paeth(data[i + x - bpp], data[i + x - bpl], data[i + x - bpp - bpl]);
    }
  }
  return data;
};
UPNG.decode._paeth = function(a, b, c) {
  var p = a + b - c, pa = p - a, pb = p - b, pc = p - c;
  if (pa * pa <= pb * pb && pa * pa <= pc * pc) return a;
  else if (pb * pb <= pc * pc) return b;
  return c;
};
UPNG.decode._IHDR = function(data, offset, out) {
  var bin = UPNG._bin;
  out.width = bin.readUint(data, offset);
  offset += 4;
  out.height = bin.readUint(data, offset);
  offset += 4;
  out.depth = data[offset];
  offset++;
  out.ctype = data[offset];
  offset++;
  out.compress = data[offset];
  offset++;
  out.filter = data[offset];
  offset++;
  out.interlace = data[offset];
  offset++;
};
UPNG._bin = {
  nextZero: function(data, p) {
    while (data[p] != 0) p++;
    return p;
  },
  readUshort: function(buff, p) {
    return buff[p] << 8 | buff[p + 1];
  },
  writeUshort: function(buff, p, n) {
    buff[p] = n >> 8 & 255;
    buff[p + 1] = n & 255;
  },
  readUint: function(buff, p) {
    return buff[p] * (256 * 256 * 256) + (buff[p + 1] << 16 | buff[p + 2] << 8 | buff[p + 3]);
  },
  writeUint: function(buff, p, n) {
    buff[p] = n >> 24 & 255;
    buff[p + 1] = n >> 16 & 255;
    buff[p + 2] = n >> 8 & 255;
    buff[p + 3] = n & 255;
  },
  readASCII: function(buff, p, l) {
    var s = "";
    for (var i = 0; i < l; i++) s += String.fromCharCode(buff[p + i]);
    return s;
  },
  writeASCII: function(data, p, s) {
    for (var i = 0; i < s.length; i++) data[p + i] = s.charCodeAt(i);
  },
  readBytes: function(buff, p, l) {
    var arr = [];
    for (var i = 0; i < l; i++) arr.push(buff[p + i]);
    return arr;
  },
  pad: function(n) {
    return n.length < 2 ? "0" + n : n;
  },
  readUTF8: function(buff, p, l) {
    var s = "", ns;
    for (var i = 0; i < l; i++) s += "%" + UPNG._bin.pad(buff[p + i].toString(16));
    try {
      ns = decodeURIComponent(s);
    } catch (e) {
      return UPNG._bin.readASCII(buff, p, l);
    }
    return ns;
  }
};
UPNG._copyTile = function(sb, sw, sh, tb, tw, th, xoff, yoff, mode) {
  var w = Math.min(sw, tw), h = Math.min(sh, th);
  var si = 0, ti = 0;
  for (var y = 0; y < h; y++)
    for (var x = 0; x < w; x++) {
      if (xoff >= 0 && yoff >= 0) {
        si = y * sw + x << 2;
        ti = (yoff + y) * tw + xoff + x << 2;
      } else {
        si = (-yoff + y) * sw - xoff + x << 2;
        ti = y * tw + x << 2;
      }
      if (mode == 0) {
        tb[ti] = sb[si];
        tb[ti + 1] = sb[si + 1];
        tb[ti + 2] = sb[si + 2];
        tb[ti + 3] = sb[si + 3];
      } else if (mode == 1) {
        var fa = sb[si + 3] * (1 / 255), fr = sb[si] * fa, fg = sb[si + 1] * fa, fb = sb[si + 2] * fa;
        var ba = tb[ti + 3] * (1 / 255), br = tb[ti] * ba, bg = tb[ti + 1] * ba, bb = tb[ti + 2] * ba;
        var ifa = 1 - fa, oa = fa + ba * ifa, ioa = oa == 0 ? 0 : 1 / oa;
        tb[ti + 3] = 255 * oa;
        tb[ti + 0] = (fr + br * ifa) * ioa;
        tb[ti + 1] = (fg + bg * ifa) * ioa;
        tb[ti + 2] = (fb + bb * ifa) * ioa;
      } else if (mode == 2) {
        var fa = sb[si + 3], fr = sb[si], fg = sb[si + 1], fb = sb[si + 2];
        var ba = tb[ti + 3], br = tb[ti], bg = tb[ti + 1], bb = tb[ti + 2];
        if (fa == ba && fr == br && fg == bg && fb == bb) {
          tb[ti] = 0;
          tb[ti + 1] = 0;
          tb[ti + 2] = 0;
          tb[ti + 3] = 0;
        } else {
          tb[ti] = fr;
          tb[ti + 1] = fg;
          tb[ti + 2] = fb;
          tb[ti + 3] = fa;
        }
      } else if (mode == 3) {
        var fa = sb[si + 3], fr = sb[si], fg = sb[si + 1], fb = sb[si + 2];
        var ba = tb[ti + 3], br = tb[ti], bg = tb[ti + 1], bb = tb[ti + 2];
        if (fa == ba && fr == br && fg == bg && fb == bb) continue;
        if (fa < 220 && ba > 20) return false;
      }
    }
  return true;
};
UPNG.encode = function(bufs, w, h, ps, dels, tabs, forbidPlte) {
  if (ps == null) ps = 0;
  if (forbidPlte == null) forbidPlte = false;
  var nimg = UPNG.encode.compress(bufs, w, h, ps, [false, false, false, 0, forbidPlte]);
  UPNG.encode.compressPNG(nimg, -1);
  return UPNG.encode._main(nimg, w, h, dels, tabs);
};
UPNG.encodeLL = function(bufs, w, h, cc, ac, depth, dels, tabs) {
  var nimg = { ctype: 0 + (cc == 1 ? 0 : 2) + (ac == 0 ? 0 : 4), depth, frames: [] };
  var time = Date.now();
  var bipp = (cc + ac) * depth, bipl = bipp * w;
  for (var i = 0; i < bufs.length; i++)
    nimg.frames.push({ rect: { x: 0, y: 0, width: w, height: h }, img: new Uint8Array(bufs[i]), blend: 0, dispose: 1, bpp: Math.ceil(bipp / 8), bpl: Math.ceil(bipl / 8) });
  UPNG.encode.compressPNG(nimg, 0, true);
  var out = UPNG.encode._main(nimg, w, h, dels, tabs);
  return out;
};
UPNG.encode._main = function(nimg, w, h, dels, tabs) {
  if (tabs == null) tabs = {};
  var crc = UPNG.crc.crc, wUi = UPNG._bin.writeUint, wUs = UPNG._bin.writeUshort, wAs = UPNG._bin.writeASCII;
  var offset = 8, anim = nimg.frames.length > 1, pltAlpha = false;
  var leng = 8 + (16 + 5 + 4) + (anim ? 20 : 0);
  if (tabs["sRGB"] != null) leng += 8 + 1 + 4;
  if (tabs["pHYs"] != null) leng += 8 + 9 + 4;
  if (nimg.ctype == 3) {
    var dl = nimg.plte.length;
    for (var i = 0; i < dl; i++) if (nimg.plte[i] >>> 24 != 255) pltAlpha = true;
    leng += 8 + dl * 3 + 4 + (pltAlpha ? 8 + dl * 1 + 4 : 0);
  }
  for (var j = 0; j < nimg.frames.length; j++) {
    var fr = nimg.frames[j];
    if (anim) leng += 38;
    leng += fr.cimg.length + 12;
    if (j != 0) leng += 4;
  }
  leng += 12;
  var data = new Uint8Array(leng);
  var wr = [137, 80, 78, 71, 13, 10, 26, 10];
  for (var i = 0; i < 8; i++) data[i] = wr[i];
  wUi(data, offset, 13);
  offset += 4;
  wAs(data, offset, "IHDR");
  offset += 4;
  wUi(data, offset, w);
  offset += 4;
  wUi(data, offset, h);
  offset += 4;
  data[offset] = nimg.depth;
  offset++;
  data[offset] = nimg.ctype;
  offset++;
  data[offset] = 0;
  offset++;
  data[offset] = 0;
  offset++;
  data[offset] = 0;
  offset++;
  wUi(data, offset, crc(data, offset - 17, 17));
  offset += 4;
  if (tabs["sRGB"] != null) {
    wUi(data, offset, 1);
    offset += 4;
    wAs(data, offset, "sRGB");
    offset += 4;
    data[offset] = tabs["sRGB"];
    offset++;
    wUi(data, offset, crc(data, offset - 5, 5));
    offset += 4;
  }
  if (tabs["pHYs"] != null) {
    wUi(data, offset, 9);
    offset += 4;
    wAs(data, offset, "pHYs");
    offset += 4;
    wUi(data, offset, tabs["pHYs"][0]);
    offset += 4;
    wUi(data, offset, tabs["pHYs"][1]);
    offset += 4;
    data[offset] = tabs["pHYs"][2];
    offset++;
    wUi(data, offset, crc(data, offset - 13, 13));
    offset += 4;
  }
  if (anim) {
    wUi(data, offset, 8);
    offset += 4;
    wAs(data, offset, "acTL");
    offset += 4;
    wUi(data, offset, nimg.frames.length);
    offset += 4;
    wUi(data, offset, tabs["loop"] != null ? tabs["loop"] : 0);
    offset += 4;
    wUi(data, offset, crc(data, offset - 12, 12));
    offset += 4;
  }
  if (nimg.ctype == 3) {
    var dl = nimg.plte.length;
    wUi(data, offset, dl * 3);
    offset += 4;
    wAs(data, offset, "PLTE");
    offset += 4;
    for (var i = 0; i < dl; i++) {
      var ti = i * 3, c = nimg.plte[i], r = c & 255, g = c >>> 8 & 255, b = c >>> 16 & 255;
      data[offset + ti + 0] = r;
      data[offset + ti + 1] = g;
      data[offset + ti + 2] = b;
    }
    offset += dl * 3;
    wUi(data, offset, crc(data, offset - dl * 3 - 4, dl * 3 + 4));
    offset += 4;
    if (pltAlpha) {
      wUi(data, offset, dl);
      offset += 4;
      wAs(data, offset, "tRNS");
      offset += 4;
      for (var i = 0; i < dl; i++) data[offset + i] = nimg.plte[i] >>> 24 & 255;
      offset += dl;
      wUi(data, offset, crc(data, offset - dl - 4, dl + 4));
      offset += 4;
    }
  }
  var fi = 0;
  for (var j = 0; j < nimg.frames.length; j++) {
    var fr = nimg.frames[j];
    if (anim) {
      wUi(data, offset, 26);
      offset += 4;
      wAs(data, offset, "fcTL");
      offset += 4;
      wUi(data, offset, fi++);
      offset += 4;
      wUi(data, offset, fr.rect.width);
      offset += 4;
      wUi(data, offset, fr.rect.height);
      offset += 4;
      wUi(data, offset, fr.rect.x);
      offset += 4;
      wUi(data, offset, fr.rect.y);
      offset += 4;
      wUs(data, offset, dels[j]);
      offset += 2;
      wUs(data, offset, 1e3);
      offset += 2;
      data[offset] = fr.dispose;
      offset++;
      data[offset] = fr.blend;
      offset++;
      wUi(data, offset, crc(data, offset - 30, 30));
      offset += 4;
    }
    var imgd = fr.cimg, dl = imgd.length;
    wUi(data, offset, dl + (j == 0 ? 0 : 4));
    offset += 4;
    var ioff = offset;
    wAs(data, offset, j == 0 ? "IDAT" : "fdAT");
    offset += 4;
    if (j != 0) {
      wUi(data, offset, fi++);
      offset += 4;
    }
    data.set(imgd, offset);
    offset += dl;
    wUi(data, offset, crc(data, ioff, offset - ioff));
    offset += 4;
  }
  wUi(data, offset, 0);
  offset += 4;
  wAs(data, offset, "IEND");
  offset += 4;
  wUi(data, offset, crc(data, offset - 4, 4));
  offset += 4;
  return data.buffer;
};
UPNG.encode.compressPNG = function(out, filter, levelZero) {
  for (var i = 0; i < out.frames.length; i++) {
    var frm = out.frames[i], nw = frm.rect.width, nh = frm.rect.height;
    var fdata = new Uint8Array(nh * frm.bpl + nh);
    frm.cimg = UPNG.encode._filterZero(frm.img, nh, frm.bpp, frm.bpl, fdata, filter, levelZero);
  }
};
UPNG.encode.compress = function(bufs, w, h, ps, prms) {
  var onlyBlend = prms[0], evenCrd = prms[1], forbidPrev = prms[2], minBits = prms[3], forbidPlte = prms[4];
  var ctype = 6, depth = 8, alphaAnd = 255;
  for (var j = 0; j < bufs.length; j++) {
    var img = new Uint8Array(bufs[j]), ilen = img.length;
    for (var i = 0; i < ilen; i += 4) alphaAnd &= img[i + 3];
  }
  var gotAlpha = alphaAnd != 255;
  var frms = UPNG.encode.framize(bufs, w, h, onlyBlend, evenCrd, forbidPrev);
  var cmap = {}, plte = [], inds = [];
  if (ps != 0) {
    var nbufs = [];
    for (var i = 0; i < frms.length; i++) nbufs.push(frms[i].img.buffer);
    var abuf = UPNG.encode.concatRGBA(nbufs), qres = UPNG.quantize(abuf, ps);
    var cof = 0, bb = new Uint8Array(qres.abuf);
    for (var i = 0; i < frms.length; i++) {
      var ti = frms[i].img, bln = ti.length;
      inds.push(new Uint8Array(qres.inds.buffer, cof >> 2, bln >> 2));
      for (var j = 0; j < bln; j += 4) {
        ti[j] = bb[cof + j];
        ti[j + 1] = bb[cof + j + 1];
        ti[j + 2] = bb[cof + j + 2];
        ti[j + 3] = bb[cof + j + 3];
      }
      cof += bln;
    }
    for (var i = 0; i < qres.plte.length; i++) plte.push(qres.plte[i].est.rgba);
  } else {
    for (var j = 0; j < frms.length; j++) {
      var frm = frms[j], img32 = new Uint32Array(frm.img.buffer), nw = frm.rect.width, ilen = img32.length;
      var ind = new Uint8Array(ilen);
      inds.push(ind);
      for (var i = 0; i < ilen; i++) {
        var c = img32[i];
        if (i != 0 && c == img32[i - 1]) ind[i] = ind[i - 1];
        else if (i > nw && c == img32[i - nw]) ind[i] = ind[i - nw];
        else {
          var cmc = cmap[c];
          if (cmc == null) {
            cmap[c] = cmc = plte.length;
            plte.push(c);
            if (plte.length >= 300) break;
          }
          ind[i] = cmc;
        }
      }
    }
  }
  var cc = plte.length;
  if (cc <= 256 && forbidPlte == false) {
    if (cc <= 2) depth = 1;
    else if (cc <= 4) depth = 2;
    else if (cc <= 16) depth = 4;
    else depth = 8;
    depth = Math.max(depth, minBits);
  }
  for (var j = 0; j < frms.length; j++) {
    var frm = frms[j], nx = frm.rect.x, ny = frm.rect.y, nw = frm.rect.width, nh = frm.rect.height;
    var cimg = frm.img, cimg32 = new Uint32Array(cimg.buffer);
    var bpl = 4 * nw, bpp = 4;
    if (cc <= 256 && forbidPlte == false) {
      bpl = Math.ceil(depth * nw / 8);
      var nimg = new Uint8Array(bpl * nh);
      var inj = inds[j];
      for (var y = 0; y < nh; y++) {
        var i = y * bpl, ii = y * nw;
        if (depth == 8) for (var x = 0; x < nw; x++) nimg[i + x] = inj[ii + x];
        else if (depth == 4) for (var x = 0; x < nw; x++) nimg[i + (x >> 1)] |= inj[ii + x] << 4 - (x & 1) * 4;
        else if (depth == 2) for (var x = 0; x < nw; x++) nimg[i + (x >> 2)] |= inj[ii + x] << 6 - (x & 3) * 2;
        else if (depth == 1) for (var x = 0; x < nw; x++) nimg[i + (x >> 3)] |= inj[ii + x] << 7 - (x & 7) * 1;
      }
      cimg = nimg;
      ctype = 3;
      bpp = 1;
    } else if (gotAlpha == false && frms.length == 1) {
      var nimg = new Uint8Array(nw * nh * 3), area = nw * nh;
      for (var i = 0; i < area; i++) {
        var ti = i * 3, qi = i * 4;
        nimg[ti] = cimg[qi];
        nimg[ti + 1] = cimg[qi + 1];
        nimg[ti + 2] = cimg[qi + 2];
      }
      cimg = nimg;
      ctype = 2;
      bpp = 3;
      bpl = 3 * nw;
    }
    frm.img = cimg;
    frm.bpl = bpl;
    frm.bpp = bpp;
  }
  return { ctype, depth, plte, frames: frms };
};
UPNG.encode.framize = function(bufs, w, h, alwaysBlend, evenCrd, forbidPrev) {
  var frms = [];
  for (var j = 0; j < bufs.length; j++) {
    var cimg = new Uint8Array(bufs[j]), cimg32 = new Uint32Array(cimg.buffer);
    var nimg;
    var nx = 0, ny = 0, nw = w, nh = h, blend = alwaysBlend ? 1 : 0;
    if (j != 0) {
      var tlim = forbidPrev || alwaysBlend || j == 1 || frms[j - 2].dispose != 0 ? 1 : 2, tstp = 0, tarea = 1e9;
      for (var it = 0; it < tlim; it++) {
        var pimg = new Uint8Array(bufs[j - 1 - it]), p32 = new Uint32Array(bufs[j - 1 - it]);
        var mix = w, miy = h, max = -1, may = -1;
        for (var y = 0; y < h; y++) for (var x = 0; x < w; x++) {
          var i = y * w + x;
          if (cimg32[i] != p32[i]) {
            if (x < mix) mix = x;
            if (x > max) max = x;
            if (y < miy) miy = y;
            if (y > may) may = y;
          }
        }
        if (max == -1) mix = miy = max = may = 0;
        if (evenCrd) {
          if ((mix & 1) == 1) mix--;
          if ((miy & 1) == 1) miy--;
        }
        var sarea = (max - mix + 1) * (may - miy + 1);
        if (sarea < tarea) {
          tarea = sarea;
          tstp = it;
          nx = mix;
          ny = miy;
          nw = max - mix + 1;
          nh = may - miy + 1;
        }
      }
      var pimg = new Uint8Array(bufs[j - 1 - tstp]);
      if (tstp == 1) frms[j - 1].dispose = 2;
      nimg = new Uint8Array(nw * nh * 4);
      UPNG._copyTile(pimg, w, h, nimg, nw, nh, -nx, -ny, 0);
      blend = UPNG._copyTile(cimg, w, h, nimg, nw, nh, -nx, -ny, 3) ? 1 : 0;
      if (blend == 1) UPNG.encode._prepareDiff(cimg, w, h, nimg, { x: nx, y: ny, width: nw, height: nh });
      else UPNG._copyTile(cimg, w, h, nimg, nw, nh, -nx, -ny, 0);
    } else nimg = cimg.slice(0);
    frms.push({ rect: { x: nx, y: ny, width: nw, height: nh }, img: nimg, blend, dispose: 0 });
  }
  if (alwaysBlend) for (var j = 0; j < frms.length; j++) {
    var frm = frms[j];
    if (frm.blend == 1) continue;
    var r0 = frm.rect, r1 = frms[j - 1].rect;
    var miX = Math.min(r0.x, r1.x), miY = Math.min(r0.y, r1.y);
    var maX = Math.max(r0.x + r0.width, r1.x + r1.width), maY = Math.max(r0.y + r0.height, r1.y + r1.height);
    var r = { x: miX, y: miY, width: maX - miX, height: maY - miY };
    frms[j - 1].dispose = 1;
    if (j - 1 != 0)
      UPNG.encode._updateFrame(bufs, w, h, frms, j - 1, r, evenCrd);
    UPNG.encode._updateFrame(bufs, w, h, frms, j, r, evenCrd);
  }
  var area = 0;
  if (bufs.length != 1) for (var i = 0; i < frms.length; i++) {
    var frm = frms[i];
    area += frm.rect.width * frm.rect.height;
  }
  return frms;
};
UPNG.encode._updateFrame = function(bufs, w, h, frms, i, r, evenCrd) {
  var U8 = Uint8Array, U32 = Uint32Array;
  var pimg = new U8(bufs[i - 1]), pimg32 = new U32(bufs[i - 1]), nimg = i + 1 < bufs.length ? new U8(bufs[i + 1]) : null;
  var cimg = new U8(bufs[i]), cimg32 = new U32(cimg.buffer);
  var mix = w, miy = h, max = -1, may = -1;
  for (var y = 0; y < r.height; y++) for (var x = 0; x < r.width; x++) {
    var cx2 = r.x + x, cy2 = r.y + y;
    var j = cy2 * w + cx2, cc = cimg32[j];
    if (cc == 0 || frms[i - 1].dispose == 0 && pimg32[j] == cc && (nimg == null || nimg[j * 4 + 3] != 0)) {
    } else {
      if (cx2 < mix) mix = cx2;
      if (cx2 > max) max = cx2;
      if (cy2 < miy) miy = cy2;
      if (cy2 > may) may = cy2;
    }
  }
  if (max == -1) mix = miy = max = may = 0;
  if (evenCrd) {
    if ((mix & 1) == 1) mix--;
    if ((miy & 1) == 1) miy--;
  }
  r = { x: mix, y: miy, width: max - mix + 1, height: may - miy + 1 };
  var fr = frms[i];
  fr.rect = r;
  fr.blend = 1;
  fr.img = new Uint8Array(r.width * r.height * 4);
  if (frms[i - 1].dispose == 0) {
    UPNG._copyTile(pimg, w, h, fr.img, r.width, r.height, -r.x, -r.y, 0);
    UPNG.encode._prepareDiff(cimg, w, h, fr.img, r);
  } else
    UPNG._copyTile(cimg, w, h, fr.img, r.width, r.height, -r.x, -r.y, 0);
};
UPNG.encode._prepareDiff = function(cimg, w, h, nimg, rec) {
  UPNG._copyTile(cimg, w, h, nimg, rec.width, rec.height, -rec.x, -rec.y, 2);
};
UPNG.encode._filterZero = function(img, h, bpp, bpl, data, filter, levelZero) {
  var fls = [], ftry = [0, 1, 2, 3, 4];
  if (filter != -1) ftry = [filter];
  else if (h * bpl > 5e5 || bpp == 1) ftry = [0];
  var opts;
  if (levelZero) opts = { level: 0 };
  var CMPR = levelZero && UZIP != null ? UZIP : import_pako4.default;
  for (var i = 0; i < ftry.length; i++) {
    for (var y = 0; y < h; y++) UPNG.encode._filterLine(data, img, y, bpl, bpp, ftry[i]);
    fls.push(CMPR["deflate"](data, opts));
  }
  var ti, tsize = 1e9;
  for (var i = 0; i < fls.length; i++) if (fls[i].length < tsize) {
    ti = i;
    tsize = fls[i].length;
  }
  return fls[ti];
};
UPNG.encode._filterLine = function(data, img, y, bpl, bpp, type) {
  var i = y * bpl, di = i + y, paeth = UPNG.decode._paeth;
  data[di] = type;
  di++;
  if (type == 0) {
    if (bpl < 500) for (var x = 0; x < bpl; x++) data[di + x] = img[i + x];
    else data.set(new Uint8Array(img.buffer, i, bpl), di);
  } else if (type == 1) {
    for (var x = 0; x < bpp; x++) data[di + x] = img[i + x];
    for (var x = bpp; x < bpl; x++) data[di + x] = img[i + x] - img[i + x - bpp] + 256 & 255;
  } else if (y == 0) {
    for (var x = 0; x < bpp; x++) data[di + x] = img[i + x];
    if (type == 2) for (var x = bpp; x < bpl; x++) data[di + x] = img[i + x];
    if (type == 3) for (var x = bpp; x < bpl; x++) data[di + x] = img[i + x] - (img[i + x - bpp] >> 1) + 256 & 255;
    if (type == 4) for (var x = bpp; x < bpl; x++) data[di + x] = img[i + x] - paeth(img[i + x - bpp], 0, 0) + 256 & 255;
  } else {
    if (type == 2) {
      for (var x = 0; x < bpl; x++) data[di + x] = img[i + x] + 256 - img[i + x - bpl] & 255;
    }
    if (type == 3) {
      for (var x = 0; x < bpp; x++) data[di + x] = img[i + x] + 256 - (img[i + x - bpl] >> 1) & 255;
      for (var x = bpp; x < bpl; x++) data[di + x] = img[i + x] + 256 - (img[i + x - bpl] + img[i + x - bpp] >> 1) & 255;
    }
    if (type == 4) {
      for (var x = 0; x < bpp; x++) data[di + x] = img[i + x] + 256 - paeth(0, img[i + x - bpl], 0) & 255;
      for (var x = bpp; x < bpl; x++) data[di + x] = img[i + x] + 256 - paeth(img[i + x - bpp], img[i + x - bpl], img[i + x - bpp - bpl]) & 255;
    }
  }
};
UPNG.crc = {
  table: function() {
    var tab = new Uint32Array(256);
    for (var n = 0; n < 256; n++) {
      var c = n;
      for (var k = 0; k < 8; k++) {
        if (c & 1) c = 3988292384 ^ c >>> 1;
        else c = c >>> 1;
      }
      tab[n] = c;
    }
    return tab;
  }(),
  update: function(c, buf, off, len) {
    for (var i = 0; i < len; i++) c = UPNG.crc.table[(c ^ buf[off + i]) & 255] ^ c >>> 8;
    return c;
  },
  crc: function(b, o, l) {
    return UPNG.crc.update(4294967295, b, o, l) ^ 4294967295;
  }
};
UPNG.quantize = function(abuf, ps) {
  var oimg = new Uint8Array(abuf), nimg = oimg.slice(0), nimg32 = new Uint32Array(nimg.buffer);
  var KD = UPNG.quantize.getKDtree(nimg, ps);
  var root = KD[0], leafs = KD[1];
  var planeDst = UPNG.quantize.planeDst;
  var sb = oimg, tb = nimg32, len = sb.length;
  var inds = new Uint8Array(oimg.length >> 2);
  for (var i = 0; i < len; i += 4) {
    var r = sb[i] * (1 / 255), g = sb[i + 1] * (1 / 255), b = sb[i + 2] * (1 / 255), a = sb[i + 3] * (1 / 255);
    var nd = UPNG.quantize.getNearest(root, r, g, b, a);
    inds[i >> 2] = nd.ind;
    tb[i >> 2] = nd.est.rgba;
  }
  return { abuf: nimg.buffer, inds, plte: leafs };
};
UPNG.quantize.getKDtree = function(nimg, ps, err) {
  if (err == null) err = 1e-4;
  var nimg32 = new Uint32Array(nimg.buffer);
  var root = { i0: 0, i1: nimg.length, bst: null, est: null, tdst: 0, left: null, right: null };
  root.bst = UPNG.quantize.stats(nimg, root.i0, root.i1);
  root.est = UPNG.quantize.estats(root.bst);
  var leafs = [root];
  while (leafs.length < ps) {
    var maxL = 0, mi = 0;
    for (var i = 0; i < leafs.length; i++) if (leafs[i].est.L > maxL) {
      maxL = leafs[i].est.L;
      mi = i;
    }
    if (maxL < err) break;
    var node = leafs[mi];
    var s0 = UPNG.quantize.splitPixels(nimg, nimg32, node.i0, node.i1, node.est.e, node.est.eMq255);
    var s0wrong = node.i0 >= s0 || node.i1 <= s0;
    if (s0wrong) {
      node.est.L = 0;
      continue;
    }
    var ln = { i0: node.i0, i1: s0, bst: null, est: null, tdst: 0, left: null, right: null };
    ln.bst = UPNG.quantize.stats(nimg, ln.i0, ln.i1);
    ln.est = UPNG.quantize.estats(ln.bst);
    var rn = { i0: s0, i1: node.i1, bst: null, est: null, tdst: 0, left: null, right: null };
    rn.bst = { R: [], m: [], N: node.bst.N - ln.bst.N };
    for (var i = 0; i < 16; i++) rn.bst.R[i] = node.bst.R[i] - ln.bst.R[i];
    for (var i = 0; i < 4; i++) rn.bst.m[i] = node.bst.m[i] - ln.bst.m[i];
    rn.est = UPNG.quantize.estats(rn.bst);
    node.left = ln;
    node.right = rn;
    leafs[mi] = ln;
    leafs.push(rn);
  }
  leafs.sort(function(a, b) {
    return b.bst.N - a.bst.N;
  });
  for (var i = 0; i < leafs.length; i++) leafs[i].ind = i;
  return [root, leafs];
};
UPNG.quantize.getNearest = function(nd, r, g, b, a) {
  if (nd.left == null) {
    nd.tdst = UPNG.quantize.dist(nd.est.q, r, g, b, a);
    return nd;
  }
  var planeDst = UPNG.quantize.planeDst(nd.est, r, g, b, a);
  var node0 = nd.left, node1 = nd.right;
  if (planeDst > 0) {
    node0 = nd.right;
    node1 = nd.left;
  }
  var ln = UPNG.quantize.getNearest(node0, r, g, b, a);
  if (ln.tdst <= planeDst * planeDst) return ln;
  var rn = UPNG.quantize.getNearest(node1, r, g, b, a);
  return rn.tdst < ln.tdst ? rn : ln;
};
UPNG.quantize.planeDst = function(est, r, g, b, a) {
  var e = est.e;
  return e[0] * r + e[1] * g + e[2] * b + e[3] * a - est.eMq;
};
UPNG.quantize.dist = function(q, r, g, b, a) {
  var d0 = r - q[0], d1 = g - q[1], d2 = b - q[2], d3 = a - q[3];
  return d0 * d0 + d1 * d1 + d2 * d2 + d3 * d3;
};
UPNG.quantize.splitPixels = function(nimg, nimg32, i0, i1, e, eMq) {
  var vecDot = UPNG.quantize.vecDot;
  i1 -= 4;
  var shfs = 0;
  while (i0 < i1) {
    while (vecDot(nimg, i0, e) <= eMq) i0 += 4;
    while (vecDot(nimg, i1, e) > eMq) i1 -= 4;
    if (i0 >= i1) break;
    var t = nimg32[i0 >> 2];
    nimg32[i0 >> 2] = nimg32[i1 >> 2];
    nimg32[i1 >> 2] = t;
    i0 += 4;
    i1 -= 4;
  }
  while (vecDot(nimg, i0, e) > eMq) i0 -= 4;
  return i0 + 4;
};
UPNG.quantize.vecDot = function(nimg, i, e) {
  return nimg[i] * e[0] + nimg[i + 1] * e[1] + nimg[i + 2] * e[2] + nimg[i + 3] * e[3];
};
UPNG.quantize.stats = function(nimg, i0, i1) {
  var R = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
  var m = [0, 0, 0, 0];
  var N = i1 - i0 >> 2;
  for (var i = i0; i < i1; i += 4) {
    var r = nimg[i] * (1 / 255), g = nimg[i + 1] * (1 / 255), b = nimg[i + 2] * (1 / 255), a = nimg[i + 3] * (1 / 255);
    m[0] += r;
    m[1] += g;
    m[2] += b;
    m[3] += a;
    R[0] += r * r;
    R[1] += r * g;
    R[2] += r * b;
    R[3] += r * a;
    R[5] += g * g;
    R[6] += g * b;
    R[7] += g * a;
    R[10] += b * b;
    R[11] += b * a;
    R[15] += a * a;
  }
  R[4] = R[1];
  R[8] = R[2];
  R[9] = R[6];
  R[12] = R[3];
  R[13] = R[7];
  R[14] = R[11];
  return { R, m, N };
};
UPNG.quantize.estats = function(stats) {
  var R = stats.R, m = stats.m, N = stats.N;
  var m0 = m[0], m1 = m[1], m2 = m[2], m3 = m[3], iN = N == 0 ? 0 : 1 / N;
  var Rj = [
    R[0] - m0 * m0 * iN,
    R[1] - m0 * m1 * iN,
    R[2] - m0 * m2 * iN,
    R[3] - m0 * m3 * iN,
    R[4] - m1 * m0 * iN,
    R[5] - m1 * m1 * iN,
    R[6] - m1 * m2 * iN,
    R[7] - m1 * m3 * iN,
    R[8] - m2 * m0 * iN,
    R[9] - m2 * m1 * iN,
    R[10] - m2 * m2 * iN,
    R[11] - m2 * m3 * iN,
    R[12] - m3 * m0 * iN,
    R[13] - m3 * m1 * iN,
    R[14] - m3 * m2 * iN,
    R[15] - m3 * m3 * iN
  ];
  var A = Rj, M = UPNG.M4;
  var b = [0.5, 0.5, 0.5, 0.5], mi = 0, tmi = 0;
  if (N != 0)
    for (var i = 0; i < 10; i++) {
      b = M.multVec(A, b);
      tmi = Math.sqrt(M.dot(b, b));
      b = M.sml(1 / tmi, b);
      if (Math.abs(tmi - mi) < 1e-9) break;
      mi = tmi;
    }
  var q = [m0 * iN, m1 * iN, m2 * iN, m3 * iN];
  var eMq255 = M.dot(M.sml(255, q), b);
  return {
    Cov: Rj,
    q,
    e: b,
    L: mi,
    eMq255,
    eMq: M.dot(b, q),
    rgba: (Math.round(255 * q[3]) << 24 | Math.round(255 * q[2]) << 16 | Math.round(255 * q[1]) << 8 | Math.round(255 * q[0]) << 0) >>> 0
  };
};
UPNG.M4 = {
  multVec: function(m, v) {
    return [
      m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3] * v[3],
      m[4] * v[0] + m[5] * v[1] + m[6] * v[2] + m[7] * v[3],
      m[8] * v[0] + m[9] * v[1] + m[10] * v[2] + m[11] * v[3],
      m[12] * v[0] + m[13] * v[1] + m[14] * v[2] + m[15] * v[3]
    ];
  },
  dot: function(x, y) {
    return x[0] * y[0] + x[1] * y[1] + x[2] * y[2] + x[3] * y[3];
  },
  sml: function(a, y) {
    return [a * y[0], a * y[1], a * y[2], a * y[3]];
  }
};
UPNG.encode.concatRGBA = function(bufs) {
  var tlen = 0;
  for (var i = 0; i < bufs.length; i++) tlen += bufs[i].byteLength;
  var nimg = new Uint8Array(tlen), noff = 0;
  for (var i = 0; i < bufs.length; i++) {
    var img = new Uint8Array(bufs[i]), il = img.length;
    for (var j = 0; j < il; j += 4) {
      var r = img[j], g = img[j + 1], b = img[j + 2], a = img[j + 3];
      if (a == 0) r = g = b = 0;
      nimg[noff + j] = r;
      nimg[noff + j + 1] = g;
      nimg[noff + j + 2] = b;
      nimg[noff + j + 3] = a;
    }
    noff += il;
  }
  return nimg.buffer;
};
var UPNG_default = UPNG;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/utils/png.js
var getImageType = function(ctype) {
  if (ctype === 0)
    return PngType.Greyscale;
  if (ctype === 2)
    return PngType.Truecolour;
  if (ctype === 3)
    return PngType.IndexedColour;
  if (ctype === 4)
    return PngType.GreyscaleWithAlpha;
  if (ctype === 6)
    return PngType.TruecolourWithAlpha;
  throw new Error("Unknown color type: " + ctype);
};
var splitAlphaChannel = function(rgbaChannel) {
  var pixelCount = Math.floor(rgbaChannel.length / 4);
  var rgbChannel = new Uint8Array(pixelCount * 3);
  var alphaChannel = new Uint8Array(pixelCount * 1);
  var rgbaOffset = 0;
  var rgbOffset = 0;
  var alphaOffset = 0;
  while (rgbaOffset < rgbaChannel.length) {
    rgbChannel[rgbOffset++] = rgbaChannel[rgbaOffset++];
    rgbChannel[rgbOffset++] = rgbaChannel[rgbaOffset++];
    rgbChannel[rgbOffset++] = rgbaChannel[rgbaOffset++];
    alphaChannel[alphaOffset++] = rgbaChannel[rgbaOffset++];
  }
  return { rgbChannel, alphaChannel };
};
var PngType;
(function(PngType2) {
  PngType2["Greyscale"] = "Greyscale";
  PngType2["Truecolour"] = "Truecolour";
  PngType2["IndexedColour"] = "IndexedColour";
  PngType2["GreyscaleWithAlpha"] = "GreyscaleWithAlpha";
  PngType2["TruecolourWithAlpha"] = "TruecolourWithAlpha";
})(PngType || (PngType = {}));
var PNG = (
  /** @class */
  function() {
    function PNG2(pngData) {
      var upng = UPNG_default.decode(pngData);
      var frames = UPNG_default.toRGBA8(upng);
      if (frames.length > 1)
        throw new Error("Animated PNGs are not supported");
      var frame = new Uint8Array(frames[0]);
      var _a = splitAlphaChannel(frame), rgbChannel = _a.rgbChannel, alphaChannel = _a.alphaChannel;
      this.rgbChannel = rgbChannel;
      var hasAlphaValues = alphaChannel.some(function(a) {
        return a < 255;
      });
      if (hasAlphaValues)
        this.alphaChannel = alphaChannel;
      this.type = getImageType(upng.ctype);
      this.width = upng.width;
      this.height = upng.height;
      this.bitsPerComponent = 8;
    }
    PNG2.load = function(pngData) {
      return new PNG2(pngData);
    };
    return PNG2;
  }()
);

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/embedders/PngEmbedder.js
var PngEmbedder = (
  /** @class */
  function() {
    function PngEmbedder2(png) {
      this.image = png;
      this.bitsPerComponent = png.bitsPerComponent;
      this.width = png.width;
      this.height = png.height;
      this.colorSpace = "DeviceRGB";
    }
    PngEmbedder2.for = function(imageData) {
      return __awaiter(this, void 0, void 0, function() {
        var png;
        return __generator(this, function(_a) {
          png = PNG.load(imageData);
          return [2, new PngEmbedder2(png)];
        });
      });
    };
    PngEmbedder2.prototype.embedIntoContext = function(context, ref) {
      return __awaiter(this, void 0, void 0, function() {
        var SMask, xObject;
        return __generator(this, function(_a) {
          SMask = this.embedAlphaChannel(context);
          xObject = context.flateStream(this.image.rgbChannel, {
            Type: "XObject",
            Subtype: "Image",
            BitsPerComponent: this.image.bitsPerComponent,
            Width: this.image.width,
            Height: this.image.height,
            ColorSpace: this.colorSpace,
            SMask
          });
          if (ref) {
            context.assign(ref, xObject);
            return [2, ref];
          } else {
            return [2, context.register(xObject)];
          }
          return [
            2
            /*return*/
          ];
        });
      });
    };
    PngEmbedder2.prototype.embedAlphaChannel = function(context) {
      if (!this.image.alphaChannel)
        return void 0;
      var xObject = context.flateStream(this.image.alphaChannel, {
        Type: "XObject",
        Subtype: "Image",
        Height: this.image.height,
        Width: this.image.width,
        BitsPerComponent: this.image.bitsPerComponent,
        ColorSpace: "DeviceGray",
        Decode: [0, 1]
      });
      return context.register(xObject);
    };
    return PngEmbedder2;
  }()
);
var PngEmbedder_default = PngEmbedder;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/streams/Stream.js
var Stream = (
  /** @class */
  function() {
    function Stream2(buffer, start, length) {
      this.bytes = buffer;
      this.start = start || 0;
      this.pos = this.start;
      this.end = !!start && !!length ? start + length : this.bytes.length;
    }
    Object.defineProperty(Stream2.prototype, "length", {
      get: function() {
        return this.end - this.start;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Stream2.prototype, "isEmpty", {
      get: function() {
        return this.length === 0;
      },
      enumerable: false,
      configurable: true
    });
    Stream2.prototype.getByte = function() {
      if (this.pos >= this.end) {
        return -1;
      }
      return this.bytes[this.pos++];
    };
    Stream2.prototype.getUint16 = function() {
      var b0 = this.getByte();
      var b1 = this.getByte();
      if (b0 === -1 || b1 === -1) {
        return -1;
      }
      return (b0 << 8) + b1;
    };
    Stream2.prototype.getInt32 = function() {
      var b0 = this.getByte();
      var b1 = this.getByte();
      var b2 = this.getByte();
      var b3 = this.getByte();
      return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3;
    };
    Stream2.prototype.getBytes = function(length, forceClamped) {
      if (forceClamped === void 0) {
        forceClamped = false;
      }
      var bytes = this.bytes;
      var pos = this.pos;
      var strEnd = this.end;
      if (!length) {
        var subarray = bytes.subarray(pos, strEnd);
        return forceClamped ? new Uint8ClampedArray(subarray) : subarray;
      } else {
        var end = pos + length;
        if (end > strEnd) {
          end = strEnd;
        }
        this.pos = end;
        var subarray = bytes.subarray(pos, end);
        return forceClamped ? new Uint8ClampedArray(subarray) : subarray;
      }
    };
    Stream2.prototype.peekByte = function() {
      var peekedByte = this.getByte();
      this.pos--;
      return peekedByte;
    };
    Stream2.prototype.peekBytes = function(length, forceClamped) {
      if (forceClamped === void 0) {
        forceClamped = false;
      }
      var bytes = this.getBytes(length, forceClamped);
      this.pos -= bytes.length;
      return bytes;
    };
    Stream2.prototype.skip = function(n) {
      if (!n) {
        n = 1;
      }
      this.pos += n;
    };
    Stream2.prototype.reset = function() {
      this.pos = this.start;
    };
    Stream2.prototype.moveStart = function() {
      this.start = this.pos;
    };
    Stream2.prototype.makeSubStream = function(start, length) {
      return new Stream2(this.bytes, start, length);
    };
    Stream2.prototype.decode = function() {
      return this.bytes;
    };
    return Stream2;
  }()
);
var Stream_default = Stream;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/streams/DecodeStream.js
var emptyBuffer = new Uint8Array(0);
var DecodeStream = (
  /** @class */
  function() {
    function DecodeStream2(maybeMinBufferLength) {
      this.pos = 0;
      this.bufferLength = 0;
      this.eof = false;
      this.buffer = emptyBuffer;
      this.minBufferLength = 512;
      if (maybeMinBufferLength) {
        while (this.minBufferLength < maybeMinBufferLength) {
          this.minBufferLength *= 2;
        }
      }
    }
    Object.defineProperty(DecodeStream2.prototype, "isEmpty", {
      get: function() {
        while (!this.eof && this.bufferLength === 0) {
          this.readBlock();
        }
        return this.bufferLength === 0;
      },
      enumerable: false,
      configurable: true
    });
    DecodeStream2.prototype.getByte = function() {
      var pos = this.pos;
      while (this.bufferLength <= pos) {
        if (this.eof) {
          return -1;
        }
        this.readBlock();
      }
      return this.buffer[this.pos++];
    };
    DecodeStream2.prototype.getUint16 = function() {
      var b0 = this.getByte();
      var b1 = this.getByte();
      if (b0 === -1 || b1 === -1) {
        return -1;
      }
      return (b0 << 8) + b1;
    };
    DecodeStream2.prototype.getInt32 = function() {
      var b0 = this.getByte();
      var b1 = this.getByte();
      var b2 = this.getByte();
      var b3 = this.getByte();
      return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3;
    };
    DecodeStream2.prototype.getBytes = function(length, forceClamped) {
      if (forceClamped === void 0) {
        forceClamped = false;
      }
      var end;
      var pos = this.pos;
      if (length) {
        this.ensureBuffer(pos + length);
        end = pos + length;
        while (!this.eof && this.bufferLength < end) {
          this.readBlock();
        }
        var bufEnd = this.bufferLength;
        if (end > bufEnd) {
          end = bufEnd;
        }
      } else {
        while (!this.eof) {
          this.readBlock();
        }
        end = this.bufferLength;
      }
      this.pos = end;
      var subarray = this.buffer.subarray(pos, end);
      return forceClamped && !(subarray instanceof Uint8ClampedArray) ? new Uint8ClampedArray(subarray) : subarray;
    };
    DecodeStream2.prototype.peekByte = function() {
      var peekedByte = this.getByte();
      this.pos--;
      return peekedByte;
    };
    DecodeStream2.prototype.peekBytes = function(length, forceClamped) {
      if (forceClamped === void 0) {
        forceClamped = false;
      }
      var bytes = this.getBytes(length, forceClamped);
      this.pos -= bytes.length;
      return bytes;
    };
    DecodeStream2.prototype.skip = function(n) {
      if (!n) {
        n = 1;
      }
      this.pos += n;
    };
    DecodeStream2.prototype.reset = function() {
      this.pos = 0;
    };
    DecodeStream2.prototype.makeSubStream = function(start, length) {
      var end = start + length;
      while (this.bufferLength <= end && !this.eof) {
        this.readBlock();
      }
      return new Stream_default(
        this.buffer,
        start,
        length
        /* dict */
      );
    };
    DecodeStream2.prototype.decode = function() {
      while (!this.eof)
        this.readBlock();
      return this.buffer.subarray(0, this.bufferLength);
    };
    DecodeStream2.prototype.readBlock = function() {
      throw new MethodNotImplementedError(this.constructor.name, "readBlock");
    };
    DecodeStream2.prototype.ensureBuffer = function(requested) {
      var buffer = this.buffer;
      if (requested <= buffer.byteLength) {
        return buffer;
      }
      var size = this.minBufferLength;
      while (size < requested) {
        size *= 2;
      }
      var buffer2 = new Uint8Array(size);
      buffer2.set(buffer);
      return this.buffer = buffer2;
    };
    return DecodeStream2;
  }()
);
var DecodeStream_default = DecodeStream;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/streams/Ascii85Stream.js
var isSpace = function(ch) {
  return ch === 32 || ch === 9 || ch === 13 || ch === 10;
};
var Ascii85Stream = (
  /** @class */
  function(_super) {
    __extends(Ascii85Stream2, _super);
    function Ascii85Stream2(stream2, maybeLength) {
      var _this = _super.call(this, maybeLength) || this;
      _this.stream = stream2;
      _this.input = new Uint8Array(5);
      if (maybeLength) {
        maybeLength = 0.8 * maybeLength;
      }
      return _this;
    }
    Ascii85Stream2.prototype.readBlock = function() {
      var TILDA_CHAR = 126;
      var Z_LOWER_CHAR = 122;
      var EOF = -1;
      var stream2 = this.stream;
      var c = stream2.getByte();
      while (isSpace(c)) {
        c = stream2.getByte();
      }
      if (c === EOF || c === TILDA_CHAR) {
        this.eof = true;
        return;
      }
      var bufferLength = this.bufferLength;
      var buffer;
      var i;
      if (c === Z_LOWER_CHAR) {
        buffer = this.ensureBuffer(bufferLength + 4);
        for (i = 0; i < 4; ++i) {
          buffer[bufferLength + i] = 0;
        }
        this.bufferLength += 4;
      } else {
        var input = this.input;
        input[0] = c;
        for (i = 1; i < 5; ++i) {
          c = stream2.getByte();
          while (isSpace(c)) {
            c = stream2.getByte();
          }
          input[i] = c;
          if (c === EOF || c === TILDA_CHAR) {
            break;
          }
        }
        buffer = this.ensureBuffer(bufferLength + i - 1);
        this.bufferLength += i - 1;
        if (i < 5) {
          for (; i < 5; ++i) {
            input[i] = 33 + 84;
          }
          this.eof = true;
        }
        var t = 0;
        for (i = 0; i < 5; ++i) {
          t = t * 85 + (input[i] - 33);
        }
        for (i = 3; i >= 0; --i) {
          buffer[bufferLength + i] = t & 255;
          t >>= 8;
        }
      }
    };
    return Ascii85Stream2;
  }(DecodeStream_default)
);
var Ascii85Stream_default = Ascii85Stream;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/streams/AsciiHexStream.js
var AsciiHexStream = (
  /** @class */
  function(_super) {
    __extends(AsciiHexStream2, _super);
    function AsciiHexStream2(stream2, maybeLength) {
      var _this = _super.call(this, maybeLength) || this;
      _this.stream = stream2;
      _this.firstDigit = -1;
      if (maybeLength) {
        maybeLength = 0.5 * maybeLength;
      }
      return _this;
    }
    AsciiHexStream2.prototype.readBlock = function() {
      var UPSTREAM_BLOCK_SIZE = 8e3;
      var bytes = this.stream.getBytes(UPSTREAM_BLOCK_SIZE);
      if (!bytes.length) {
        this.eof = true;
        return;
      }
      var maxDecodeLength = bytes.length + 1 >> 1;
      var buffer = this.ensureBuffer(this.bufferLength + maxDecodeLength);
      var bufferLength = this.bufferLength;
      var firstDigit = this.firstDigit;
      for (var i = 0, ii = bytes.length; i < ii; i++) {
        var ch = bytes[i];
        var digit = void 0;
        if (ch >= 48 && ch <= 57) {
          digit = ch & 15;
        } else if (ch >= 65 && ch <= 70 || ch >= 97 && ch <= 102) {
          digit = (ch & 15) + 9;
        } else if (ch === 62) {
          this.eof = true;
          break;
        } else {
          continue;
        }
        if (firstDigit < 0) {
          firstDigit = digit;
        } else {
          buffer[bufferLength++] = firstDigit << 4 | digit;
          firstDigit = -1;
        }
      }
      if (firstDigit >= 0 && this.eof) {
        buffer[bufferLength++] = firstDigit << 4;
        firstDigit = -1;
      }
      this.firstDigit = firstDigit;
      this.bufferLength = bufferLength;
    };
    return AsciiHexStream2;
  }(DecodeStream_default)
);
var AsciiHexStream_default = AsciiHexStream;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/streams/FlateStream.js
var codeLenCodeMap = new Int32Array([
  16,
  17,
  18,
  0,
  8,
  7,
  9,
  6,
  10,
  5,
  11,
  4,
  12,
  3,
  13,
  2,
  14,
  1,
  15
]);
var lengthDecode = new Int32Array([
  3,
  4,
  5,
  6,
  7,
  8,
  9,
  10,
  65547,
  65549,
  65551,
  65553,
  131091,
  131095,
  131099,
  131103,
  196643,
  196651,
  196659,
  196667,
  262211,
  262227,
  262243,
  262259,
  327811,
  327843,
  327875,
  327907,
  258,
  258,
  258
]);
var distDecode = new Int32Array([
  1,
  2,
  3,
  4,
  65541,
  65543,
  131081,
  131085,
  196625,
  196633,
  262177,
  262193,
  327745,
  327777,
  393345,
  393409,
  459009,
  459137,
  524801,
  525057,
  590849,
  591361,
  657409,
  658433,
  724993,
  727041,
  794625,
  798721,
  868353,
  876545
]);
var fixedLitCodeTab = [new Int32Array([
  459008,
  524368,
  524304,
  524568,
  459024,
  524400,
  524336,
  590016,
  459016,
  524384,
  524320,
  589984,
  524288,
  524416,
  524352,
  590048,
  459012,
  524376,
  524312,
  589968,
  459028,
  524408,
  524344,
  590032,
  459020,
  524392,
  524328,
  59e4,
  524296,
  524424,
  524360,
  590064,
  459010,
  524372,
  524308,
  524572,
  459026,
  524404,
  524340,
  590024,
  459018,
  524388,
  524324,
  589992,
  524292,
  524420,
  524356,
  590056,
  459014,
  524380,
  524316,
  589976,
  459030,
  524412,
  524348,
  590040,
  459022,
  524396,
  524332,
  590008,
  524300,
  524428,
  524364,
  590072,
  459009,
  524370,
  524306,
  524570,
  459025,
  524402,
  524338,
  590020,
  459017,
  524386,
  524322,
  589988,
  524290,
  524418,
  524354,
  590052,
  459013,
  524378,
  524314,
  589972,
  459029,
  524410,
  524346,
  590036,
  459021,
  524394,
  524330,
  590004,
  524298,
  524426,
  524362,
  590068,
  459011,
  524374,
  524310,
  524574,
  459027,
  524406,
  524342,
  590028,
  459019,
  524390,
  524326,
  589996,
  524294,
  524422,
  524358,
  590060,
  459015,
  524382,
  524318,
  589980,
  459031,
  524414,
  524350,
  590044,
  459023,
  524398,
  524334,
  590012,
  524302,
  524430,
  524366,
  590076,
  459008,
  524369,
  524305,
  524569,
  459024,
  524401,
  524337,
  590018,
  459016,
  524385,
  524321,
  589986,
  524289,
  524417,
  524353,
  590050,
  459012,
  524377,
  524313,
  589970,
  459028,
  524409,
  524345,
  590034,
  459020,
  524393,
  524329,
  590002,
  524297,
  524425,
  524361,
  590066,
  459010,
  524373,
  524309,
  524573,
  459026,
  524405,
  524341,
  590026,
  459018,
  524389,
  524325,
  589994,
  524293,
  524421,
  524357,
  590058,
  459014,
  524381,
  524317,
  589978,
  459030,
  524413,
  524349,
  590042,
  459022,
  524397,
  524333,
  590010,
  524301,
  524429,
  524365,
  590074,
  459009,
  524371,
  524307,
  524571,
  459025,
  524403,
  524339,
  590022,
  459017,
  524387,
  524323,
  589990,
  524291,
  524419,
  524355,
  590054,
  459013,
  524379,
  524315,
  589974,
  459029,
  524411,
  524347,
  590038,
  459021,
  524395,
  524331,
  590006,
  524299,
  524427,
  524363,
  590070,
  459011,
  524375,
  524311,
  524575,
  459027,
  524407,
  524343,
  590030,
  459019,
  524391,
  524327,
  589998,
  524295,
  524423,
  524359,
  590062,
  459015,
  524383,
  524319,
  589982,
  459031,
  524415,
  524351,
  590046,
  459023,
  524399,
  524335,
  590014,
  524303,
  524431,
  524367,
  590078,
  459008,
  524368,
  524304,
  524568,
  459024,
  524400,
  524336,
  590017,
  459016,
  524384,
  524320,
  589985,
  524288,
  524416,
  524352,
  590049,
  459012,
  524376,
  524312,
  589969,
  459028,
  524408,
  524344,
  590033,
  459020,
  524392,
  524328,
  590001,
  524296,
  524424,
  524360,
  590065,
  459010,
  524372,
  524308,
  524572,
  459026,
  524404,
  524340,
  590025,
  459018,
  524388,
  524324,
  589993,
  524292,
  524420,
  524356,
  590057,
  459014,
  524380,
  524316,
  589977,
  459030,
  524412,
  524348,
  590041,
  459022,
  524396,
  524332,
  590009,
  524300,
  524428,
  524364,
  590073,
  459009,
  524370,
  524306,
  524570,
  459025,
  524402,
  524338,
  590021,
  459017,
  524386,
  524322,
  589989,
  524290,
  524418,
  524354,
  590053,
  459013,
  524378,
  524314,
  589973,
  459029,
  524410,
  524346,
  590037,
  459021,
  524394,
  524330,
  590005,
  524298,
  524426,
  524362,
  590069,
  459011,
  524374,
  524310,
  524574,
  459027,
  524406,
  524342,
  590029,
  459019,
  524390,
  524326,
  589997,
  524294,
  524422,
  524358,
  590061,
  459015,
  524382,
  524318,
  589981,
  459031,
  524414,
  524350,
  590045,
  459023,
  524398,
  524334,
  590013,
  524302,
  524430,
  524366,
  590077,
  459008,
  524369,
  524305,
  524569,
  459024,
  524401,
  524337,
  590019,
  459016,
  524385,
  524321,
  589987,
  524289,
  524417,
  524353,
  590051,
  459012,
  524377,
  524313,
  589971,
  459028,
  524409,
  524345,
  590035,
  459020,
  524393,
  524329,
  590003,
  524297,
  524425,
  524361,
  590067,
  459010,
  524373,
  524309,
  524573,
  459026,
  524405,
  524341,
  590027,
  459018,
  524389,
  524325,
  589995,
  524293,
  524421,
  524357,
  590059,
  459014,
  524381,
  524317,
  589979,
  459030,
  524413,
  524349,
  590043,
  459022,
  524397,
  524333,
  590011,
  524301,
  524429,
  524365,
  590075,
  459009,
  524371,
  524307,
  524571,
  459025,
  524403,
  524339,
  590023,
  459017,
  524387,
  524323,
  589991,
  524291,
  524419,
  524355,
  590055,
  459013,
  524379,
  524315,
  589975,
  459029,
  524411,
  524347,
  590039,
  459021,
  524395,
  524331,
  590007,
  524299,
  524427,
  524363,
  590071,
  459011,
  524375,
  524311,
  524575,
  459027,
  524407,
  524343,
  590031,
  459019,
  524391,
  524327,
  589999,
  524295,
  524423,
  524359,
  590063,
  459015,
  524383,
  524319,
  589983,
  459031,
  524415,
  524351,
  590047,
  459023,
  524399,
  524335,
  590015,
  524303,
  524431,
  524367,
  590079
]), 9];
var fixedDistCodeTab = [new Int32Array([
  327680,
  327696,
  327688,
  327704,
  327684,
  327700,
  327692,
  327708,
  327682,
  327698,
  327690,
  327706,
  327686,
  327702,
  327694,
  0,
  327681,
  327697,
  327689,
  327705,
  327685,
  327701,
  327693,
  327709,
  327683,
  327699,
  327691,
  327707,
  327687,
  327703,
  327695,
  0
]), 5];
var FlateStream = (
  /** @class */
  function(_super) {
    __extends(FlateStream2, _super);
    function FlateStream2(stream2, maybeLength) {
      var _this = _super.call(this, maybeLength) || this;
      _this.stream = stream2;
      var cmf = stream2.getByte();
      var flg = stream2.getByte();
      if (cmf === -1 || flg === -1) {
        throw new Error("Invalid header in flate stream: " + cmf + ", " + flg);
      }
      if ((cmf & 15) !== 8) {
        throw new Error("Unknown compression method in flate stream: " + cmf + ", " + flg);
      }
      if (((cmf << 8) + flg) % 31 !== 0) {
        throw new Error("Bad FCHECK in flate stream: " + cmf + ", " + flg);
      }
      if (flg & 32) {
        throw new Error("FDICT bit set in flate stream: " + cmf + ", " + flg);
      }
      _this.codeSize = 0;
      _this.codeBuf = 0;
      return _this;
    }
    FlateStream2.prototype.readBlock = function() {
      var buffer;
      var len;
      var str = this.stream;
      var hdr = this.getBits(3);
      if (hdr & 1) {
        this.eof = true;
      }
      hdr >>= 1;
      if (hdr === 0) {
        var b = void 0;
        if ((b = str.getByte()) === -1) {
          throw new Error("Bad block header in flate stream");
        }
        var blockLen = b;
        if ((b = str.getByte()) === -1) {
          throw new Error("Bad block header in flate stream");
        }
        blockLen |= b << 8;
        if ((b = str.getByte()) === -1) {
          throw new Error("Bad block header in flate stream");
        }
        var check = b;
        if ((b = str.getByte()) === -1) {
          throw new Error("Bad block header in flate stream");
        }
        check |= b << 8;
        if (check !== (~blockLen & 65535) && (blockLen !== 0 || check !== 0)) {
          throw new Error("Bad uncompressed block length in flate stream");
        }
        this.codeBuf = 0;
        this.codeSize = 0;
        var bufferLength = this.bufferLength;
        buffer = this.ensureBuffer(bufferLength + blockLen);
        var end = bufferLength + blockLen;
        this.bufferLength = end;
        if (blockLen === 0) {
          if (str.peekByte() === -1) {
            this.eof = true;
          }
        } else {
          for (var n = bufferLength; n < end; ++n) {
            if ((b = str.getByte()) === -1) {
              this.eof = true;
              break;
            }
            buffer[n] = b;
          }
        }
        return;
      }
      var litCodeTable;
      var distCodeTable;
      if (hdr === 1) {
        litCodeTable = fixedLitCodeTab;
        distCodeTable = fixedDistCodeTab;
      } else if (hdr === 2) {
        var numLitCodes = this.getBits(5) + 257;
        var numDistCodes = this.getBits(5) + 1;
        var numCodeLenCodes = this.getBits(4) + 4;
        var codeLenCodeLengths = new Uint8Array(codeLenCodeMap.length);
        var i = void 0;
        for (i = 0; i < numCodeLenCodes; ++i) {
          codeLenCodeLengths[codeLenCodeMap[i]] = this.getBits(3);
        }
        var codeLenCodeTab = this.generateHuffmanTable(codeLenCodeLengths);
        len = 0;
        i = 0;
        var codes = numLitCodes + numDistCodes;
        var codeLengths = new Uint8Array(codes);
        var bitsLength = void 0;
        var bitsOffset = void 0;
        var what = void 0;
        while (i < codes) {
          var code = this.getCode(codeLenCodeTab);
          if (code === 16) {
            bitsLength = 2;
            bitsOffset = 3;
            what = len;
          } else if (code === 17) {
            bitsLength = 3;
            bitsOffset = 3;
            what = len = 0;
          } else if (code === 18) {
            bitsLength = 7;
            bitsOffset = 11;
            what = len = 0;
          } else {
            codeLengths[i++] = len = code;
            continue;
          }
          var repeatLength = this.getBits(bitsLength) + bitsOffset;
          while (repeatLength-- > 0) {
            codeLengths[i++] = what;
          }
        }
        litCodeTable = this.generateHuffmanTable(codeLengths.subarray(0, numLitCodes));
        distCodeTable = this.generateHuffmanTable(codeLengths.subarray(numLitCodes, codes));
      } else {
        throw new Error("Unknown block type in flate stream");
      }
      buffer = this.buffer;
      var limit = buffer ? buffer.length : 0;
      var pos = this.bufferLength;
      while (true) {
        var code1 = this.getCode(litCodeTable);
        if (code1 < 256) {
          if (pos + 1 >= limit) {
            buffer = this.ensureBuffer(pos + 1);
            limit = buffer.length;
          }
          buffer[pos++] = code1;
          continue;
        }
        if (code1 === 256) {
          this.bufferLength = pos;
          return;
        }
        code1 -= 257;
        code1 = lengthDecode[code1];
        var code2 = code1 >> 16;
        if (code2 > 0) {
          code2 = this.getBits(code2);
        }
        len = (code1 & 65535) + code2;
        code1 = this.getCode(distCodeTable);
        code1 = distDecode[code1];
        code2 = code1 >> 16;
        if (code2 > 0) {
          code2 = this.getBits(code2);
        }
        var dist = (code1 & 65535) + code2;
        if (pos + len >= limit) {
          buffer = this.ensureBuffer(pos + len);
          limit = buffer.length;
        }
        for (var k = 0; k < len; ++k, ++pos) {
          buffer[pos] = buffer[pos - dist];
        }
      }
    };
    FlateStream2.prototype.getBits = function(bits) {
      var str = this.stream;
      var codeSize = this.codeSize;
      var codeBuf = this.codeBuf;
      var b;
      while (codeSize < bits) {
        if ((b = str.getByte()) === -1) {
          throw new Error("Bad encoding in flate stream");
        }
        codeBuf |= b << codeSize;
        codeSize += 8;
      }
      b = codeBuf & (1 << bits) - 1;
      this.codeBuf = codeBuf >> bits;
      this.codeSize = codeSize -= bits;
      return b;
    };
    FlateStream2.prototype.getCode = function(table) {
      var str = this.stream;
      var codes = table[0];
      var maxLen = table[1];
      var codeSize = this.codeSize;
      var codeBuf = this.codeBuf;
      var b;
      while (codeSize < maxLen) {
        if ((b = str.getByte()) === -1) {
          break;
        }
        codeBuf |= b << codeSize;
        codeSize += 8;
      }
      var code = codes[codeBuf & (1 << maxLen) - 1];
      if (typeof codes === "number") {
        console.log("FLATE:", code);
      }
      var codeLen = code >> 16;
      var codeVal = code & 65535;
      if (codeLen < 1 || codeSize < codeLen) {
        throw new Error("Bad encoding in flate stream");
      }
      this.codeBuf = codeBuf >> codeLen;
      this.codeSize = codeSize - codeLen;
      return codeVal;
    };
    FlateStream2.prototype.generateHuffmanTable = function(lengths) {
      var n = lengths.length;
      var maxLen = 0;
      var i;
      for (i = 0; i < n; ++i) {
        if (lengths[i] > maxLen) {
          maxLen = lengths[i];
        }
      }
      var size = 1 << maxLen;
      var codes = new Int32Array(size);
      for (var len = 1, code = 0, skip = 2; len <= maxLen; ++len, code <<= 1, skip <<= 1) {
        for (var val = 0; val < n; ++val) {
          if (lengths[val] === len) {
            var code2 = 0;
            var t = code;
            for (i = 0; i < len; ++i) {
              code2 = code2 << 1 | t & 1;
              t >>= 1;
            }
            for (i = code2; i < size; i += skip) {
              codes[i] = len << 16 | val;
            }
            ++code;
          }
        }
      }
      return [codes, maxLen];
    };
    return FlateStream2;
  }(DecodeStream_default)
);
var FlateStream_default = FlateStream;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/streams/LZWStream.js
var LZWStream = (
  /** @class */
  function(_super) {
    __extends(LZWStream2, _super);
    function LZWStream2(stream2, maybeLength, earlyChange) {
      var _this = _super.call(this, maybeLength) || this;
      _this.stream = stream2;
      _this.cachedData = 0;
      _this.bitsCached = 0;
      var maxLzwDictionarySize = 4096;
      var lzwState = {
        earlyChange,
        codeLength: 9,
        nextCode: 258,
        dictionaryValues: new Uint8Array(maxLzwDictionarySize),
        dictionaryLengths: new Uint16Array(maxLzwDictionarySize),
        dictionaryPrevCodes: new Uint16Array(maxLzwDictionarySize),
        currentSequence: new Uint8Array(maxLzwDictionarySize),
        currentSequenceLength: 0
      };
      for (var i = 0; i < 256; ++i) {
        lzwState.dictionaryValues[i] = i;
        lzwState.dictionaryLengths[i] = 1;
      }
      _this.lzwState = lzwState;
      return _this;
    }
    LZWStream2.prototype.readBlock = function() {
      var blockSize = 512;
      var estimatedDecodedSize = blockSize * 2;
      var decodedSizeDelta = blockSize;
      var i;
      var j;
      var q;
      var lzwState = this.lzwState;
      if (!lzwState) {
        return;
      }
      var earlyChange = lzwState.earlyChange;
      var nextCode = lzwState.nextCode;
      var dictionaryValues = lzwState.dictionaryValues;
      var dictionaryLengths = lzwState.dictionaryLengths;
      var dictionaryPrevCodes = lzwState.dictionaryPrevCodes;
      var codeLength = lzwState.codeLength;
      var prevCode = lzwState.prevCode;
      var currentSequence = lzwState.currentSequence;
      var currentSequenceLength = lzwState.currentSequenceLength;
      var decodedLength = 0;
      var currentBufferLength = this.bufferLength;
      var buffer = this.ensureBuffer(this.bufferLength + estimatedDecodedSize);
      for (i = 0; i < blockSize; i++) {
        var code = this.readBits(codeLength);
        var hasPrev = currentSequenceLength > 0;
        if (!code || code < 256) {
          currentSequence[0] = code;
          currentSequenceLength = 1;
        } else if (code >= 258) {
          if (code < nextCode) {
            currentSequenceLength = dictionaryLengths[code];
            for (j = currentSequenceLength - 1, q = code; j >= 0; j--) {
              currentSequence[j] = dictionaryValues[q];
              q = dictionaryPrevCodes[q];
            }
          } else {
            currentSequence[currentSequenceLength++] = currentSequence[0];
          }
        } else if (code === 256) {
          codeLength = 9;
          nextCode = 258;
          currentSequenceLength = 0;
          continue;
        } else {
          this.eof = true;
          delete this.lzwState;
          break;
        }
        if (hasPrev) {
          dictionaryPrevCodes[nextCode] = prevCode;
          dictionaryLengths[nextCode] = dictionaryLengths[prevCode] + 1;
          dictionaryValues[nextCode] = currentSequence[0];
          nextCode++;
          codeLength = nextCode + earlyChange & nextCode + earlyChange - 1 ? codeLength : Math.min(Math.log(nextCode + earlyChange) / 0.6931471805599453 + 1, 12) | 0;
        }
        prevCode = code;
        decodedLength += currentSequenceLength;
        if (estimatedDecodedSize < decodedLength) {
          do {
            estimatedDecodedSize += decodedSizeDelta;
          } while (estimatedDecodedSize < decodedLength);
          buffer = this.ensureBuffer(this.bufferLength + estimatedDecodedSize);
        }
        for (j = 0; j < currentSequenceLength; j++) {
          buffer[currentBufferLength++] = currentSequence[j];
        }
      }
      lzwState.nextCode = nextCode;
      lzwState.codeLength = codeLength;
      lzwState.prevCode = prevCode;
      lzwState.currentSequenceLength = currentSequenceLength;
      this.bufferLength = currentBufferLength;
    };
    LZWStream2.prototype.readBits = function(n) {
      var bitsCached = this.bitsCached;
      var cachedData = this.cachedData;
      while (bitsCached < n) {
        var c = this.stream.getByte();
        if (c === -1) {
          this.eof = true;
          return null;
        }
        cachedData = cachedData << 8 | c;
        bitsCached += 8;
      }
      this.bitsCached = bitsCached -= n;
      this.cachedData = cachedData;
      return cachedData >>> bitsCached & (1 << n) - 1;
    };
    return LZWStream2;
  }(DecodeStream_default)
);
var LZWStream_default = LZWStream;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/streams/RunLengthStream.js
var RunLengthStream = (
  /** @class */
  function(_super) {
    __extends(RunLengthStream2, _super);
    function RunLengthStream2(stream2, maybeLength) {
      var _this = _super.call(this, maybeLength) || this;
      _this.stream = stream2;
      return _this;
    }
    RunLengthStream2.prototype.readBlock = function() {
      var repeatHeader = this.stream.getBytes(2);
      if (!repeatHeader || repeatHeader.length < 2 || repeatHeader[0] === 128) {
        this.eof = true;
        return;
      }
      var buffer;
      var bufferLength = this.bufferLength;
      var n = repeatHeader[0];
      if (n < 128) {
        buffer = this.ensureBuffer(bufferLength + n + 1);
        buffer[bufferLength++] = repeatHeader[1];
        if (n > 0) {
          var source = this.stream.getBytes(n);
          buffer.set(source, bufferLength);
          bufferLength += n;
        }
      } else {
        n = 257 - n;
        var b = repeatHeader[1];
        buffer = this.ensureBuffer(bufferLength + n + 1);
        for (var i = 0; i < n; i++) {
          buffer[bufferLength++] = b;
        }
      }
      this.bufferLength = bufferLength;
    };
    return RunLengthStream2;
  }(DecodeStream_default)
);
var RunLengthStream_default = RunLengthStream;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/streams/decode.js
var decodeStream = function(stream2, encoding, params) {
  if (encoding === PDFName_default.of("FlateDecode")) {
    return new FlateStream_default(stream2);
  }
  if (encoding === PDFName_default.of("LZWDecode")) {
    var earlyChange = 1;
    if (params instanceof PDFDict_default) {
      var EarlyChange = params.lookup(PDFName_default.of("EarlyChange"));
      if (EarlyChange instanceof PDFNumber_default) {
        earlyChange = EarlyChange.asNumber();
      }
    }
    return new LZWStream_default(stream2, void 0, earlyChange);
  }
  if (encoding === PDFName_default.of("ASCII85Decode")) {
    return new Ascii85Stream_default(stream2);
  }
  if (encoding === PDFName_default.of("ASCIIHexDecode")) {
    return new AsciiHexStream_default(stream2);
  }
  if (encoding === PDFName_default.of("RunLengthDecode")) {
    return new RunLengthStream_default(stream2);
  }
  throw new UnsupportedEncodingError(encoding.asString());
};
var decodePDFRawStream = function(_a) {
  var dict = _a.dict, contents = _a.contents;
  var stream2 = new Stream_default(contents);
  var Filter = dict.lookup(PDFName_default.of("Filter"));
  var DecodeParms = dict.lookup(PDFName_default.of("DecodeParms"));
  if (Filter instanceof PDFName_default) {
    stream2 = decodeStream(stream2, Filter, DecodeParms);
  } else if (Filter instanceof PDFArray_default) {
    for (var idx = 0, len = Filter.size(); idx < len; idx++) {
      stream2 = decodeStream(stream2, Filter.lookup(idx, PDFName_default), DecodeParms && DecodeParms.lookupMaybe(idx, PDFDict_default));
    }
  } else if (!!Filter) {
    throw new UnexpectedObjectTypeError([PDFName_default, PDFArray_default], Filter);
  }
  return stream2;
};

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/embedders/PDFPageEmbedder.js
var fullPageBoundingBox = function(page) {
  var mediaBox = page.MediaBox();
  var width = mediaBox.lookup(2, PDFNumber_default).asNumber() - mediaBox.lookup(0, PDFNumber_default).asNumber();
  var height = mediaBox.lookup(3, PDFNumber_default).asNumber() - mediaBox.lookup(1, PDFNumber_default).asNumber();
  return { left: 0, bottom: 0, right: width, top: height };
};
var boundingBoxAdjustedMatrix = function(bb) {
  return [1, 0, 0, 1, -bb.left, -bb.bottom];
};
var PDFPageEmbedder = (
  /** @class */
  function() {
    function PDFPageEmbedder2(page, boundingBox, transformationMatrix) {
      this.page = page;
      var bb = boundingBox !== null && boundingBox !== void 0 ? boundingBox : fullPageBoundingBox(page);
      this.width = bb.right - bb.left;
      this.height = bb.top - bb.bottom;
      this.boundingBox = bb;
      this.transformationMatrix = transformationMatrix !== null && transformationMatrix !== void 0 ? transformationMatrix : boundingBoxAdjustedMatrix(bb);
    }
    PDFPageEmbedder2.for = function(page, boundingBox, transformationMatrix) {
      return __awaiter(this, void 0, void 0, function() {
        return __generator(this, function(_a) {
          return [2, new PDFPageEmbedder2(page, boundingBox, transformationMatrix)];
        });
      });
    };
    PDFPageEmbedder2.prototype.embedIntoContext = function(context, ref) {
      return __awaiter(this, void 0, void 0, function() {
        var _a, Contents, Resources, decodedContents, _b, left, bottom, right, top, xObject;
        return __generator(this, function(_c) {
          _a = this.page.normalizedEntries(), Contents = _a.Contents, Resources = _a.Resources;
          if (!Contents)
            throw new MissingPageContentsEmbeddingError();
          decodedContents = this.decodeContents(Contents);
          _b = this.boundingBox, left = _b.left, bottom = _b.bottom, right = _b.right, top = _b.top;
          xObject = context.flateStream(decodedContents, {
            Type: "XObject",
            Subtype: "Form",
            FormType: 1,
            BBox: [left, bottom, right, top],
            Matrix: this.transformationMatrix,
            Resources
          });
          if (ref) {
            context.assign(ref, xObject);
            return [2, ref];
          } else {
            return [2, context.register(xObject)];
          }
          return [
            2
            /*return*/
          ];
        });
      });
    };
    PDFPageEmbedder2.prototype.decodeContents = function(contents) {
      var newline = Uint8Array.of(CharCodes_default.Newline);
      var decodedContents = [];
      for (var idx = 0, len = contents.size(); idx < len; idx++) {
        var stream2 = contents.lookup(idx, PDFStream_default);
        var content = void 0;
        if (stream2 instanceof PDFRawStream_default) {
          content = decodePDFRawStream(stream2).decode();
        } else if (stream2 instanceof PDFContentStream_default) {
          content = stream2.getUnencodedContents();
        } else {
          throw new UnrecognizedStreamTypeError(stream2);
        }
        decodedContents.push(content, newline);
      }
      return mergeIntoTypedArray.apply(void 0, decodedContents);
    };
    return PDFPageEmbedder2;
  }()
);
var PDFPageEmbedder_default = PDFPageEmbedder;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/interactive/ViewerPreferences.js
var asEnum = function(rawValue, enumType) {
  if (rawValue === void 0)
    return void 0;
  return enumType[rawValue];
};
var NonFullScreenPageMode;
(function(NonFullScreenPageMode2) {
  NonFullScreenPageMode2["UseNone"] = "UseNone";
  NonFullScreenPageMode2["UseOutlines"] = "UseOutlines";
  NonFullScreenPageMode2["UseThumbs"] = "UseThumbs";
  NonFullScreenPageMode2["UseOC"] = "UseOC";
})(NonFullScreenPageMode || (NonFullScreenPageMode = {}));
var ReadingDirection;
(function(ReadingDirection2) {
  ReadingDirection2["L2R"] = "L2R";
  ReadingDirection2["R2L"] = "R2L";
})(ReadingDirection || (ReadingDirection = {}));
var PrintScaling;
(function(PrintScaling2) {
  PrintScaling2["None"] = "None";
  PrintScaling2["AppDefault"] = "AppDefault";
})(PrintScaling || (PrintScaling = {}));
var Duplex;
(function(Duplex2) {
  Duplex2["Simplex"] = "Simplex";
  Duplex2["DuplexFlipShortEdge"] = "DuplexFlipShortEdge";
  Duplex2["DuplexFlipLongEdge"] = "DuplexFlipLongEdge";
})(Duplex || (Duplex = {}));
var ViewerPreferences = (
  /** @class */
  function() {
    function ViewerPreferences2(dict) {
      this.dict = dict;
    }
    ViewerPreferences2.prototype.lookupBool = function(key) {
      var returnObj = this.dict.lookup(PDFName_default.of(key));
      if (returnObj instanceof PDFBool_default)
        return returnObj;
      return void 0;
    };
    ViewerPreferences2.prototype.lookupName = function(key) {
      var returnObj = this.dict.lookup(PDFName_default.of(key));
      if (returnObj instanceof PDFName_default)
        return returnObj;
      return void 0;
    };
    ViewerPreferences2.prototype.HideToolbar = function() {
      return this.lookupBool("HideToolbar");
    };
    ViewerPreferences2.prototype.HideMenubar = function() {
      return this.lookupBool("HideMenubar");
    };
    ViewerPreferences2.prototype.HideWindowUI = function() {
      return this.lookupBool("HideWindowUI");
    };
    ViewerPreferences2.prototype.FitWindow = function() {
      return this.lookupBool("FitWindow");
    };
    ViewerPreferences2.prototype.CenterWindow = function() {
      return this.lookupBool("CenterWindow");
    };
    ViewerPreferences2.prototype.DisplayDocTitle = function() {
      return this.lookupBool("DisplayDocTitle");
    };
    ViewerPreferences2.prototype.NonFullScreenPageMode = function() {
      return this.lookupName("NonFullScreenPageMode");
    };
    ViewerPreferences2.prototype.Direction = function() {
      return this.lookupName("Direction");
    };
    ViewerPreferences2.prototype.PrintScaling = function() {
      return this.lookupName("PrintScaling");
    };
    ViewerPreferences2.prototype.Duplex = function() {
      return this.lookupName("Duplex");
    };
    ViewerPreferences2.prototype.PickTrayByPDFSize = function() {
      return this.lookupBool("PickTrayByPDFSize");
    };
    ViewerPreferences2.prototype.PrintPageRange = function() {
      var PrintPageRange = this.dict.lookup(PDFName_default.of("PrintPageRange"));
      if (PrintPageRange instanceof PDFArray_default)
        return PrintPageRange;
      return void 0;
    };
    ViewerPreferences2.prototype.NumCopies = function() {
      var NumCopies = this.dict.lookup(PDFName_default.of("NumCopies"));
      if (NumCopies instanceof PDFNumber_default)
        return NumCopies;
      return void 0;
    };
    ViewerPreferences2.prototype.getHideToolbar = function() {
      var _a, _b;
      return (_b = (_a = this.HideToolbar()) === null || _a === void 0 ? void 0 : _a.asBoolean()) !== null && _b !== void 0 ? _b : false;
    };
    ViewerPreferences2.prototype.getHideMenubar = function() {
      var _a, _b;
      return (_b = (_a = this.HideMenubar()) === null || _a === void 0 ? void 0 : _a.asBoolean()) !== null && _b !== void 0 ? _b : false;
    };
    ViewerPreferences2.prototype.getHideWindowUI = function() {
      var _a, _b;
      return (_b = (_a = this.HideWindowUI()) === null || _a === void 0 ? void 0 : _a.asBoolean()) !== null && _b !== void 0 ? _b : false;
    };
    ViewerPreferences2.prototype.getFitWindow = function() {
      var _a, _b;
      return (_b = (_a = this.FitWindow()) === null || _a === void 0 ? void 0 : _a.asBoolean()) !== null && _b !== void 0 ? _b : false;
    };
    ViewerPreferences2.prototype.getCenterWindow = function() {
      var _a, _b;
      return (_b = (_a = this.CenterWindow()) === null || _a === void 0 ? void 0 : _a.asBoolean()) !== null && _b !== void 0 ? _b : false;
    };
    ViewerPreferences2.prototype.getDisplayDocTitle = function() {
      var _a, _b;
      return (_b = (_a = this.DisplayDocTitle()) === null || _a === void 0 ? void 0 : _a.asBoolean()) !== null && _b !== void 0 ? _b : false;
    };
    ViewerPreferences2.prototype.getNonFullScreenPageMode = function() {
      var _a, _b;
      var mode = (_a = this.NonFullScreenPageMode()) === null || _a === void 0 ? void 0 : _a.decodeText();
      return (_b = asEnum(mode, NonFullScreenPageMode)) !== null && _b !== void 0 ? _b : NonFullScreenPageMode.UseNone;
    };
    ViewerPreferences2.prototype.getReadingDirection = function() {
      var _a, _b;
      var direction = (_a = this.Direction()) === null || _a === void 0 ? void 0 : _a.decodeText();
      return (_b = asEnum(direction, ReadingDirection)) !== null && _b !== void 0 ? _b : ReadingDirection.L2R;
    };
    ViewerPreferences2.prototype.getPrintScaling = function() {
      var _a, _b;
      var scaling = (_a = this.PrintScaling()) === null || _a === void 0 ? void 0 : _a.decodeText();
      return (_b = asEnum(scaling, PrintScaling)) !== null && _b !== void 0 ? _b : PrintScaling.AppDefault;
    };
    ViewerPreferences2.prototype.getDuplex = function() {
      var _a;
      var duplex = (_a = this.Duplex()) === null || _a === void 0 ? void 0 : _a.decodeText();
      return asEnum(duplex, Duplex);
    };
    ViewerPreferences2.prototype.getPickTrayByPDFSize = function() {
      var _a;
      return (_a = this.PickTrayByPDFSize()) === null || _a === void 0 ? void 0 : _a.asBoolean();
    };
    ViewerPreferences2.prototype.getPrintPageRange = function() {
      var rng = this.PrintPageRange();
      if (!rng)
        return [];
      var pageRanges = [];
      for (var i = 0; i < rng.size(); i += 2) {
        var start = rng.lookup(i, PDFNumber_default).asNumber();
        var end = rng.lookup(i + 1, PDFNumber_default).asNumber();
        pageRanges.push({ start, end });
      }
      return pageRanges;
    };
    ViewerPreferences2.prototype.getNumCopies = function() {
      var _a, _b;
      return (_b = (_a = this.NumCopies()) === null || _a === void 0 ? void 0 : _a.asNumber()) !== null && _b !== void 0 ? _b : 1;
    };
    ViewerPreferences2.prototype.setHideToolbar = function(hideToolbar) {
      var HideToolbar = this.dict.context.obj(hideToolbar);
      this.dict.set(PDFName_default.of("HideToolbar"), HideToolbar);
    };
    ViewerPreferences2.prototype.setHideMenubar = function(hideMenubar) {
      var HideMenubar = this.dict.context.obj(hideMenubar);
      this.dict.set(PDFName_default.of("HideMenubar"), HideMenubar);
    };
    ViewerPreferences2.prototype.setHideWindowUI = function(hideWindowUI) {
      var HideWindowUI = this.dict.context.obj(hideWindowUI);
      this.dict.set(PDFName_default.of("HideWindowUI"), HideWindowUI);
    };
    ViewerPreferences2.prototype.setFitWindow = function(fitWindow) {
      var FitWindow = this.dict.context.obj(fitWindow);
      this.dict.set(PDFName_default.of("FitWindow"), FitWindow);
    };
    ViewerPreferences2.prototype.setCenterWindow = function(centerWindow) {
      var CenterWindow = this.dict.context.obj(centerWindow);
      this.dict.set(PDFName_default.of("CenterWindow"), CenterWindow);
    };
    ViewerPreferences2.prototype.setDisplayDocTitle = function(displayTitle) {
      var DisplayDocTitle = this.dict.context.obj(displayTitle);
      this.dict.set(PDFName_default.of("DisplayDocTitle"), DisplayDocTitle);
    };
    ViewerPreferences2.prototype.setNonFullScreenPageMode = function(nonFullScreenPageMode) {
      assertIsOneOf(nonFullScreenPageMode, "nonFullScreenPageMode", NonFullScreenPageMode);
      var mode = PDFName_default.of(nonFullScreenPageMode);
      this.dict.set(PDFName_default.of("NonFullScreenPageMode"), mode);
    };
    ViewerPreferences2.prototype.setReadingDirection = function(readingDirection) {
      assertIsOneOf(readingDirection, "readingDirection", ReadingDirection);
      var direction = PDFName_default.of(readingDirection);
      this.dict.set(PDFName_default.of("Direction"), direction);
    };
    ViewerPreferences2.prototype.setPrintScaling = function(printScaling) {
      assertIsOneOf(printScaling, "printScaling", PrintScaling);
      var scaling = PDFName_default.of(printScaling);
      this.dict.set(PDFName_default.of("PrintScaling"), scaling);
    };
    ViewerPreferences2.prototype.setDuplex = function(duplex) {
      assertIsOneOf(duplex, "duplex", Duplex);
      var dup = PDFName_default.of(duplex);
      this.dict.set(PDFName_default.of("Duplex"), dup);
    };
    ViewerPreferences2.prototype.setPickTrayByPDFSize = function(pickTrayByPDFSize) {
      var PickTrayByPDFSize = this.dict.context.obj(pickTrayByPDFSize);
      this.dict.set(PDFName_default.of("PickTrayByPDFSize"), PickTrayByPDFSize);
    };
    ViewerPreferences2.prototype.setPrintPageRange = function(printPageRange) {
      if (!Array.isArray(printPageRange))
        printPageRange = [printPageRange];
      var flatRange = [];
      for (var idx = 0, len = printPageRange.length; idx < len; idx++) {
        flatRange.push(printPageRange[idx].start);
        flatRange.push(printPageRange[idx].end);
      }
      assertEachIs(flatRange, "printPageRange", ["number"]);
      var pageRanges = this.dict.context.obj(flatRange);
      this.dict.set(PDFName_default.of("PrintPageRange"), pageRanges);
    };
    ViewerPreferences2.prototype.setNumCopies = function(numCopies) {
      assertRange(numCopies, "numCopies", 1, Number.MAX_VALUE);
      assertInteger(numCopies, "numCopies");
      var NumCopies = this.dict.context.obj(numCopies);
      this.dict.set(PDFName_default.of("NumCopies"), NumCopies);
    };
    ViewerPreferences2.fromDict = function(dict) {
      return new ViewerPreferences2(dict);
    };
    ViewerPreferences2.create = function(context) {
      var dict = context.obj({});
      return new ViewerPreferences2(dict);
    };
    return ViewerPreferences2;
  }()
);
var ViewerPreferences_default = ViewerPreferences;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/acroform/PDFAcroField.js
var tfRegex = /\/([^\0\t\n\f\r\ ]+)[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]+Tf/;
var PDFAcroField = (
  /** @class */
  function() {
    function PDFAcroField2(dict, ref) {
      this.dict = dict;
      this.ref = ref;
    }
    PDFAcroField2.prototype.T = function() {
      return this.dict.lookupMaybe(PDFName_default.of("T"), PDFString_default, PDFHexString_default);
    };
    PDFAcroField2.prototype.Ff = function() {
      var numberOrRef = this.getInheritableAttribute(PDFName_default.of("Ff"));
      return this.dict.context.lookupMaybe(numberOrRef, PDFNumber_default);
    };
    PDFAcroField2.prototype.V = function() {
      var valueOrRef = this.getInheritableAttribute(PDFName_default.of("V"));
      return this.dict.context.lookup(valueOrRef);
    };
    PDFAcroField2.prototype.Kids = function() {
      return this.dict.lookupMaybe(PDFName_default.of("Kids"), PDFArray_default);
    };
    PDFAcroField2.prototype.DA = function() {
      var da = this.dict.lookup(PDFName_default.of("DA"));
      if (da instanceof PDFString_default || da instanceof PDFHexString_default)
        return da;
      return void 0;
    };
    PDFAcroField2.prototype.setKids = function(kids) {
      this.dict.set(PDFName_default.of("Kids"), this.dict.context.obj(kids));
    };
    PDFAcroField2.prototype.getParent = function() {
      var parentRef = this.dict.get(PDFName_default.of("Parent"));
      if (parentRef instanceof PDFRef_default) {
        var parent_1 = this.dict.lookup(PDFName_default.of("Parent"), PDFDict_default);
        return new PDFAcroField2(parent_1, parentRef);
      }
      return void 0;
    };
    PDFAcroField2.prototype.setParent = function(parent) {
      if (!parent)
        this.dict.delete(PDFName_default.of("Parent"));
      else
        this.dict.set(PDFName_default.of("Parent"), parent);
    };
    PDFAcroField2.prototype.getFullyQualifiedName = function() {
      var parent = this.getParent();
      if (!parent)
        return this.getPartialName();
      return parent.getFullyQualifiedName() + "." + this.getPartialName();
    };
    PDFAcroField2.prototype.getPartialName = function() {
      var _a;
      return (_a = this.T()) === null || _a === void 0 ? void 0 : _a.decodeText();
    };
    PDFAcroField2.prototype.setPartialName = function(partialName) {
      if (!partialName)
        this.dict.delete(PDFName_default.of("T"));
      else
        this.dict.set(PDFName_default.of("T"), PDFHexString_default.fromText(partialName));
    };
    PDFAcroField2.prototype.setDefaultAppearance = function(appearance) {
      this.dict.set(PDFName_default.of("DA"), PDFString_default.of(appearance));
    };
    PDFAcroField2.prototype.getDefaultAppearance = function() {
      var DA = this.DA();
      if (DA instanceof PDFHexString_default) {
        return DA.decodeText();
      }
      return DA === null || DA === void 0 ? void 0 : DA.asString();
    };
    PDFAcroField2.prototype.setFontSize = function(fontSize) {
      var _a;
      var name = (_a = this.getFullyQualifiedName()) !== null && _a !== void 0 ? _a : "";
      var da = this.getDefaultAppearance();
      if (!da)
        throw new MissingDAEntryError(name);
      var daMatch = findLastMatch(da, tfRegex);
      if (!daMatch.match)
        throw new MissingTfOperatorError(name);
      var daStart = da.slice(0, daMatch.pos - daMatch.match[0].length);
      var daEnd = daMatch.pos <= da.length ? da.slice(daMatch.pos) : "";
      var fontName = daMatch.match[1];
      var modifiedDa = daStart + " /" + fontName + " " + fontSize + " Tf " + daEnd;
      this.setDefaultAppearance(modifiedDa);
    };
    PDFAcroField2.prototype.getFlags = function() {
      var _a, _b;
      return (_b = (_a = this.Ff()) === null || _a === void 0 ? void 0 : _a.asNumber()) !== null && _b !== void 0 ? _b : 0;
    };
    PDFAcroField2.prototype.setFlags = function(flags) {
      this.dict.set(PDFName_default.of("Ff"), PDFNumber_default.of(flags));
    };
    PDFAcroField2.prototype.hasFlag = function(flag3) {
      var flags = this.getFlags();
      return (flags & flag3) !== 0;
    };
    PDFAcroField2.prototype.setFlag = function(flag3) {
      var flags = this.getFlags();
      this.setFlags(flags | flag3);
    };
    PDFAcroField2.prototype.clearFlag = function(flag3) {
      var flags = this.getFlags();
      this.setFlags(flags & ~flag3);
    };
    PDFAcroField2.prototype.setFlagTo = function(flag3, enable) {
      if (enable)
        this.setFlag(flag3);
      else
        this.clearFlag(flag3);
    };
    PDFAcroField2.prototype.getInheritableAttribute = function(name) {
      var attribute;
      this.ascend(function(node) {
        if (!attribute)
          attribute = node.dict.get(name);
      });
      return attribute;
    };
    PDFAcroField2.prototype.ascend = function(visitor) {
      visitor(this);
      var parent = this.getParent();
      if (parent)
        parent.ascend(visitor);
    };
    return PDFAcroField2;
  }()
);
var PDFAcroField_default = PDFAcroField;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/annotation/BorderStyle.js
var BorderStyle = (
  /** @class */
  function() {
    function BorderStyle2(dict) {
      this.dict = dict;
    }
    BorderStyle2.prototype.W = function() {
      var W = this.dict.lookup(PDFName_default.of("W"));
      if (W instanceof PDFNumber_default)
        return W;
      return void 0;
    };
    BorderStyle2.prototype.getWidth = function() {
      var _a, _b;
      return (_b = (_a = this.W()) === null || _a === void 0 ? void 0 : _a.asNumber()) !== null && _b !== void 0 ? _b : 1;
    };
    BorderStyle2.prototype.setWidth = function(width) {
      var W = this.dict.context.obj(width);
      this.dict.set(PDFName_default.of("W"), W);
    };
    BorderStyle2.fromDict = function(dict) {
      return new BorderStyle2(dict);
    };
    return BorderStyle2;
  }()
);
var BorderStyle_default = BorderStyle;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/annotation/PDFAnnotation.js
var PDFAnnotation = (
  /** @class */
  function() {
    function PDFAnnotation2(dict) {
      this.dict = dict;
    }
    PDFAnnotation2.prototype.Rect = function() {
      return this.dict.lookup(PDFName_default.of("Rect"), PDFArray_default);
    };
    PDFAnnotation2.prototype.AP = function() {
      return this.dict.lookupMaybe(PDFName_default.of("AP"), PDFDict_default);
    };
    PDFAnnotation2.prototype.F = function() {
      var numberOrRef = this.dict.lookup(PDFName_default.of("F"));
      return this.dict.context.lookupMaybe(numberOrRef, PDFNumber_default);
    };
    PDFAnnotation2.prototype.getRectangle = function() {
      var _a;
      var Rect = this.Rect();
      return (_a = Rect === null || Rect === void 0 ? void 0 : Rect.asRectangle()) !== null && _a !== void 0 ? _a : { x: 0, y: 0, width: 0, height: 0 };
    };
    PDFAnnotation2.prototype.setRectangle = function(rect) {
      var x = rect.x, y = rect.y, width = rect.width, height = rect.height;
      var Rect = this.dict.context.obj([x, y, x + width, y + height]);
      this.dict.set(PDFName_default.of("Rect"), Rect);
    };
    PDFAnnotation2.prototype.getAppearanceState = function() {
      var AS = this.dict.lookup(PDFName_default.of("AS"));
      if (AS instanceof PDFName_default)
        return AS;
      return void 0;
    };
    PDFAnnotation2.prototype.setAppearanceState = function(state) {
      this.dict.set(PDFName_default.of("AS"), state);
    };
    PDFAnnotation2.prototype.setAppearances = function(appearances) {
      this.dict.set(PDFName_default.of("AP"), appearances);
    };
    PDFAnnotation2.prototype.ensureAP = function() {
      var AP = this.AP();
      if (!AP) {
        AP = this.dict.context.obj({});
        this.dict.set(PDFName_default.of("AP"), AP);
      }
      return AP;
    };
    PDFAnnotation2.prototype.getNormalAppearance = function() {
      var AP = this.ensureAP();
      var N = AP.get(PDFName_default.of("N"));
      if (N instanceof PDFRef_default || N instanceof PDFDict_default)
        return N;
      throw new Error("Unexpected N type: " + (N === null || N === void 0 ? void 0 : N.constructor.name));
    };
    PDFAnnotation2.prototype.setNormalAppearance = function(appearance) {
      var AP = this.ensureAP();
      AP.set(PDFName_default.of("N"), appearance);
    };
    PDFAnnotation2.prototype.setRolloverAppearance = function(appearance) {
      var AP = this.ensureAP();
      AP.set(PDFName_default.of("R"), appearance);
    };
    PDFAnnotation2.prototype.setDownAppearance = function(appearance) {
      var AP = this.ensureAP();
      AP.set(PDFName_default.of("D"), appearance);
    };
    PDFAnnotation2.prototype.removeRolloverAppearance = function() {
      var AP = this.AP();
      AP === null || AP === void 0 ? void 0 : AP.delete(PDFName_default.of("R"));
    };
    PDFAnnotation2.prototype.removeDownAppearance = function() {
      var AP = this.AP();
      AP === null || AP === void 0 ? void 0 : AP.delete(PDFName_default.of("D"));
    };
    PDFAnnotation2.prototype.getAppearances = function() {
      var AP = this.AP();
      if (!AP)
        return void 0;
      var N = AP.lookup(PDFName_default.of("N"), PDFDict_default, PDFStream_default);
      var R = AP.lookupMaybe(PDFName_default.of("R"), PDFDict_default, PDFStream_default);
      var D = AP.lookupMaybe(PDFName_default.of("D"), PDFDict_default, PDFStream_default);
      return { normal: N, rollover: R, down: D };
    };
    PDFAnnotation2.prototype.getFlags = function() {
      var _a, _b;
      return (_b = (_a = this.F()) === null || _a === void 0 ? void 0 : _a.asNumber()) !== null && _b !== void 0 ? _b : 0;
    };
    PDFAnnotation2.prototype.setFlags = function(flags) {
      this.dict.set(PDFName_default.of("F"), PDFNumber_default.of(flags));
    };
    PDFAnnotation2.prototype.hasFlag = function(flag3) {
      var flags = this.getFlags();
      return (flags & flag3) !== 0;
    };
    PDFAnnotation2.prototype.setFlag = function(flag3) {
      var flags = this.getFlags();
      this.setFlags(flags | flag3);
    };
    PDFAnnotation2.prototype.clearFlag = function(flag3) {
      var flags = this.getFlags();
      this.setFlags(flags & ~flag3);
    };
    PDFAnnotation2.prototype.setFlagTo = function(flag3, enable) {
      if (enable)
        this.setFlag(flag3);
      else
        this.clearFlag(flag3);
    };
    PDFAnnotation2.fromDict = function(dict) {
      return new PDFAnnotation2(dict);
    };
    return PDFAnnotation2;
  }()
);
var PDFAnnotation_default = PDFAnnotation;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/annotation/AppearanceCharacteristics.js
var AppearanceCharacteristics = (
  /** @class */
  function() {
    function AppearanceCharacteristics2(dict) {
      this.dict = dict;
    }
    AppearanceCharacteristics2.prototype.R = function() {
      var R = this.dict.lookup(PDFName_default.of("R"));
      if (R instanceof PDFNumber_default)
        return R;
      return void 0;
    };
    AppearanceCharacteristics2.prototype.BC = function() {
      var BC = this.dict.lookup(PDFName_default.of("BC"));
      if (BC instanceof PDFArray_default)
        return BC;
      return void 0;
    };
    AppearanceCharacteristics2.prototype.BG = function() {
      var BG = this.dict.lookup(PDFName_default.of("BG"));
      if (BG instanceof PDFArray_default)
        return BG;
      return void 0;
    };
    AppearanceCharacteristics2.prototype.CA = function() {
      var CA = this.dict.lookup(PDFName_default.of("CA"));
      if (CA instanceof PDFHexString_default || CA instanceof PDFString_default)
        return CA;
      return void 0;
    };
    AppearanceCharacteristics2.prototype.RC = function() {
      var RC = this.dict.lookup(PDFName_default.of("RC"));
      if (RC instanceof PDFHexString_default || RC instanceof PDFString_default)
        return RC;
      return void 0;
    };
    AppearanceCharacteristics2.prototype.AC = function() {
      var AC = this.dict.lookup(PDFName_default.of("AC"));
      if (AC instanceof PDFHexString_default || AC instanceof PDFString_default)
        return AC;
      return void 0;
    };
    AppearanceCharacteristics2.prototype.getRotation = function() {
      var _a;
      return (_a = this.R()) === null || _a === void 0 ? void 0 : _a.asNumber();
    };
    AppearanceCharacteristics2.prototype.getBorderColor = function() {
      var BC = this.BC();
      if (!BC)
        return void 0;
      var components = [];
      for (var idx = 0, len = BC === null || BC === void 0 ? void 0 : BC.size(); idx < len; idx++) {
        var component = BC.get(idx);
        if (component instanceof PDFNumber_default)
          components.push(component.asNumber());
      }
      return components;
    };
    AppearanceCharacteristics2.prototype.getBackgroundColor = function() {
      var BG = this.BG();
      if (!BG)
        return void 0;
      var components = [];
      for (var idx = 0, len = BG === null || BG === void 0 ? void 0 : BG.size(); idx < len; idx++) {
        var component = BG.get(idx);
        if (component instanceof PDFNumber_default)
          components.push(component.asNumber());
      }
      return components;
    };
    AppearanceCharacteristics2.prototype.getCaptions = function() {
      var CA = this.CA();
      var RC = this.RC();
      var AC = this.AC();
      return {
        normal: CA === null || CA === void 0 ? void 0 : CA.decodeText(),
        rollover: RC === null || RC === void 0 ? void 0 : RC.decodeText(),
        down: AC === null || AC === void 0 ? void 0 : AC.decodeText()
      };
    };
    AppearanceCharacteristics2.prototype.setRotation = function(rotation) {
      var R = this.dict.context.obj(rotation);
      this.dict.set(PDFName_default.of("R"), R);
    };
    AppearanceCharacteristics2.prototype.setBorderColor = function(color) {
      var BC = this.dict.context.obj(color);
      this.dict.set(PDFName_default.of("BC"), BC);
    };
    AppearanceCharacteristics2.prototype.setBackgroundColor = function(color) {
      var BG = this.dict.context.obj(color);
      this.dict.set(PDFName_default.of("BG"), BG);
    };
    AppearanceCharacteristics2.prototype.setCaptions = function(captions) {
      var CA = PDFHexString_default.fromText(captions.normal);
      this.dict.set(PDFName_default.of("CA"), CA);
      if (captions.rollover) {
        var RC = PDFHexString_default.fromText(captions.rollover);
        this.dict.set(PDFName_default.of("RC"), RC);
      } else {
        this.dict.delete(PDFName_default.of("RC"));
      }
      if (captions.down) {
        var AC = PDFHexString_default.fromText(captions.down);
        this.dict.set(PDFName_default.of("AC"), AC);
      } else {
        this.dict.delete(PDFName_default.of("AC"));
      }
    };
    AppearanceCharacteristics2.fromDict = function(dict) {
      return new AppearanceCharacteristics2(dict);
    };
    return AppearanceCharacteristics2;
  }()
);
var AppearanceCharacteristics_default = AppearanceCharacteristics;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/annotation/PDFWidgetAnnotation.js
var PDFWidgetAnnotation = (
  /** @class */
  function(_super) {
    __extends(PDFWidgetAnnotation2, _super);
    function PDFWidgetAnnotation2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    PDFWidgetAnnotation2.prototype.MK = function() {
      var MK = this.dict.lookup(PDFName_default.of("MK"));
      if (MK instanceof PDFDict_default)
        return MK;
      return void 0;
    };
    PDFWidgetAnnotation2.prototype.BS = function() {
      var BS = this.dict.lookup(PDFName_default.of("BS"));
      if (BS instanceof PDFDict_default)
        return BS;
      return void 0;
    };
    PDFWidgetAnnotation2.prototype.DA = function() {
      var da = this.dict.lookup(PDFName_default.of("DA"));
      if (da instanceof PDFString_default || da instanceof PDFHexString_default)
        return da;
      return void 0;
    };
    PDFWidgetAnnotation2.prototype.P = function() {
      var P = this.dict.get(PDFName_default.of("P"));
      if (P instanceof PDFRef_default)
        return P;
      return void 0;
    };
    PDFWidgetAnnotation2.prototype.setP = function(page) {
      this.dict.set(PDFName_default.of("P"), page);
    };
    PDFWidgetAnnotation2.prototype.setDefaultAppearance = function(appearance) {
      this.dict.set(PDFName_default.of("DA"), PDFString_default.of(appearance));
    };
    PDFWidgetAnnotation2.prototype.getDefaultAppearance = function() {
      var DA = this.DA();
      if (DA instanceof PDFHexString_default) {
        return DA.decodeText();
      }
      return DA === null || DA === void 0 ? void 0 : DA.asString();
    };
    PDFWidgetAnnotation2.prototype.getAppearanceCharacteristics = function() {
      var MK = this.MK();
      if (MK)
        return AppearanceCharacteristics_default.fromDict(MK);
      return void 0;
    };
    PDFWidgetAnnotation2.prototype.getOrCreateAppearanceCharacteristics = function() {
      var MK = this.MK();
      if (MK)
        return AppearanceCharacteristics_default.fromDict(MK);
      var ac = AppearanceCharacteristics_default.fromDict(this.dict.context.obj({}));
      this.dict.set(PDFName_default.of("MK"), ac.dict);
      return ac;
    };
    PDFWidgetAnnotation2.prototype.getBorderStyle = function() {
      var BS = this.BS();
      if (BS)
        return BorderStyle_default.fromDict(BS);
      return void 0;
    };
    PDFWidgetAnnotation2.prototype.getOrCreateBorderStyle = function() {
      var BS = this.BS();
      if (BS)
        return BorderStyle_default.fromDict(BS);
      var bs = BorderStyle_default.fromDict(this.dict.context.obj({}));
      this.dict.set(PDFName_default.of("BS"), bs.dict);
      return bs;
    };
    PDFWidgetAnnotation2.prototype.getOnValue = function() {
      var _a;
      var normal = (_a = this.getAppearances()) === null || _a === void 0 ? void 0 : _a.normal;
      if (normal instanceof PDFDict_default) {
        var keys = normal.keys();
        for (var idx = 0, len = keys.length; idx < len; idx++) {
          var key = keys[idx];
          if (key !== PDFName_default.of("Off"))
            return key;
        }
      }
      return void 0;
    };
    PDFWidgetAnnotation2.fromDict = function(dict) {
      return new PDFWidgetAnnotation2(dict);
    };
    PDFWidgetAnnotation2.create = function(context, parent) {
      var dict = context.obj({
        Type: "Annot",
        Subtype: "Widget",
        Rect: [0, 0, 0, 0],
        Parent: parent
      });
      return new PDFWidgetAnnotation2(dict);
    };
    return PDFWidgetAnnotation2;
  }(PDFAnnotation_default)
);
var PDFWidgetAnnotation_default = PDFWidgetAnnotation;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/acroform/PDFAcroTerminal.js
var PDFAcroTerminal = (
  /** @class */
  function(_super) {
    __extends(PDFAcroTerminal2, _super);
    function PDFAcroTerminal2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    PDFAcroTerminal2.prototype.FT = function() {
      var nameOrRef = this.getInheritableAttribute(PDFName_default.of("FT"));
      return this.dict.context.lookup(nameOrRef, PDFName_default);
    };
    PDFAcroTerminal2.prototype.getWidgets = function() {
      var kidDicts = this.Kids();
      if (!kidDicts)
        return [PDFWidgetAnnotation_default.fromDict(this.dict)];
      var widgets = new Array(kidDicts.size());
      for (var idx = 0, len = kidDicts.size(); idx < len; idx++) {
        var dict = kidDicts.lookup(idx, PDFDict_default);
        widgets[idx] = PDFWidgetAnnotation_default.fromDict(dict);
      }
      return widgets;
    };
    PDFAcroTerminal2.prototype.addWidget = function(ref) {
      var Kids = this.normalizedEntries().Kids;
      Kids.push(ref);
    };
    PDFAcroTerminal2.prototype.removeWidget = function(idx) {
      var kidDicts = this.Kids();
      if (!kidDicts) {
        if (idx !== 0)
          throw new IndexOutOfBoundsError(idx, 0, 0);
        this.setKids([]);
      } else {
        if (idx < 0 || idx > kidDicts.size()) {
          throw new IndexOutOfBoundsError(idx, 0, kidDicts.size());
        }
        kidDicts.remove(idx);
      }
    };
    PDFAcroTerminal2.prototype.normalizedEntries = function() {
      var Kids = this.Kids();
      if (!Kids) {
        Kids = this.dict.context.obj([this.ref]);
        this.dict.set(PDFName_default.of("Kids"), Kids);
      }
      return { Kids };
    };
    PDFAcroTerminal2.fromDict = function(dict, ref) {
      return new PDFAcroTerminal2(dict, ref);
    };
    return PDFAcroTerminal2;
  }(PDFAcroField_default)
);
var PDFAcroTerminal_default = PDFAcroTerminal;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/acroform/PDFAcroButton.js
var PDFAcroButton = (
  /** @class */
  function(_super) {
    __extends(PDFAcroButton2, _super);
    function PDFAcroButton2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    PDFAcroButton2.prototype.Opt = function() {
      return this.dict.lookupMaybe(PDFName_default.of("Opt"), PDFString_default, PDFHexString_default, PDFArray_default);
    };
    PDFAcroButton2.prototype.setOpt = function(opt) {
      this.dict.set(PDFName_default.of("Opt"), this.dict.context.obj(opt));
    };
    PDFAcroButton2.prototype.getExportValues = function() {
      var opt = this.Opt();
      if (!opt)
        return void 0;
      if (opt instanceof PDFString_default || opt instanceof PDFHexString_default) {
        return [opt];
      }
      var values2 = [];
      for (var idx = 0, len = opt.size(); idx < len; idx++) {
        var value = opt.lookup(idx);
        if (value instanceof PDFString_default || value instanceof PDFHexString_default) {
          values2.push(value);
        }
      }
      return values2;
    };
    PDFAcroButton2.prototype.removeExportValue = function(idx) {
      var opt = this.Opt();
      if (!opt)
        return;
      if (opt instanceof PDFString_default || opt instanceof PDFHexString_default) {
        if (idx !== 0)
          throw new IndexOutOfBoundsError(idx, 0, 0);
        this.setOpt([]);
      } else {
        if (idx < 0 || idx > opt.size()) {
          throw new IndexOutOfBoundsError(idx, 0, opt.size());
        }
        opt.remove(idx);
      }
    };
    PDFAcroButton2.prototype.normalizeExportValues = function() {
      var _a, _b, _c, _d;
      var exportValues = (_a = this.getExportValues()) !== null && _a !== void 0 ? _a : [];
      var Opt = [];
      var widgets = this.getWidgets();
      for (var idx = 0, len = widgets.length; idx < len; idx++) {
        var widget = widgets[idx];
        var exportVal = (_b = exportValues[idx]) !== null && _b !== void 0 ? _b : PDFHexString_default.fromText((_d = (_c = widget.getOnValue()) === null || _c === void 0 ? void 0 : _c.decodeText()) !== null && _d !== void 0 ? _d : "");
        Opt.push(exportVal);
      }
      this.setOpt(Opt);
    };
    PDFAcroButton2.prototype.addOpt = function(opt, useExistingOptIdx) {
      var _a;
      this.normalizeExportValues();
      var optText = opt.decodeText();
      var existingIdx;
      if (useExistingOptIdx) {
        var exportValues = (_a = this.getExportValues()) !== null && _a !== void 0 ? _a : [];
        for (var idx = 0, len = exportValues.length; idx < len; idx++) {
          var exportVal = exportValues[idx];
          if (exportVal.decodeText() === optText)
            existingIdx = idx;
        }
      }
      var Opt = this.Opt();
      Opt.push(opt);
      return existingIdx !== null && existingIdx !== void 0 ? existingIdx : Opt.size() - 1;
    };
    PDFAcroButton2.prototype.addWidgetWithOpt = function(widget, opt, useExistingOptIdx) {
      var optIdx = this.addOpt(opt, useExistingOptIdx);
      var apStateValue = PDFName_default.of(String(optIdx));
      this.addWidget(widget);
      return apStateValue;
    };
    return PDFAcroButton2;
  }(PDFAcroTerminal_default)
);
var PDFAcroButton_default = PDFAcroButton;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/acroform/PDFAcroCheckBox.js
var PDFAcroCheckBox = (
  /** @class */
  function(_super) {
    __extends(PDFAcroCheckBox2, _super);
    function PDFAcroCheckBox2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    PDFAcroCheckBox2.prototype.setValue = function(value) {
      var _a;
      var onValue = (_a = this.getOnValue()) !== null && _a !== void 0 ? _a : PDFName_default.of("Yes");
      if (value !== onValue && value !== PDFName_default.of("Off")) {
        throw new InvalidAcroFieldValueError();
      }
      this.dict.set(PDFName_default.of("V"), value);
      var widgets = this.getWidgets();
      for (var idx = 0, len = widgets.length; idx < len; idx++) {
        var widget = widgets[idx];
        var state = widget.getOnValue() === value ? value : PDFName_default.of("Off");
        widget.setAppearanceState(state);
      }
    };
    PDFAcroCheckBox2.prototype.getValue = function() {
      var v = this.V();
      if (v instanceof PDFName_default)
        return v;
      return PDFName_default.of("Off");
    };
    PDFAcroCheckBox2.prototype.getOnValue = function() {
      var widget = this.getWidgets()[0];
      return widget === null || widget === void 0 ? void 0 : widget.getOnValue();
    };
    PDFAcroCheckBox2.fromDict = function(dict, ref) {
      return new PDFAcroCheckBox2(dict, ref);
    };
    PDFAcroCheckBox2.create = function(context) {
      var dict = context.obj({
        FT: "Btn",
        Kids: []
      });
      var ref = context.register(dict);
      return new PDFAcroCheckBox2(dict, ref);
    };
    return PDFAcroCheckBox2;
  }(PDFAcroButton_default)
);
var PDFAcroCheckBox_default = PDFAcroCheckBox;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/acroform/flags.js
var flag = function(bitIndex) {
  return 1 << bitIndex;
};
var AcroFieldFlags;
(function(AcroFieldFlags2) {
  AcroFieldFlags2[AcroFieldFlags2["ReadOnly"] = flag(1 - 1)] = "ReadOnly";
  AcroFieldFlags2[AcroFieldFlags2["Required"] = flag(2 - 1)] = "Required";
  AcroFieldFlags2[AcroFieldFlags2["NoExport"] = flag(3 - 1)] = "NoExport";
})(AcroFieldFlags || (AcroFieldFlags = {}));
var AcroButtonFlags;
(function(AcroButtonFlags2) {
  AcroButtonFlags2[AcroButtonFlags2["NoToggleToOff"] = flag(15 - 1)] = "NoToggleToOff";
  AcroButtonFlags2[AcroButtonFlags2["Radio"] = flag(16 - 1)] = "Radio";
  AcroButtonFlags2[AcroButtonFlags2["PushButton"] = flag(17 - 1)] = "PushButton";
  AcroButtonFlags2[AcroButtonFlags2["RadiosInUnison"] = flag(26 - 1)] = "RadiosInUnison";
})(AcroButtonFlags || (AcroButtonFlags = {}));
var AcroTextFlags;
(function(AcroTextFlags2) {
  AcroTextFlags2[AcroTextFlags2["Multiline"] = flag(13 - 1)] = "Multiline";
  AcroTextFlags2[AcroTextFlags2["Password"] = flag(14 - 1)] = "Password";
  AcroTextFlags2[AcroTextFlags2["FileSelect"] = flag(21 - 1)] = "FileSelect";
  AcroTextFlags2[AcroTextFlags2["DoNotSpellCheck"] = flag(23 - 1)] = "DoNotSpellCheck";
  AcroTextFlags2[AcroTextFlags2["DoNotScroll"] = flag(24 - 1)] = "DoNotScroll";
  AcroTextFlags2[AcroTextFlags2["Comb"] = flag(25 - 1)] = "Comb";
  AcroTextFlags2[AcroTextFlags2["RichText"] = flag(26 - 1)] = "RichText";
})(AcroTextFlags || (AcroTextFlags = {}));
var AcroChoiceFlags;
(function(AcroChoiceFlags2) {
  AcroChoiceFlags2[AcroChoiceFlags2["Combo"] = flag(18 - 1)] = "Combo";
  AcroChoiceFlags2[AcroChoiceFlags2["Edit"] = flag(19 - 1)] = "Edit";
  AcroChoiceFlags2[AcroChoiceFlags2["Sort"] = flag(20 - 1)] = "Sort";
  AcroChoiceFlags2[AcroChoiceFlags2["MultiSelect"] = flag(22 - 1)] = "MultiSelect";
  AcroChoiceFlags2[AcroChoiceFlags2["DoNotSpellCheck"] = flag(23 - 1)] = "DoNotSpellCheck";
  AcroChoiceFlags2[AcroChoiceFlags2["CommitOnSelChange"] = flag(27 - 1)] = "CommitOnSelChange";
})(AcroChoiceFlags || (AcroChoiceFlags = {}));

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/acroform/PDFAcroChoice.js
var PDFAcroChoice = (
  /** @class */
  function(_super) {
    __extends(PDFAcroChoice2, _super);
    function PDFAcroChoice2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    PDFAcroChoice2.prototype.setValues = function(values2) {
      if (this.hasFlag(AcroChoiceFlags.Combo) && !this.hasFlag(AcroChoiceFlags.Edit) && !this.valuesAreValid(values2)) {
        throw new InvalidAcroFieldValueError();
      }
      if (values2.length === 0) {
        this.dict.delete(PDFName_default.of("V"));
      }
      if (values2.length === 1) {
        this.dict.set(PDFName_default.of("V"), values2[0]);
      }
      if (values2.length > 1) {
        if (!this.hasFlag(AcroChoiceFlags.MultiSelect)) {
          throw new MultiSelectValueError();
        }
        this.dict.set(PDFName_default.of("V"), this.dict.context.obj(values2));
      }
      this.updateSelectedIndices(values2);
    };
    PDFAcroChoice2.prototype.valuesAreValid = function(values2) {
      var options = this.getOptions();
      var _loop_1 = function(idx2, len2) {
        var val = values2[idx2].decodeText();
        if (!options.find(function(o) {
          return val === (o.display || o.value).decodeText();
        })) {
          return { value: false };
        }
      };
      for (var idx = 0, len = values2.length; idx < len; idx++) {
        var state_1 = _loop_1(idx, len);
        if (typeof state_1 === "object")
          return state_1.value;
      }
      return true;
    };
    PDFAcroChoice2.prototype.updateSelectedIndices = function(values2) {
      if (values2.length > 1) {
        var indices = new Array(values2.length);
        var options = this.getOptions();
        var _loop_2 = function(idx2, len2) {
          var val = values2[idx2].decodeText();
          indices[idx2] = options.findIndex(function(o) {
            return val === (o.display || o.value).decodeText();
          });
        };
        for (var idx = 0, len = values2.length; idx < len; idx++) {
          _loop_2(idx, len);
        }
        this.dict.set(PDFName_default.of("I"), this.dict.context.obj(indices.sort()));
      } else {
        this.dict.delete(PDFName_default.of("I"));
      }
    };
    PDFAcroChoice2.prototype.getValues = function() {
      var v = this.V();
      if (v instanceof PDFString_default || v instanceof PDFHexString_default)
        return [v];
      if (v instanceof PDFArray_default) {
        var values2 = [];
        for (var idx = 0, len = v.size(); idx < len; idx++) {
          var value = v.lookup(idx);
          if (value instanceof PDFString_default || value instanceof PDFHexString_default) {
            values2.push(value);
          }
        }
        return values2;
      }
      return [];
    };
    PDFAcroChoice2.prototype.Opt = function() {
      return this.dict.lookupMaybe(PDFName_default.of("Opt"), PDFString_default, PDFHexString_default, PDFArray_default);
    };
    PDFAcroChoice2.prototype.setOptions = function(options) {
      var newOpt = new Array(options.length);
      for (var idx = 0, len = options.length; idx < len; idx++) {
        var _a = options[idx], value = _a.value, display = _a.display;
        newOpt[idx] = this.dict.context.obj([value, display || value]);
      }
      this.dict.set(PDFName_default.of("Opt"), this.dict.context.obj(newOpt));
    };
    PDFAcroChoice2.prototype.getOptions = function() {
      var Opt = this.Opt();
      if (Opt instanceof PDFString_default || Opt instanceof PDFHexString_default) {
        return [{ value: Opt, display: Opt }];
      }
      if (Opt instanceof PDFArray_default) {
        var res = [];
        for (var idx = 0, len = Opt.size(); idx < len; idx++) {
          var item = Opt.lookup(idx);
          if (item instanceof PDFString_default || item instanceof PDFHexString_default) {
            res.push({ value: item, display: item });
          }
          if (item instanceof PDFArray_default) {
            if (item.size() > 0) {
              var first = item.lookup(0, PDFString_default, PDFHexString_default);
              var second = item.lookupMaybe(1, PDFString_default, PDFHexString_default);
              res.push({ value: first, display: second || first });
            }
          }
        }
        return res;
      }
      return [];
    };
    return PDFAcroChoice2;
  }(PDFAcroTerminal_default)
);
var PDFAcroChoice_default = PDFAcroChoice;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/acroform/PDFAcroComboBox.js
var PDFAcroComboBox = (
  /** @class */
  function(_super) {
    __extends(PDFAcroComboBox2, _super);
    function PDFAcroComboBox2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    PDFAcroComboBox2.fromDict = function(dict, ref) {
      return new PDFAcroComboBox2(dict, ref);
    };
    PDFAcroComboBox2.create = function(context) {
      var dict = context.obj({
        FT: "Ch",
        Ff: AcroChoiceFlags.Combo,
        Kids: []
      });
      var ref = context.register(dict);
      return new PDFAcroComboBox2(dict, ref);
    };
    return PDFAcroComboBox2;
  }(PDFAcroChoice_default)
);
var PDFAcroComboBox_default = PDFAcroComboBox;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/acroform/PDFAcroNonTerminal.js
var PDFAcroNonTerminal = (
  /** @class */
  function(_super) {
    __extends(PDFAcroNonTerminal2, _super);
    function PDFAcroNonTerminal2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    PDFAcroNonTerminal2.prototype.addField = function(field) {
      var Kids = this.normalizedEntries().Kids;
      Kids === null || Kids === void 0 ? void 0 : Kids.push(field);
    };
    PDFAcroNonTerminal2.prototype.normalizedEntries = function() {
      var Kids = this.Kids();
      if (!Kids) {
        Kids = this.dict.context.obj([]);
        this.dict.set(PDFName_default.of("Kids"), Kids);
      }
      return { Kids };
    };
    PDFAcroNonTerminal2.fromDict = function(dict, ref) {
      return new PDFAcroNonTerminal2(dict, ref);
    };
    PDFAcroNonTerminal2.create = function(context) {
      var dict = context.obj({});
      var ref = context.register(dict);
      return new PDFAcroNonTerminal2(dict, ref);
    };
    return PDFAcroNonTerminal2;
  }(PDFAcroField_default)
);
var PDFAcroNonTerminal_default = PDFAcroNonTerminal;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/acroform/PDFAcroSignature.js
var PDFAcroSignature = (
  /** @class */
  function(_super) {
    __extends(PDFAcroSignature2, _super);
    function PDFAcroSignature2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    PDFAcroSignature2.fromDict = function(dict, ref) {
      return new PDFAcroSignature2(dict, ref);
    };
    return PDFAcroSignature2;
  }(PDFAcroTerminal_default)
);
var PDFAcroSignature_default = PDFAcroSignature;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/acroform/PDFAcroText.js
var PDFAcroText = (
  /** @class */
  function(_super) {
    __extends(PDFAcroText2, _super);
    function PDFAcroText2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    PDFAcroText2.prototype.MaxLen = function() {
      var maxLen = this.dict.lookup(PDFName_default.of("MaxLen"));
      if (maxLen instanceof PDFNumber_default)
        return maxLen;
      return void 0;
    };
    PDFAcroText2.prototype.Q = function() {
      var q = this.dict.lookup(PDFName_default.of("Q"));
      if (q instanceof PDFNumber_default)
        return q;
      return void 0;
    };
    PDFAcroText2.prototype.setMaxLength = function(maxLength) {
      this.dict.set(PDFName_default.of("MaxLen"), PDFNumber_default.of(maxLength));
    };
    PDFAcroText2.prototype.removeMaxLength = function() {
      this.dict.delete(PDFName_default.of("MaxLen"));
    };
    PDFAcroText2.prototype.getMaxLength = function() {
      var _a;
      return (_a = this.MaxLen()) === null || _a === void 0 ? void 0 : _a.asNumber();
    };
    PDFAcroText2.prototype.setQuadding = function(quadding) {
      this.dict.set(PDFName_default.of("Q"), PDFNumber_default.of(quadding));
    };
    PDFAcroText2.prototype.getQuadding = function() {
      var _a;
      return (_a = this.Q()) === null || _a === void 0 ? void 0 : _a.asNumber();
    };
    PDFAcroText2.prototype.setValue = function(value) {
      this.dict.set(PDFName_default.of("V"), value);
    };
    PDFAcroText2.prototype.removeValue = function() {
      this.dict.delete(PDFName_default.of("V"));
    };
    PDFAcroText2.prototype.getValue = function() {
      var v = this.V();
      if (v instanceof PDFString_default || v instanceof PDFHexString_default)
        return v;
      return void 0;
    };
    PDFAcroText2.fromDict = function(dict, ref) {
      return new PDFAcroText2(dict, ref);
    };
    PDFAcroText2.create = function(context) {
      var dict = context.obj({
        FT: "Tx",
        Kids: []
      });
      var ref = context.register(dict);
      return new PDFAcroText2(dict, ref);
    };
    return PDFAcroText2;
  }(PDFAcroTerminal_default)
);
var PDFAcroText_default = PDFAcroText;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/acroform/PDFAcroPushButton.js
var PDFAcroPushButton = (
  /** @class */
  function(_super) {
    __extends(PDFAcroPushButton2, _super);
    function PDFAcroPushButton2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    PDFAcroPushButton2.fromDict = function(dict, ref) {
      return new PDFAcroPushButton2(dict, ref);
    };
    PDFAcroPushButton2.create = function(context) {
      var dict = context.obj({
        FT: "Btn",
        Ff: AcroButtonFlags.PushButton,
        Kids: []
      });
      var ref = context.register(dict);
      return new PDFAcroPushButton2(dict, ref);
    };
    return PDFAcroPushButton2;
  }(PDFAcroButton_default)
);
var PDFAcroPushButton_default = PDFAcroPushButton;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/acroform/PDFAcroRadioButton.js
var PDFAcroRadioButton = (
  /** @class */
  function(_super) {
    __extends(PDFAcroRadioButton2, _super);
    function PDFAcroRadioButton2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    PDFAcroRadioButton2.prototype.setValue = function(value) {
      var onValues = this.getOnValues();
      if (!onValues.includes(value) && value !== PDFName_default.of("Off")) {
        throw new InvalidAcroFieldValueError();
      }
      this.dict.set(PDFName_default.of("V"), value);
      var widgets = this.getWidgets();
      for (var idx = 0, len = widgets.length; idx < len; idx++) {
        var widget = widgets[idx];
        var state = widget.getOnValue() === value ? value : PDFName_default.of("Off");
        widget.setAppearanceState(state);
      }
    };
    PDFAcroRadioButton2.prototype.getValue = function() {
      var v = this.V();
      if (v instanceof PDFName_default)
        return v;
      return PDFName_default.of("Off");
    };
    PDFAcroRadioButton2.prototype.getOnValues = function() {
      var widgets = this.getWidgets();
      var onValues = [];
      for (var idx = 0, len = widgets.length; idx < len; idx++) {
        var onValue = widgets[idx].getOnValue();
        if (onValue)
          onValues.push(onValue);
      }
      return onValues;
    };
    PDFAcroRadioButton2.fromDict = function(dict, ref) {
      return new PDFAcroRadioButton2(dict, ref);
    };
    PDFAcroRadioButton2.create = function(context) {
      var dict = context.obj({
        FT: "Btn",
        Ff: AcroButtonFlags.Radio,
        Kids: []
      });
      var ref = context.register(dict);
      return new PDFAcroRadioButton2(dict, ref);
    };
    return PDFAcroRadioButton2;
  }(PDFAcroButton_default)
);
var PDFAcroRadioButton_default = PDFAcroRadioButton;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/acroform/PDFAcroListBox.js
var PDFAcroListBox = (
  /** @class */
  function(_super) {
    __extends(PDFAcroListBox2, _super);
    function PDFAcroListBox2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    PDFAcroListBox2.fromDict = function(dict, ref) {
      return new PDFAcroListBox2(dict, ref);
    };
    PDFAcroListBox2.create = function(context) {
      var dict = context.obj({
        FT: "Ch",
        Kids: []
      });
      var ref = context.register(dict);
      return new PDFAcroListBox2(dict, ref);
    };
    return PDFAcroListBox2;
  }(PDFAcroChoice_default)
);
var PDFAcroListBox_default = PDFAcroListBox;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/acroform/utils.js
var createPDFAcroFields = function(kidDicts) {
  if (!kidDicts)
    return [];
  var kids = [];
  for (var idx = 0, len = kidDicts.size(); idx < len; idx++) {
    var ref = kidDicts.get(idx);
    var dict = kidDicts.lookup(idx);
    if (ref instanceof PDFRef_default && dict instanceof PDFDict_default) {
      kids.push([createPDFAcroField(dict, ref), ref]);
    }
  }
  return kids;
};
var createPDFAcroField = function(dict, ref) {
  var isNonTerminal = isNonTerminalAcroField(dict);
  if (isNonTerminal)
    return PDFAcroNonTerminal_default.fromDict(dict, ref);
  return createPDFAcroTerminal(dict, ref);
};
var isNonTerminalAcroField = function(dict) {
  var kids = dict.lookup(PDFName_default.of("Kids"));
  if (kids instanceof PDFArray_default) {
    for (var idx = 0, len = kids.size(); idx < len; idx++) {
      var kid = kids.lookup(idx);
      var kidIsField = kid instanceof PDFDict_default && kid.has(PDFName_default.of("T"));
      if (kidIsField)
        return true;
    }
  }
  return false;
};
var createPDFAcroTerminal = function(dict, ref) {
  var ftNameOrRef = getInheritableAttribute(dict, PDFName_default.of("FT"));
  var type = dict.context.lookup(ftNameOrRef, PDFName_default);
  if (type === PDFName_default.of("Btn"))
    return createPDFAcroButton(dict, ref);
  if (type === PDFName_default.of("Ch"))
    return createPDFAcroChoice(dict, ref);
  if (type === PDFName_default.of("Tx"))
    return PDFAcroText_default.fromDict(dict, ref);
  if (type === PDFName_default.of("Sig"))
    return PDFAcroSignature_default.fromDict(dict, ref);
  return PDFAcroTerminal_default.fromDict(dict, ref);
};
var createPDFAcroButton = function(dict, ref) {
  var _a;
  var ffNumberOrRef = getInheritableAttribute(dict, PDFName_default.of("Ff"));
  var ffNumber = dict.context.lookupMaybe(ffNumberOrRef, PDFNumber_default);
  var flags = (_a = ffNumber === null || ffNumber === void 0 ? void 0 : ffNumber.asNumber()) !== null && _a !== void 0 ? _a : 0;
  if (flagIsSet(flags, AcroButtonFlags.PushButton)) {
    return PDFAcroPushButton_default.fromDict(dict, ref);
  } else if (flagIsSet(flags, AcroButtonFlags.Radio)) {
    return PDFAcroRadioButton_default.fromDict(dict, ref);
  } else {
    return PDFAcroCheckBox_default.fromDict(dict, ref);
  }
};
var createPDFAcroChoice = function(dict, ref) {
  var _a;
  var ffNumberOrRef = getInheritableAttribute(dict, PDFName_default.of("Ff"));
  var ffNumber = dict.context.lookupMaybe(ffNumberOrRef, PDFNumber_default);
  var flags = (_a = ffNumber === null || ffNumber === void 0 ? void 0 : ffNumber.asNumber()) !== null && _a !== void 0 ? _a : 0;
  if (flagIsSet(flags, AcroChoiceFlags.Combo)) {
    return PDFAcroComboBox_default.fromDict(dict, ref);
  } else {
    return PDFAcroListBox_default.fromDict(dict, ref);
  }
};
var flagIsSet = function(flags, flag3) {
  return (flags & flag3) !== 0;
};
var getInheritableAttribute = function(startNode, name) {
  var attribute;
  ascend(startNode, function(node) {
    if (!attribute)
      attribute = node.get(name);
  });
  return attribute;
};
var ascend = function(startNode, visitor) {
  visitor(startNode);
  var Parent = startNode.lookupMaybe(PDFName_default.of("Parent"), PDFDict_default);
  if (Parent)
    ascend(Parent, visitor);
};

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/acroform/PDFAcroForm.js
var PDFAcroForm = (
  /** @class */
  function() {
    function PDFAcroForm2(dict) {
      this.dict = dict;
    }
    PDFAcroForm2.prototype.Fields = function() {
      var fields = this.dict.lookup(PDFName_default.of("Fields"));
      if (fields instanceof PDFArray_default)
        return fields;
      return void 0;
    };
    PDFAcroForm2.prototype.getFields = function() {
      var Fields = this.normalizedEntries().Fields;
      var fields = new Array(Fields.size());
      for (var idx = 0, len = Fields.size(); idx < len; idx++) {
        var ref = Fields.get(idx);
        var dict = Fields.lookup(idx, PDFDict_default);
        fields[idx] = [createPDFAcroField(dict, ref), ref];
      }
      return fields;
    };
    PDFAcroForm2.prototype.getAllFields = function() {
      var allFields = [];
      var pushFields = function(fields) {
        if (!fields)
          return;
        for (var idx = 0, len = fields.length; idx < len; idx++) {
          var field = fields[idx];
          allFields.push(field);
          var fieldModel = field[0];
          if (fieldModel instanceof PDFAcroNonTerminal_default) {
            pushFields(createPDFAcroFields(fieldModel.Kids()));
          }
        }
      };
      pushFields(this.getFields());
      return allFields;
    };
    PDFAcroForm2.prototype.addField = function(field) {
      var Fields = this.normalizedEntries().Fields;
      Fields === null || Fields === void 0 ? void 0 : Fields.push(field);
    };
    PDFAcroForm2.prototype.removeField = function(field) {
      var parent = field.getParent();
      var fields = parent === void 0 ? this.normalizedEntries().Fields : parent.Kids();
      var index = fields === null || fields === void 0 ? void 0 : fields.indexOf(field.ref);
      if (fields === void 0 || index === void 0) {
        throw new Error("Tried to remove inexistent field " + field.getFullyQualifiedName());
      }
      fields.remove(index);
      if (parent !== void 0 && fields.size() === 0) {
        this.removeField(parent);
      }
    };
    PDFAcroForm2.prototype.normalizedEntries = function() {
      var Fields = this.Fields();
      if (!Fields) {
        Fields = this.dict.context.obj([]);
        this.dict.set(PDFName_default.of("Fields"), Fields);
      }
      return { Fields };
    };
    PDFAcroForm2.fromDict = function(dict) {
      return new PDFAcroForm2(dict);
    };
    PDFAcroForm2.create = function(context) {
      var dict = context.obj({ Fields: [] });
      return new PDFAcroForm2(dict);
    };
    return PDFAcroForm2;
  }()
);
var PDFAcroForm_default = PDFAcroForm;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/structures/PDFCatalog.js
var PDFCatalog = (
  /** @class */
  function(_super) {
    __extends(PDFCatalog2, _super);
    function PDFCatalog2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    PDFCatalog2.prototype.Pages = function() {
      return this.lookup(PDFName_default.of("Pages"), PDFDict_default);
    };
    PDFCatalog2.prototype.AcroForm = function() {
      return this.lookupMaybe(PDFName_default.of("AcroForm"), PDFDict_default);
    };
    PDFCatalog2.prototype.getAcroForm = function() {
      var dict = this.AcroForm();
      if (!dict)
        return void 0;
      return PDFAcroForm_default.fromDict(dict);
    };
    PDFCatalog2.prototype.getOrCreateAcroForm = function() {
      var acroForm = this.getAcroForm();
      if (!acroForm) {
        acroForm = PDFAcroForm_default.create(this.context);
        var acroFormRef = this.context.register(acroForm.dict);
        this.set(PDFName_default.of("AcroForm"), acroFormRef);
      }
      return acroForm;
    };
    PDFCatalog2.prototype.ViewerPreferences = function() {
      return this.lookupMaybe(PDFName_default.of("ViewerPreferences"), PDFDict_default);
    };
    PDFCatalog2.prototype.getViewerPreferences = function() {
      var dict = this.ViewerPreferences();
      if (!dict)
        return void 0;
      return ViewerPreferences_default.fromDict(dict);
    };
    PDFCatalog2.prototype.getOrCreateViewerPreferences = function() {
      var viewerPrefs = this.getViewerPreferences();
      if (!viewerPrefs) {
        viewerPrefs = ViewerPreferences_default.create(this.context);
        var viewerPrefsRef = this.context.register(viewerPrefs.dict);
        this.set(PDFName_default.of("ViewerPreferences"), viewerPrefsRef);
      }
      return viewerPrefs;
    };
    PDFCatalog2.prototype.insertLeafNode = function(leafRef, index) {
      var pagesRef = this.get(PDFName_default.of("Pages"));
      var maybeParentRef = this.Pages().insertLeafNode(leafRef, index);
      return maybeParentRef || pagesRef;
    };
    PDFCatalog2.prototype.removeLeafNode = function(index) {
      this.Pages().removeLeafNode(index);
    };
    PDFCatalog2.withContextAndPages = function(context, pages) {
      var dict = /* @__PURE__ */ new Map();
      dict.set(PDFName_default.of("Type"), PDFName_default.of("Catalog"));
      dict.set(PDFName_default.of("Pages"), pages);
      return new PDFCatalog2(dict, context);
    };
    PDFCatalog2.fromMapWithContext = function(map, context) {
      return new PDFCatalog2(map, context);
    };
    return PDFCatalog2;
  }(PDFDict_default)
);
var PDFCatalog_default = PDFCatalog;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/structures/PDFPageTree.js
var PDFPageTree = (
  /** @class */
  function(_super) {
    __extends(PDFPageTree2, _super);
    function PDFPageTree2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    PDFPageTree2.prototype.Parent = function() {
      return this.lookup(PDFName_default.of("Parent"));
    };
    PDFPageTree2.prototype.Kids = function() {
      return this.lookup(PDFName_default.of("Kids"), PDFArray_default);
    };
    PDFPageTree2.prototype.Count = function() {
      return this.lookup(PDFName_default.of("Count"), PDFNumber_default);
    };
    PDFPageTree2.prototype.pushTreeNode = function(treeRef) {
      var Kids = this.Kids();
      Kids.push(treeRef);
    };
    PDFPageTree2.prototype.pushLeafNode = function(leafRef) {
      var Kids = this.Kids();
      this.insertLeafKid(Kids.size(), leafRef);
    };
    PDFPageTree2.prototype.insertLeafNode = function(leafRef, targetIndex) {
      var Kids = this.Kids();
      var Count = this.Count().asNumber();
      if (targetIndex > Count) {
        throw new InvalidTargetIndexError(targetIndex, Count);
      }
      var leafsRemainingUntilTarget = targetIndex;
      for (var idx = 0, len = Kids.size(); idx < len; idx++) {
        if (leafsRemainingUntilTarget === 0) {
          this.insertLeafKid(idx, leafRef);
          return void 0;
        }
        var kidRef = Kids.get(idx);
        var kid = this.context.lookup(kidRef);
        if (kid instanceof PDFPageTree2) {
          if (kid.Count().asNumber() > leafsRemainingUntilTarget) {
            return kid.insertLeafNode(leafRef, leafsRemainingUntilTarget) || kidRef;
          } else {
            leafsRemainingUntilTarget -= kid.Count().asNumber();
          }
        }
        if (kid instanceof PDFPageLeaf_default) {
          leafsRemainingUntilTarget -= 1;
        }
      }
      if (leafsRemainingUntilTarget === 0) {
        this.insertLeafKid(Kids.size(), leafRef);
        return void 0;
      }
      throw new CorruptPageTreeError(targetIndex, "insertLeafNode");
    };
    PDFPageTree2.prototype.removeLeafNode = function(targetIndex, prune) {
      if (prune === void 0) {
        prune = true;
      }
      var Kids = this.Kids();
      var Count = this.Count().asNumber();
      if (targetIndex >= Count) {
        throw new InvalidTargetIndexError(targetIndex, Count);
      }
      var leafsRemainingUntilTarget = targetIndex;
      for (var idx = 0, len = Kids.size(); idx < len; idx++) {
        var kidRef = Kids.get(idx);
        var kid = this.context.lookup(kidRef);
        if (kid instanceof PDFPageTree2) {
          if (kid.Count().asNumber() > leafsRemainingUntilTarget) {
            kid.removeLeafNode(leafsRemainingUntilTarget, prune);
            if (prune && kid.Kids().size() === 0)
              Kids.remove(idx);
            return;
          } else {
            leafsRemainingUntilTarget -= kid.Count().asNumber();
          }
        }
        if (kid instanceof PDFPageLeaf_default) {
          if (leafsRemainingUntilTarget === 0) {
            this.removeKid(idx);
            return;
          } else {
            leafsRemainingUntilTarget -= 1;
          }
        }
      }
      throw new CorruptPageTreeError(targetIndex, "removeLeafNode");
    };
    PDFPageTree2.prototype.ascend = function(visitor) {
      visitor(this);
      var Parent = this.Parent();
      if (Parent)
        Parent.ascend(visitor);
    };
    PDFPageTree2.prototype.traverse = function(visitor) {
      var Kids = this.Kids();
      for (var idx = 0, len = Kids.size(); idx < len; idx++) {
        var kidRef = Kids.get(idx);
        var kid = this.context.lookup(kidRef);
        if (kid instanceof PDFPageTree2)
          kid.traverse(visitor);
        visitor(kid, kidRef);
      }
    };
    PDFPageTree2.prototype.insertLeafKid = function(kidIdx, leafRef) {
      var Kids = this.Kids();
      this.ascend(function(node) {
        var newCount = node.Count().asNumber() + 1;
        node.set(PDFName_default.of("Count"), PDFNumber_default.of(newCount));
      });
      Kids.insert(kidIdx, leafRef);
    };
    PDFPageTree2.prototype.removeKid = function(kidIdx) {
      var Kids = this.Kids();
      var kid = Kids.lookup(kidIdx);
      if (kid instanceof PDFPageLeaf_default) {
        this.ascend(function(node) {
          var newCount = node.Count().asNumber() - 1;
          node.set(PDFName_default.of("Count"), PDFNumber_default.of(newCount));
        });
      }
      Kids.remove(kidIdx);
    };
    PDFPageTree2.withContext = function(context, parent) {
      var dict = /* @__PURE__ */ new Map();
      dict.set(PDFName_default.of("Type"), PDFName_default.of("Pages"));
      dict.set(PDFName_default.of("Kids"), context.obj([]));
      dict.set(PDFName_default.of("Count"), context.obj(0));
      if (parent)
        dict.set(PDFName_default.of("Parent"), parent);
      return new PDFPageTree2(dict, context);
    };
    PDFPageTree2.fromMapWithContext = function(map, context) {
      return new PDFPageTree2(map, context);
    };
    return PDFPageTree2;
  }(PDFDict_default)
);
var PDFPageTree_default = PDFPageTree;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/syntax/Numeric.js
var IsDigit = new Uint8Array(256);
IsDigit[CharCodes_default.Zero] = 1;
IsDigit[CharCodes_default.One] = 1;
IsDigit[CharCodes_default.Two] = 1;
IsDigit[CharCodes_default.Three] = 1;
IsDigit[CharCodes_default.Four] = 1;
IsDigit[CharCodes_default.Five] = 1;
IsDigit[CharCodes_default.Six] = 1;
IsDigit[CharCodes_default.Seven] = 1;
IsDigit[CharCodes_default.Eight] = 1;
IsDigit[CharCodes_default.Nine] = 1;
var IsNumericPrefix = new Uint8Array(256);
IsNumericPrefix[CharCodes_default.Period] = 1;
IsNumericPrefix[CharCodes_default.Plus] = 1;
IsNumericPrefix[CharCodes_default.Minus] = 1;
var IsNumeric = new Uint8Array(256);
for (idx = 0, len = 256; idx < len; idx++) {
  IsNumeric[idx] = IsDigit[idx] || IsNumericPrefix[idx] ? 1 : 0;
}
var idx;
var len;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/parser/BaseParser.js
var Newline = CharCodes_default.Newline;
var CarriageReturn = CharCodes_default.CarriageReturn;
var BaseParser = (
  /** @class */
  function() {
    function BaseParser2(bytes, capNumbers) {
      if (capNumbers === void 0) {
        capNumbers = false;
      }
      this.bytes = bytes;
      this.capNumbers = capNumbers;
    }
    BaseParser2.prototype.parseRawInt = function() {
      var value = "";
      while (!this.bytes.done()) {
        var byte = this.bytes.peek();
        if (!IsDigit[byte])
          break;
        value += charFromCode(this.bytes.next());
      }
      var numberValue = Number(value);
      if (!value || !isFinite(numberValue)) {
        throw new NumberParsingError(this.bytes.position(), value);
      }
      return numberValue;
    };
    BaseParser2.prototype.parseRawNumber = function() {
      var value = "";
      while (!this.bytes.done()) {
        var byte = this.bytes.peek();
        if (!IsNumeric[byte])
          break;
        value += charFromCode(this.bytes.next());
        if (byte === CharCodes_default.Period)
          break;
      }
      while (!this.bytes.done()) {
        var byte = this.bytes.peek();
        if (!IsDigit[byte])
          break;
        value += charFromCode(this.bytes.next());
      }
      var numberValue = Number(value);
      if (!value || !isFinite(numberValue)) {
        throw new NumberParsingError(this.bytes.position(), value);
      }
      if (numberValue > Number.MAX_SAFE_INTEGER) {
        if (this.capNumbers) {
          var msg = "Parsed number that is too large for some PDF readers: " + value + ", using Number.MAX_SAFE_INTEGER instead.";
          console.warn(msg);
          return Number.MAX_SAFE_INTEGER;
        } else {
          var msg = "Parsed number that is too large for some PDF readers: " + value + ", not capping.";
          console.warn(msg);
        }
      }
      return numberValue;
    };
    BaseParser2.prototype.skipWhitespace = function() {
      while (!this.bytes.done() && IsWhitespace[this.bytes.peek()]) {
        this.bytes.next();
      }
    };
    BaseParser2.prototype.skipLine = function() {
      while (!this.bytes.done()) {
        var byte = this.bytes.peek();
        if (byte === Newline || byte === CarriageReturn)
          return;
        this.bytes.next();
      }
    };
    BaseParser2.prototype.skipComment = function() {
      if (this.bytes.peek() !== CharCodes_default.Percent)
        return false;
      while (!this.bytes.done()) {
        var byte = this.bytes.peek();
        if (byte === Newline || byte === CarriageReturn)
          return true;
        this.bytes.next();
      }
      return true;
    };
    BaseParser2.prototype.skipWhitespaceAndComments = function() {
      this.skipWhitespace();
      while (this.skipComment())
        this.skipWhitespace();
    };
    BaseParser2.prototype.matchKeyword = function(keyword) {
      var initialOffset = this.bytes.offset();
      for (var idx = 0, len = keyword.length; idx < len; idx++) {
        if (this.bytes.done() || this.bytes.next() !== keyword[idx]) {
          this.bytes.moveTo(initialOffset);
          return false;
        }
      }
      return true;
    };
    return BaseParser2;
  }()
);
var BaseParser_default = BaseParser;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/parser/ByteStream.js
var ByteStream = (
  /** @class */
  function() {
    function ByteStream2(bytes) {
      this.idx = 0;
      this.line = 0;
      this.column = 0;
      this.bytes = bytes;
      this.length = this.bytes.length;
    }
    ByteStream2.prototype.moveTo = function(offset) {
      this.idx = offset;
    };
    ByteStream2.prototype.next = function() {
      var byte = this.bytes[this.idx++];
      if (byte === CharCodes_default.Newline) {
        this.line += 1;
        this.column = 0;
      } else {
        this.column += 1;
      }
      return byte;
    };
    ByteStream2.prototype.assertNext = function(expected) {
      if (this.peek() !== expected) {
        throw new NextByteAssertionError(this.position(), expected, this.peek());
      }
      return this.next();
    };
    ByteStream2.prototype.peek = function() {
      return this.bytes[this.idx];
    };
    ByteStream2.prototype.peekAhead = function(steps) {
      return this.bytes[this.idx + steps];
    };
    ByteStream2.prototype.peekAt = function(offset) {
      return this.bytes[offset];
    };
    ByteStream2.prototype.done = function() {
      return this.idx >= this.length;
    };
    ByteStream2.prototype.offset = function() {
      return this.idx;
    };
    ByteStream2.prototype.slice = function(start, end) {
      return this.bytes.slice(start, end);
    };
    ByteStream2.prototype.position = function() {
      return { line: this.line, column: this.column, offset: this.idx };
    };
    ByteStream2.of = function(bytes) {
      return new ByteStream2(bytes);
    };
    ByteStream2.fromPDFRawStream = function(rawStream) {
      return ByteStream2.of(decodePDFRawStream(rawStream).decode());
    };
    return ByteStream2;
  }()
);
var ByteStream_default = ByteStream;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/syntax/Keywords.js
var Space = CharCodes_default.Space;
var CarriageReturn2 = CharCodes_default.CarriageReturn;
var Newline2 = CharCodes_default.Newline;
var stream = [
  CharCodes_default.s,
  CharCodes_default.t,
  CharCodes_default.r,
  CharCodes_default.e,
  CharCodes_default.a,
  CharCodes_default.m
];
var endstream = [
  CharCodes_default.e,
  CharCodes_default.n,
  CharCodes_default.d,
  CharCodes_default.s,
  CharCodes_default.t,
  CharCodes_default.r,
  CharCodes_default.e,
  CharCodes_default.a,
  CharCodes_default.m
];
var Keywords = {
  header: [
    CharCodes_default.Percent,
    CharCodes_default.P,
    CharCodes_default.D,
    CharCodes_default.F,
    CharCodes_default.Dash
  ],
  eof: [
    CharCodes_default.Percent,
    CharCodes_default.Percent,
    CharCodes_default.E,
    CharCodes_default.O,
    CharCodes_default.F
  ],
  obj: [CharCodes_default.o, CharCodes_default.b, CharCodes_default.j],
  endobj: [
    CharCodes_default.e,
    CharCodes_default.n,
    CharCodes_default.d,
    CharCodes_default.o,
    CharCodes_default.b,
    CharCodes_default.j
  ],
  xref: [CharCodes_default.x, CharCodes_default.r, CharCodes_default.e, CharCodes_default.f],
  trailer: [
    CharCodes_default.t,
    CharCodes_default.r,
    CharCodes_default.a,
    CharCodes_default.i,
    CharCodes_default.l,
    CharCodes_default.e,
    CharCodes_default.r
  ],
  startxref: [
    CharCodes_default.s,
    CharCodes_default.t,
    CharCodes_default.a,
    CharCodes_default.r,
    CharCodes_default.t,
    CharCodes_default.x,
    CharCodes_default.r,
    CharCodes_default.e,
    CharCodes_default.f
  ],
  true: [CharCodes_default.t, CharCodes_default.r, CharCodes_default.u, CharCodes_default.e],
  false: [CharCodes_default.f, CharCodes_default.a, CharCodes_default.l, CharCodes_default.s, CharCodes_default.e],
  null: [CharCodes_default.n, CharCodes_default.u, CharCodes_default.l, CharCodes_default.l],
  stream,
  streamEOF1: __spreadArrays(stream, [Space, CarriageReturn2, Newline2]),
  streamEOF2: __spreadArrays(stream, [CarriageReturn2, Newline2]),
  streamEOF3: __spreadArrays(stream, [CarriageReturn2]),
  streamEOF4: __spreadArrays(stream, [Newline2]),
  endstream,
  EOF1endstream: __spreadArrays([CarriageReturn2, Newline2], endstream),
  EOF2endstream: __spreadArrays([CarriageReturn2], endstream),
  EOF3endstream: __spreadArrays([Newline2], endstream)
};

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/parser/PDFObjectParser.js
var PDFObjectParser = (
  /** @class */
  function(_super) {
    __extends(PDFObjectParser2, _super);
    function PDFObjectParser2(byteStream, context, capNumbers) {
      if (capNumbers === void 0) {
        capNumbers = false;
      }
      var _this = _super.call(this, byteStream, capNumbers) || this;
      _this.context = context;
      return _this;
    }
    PDFObjectParser2.prototype.parseObject = function() {
      this.skipWhitespaceAndComments();
      if (this.matchKeyword(Keywords.true))
        return PDFBool_default.True;
      if (this.matchKeyword(Keywords.false))
        return PDFBool_default.False;
      if (this.matchKeyword(Keywords.null))
        return PDFNull_default;
      var byte = this.bytes.peek();
      if (byte === CharCodes_default.LessThan && this.bytes.peekAhead(1) === CharCodes_default.LessThan) {
        return this.parseDictOrStream();
      }
      if (byte === CharCodes_default.LessThan)
        return this.parseHexString();
      if (byte === CharCodes_default.LeftParen)
        return this.parseString();
      if (byte === CharCodes_default.ForwardSlash)
        return this.parseName();
      if (byte === CharCodes_default.LeftSquareBracket)
        return this.parseArray();
      if (IsNumeric[byte])
        return this.parseNumberOrRef();
      throw new PDFObjectParsingError(this.bytes.position(), byte);
    };
    PDFObjectParser2.prototype.parseNumberOrRef = function() {
      var firstNum = this.parseRawNumber();
      this.skipWhitespaceAndComments();
      var lookaheadStart = this.bytes.offset();
      if (IsDigit[this.bytes.peek()]) {
        var secondNum = this.parseRawNumber();
        this.skipWhitespaceAndComments();
        if (this.bytes.peek() === CharCodes_default.R) {
          this.bytes.assertNext(CharCodes_default.R);
          return PDFRef_default.of(firstNum, secondNum);
        }
      }
      this.bytes.moveTo(lookaheadStart);
      return PDFNumber_default.of(firstNum);
    };
    PDFObjectParser2.prototype.parseHexString = function() {
      var value = "";
      this.bytes.assertNext(CharCodes_default.LessThan);
      while (!this.bytes.done() && this.bytes.peek() !== CharCodes_default.GreaterThan) {
        value += charFromCode(this.bytes.next());
      }
      this.bytes.assertNext(CharCodes_default.GreaterThan);
      return PDFHexString_default.of(value);
    };
    PDFObjectParser2.prototype.parseString = function() {
      var nestingLvl = 0;
      var isEscaped = false;
      var value = "";
      while (!this.bytes.done()) {
        var byte = this.bytes.next();
        value += charFromCode(byte);
        if (!isEscaped) {
          if (byte === CharCodes_default.LeftParen)
            nestingLvl += 1;
          if (byte === CharCodes_default.RightParen)
            nestingLvl -= 1;
        }
        if (byte === CharCodes_default.BackSlash) {
          isEscaped = !isEscaped;
        } else if (isEscaped) {
          isEscaped = false;
        }
        if (nestingLvl === 0) {
          return PDFString_default.of(value.substring(1, value.length - 1));
        }
      }
      throw new UnbalancedParenthesisError(this.bytes.position());
    };
    PDFObjectParser2.prototype.parseName = function() {
      this.bytes.assertNext(CharCodes_default.ForwardSlash);
      var name = "";
      while (!this.bytes.done()) {
        var byte = this.bytes.peek();
        if (IsWhitespace[byte] || IsDelimiter[byte])
          break;
        name += charFromCode(byte);
        this.bytes.next();
      }
      return PDFName_default.of(name);
    };
    PDFObjectParser2.prototype.parseArray = function() {
      this.bytes.assertNext(CharCodes_default.LeftSquareBracket);
      this.skipWhitespaceAndComments();
      var pdfArray = PDFArray_default.withContext(this.context);
      while (this.bytes.peek() !== CharCodes_default.RightSquareBracket) {
        var element = this.parseObject();
        pdfArray.push(element);
        this.skipWhitespaceAndComments();
      }
      this.bytes.assertNext(CharCodes_default.RightSquareBracket);
      return pdfArray;
    };
    PDFObjectParser2.prototype.parseDict = function() {
      this.bytes.assertNext(CharCodes_default.LessThan);
      this.bytes.assertNext(CharCodes_default.LessThan);
      this.skipWhitespaceAndComments();
      var dict = /* @__PURE__ */ new Map();
      while (!this.bytes.done() && this.bytes.peek() !== CharCodes_default.GreaterThan && this.bytes.peekAhead(1) !== CharCodes_default.GreaterThan) {
        var key = this.parseName();
        var value = this.parseObject();
        dict.set(key, value);
        this.skipWhitespaceAndComments();
      }
      this.skipWhitespaceAndComments();
      this.bytes.assertNext(CharCodes_default.GreaterThan);
      this.bytes.assertNext(CharCodes_default.GreaterThan);
      var Type = dict.get(PDFName_default.of("Type"));
      if (Type === PDFName_default.of("Catalog")) {
        return PDFCatalog_default.fromMapWithContext(dict, this.context);
      } else if (Type === PDFName_default.of("Pages")) {
        return PDFPageTree_default.fromMapWithContext(dict, this.context);
      } else if (Type === PDFName_default.of("Page")) {
        return PDFPageLeaf_default.fromMapWithContext(dict, this.context);
      } else {
        return PDFDict_default.fromMapWithContext(dict, this.context);
      }
    };
    PDFObjectParser2.prototype.parseDictOrStream = function() {
      var startPos = this.bytes.position();
      var dict = this.parseDict();
      this.skipWhitespaceAndComments();
      if (!this.matchKeyword(Keywords.streamEOF1) && !this.matchKeyword(Keywords.streamEOF2) && !this.matchKeyword(Keywords.streamEOF3) && !this.matchKeyword(Keywords.streamEOF4) && !this.matchKeyword(Keywords.stream)) {
        return dict;
      }
      var start = this.bytes.offset();
      var end;
      var Length = dict.get(PDFName_default.of("Length"));
      if (Length instanceof PDFNumber_default) {
        end = start + Length.asNumber();
        this.bytes.moveTo(end);
        this.skipWhitespaceAndComments();
        if (!this.matchKeyword(Keywords.endstream)) {
          this.bytes.moveTo(start);
          end = this.findEndOfStreamFallback(startPos);
        }
      } else {
        end = this.findEndOfStreamFallback(startPos);
      }
      var contents = this.bytes.slice(start, end);
      return PDFRawStream_default.of(dict, contents);
    };
    PDFObjectParser2.prototype.findEndOfStreamFallback = function(startPos) {
      var nestingLvl = 1;
      var end = this.bytes.offset();
      while (!this.bytes.done()) {
        end = this.bytes.offset();
        if (this.matchKeyword(Keywords.stream)) {
          nestingLvl += 1;
        } else if (this.matchKeyword(Keywords.EOF1endstream) || this.matchKeyword(Keywords.EOF2endstream) || this.matchKeyword(Keywords.EOF3endstream) || this.matchKeyword(Keywords.endstream)) {
          nestingLvl -= 1;
        } else {
          this.bytes.next();
        }
        if (nestingLvl === 0)
          break;
      }
      if (nestingLvl !== 0)
        throw new PDFStreamParsingError(startPos);
      return end;
    };
    PDFObjectParser2.forBytes = function(bytes, context, capNumbers) {
      return new PDFObjectParser2(ByteStream_default.of(bytes), context, capNumbers);
    };
    PDFObjectParser2.forByteStream = function(byteStream, context, capNumbers) {
      if (capNumbers === void 0) {
        capNumbers = false;
      }
      return new PDFObjectParser2(byteStream, context, capNumbers);
    };
    return PDFObjectParser2;
  }(BaseParser_default)
);
var PDFObjectParser_default = PDFObjectParser;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/parser/PDFObjectStreamParser.js
var PDFObjectStreamParser = (
  /** @class */
  function(_super) {
    __extends(PDFObjectStreamParser2, _super);
    function PDFObjectStreamParser2(rawStream, shouldWaitForTick) {
      var _this = _super.call(this, ByteStream_default.fromPDFRawStream(rawStream), rawStream.dict.context) || this;
      var dict = rawStream.dict;
      _this.alreadyParsed = false;
      _this.shouldWaitForTick = shouldWaitForTick || function() {
        return false;
      };
      _this.firstOffset = dict.lookup(PDFName_default.of("First"), PDFNumber_default).asNumber();
      _this.objectCount = dict.lookup(PDFName_default.of("N"), PDFNumber_default).asNumber();
      return _this;
    }
    PDFObjectStreamParser2.prototype.parseIntoContext = function() {
      return __awaiter(this, void 0, void 0, function() {
        var offsetsAndObjectNumbers, idx, len, _a, objectNumber, offset, object, ref;
        return __generator(this, function(_b) {
          switch (_b.label) {
            case 0:
              if (this.alreadyParsed) {
                throw new ReparseError("PDFObjectStreamParser", "parseIntoContext");
              }
              this.alreadyParsed = true;
              offsetsAndObjectNumbers = this.parseOffsetsAndObjectNumbers();
              idx = 0, len = offsetsAndObjectNumbers.length;
              _b.label = 1;
            case 1:
              if (!(idx < len)) return [3, 4];
              _a = offsetsAndObjectNumbers[idx], objectNumber = _a.objectNumber, offset = _a.offset;
              this.bytes.moveTo(this.firstOffset + offset);
              object = this.parseObject();
              ref = PDFRef_default.of(objectNumber, 0);
              this.context.assign(ref, object);
              if (!this.shouldWaitForTick()) return [3, 3];
              return [4, waitForTick()];
            case 2:
              _b.sent();
              _b.label = 3;
            case 3:
              idx++;
              return [3, 1];
            case 4:
              return [
                2
                /*return*/
              ];
          }
        });
      });
    };
    PDFObjectStreamParser2.prototype.parseOffsetsAndObjectNumbers = function() {
      var offsetsAndObjectNumbers = [];
      for (var idx = 0, len = this.objectCount; idx < len; idx++) {
        this.skipWhitespaceAndComments();
        var objectNumber = this.parseRawInt();
        this.skipWhitespaceAndComments();
        var offset = this.parseRawInt();
        offsetsAndObjectNumbers.push({ objectNumber, offset });
      }
      return offsetsAndObjectNumbers;
    };
    PDFObjectStreamParser2.forStream = function(rawStream, shouldWaitForTick) {
      return new PDFObjectStreamParser2(rawStream, shouldWaitForTick);
    };
    return PDFObjectStreamParser2;
  }(PDFObjectParser_default)
);
var PDFObjectStreamParser_default = PDFObjectStreamParser;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/parser/PDFXRefStreamParser.js
var PDFXRefStreamParser = (
  /** @class */
  function() {
    function PDFXRefStreamParser2(rawStream) {
      this.alreadyParsed = false;
      this.dict = rawStream.dict;
      this.bytes = ByteStream_default.fromPDFRawStream(rawStream);
      this.context = this.dict.context;
      var Size = this.dict.lookup(PDFName_default.of("Size"), PDFNumber_default);
      var Index = this.dict.lookup(PDFName_default.of("Index"));
      if (Index instanceof PDFArray_default) {
        this.subsections = [];
        for (var idx = 0, len = Index.size(); idx < len; idx += 2) {
          var firstObjectNumber = Index.lookup(idx + 0, PDFNumber_default).asNumber();
          var length_1 = Index.lookup(idx + 1, PDFNumber_default).asNumber();
          this.subsections.push({ firstObjectNumber, length: length_1 });
        }
      } else {
        this.subsections = [{ firstObjectNumber: 0, length: Size.asNumber() }];
      }
      var W = this.dict.lookup(PDFName_default.of("W"), PDFArray_default);
      this.byteWidths = [-1, -1, -1];
      for (var idx = 0, len = W.size(); idx < len; idx++) {
        this.byteWidths[idx] = W.lookup(idx, PDFNumber_default).asNumber();
      }
    }
    PDFXRefStreamParser2.prototype.parseIntoContext = function() {
      if (this.alreadyParsed) {
        throw new ReparseError("PDFXRefStreamParser", "parseIntoContext");
      }
      this.alreadyParsed = true;
      this.context.trailerInfo = {
        Root: this.dict.get(PDFName_default.of("Root")),
        Encrypt: this.dict.get(PDFName_default.of("Encrypt")),
        Info: this.dict.get(PDFName_default.of("Info")),
        ID: this.dict.get(PDFName_default.of("ID"))
      };
      var entries = this.parseEntries();
      return entries;
    };
    PDFXRefStreamParser2.prototype.parseEntries = function() {
      var entries = [];
      var _a = this.byteWidths, typeFieldWidth = _a[0], offsetFieldWidth = _a[1], genFieldWidth = _a[2];
      for (var subsectionIdx = 0, subsectionLen = this.subsections.length; subsectionIdx < subsectionLen; subsectionIdx++) {
        var _b = this.subsections[subsectionIdx], firstObjectNumber = _b.firstObjectNumber, length_2 = _b.length;
        for (var objIdx = 0; objIdx < length_2; objIdx++) {
          var type = 0;
          for (var idx = 0, len = typeFieldWidth; idx < len; idx++) {
            type = type << 8 | this.bytes.next();
          }
          var offset = 0;
          for (var idx = 0, len = offsetFieldWidth; idx < len; idx++) {
            offset = offset << 8 | this.bytes.next();
          }
          var generationNumber = 0;
          for (var idx = 0, len = genFieldWidth; idx < len; idx++) {
            generationNumber = generationNumber << 8 | this.bytes.next();
          }
          if (typeFieldWidth === 0)
            type = 1;
          var objectNumber = firstObjectNumber + objIdx;
          var entry = {
            ref: PDFRef_default.of(objectNumber, generationNumber),
            offset,
            deleted: type === 0,
            inObjectStream: type === 2
          };
          entries.push(entry);
        }
      }
      return entries;
    };
    PDFXRefStreamParser2.forStream = function(rawStream) {
      return new PDFXRefStreamParser2(rawStream);
    };
    return PDFXRefStreamParser2;
  }()
);
var PDFXRefStreamParser_default = PDFXRefStreamParser;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/parser/PDFParser.js
var PDFParser = (
  /** @class */
  function(_super) {
    __extends(PDFParser2, _super);
    function PDFParser2(pdfBytes, objectsPerTick, throwOnInvalidObject, capNumbers) {
      if (objectsPerTick === void 0) {
        objectsPerTick = Infinity;
      }
      if (throwOnInvalidObject === void 0) {
        throwOnInvalidObject = false;
      }
      if (capNumbers === void 0) {
        capNumbers = false;
      }
      var _this = _super.call(this, ByteStream_default.of(pdfBytes), PDFContext_default.create(), capNumbers) || this;
      _this.alreadyParsed = false;
      _this.parsedObjects = 0;
      _this.shouldWaitForTick = function() {
        _this.parsedObjects += 1;
        return _this.parsedObjects % _this.objectsPerTick === 0;
      };
      _this.objectsPerTick = objectsPerTick;
      _this.throwOnInvalidObject = throwOnInvalidObject;
      return _this;
    }
    PDFParser2.prototype.parseDocument = function() {
      return __awaiter(this, void 0, void 0, function() {
        var prevOffset, offset;
        return __generator(this, function(_a) {
          switch (_a.label) {
            case 0:
              if (this.alreadyParsed) {
                throw new ReparseError("PDFParser", "parseDocument");
              }
              this.alreadyParsed = true;
              this.context.header = this.parseHeader();
              _a.label = 1;
            case 1:
              if (!!this.bytes.done()) return [3, 3];
              return [4, this.parseDocumentSection()];
            case 2:
              _a.sent();
              offset = this.bytes.offset();
              if (offset === prevOffset) {
                throw new StalledParserError(this.bytes.position());
              }
              prevOffset = offset;
              return [3, 1];
            case 3:
              this.maybeRecoverRoot();
              if (this.context.lookup(PDFRef_default.of(0))) {
                console.warn("Removing parsed object: 0 0 R");
                this.context.delete(PDFRef_default.of(0));
              }
              return [2, this.context];
          }
        });
      });
    };
    PDFParser2.prototype.maybeRecoverRoot = function() {
      var isValidCatalog = function(obj) {
        return obj instanceof PDFDict_default && obj.lookup(PDFName_default.of("Type")) === PDFName_default.of("Catalog");
      };
      var catalog = this.context.lookup(this.context.trailerInfo.Root);
      if (!isValidCatalog(catalog)) {
        var indirectObjects = this.context.enumerateIndirectObjects();
        for (var idx = 0, len = indirectObjects.length; idx < len; idx++) {
          var _a = indirectObjects[idx], ref = _a[0], object = _a[1];
          if (isValidCatalog(object)) {
            this.context.trailerInfo.Root = ref;
          }
        }
      }
    };
    PDFParser2.prototype.parseHeader = function() {
      while (!this.bytes.done()) {
        if (this.matchKeyword(Keywords.header)) {
          var major = this.parseRawInt();
          this.bytes.assertNext(CharCodes_default.Period);
          var minor = this.parseRawInt();
          var header = PDFHeader_default.forVersion(major, minor);
          this.skipBinaryHeaderComment();
          return header;
        }
        this.bytes.next();
      }
      throw new MissingPDFHeaderError(this.bytes.position());
    };
    PDFParser2.prototype.parseIndirectObjectHeader = function() {
      this.skipWhitespaceAndComments();
      var objectNumber = this.parseRawInt();
      this.skipWhitespaceAndComments();
      var generationNumber = this.parseRawInt();
      this.skipWhitespaceAndComments();
      if (!this.matchKeyword(Keywords.obj)) {
        throw new MissingKeywordError(this.bytes.position(), Keywords.obj);
      }
      return PDFRef_default.of(objectNumber, generationNumber);
    };
    PDFParser2.prototype.matchIndirectObjectHeader = function() {
      var initialOffset = this.bytes.offset();
      try {
        this.parseIndirectObjectHeader();
        return true;
      } catch (e) {
        this.bytes.moveTo(initialOffset);
        return false;
      }
    };
    PDFParser2.prototype.parseIndirectObject = function() {
      return __awaiter(this, void 0, void 0, function() {
        var ref, object;
        return __generator(this, function(_a) {
          switch (_a.label) {
            case 0:
              ref = this.parseIndirectObjectHeader();
              this.skipWhitespaceAndComments();
              object = this.parseObject();
              this.skipWhitespaceAndComments();
              this.matchKeyword(Keywords.endobj);
              if (!(object instanceof PDFRawStream_default && object.dict.lookup(PDFName_default.of("Type")) === PDFName_default.of("ObjStm"))) return [3, 2];
              return [4, PDFObjectStreamParser_default.forStream(object, this.shouldWaitForTick).parseIntoContext()];
            case 1:
              _a.sent();
              return [3, 3];
            case 2:
              if (object instanceof PDFRawStream_default && object.dict.lookup(PDFName_default.of("Type")) === PDFName_default.of("XRef")) {
                PDFXRefStreamParser_default.forStream(object).parseIntoContext();
              } else {
                this.context.assign(ref, object);
              }
              _a.label = 3;
            case 3:
              return [2, ref];
          }
        });
      });
    };
    PDFParser2.prototype.tryToParseInvalidIndirectObject = function() {
      var startPos = this.bytes.position();
      var msg = "Trying to parse invalid object: " + JSON.stringify(startPos) + ")";
      if (this.throwOnInvalidObject)
        throw new Error(msg);
      console.warn(msg);
      var ref = this.parseIndirectObjectHeader();
      console.warn("Invalid object ref: " + ref);
      this.skipWhitespaceAndComments();
      var start = this.bytes.offset();
      var failed = true;
      while (!this.bytes.done()) {
        if (this.matchKeyword(Keywords.endobj)) {
          failed = false;
        }
        if (!failed)
          break;
        this.bytes.next();
      }
      if (failed)
        throw new PDFInvalidObjectParsingError(startPos);
      var end = this.bytes.offset() - Keywords.endobj.length;
      var object = PDFInvalidObject_default.of(this.bytes.slice(start, end));
      this.context.assign(ref, object);
      return ref;
    };
    PDFParser2.prototype.parseIndirectObjects = function() {
      return __awaiter(this, void 0, void 0, function() {
        var initialOffset, e_1;
        return __generator(this, function(_a) {
          switch (_a.label) {
            case 0:
              this.skipWhitespaceAndComments();
              _a.label = 1;
            case 1:
              if (!(!this.bytes.done() && IsDigit[this.bytes.peek()])) return [3, 8];
              initialOffset = this.bytes.offset();
              _a.label = 2;
            case 2:
              _a.trys.push([2, 4, , 5]);
              return [4, this.parseIndirectObject()];
            case 3:
              _a.sent();
              return [3, 5];
            case 4:
              e_1 = _a.sent();
              this.bytes.moveTo(initialOffset);
              this.tryToParseInvalidIndirectObject();
              return [3, 5];
            case 5:
              this.skipWhitespaceAndComments();
              this.skipJibberish();
              if (!this.shouldWaitForTick()) return [3, 7];
              return [4, waitForTick()];
            case 6:
              _a.sent();
              _a.label = 7;
            case 7:
              return [3, 1];
            case 8:
              return [
                2
                /*return*/
              ];
          }
        });
      });
    };
    PDFParser2.prototype.maybeParseCrossRefSection = function() {
      this.skipWhitespaceAndComments();
      if (!this.matchKeyword(Keywords.xref))
        return;
      this.skipWhitespaceAndComments();
      var objectNumber = -1;
      var xref = PDFCrossRefSection_default.createEmpty();
      while (!this.bytes.done() && IsDigit[this.bytes.peek()]) {
        var firstInt = this.parseRawInt();
        this.skipWhitespaceAndComments();
        var secondInt = this.parseRawInt();
        this.skipWhitespaceAndComments();
        var byte = this.bytes.peek();
        if (byte === CharCodes_default.n || byte === CharCodes_default.f) {
          var ref = PDFRef_default.of(objectNumber, secondInt);
          if (this.bytes.next() === CharCodes_default.n) {
            xref.addEntry(ref, firstInt);
          } else {
            xref.addDeletedEntry(ref, firstInt);
          }
          objectNumber += 1;
        } else {
          objectNumber = firstInt;
        }
        this.skipWhitespaceAndComments();
      }
      return xref;
    };
    PDFParser2.prototype.maybeParseTrailerDict = function() {
      this.skipWhitespaceAndComments();
      if (!this.matchKeyword(Keywords.trailer))
        return;
      this.skipWhitespaceAndComments();
      var dict = this.parseDict();
      var context = this.context;
      context.trailerInfo = {
        Root: dict.get(PDFName_default.of("Root")) || context.trailerInfo.Root,
        Encrypt: dict.get(PDFName_default.of("Encrypt")) || context.trailerInfo.Encrypt,
        Info: dict.get(PDFName_default.of("Info")) || context.trailerInfo.Info,
        ID: dict.get(PDFName_default.of("ID")) || context.trailerInfo.ID
      };
    };
    PDFParser2.prototype.maybeParseTrailer = function() {
      this.skipWhitespaceAndComments();
      if (!this.matchKeyword(Keywords.startxref))
        return;
      this.skipWhitespaceAndComments();
      var offset = this.parseRawInt();
      this.skipWhitespace();
      this.matchKeyword(Keywords.eof);
      this.skipWhitespaceAndComments();
      this.matchKeyword(Keywords.eof);
      this.skipWhitespaceAndComments();
      return PDFTrailer_default.forLastCrossRefSectionOffset(offset);
    };
    PDFParser2.prototype.parseDocumentSection = function() {
      return __awaiter(this, void 0, void 0, function() {
        return __generator(this, function(_a) {
          switch (_a.label) {
            case 0:
              return [4, this.parseIndirectObjects()];
            case 1:
              _a.sent();
              this.maybeParseCrossRefSection();
              this.maybeParseTrailerDict();
              this.maybeParseTrailer();
              this.skipJibberish();
              return [
                2
                /*return*/
              ];
          }
        });
      });
    };
    PDFParser2.prototype.skipJibberish = function() {
      this.skipWhitespaceAndComments();
      while (!this.bytes.done()) {
        var initialOffset = this.bytes.offset();
        var byte = this.bytes.peek();
        var isAlphaNumeric = byte >= CharCodes_default.Space && byte <= CharCodes_default.Tilde;
        if (isAlphaNumeric) {
          if (this.matchKeyword(Keywords.xref) || this.matchKeyword(Keywords.trailer) || this.matchKeyword(Keywords.startxref) || this.matchIndirectObjectHeader()) {
            this.bytes.moveTo(initialOffset);
            break;
          }
        }
        this.bytes.next();
      }
    };
    PDFParser2.prototype.skipBinaryHeaderComment = function() {
      this.skipWhitespaceAndComments();
      try {
        var initialOffset = this.bytes.offset();
        this.parseIndirectObjectHeader();
        this.bytes.moveTo(initialOffset);
      } catch (e) {
        this.bytes.next();
        this.skipWhitespaceAndComments();
      }
    };
    PDFParser2.forBytesWithOptions = function(pdfBytes, objectsPerTick, throwOnInvalidObject, capNumbers) {
      return new PDFParser2(pdfBytes, objectsPerTick, throwOnInvalidObject, capNumbers);
    };
    return PDFParser2;
  }(PDFObjectParser_default)
);
var PDFParser_default = PDFParser;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/annotation/flags.js
var flag2 = function(bitIndex) {
  return 1 << bitIndex;
};
var AnnotationFlags;
(function(AnnotationFlags2) {
  AnnotationFlags2[AnnotationFlags2["Invisible"] = flag2(1 - 1)] = "Invisible";
  AnnotationFlags2[AnnotationFlags2["Hidden"] = flag2(2 - 1)] = "Hidden";
  AnnotationFlags2[AnnotationFlags2["Print"] = flag2(3 - 1)] = "Print";
  AnnotationFlags2[AnnotationFlags2["NoZoom"] = flag2(4 - 1)] = "NoZoom";
  AnnotationFlags2[AnnotationFlags2["NoRotate"] = flag2(5 - 1)] = "NoRotate";
  AnnotationFlags2[AnnotationFlags2["NoView"] = flag2(6 - 1)] = "NoView";
  AnnotationFlags2[AnnotationFlags2["ReadOnly"] = flag2(7 - 1)] = "ReadOnly";
  AnnotationFlags2[AnnotationFlags2["Locked"] = flag2(8 - 1)] = "Locked";
  AnnotationFlags2[AnnotationFlags2["ToggleNoView"] = flag2(9 - 1)] = "ToggleNoView";
  AnnotationFlags2[AnnotationFlags2["LockedContents"] = flag2(10 - 1)] = "LockedContents";
})(AnnotationFlags || (AnnotationFlags = {}));

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/api/objects.js
var asPDFName = function(name) {
  return name instanceof PDFName_default ? name : PDFName_default.of(name);
};
var asPDFNumber = function(num) {
  return num instanceof PDFNumber_default ? num : PDFNumber_default.of(num);
};
var asNumber = function(num) {
  return num instanceof PDFNumber_default ? num.asNumber() : num;
};

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/api/rotations.js
var RotationTypes;
(function(RotationTypes2) {
  RotationTypes2["Degrees"] = "degrees";
  RotationTypes2["Radians"] = "radians";
})(RotationTypes || (RotationTypes = {}));
var degrees = function(degreeAngle) {
  assertIs(degreeAngle, "degreeAngle", ["number"]);
  return { type: RotationTypes.Degrees, angle: degreeAngle };
};
var Radians = RotationTypes.Radians;
var Degrees = RotationTypes.Degrees;
var degreesToRadians = function(degree) {
  return degree * Math.PI / 180;
};
var radiansToDegrees = function(radian) {
  return radian * 180 / Math.PI;
};
var toRadians = function(rotation) {
  return rotation.type === Radians ? rotation.angle : rotation.type === Degrees ? degreesToRadians(rotation.angle) : error("Invalid rotation: " + JSON.stringify(rotation));
};
var toDegrees = function(rotation) {
  return rotation.type === Radians ? radiansToDegrees(rotation.angle) : rotation.type === Degrees ? rotation.angle : error("Invalid rotation: " + JSON.stringify(rotation));
};
var reduceRotation = function(degreeAngle) {
  if (degreeAngle === void 0) {
    degreeAngle = 0;
  }
  var quadrants = degreeAngle / 90 % 4;
  if (quadrants === 0)
    return 0;
  if (quadrants === 1)
    return 90;
  if (quadrants === 2)
    return 180;
  if (quadrants === 3)
    return 270;
  return 0;
};
var adjustDimsForRotation = function(dims, degreeAngle) {
  if (degreeAngle === void 0) {
    degreeAngle = 0;
  }
  var rotation = reduceRotation(degreeAngle);
  return rotation === 90 || rotation === 270 ? { width: dims.height, height: dims.width } : { width: dims.width, height: dims.height };
};
var rotateRectangle = function(rectangle, borderWidth, degreeAngle) {
  if (borderWidth === void 0) {
    borderWidth = 0;
  }
  if (degreeAngle === void 0) {
    degreeAngle = 0;
  }
  var x = rectangle.x, y = rectangle.y, w = rectangle.width, h = rectangle.height;
  var r = reduceRotation(degreeAngle);
  var b = borderWidth / 2;
  if (r === 0)
    return { x: x - b, y: y - b, width: w, height: h };
  else if (r === 90)
    return { x: x - h + b, y: y - b, width: h, height: w };
  else if (r === 180)
    return { x: x - w + b, y: y - h + b, width: w, height: h };
  else if (r === 270)
    return { x: x - b, y: y - w + b, width: h, height: w };
  else
    return { x: x - b, y: y - b, width: w, height: h };
};

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/api/operators.js
var clip = function() {
  return PDFOperator_default.of(PDFOperatorNames_default.ClipNonZero);
};
var cos = Math.cos;
var sin = Math.sin;
var tan = Math.tan;
var concatTransformationMatrix = function(a, b, c, d, e, f) {
  return PDFOperator_default.of(PDFOperatorNames_default.ConcatTransformationMatrix, [
    asPDFNumber(a),
    asPDFNumber(b),
    asPDFNumber(c),
    asPDFNumber(d),
    asPDFNumber(e),
    asPDFNumber(f)
  ]);
};
var translate = function(xPos, yPos) {
  return concatTransformationMatrix(1, 0, 0, 1, xPos, yPos);
};
var scale = function(xPos, yPos) {
  return concatTransformationMatrix(xPos, 0, 0, yPos, 0, 0);
};
var rotateRadians = function(angle) {
  return concatTransformationMatrix(cos(asNumber(angle)), sin(asNumber(angle)), -sin(asNumber(angle)), cos(asNumber(angle)), 0, 0);
};
var rotateDegrees = function(angle) {
  return rotateRadians(degreesToRadians(asNumber(angle)));
};
var skewRadians = function(xSkewAngle, ySkewAngle) {
  return concatTransformationMatrix(1, tan(asNumber(xSkewAngle)), tan(asNumber(ySkewAngle)), 1, 0, 0);
};
var setDashPattern = function(dashArray, dashPhase) {
  return PDFOperator_default.of(PDFOperatorNames_default.SetLineDashPattern, [
    "[" + dashArray.map(asPDFNumber).join(" ") + "]",
    asPDFNumber(dashPhase)
  ]);
};
var LineCapStyle;
(function(LineCapStyle2) {
  LineCapStyle2[LineCapStyle2["Butt"] = 0] = "Butt";
  LineCapStyle2[LineCapStyle2["Round"] = 1] = "Round";
  LineCapStyle2[LineCapStyle2["Projecting"] = 2] = "Projecting";
})(LineCapStyle || (LineCapStyle = {}));
var setLineCap = function(style) {
  return PDFOperator_default.of(PDFOperatorNames_default.SetLineCapStyle, [asPDFNumber(style)]);
};
var LineJoinStyle;
(function(LineJoinStyle2) {
  LineJoinStyle2[LineJoinStyle2["Miter"] = 0] = "Miter";
  LineJoinStyle2[LineJoinStyle2["Round"] = 1] = "Round";
  LineJoinStyle2[LineJoinStyle2["Bevel"] = 2] = "Bevel";
})(LineJoinStyle || (LineJoinStyle = {}));
var setGraphicsState = function(state) {
  return PDFOperator_default.of(PDFOperatorNames_default.SetGraphicsStateParams, [asPDFName(state)]);
};
var pushGraphicsState = function() {
  return PDFOperator_default.of(PDFOperatorNames_default.PushGraphicsState);
};
var popGraphicsState = function() {
  return PDFOperator_default.of(PDFOperatorNames_default.PopGraphicsState);
};
var setLineWidth = function(width) {
  return PDFOperator_default.of(PDFOperatorNames_default.SetLineWidth, [asPDFNumber(width)]);
};
var appendBezierCurve = function(x1, y1, x2, y2, x3, y3) {
  return PDFOperator_default.of(PDFOperatorNames_default.AppendBezierCurve, [
    asPDFNumber(x1),
    asPDFNumber(y1),
    asPDFNumber(x2),
    asPDFNumber(y2),
    asPDFNumber(x3),
    asPDFNumber(y3)
  ]);
};
var appendQuadraticCurve = function(x1, y1, x2, y2) {
  return PDFOperator_default.of(PDFOperatorNames_default.CurveToReplicateInitialPoint, [
    asPDFNumber(x1),
    asPDFNumber(y1),
    asPDFNumber(x2),
    asPDFNumber(y2)
  ]);
};
var closePath = function() {
  return PDFOperator_default.of(PDFOperatorNames_default.ClosePath);
};
var moveTo = function(xPos, yPos) {
  return PDFOperator_default.of(PDFOperatorNames_default.MoveTo, [asPDFNumber(xPos), asPDFNumber(yPos)]);
};
var lineTo = function(xPos, yPos) {
  return PDFOperator_default.of(PDFOperatorNames_default.LineTo, [asPDFNumber(xPos), asPDFNumber(yPos)]);
};
var stroke = function() {
  return PDFOperator_default.of(PDFOperatorNames_default.StrokePath);
};
var fill = function() {
  return PDFOperator_default.of(PDFOperatorNames_default.FillNonZero);
};
var fillAndStroke = function() {
  return PDFOperator_default.of(PDFOperatorNames_default.FillNonZeroAndStroke);
};
var endPath = function() {
  return PDFOperator_default.of(PDFOperatorNames_default.EndPath);
};
var nextLine = function() {
  return PDFOperator_default.of(PDFOperatorNames_default.NextLine);
};
var showText = function(text) {
  return PDFOperator_default.of(PDFOperatorNames_default.ShowText, [text]);
};
var beginText = function() {
  return PDFOperator_default.of(PDFOperatorNames_default.BeginText);
};
var endText = function() {
  return PDFOperator_default.of(PDFOperatorNames_default.EndText);
};
var setFontAndSize = function(name, size) {
  return PDFOperator_default.of(PDFOperatorNames_default.SetFontAndSize, [asPDFName(name), asPDFNumber(size)]);
};
var setLineHeight = function(lineHeight) {
  return PDFOperator_default.of(PDFOperatorNames_default.SetTextLineHeight, [asPDFNumber(lineHeight)]);
};
var TextRenderingMode;
(function(TextRenderingMode2) {
  TextRenderingMode2[TextRenderingMode2["Fill"] = 0] = "Fill";
  TextRenderingMode2[TextRenderingMode2["Outline"] = 1] = "Outline";
  TextRenderingMode2[TextRenderingMode2["FillAndOutline"] = 2] = "FillAndOutline";
  TextRenderingMode2[TextRenderingMode2["Invisible"] = 3] = "Invisible";
  TextRenderingMode2[TextRenderingMode2["FillAndClip"] = 4] = "FillAndClip";
  TextRenderingMode2[TextRenderingMode2["OutlineAndClip"] = 5] = "OutlineAndClip";
  TextRenderingMode2[TextRenderingMode2["FillAndOutlineAndClip"] = 6] = "FillAndOutlineAndClip";
  TextRenderingMode2[TextRenderingMode2["Clip"] = 7] = "Clip";
})(TextRenderingMode || (TextRenderingMode = {}));
var setTextMatrix = function(a, b, c, d, e, f) {
  return PDFOperator_default.of(PDFOperatorNames_default.SetTextMatrix, [
    asPDFNumber(a),
    asPDFNumber(b),
    asPDFNumber(c),
    asPDFNumber(d),
    asPDFNumber(e),
    asPDFNumber(f)
  ]);
};
var rotateAndSkewTextRadiansAndTranslate = function(rotationAngle, xSkewAngle, ySkewAngle, x, y) {
  return setTextMatrix(cos(asNumber(rotationAngle)), sin(asNumber(rotationAngle)) + tan(asNumber(xSkewAngle)), -sin(asNumber(rotationAngle)) + tan(asNumber(ySkewAngle)), cos(asNumber(rotationAngle)), x, y);
};
var drawObject = function(name) {
  return PDFOperator_default.of(PDFOperatorNames_default.DrawObject, [asPDFName(name)]);
};
var setFillingGrayscaleColor = function(gray) {
  return PDFOperator_default.of(PDFOperatorNames_default.NonStrokingColorGray, [asPDFNumber(gray)]);
};
var setStrokingGrayscaleColor = function(gray) {
  return PDFOperator_default.of(PDFOperatorNames_default.StrokingColorGray, [asPDFNumber(gray)]);
};
var setFillingRgbColor = function(red, green, blue) {
  return PDFOperator_default.of(PDFOperatorNames_default.NonStrokingColorRgb, [
    asPDFNumber(red),
    asPDFNumber(green),
    asPDFNumber(blue)
  ]);
};
var setStrokingRgbColor = function(red, green, blue) {
  return PDFOperator_default.of(PDFOperatorNames_default.StrokingColorRgb, [
    asPDFNumber(red),
    asPDFNumber(green),
    asPDFNumber(blue)
  ]);
};
var setFillingCmykColor = function(cyan, magenta, yellow, key) {
  return PDFOperator_default.of(PDFOperatorNames_default.NonStrokingColorCmyk, [
    asPDFNumber(cyan),
    asPDFNumber(magenta),
    asPDFNumber(yellow),
    asPDFNumber(key)
  ]);
};
var setStrokingCmykColor = function(cyan, magenta, yellow, key) {
  return PDFOperator_default.of(PDFOperatorNames_default.StrokingColorCmyk, [
    asPDFNumber(cyan),
    asPDFNumber(magenta),
    asPDFNumber(yellow),
    asPDFNumber(key)
  ]);
};
var beginMarkedContent = function(tag) {
  return PDFOperator_default.of(PDFOperatorNames_default.BeginMarkedContent, [asPDFName(tag)]);
};
var endMarkedContent = function() {
  return PDFOperator_default.of(PDFOperatorNames_default.EndMarkedContent);
};

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/api/colors.js
var ColorTypes;
(function(ColorTypes2) {
  ColorTypes2["Grayscale"] = "Grayscale";
  ColorTypes2["RGB"] = "RGB";
  ColorTypes2["CMYK"] = "CMYK";
})(ColorTypes || (ColorTypes = {}));
var grayscale = function(gray) {
  assertRange(gray, "gray", 0, 1);
  return { type: ColorTypes.Grayscale, gray };
};
var rgb = function(red, green, blue) {
  assertRange(red, "red", 0, 1);
  assertRange(green, "green", 0, 1);
  assertRange(blue, "blue", 0, 1);
  return { type: ColorTypes.RGB, red, green, blue };
};
var cmyk = function(cyan, magenta, yellow, key) {
  assertRange(cyan, "cyan", 0, 1);
  assertRange(magenta, "magenta", 0, 1);
  assertRange(yellow, "yellow", 0, 1);
  assertRange(key, "key", 0, 1);
  return { type: ColorTypes.CMYK, cyan, magenta, yellow, key };
};
var Grayscale = ColorTypes.Grayscale;
var RGB = ColorTypes.RGB;
var CMYK = ColorTypes.CMYK;
var setFillingColor = function(color) {
  return color.type === Grayscale ? setFillingGrayscaleColor(color.gray) : color.type === RGB ? setFillingRgbColor(color.red, color.green, color.blue) : color.type === CMYK ? setFillingCmykColor(color.cyan, color.magenta, color.yellow, color.key) : error("Invalid color: " + JSON.stringify(color));
};
var setStrokingColor = function(color) {
  return color.type === Grayscale ? setStrokingGrayscaleColor(color.gray) : color.type === RGB ? setStrokingRgbColor(color.red, color.green, color.blue) : color.type === CMYK ? setStrokingCmykColor(color.cyan, color.magenta, color.yellow, color.key) : error("Invalid color: " + JSON.stringify(color));
};
var componentsToColor = function(comps, scale2) {
  if (scale2 === void 0) {
    scale2 = 1;
  }
  return (comps === null || comps === void 0 ? void 0 : comps.length) === 1 ? grayscale(comps[0] * scale2) : (comps === null || comps === void 0 ? void 0 : comps.length) === 3 ? rgb(comps[0] * scale2, comps[1] * scale2, comps[2] * scale2) : (comps === null || comps === void 0 ? void 0 : comps.length) === 4 ? cmyk(comps[0] * scale2, comps[1] * scale2, comps[2] * scale2, comps[3] * scale2) : void 0;
};
var colorToComponents = function(color) {
  return color.type === Grayscale ? [color.gray] : color.type === RGB ? [color.red, color.green, color.blue] : color.type === CMYK ? [color.cyan, color.magenta, color.yellow, color.key] : error("Invalid color: " + JSON.stringify(color));
};

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/api/svgPath.js
var cx = 0;
var cy = 0;
var px = 0;
var py = 0;
var sx = 0;
var sy = 0;
var parameters = /* @__PURE__ */ new Map([
  ["A", 7],
  ["a", 7],
  ["C", 6],
  ["c", 6],
  ["H", 1],
  ["h", 1],
  ["L", 2],
  ["l", 2],
  ["M", 2],
  ["m", 2],
  ["Q", 4],
  ["q", 4],
  ["S", 4],
  ["s", 4],
  ["T", 2],
  ["t", 2],
  ["V", 1],
  ["v", 1],
  ["Z", 0],
  ["z", 0]
]);
var parse = function(path3) {
  var cmd;
  var ret = [];
  var args = [];
  var curArg = "";
  var foundDecimal = false;
  var params = 0;
  for (var _i = 0, path_1 = path3; _i < path_1.length; _i++) {
    var c = path_1[_i];
    if (parameters.has(c)) {
      params = parameters.get(c);
      if (cmd) {
        if (curArg.length > 0) {
          args[args.length] = +curArg;
        }
        ret[ret.length] = { cmd, args };
        args = [];
        curArg = "";
        foundDecimal = false;
      }
      cmd = c;
    } else if ([" ", ","].includes(c) || c === "-" && curArg.length > 0 && curArg[curArg.length - 1] !== "e" || c === "." && foundDecimal) {
      if (curArg.length === 0) {
        continue;
      }
      if (args.length === params) {
        ret[ret.length] = { cmd, args };
        args = [+curArg];
        if (cmd === "M") {
          cmd = "L";
        }
        if (cmd === "m") {
          cmd = "l";
        }
      } else {
        args[args.length] = +curArg;
      }
      foundDecimal = c === ".";
      curArg = ["-", "."].includes(c) ? c : "";
    } else {
      curArg += c;
      if (c === ".") {
        foundDecimal = true;
      }
    }
  }
  if (curArg.length > 0) {
    if (args.length === params) {
      ret[ret.length] = { cmd, args };
      args = [+curArg];
      if (cmd === "M") {
        cmd = "L";
      }
      if (cmd === "m") {
        cmd = "l";
      }
    } else {
      args[args.length] = +curArg;
    }
  }
  ret[ret.length] = { cmd, args };
  return ret;
};
var apply = function(commands) {
  cx = cy = px = py = sx = sy = 0;
  var cmds = [];
  for (var i = 0; i < commands.length; i++) {
    var c = commands[i];
    if (c.cmd && typeof runners[c.cmd] === "function") {
      var cmd = runners[c.cmd](c.args);
      if (Array.isArray(cmd)) {
        cmds = cmds.concat(cmd);
      } else {
        cmds.push(cmd);
      }
    }
  }
  return cmds;
};
var runners = {
  M: function(a) {
    cx = a[0];
    cy = a[1];
    px = py = null;
    sx = cx;
    sy = cy;
    return moveTo(cx, cy);
  },
  m: function(a) {
    cx += a[0];
    cy += a[1];
    px = py = null;
    sx = cx;
    sy = cy;
    return moveTo(cx, cy);
  },
  C: function(a) {
    cx = a[4];
    cy = a[5];
    px = a[2];
    py = a[3];
    return appendBezierCurve(a[0], a[1], a[2], a[3], a[4], a[5]);
  },
  c: function(a) {
    var cmd = appendBezierCurve(a[0] + cx, a[1] + cy, a[2] + cx, a[3] + cy, a[4] + cx, a[5] + cy);
    px = cx + a[2];
    py = cy + a[3];
    cx += a[4];
    cy += a[5];
    return cmd;
  },
  S: function(a) {
    if (px === null || py === null) {
      px = cx;
      py = cy;
    }
    var cmd = appendBezierCurve(cx - (px - cx), cy - (py - cy), a[0], a[1], a[2], a[3]);
    px = a[0];
    py = a[1];
    cx = a[2];
    cy = a[3];
    return cmd;
  },
  s: function(a) {
    if (px === null || py === null) {
      px = cx;
      py = cy;
    }
    var cmd = appendBezierCurve(cx - (px - cx), cy - (py - cy), cx + a[0], cy + a[1], cx + a[2], cy + a[3]);
    px = cx + a[0];
    py = cy + a[1];
    cx += a[2];
    cy += a[3];
    return cmd;
  },
  Q: function(a) {
    px = a[0];
    py = a[1];
    cx = a[2];
    cy = a[3];
    return appendQuadraticCurve(a[0], a[1], cx, cy);
  },
  q: function(a) {
    var cmd = appendQuadraticCurve(a[0] + cx, a[1] + cy, a[2] + cx, a[3] + cy);
    px = cx + a[0];
    py = cy + a[1];
    cx += a[2];
    cy += a[3];
    return cmd;
  },
  T: function(a) {
    if (px === null || py === null) {
      px = cx;
      py = cy;
    } else {
      px = cx - (px - cx);
      py = cy - (py - cy);
    }
    var cmd = appendQuadraticCurve(px, py, a[0], a[1]);
    px = cx - (px - cx);
    py = cy - (py - cy);
    cx = a[0];
    cy = a[1];
    return cmd;
  },
  t: function(a) {
    if (px === null || py === null) {
      px = cx;
      py = cy;
    } else {
      px = cx - (px - cx);
      py = cy - (py - cy);
    }
    var cmd = appendQuadraticCurve(px, py, cx + a[0], cy + a[1]);
    cx += a[0];
    cy += a[1];
    return cmd;
  },
  A: function(a) {
    var cmds = solveArc(cx, cy, a);
    cx = a[5];
    cy = a[6];
    return cmds;
  },
  a: function(a) {
    a[5] += cx;
    a[6] += cy;
    var cmds = solveArc(cx, cy, a);
    cx = a[5];
    cy = a[6];
    return cmds;
  },
  L: function(a) {
    cx = a[0];
    cy = a[1];
    px = py = null;
    return lineTo(cx, cy);
  },
  l: function(a) {
    cx += a[0];
    cy += a[1];
    px = py = null;
    return lineTo(cx, cy);
  },
  H: function(a) {
    cx = a[0];
    px = py = null;
    return lineTo(cx, cy);
  },
  h: function(a) {
    cx += a[0];
    px = py = null;
    return lineTo(cx, cy);
  },
  V: function(a) {
    cy = a[0];
    px = py = null;
    return lineTo(cx, cy);
  },
  v: function(a) {
    cy += a[0];
    px = py = null;
    return lineTo(cx, cy);
  },
  Z: function() {
    var cmd = closePath();
    cx = sx;
    cy = sy;
    return cmd;
  },
  z: function() {
    var cmd = closePath();
    cx = sx;
    cy = sy;
    return cmd;
  }
};
var solveArc = function(x, y, coords) {
  var rx = coords[0], ry = coords[1], rot = coords[2], large = coords[3], sweep = coords[4], ex = coords[5], ey = coords[6];
  var segs = arcToSegments(ex, ey, rx, ry, large, sweep, rot, x, y);
  var cmds = [];
  for (var _i = 0, segs_1 = segs; _i < segs_1.length; _i++) {
    var seg = segs_1[_i];
    var bez = segmentToBezier.apply(void 0, seg);
    cmds.push(appendBezierCurve.apply(void 0, bez));
  }
  return cmds;
};
var arcToSegments = function(x, y, rx, ry, large, sweep, rotateX, ox, oy) {
  var th = rotateX * (Math.PI / 180);
  var sinTh = Math.sin(th);
  var cosTh = Math.cos(th);
  rx = Math.abs(rx);
  ry = Math.abs(ry);
  px = cosTh * (ox - x) * 0.5 + sinTh * (oy - y) * 0.5;
  py = cosTh * (oy - y) * 0.5 - sinTh * (ox - x) * 0.5;
  var pl = px * px / (rx * rx) + py * py / (ry * ry);
  if (pl > 1) {
    pl = Math.sqrt(pl);
    rx *= pl;
    ry *= pl;
  }
  var a00 = cosTh / rx;
  var a01 = sinTh / rx;
  var a10 = -sinTh / ry;
  var a11 = cosTh / ry;
  var x0 = a00 * ox + a01 * oy;
  var y0 = a10 * ox + a11 * oy;
  var x1 = a00 * x + a01 * y;
  var y1 = a10 * x + a11 * y;
  var d = (x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0);
  var sfactorSq = 1 / d - 0.25;
  if (sfactorSq < 0) {
    sfactorSq = 0;
  }
  var sfactor = Math.sqrt(sfactorSq);
  if (sweep === large) {
    sfactor = -sfactor;
  }
  var xc = 0.5 * (x0 + x1) - sfactor * (y1 - y0);
  var yc = 0.5 * (y0 + y1) + sfactor * (x1 - x0);
  var th0 = Math.atan2(y0 - yc, x0 - xc);
  var th1 = Math.atan2(y1 - yc, x1 - xc);
  var thArc = th1 - th0;
  if (thArc < 0 && sweep === 1) {
    thArc += 2 * Math.PI;
  } else if (thArc > 0 && sweep === 0) {
    thArc -= 2 * Math.PI;
  }
  var segments = Math.ceil(Math.abs(thArc / (Math.PI * 0.5 + 1e-3)));
  var result = [];
  for (var i = 0; i < segments; i++) {
    var th2 = th0 + i * thArc / segments;
    var th3 = th0 + (i + 1) * thArc / segments;
    result[i] = [xc, yc, th2, th3, rx, ry, sinTh, cosTh];
  }
  return result;
};
var segmentToBezier = function(cx1, cy1, th0, th1, rx, ry, sinTh, cosTh) {
  var a00 = cosTh * rx;
  var a01 = -sinTh * ry;
  var a10 = sinTh * rx;
  var a11 = cosTh * ry;
  var thHalf = 0.5 * (th1 - th0);
  var t = 8 / 3 * Math.sin(thHalf * 0.5) * Math.sin(thHalf * 0.5) / Math.sin(thHalf);
  var x1 = cx1 + Math.cos(th0) - t * Math.sin(th0);
  var y1 = cy1 + Math.sin(th0) + t * Math.cos(th0);
  var x3 = cx1 + Math.cos(th1);
  var y3 = cy1 + Math.sin(th1);
  var x2 = x3 + t * Math.sin(th1);
  var y2 = y3 - t * Math.cos(th1);
  var result = [
    a00 * x1 + a01 * y1,
    a10 * x1 + a11 * y1,
    a00 * x2 + a01 * y2,
    a10 * x2 + a11 * y2,
    a00 * x3 + a01 * y3,
    a10 * x3 + a11 * y3
  ];
  return result;
};
var svgPathToOperators = function(path3) {
  return apply(parse(path3));
};

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/api/operations.js
var drawLinesOfText = function(lines, options) {
  var operators = [
    pushGraphicsState(),
    options.graphicsState && setGraphicsState(options.graphicsState),
    beginText(),
    setFillingColor(options.color),
    setFontAndSize(options.font, options.size),
    setLineHeight(options.lineHeight),
    rotateAndSkewTextRadiansAndTranslate(toRadians(options.rotate), toRadians(options.xSkew), toRadians(options.ySkew), options.x, options.y)
  ].filter(Boolean);
  for (var idx = 0, len = lines.length; idx < len; idx++) {
    operators.push(showText(lines[idx]), nextLine());
  }
  operators.push(endText(), popGraphicsState());
  return operators;
};
var drawImage = function(name, options) {
  return [
    pushGraphicsState(),
    options.graphicsState && setGraphicsState(options.graphicsState),
    translate(options.x, options.y),
    rotateRadians(toRadians(options.rotate)),
    scale(options.width, options.height),
    skewRadians(toRadians(options.xSkew), toRadians(options.ySkew)),
    drawObject(name),
    popGraphicsState()
  ].filter(Boolean);
};
var drawPage = function(name, options) {
  return [
    pushGraphicsState(),
    options.graphicsState && setGraphicsState(options.graphicsState),
    translate(options.x, options.y),
    rotateRadians(toRadians(options.rotate)),
    scale(options.xScale, options.yScale),
    skewRadians(toRadians(options.xSkew), toRadians(options.ySkew)),
    drawObject(name),
    popGraphicsState()
  ].filter(Boolean);
};
var drawLine = function(options) {
  var _a, _b;
  return [
    pushGraphicsState(),
    options.graphicsState && setGraphicsState(options.graphicsState),
    options.color && setStrokingColor(options.color),
    setLineWidth(options.thickness),
    setDashPattern((_a = options.dashArray) !== null && _a !== void 0 ? _a : [], (_b = options.dashPhase) !== null && _b !== void 0 ? _b : 0),
    moveTo(options.start.x, options.start.y),
    options.lineCap && setLineCap(options.lineCap),
    moveTo(options.start.x, options.start.y),
    lineTo(options.end.x, options.end.y),
    stroke(),
    popGraphicsState()
  ].filter(Boolean);
};
var drawRectangle = function(options) {
  var _a, _b;
  return [
    pushGraphicsState(),
    options.graphicsState && setGraphicsState(options.graphicsState),
    options.color && setFillingColor(options.color),
    options.borderColor && setStrokingColor(options.borderColor),
    setLineWidth(options.borderWidth),
    options.borderLineCap && setLineCap(options.borderLineCap),
    setDashPattern((_a = options.borderDashArray) !== null && _a !== void 0 ? _a : [], (_b = options.borderDashPhase) !== null && _b !== void 0 ? _b : 0),
    translate(options.x, options.y),
    rotateRadians(toRadians(options.rotate)),
    skewRadians(toRadians(options.xSkew), toRadians(options.ySkew)),
    moveTo(0, 0),
    lineTo(0, options.height),
    lineTo(options.width, options.height),
    lineTo(options.width, 0),
    closePath(),
    // prettier-ignore
    options.color && options.borderWidth ? fillAndStroke() : options.color ? fill() : options.borderColor ? stroke() : closePath(),
    popGraphicsState()
  ].filter(Boolean);
};
var KAPPA = 4 * ((Math.sqrt(2) - 1) / 3);
var drawEllipsePath = function(config) {
  var x = asNumber(config.x);
  var y = asNumber(config.y);
  var xScale = asNumber(config.xScale);
  var yScale = asNumber(config.yScale);
  x -= xScale;
  y -= yScale;
  var ox = xScale * KAPPA;
  var oy = yScale * KAPPA;
  var xe = x + xScale * 2;
  var ye = y + yScale * 2;
  var xm = x + xScale;
  var ym = y + yScale;
  return [
    pushGraphicsState(),
    moveTo(x, ym),
    appendBezierCurve(x, ym - oy, xm - ox, y, xm, y),
    appendBezierCurve(xm + ox, y, xe, ym - oy, xe, ym),
    appendBezierCurve(xe, ym + oy, xm + ox, ye, xm, ye),
    appendBezierCurve(xm - ox, ye, x, ym + oy, x, ym),
    popGraphicsState()
  ];
};
var drawEllipseCurves = function(config) {
  var centerX = asNumber(config.x);
  var centerY = asNumber(config.y);
  var xScale = asNumber(config.xScale);
  var yScale = asNumber(config.yScale);
  var x = -xScale;
  var y = -yScale;
  var ox = xScale * KAPPA;
  var oy = yScale * KAPPA;
  var xe = x + xScale * 2;
  var ye = y + yScale * 2;
  var xm = x + xScale;
  var ym = y + yScale;
  return [
    translate(centerX, centerY),
    rotateRadians(toRadians(config.rotate)),
    moveTo(x, ym),
    appendBezierCurve(x, ym - oy, xm - ox, y, xm, y),
    appendBezierCurve(xm + ox, y, xe, ym - oy, xe, ym),
    appendBezierCurve(xe, ym + oy, xm + ox, ye, xm, ye),
    appendBezierCurve(xm - ox, ye, x, ym + oy, x, ym)
  ];
};
var drawEllipse = function(options) {
  var _a, _b, _c;
  return __spreadArrays([
    pushGraphicsState(),
    options.graphicsState && setGraphicsState(options.graphicsState),
    options.color && setFillingColor(options.color),
    options.borderColor && setStrokingColor(options.borderColor),
    setLineWidth(options.borderWidth),
    options.borderLineCap && setLineCap(options.borderLineCap),
    setDashPattern((_a = options.borderDashArray) !== null && _a !== void 0 ? _a : [], (_b = options.borderDashPhase) !== null && _b !== void 0 ? _b : 0)
  ], options.rotate === void 0 ? drawEllipsePath({
    x: options.x,
    y: options.y,
    xScale: options.xScale,
    yScale: options.yScale
  }) : drawEllipseCurves({
    x: options.x,
    y: options.y,
    xScale: options.xScale,
    yScale: options.yScale,
    rotate: (_c = options.rotate) !== null && _c !== void 0 ? _c : degrees(0)
  }), [
    // prettier-ignore
    options.color && options.borderWidth ? fillAndStroke() : options.color ? fill() : options.borderColor ? stroke() : closePath(),
    popGraphicsState()
  ]).filter(Boolean);
};
var drawSvgPath = function(path3, options) {
  var _a, _b, _c;
  return __spreadArrays([
    pushGraphicsState(),
    options.graphicsState && setGraphicsState(options.graphicsState),
    translate(options.x, options.y),
    rotateRadians(toRadians((_a = options.rotate) !== null && _a !== void 0 ? _a : degrees(0))),
    // SVG path Y axis is opposite pdf-lib's
    options.scale ? scale(options.scale, -options.scale) : scale(1, -1),
    options.color && setFillingColor(options.color),
    options.borderColor && setStrokingColor(options.borderColor),
    options.borderWidth && setLineWidth(options.borderWidth),
    options.borderLineCap && setLineCap(options.borderLineCap),
    setDashPattern((_b = options.borderDashArray) !== null && _b !== void 0 ? _b : [], (_c = options.borderDashPhase) !== null && _c !== void 0 ? _c : 0)
  ], svgPathToOperators(path3), [
    // prettier-ignore
    options.color && options.borderWidth ? fillAndStroke() : options.color ? fill() : options.borderColor ? stroke() : closePath(),
    popGraphicsState()
  ]).filter(Boolean);
};
var drawCheckMark = function(options) {
  var size = asNumber(options.size);
  var p2x = -1 + 0.75;
  var p2y = -1 + 0.51;
  var p3y = 1 - 0.525;
  var p3x = 1 - 0.31;
  var p1x = -1 + 0.325;
  var p1y = -((p1x - p2x) * (p3x - p2x)) / (p3y - p2y) + p2y;
  return [
    pushGraphicsState(),
    options.color && setStrokingColor(options.color),
    setLineWidth(options.thickness),
    translate(options.x, options.y),
    moveTo(p1x * size, p1y * size),
    lineTo(p2x * size, p2y * size),
    lineTo(p3x * size, p3y * size),
    stroke(),
    popGraphicsState()
  ].filter(Boolean);
};
var rotateInPlace = function(options) {
  return options.rotation === 0 ? [
    translate(0, 0),
    rotateDegrees(0)
  ] : options.rotation === 90 ? [
    translate(options.width, 0),
    rotateDegrees(90)
  ] : options.rotation === 180 ? [
    translate(options.width, options.height),
    rotateDegrees(180)
  ] : options.rotation === 270 ? [
    translate(0, options.height),
    rotateDegrees(270)
  ] : [];
};
var drawCheckBox = function(options) {
  var outline = drawRectangle({
    x: options.x,
    y: options.y,
    width: options.width,
    height: options.height,
    borderWidth: options.borderWidth,
    color: options.color,
    borderColor: options.borderColor,
    rotate: degrees(0),
    xSkew: degrees(0),
    ySkew: degrees(0)
  });
  if (!options.filled)
    return outline;
  var width = asNumber(options.width);
  var height = asNumber(options.height);
  var checkMarkSize = Math.min(width, height) / 2;
  var checkMark = drawCheckMark({
    x: width / 2,
    y: height / 2,
    size: checkMarkSize,
    thickness: options.thickness,
    color: options.markColor
  });
  return __spreadArrays([pushGraphicsState()], outline, checkMark, [popGraphicsState()]);
};
var drawRadioButton = function(options) {
  var width = asNumber(options.width);
  var height = asNumber(options.height);
  var outlineScale = Math.min(width, height) / 2;
  var outline = drawEllipse({
    x: options.x,
    y: options.y,
    xScale: outlineScale,
    yScale: outlineScale,
    color: options.color,
    borderColor: options.borderColor,
    borderWidth: options.borderWidth
  });
  if (!options.filled)
    return outline;
  var dot = drawEllipse({
    x: options.x,
    y: options.y,
    xScale: outlineScale * 0.45,
    yScale: outlineScale * 0.45,
    color: options.dotColor,
    borderColor: void 0,
    borderWidth: 0
  });
  return __spreadArrays([pushGraphicsState()], outline, dot, [popGraphicsState()]);
};
var drawButton = function(options) {
  var x = asNumber(options.x);
  var y = asNumber(options.y);
  var width = asNumber(options.width);
  var height = asNumber(options.height);
  var background = drawRectangle({
    x,
    y,
    width,
    height,
    borderWidth: options.borderWidth,
    color: options.color,
    borderColor: options.borderColor,
    rotate: degrees(0),
    xSkew: degrees(0),
    ySkew: degrees(0)
  });
  var lines = drawTextLines(options.textLines, {
    color: options.textColor,
    font: options.font,
    size: options.fontSize,
    rotate: degrees(0),
    xSkew: degrees(0),
    ySkew: degrees(0)
  });
  return __spreadArrays([pushGraphicsState()], background, lines, [popGraphicsState()]);
};
var drawTextLines = function(lines, options) {
  var operators = [
    beginText(),
    setFillingColor(options.color),
    setFontAndSize(options.font, options.size)
  ];
  for (var idx = 0, len = lines.length; idx < len; idx++) {
    var _a = lines[idx], encoded = _a.encoded, x = _a.x, y = _a.y;
    operators.push(rotateAndSkewTextRadiansAndTranslate(toRadians(options.rotate), toRadians(options.xSkew), toRadians(options.ySkew), x, y), showText(encoded));
  }
  operators.push(endText());
  return operators;
};
var drawTextField = function(options) {
  var x = asNumber(options.x);
  var y = asNumber(options.y);
  var width = asNumber(options.width);
  var height = asNumber(options.height);
  var borderWidth = asNumber(options.borderWidth);
  var padding = asNumber(options.padding);
  var clipX = x + borderWidth / 2 + padding;
  var clipY = y + borderWidth / 2 + padding;
  var clipWidth = width - (borderWidth / 2 + padding) * 2;
  var clipHeight = height - (borderWidth / 2 + padding) * 2;
  var clippingArea = [
    moveTo(clipX, clipY),
    lineTo(clipX, clipY + clipHeight),
    lineTo(clipX + clipWidth, clipY + clipHeight),
    lineTo(clipX + clipWidth, clipY),
    closePath(),
    clip(),
    endPath()
  ];
  var background = drawRectangle({
    x,
    y,
    width,
    height,
    borderWidth: options.borderWidth,
    color: options.color,
    borderColor: options.borderColor,
    rotate: degrees(0),
    xSkew: degrees(0),
    ySkew: degrees(0)
  });
  var lines = drawTextLines(options.textLines, {
    color: options.textColor,
    font: options.font,
    size: options.fontSize,
    rotate: degrees(0),
    xSkew: degrees(0),
    ySkew: degrees(0)
  });
  var markedContent = __spreadArrays([
    beginMarkedContent("Tx"),
    pushGraphicsState()
  ], lines, [
    popGraphicsState(),
    endMarkedContent()
  ]);
  return __spreadArrays([
    pushGraphicsState()
  ], background, clippingArea, markedContent, [
    popGraphicsState()
  ]);
};
var drawOptionList = function(options) {
  var x = asNumber(options.x);
  var y = asNumber(options.y);
  var width = asNumber(options.width);
  var height = asNumber(options.height);
  var lineHeight = asNumber(options.lineHeight);
  var borderWidth = asNumber(options.borderWidth);
  var padding = asNumber(options.padding);
  var clipX = x + borderWidth / 2 + padding;
  var clipY = y + borderWidth / 2 + padding;
  var clipWidth = width - (borderWidth / 2 + padding) * 2;
  var clipHeight = height - (borderWidth / 2 + padding) * 2;
  var clippingArea = [
    moveTo(clipX, clipY),
    lineTo(clipX, clipY + clipHeight),
    lineTo(clipX + clipWidth, clipY + clipHeight),
    lineTo(clipX + clipWidth, clipY),
    closePath(),
    clip(),
    endPath()
  ];
  var background = drawRectangle({
    x,
    y,
    width,
    height,
    borderWidth: options.borderWidth,
    color: options.color,
    borderColor: options.borderColor,
    rotate: degrees(0),
    xSkew: degrees(0),
    ySkew: degrees(0)
  });
  var highlights = [];
  for (var idx = 0, len = options.selectedLines.length; idx < len; idx++) {
    var line = options.textLines[options.selectedLines[idx]];
    highlights.push.apply(highlights, drawRectangle({
      x: line.x - padding,
      y: line.y - (lineHeight - line.height) / 2,
      width: width - borderWidth,
      height: line.height + (lineHeight - line.height) / 2,
      borderWidth: 0,
      color: options.selectedColor,
      borderColor: void 0,
      rotate: degrees(0),
      xSkew: degrees(0),
      ySkew: degrees(0)
    }));
  }
  var lines = drawTextLines(options.textLines, {
    color: options.textColor,
    font: options.font,
    size: options.fontSize,
    rotate: degrees(0),
    xSkew: degrees(0),
    ySkew: degrees(0)
  });
  var markedContent = __spreadArrays([
    beginMarkedContent("Tx"),
    pushGraphicsState()
  ], lines, [
    popGraphicsState(),
    endMarkedContent()
  ]);
  return __spreadArrays([
    pushGraphicsState()
  ], background, highlights, clippingArea, markedContent, [
    popGraphicsState()
  ]);
};

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/api/errors.js
var EncryptedPDFError = (
  /** @class */
  function(_super) {
    __extends(EncryptedPDFError2, _super);
    function EncryptedPDFError2() {
      var _this = this;
      var msg = "Input document to `PDFDocument.load` is encrypted. You can use `PDFDocument.load(..., { ignoreEncryption: true })` if you wish to load the document anyways.";
      _this = _super.call(this, msg) || this;
      return _this;
    }
    return EncryptedPDFError2;
  }(Error)
);
var FontkitNotRegisteredError = (
  /** @class */
  function(_super) {
    __extends(FontkitNotRegisteredError2, _super);
    function FontkitNotRegisteredError2() {
      var _this = this;
      var msg = "Input to `PDFDocument.embedFont` was a custom font, but no `fontkit` instance was found. You must register a `fontkit` instance with `PDFDocument.registerFontkit(...)` before embedding custom fonts.";
      _this = _super.call(this, msg) || this;
      return _this;
    }
    return FontkitNotRegisteredError2;
  }(Error)
);
var ForeignPageError = (
  /** @class */
  function(_super) {
    __extends(ForeignPageError2, _super);
    function ForeignPageError2() {
      var _this = this;
      var msg = "A `page` passed to `PDFDocument.addPage` or `PDFDocument.insertPage` was from a different (foreign) PDF document. If you want to copy pages from one PDFDocument to another, you must use `PDFDocument.copyPages(...)` to copy the pages before adding or inserting them.";
      _this = _super.call(this, msg) || this;
      return _this;
    }
    return ForeignPageError2;
  }(Error)
);
var RemovePageFromEmptyDocumentError = (
  /** @class */
  function(_super) {
    __extends(RemovePageFromEmptyDocumentError2, _super);
    function RemovePageFromEmptyDocumentError2() {
      var _this = this;
      var msg = "PDFDocument has no pages so `PDFDocument.removePage` cannot be called";
      _this = _super.call(this, msg) || this;
      return _this;
    }
    return RemovePageFromEmptyDocumentError2;
  }(Error)
);
var NoSuchFieldError = (
  /** @class */
  function(_super) {
    __extends(NoSuchFieldError2, _super);
    function NoSuchFieldError2(name) {
      var _this = this;
      var msg = 'PDFDocument has no form field with the name "' + name + '"';
      _this = _super.call(this, msg) || this;
      return _this;
    }
    return NoSuchFieldError2;
  }(Error)
);
var UnexpectedFieldTypeError = (
  /** @class */
  function(_super) {
    __extends(UnexpectedFieldTypeError2, _super);
    function UnexpectedFieldTypeError2(name, expected, actual) {
      var _a, _b;
      var _this = this;
      var expectedType = expected === null || expected === void 0 ? void 0 : expected.name;
      var actualType = (_b = (_a = actual === null || actual === void 0 ? void 0 : actual.constructor) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : actual;
      var msg = 'Expected field "' + name + '" to be of type ' + expectedType + ", " + ("but it is actually of type " + actualType);
      _this = _super.call(this, msg) || this;
      return _this;
    }
    return UnexpectedFieldTypeError2;
  }(Error)
);
var MissingOnValueCheckError = (
  /** @class */
  function(_super) {
    __extends(MissingOnValueCheckError2, _super);
    function MissingOnValueCheckError2(onValue) {
      var _this = this;
      var msg = 'Failed to select check box due to missing onValue: "' + onValue + '"';
      _this = _super.call(this, msg) || this;
      return _this;
    }
    return MissingOnValueCheckError2;
  }(Error)
);
var FieldAlreadyExistsError = (
  /** @class */
  function(_super) {
    __extends(FieldAlreadyExistsError2, _super);
    function FieldAlreadyExistsError2(name) {
      var _this = this;
      var msg = 'A field already exists with the specified name: "' + name + '"';
      _this = _super.call(this, msg) || this;
      return _this;
    }
    return FieldAlreadyExistsError2;
  }(Error)
);
var InvalidFieldNamePartError = (
  /** @class */
  function(_super) {
    __extends(InvalidFieldNamePartError2, _super);
    function InvalidFieldNamePartError2(namePart) {
      var _this = this;
      var msg = 'Field name contains invalid component: "' + namePart + '"';
      _this = _super.call(this, msg) || this;
      return _this;
    }
    return InvalidFieldNamePartError2;
  }(Error)
);
var FieldExistsAsNonTerminalError = (
  /** @class */
  function(_super) {
    __extends(FieldExistsAsNonTerminalError2, _super);
    function FieldExistsAsNonTerminalError2(name) {
      var _this = this;
      var msg = 'A non-terminal field already exists with the specified name: "' + name + '"';
      _this = _super.call(this, msg) || this;
      return _this;
    }
    return FieldExistsAsNonTerminalError2;
  }(Error)
);
var RichTextFieldReadError = (
  /** @class */
  function(_super) {
    __extends(RichTextFieldReadError2, _super);
    function RichTextFieldReadError2(fieldName) {
      var _this = this;
      var msg = "Reading rich text fields is not supported: Attempted to read rich text field: " + fieldName;
      _this = _super.call(this, msg) || this;
      return _this;
    }
    return RichTextFieldReadError2;
  }(Error)
);
var CombedTextLayoutError = (
  /** @class */
  function(_super) {
    __extends(CombedTextLayoutError2, _super);
    function CombedTextLayoutError2(lineLength, cellCount) {
      var _this = this;
      var msg = "Failed to layout combed text as lineLength=" + lineLength + " is greater than cellCount=" + cellCount;
      _this = _super.call(this, msg) || this;
      return _this;
    }
    return CombedTextLayoutError2;
  }(Error)
);
var ExceededMaxLengthError = (
  /** @class */
  function(_super) {
    __extends(ExceededMaxLengthError2, _super);
    function ExceededMaxLengthError2(textLength, maxLength, name) {
      var _this = this;
      var msg = "Attempted to set text with length=" + textLength + " for TextField with maxLength=" + maxLength + " and name=" + name;
      _this = _super.call(this, msg) || this;
      return _this;
    }
    return ExceededMaxLengthError2;
  }(Error)
);
var InvalidMaxLengthError = (
  /** @class */
  function(_super) {
    __extends(InvalidMaxLengthError2, _super);
    function InvalidMaxLengthError2(textLength, maxLength, name) {
      var _this = this;
      var msg = "Attempted to set maxLength=" + maxLength + ", which is less than " + textLength + ", the length of this field's current value (name=" + name + ")";
      _this = _super.call(this, msg) || this;
      return _this;
    }
    return InvalidMaxLengthError2;
  }(Error)
);

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/api/text/alignment.js
var TextAlignment;
(function(TextAlignment2) {
  TextAlignment2[TextAlignment2["Left"] = 0] = "Left";
  TextAlignment2[TextAlignment2["Center"] = 1] = "Center";
  TextAlignment2[TextAlignment2["Right"] = 2] = "Right";
})(TextAlignment || (TextAlignment = {}));

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/api/text/layout.js
var MIN_FONT_SIZE = 4;
var MAX_FONT_SIZE = 500;
var computeFontSize = function(lines, font, bounds, multiline) {
  if (multiline === void 0) {
    multiline = false;
  }
  var fontSize = MIN_FONT_SIZE;
  while (fontSize < MAX_FONT_SIZE) {
    var linesUsed = 0;
    for (var lineIdx = 0, lineLen = lines.length; lineIdx < lineLen; lineIdx++) {
      linesUsed += 1;
      var line = lines[lineIdx];
      var words = line.split(" ");
      var spaceInLineRemaining = bounds.width;
      for (var idx = 0, len = words.length; idx < len; idx++) {
        var isLastWord = idx === len - 1;
        var word = isLastWord ? words[idx] : words[idx] + " ";
        var widthOfWord = font.widthOfTextAtSize(word, fontSize);
        spaceInLineRemaining -= widthOfWord;
        if (spaceInLineRemaining <= 0) {
          linesUsed += 1;
          spaceInLineRemaining = bounds.width - widthOfWord;
        }
      }
    }
    if (!multiline && linesUsed > lines.length)
      return fontSize - 1;
    var height = font.heightAtSize(fontSize);
    var lineHeight = height + height * 0.2;
    var totalHeight = lineHeight * linesUsed;
    if (totalHeight > Math.abs(bounds.height))
      return fontSize - 1;
    fontSize += 1;
  }
  return fontSize;
};
var computeCombedFontSize = function(line, font, bounds, cellCount) {
  var cellWidth = bounds.width / cellCount;
  var cellHeight = bounds.height;
  var fontSize = MIN_FONT_SIZE;
  var chars3 = charSplit(line);
  while (fontSize < MAX_FONT_SIZE) {
    for (var idx = 0, len = chars3.length; idx < len; idx++) {
      var c = chars3[idx];
      var tooLong = font.widthOfTextAtSize(c, fontSize) > cellWidth * 0.75;
      if (tooLong)
        return fontSize - 1;
    }
    var height = font.heightAtSize(fontSize, { descender: false });
    if (height > cellHeight)
      return fontSize - 1;
    fontSize += 1;
  }
  return fontSize;
};
var lastIndexOfWhitespace = function(line) {
  for (var idx = line.length; idx > 0; idx--) {
    if (/\s/.test(line[idx]))
      return idx;
  }
  return void 0;
};
var splitOutLines = function(input, maxWidth, font, fontSize) {
  var _a;
  var lastWhitespaceIdx = input.length;
  while (lastWhitespaceIdx > 0) {
    var line = input.substring(0, lastWhitespaceIdx);
    var encoded = font.encodeText(line);
    var width = font.widthOfTextAtSize(line, fontSize);
    if (width < maxWidth) {
      var remainder = input.substring(lastWhitespaceIdx) || void 0;
      return { line, encoded, width, remainder };
    }
    lastWhitespaceIdx = (_a = lastIndexOfWhitespace(line)) !== null && _a !== void 0 ? _a : 0;
  }
  return {
    line: input,
    encoded: font.encodeText(input),
    width: font.widthOfTextAtSize(input, fontSize),
    remainder: void 0
  };
};
var layoutMultilineText = function(text, _a) {
  var alignment = _a.alignment, fontSize = _a.fontSize, font = _a.font, bounds = _a.bounds;
  var lines = lineSplit(cleanText(text));
  if (fontSize === void 0 || fontSize === 0) {
    fontSize = computeFontSize(lines, font, bounds, true);
  }
  var height = font.heightAtSize(fontSize);
  var lineHeight = height + height * 0.2;
  var textLines = [];
  var minX = bounds.x;
  var minY = bounds.y;
  var maxX = bounds.x + bounds.width;
  var maxY = bounds.y + bounds.height;
  var y = bounds.y + bounds.height;
  for (var idx = 0, len = lines.length; idx < len; idx++) {
    var prevRemainder = lines[idx];
    while (prevRemainder !== void 0) {
      var _b = splitOutLines(prevRemainder, bounds.width, font, fontSize), line = _b.line, encoded = _b.encoded, width = _b.width, remainder = _b.remainder;
      var x = alignment === TextAlignment.Left ? bounds.x : alignment === TextAlignment.Center ? bounds.x + bounds.width / 2 - width / 2 : alignment === TextAlignment.Right ? bounds.x + bounds.width - width : bounds.x;
      y -= lineHeight;
      if (x < minX)
        minX = x;
      if (y < minY)
        minY = y;
      if (x + width > maxX)
        maxX = x + width;
      if (y + height > maxY)
        maxY = y + height;
      textLines.push({ text: line, encoded, width, height, x, y });
      prevRemainder = remainder === null || remainder === void 0 ? void 0 : remainder.trim();
    }
  }
  return {
    fontSize,
    lineHeight,
    lines: textLines,
    bounds: {
      x: minX,
      y: minY,
      width: maxX - minX,
      height: maxY - minY
    }
  };
};
var layoutCombedText = function(text, _a) {
  var fontSize = _a.fontSize, font = _a.font, bounds = _a.bounds, cellCount = _a.cellCount;
  var line = mergeLines(cleanText(text));
  if (line.length > cellCount) {
    throw new CombedTextLayoutError(line.length, cellCount);
  }
  if (fontSize === void 0 || fontSize === 0) {
    fontSize = computeCombedFontSize(line, font, bounds, cellCount);
  }
  var cellWidth = bounds.width / cellCount;
  var height = font.heightAtSize(fontSize, { descender: false });
  var y = bounds.y + (bounds.height / 2 - height / 2);
  var cells = [];
  var minX = bounds.x;
  var minY = bounds.y;
  var maxX = bounds.x + bounds.width;
  var maxY = bounds.y + bounds.height;
  var cellOffset = 0;
  var charOffset = 0;
  while (cellOffset < cellCount) {
    var _b = charAtIndex(line, charOffset), char = _b[0], charLength = _b[1];
    var encoded = font.encodeText(char);
    var width = font.widthOfTextAtSize(char, fontSize);
    var cellCenter = bounds.x + (cellWidth * cellOffset + cellWidth / 2);
    var x = cellCenter - width / 2;
    if (x < minX)
      minX = x;
    if (y < minY)
      minY = y;
    if (x + width > maxX)
      maxX = x + width;
    if (y + height > maxY)
      maxY = y + height;
    cells.push({ text: line, encoded, width, height, x, y });
    cellOffset += 1;
    charOffset += charLength;
  }
  return {
    fontSize,
    cells,
    bounds: {
      x: minX,
      y: minY,
      width: maxX - minX,
      height: maxY - minY
    }
  };
};
var layoutSinglelineText = function(text, _a) {
  var alignment = _a.alignment, fontSize = _a.fontSize, font = _a.font, bounds = _a.bounds;
  var line = mergeLines(cleanText(text));
  if (fontSize === void 0 || fontSize === 0) {
    fontSize = computeFontSize([line], font, bounds);
  }
  var encoded = font.encodeText(line);
  var width = font.widthOfTextAtSize(line, fontSize);
  var height = font.heightAtSize(fontSize, { descender: false });
  var x = alignment === TextAlignment.Left ? bounds.x : alignment === TextAlignment.Center ? bounds.x + bounds.width / 2 - width / 2 : alignment === TextAlignment.Right ? bounds.x + bounds.width - width : bounds.x;
  var y = bounds.y + (bounds.height / 2 - height / 2);
  return {
    fontSize,
    line: { text: line, encoded, width, height, x, y },
    bounds: { x, y, width, height }
  };
};

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/api/form/appearances.js
var normalizeAppearance = function(appearance) {
  if ("normal" in appearance)
    return appearance;
  return { normal: appearance };
};
var tfRegex2 = /\/([^\0\t\n\f\r\ ]+)[\0\t\n\f\r\ ]+(\d*\.\d+|\d+)[\0\t\n\f\r\ ]+Tf/;
var getDefaultFontSize = function(field) {
  var _a, _b;
  var da = (_a = field.getDefaultAppearance()) !== null && _a !== void 0 ? _a : "";
  var daMatch = (_b = findLastMatch(da, tfRegex2).match) !== null && _b !== void 0 ? _b : [];
  var defaultFontSize = Number(daMatch[2]);
  return isFinite(defaultFontSize) ? defaultFontSize : void 0;
};
var colorRegex = /(\d*\.\d+|\d+)[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]+(g|rg|k)/;
var getDefaultColor = function(field) {
  var _a;
  var da = (_a = field.getDefaultAppearance()) !== null && _a !== void 0 ? _a : "";
  var daMatch = findLastMatch(da, colorRegex).match;
  var _b = daMatch !== null && daMatch !== void 0 ? daMatch : [], c1 = _b[1], c2 = _b[2], c3 = _b[3], c4 = _b[4], colorSpace = _b[5];
  if (colorSpace === "g" && c1) {
    return grayscale(Number(c1));
  }
  if (colorSpace === "rg" && c1 && c2 && c3) {
    return rgb(Number(c1), Number(c2), Number(c3));
  }
  if (colorSpace === "k" && c1 && c2 && c3 && c4) {
    return cmyk(Number(c1), Number(c2), Number(c3), Number(c4));
  }
  return void 0;
};
var updateDefaultAppearance = function(field, color, font, fontSize) {
  var _a;
  if (fontSize === void 0) {
    fontSize = 0;
  }
  var da = [
    setFillingColor(color).toString(),
    setFontAndSize((_a = font === null || font === void 0 ? void 0 : font.name) !== null && _a !== void 0 ? _a : "dummy__noop", fontSize).toString()
  ].join("\n");
  field.setDefaultAppearance(da);
};
var defaultCheckBoxAppearanceProvider = function(checkBox, widget) {
  var _a, _b, _c;
  var widgetColor = getDefaultColor(widget);
  var fieldColor = getDefaultColor(checkBox.acroField);
  var rectangle = widget.getRectangle();
  var ap = widget.getAppearanceCharacteristics();
  var bs = widget.getBorderStyle();
  var borderWidth = (_a = bs === null || bs === void 0 ? void 0 : bs.getWidth()) !== null && _a !== void 0 ? _a : 0;
  var rotation = reduceRotation(ap === null || ap === void 0 ? void 0 : ap.getRotation());
  var _d = adjustDimsForRotation(rectangle, rotation), width = _d.width, height = _d.height;
  var rotate = rotateInPlace(__assign(__assign({}, rectangle), { rotation }));
  var black = rgb(0, 0, 0);
  var borderColor = (_b = componentsToColor(ap === null || ap === void 0 ? void 0 : ap.getBorderColor())) !== null && _b !== void 0 ? _b : black;
  var normalBackgroundColor = componentsToColor(ap === null || ap === void 0 ? void 0 : ap.getBackgroundColor());
  var downBackgroundColor = componentsToColor(ap === null || ap === void 0 ? void 0 : ap.getBackgroundColor(), 0.8);
  var textColor = (_c = widgetColor !== null && widgetColor !== void 0 ? widgetColor : fieldColor) !== null && _c !== void 0 ? _c : black;
  if (widgetColor) {
    updateDefaultAppearance(widget, textColor);
  } else {
    updateDefaultAppearance(checkBox.acroField, textColor);
  }
  var options = {
    x: 0 + borderWidth / 2,
    y: 0 + borderWidth / 2,
    width: width - borderWidth,
    height: height - borderWidth,
    thickness: 1.5,
    borderWidth,
    borderColor,
    markColor: textColor
  };
  return {
    normal: {
      on: __spreadArrays(rotate, drawCheckBox(__assign(__assign({}, options), { color: normalBackgroundColor, filled: true }))),
      off: __spreadArrays(rotate, drawCheckBox(__assign(__assign({}, options), { color: normalBackgroundColor, filled: false })))
    },
    down: {
      on: __spreadArrays(rotate, drawCheckBox(__assign(__assign({}, options), { color: downBackgroundColor, filled: true }))),
      off: __spreadArrays(rotate, drawCheckBox(__assign(__assign({}, options), { color: downBackgroundColor, filled: false })))
    }
  };
};
var defaultRadioGroupAppearanceProvider = function(radioGroup, widget) {
  var _a, _b, _c;
  var widgetColor = getDefaultColor(widget);
  var fieldColor = getDefaultColor(radioGroup.acroField);
  var rectangle = widget.getRectangle();
  var ap = widget.getAppearanceCharacteristics();
  var bs = widget.getBorderStyle();
  var borderWidth = (_a = bs === null || bs === void 0 ? void 0 : bs.getWidth()) !== null && _a !== void 0 ? _a : 0;
  var rotation = reduceRotation(ap === null || ap === void 0 ? void 0 : ap.getRotation());
  var _d = adjustDimsForRotation(rectangle, rotation), width = _d.width, height = _d.height;
  var rotate = rotateInPlace(__assign(__assign({}, rectangle), { rotation }));
  var black = rgb(0, 0, 0);
  var borderColor = (_b = componentsToColor(ap === null || ap === void 0 ? void 0 : ap.getBorderColor())) !== null && _b !== void 0 ? _b : black;
  var normalBackgroundColor = componentsToColor(ap === null || ap === void 0 ? void 0 : ap.getBackgroundColor());
  var downBackgroundColor = componentsToColor(ap === null || ap === void 0 ? void 0 : ap.getBackgroundColor(), 0.8);
  var textColor = (_c = widgetColor !== null && widgetColor !== void 0 ? widgetColor : fieldColor) !== null && _c !== void 0 ? _c : black;
  if (widgetColor) {
    updateDefaultAppearance(widget, textColor);
  } else {
    updateDefaultAppearance(radioGroup.acroField, textColor);
  }
  var options = {
    x: width / 2,
    y: height / 2,
    width: width - borderWidth,
    height: height - borderWidth,
    borderWidth,
    borderColor,
    dotColor: textColor
  };
  return {
    normal: {
      on: __spreadArrays(rotate, drawRadioButton(__assign(__assign({}, options), { color: normalBackgroundColor, filled: true }))),
      off: __spreadArrays(rotate, drawRadioButton(__assign(__assign({}, options), { color: normalBackgroundColor, filled: false })))
    },
    down: {
      on: __spreadArrays(rotate, drawRadioButton(__assign(__assign({}, options), { color: downBackgroundColor, filled: true }))),
      off: __spreadArrays(rotate, drawRadioButton(__assign(__assign({}, options), { color: downBackgroundColor, filled: false })))
    }
  };
};
var defaultButtonAppearanceProvider = function(button, widget, font) {
  var _a, _b, _c, _d, _e;
  var widgetColor = getDefaultColor(widget);
  var fieldColor = getDefaultColor(button.acroField);
  var widgetFontSize = getDefaultFontSize(widget);
  var fieldFontSize = getDefaultFontSize(button.acroField);
  var rectangle = widget.getRectangle();
  var ap = widget.getAppearanceCharacteristics();
  var bs = widget.getBorderStyle();
  var captions = ap === null || ap === void 0 ? void 0 : ap.getCaptions();
  var normalText = (_a = captions === null || captions === void 0 ? void 0 : captions.normal) !== null && _a !== void 0 ? _a : "";
  var downText = (_c = (_b = captions === null || captions === void 0 ? void 0 : captions.down) !== null && _b !== void 0 ? _b : normalText) !== null && _c !== void 0 ? _c : "";
  var borderWidth = (_d = bs === null || bs === void 0 ? void 0 : bs.getWidth()) !== null && _d !== void 0 ? _d : 0;
  var rotation = reduceRotation(ap === null || ap === void 0 ? void 0 : ap.getRotation());
  var _f = adjustDimsForRotation(rectangle, rotation), width = _f.width, height = _f.height;
  var rotate = rotateInPlace(__assign(__assign({}, rectangle), { rotation }));
  var black = rgb(0, 0, 0);
  var borderColor = componentsToColor(ap === null || ap === void 0 ? void 0 : ap.getBorderColor());
  var normalBackgroundColor = componentsToColor(ap === null || ap === void 0 ? void 0 : ap.getBackgroundColor());
  var downBackgroundColor = componentsToColor(ap === null || ap === void 0 ? void 0 : ap.getBackgroundColor(), 0.8);
  var bounds = {
    x: borderWidth,
    y: borderWidth,
    width: width - borderWidth * 2,
    height: height - borderWidth * 2
  };
  var normalLayout = layoutSinglelineText(normalText, {
    alignment: TextAlignment.Center,
    fontSize: widgetFontSize !== null && widgetFontSize !== void 0 ? widgetFontSize : fieldFontSize,
    font,
    bounds
  });
  var downLayout = layoutSinglelineText(downText, {
    alignment: TextAlignment.Center,
    fontSize: widgetFontSize !== null && widgetFontSize !== void 0 ? widgetFontSize : fieldFontSize,
    font,
    bounds
  });
  var fontSize = Math.min(normalLayout.fontSize, downLayout.fontSize);
  var textColor = (_e = widgetColor !== null && widgetColor !== void 0 ? widgetColor : fieldColor) !== null && _e !== void 0 ? _e : black;
  if (widgetColor || widgetFontSize !== void 0) {
    updateDefaultAppearance(widget, textColor, font, fontSize);
  } else {
    updateDefaultAppearance(button.acroField, textColor, font, fontSize);
  }
  var options = {
    x: 0 + borderWidth / 2,
    y: 0 + borderWidth / 2,
    width: width - borderWidth,
    height: height - borderWidth,
    borderWidth,
    borderColor,
    textColor,
    font: font.name,
    fontSize
  };
  return {
    normal: __spreadArrays(rotate, drawButton(__assign(__assign({}, options), { color: normalBackgroundColor, textLines: [normalLayout.line] }))),
    down: __spreadArrays(rotate, drawButton(__assign(__assign({}, options), { color: downBackgroundColor, textLines: [downLayout.line] })))
  };
};
var defaultTextFieldAppearanceProvider = function(textField, widget, font) {
  var _a, _b, _c, _d;
  var widgetColor = getDefaultColor(widget);
  var fieldColor = getDefaultColor(textField.acroField);
  var widgetFontSize = getDefaultFontSize(widget);
  var fieldFontSize = getDefaultFontSize(textField.acroField);
  var rectangle = widget.getRectangle();
  var ap = widget.getAppearanceCharacteristics();
  var bs = widget.getBorderStyle();
  var text = (_a = textField.getText()) !== null && _a !== void 0 ? _a : "";
  var borderWidth = (_b = bs === null || bs === void 0 ? void 0 : bs.getWidth()) !== null && _b !== void 0 ? _b : 0;
  var rotation = reduceRotation(ap === null || ap === void 0 ? void 0 : ap.getRotation());
  var _e = adjustDimsForRotation(rectangle, rotation), width = _e.width, height = _e.height;
  var rotate = rotateInPlace(__assign(__assign({}, rectangle), { rotation }));
  var black = rgb(0, 0, 0);
  var borderColor = componentsToColor(ap === null || ap === void 0 ? void 0 : ap.getBorderColor());
  var normalBackgroundColor = componentsToColor(ap === null || ap === void 0 ? void 0 : ap.getBackgroundColor());
  var textLines;
  var fontSize;
  var padding = textField.isCombed() ? 0 : 1;
  var bounds = {
    x: borderWidth + padding,
    y: borderWidth + padding,
    width: width - (borderWidth + padding) * 2,
    height: height - (borderWidth + padding) * 2
  };
  if (textField.isMultiline()) {
    var layout = layoutMultilineText(text, {
      alignment: textField.getAlignment(),
      fontSize: widgetFontSize !== null && widgetFontSize !== void 0 ? widgetFontSize : fieldFontSize,
      font,
      bounds
    });
    textLines = layout.lines;
    fontSize = layout.fontSize;
  } else if (textField.isCombed()) {
    var layout = layoutCombedText(text, {
      fontSize: widgetFontSize !== null && widgetFontSize !== void 0 ? widgetFontSize : fieldFontSize,
      font,
      bounds,
      cellCount: (_c = textField.getMaxLength()) !== null && _c !== void 0 ? _c : 0
    });
    textLines = layout.cells;
    fontSize = layout.fontSize;
  } else {
    var layout = layoutSinglelineText(text, {
      alignment: textField.getAlignment(),
      fontSize: widgetFontSize !== null && widgetFontSize !== void 0 ? widgetFontSize : fieldFontSize,
      font,
      bounds
    });
    textLines = [layout.line];
    fontSize = layout.fontSize;
  }
  var textColor = (_d = widgetColor !== null && widgetColor !== void 0 ? widgetColor : fieldColor) !== null && _d !== void 0 ? _d : black;
  if (widgetColor || widgetFontSize !== void 0) {
    updateDefaultAppearance(widget, textColor, font, fontSize);
  } else {
    updateDefaultAppearance(textField.acroField, textColor, font, fontSize);
  }
  var options = {
    x: 0 + borderWidth / 2,
    y: 0 + borderWidth / 2,
    width: width - borderWidth,
    height: height - borderWidth,
    borderWidth: borderWidth !== null && borderWidth !== void 0 ? borderWidth : 0,
    borderColor,
    textColor,
    font: font.name,
    fontSize,
    color: normalBackgroundColor,
    textLines,
    padding
  };
  return __spreadArrays(rotate, drawTextField(options));
};
var defaultDropdownAppearanceProvider = function(dropdown, widget, font) {
  var _a, _b, _c;
  var widgetColor = getDefaultColor(widget);
  var fieldColor = getDefaultColor(dropdown.acroField);
  var widgetFontSize = getDefaultFontSize(widget);
  var fieldFontSize = getDefaultFontSize(dropdown.acroField);
  var rectangle = widget.getRectangle();
  var ap = widget.getAppearanceCharacteristics();
  var bs = widget.getBorderStyle();
  var text = (_a = dropdown.getSelected()[0]) !== null && _a !== void 0 ? _a : "";
  var borderWidth = (_b = bs === null || bs === void 0 ? void 0 : bs.getWidth()) !== null && _b !== void 0 ? _b : 0;
  var rotation = reduceRotation(ap === null || ap === void 0 ? void 0 : ap.getRotation());
  var _d = adjustDimsForRotation(rectangle, rotation), width = _d.width, height = _d.height;
  var rotate = rotateInPlace(__assign(__assign({}, rectangle), { rotation }));
  var black = rgb(0, 0, 0);
  var borderColor = componentsToColor(ap === null || ap === void 0 ? void 0 : ap.getBorderColor());
  var normalBackgroundColor = componentsToColor(ap === null || ap === void 0 ? void 0 : ap.getBackgroundColor());
  var padding = 1;
  var bounds = {
    x: borderWidth + padding,
    y: borderWidth + padding,
    width: width - (borderWidth + padding) * 2,
    height: height - (borderWidth + padding) * 2
  };
  var _e = layoutSinglelineText(text, {
    alignment: TextAlignment.Left,
    fontSize: widgetFontSize !== null && widgetFontSize !== void 0 ? widgetFontSize : fieldFontSize,
    font,
    bounds
  }), line = _e.line, fontSize = _e.fontSize;
  var textColor = (_c = widgetColor !== null && widgetColor !== void 0 ? widgetColor : fieldColor) !== null && _c !== void 0 ? _c : black;
  if (widgetColor || widgetFontSize !== void 0) {
    updateDefaultAppearance(widget, textColor, font, fontSize);
  } else {
    updateDefaultAppearance(dropdown.acroField, textColor, font, fontSize);
  }
  var options = {
    x: 0 + borderWidth / 2,
    y: 0 + borderWidth / 2,
    width: width - borderWidth,
    height: height - borderWidth,
    borderWidth: borderWidth !== null && borderWidth !== void 0 ? borderWidth : 0,
    borderColor,
    textColor,
    font: font.name,
    fontSize,
    color: normalBackgroundColor,
    textLines: [line],
    padding
  };
  return __spreadArrays(rotate, drawTextField(options));
};
var defaultOptionListAppearanceProvider = function(optionList, widget, font) {
  var _a, _b;
  var widgetColor = getDefaultColor(widget);
  var fieldColor = getDefaultColor(optionList.acroField);
  var widgetFontSize = getDefaultFontSize(widget);
  var fieldFontSize = getDefaultFontSize(optionList.acroField);
  var rectangle = widget.getRectangle();
  var ap = widget.getAppearanceCharacteristics();
  var bs = widget.getBorderStyle();
  var borderWidth = (_a = bs === null || bs === void 0 ? void 0 : bs.getWidth()) !== null && _a !== void 0 ? _a : 0;
  var rotation = reduceRotation(ap === null || ap === void 0 ? void 0 : ap.getRotation());
  var _c = adjustDimsForRotation(rectangle, rotation), width = _c.width, height = _c.height;
  var rotate = rotateInPlace(__assign(__assign({}, rectangle), { rotation }));
  var black = rgb(0, 0, 0);
  var borderColor = componentsToColor(ap === null || ap === void 0 ? void 0 : ap.getBorderColor());
  var normalBackgroundColor = componentsToColor(ap === null || ap === void 0 ? void 0 : ap.getBackgroundColor());
  var options = optionList.getOptions();
  var selected = optionList.getSelected();
  if (optionList.isSorted())
    options.sort();
  var text = "";
  for (var idx = 0, len = options.length; idx < len; idx++) {
    text += options[idx];
    if (idx < len - 1)
      text += "\n";
  }
  var padding = 1;
  var bounds = {
    x: borderWidth + padding,
    y: borderWidth + padding,
    width: width - (borderWidth + padding) * 2,
    height: height - (borderWidth + padding) * 2
  };
  var _d = layoutMultilineText(text, {
    alignment: TextAlignment.Left,
    fontSize: widgetFontSize !== null && widgetFontSize !== void 0 ? widgetFontSize : fieldFontSize,
    font,
    bounds
  }), lines = _d.lines, fontSize = _d.fontSize, lineHeight = _d.lineHeight;
  var selectedLines = [];
  for (var idx = 0, len = lines.length; idx < len; idx++) {
    var line = lines[idx];
    if (selected.includes(line.text))
      selectedLines.push(idx);
  }
  var blue = rgb(153 / 255, 193 / 255, 218 / 255);
  var textColor = (_b = widgetColor !== null && widgetColor !== void 0 ? widgetColor : fieldColor) !== null && _b !== void 0 ? _b : black;
  if (widgetColor || widgetFontSize !== void 0) {
    updateDefaultAppearance(widget, textColor, font, fontSize);
  } else {
    updateDefaultAppearance(optionList.acroField, textColor, font, fontSize);
  }
  return __spreadArrays(rotate, drawOptionList({
    x: 0 + borderWidth / 2,
    y: 0 + borderWidth / 2,
    width: width - borderWidth,
    height: height - borderWidth,
    borderWidth: borderWidth !== null && borderWidth !== void 0 ? borderWidth : 0,
    borderColor,
    textColor,
    font: font.name,
    fontSize,
    color: normalBackgroundColor,
    textLines: lines,
    lineHeight,
    selectedColor: blue,
    selectedLines,
    padding
  }));
};

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/api/PDFEmbeddedPage.js
var PDFEmbeddedPage = (
  /** @class */
  function() {
    function PDFEmbeddedPage2(ref, doc, embedder) {
      this.alreadyEmbedded = false;
      assertIs(ref, "ref", [[PDFRef_default, "PDFRef"]]);
      assertIs(doc, "doc", [[PDFDocument_default, "PDFDocument"]]);
      assertIs(embedder, "embedder", [[PDFPageEmbedder_default, "PDFPageEmbedder"]]);
      this.ref = ref;
      this.doc = doc;
      this.width = embedder.width;
      this.height = embedder.height;
      this.embedder = embedder;
    }
    PDFEmbeddedPage2.prototype.scale = function(factor) {
      assertIs(factor, "factor", ["number"]);
      return { width: this.width * factor, height: this.height * factor };
    };
    PDFEmbeddedPage2.prototype.size = function() {
      return this.scale(1);
    };
    PDFEmbeddedPage2.prototype.embed = function() {
      return __awaiter(this, void 0, void 0, function() {
        return __generator(this, function(_a) {
          switch (_a.label) {
            case 0:
              if (!!this.alreadyEmbedded) return [3, 2];
              return [4, this.embedder.embedIntoContext(this.doc.context, this.ref)];
            case 1:
              _a.sent();
              this.alreadyEmbedded = true;
              _a.label = 2;
            case 2:
              return [
                2
                /*return*/
              ];
          }
        });
      });
    };
    PDFEmbeddedPage2.of = function(ref, doc, embedder) {
      return new PDFEmbeddedPage2(ref, doc, embedder);
    };
    return PDFEmbeddedPage2;
  }()
);
var PDFEmbeddedPage_default = PDFEmbeddedPage;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/api/PDFFont.js
var PDFFont = (
  /** @class */
  function() {
    function PDFFont2(ref, doc, embedder) {
      this.modified = true;
      assertIs(ref, "ref", [[PDFRef_default, "PDFRef"]]);
      assertIs(doc, "doc", [[PDFDocument_default, "PDFDocument"]]);
      assertIs(embedder, "embedder", [
        [CustomFontEmbedder_default, "CustomFontEmbedder"],
        [StandardFontEmbedder_default, "StandardFontEmbedder"]
      ]);
      this.ref = ref;
      this.doc = doc;
      this.name = embedder.fontName;
      this.embedder = embedder;
    }
    PDFFont2.prototype.encodeText = function(text) {
      assertIs(text, "text", ["string"]);
      this.modified = true;
      return this.embedder.encodeText(text);
    };
    PDFFont2.prototype.widthOfTextAtSize = function(text, size) {
      assertIs(text, "text", ["string"]);
      assertIs(size, "size", ["number"]);
      return this.embedder.widthOfTextAtSize(text, size);
    };
    PDFFont2.prototype.heightAtSize = function(size, options) {
      var _a;
      assertIs(size, "size", ["number"]);
      assertOrUndefined(options === null || options === void 0 ? void 0 : options.descender, "options.descender", ["boolean"]);
      return this.embedder.heightOfFontAtSize(size, {
        descender: (_a = options === null || options === void 0 ? void 0 : options.descender) !== null && _a !== void 0 ? _a : true
      });
    };
    PDFFont2.prototype.sizeAtHeight = function(height) {
      assertIs(height, "height", ["number"]);
      return this.embedder.sizeOfFontAtHeight(height);
    };
    PDFFont2.prototype.getCharacterSet = function() {
      if (this.embedder instanceof StandardFontEmbedder_default) {
        return this.embedder.encoding.supportedCodePoints;
      } else {
        return this.embedder.font.characterSet;
      }
    };
    PDFFont2.prototype.embed = function() {
      return __awaiter(this, void 0, void 0, function() {
        return __generator(this, function(_a) {
          switch (_a.label) {
            case 0:
              if (!this.modified) return [3, 2];
              return [4, this.embedder.embedIntoContext(this.doc.context, this.ref)];
            case 1:
              _a.sent();
              this.modified = false;
              _a.label = 2;
            case 2:
              return [
                2
                /*return*/
              ];
          }
        });
      });
    };
    PDFFont2.of = function(ref, doc, embedder) {
      return new PDFFont2(ref, doc, embedder);
    };
    return PDFFont2;
  }()
);
var PDFFont_default = PDFFont;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/api/PDFImage.js
var PDFImage = (
  /** @class */
  function() {
    function PDFImage2(ref, doc, embedder) {
      assertIs(ref, "ref", [[PDFRef_default, "PDFRef"]]);
      assertIs(doc, "doc", [[PDFDocument_default, "PDFDocument"]]);
      assertIs(embedder, "embedder", [
        [JpegEmbedder_default, "JpegEmbedder"],
        [PngEmbedder_default, "PngEmbedder"]
      ]);
      this.ref = ref;
      this.doc = doc;
      this.width = embedder.width;
      this.height = embedder.height;
      this.embedder = embedder;
    }
    PDFImage2.prototype.scale = function(factor) {
      assertIs(factor, "factor", ["number"]);
      return { width: this.width * factor, height: this.height * factor };
    };
    PDFImage2.prototype.scaleToFit = function(width, height) {
      assertIs(width, "width", ["number"]);
      assertIs(height, "height", ["number"]);
      var imgWidthScale = width / this.width;
      var imgHeightScale = height / this.height;
      var scale2 = Math.min(imgWidthScale, imgHeightScale);
      return this.scale(scale2);
    };
    PDFImage2.prototype.size = function() {
      return this.scale(1);
    };
    PDFImage2.prototype.embed = function() {
      return __awaiter(this, void 0, void 0, function() {
        var _a, doc, ref;
        return __generator(this, function(_b) {
          switch (_b.label) {
            case 0:
              if (!this.embedder)
                return [
                  2
                  /*return*/
                ];
              if (!this.embedTask) {
                _a = this, doc = _a.doc, ref = _a.ref;
                this.embedTask = this.embedder.embedIntoContext(doc.context, ref);
              }
              return [4, this.embedTask];
            case 1:
              _b.sent();
              this.embedder = void 0;
              return [
                2
                /*return*/
              ];
          }
        });
      });
    };
    PDFImage2.of = function(ref, doc, embedder) {
      return new PDFImage2(ref, doc, embedder);
    };
    return PDFImage2;
  }()
);
var PDFImage_default = PDFImage;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/api/image/alignment.js
var ImageAlignment;
(function(ImageAlignment2) {
  ImageAlignment2[ImageAlignment2["Left"] = 0] = "Left";
  ImageAlignment2[ImageAlignment2["Center"] = 1] = "Center";
  ImageAlignment2[ImageAlignment2["Right"] = 2] = "Right";
})(ImageAlignment || (ImageAlignment = {}));

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/api/form/PDFField.js
var assertFieldAppearanceOptions = function(options) {
  assertOrUndefined(options === null || options === void 0 ? void 0 : options.x, "options.x", ["number"]);
  assertOrUndefined(options === null || options === void 0 ? void 0 : options.y, "options.y", ["number"]);
  assertOrUndefined(options === null || options === void 0 ? void 0 : options.width, "options.width", ["number"]);
  assertOrUndefined(options === null || options === void 0 ? void 0 : options.height, "options.height", ["number"]);
  assertOrUndefined(options === null || options === void 0 ? void 0 : options.textColor, "options.textColor", [
    [Object, "Color"]
  ]);
  assertOrUndefined(options === null || options === void 0 ? void 0 : options.backgroundColor, "options.backgroundColor", [
    [Object, "Color"]
  ]);
  assertOrUndefined(options === null || options === void 0 ? void 0 : options.borderColor, "options.borderColor", [
    [Object, "Color"]
  ]);
  assertOrUndefined(options === null || options === void 0 ? void 0 : options.borderWidth, "options.borderWidth", ["number"]);
  assertOrUndefined(options === null || options === void 0 ? void 0 : options.rotate, "options.rotate", [[Object, "Rotation"]]);
};
var PDFField = (
  /** @class */
  function() {
    function PDFField2(acroField, ref, doc) {
      assertIs(acroField, "acroField", [[PDFAcroTerminal_default, "PDFAcroTerminal"]]);
      assertIs(ref, "ref", [[PDFRef_default, "PDFRef"]]);
      assertIs(doc, "doc", [[PDFDocument_default, "PDFDocument"]]);
      this.acroField = acroField;
      this.ref = ref;
      this.doc = doc;
    }
    PDFField2.prototype.getName = function() {
      var _a;
      return (_a = this.acroField.getFullyQualifiedName()) !== null && _a !== void 0 ? _a : "";
    };
    PDFField2.prototype.isReadOnly = function() {
      return this.acroField.hasFlag(AcroFieldFlags.ReadOnly);
    };
    PDFField2.prototype.enableReadOnly = function() {
      this.acroField.setFlagTo(AcroFieldFlags.ReadOnly, true);
    };
    PDFField2.prototype.disableReadOnly = function() {
      this.acroField.setFlagTo(AcroFieldFlags.ReadOnly, false);
    };
    PDFField2.prototype.isRequired = function() {
      return this.acroField.hasFlag(AcroFieldFlags.Required);
    };
    PDFField2.prototype.enableRequired = function() {
      this.acroField.setFlagTo(AcroFieldFlags.Required, true);
    };
    PDFField2.prototype.disableRequired = function() {
      this.acroField.setFlagTo(AcroFieldFlags.Required, false);
    };
    PDFField2.prototype.isExported = function() {
      return !this.acroField.hasFlag(AcroFieldFlags.NoExport);
    };
    PDFField2.prototype.enableExporting = function() {
      this.acroField.setFlagTo(AcroFieldFlags.NoExport, false);
    };
    PDFField2.prototype.disableExporting = function() {
      this.acroField.setFlagTo(AcroFieldFlags.NoExport, true);
    };
    PDFField2.prototype.needsAppearancesUpdate = function() {
      throw new MethodNotImplementedError(this.constructor.name, "needsAppearancesUpdate");
    };
    PDFField2.prototype.defaultUpdateAppearances = function(_font) {
      throw new MethodNotImplementedError(this.constructor.name, "defaultUpdateAppearances");
    };
    PDFField2.prototype.markAsDirty = function() {
      this.doc.getForm().markFieldAsDirty(this.ref);
    };
    PDFField2.prototype.markAsClean = function() {
      this.doc.getForm().markFieldAsClean(this.ref);
    };
    PDFField2.prototype.isDirty = function() {
      return this.doc.getForm().fieldIsDirty(this.ref);
    };
    PDFField2.prototype.createWidget = function(options) {
      var _a;
      var textColor = options.textColor;
      var backgroundColor = options.backgroundColor;
      var borderColor = options.borderColor;
      var borderWidth = options.borderWidth;
      var degreesAngle = toDegrees(options.rotate);
      var caption = options.caption;
      var x = options.x;
      var y = options.y;
      var width = options.width + borderWidth;
      var height = options.height + borderWidth;
      var hidden = Boolean(options.hidden);
      var pageRef = options.page;
      assertMultiple(degreesAngle, "degreesAngle", 90);
      var widget = PDFWidgetAnnotation_default.create(this.doc.context, this.ref);
      var rect = rotateRectangle({ x, y, width, height }, borderWidth, degreesAngle);
      widget.setRectangle(rect);
      if (pageRef)
        widget.setP(pageRef);
      var ac = widget.getOrCreateAppearanceCharacteristics();
      if (backgroundColor) {
        ac.setBackgroundColor(colorToComponents(backgroundColor));
      }
      ac.setRotation(degreesAngle);
      if (caption)
        ac.setCaptions({ normal: caption });
      if (borderColor)
        ac.setBorderColor(colorToComponents(borderColor));
      var bs = widget.getOrCreateBorderStyle();
      if (borderWidth !== void 0)
        bs.setWidth(borderWidth);
      widget.setFlagTo(AnnotationFlags.Print, true);
      widget.setFlagTo(AnnotationFlags.Hidden, hidden);
      widget.setFlagTo(AnnotationFlags.Invisible, false);
      if (textColor) {
        var da = (_a = this.acroField.getDefaultAppearance()) !== null && _a !== void 0 ? _a : "";
        var newDa = da + "\n" + setFillingColor(textColor).toString();
        this.acroField.setDefaultAppearance(newDa);
      }
      return widget;
    };
    PDFField2.prototype.updateWidgetAppearanceWithFont = function(widget, font, _a) {
      var normal = _a.normal, rollover = _a.rollover, down = _a.down;
      this.updateWidgetAppearances(widget, {
        normal: this.createAppearanceStream(widget, normal, font),
        rollover: rollover && this.createAppearanceStream(widget, rollover, font),
        down: down && this.createAppearanceStream(widget, down, font)
      });
    };
    PDFField2.prototype.updateOnOffWidgetAppearance = function(widget, onValue, _a) {
      var normal = _a.normal, rollover = _a.rollover, down = _a.down;
      this.updateWidgetAppearances(widget, {
        normal: this.createAppearanceDict(widget, normal, onValue),
        rollover: rollover && this.createAppearanceDict(widget, rollover, onValue),
        down: down && this.createAppearanceDict(widget, down, onValue)
      });
    };
    PDFField2.prototype.updateWidgetAppearances = function(widget, _a) {
      var normal = _a.normal, rollover = _a.rollover, down = _a.down;
      widget.setNormalAppearance(normal);
      if (rollover) {
        widget.setRolloverAppearance(rollover);
      } else {
        widget.removeRolloverAppearance();
      }
      if (down) {
        widget.setDownAppearance(down);
      } else {
        widget.removeDownAppearance();
      }
    };
    PDFField2.prototype.createAppearanceStream = function(widget, appearance, font) {
      var _a;
      var context = this.acroField.dict.context;
      var _b = widget.getRectangle(), width = _b.width, height = _b.height;
      var Resources = font && { Font: (_a = {}, _a[font.name] = font.ref, _a) };
      var stream2 = context.formXObject(appearance, {
        Resources,
        BBox: context.obj([0, 0, width, height]),
        Matrix: context.obj([1, 0, 0, 1, 0, 0])
      });
      var streamRef = context.register(stream2);
      return streamRef;
    };
    PDFField2.prototype.createImageAppearanceStream = function(widget, image, alignment) {
      var _a;
      var _b;
      var context = this.acroField.dict.context;
      var rectangle = widget.getRectangle();
      var ap = widget.getAppearanceCharacteristics();
      var bs = widget.getBorderStyle();
      var borderWidth = (_b = bs === null || bs === void 0 ? void 0 : bs.getWidth()) !== null && _b !== void 0 ? _b : 0;
      var rotation = reduceRotation(ap === null || ap === void 0 ? void 0 : ap.getRotation());
      var rotate = rotateInPlace(__assign(__assign({}, rectangle), { rotation }));
      var adj = adjustDimsForRotation(rectangle, rotation);
      var imageDims = image.scaleToFit(adj.width - borderWidth * 2, adj.height - borderWidth * 2);
      var options = {
        x: borderWidth,
        y: borderWidth,
        width: imageDims.width,
        height: imageDims.height,
        //
        rotate: degrees(0),
        xSkew: degrees(0),
        ySkew: degrees(0)
      };
      if (alignment === ImageAlignment.Center) {
        options.x += (adj.width - borderWidth * 2) / 2 - imageDims.width / 2;
        options.y += (adj.height - borderWidth * 2) / 2 - imageDims.height / 2;
      } else if (alignment === ImageAlignment.Right) {
        options.x = adj.width - borderWidth - imageDims.width;
        options.y = adj.height - borderWidth - imageDims.height;
      }
      var imageName = this.doc.context.addRandomSuffix("Image", 10);
      var appearance = __spreadArrays(rotate, drawImage(imageName, options));
      var Resources = { XObject: (_a = {}, _a[imageName] = image.ref, _a) };
      var stream2 = context.formXObject(appearance, {
        Resources,
        BBox: context.obj([0, 0, rectangle.width, rectangle.height]),
        Matrix: context.obj([1, 0, 0, 1, 0, 0])
      });
      return context.register(stream2);
    };
    PDFField2.prototype.createAppearanceDict = function(widget, appearance, onValue) {
      var context = this.acroField.dict.context;
      var onStreamRef = this.createAppearanceStream(widget, appearance.on);
      var offStreamRef = this.createAppearanceStream(widget, appearance.off);
      var appearanceDict = context.obj({});
      appearanceDict.set(onValue, onStreamRef);
      appearanceDict.set(PDFName_default.of("Off"), offStreamRef);
      return appearanceDict;
    };
    return PDFField2;
  }()
);
var PDFField_default = PDFField;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/api/form/PDFCheckBox.js
var PDFCheckBox = (
  /** @class */
  function(_super) {
    __extends(PDFCheckBox2, _super);
    function PDFCheckBox2(acroCheckBox, ref, doc) {
      var _this = _super.call(this, acroCheckBox, ref, doc) || this;
      assertIs(acroCheckBox, "acroCheckBox", [
        [PDFAcroCheckBox_default, "PDFAcroCheckBox"]
      ]);
      _this.acroField = acroCheckBox;
      return _this;
    }
    PDFCheckBox2.prototype.check = function() {
      var _a;
      var onValue = (_a = this.acroField.getOnValue()) !== null && _a !== void 0 ? _a : PDFName_default.of("Yes");
      this.markAsDirty();
      this.acroField.setValue(onValue);
    };
    PDFCheckBox2.prototype.uncheck = function() {
      this.markAsDirty();
      this.acroField.setValue(PDFName_default.of("Off"));
    };
    PDFCheckBox2.prototype.isChecked = function() {
      var onValue = this.acroField.getOnValue();
      return !!onValue && onValue === this.acroField.getValue();
    };
    PDFCheckBox2.prototype.addToPage = function(page, options) {
      var _a, _b, _c, _d, _e, _f;
      assertIs(page, "page", [[PDFPage_default, "PDFPage"]]);
      assertFieldAppearanceOptions(options);
      if (!options)
        options = {};
      if (!("textColor" in options))
        options.textColor = rgb(0, 0, 0);
      if (!("backgroundColor" in options))
        options.backgroundColor = rgb(1, 1, 1);
      if (!("borderColor" in options))
        options.borderColor = rgb(0, 0, 0);
      if (!("borderWidth" in options))
        options.borderWidth = 1;
      var widget = this.createWidget({
        x: (_a = options.x) !== null && _a !== void 0 ? _a : 0,
        y: (_b = options.y) !== null && _b !== void 0 ? _b : 0,
        width: (_c = options.width) !== null && _c !== void 0 ? _c : 50,
        height: (_d = options.height) !== null && _d !== void 0 ? _d : 50,
        textColor: options.textColor,
        backgroundColor: options.backgroundColor,
        borderColor: options.borderColor,
        borderWidth: (_e = options.borderWidth) !== null && _e !== void 0 ? _e : 0,
        rotate: (_f = options.rotate) !== null && _f !== void 0 ? _f : degrees(0),
        hidden: options.hidden,
        page: page.ref
      });
      var widgetRef = this.doc.context.register(widget.dict);
      this.acroField.addWidget(widgetRef);
      widget.setAppearanceState(PDFName_default.of("Off"));
      this.updateWidgetAppearance(widget, PDFName_default.of("Yes"));
      page.node.addAnnot(widgetRef);
    };
    PDFCheckBox2.prototype.needsAppearancesUpdate = function() {
      var _a;
      var widgets = this.acroField.getWidgets();
      for (var idx = 0, len = widgets.length; idx < len; idx++) {
        var widget = widgets[idx];
        var state = widget.getAppearanceState();
        var normal = (_a = widget.getAppearances()) === null || _a === void 0 ? void 0 : _a.normal;
        if (!(normal instanceof PDFDict_default))
          return true;
        if (state && !normal.has(state))
          return true;
      }
      return false;
    };
    PDFCheckBox2.prototype.defaultUpdateAppearances = function() {
      this.updateAppearances();
    };
    PDFCheckBox2.prototype.updateAppearances = function(provider) {
      var _a;
      assertOrUndefined(provider, "provider", [Function]);
      var widgets = this.acroField.getWidgets();
      for (var idx = 0, len = widgets.length; idx < len; idx++) {
        var widget = widgets[idx];
        var onValue = (_a = widget.getOnValue()) !== null && _a !== void 0 ? _a : PDFName_default.of("Yes");
        if (!onValue)
          continue;
        this.updateWidgetAppearance(widget, onValue, provider);
      }
      this.markAsClean();
    };
    PDFCheckBox2.prototype.updateWidgetAppearance = function(widget, onValue, provider) {
      var apProvider = provider !== null && provider !== void 0 ? provider : defaultCheckBoxAppearanceProvider;
      var appearances = normalizeAppearance(apProvider(this, widget));
      this.updateOnOffWidgetAppearance(widget, onValue, appearances);
    };
    PDFCheckBox2.of = function(acroCheckBox, ref, doc) {
      return new PDFCheckBox2(acroCheckBox, ref, doc);
    };
    return PDFCheckBox2;
  }(PDFField_default)
);
var PDFCheckBox_default = PDFCheckBox;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/api/form/PDFDropdown.js
var PDFDropdown = (
  /** @class */
  function(_super) {
    __extends(PDFDropdown2, _super);
    function PDFDropdown2(acroComboBox, ref, doc) {
      var _this = _super.call(this, acroComboBox, ref, doc) || this;
      assertIs(acroComboBox, "acroComboBox", [
        [PDFAcroComboBox_default, "PDFAcroComboBox"]
      ]);
      _this.acroField = acroComboBox;
      return _this;
    }
    PDFDropdown2.prototype.getOptions = function() {
      var rawOptions = this.acroField.getOptions();
      var options = new Array(rawOptions.length);
      for (var idx = 0, len = options.length; idx < len; idx++) {
        var _a = rawOptions[idx], display = _a.display, value = _a.value;
        options[idx] = (display !== null && display !== void 0 ? display : value).decodeText();
      }
      return options;
    };
    PDFDropdown2.prototype.getSelected = function() {
      var values2 = this.acroField.getValues();
      var selected = new Array(values2.length);
      for (var idx = 0, len = values2.length; idx < len; idx++) {
        selected[idx] = values2[idx].decodeText();
      }
      return selected;
    };
    PDFDropdown2.prototype.setOptions = function(options) {
      assertIs(options, "options", [Array]);
      var optionObjects = new Array(options.length);
      for (var idx = 0, len = options.length; idx < len; idx++) {
        optionObjects[idx] = { value: PDFHexString_default.fromText(options[idx]) };
      }
      this.acroField.setOptions(optionObjects);
    };
    PDFDropdown2.prototype.addOptions = function(options) {
      assertIs(options, "options", ["string", Array]);
      var optionsArr = Array.isArray(options) ? options : [options];
      var existingOptions = this.acroField.getOptions();
      var newOptions = new Array(optionsArr.length);
      for (var idx = 0, len = optionsArr.length; idx < len; idx++) {
        newOptions[idx] = { value: PDFHexString_default.fromText(optionsArr[idx]) };
      }
      this.acroField.setOptions(existingOptions.concat(newOptions));
    };
    PDFDropdown2.prototype.select = function(options, merge2) {
      if (merge2 === void 0) {
        merge2 = false;
      }
      assertIs(options, "options", ["string", Array]);
      assertIs(merge2, "merge", ["boolean"]);
      var optionsArr = Array.isArray(options) ? options : [options];
      var validOptions = this.getOptions();
      var hasCustomOption = optionsArr.find(function(option) {
        return !validOptions.includes(option);
      });
      if (hasCustomOption)
        this.enableEditing();
      this.markAsDirty();
      if (optionsArr.length > 1 || optionsArr.length === 1 && merge2) {
        this.enableMultiselect();
      }
      var values2 = new Array(optionsArr.length);
      for (var idx = 0, len = optionsArr.length; idx < len; idx++) {
        values2[idx] = PDFHexString_default.fromText(optionsArr[idx]);
      }
      if (merge2) {
        var existingValues = this.acroField.getValues();
        this.acroField.setValues(existingValues.concat(values2));
      } else {
        this.acroField.setValues(values2);
      }
    };
    PDFDropdown2.prototype.clear = function() {
      this.markAsDirty();
      this.acroField.setValues([]);
    };
    PDFDropdown2.prototype.setFontSize = function(fontSize) {
      assertPositive(fontSize, "fontSize");
      this.acroField.setFontSize(fontSize);
      this.markAsDirty();
    };
    PDFDropdown2.prototype.isEditable = function() {
      return this.acroField.hasFlag(AcroChoiceFlags.Edit);
    };
    PDFDropdown2.prototype.enableEditing = function() {
      this.acroField.setFlagTo(AcroChoiceFlags.Edit, true);
    };
    PDFDropdown2.prototype.disableEditing = function() {
      this.acroField.setFlagTo(AcroChoiceFlags.Edit, false);
    };
    PDFDropdown2.prototype.isSorted = function() {
      return this.acroField.hasFlag(AcroChoiceFlags.Sort);
    };
    PDFDropdown2.prototype.enableSorting = function() {
      this.acroField.setFlagTo(AcroChoiceFlags.Sort, true);
    };
    PDFDropdown2.prototype.disableSorting = function() {
      this.acroField.setFlagTo(AcroChoiceFlags.Sort, false);
    };
    PDFDropdown2.prototype.isMultiselect = function() {
      return this.acroField.hasFlag(AcroChoiceFlags.MultiSelect);
    };
    PDFDropdown2.prototype.enableMultiselect = function() {
      this.acroField.setFlagTo(AcroChoiceFlags.MultiSelect, true);
    };
    PDFDropdown2.prototype.disableMultiselect = function() {
      this.acroField.setFlagTo(AcroChoiceFlags.MultiSelect, false);
    };
    PDFDropdown2.prototype.isSpellChecked = function() {
      return !this.acroField.hasFlag(AcroChoiceFlags.DoNotSpellCheck);
    };
    PDFDropdown2.prototype.enableSpellChecking = function() {
      this.acroField.setFlagTo(AcroChoiceFlags.DoNotSpellCheck, false);
    };
    PDFDropdown2.prototype.disableSpellChecking = function() {
      this.acroField.setFlagTo(AcroChoiceFlags.DoNotSpellCheck, true);
    };
    PDFDropdown2.prototype.isSelectOnClick = function() {
      return this.acroField.hasFlag(AcroChoiceFlags.CommitOnSelChange);
    };
    PDFDropdown2.prototype.enableSelectOnClick = function() {
      this.acroField.setFlagTo(AcroChoiceFlags.CommitOnSelChange, true);
    };
    PDFDropdown2.prototype.disableSelectOnClick = function() {
      this.acroField.setFlagTo(AcroChoiceFlags.CommitOnSelChange, false);
    };
    PDFDropdown2.prototype.addToPage = function(page, options) {
      var _a, _b, _c, _d, _e, _f, _g;
      assertIs(page, "page", [[PDFPage_default, "PDFPage"]]);
      assertFieldAppearanceOptions(options);
      if (!options)
        options = {};
      if (!("textColor" in options))
        options.textColor = rgb(0, 0, 0);
      if (!("backgroundColor" in options))
        options.backgroundColor = rgb(1, 1, 1);
      if (!("borderColor" in options))
        options.borderColor = rgb(0, 0, 0);
      if (!("borderWidth" in options))
        options.borderWidth = 1;
      var widget = this.createWidget({
        x: (_a = options.x) !== null && _a !== void 0 ? _a : 0,
        y: (_b = options.y) !== null && _b !== void 0 ? _b : 0,
        width: (_c = options.width) !== null && _c !== void 0 ? _c : 200,
        height: (_d = options.height) !== null && _d !== void 0 ? _d : 50,
        textColor: options.textColor,
        backgroundColor: options.backgroundColor,
        borderColor: options.borderColor,
        borderWidth: (_e = options.borderWidth) !== null && _e !== void 0 ? _e : 0,
        rotate: (_f = options.rotate) !== null && _f !== void 0 ? _f : degrees(0),
        hidden: options.hidden,
        page: page.ref
      });
      var widgetRef = this.doc.context.register(widget.dict);
      this.acroField.addWidget(widgetRef);
      var font = (_g = options.font) !== null && _g !== void 0 ? _g : this.doc.getForm().getDefaultFont();
      this.updateWidgetAppearance(widget, font);
      page.node.addAnnot(widgetRef);
    };
    PDFDropdown2.prototype.needsAppearancesUpdate = function() {
      var _a;
      if (this.isDirty())
        return true;
      var widgets = this.acroField.getWidgets();
      for (var idx = 0, len = widgets.length; idx < len; idx++) {
        var widget = widgets[idx];
        var hasAppearances = ((_a = widget.getAppearances()) === null || _a === void 0 ? void 0 : _a.normal) instanceof PDFStream_default;
        if (!hasAppearances)
          return true;
      }
      return false;
    };
    PDFDropdown2.prototype.defaultUpdateAppearances = function(font) {
      assertIs(font, "font", [[PDFFont_default, "PDFFont"]]);
      this.updateAppearances(font);
    };
    PDFDropdown2.prototype.updateAppearances = function(font, provider) {
      assertIs(font, "font", [[PDFFont_default, "PDFFont"]]);
      assertOrUndefined(provider, "provider", [Function]);
      var widgets = this.acroField.getWidgets();
      for (var idx = 0, len = widgets.length; idx < len; idx++) {
        var widget = widgets[idx];
        this.updateWidgetAppearance(widget, font, provider);
      }
      this.markAsClean();
    };
    PDFDropdown2.prototype.updateWidgetAppearance = function(widget, font, provider) {
      var apProvider = provider !== null && provider !== void 0 ? provider : defaultDropdownAppearanceProvider;
      var appearances = normalizeAppearance(apProvider(this, widget, font));
      this.updateWidgetAppearanceWithFont(widget, font, appearances);
    };
    PDFDropdown2.of = function(acroComboBox, ref, doc) {
      return new PDFDropdown2(acroComboBox, ref, doc);
    };
    return PDFDropdown2;
  }(PDFField_default)
);
var PDFDropdown_default = PDFDropdown;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/api/form/PDFOptionList.js
var PDFOptionList = (
  /** @class */
  function(_super) {
    __extends(PDFOptionList2, _super);
    function PDFOptionList2(acroListBox, ref, doc) {
      var _this = _super.call(this, acroListBox, ref, doc) || this;
      assertIs(acroListBox, "acroListBox", [[PDFAcroListBox_default, "PDFAcroListBox"]]);
      _this.acroField = acroListBox;
      return _this;
    }
    PDFOptionList2.prototype.getOptions = function() {
      var rawOptions = this.acroField.getOptions();
      var options = new Array(rawOptions.length);
      for (var idx = 0, len = options.length; idx < len; idx++) {
        var _a = rawOptions[idx], display = _a.display, value = _a.value;
        options[idx] = (display !== null && display !== void 0 ? display : value).decodeText();
      }
      return options;
    };
    PDFOptionList2.prototype.getSelected = function() {
      var values2 = this.acroField.getValues();
      var selected = new Array(values2.length);
      for (var idx = 0, len = values2.length; idx < len; idx++) {
        selected[idx] = values2[idx].decodeText();
      }
      return selected;
    };
    PDFOptionList2.prototype.setOptions = function(options) {
      assertIs(options, "options", [Array]);
      this.markAsDirty();
      var optionObjects = new Array(options.length);
      for (var idx = 0, len = options.length; idx < len; idx++) {
        optionObjects[idx] = { value: PDFHexString_default.fromText(options[idx]) };
      }
      this.acroField.setOptions(optionObjects);
    };
    PDFOptionList2.prototype.addOptions = function(options) {
      assertIs(options, "options", ["string", Array]);
      this.markAsDirty();
      var optionsArr = Array.isArray(options) ? options : [options];
      var existingOptions = this.acroField.getOptions();
      var newOptions = new Array(optionsArr.length);
      for (var idx = 0, len = optionsArr.length; idx < len; idx++) {
        newOptions[idx] = { value: PDFHexString_default.fromText(optionsArr[idx]) };
      }
      this.acroField.setOptions(existingOptions.concat(newOptions));
    };
    PDFOptionList2.prototype.select = function(options, merge2) {
      if (merge2 === void 0) {
        merge2 = false;
      }
      assertIs(options, "options", ["string", Array]);
      assertIs(merge2, "merge", ["boolean"]);
      var optionsArr = Array.isArray(options) ? options : [options];
      var validOptions = this.getOptions();
      assertIsSubset(optionsArr, "option", validOptions);
      this.markAsDirty();
      if (optionsArr.length > 1 || optionsArr.length === 1 && merge2) {
        this.enableMultiselect();
      }
      var values2 = new Array(optionsArr.length);
      for (var idx = 0, len = optionsArr.length; idx < len; idx++) {
        values2[idx] = PDFHexString_default.fromText(optionsArr[idx]);
      }
      if (merge2) {
        var existingValues = this.acroField.getValues();
        this.acroField.setValues(existingValues.concat(values2));
      } else {
        this.acroField.setValues(values2);
      }
    };
    PDFOptionList2.prototype.clear = function() {
      this.markAsDirty();
      this.acroField.setValues([]);
    };
    PDFOptionList2.prototype.setFontSize = function(fontSize) {
      assertPositive(fontSize, "fontSize");
      this.acroField.setFontSize(fontSize);
      this.markAsDirty();
    };
    PDFOptionList2.prototype.isSorted = function() {
      return this.acroField.hasFlag(AcroChoiceFlags.Sort);
    };
    PDFOptionList2.prototype.enableSorting = function() {
      this.acroField.setFlagTo(AcroChoiceFlags.Sort, true);
    };
    PDFOptionList2.prototype.disableSorting = function() {
      this.acroField.setFlagTo(AcroChoiceFlags.Sort, false);
    };
    PDFOptionList2.prototype.isMultiselect = function() {
      return this.acroField.hasFlag(AcroChoiceFlags.MultiSelect);
    };
    PDFOptionList2.prototype.enableMultiselect = function() {
      this.acroField.setFlagTo(AcroChoiceFlags.MultiSelect, true);
    };
    PDFOptionList2.prototype.disableMultiselect = function() {
      this.acroField.setFlagTo(AcroChoiceFlags.MultiSelect, false);
    };
    PDFOptionList2.prototype.isSelectOnClick = function() {
      return this.acroField.hasFlag(AcroChoiceFlags.CommitOnSelChange);
    };
    PDFOptionList2.prototype.enableSelectOnClick = function() {
      this.acroField.setFlagTo(AcroChoiceFlags.CommitOnSelChange, true);
    };
    PDFOptionList2.prototype.disableSelectOnClick = function() {
      this.acroField.setFlagTo(AcroChoiceFlags.CommitOnSelChange, false);
    };
    PDFOptionList2.prototype.addToPage = function(page, options) {
      var _a, _b, _c, _d, _e, _f, _g;
      assertIs(page, "page", [[PDFPage_default, "PDFPage"]]);
      assertFieldAppearanceOptions(options);
      if (!options)
        options = {};
      if (!("textColor" in options))
        options.textColor = rgb(0, 0, 0);
      if (!("backgroundColor" in options))
        options.backgroundColor = rgb(1, 1, 1);
      if (!("borderColor" in options))
        options.borderColor = rgb(0, 0, 0);
      if (!("borderWidth" in options))
        options.borderWidth = 1;
      var widget = this.createWidget({
        x: (_a = options.x) !== null && _a !== void 0 ? _a : 0,
        y: (_b = options.y) !== null && _b !== void 0 ? _b : 0,
        width: (_c = options.width) !== null && _c !== void 0 ? _c : 200,
        height: (_d = options.height) !== null && _d !== void 0 ? _d : 100,
        textColor: options.textColor,
        backgroundColor: options.backgroundColor,
        borderColor: options.borderColor,
        borderWidth: (_e = options.borderWidth) !== null && _e !== void 0 ? _e : 0,
        rotate: (_f = options.rotate) !== null && _f !== void 0 ? _f : degrees(0),
        hidden: options.hidden,
        page: page.ref
      });
      var widgetRef = this.doc.context.register(widget.dict);
      this.acroField.addWidget(widgetRef);
      var font = (_g = options.font) !== null && _g !== void 0 ? _g : this.doc.getForm().getDefaultFont();
      this.updateWidgetAppearance(widget, font);
      page.node.addAnnot(widgetRef);
    };
    PDFOptionList2.prototype.needsAppearancesUpdate = function() {
      var _a;
      if (this.isDirty())
        return true;
      var widgets = this.acroField.getWidgets();
      for (var idx = 0, len = widgets.length; idx < len; idx++) {
        var widget = widgets[idx];
        var hasAppearances = ((_a = widget.getAppearances()) === null || _a === void 0 ? void 0 : _a.normal) instanceof PDFStream_default;
        if (!hasAppearances)
          return true;
      }
      return false;
    };
    PDFOptionList2.prototype.defaultUpdateAppearances = function(font) {
      assertIs(font, "font", [[PDFFont_default, "PDFFont"]]);
      this.updateAppearances(font);
    };
    PDFOptionList2.prototype.updateAppearances = function(font, provider) {
      assertIs(font, "font", [[PDFFont_default, "PDFFont"]]);
      assertOrUndefined(provider, "provider", [Function]);
      var widgets = this.acroField.getWidgets();
      for (var idx = 0, len = widgets.length; idx < len; idx++) {
        var widget = widgets[idx];
        this.updateWidgetAppearance(widget, font, provider);
      }
      this.markAsClean();
    };
    PDFOptionList2.prototype.updateWidgetAppearance = function(widget, font, provider) {
      var apProvider = provider !== null && provider !== void 0 ? provider : defaultOptionListAppearanceProvider;
      var appearances = normalizeAppearance(apProvider(this, widget, font));
      this.updateWidgetAppearanceWithFont(widget, font, appearances);
    };
    PDFOptionList2.of = function(acroListBox, ref, doc) {
      return new PDFOptionList2(acroListBox, ref, doc);
    };
    return PDFOptionList2;
  }(PDFField_default)
);
var PDFOptionList_default = PDFOptionList;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/api/form/PDFRadioGroup.js
var PDFRadioGroup = (
  /** @class */
  function(_super) {
    __extends(PDFRadioGroup2, _super);
    function PDFRadioGroup2(acroRadioButton, ref, doc) {
      var _this = _super.call(this, acroRadioButton, ref, doc) || this;
      assertIs(acroRadioButton, "acroRadioButton", [
        [PDFAcroRadioButton_default, "PDFAcroRadioButton"]
      ]);
      _this.acroField = acroRadioButton;
      return _this;
    }
    PDFRadioGroup2.prototype.getOptions = function() {
      var exportValues = this.acroField.getExportValues();
      if (exportValues) {
        var exportOptions = new Array(exportValues.length);
        for (var idx = 0, len = exportValues.length; idx < len; idx++) {
          exportOptions[idx] = exportValues[idx].decodeText();
        }
        return exportOptions;
      }
      var onValues = this.acroField.getOnValues();
      var onOptions = new Array(onValues.length);
      for (var idx = 0, len = onOptions.length; idx < len; idx++) {
        onOptions[idx] = onValues[idx].decodeText();
      }
      return onOptions;
    };
    PDFRadioGroup2.prototype.getSelected = function() {
      var value = this.acroField.getValue();
      if (value === PDFName_default.of("Off"))
        return void 0;
      var exportValues = this.acroField.getExportValues();
      if (exportValues) {
        var onValues = this.acroField.getOnValues();
        for (var idx = 0, len = onValues.length; idx < len; idx++) {
          if (onValues[idx] === value)
            return exportValues[idx].decodeText();
        }
      }
      return value.decodeText();
    };
    PDFRadioGroup2.prototype.select = function(option) {
      assertIs(option, "option", ["string"]);
      var validOptions = this.getOptions();
      assertIsOneOf(option, "option", validOptions);
      this.markAsDirty();
      var onValues = this.acroField.getOnValues();
      var exportValues = this.acroField.getExportValues();
      if (exportValues) {
        for (var idx = 0, len = exportValues.length; idx < len; idx++) {
          if (exportValues[idx].decodeText() === option) {
            this.acroField.setValue(onValues[idx]);
          }
        }
      } else {
        for (var idx = 0, len = onValues.length; idx < len; idx++) {
          var value = onValues[idx];
          if (value.decodeText() === option)
            this.acroField.setValue(value);
        }
      }
    };
    PDFRadioGroup2.prototype.clear = function() {
      this.markAsDirty();
      this.acroField.setValue(PDFName_default.of("Off"));
    };
    PDFRadioGroup2.prototype.isOffToggleable = function() {
      return !this.acroField.hasFlag(AcroButtonFlags.NoToggleToOff);
    };
    PDFRadioGroup2.prototype.enableOffToggling = function() {
      this.acroField.setFlagTo(AcroButtonFlags.NoToggleToOff, false);
    };
    PDFRadioGroup2.prototype.disableOffToggling = function() {
      this.acroField.setFlagTo(AcroButtonFlags.NoToggleToOff, true);
    };
    PDFRadioGroup2.prototype.isMutuallyExclusive = function() {
      return !this.acroField.hasFlag(AcroButtonFlags.RadiosInUnison);
    };
    PDFRadioGroup2.prototype.enableMutualExclusion = function() {
      this.acroField.setFlagTo(AcroButtonFlags.RadiosInUnison, false);
    };
    PDFRadioGroup2.prototype.disableMutualExclusion = function() {
      this.acroField.setFlagTo(AcroButtonFlags.RadiosInUnison, true);
    };
    PDFRadioGroup2.prototype.addOptionToPage = function(option, page, options) {
      var _a, _b, _c, _d, _e, _f, _g, _h, _j;
      assertIs(option, "option", ["string"]);
      assertIs(page, "page", [[PDFPage_default, "PDFPage"]]);
      assertFieldAppearanceOptions(options);
      var widget = this.createWidget({
        x: (_a = options === null || options === void 0 ? void 0 : options.x) !== null && _a !== void 0 ? _a : 0,
        y: (_b = options === null || options === void 0 ? void 0 : options.y) !== null && _b !== void 0 ? _b : 0,
        width: (_c = options === null || options === void 0 ? void 0 : options.width) !== null && _c !== void 0 ? _c : 50,
        height: (_d = options === null || options === void 0 ? void 0 : options.height) !== null && _d !== void 0 ? _d : 50,
        textColor: (_e = options === null || options === void 0 ? void 0 : options.textColor) !== null && _e !== void 0 ? _e : rgb(0, 0, 0),
        backgroundColor: (_f = options === null || options === void 0 ? void 0 : options.backgroundColor) !== null && _f !== void 0 ? _f : rgb(1, 1, 1),
        borderColor: (_g = options === null || options === void 0 ? void 0 : options.borderColor) !== null && _g !== void 0 ? _g : rgb(0, 0, 0),
        borderWidth: (_h = options === null || options === void 0 ? void 0 : options.borderWidth) !== null && _h !== void 0 ? _h : 1,
        rotate: (_j = options === null || options === void 0 ? void 0 : options.rotate) !== null && _j !== void 0 ? _j : degrees(0),
        hidden: options === null || options === void 0 ? void 0 : options.hidden,
        page: page.ref
      });
      var widgetRef = this.doc.context.register(widget.dict);
      var apStateValue = this.acroField.addWidgetWithOpt(widgetRef, PDFHexString_default.fromText(option), !this.isMutuallyExclusive());
      widget.setAppearanceState(PDFName_default.of("Off"));
      this.updateWidgetAppearance(widget, apStateValue);
      page.node.addAnnot(widgetRef);
    };
    PDFRadioGroup2.prototype.needsAppearancesUpdate = function() {
      var _a;
      var widgets = this.acroField.getWidgets();
      for (var idx = 0, len = widgets.length; idx < len; idx++) {
        var widget = widgets[idx];
        var state = widget.getAppearanceState();
        var normal = (_a = widget.getAppearances()) === null || _a === void 0 ? void 0 : _a.normal;
        if (!(normal instanceof PDFDict_default))
          return true;
        if (state && !normal.has(state))
          return true;
      }
      return false;
    };
    PDFRadioGroup2.prototype.defaultUpdateAppearances = function() {
      this.updateAppearances();
    };
    PDFRadioGroup2.prototype.updateAppearances = function(provider) {
      assertOrUndefined(provider, "provider", [Function]);
      var widgets = this.acroField.getWidgets();
      for (var idx = 0, len = widgets.length; idx < len; idx++) {
        var widget = widgets[idx];
        var onValue = widget.getOnValue();
        if (!onValue)
          continue;
        this.updateWidgetAppearance(widget, onValue, provider);
      }
    };
    PDFRadioGroup2.prototype.updateWidgetAppearance = function(widget, onValue, provider) {
      var apProvider = provider !== null && provider !== void 0 ? provider : defaultRadioGroupAppearanceProvider;
      var appearances = normalizeAppearance(apProvider(this, widget));
      this.updateOnOffWidgetAppearance(widget, onValue, appearances);
    };
    PDFRadioGroup2.of = function(acroRadioButton, ref, doc) {
      return new PDFRadioGroup2(acroRadioButton, ref, doc);
    };
    return PDFRadioGroup2;
  }(PDFField_default)
);
var PDFRadioGroup_default = PDFRadioGroup;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/api/form/PDFSignature.js
var PDFSignature = (
  /** @class */
  function(_super) {
    __extends(PDFSignature2, _super);
    function PDFSignature2(acroSignature, ref, doc) {
      var _this = _super.call(this, acroSignature, ref, doc) || this;
      assertIs(acroSignature, "acroSignature", [
        [PDFAcroSignature_default, "PDFAcroSignature"]
      ]);
      _this.acroField = acroSignature;
      return _this;
    }
    PDFSignature2.prototype.needsAppearancesUpdate = function() {
      return false;
    };
    PDFSignature2.of = function(acroSignature, ref, doc) {
      return new PDFSignature2(acroSignature, ref, doc);
    };
    return PDFSignature2;
  }(PDFField_default)
);
var PDFSignature_default = PDFSignature;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/api/form/PDFTextField.js
var PDFTextField = (
  /** @class */
  function(_super) {
    __extends(PDFTextField2, _super);
    function PDFTextField2(acroText, ref, doc) {
      var _this = _super.call(this, acroText, ref, doc) || this;
      assertIs(acroText, "acroText", [[PDFAcroText_default, "PDFAcroText"]]);
      _this.acroField = acroText;
      return _this;
    }
    PDFTextField2.prototype.getText = function() {
      var value = this.acroField.getValue();
      if (!value && this.isRichFormatted()) {
        throw new RichTextFieldReadError(this.getName());
      }
      return value === null || value === void 0 ? void 0 : value.decodeText();
    };
    PDFTextField2.prototype.setText = function(text) {
      assertOrUndefined(text, "text", ["string"]);
      var maxLength = this.getMaxLength();
      if (maxLength !== void 0 && text && text.length > maxLength) {
        throw new ExceededMaxLengthError(text.length, maxLength, this.getName());
      }
      this.markAsDirty();
      this.disableRichFormatting();
      if (text) {
        this.acroField.setValue(PDFHexString_default.fromText(text));
      } else {
        this.acroField.removeValue();
      }
    };
    PDFTextField2.prototype.getAlignment = function() {
      var quadding = this.acroField.getQuadding();
      return quadding === 0 ? TextAlignment.Left : quadding === 1 ? TextAlignment.Center : quadding === 2 ? TextAlignment.Right : TextAlignment.Left;
    };
    PDFTextField2.prototype.setAlignment = function(alignment) {
      assertIsOneOf(alignment, "alignment", TextAlignment);
      this.markAsDirty();
      this.acroField.setQuadding(alignment);
    };
    PDFTextField2.prototype.getMaxLength = function() {
      return this.acroField.getMaxLength();
    };
    PDFTextField2.prototype.setMaxLength = function(maxLength) {
      assertRangeOrUndefined(maxLength, "maxLength", 0, Number.MAX_SAFE_INTEGER);
      this.markAsDirty();
      if (maxLength === void 0) {
        this.acroField.removeMaxLength();
      } else {
        var text = this.getText();
        if (text && text.length > maxLength) {
          throw new InvalidMaxLengthError(text.length, maxLength, this.getName());
        }
        this.acroField.setMaxLength(maxLength);
      }
    };
    PDFTextField2.prototype.removeMaxLength = function() {
      this.markAsDirty();
      this.acroField.removeMaxLength();
    };
    PDFTextField2.prototype.setImage = function(image) {
      var fieldAlignment = this.getAlignment();
      var alignment = fieldAlignment === TextAlignment.Center ? ImageAlignment.Center : fieldAlignment === TextAlignment.Right ? ImageAlignment.Right : ImageAlignment.Left;
      var widgets = this.acroField.getWidgets();
      for (var idx = 0, len = widgets.length; idx < len; idx++) {
        var widget = widgets[idx];
        var streamRef = this.createImageAppearanceStream(widget, image, alignment);
        this.updateWidgetAppearances(widget, { normal: streamRef });
      }
      this.markAsClean();
    };
    PDFTextField2.prototype.setFontSize = function(fontSize) {
      assertPositive(fontSize, "fontSize");
      this.acroField.setFontSize(fontSize);
      this.markAsDirty();
    };
    PDFTextField2.prototype.isMultiline = function() {
      return this.acroField.hasFlag(AcroTextFlags.Multiline);
    };
    PDFTextField2.prototype.enableMultiline = function() {
      this.markAsDirty();
      this.acroField.setFlagTo(AcroTextFlags.Multiline, true);
    };
    PDFTextField2.prototype.disableMultiline = function() {
      this.markAsDirty();
      this.acroField.setFlagTo(AcroTextFlags.Multiline, false);
    };
    PDFTextField2.prototype.isPassword = function() {
      return this.acroField.hasFlag(AcroTextFlags.Password);
    };
    PDFTextField2.prototype.enablePassword = function() {
      this.acroField.setFlagTo(AcroTextFlags.Password, true);
    };
    PDFTextField2.prototype.disablePassword = function() {
      this.acroField.setFlagTo(AcroTextFlags.Password, false);
    };
    PDFTextField2.prototype.isFileSelector = function() {
      return this.acroField.hasFlag(AcroTextFlags.FileSelect);
    };
    PDFTextField2.prototype.enableFileSelection = function() {
      this.acroField.setFlagTo(AcroTextFlags.FileSelect, true);
    };
    PDFTextField2.prototype.disableFileSelection = function() {
      this.acroField.setFlagTo(AcroTextFlags.FileSelect, false);
    };
    PDFTextField2.prototype.isSpellChecked = function() {
      return !this.acroField.hasFlag(AcroTextFlags.DoNotSpellCheck);
    };
    PDFTextField2.prototype.enableSpellChecking = function() {
      this.acroField.setFlagTo(AcroTextFlags.DoNotSpellCheck, false);
    };
    PDFTextField2.prototype.disableSpellChecking = function() {
      this.acroField.setFlagTo(AcroTextFlags.DoNotSpellCheck, true);
    };
    PDFTextField2.prototype.isScrollable = function() {
      return !this.acroField.hasFlag(AcroTextFlags.DoNotScroll);
    };
    PDFTextField2.prototype.enableScrolling = function() {
      this.acroField.setFlagTo(AcroTextFlags.DoNotScroll, false);
    };
    PDFTextField2.prototype.disableScrolling = function() {
      this.acroField.setFlagTo(AcroTextFlags.DoNotScroll, true);
    };
    PDFTextField2.prototype.isCombed = function() {
      return this.acroField.hasFlag(AcroTextFlags.Comb) && !this.isMultiline() && !this.isPassword() && !this.isFileSelector() && this.getMaxLength() !== void 0;
    };
    PDFTextField2.prototype.enableCombing = function() {
      if (this.getMaxLength() === void 0) {
        var msg = "PDFTextFields must have a max length in order to be combed";
        console.warn(msg);
      }
      this.markAsDirty();
      this.disableMultiline();
      this.disablePassword();
      this.disableFileSelection();
      this.acroField.setFlagTo(AcroTextFlags.Comb, true);
    };
    PDFTextField2.prototype.disableCombing = function() {
      this.markAsDirty();
      this.acroField.setFlagTo(AcroTextFlags.Comb, false);
    };
    PDFTextField2.prototype.isRichFormatted = function() {
      return this.acroField.hasFlag(AcroTextFlags.RichText);
    };
    PDFTextField2.prototype.enableRichFormatting = function() {
      this.acroField.setFlagTo(AcroTextFlags.RichText, true);
    };
    PDFTextField2.prototype.disableRichFormatting = function() {
      this.acroField.setFlagTo(AcroTextFlags.RichText, false);
    };
    PDFTextField2.prototype.addToPage = function(page, options) {
      var _a, _b, _c, _d, _e, _f, _g;
      assertIs(page, "page", [[PDFPage_default, "PDFPage"]]);
      assertFieldAppearanceOptions(options);
      if (!options)
        options = {};
      if (!("textColor" in options))
        options.textColor = rgb(0, 0, 0);
      if (!("backgroundColor" in options))
        options.backgroundColor = rgb(1, 1, 1);
      if (!("borderColor" in options))
        options.borderColor = rgb(0, 0, 0);
      if (!("borderWidth" in options))
        options.borderWidth = 1;
      var widget = this.createWidget({
        x: (_a = options.x) !== null && _a !== void 0 ? _a : 0,
        y: (_b = options.y) !== null && _b !== void 0 ? _b : 0,
        width: (_c = options.width) !== null && _c !== void 0 ? _c : 200,
        height: (_d = options.height) !== null && _d !== void 0 ? _d : 50,
        textColor: options.textColor,
        backgroundColor: options.backgroundColor,
        borderColor: options.borderColor,
        borderWidth: (_e = options.borderWidth) !== null && _e !== void 0 ? _e : 0,
        rotate: (_f = options.rotate) !== null && _f !== void 0 ? _f : degrees(0),
        hidden: options.hidden,
        page: page.ref
      });
      var widgetRef = this.doc.context.register(widget.dict);
      this.acroField.addWidget(widgetRef);
      var font = (_g = options.font) !== null && _g !== void 0 ? _g : this.doc.getForm().getDefaultFont();
      this.updateWidgetAppearance(widget, font);
      page.node.addAnnot(widgetRef);
    };
    PDFTextField2.prototype.needsAppearancesUpdate = function() {
      var _a;
      if (this.isDirty())
        return true;
      var widgets = this.acroField.getWidgets();
      for (var idx = 0, len = widgets.length; idx < len; idx++) {
        var widget = widgets[idx];
        var hasAppearances = ((_a = widget.getAppearances()) === null || _a === void 0 ? void 0 : _a.normal) instanceof PDFStream_default;
        if (!hasAppearances)
          return true;
      }
      return false;
    };
    PDFTextField2.prototype.defaultUpdateAppearances = function(font) {
      assertIs(font, "font", [[PDFFont_default, "PDFFont"]]);
      this.updateAppearances(font);
    };
    PDFTextField2.prototype.updateAppearances = function(font, provider) {
      assertIs(font, "font", [[PDFFont_default, "PDFFont"]]);
      assertOrUndefined(provider, "provider", [Function]);
      var widgets = this.acroField.getWidgets();
      for (var idx = 0, len = widgets.length; idx < len; idx++) {
        var widget = widgets[idx];
        this.updateWidgetAppearance(widget, font, provider);
      }
      this.markAsClean();
    };
    PDFTextField2.prototype.updateWidgetAppearance = function(widget, font, provider) {
      var apProvider = provider !== null && provider !== void 0 ? provider : defaultTextFieldAppearanceProvider;
      var appearances = normalizeAppearance(apProvider(this, widget, font));
      this.updateWidgetAppearanceWithFont(widget, font, appearances);
    };
    PDFTextField2.of = function(acroText, ref, doc) {
      return new PDFTextField2(acroText, ref, doc);
    };
    return PDFTextField2;
  }(PDFField_default)
);
var PDFTextField_default = PDFTextField;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/api/StandardFonts.js
var StandardFonts;
(function(StandardFonts2) {
  StandardFonts2["Courier"] = "Courier";
  StandardFonts2["CourierBold"] = "Courier-Bold";
  StandardFonts2["CourierOblique"] = "Courier-Oblique";
  StandardFonts2["CourierBoldOblique"] = "Courier-BoldOblique";
  StandardFonts2["Helvetica"] = "Helvetica";
  StandardFonts2["HelveticaBold"] = "Helvetica-Bold";
  StandardFonts2["HelveticaOblique"] = "Helvetica-Oblique";
  StandardFonts2["HelveticaBoldOblique"] = "Helvetica-BoldOblique";
  StandardFonts2["TimesRoman"] = "Times-Roman";
  StandardFonts2["TimesRomanBold"] = "Times-Bold";
  StandardFonts2["TimesRomanItalic"] = "Times-Italic";
  StandardFonts2["TimesRomanBoldItalic"] = "Times-BoldItalic";
  StandardFonts2["Symbol"] = "Symbol";
  StandardFonts2["ZapfDingbats"] = "ZapfDingbats";
})(StandardFonts || (StandardFonts = {}));

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/api/form/PDFForm.js
var PDFForm = (
  /** @class */
  function() {
    function PDFForm2(acroForm, doc) {
      var _this = this;
      this.embedDefaultFont = function() {
        return _this.doc.embedStandardFont(StandardFonts.Helvetica);
      };
      assertIs(acroForm, "acroForm", [[PDFAcroForm_default, "PDFAcroForm"]]);
      assertIs(doc, "doc", [[PDFDocument_default, "PDFDocument"]]);
      this.acroForm = acroForm;
      this.doc = doc;
      this.dirtyFields = /* @__PURE__ */ new Set();
      this.defaultFontCache = Cache_default.populatedBy(this.embedDefaultFont);
    }
    PDFForm2.prototype.hasXFA = function() {
      return this.acroForm.dict.has(PDFName_default.of("XFA"));
    };
    PDFForm2.prototype.deleteXFA = function() {
      this.acroForm.dict.delete(PDFName_default.of("XFA"));
    };
    PDFForm2.prototype.getFields = function() {
      var allFields = this.acroForm.getAllFields();
      var fields = [];
      for (var idx = 0, len = allFields.length; idx < len; idx++) {
        var _a = allFields[idx], acroField = _a[0], ref = _a[1];
        var field = convertToPDFField(acroField, ref, this.doc);
        if (field)
          fields.push(field);
      }
      return fields;
    };
    PDFForm2.prototype.getFieldMaybe = function(name) {
      assertIs(name, "name", ["string"]);
      var fields = this.getFields();
      for (var idx = 0, len = fields.length; idx < len; idx++) {
        var field = fields[idx];
        if (field.getName() === name)
          return field;
      }
      return void 0;
    };
    PDFForm2.prototype.getField = function(name) {
      assertIs(name, "name", ["string"]);
      var field = this.getFieldMaybe(name);
      if (field)
        return field;
      throw new NoSuchFieldError(name);
    };
    PDFForm2.prototype.getButton = function(name) {
      assertIs(name, "name", ["string"]);
      var field = this.getField(name);
      if (field instanceof PDFButton_default)
        return field;
      throw new UnexpectedFieldTypeError(name, PDFButton_default, field);
    };
    PDFForm2.prototype.getCheckBox = function(name) {
      assertIs(name, "name", ["string"]);
      var field = this.getField(name);
      if (field instanceof PDFCheckBox_default)
        return field;
      throw new UnexpectedFieldTypeError(name, PDFCheckBox_default, field);
    };
    PDFForm2.prototype.getDropdown = function(name) {
      assertIs(name, "name", ["string"]);
      var field = this.getField(name);
      if (field instanceof PDFDropdown_default)
        return field;
      throw new UnexpectedFieldTypeError(name, PDFDropdown_default, field);
    };
    PDFForm2.prototype.getOptionList = function(name) {
      assertIs(name, "name", ["string"]);
      var field = this.getField(name);
      if (field instanceof PDFOptionList_default)
        return field;
      throw new UnexpectedFieldTypeError(name, PDFOptionList_default, field);
    };
    PDFForm2.prototype.getRadioGroup = function(name) {
      assertIs(name, "name", ["string"]);
      var field = this.getField(name);
      if (field instanceof PDFRadioGroup_default)
        return field;
      throw new UnexpectedFieldTypeError(name, PDFRadioGroup_default, field);
    };
    PDFForm2.prototype.getSignature = function(name) {
      assertIs(name, "name", ["string"]);
      var field = this.getField(name);
      if (field instanceof PDFSignature_default)
        return field;
      throw new UnexpectedFieldTypeError(name, PDFSignature_default, field);
    };
    PDFForm2.prototype.getTextField = function(name) {
      assertIs(name, "name", ["string"]);
      var field = this.getField(name);
      if (field instanceof PDFTextField_default)
        return field;
      throw new UnexpectedFieldTypeError(name, PDFTextField_default, field);
    };
    PDFForm2.prototype.createButton = function(name) {
      assertIs(name, "name", ["string"]);
      var nameParts = splitFieldName(name);
      var parent = this.findOrCreateNonTerminals(nameParts.nonTerminal);
      var button = PDFAcroPushButton_default.create(this.doc.context);
      button.setPartialName(nameParts.terminal);
      addFieldToParent(parent, [button, button.ref], nameParts.terminal);
      return PDFButton_default.of(button, button.ref, this.doc);
    };
    PDFForm2.prototype.createCheckBox = function(name) {
      assertIs(name, "name", ["string"]);
      var nameParts = splitFieldName(name);
      var parent = this.findOrCreateNonTerminals(nameParts.nonTerminal);
      var checkBox = PDFAcroCheckBox_default.create(this.doc.context);
      checkBox.setPartialName(nameParts.terminal);
      addFieldToParent(parent, [checkBox, checkBox.ref], nameParts.terminal);
      return PDFCheckBox_default.of(checkBox, checkBox.ref, this.doc);
    };
    PDFForm2.prototype.createDropdown = function(name) {
      assertIs(name, "name", ["string"]);
      var nameParts = splitFieldName(name);
      var parent = this.findOrCreateNonTerminals(nameParts.nonTerminal);
      var comboBox = PDFAcroComboBox_default.create(this.doc.context);
      comboBox.setPartialName(nameParts.terminal);
      addFieldToParent(parent, [comboBox, comboBox.ref], nameParts.terminal);
      return PDFDropdown_default.of(comboBox, comboBox.ref, this.doc);
    };
    PDFForm2.prototype.createOptionList = function(name) {
      assertIs(name, "name", ["string"]);
      var nameParts = splitFieldName(name);
      var parent = this.findOrCreateNonTerminals(nameParts.nonTerminal);
      var listBox = PDFAcroListBox_default.create(this.doc.context);
      listBox.setPartialName(nameParts.terminal);
      addFieldToParent(parent, [listBox, listBox.ref], nameParts.terminal);
      return PDFOptionList_default.of(listBox, listBox.ref, this.doc);
    };
    PDFForm2.prototype.createRadioGroup = function(name) {
      assertIs(name, "name", ["string"]);
      var nameParts = splitFieldName(name);
      var parent = this.findOrCreateNonTerminals(nameParts.nonTerminal);
      var radioButton = PDFAcroRadioButton_default.create(this.doc.context);
      radioButton.setPartialName(nameParts.terminal);
      addFieldToParent(parent, [radioButton, radioButton.ref], nameParts.terminal);
      return PDFRadioGroup_default.of(radioButton, radioButton.ref, this.doc);
    };
    PDFForm2.prototype.createTextField = function(name) {
      assertIs(name, "name", ["string"]);
      var nameParts = splitFieldName(name);
      var parent = this.findOrCreateNonTerminals(nameParts.nonTerminal);
      var text = PDFAcroText_default.create(this.doc.context);
      text.setPartialName(nameParts.terminal);
      addFieldToParent(parent, [text, text.ref], nameParts.terminal);
      return PDFTextField_default.of(text, text.ref, this.doc);
    };
    PDFForm2.prototype.flatten = function(options) {
      if (options === void 0) {
        options = { updateFieldAppearances: true };
      }
      if (options.updateFieldAppearances) {
        this.updateFieldAppearances();
      }
      var fields = this.getFields();
      for (var i = 0, lenFields = fields.length; i < lenFields; i++) {
        var field = fields[i];
        var widgets = field.acroField.getWidgets();
        for (var j = 0, lenWidgets = widgets.length; j < lenWidgets; j++) {
          var widget = widgets[j];
          var page = this.findWidgetPage(widget);
          var widgetRef = this.findWidgetAppearanceRef(field, widget);
          var xObjectKey = page.node.newXObject("FlatWidget", widgetRef);
          var rectangle = widget.getRectangle();
          var operators = __spreadArrays([
            pushGraphicsState(),
            translate(rectangle.x, rectangle.y)
          ], rotateInPlace(__assign(__assign({}, rectangle), { rotation: 0 })), [
            drawObject(xObjectKey),
            popGraphicsState()
          ]).filter(Boolean);
          page.pushOperators.apply(page, operators);
        }
        this.removeField(field);
      }
    };
    PDFForm2.prototype.removeField = function(field) {
      var widgets = field.acroField.getWidgets();
      var pages = /* @__PURE__ */ new Set();
      for (var i = 0, len = widgets.length; i < len; i++) {
        var widget = widgets[i];
        var widgetRef = this.findWidgetAppearanceRef(field, widget);
        var page = this.findWidgetPage(widget);
        pages.add(page);
        page.node.removeAnnot(widgetRef);
      }
      pages.forEach(function(page2) {
        return page2.node.removeAnnot(field.ref);
      });
      this.acroForm.removeField(field.acroField);
      var fieldKids = field.acroField.normalizedEntries().Kids;
      var kidsCount = fieldKids.size();
      for (var childIndex = 0; childIndex < kidsCount; childIndex++) {
        var child = fieldKids.get(childIndex);
        if (child instanceof PDFRef_default) {
          this.doc.context.delete(child);
        }
      }
      this.doc.context.delete(field.ref);
    };
    PDFForm2.prototype.updateFieldAppearances = function(font) {
      assertOrUndefined(font, "font", [[PDFFont_default, "PDFFont"]]);
      font = font !== null && font !== void 0 ? font : this.getDefaultFont();
      var fields = this.getFields();
      for (var idx = 0, len = fields.length; idx < len; idx++) {
        var field = fields[idx];
        if (field.needsAppearancesUpdate()) {
          field.defaultUpdateAppearances(font);
        }
      }
    };
    PDFForm2.prototype.markFieldAsDirty = function(fieldRef) {
      assertOrUndefined(fieldRef, "fieldRef", [[PDFRef_default, "PDFRef"]]);
      this.dirtyFields.add(fieldRef);
    };
    PDFForm2.prototype.markFieldAsClean = function(fieldRef) {
      assertOrUndefined(fieldRef, "fieldRef", [[PDFRef_default, "PDFRef"]]);
      this.dirtyFields.delete(fieldRef);
    };
    PDFForm2.prototype.fieldIsDirty = function(fieldRef) {
      assertOrUndefined(fieldRef, "fieldRef", [[PDFRef_default, "PDFRef"]]);
      return this.dirtyFields.has(fieldRef);
    };
    PDFForm2.prototype.getDefaultFont = function() {
      return this.defaultFontCache.access();
    };
    PDFForm2.prototype.findWidgetPage = function(widget) {
      var pageRef = widget.P();
      var page = this.doc.getPages().find(function(x) {
        return x.ref === pageRef;
      });
      if (page === void 0) {
        var widgetRef = this.doc.context.getObjectRef(widget.dict);
        if (widgetRef === void 0) {
          throw new Error("Could not find PDFRef for PDFObject");
        }
        page = this.doc.findPageForAnnotationRef(widgetRef);
        if (page === void 0) {
          throw new Error("Could not find page for PDFRef " + widgetRef);
        }
      }
      return page;
    };
    PDFForm2.prototype.findWidgetAppearanceRef = function(field, widget) {
      var _a;
      var refOrDict = widget.getNormalAppearance();
      if (refOrDict instanceof PDFDict_default && (field instanceof PDFCheckBox_default || field instanceof PDFRadioGroup_default)) {
        var value = field.acroField.getValue();
        var ref = (_a = refOrDict.get(value)) !== null && _a !== void 0 ? _a : refOrDict.get(PDFName_default.of("Off"));
        if (ref instanceof PDFRef_default) {
          refOrDict = ref;
        }
      }
      if (!(refOrDict instanceof PDFRef_default)) {
        var name_1 = field.getName();
        throw new Error("Failed to extract appearance ref for: " + name_1);
      }
      return refOrDict;
    };
    PDFForm2.prototype.findOrCreateNonTerminals = function(partialNames) {
      var nonTerminal = [
        this.acroForm
      ];
      for (var idx = 0, len = partialNames.length; idx < len; idx++) {
        var namePart = partialNames[idx];
        if (!namePart)
          throw new InvalidFieldNamePartError(namePart);
        var parent_1 = nonTerminal[0], parentRef = nonTerminal[1];
        var res = this.findNonTerminal(namePart, parent_1);
        if (res) {
          nonTerminal = res;
        } else {
          var node = PDFAcroNonTerminal_default.create(this.doc.context);
          node.setPartialName(namePart);
          node.setParent(parentRef);
          var nodeRef = this.doc.context.register(node.dict);
          parent_1.addField(nodeRef);
          nonTerminal = [node, nodeRef];
        }
      }
      return nonTerminal;
    };
    PDFForm2.prototype.findNonTerminal = function(partialName, parent) {
      var fields = parent instanceof PDFAcroForm_default ? this.acroForm.getFields() : createPDFAcroFields(parent.Kids());
      for (var idx = 0, len = fields.length; idx < len; idx++) {
        var _a = fields[idx], field = _a[0], ref = _a[1];
        if (field.getPartialName() === partialName) {
          if (field instanceof PDFAcroNonTerminal_default)
            return [field, ref];
          throw new FieldAlreadyExistsError(partialName);
        }
      }
      return void 0;
    };
    PDFForm2.of = function(acroForm, doc) {
      return new PDFForm2(acroForm, doc);
    };
    return PDFForm2;
  }()
);
var PDFForm_default = PDFForm;
var convertToPDFField = function(field, ref, doc) {
  if (field instanceof PDFAcroPushButton_default)
    return PDFButton_default.of(field, ref, doc);
  if (field instanceof PDFAcroCheckBox_default)
    return PDFCheckBox_default.of(field, ref, doc);
  if (field instanceof PDFAcroComboBox_default)
    return PDFDropdown_default.of(field, ref, doc);
  if (field instanceof PDFAcroListBox_default)
    return PDFOptionList_default.of(field, ref, doc);
  if (field instanceof PDFAcroText_default)
    return PDFTextField_default.of(field, ref, doc);
  if (field instanceof PDFAcroRadioButton_default) {
    return PDFRadioGroup_default.of(field, ref, doc);
  }
  if (field instanceof PDFAcroSignature_default) {
    return PDFSignature_default.of(field, ref, doc);
  }
  return void 0;
};
var splitFieldName = function(fullyQualifiedName) {
  if (fullyQualifiedName.length === 0) {
    throw new Error("PDF field names must not be empty strings");
  }
  var parts = fullyQualifiedName.split(".");
  for (var idx = 0, len = parts.length; idx < len; idx++) {
    if (parts[idx] === "") {
      throw new Error('Periods in PDF field names must be separated by at least one character: "' + fullyQualifiedName + '"');
    }
  }
  if (parts.length === 1)
    return { nonTerminal: [], terminal: parts[0] };
  return {
    nonTerminal: parts.slice(0, parts.length - 1),
    terminal: parts[parts.length - 1]
  };
};
var addFieldToParent = function(_a, _b, partialName) {
  var parent = _a[0], parentRef = _a[1];
  var field = _b[0], fieldRef = _b[1];
  var entries = parent.normalizedEntries();
  var fields = createPDFAcroFields("Kids" in entries ? entries.Kids : entries.Fields);
  for (var idx = 0, len = fields.length; idx < len; idx++) {
    if (fields[idx][0].getPartialName() === partialName) {
      throw new FieldAlreadyExistsError(partialName);
    }
  }
  parent.addField(fieldRef);
  field.setParent(parentRef);
};

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/api/sizes.js
var PageSizes = {
  "4A0": [4767.87, 6740.79],
  "2A0": [3370.39, 4767.87],
  A0: [2383.94, 3370.39],
  A1: [1683.78, 2383.94],
  A2: [1190.55, 1683.78],
  A3: [841.89, 1190.55],
  A4: [595.28, 841.89],
  A5: [419.53, 595.28],
  A6: [297.64, 419.53],
  A7: [209.76, 297.64],
  A8: [147.4, 209.76],
  A9: [104.88, 147.4],
  A10: [73.7, 104.88],
  B0: [2834.65, 4008.19],
  B1: [2004.09, 2834.65],
  B2: [1417.32, 2004.09],
  B3: [1000.63, 1417.32],
  B4: [708.66, 1000.63],
  B5: [498.9, 708.66],
  B6: [354.33, 498.9],
  B7: [249.45, 354.33],
  B8: [175.75, 249.45],
  B9: [124.72, 175.75],
  B10: [87.87, 124.72],
  C0: [2599.37, 3676.54],
  C1: [1836.85, 2599.37],
  C2: [1298.27, 1836.85],
  C3: [918.43, 1298.27],
  C4: [649.13, 918.43],
  C5: [459.21, 649.13],
  C6: [323.15, 459.21],
  C7: [229.61, 323.15],
  C8: [161.57, 229.61],
  C9: [113.39, 161.57],
  C10: [79.37, 113.39],
  RA0: [2437.8, 3458.27],
  RA1: [1729.13, 2437.8],
  RA2: [1218.9, 1729.13],
  RA3: [864.57, 1218.9],
  RA4: [609.45, 864.57],
  SRA0: [2551.18, 3628.35],
  SRA1: [1814.17, 2551.18],
  SRA2: [1275.59, 1814.17],
  SRA3: [907.09, 1275.59],
  SRA4: [637.8, 907.09],
  Executive: [521.86, 756],
  Folio: [612, 936],
  Legal: [612, 1008],
  Letter: [612, 792],
  Tabloid: [792, 1224]
};

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/api/PDFDocumentOptions.js
var ParseSpeeds;
(function(ParseSpeeds2) {
  ParseSpeeds2[ParseSpeeds2["Fastest"] = Infinity] = "Fastest";
  ParseSpeeds2[ParseSpeeds2["Fast"] = 1500] = "Fast";
  ParseSpeeds2[ParseSpeeds2["Medium"] = 500] = "Medium";
  ParseSpeeds2[ParseSpeeds2["Slow"] = 100] = "Slow";
})(ParseSpeeds || (ParseSpeeds = {}));

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/api/PDFEmbeddedFile.js
var PDFEmbeddedFile = (
  /** @class */
  function() {
    function PDFEmbeddedFile2(ref, doc, embedder) {
      this.alreadyEmbedded = false;
      this.ref = ref;
      this.doc = doc;
      this.embedder = embedder;
    }
    PDFEmbeddedFile2.prototype.embed = function() {
      return __awaiter(this, void 0, void 0, function() {
        var ref, Names, EmbeddedFiles, EFNames, AF;
        return __generator(this, function(_a) {
          switch (_a.label) {
            case 0:
              if (!!this.alreadyEmbedded) return [3, 2];
              return [4, this.embedder.embedIntoContext(this.doc.context, this.ref)];
            case 1:
              ref = _a.sent();
              if (!this.doc.catalog.has(PDFName_default.of("Names"))) {
                this.doc.catalog.set(PDFName_default.of("Names"), this.doc.context.obj({}));
              }
              Names = this.doc.catalog.lookup(PDFName_default.of("Names"), PDFDict_default);
              if (!Names.has(PDFName_default.of("EmbeddedFiles"))) {
                Names.set(PDFName_default.of("EmbeddedFiles"), this.doc.context.obj({}));
              }
              EmbeddedFiles = Names.lookup(PDFName_default.of("EmbeddedFiles"), PDFDict_default);
              if (!EmbeddedFiles.has(PDFName_default.of("Names"))) {
                EmbeddedFiles.set(PDFName_default.of("Names"), this.doc.context.obj([]));
              }
              EFNames = EmbeddedFiles.lookup(PDFName_default.of("Names"), PDFArray_default);
              EFNames.push(PDFHexString_default.fromText(this.embedder.fileName));
              EFNames.push(ref);
              if (!this.doc.catalog.has(PDFName_default.of("AF"))) {
                this.doc.catalog.set(PDFName_default.of("AF"), this.doc.context.obj([]));
              }
              AF = this.doc.catalog.lookup(PDFName_default.of("AF"), PDFArray_default);
              AF.push(ref);
              this.alreadyEmbedded = true;
              _a.label = 2;
            case 2:
              return [
                2
                /*return*/
              ];
          }
        });
      });
    };
    PDFEmbeddedFile2.of = function(ref, doc, embedder) {
      return new PDFEmbeddedFile2(ref, doc, embedder);
    };
    return PDFEmbeddedFile2;
  }()
);
var PDFEmbeddedFile_default = PDFEmbeddedFile;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/api/PDFJavaScript.js
var PDFJavaScript = (
  /** @class */
  function() {
    function PDFJavaScript2(ref, doc, embedder) {
      this.alreadyEmbedded = false;
      this.ref = ref;
      this.doc = doc;
      this.embedder = embedder;
    }
    PDFJavaScript2.prototype.embed = function() {
      return __awaiter(this, void 0, void 0, function() {
        var _a, catalog, context, ref, Names, Javascript, JSNames;
        return __generator(this, function(_b) {
          switch (_b.label) {
            case 0:
              if (!!this.alreadyEmbedded) return [3, 2];
              _a = this.doc, catalog = _a.catalog, context = _a.context;
              return [4, this.embedder.embedIntoContext(this.doc.context, this.ref)];
            case 1:
              ref = _b.sent();
              if (!catalog.has(PDFName_default.of("Names"))) {
                catalog.set(PDFName_default.of("Names"), context.obj({}));
              }
              Names = catalog.lookup(PDFName_default.of("Names"), PDFDict_default);
              if (!Names.has(PDFName_default.of("JavaScript"))) {
                Names.set(PDFName_default.of("JavaScript"), context.obj({}));
              }
              Javascript = Names.lookup(PDFName_default.of("JavaScript"), PDFDict_default);
              if (!Javascript.has(PDFName_default.of("Names"))) {
                Javascript.set(PDFName_default.of("Names"), context.obj([]));
              }
              JSNames = Javascript.lookup(PDFName_default.of("Names"), PDFArray_default);
              JSNames.push(PDFHexString_default.fromText(this.embedder.scriptName));
              JSNames.push(ref);
              this.alreadyEmbedded = true;
              _b.label = 2;
            case 2:
              return [
                2
                /*return*/
              ];
          }
        });
      });
    };
    PDFJavaScript2.of = function(ref, doc, embedder) {
      return new PDFJavaScript2(ref, doc, embedder);
    };
    return PDFJavaScript2;
  }()
);
var PDFJavaScript_default = PDFJavaScript;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/core/embedders/JavaScriptEmbedder.js
var JavaScriptEmbedder = (
  /** @class */
  function() {
    function JavaScriptEmbedder2(script, scriptName) {
      this.script = script;
      this.scriptName = scriptName;
    }
    JavaScriptEmbedder2.for = function(script, scriptName) {
      return new JavaScriptEmbedder2(script, scriptName);
    };
    JavaScriptEmbedder2.prototype.embedIntoContext = function(context, ref) {
      return __awaiter(this, void 0, void 0, function() {
        var jsActionDict;
        return __generator(this, function(_a) {
          jsActionDict = context.obj({
            Type: "Action",
            S: "JavaScript",
            JS: PDFHexString_default.fromText(this.script)
          });
          if (ref) {
            context.assign(ref, jsActionDict);
            return [2, ref];
          } else {
            return [2, context.register(jsActionDict)];
          }
          return [
            2
            /*return*/
          ];
        });
      });
    };
    return JavaScriptEmbedder2;
  }()
);
var JavaScriptEmbedder_default = JavaScriptEmbedder;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/api/PDFDocument.js
var PDFDocument = (
  /** @class */
  function() {
    function PDFDocument2(context, ignoreEncryption, updateMetadata) {
      var _this = this;
      this.defaultWordBreaks = [" "];
      this.computePages = function() {
        var pages = [];
        _this.catalog.Pages().traverse(function(node, ref) {
          if (node instanceof PDFPageLeaf_default) {
            var page = _this.pageMap.get(node);
            if (!page) {
              page = PDFPage_default.of(node, ref, _this);
              _this.pageMap.set(node, page);
            }
            pages.push(page);
          }
        });
        return pages;
      };
      this.getOrCreateForm = function() {
        var acroForm = _this.catalog.getOrCreateAcroForm();
        return PDFForm_default.of(acroForm, _this);
      };
      assertIs(context, "context", [[PDFContext_default, "PDFContext"]]);
      assertIs(ignoreEncryption, "ignoreEncryption", ["boolean"]);
      this.context = context;
      this.catalog = context.lookup(context.trailerInfo.Root);
      this.isEncrypted = !!context.lookup(context.trailerInfo.Encrypt);
      this.pageCache = Cache_default.populatedBy(this.computePages);
      this.pageMap = /* @__PURE__ */ new Map();
      this.formCache = Cache_default.populatedBy(this.getOrCreateForm);
      this.fonts = [];
      this.images = [];
      this.embeddedPages = [];
      this.embeddedFiles = [];
      this.javaScripts = [];
      if (!ignoreEncryption && this.isEncrypted)
        throw new EncryptedPDFError();
      if (updateMetadata)
        this.updateInfoDict();
    }
    PDFDocument2.load = function(pdf, options) {
      if (options === void 0) {
        options = {};
      }
      return __awaiter(this, void 0, void 0, function() {
        var _a, ignoreEncryption, _b, parseSpeed, _c, throwOnInvalidObject, _d, updateMetadata, _e, capNumbers, bytes, context;
        return __generator(this, function(_f) {
          switch (_f.label) {
            case 0:
              _a = options.ignoreEncryption, ignoreEncryption = _a === void 0 ? false : _a, _b = options.parseSpeed, parseSpeed = _b === void 0 ? ParseSpeeds.Slow : _b, _c = options.throwOnInvalidObject, throwOnInvalidObject = _c === void 0 ? false : _c, _d = options.updateMetadata, updateMetadata = _d === void 0 ? true : _d, _e = options.capNumbers, capNumbers = _e === void 0 ? false : _e;
              assertIs(pdf, "pdf", ["string", Uint8Array, ArrayBuffer]);
              assertIs(ignoreEncryption, "ignoreEncryption", ["boolean"]);
              assertIs(parseSpeed, "parseSpeed", ["number"]);
              assertIs(throwOnInvalidObject, "throwOnInvalidObject", ["boolean"]);
              bytes = toUint8Array(pdf);
              return [4, PDFParser_default.forBytesWithOptions(bytes, parseSpeed, throwOnInvalidObject, capNumbers).parseDocument()];
            case 1:
              context = _f.sent();
              return [2, new PDFDocument2(context, ignoreEncryption, updateMetadata)];
          }
        });
      });
    };
    PDFDocument2.create = function(options) {
      if (options === void 0) {
        options = {};
      }
      return __awaiter(this, void 0, void 0, function() {
        var _a, updateMetadata, context, pageTree, pageTreeRef, catalog;
        return __generator(this, function(_b) {
          _a = options.updateMetadata, updateMetadata = _a === void 0 ? true : _a;
          context = PDFContext_default.create();
          pageTree = PDFPageTree_default.withContext(context);
          pageTreeRef = context.register(pageTree);
          catalog = PDFCatalog_default.withContextAndPages(context, pageTreeRef);
          context.trailerInfo.Root = context.register(catalog);
          return [2, new PDFDocument2(context, false, updateMetadata)];
        });
      });
    };
    PDFDocument2.prototype.registerFontkit = function(fontkit) {
      this.fontkit = fontkit;
    };
    PDFDocument2.prototype.getForm = function() {
      var form = this.formCache.access();
      if (form.hasXFA()) {
        console.warn("Removing XFA form data as pdf-lib does not support reading or writing XFA");
        form.deleteXFA();
      }
      return form;
    };
    PDFDocument2.prototype.getTitle = function() {
      var title = this.getInfoDict().lookup(PDFName_default.Title);
      if (!title)
        return void 0;
      assertIsLiteralOrHexString(title);
      return title.decodeText();
    };
    PDFDocument2.prototype.getAuthor = function() {
      var author = this.getInfoDict().lookup(PDFName_default.Author);
      if (!author)
        return void 0;
      assertIsLiteralOrHexString(author);
      return author.decodeText();
    };
    PDFDocument2.prototype.getSubject = function() {
      var subject = this.getInfoDict().lookup(PDFName_default.Subject);
      if (!subject)
        return void 0;
      assertIsLiteralOrHexString(subject);
      return subject.decodeText();
    };
    PDFDocument2.prototype.getKeywords = function() {
      var keywords = this.getInfoDict().lookup(PDFName_default.Keywords);
      if (!keywords)
        return void 0;
      assertIsLiteralOrHexString(keywords);
      return keywords.decodeText();
    };
    PDFDocument2.prototype.getCreator = function() {
      var creator = this.getInfoDict().lookup(PDFName_default.Creator);
      if (!creator)
        return void 0;
      assertIsLiteralOrHexString(creator);
      return creator.decodeText();
    };
    PDFDocument2.prototype.getProducer = function() {
      var producer = this.getInfoDict().lookup(PDFName_default.Producer);
      if (!producer)
        return void 0;
      assertIsLiteralOrHexString(producer);
      return producer.decodeText();
    };
    PDFDocument2.prototype.getCreationDate = function() {
      var creationDate = this.getInfoDict().lookup(PDFName_default.CreationDate);
      if (!creationDate)
        return void 0;
      assertIsLiteralOrHexString(creationDate);
      return creationDate.decodeDate();
    };
    PDFDocument2.prototype.getModificationDate = function() {
      var modificationDate = this.getInfoDict().lookup(PDFName_default.ModDate);
      if (!modificationDate)
        return void 0;
      assertIsLiteralOrHexString(modificationDate);
      return modificationDate.decodeDate();
    };
    PDFDocument2.prototype.setTitle = function(title, options) {
      assertIs(title, "title", ["string"]);
      var key = PDFName_default.of("Title");
      this.getInfoDict().set(key, PDFHexString_default.fromText(title));
      if (options === null || options === void 0 ? void 0 : options.showInWindowTitleBar) {
        var prefs = this.catalog.getOrCreateViewerPreferences();
        prefs.setDisplayDocTitle(true);
      }
    };
    PDFDocument2.prototype.setAuthor = function(author) {
      assertIs(author, "author", ["string"]);
      var key = PDFName_default.of("Author");
      this.getInfoDict().set(key, PDFHexString_default.fromText(author));
    };
    PDFDocument2.prototype.setSubject = function(subject) {
      assertIs(subject, "author", ["string"]);
      var key = PDFName_default.of("Subject");
      this.getInfoDict().set(key, PDFHexString_default.fromText(subject));
    };
    PDFDocument2.prototype.setKeywords = function(keywords) {
      assertIs(keywords, "keywords", [Array]);
      var key = PDFName_default.of("Keywords");
      this.getInfoDict().set(key, PDFHexString_default.fromText(keywords.join(" ")));
    };
    PDFDocument2.prototype.setCreator = function(creator) {
      assertIs(creator, "creator", ["string"]);
      var key = PDFName_default.of("Creator");
      this.getInfoDict().set(key, PDFHexString_default.fromText(creator));
    };
    PDFDocument2.prototype.setProducer = function(producer) {
      assertIs(producer, "creator", ["string"]);
      var key = PDFName_default.of("Producer");
      this.getInfoDict().set(key, PDFHexString_default.fromText(producer));
    };
    PDFDocument2.prototype.setLanguage = function(language) {
      assertIs(language, "language", ["string"]);
      var key = PDFName_default.of("Lang");
      this.catalog.set(key, PDFString_default.of(language));
    };
    PDFDocument2.prototype.setCreationDate = function(creationDate) {
      assertIs(creationDate, "creationDate", [[Date, "Date"]]);
      var key = PDFName_default.of("CreationDate");
      this.getInfoDict().set(key, PDFString_default.fromDate(creationDate));
    };
    PDFDocument2.prototype.setModificationDate = function(modificationDate) {
      assertIs(modificationDate, "modificationDate", [[Date, "Date"]]);
      var key = PDFName_default.of("ModDate");
      this.getInfoDict().set(key, PDFString_default.fromDate(modificationDate));
    };
    PDFDocument2.prototype.getPageCount = function() {
      if (this.pageCount === void 0)
        this.pageCount = this.getPages().length;
      return this.pageCount;
    };
    PDFDocument2.prototype.getPages = function() {
      return this.pageCache.access();
    };
    PDFDocument2.prototype.getPage = function(index) {
      var pages = this.getPages();
      assertRange(index, "index", 0, pages.length - 1);
      return pages[index];
    };
    PDFDocument2.prototype.getPageIndices = function() {
      return range(0, this.getPageCount());
    };
    PDFDocument2.prototype.removePage = function(index) {
      var pageCount = this.getPageCount();
      if (this.pageCount === 0)
        throw new RemovePageFromEmptyDocumentError();
      assertRange(index, "index", 0, pageCount - 1);
      this.catalog.removeLeafNode(index);
      this.pageCount = pageCount - 1;
    };
    PDFDocument2.prototype.addPage = function(page) {
      assertIs(page, "page", ["undefined", [PDFPage_default, "PDFPage"], Array]);
      return this.insertPage(this.getPageCount(), page);
    };
    PDFDocument2.prototype.insertPage = function(index, page) {
      var pageCount = this.getPageCount();
      assertRange(index, "index", 0, pageCount);
      assertIs(page, "page", ["undefined", [PDFPage_default, "PDFPage"], Array]);
      if (!page || Array.isArray(page)) {
        var dims = Array.isArray(page) ? page : PageSizes.A4;
        page = PDFPage_default.create(this);
        page.setSize.apply(page, dims);
      } else if (page.doc !== this) {
        throw new ForeignPageError();
      }
      var parentRef = this.catalog.insertLeafNode(page.ref, index);
      page.node.setParent(parentRef);
      this.pageMap.set(page.node, page);
      this.pageCache.invalidate();
      this.pageCount = pageCount + 1;
      return page;
    };
    PDFDocument2.prototype.copyPages = function(srcDoc, indices) {
      return __awaiter(this, void 0, void 0, function() {
        var copier, srcPages, copiedPages, idx, len, srcPage, copiedPage, ref;
        return __generator(this, function(_a) {
          switch (_a.label) {
            case 0:
              assertIs(srcDoc, "srcDoc", [[PDFDocument2, "PDFDocument"]]);
              assertIs(indices, "indices", [Array]);
              return [4, srcDoc.flush()];
            case 1:
              _a.sent();
              copier = PDFObjectCopier_default.for(srcDoc.context, this.context);
              srcPages = srcDoc.getPages();
              copiedPages = new Array(indices.length);
              for (idx = 0, len = indices.length; idx < len; idx++) {
                srcPage = srcPages[indices[idx]];
                copiedPage = copier.copy(srcPage.node);
                ref = this.context.register(copiedPage);
                copiedPages[idx] = PDFPage_default.of(copiedPage, ref, this);
              }
              return [2, copiedPages];
          }
        });
      });
    };
    PDFDocument2.prototype.copy = function() {
      return __awaiter(this, void 0, void 0, function() {
        var pdfCopy, contentPages, idx, len;
        return __generator(this, function(_a) {
          switch (_a.label) {
            case 0:
              return [4, PDFDocument2.create()];
            case 1:
              pdfCopy = _a.sent();
              return [4, pdfCopy.copyPages(this, this.getPageIndices())];
            case 2:
              contentPages = _a.sent();
              for (idx = 0, len = contentPages.length; idx < len; idx++) {
                pdfCopy.addPage(contentPages[idx]);
              }
              if (this.getAuthor() !== void 0) {
                pdfCopy.setAuthor(this.getAuthor());
              }
              if (this.getCreationDate() !== void 0) {
                pdfCopy.setCreationDate(this.getCreationDate());
              }
              if (this.getCreator() !== void 0) {
                pdfCopy.setCreator(this.getCreator());
              }
              if (this.getModificationDate() !== void 0) {
                pdfCopy.setModificationDate(this.getModificationDate());
              }
              if (this.getProducer() !== void 0) {
                pdfCopy.setProducer(this.getProducer());
              }
              if (this.getSubject() !== void 0) {
                pdfCopy.setSubject(this.getSubject());
              }
              if (this.getTitle() !== void 0) {
                pdfCopy.setTitle(this.getTitle());
              }
              pdfCopy.defaultWordBreaks = this.defaultWordBreaks;
              return [2, pdfCopy];
          }
        });
      });
    };
    PDFDocument2.prototype.addJavaScript = function(name, script) {
      assertIs(name, "name", ["string"]);
      assertIs(script, "script", ["string"]);
      var embedder = JavaScriptEmbedder_default.for(script, name);
      var ref = this.context.nextRef();
      var javaScript = PDFJavaScript_default.of(ref, this, embedder);
      this.javaScripts.push(javaScript);
    };
    PDFDocument2.prototype.attach = function(attachment, name, options) {
      if (options === void 0) {
        options = {};
      }
      return __awaiter(this, void 0, void 0, function() {
        var bytes, embedder, ref, embeddedFile;
        return __generator(this, function(_a) {
          assertIs(attachment, "attachment", ["string", Uint8Array, ArrayBuffer]);
          assertIs(name, "name", ["string"]);
          assertOrUndefined(options.mimeType, "mimeType", ["string"]);
          assertOrUndefined(options.description, "description", ["string"]);
          assertOrUndefined(options.creationDate, "options.creationDate", [Date]);
          assertOrUndefined(options.modificationDate, "options.modificationDate", [
            Date
          ]);
          assertIsOneOfOrUndefined(options.afRelationship, "options.afRelationship", AFRelationship);
          bytes = toUint8Array(attachment);
          embedder = FileEmbedder_default.for(bytes, name, options);
          ref = this.context.nextRef();
          embeddedFile = PDFEmbeddedFile_default.of(ref, this, embedder);
          this.embeddedFiles.push(embeddedFile);
          return [
            2
            /*return*/
          ];
        });
      });
    };
    PDFDocument2.prototype.embedFont = function(font, options) {
      if (options === void 0) {
        options = {};
      }
      return __awaiter(this, void 0, void 0, function() {
        var _a, subset, customName, features, embedder, bytes, fontkit, _b, ref, pdfFont;
        return __generator(this, function(_c) {
          switch (_c.label) {
            case 0:
              _a = options.subset, subset = _a === void 0 ? false : _a, customName = options.customName, features = options.features;
              assertIs(font, "font", ["string", Uint8Array, ArrayBuffer]);
              assertIs(subset, "subset", ["boolean"]);
              if (!isStandardFont(font)) return [3, 1];
              embedder = StandardFontEmbedder_default.for(font, customName);
              return [3, 7];
            case 1:
              if (!canBeConvertedToUint8Array(font)) return [3, 6];
              bytes = toUint8Array(font);
              fontkit = this.assertFontkit();
              if (!subset) return [3, 3];
              return [4, CustomFontSubsetEmbedder_default.for(fontkit, bytes, customName, features)];
            case 2:
              _b = _c.sent();
              return [3, 5];
            case 3:
              return [4, CustomFontEmbedder_default.for(fontkit, bytes, customName, features)];
            case 4:
              _b = _c.sent();
              _c.label = 5;
            case 5:
              embedder = _b;
              return [3, 7];
            case 6:
              throw new TypeError("`font` must be one of `StandardFonts | string | Uint8Array | ArrayBuffer`");
            case 7:
              ref = this.context.nextRef();
              pdfFont = PDFFont_default.of(ref, this, embedder);
              this.fonts.push(pdfFont);
              return [2, pdfFont];
          }
        });
      });
    };
    PDFDocument2.prototype.embedStandardFont = function(font, customName) {
      assertIs(font, "font", ["string"]);
      if (!isStandardFont(font)) {
        throw new TypeError("`font` must be one of type `StandardFonts`");
      }
      var embedder = StandardFontEmbedder_default.for(font, customName);
      var ref = this.context.nextRef();
      var pdfFont = PDFFont_default.of(ref, this, embedder);
      this.fonts.push(pdfFont);
      return pdfFont;
    };
    PDFDocument2.prototype.embedJpg = function(jpg) {
      return __awaiter(this, void 0, void 0, function() {
        var bytes, embedder, ref, pdfImage;
        return __generator(this, function(_a) {
          switch (_a.label) {
            case 0:
              assertIs(jpg, "jpg", ["string", Uint8Array, ArrayBuffer]);
              bytes = toUint8Array(jpg);
              return [4, JpegEmbedder_default.for(bytes)];
            case 1:
              embedder = _a.sent();
              ref = this.context.nextRef();
              pdfImage = PDFImage_default.of(ref, this, embedder);
              this.images.push(pdfImage);
              return [2, pdfImage];
          }
        });
      });
    };
    PDFDocument2.prototype.embedPng = function(png) {
      return __awaiter(this, void 0, void 0, function() {
        var bytes, embedder, ref, pdfImage;
        return __generator(this, function(_a) {
          switch (_a.label) {
            case 0:
              assertIs(png, "png", ["string", Uint8Array, ArrayBuffer]);
              bytes = toUint8Array(png);
              return [4, PngEmbedder_default.for(bytes)];
            case 1:
              embedder = _a.sent();
              ref = this.context.nextRef();
              pdfImage = PDFImage_default.of(ref, this, embedder);
              this.images.push(pdfImage);
              return [2, pdfImage];
          }
        });
      });
    };
    PDFDocument2.prototype.embedPdf = function(pdf, indices) {
      if (indices === void 0) {
        indices = [0];
      }
      return __awaiter(this, void 0, void 0, function() {
        var srcDoc, _a, srcPages;
        return __generator(this, function(_b) {
          switch (_b.label) {
            case 0:
              assertIs(pdf, "pdf", [
                "string",
                Uint8Array,
                ArrayBuffer,
                [PDFDocument2, "PDFDocument"]
              ]);
              assertIs(indices, "indices", [Array]);
              if (!(pdf instanceof PDFDocument2)) return [3, 1];
              _a = pdf;
              return [3, 3];
            case 1:
              return [4, PDFDocument2.load(pdf)];
            case 2:
              _a = _b.sent();
              _b.label = 3;
            case 3:
              srcDoc = _a;
              srcPages = pluckIndices(srcDoc.getPages(), indices);
              return [2, this.embedPages(srcPages)];
          }
        });
      });
    };
    PDFDocument2.prototype.embedPage = function(page, boundingBox, transformationMatrix) {
      return __awaiter(this, void 0, void 0, function() {
        var embeddedPage;
        return __generator(this, function(_a) {
          switch (_a.label) {
            case 0:
              assertIs(page, "page", [[PDFPage_default, "PDFPage"]]);
              return [4, this.embedPages([page], [boundingBox], [transformationMatrix])];
            case 1:
              embeddedPage = _a.sent()[0];
              return [2, embeddedPage];
          }
        });
      });
    };
    PDFDocument2.prototype.embedPages = function(pages, boundingBoxes, transformationMatrices) {
      if (boundingBoxes === void 0) {
        boundingBoxes = [];
      }
      if (transformationMatrices === void 0) {
        transformationMatrices = [];
      }
      return __awaiter(this, void 0, void 0, function() {
        var idx, len, currPage, nextPage, context, maybeCopyPage, embeddedPages, idx, len, page, box, matrix, embedder, ref;
        var _a;
        return __generator(this, function(_b) {
          switch (_b.label) {
            case 0:
              if (pages.length === 0)
                return [2, []];
              for (idx = 0, len = pages.length - 1; idx < len; idx++) {
                currPage = pages[idx];
                nextPage = pages[idx + 1];
                if (currPage.node.context !== nextPage.node.context) {
                  throw new PageEmbeddingMismatchedContextError();
                }
              }
              context = pages[0].node.context;
              maybeCopyPage = context === this.context ? function(p) {
                return p;
              } : PDFObjectCopier_default.for(context, this.context).copy;
              embeddedPages = new Array(pages.length);
              idx = 0, len = pages.length;
              _b.label = 1;
            case 1:
              if (!(idx < len)) return [3, 4];
              page = maybeCopyPage(pages[idx].node);
              box = boundingBoxes[idx];
              matrix = transformationMatrices[idx];
              return [4, PDFPageEmbedder_default.for(page, box, matrix)];
            case 2:
              embedder = _b.sent();
              ref = this.context.nextRef();
              embeddedPages[idx] = PDFEmbeddedPage_default.of(ref, this, embedder);
              _b.label = 3;
            case 3:
              idx++;
              return [3, 1];
            case 4:
              (_a = this.embeddedPages).push.apply(_a, embeddedPages);
              return [2, embeddedPages];
          }
        });
      });
    };
    PDFDocument2.prototype.flush = function() {
      return __awaiter(this, void 0, void 0, function() {
        return __generator(this, function(_a) {
          switch (_a.label) {
            case 0:
              return [4, this.embedAll(this.fonts)];
            case 1:
              _a.sent();
              return [4, this.embedAll(this.images)];
            case 2:
              _a.sent();
              return [4, this.embedAll(this.embeddedPages)];
            case 3:
              _a.sent();
              return [4, this.embedAll(this.embeddedFiles)];
            case 4:
              _a.sent();
              return [4, this.embedAll(this.javaScripts)];
            case 5:
              _a.sent();
              return [
                2
                /*return*/
              ];
          }
        });
      });
    };
    PDFDocument2.prototype.save = function(options) {
      if (options === void 0) {
        options = {};
      }
      return __awaiter(this, void 0, void 0, function() {
        var _a, useObjectStreams, _b, addDefaultPage, _c, objectsPerTick, _d, updateFieldAppearances, form, Writer;
        return __generator(this, function(_e) {
          switch (_e.label) {
            case 0:
              _a = options.useObjectStreams, useObjectStreams = _a === void 0 ? true : _a, _b = options.addDefaultPage, addDefaultPage = _b === void 0 ? true : _b, _c = options.objectsPerTick, objectsPerTick = _c === void 0 ? 50 : _c, _d = options.updateFieldAppearances, updateFieldAppearances = _d === void 0 ? true : _d;
              assertIs(useObjectStreams, "useObjectStreams", ["boolean"]);
              assertIs(addDefaultPage, "addDefaultPage", ["boolean"]);
              assertIs(objectsPerTick, "objectsPerTick", ["number"]);
              assertIs(updateFieldAppearances, "updateFieldAppearances", ["boolean"]);
              if (addDefaultPage && this.getPageCount() === 0)
                this.addPage();
              if (updateFieldAppearances) {
                form = this.formCache.getValue();
                if (form)
                  form.updateFieldAppearances();
              }
              return [4, this.flush()];
            case 1:
              _e.sent();
              Writer = useObjectStreams ? PDFStreamWriter_default : PDFWriter_default;
              return [2, Writer.forContext(this.context, objectsPerTick).serializeToBuffer()];
          }
        });
      });
    };
    PDFDocument2.prototype.saveAsBase64 = function(options) {
      if (options === void 0) {
        options = {};
      }
      return __awaiter(this, void 0, void 0, function() {
        var _a, dataUri, otherOptions, bytes, base64;
        return __generator(this, function(_b) {
          switch (_b.label) {
            case 0:
              _a = options.dataUri, dataUri = _a === void 0 ? false : _a, otherOptions = __rest(options, ["dataUri"]);
              assertIs(dataUri, "dataUri", ["boolean"]);
              return [4, this.save(otherOptions)];
            case 1:
              bytes = _b.sent();
              base64 = encodeToBase64(bytes);
              return [2, dataUri ? "data:application/pdf;base64," + base64 : base64];
          }
        });
      });
    };
    PDFDocument2.prototype.findPageForAnnotationRef = function(ref) {
      var pages = this.getPages();
      for (var idx = 0, len = pages.length; idx < len; idx++) {
        var page = pages[idx];
        var annotations = page.node.Annots();
        if ((annotations === null || annotations === void 0 ? void 0 : annotations.indexOf(ref)) !== void 0) {
          return page;
        }
      }
      return void 0;
    };
    PDFDocument2.prototype.embedAll = function(embeddables) {
      return __awaiter(this, void 0, void 0, function() {
        var idx, len;
        return __generator(this, function(_a) {
          switch (_a.label) {
            case 0:
              idx = 0, len = embeddables.length;
              _a.label = 1;
            case 1:
              if (!(idx < len)) return [3, 4];
              return [4, embeddables[idx].embed()];
            case 2:
              _a.sent();
              _a.label = 3;
            case 3:
              idx++;
              return [3, 1];
            case 4:
              return [
                2
                /*return*/
              ];
          }
        });
      });
    };
    PDFDocument2.prototype.updateInfoDict = function() {
      var pdfLib = "pdf-lib (https://github.com/Hopding/pdf-lib)";
      var now = /* @__PURE__ */ new Date();
      var info = this.getInfoDict();
      this.setProducer(pdfLib);
      this.setModificationDate(now);
      if (!info.get(PDFName_default.of("Creator")))
        this.setCreator(pdfLib);
      if (!info.get(PDFName_default.of("CreationDate")))
        this.setCreationDate(now);
    };
    PDFDocument2.prototype.getInfoDict = function() {
      var existingInfo = this.context.lookup(this.context.trailerInfo.Info);
      if (existingInfo instanceof PDFDict_default)
        return existingInfo;
      var newInfo = this.context.obj({});
      this.context.trailerInfo.Info = this.context.register(newInfo);
      return newInfo;
    };
    PDFDocument2.prototype.assertFontkit = function() {
      if (!this.fontkit)
        throw new FontkitNotRegisteredError();
      return this.fontkit;
    };
    return PDFDocument2;
  }()
);
var PDFDocument_default = PDFDocument;
function assertIsLiteralOrHexString(pdfObject) {
  if (!(pdfObject instanceof PDFHexString_default) && !(pdfObject instanceof PDFString_default)) {
    throw new UnexpectedObjectTypeError([PDFHexString_default, PDFString_default], pdfObject);
  }
}

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/api/PDFPageOptions.js
var BlendMode;
(function(BlendMode2) {
  BlendMode2["Normal"] = "Normal";
  BlendMode2["Multiply"] = "Multiply";
  BlendMode2["Screen"] = "Screen";
  BlendMode2["Overlay"] = "Overlay";
  BlendMode2["Darken"] = "Darken";
  BlendMode2["Lighten"] = "Lighten";
  BlendMode2["ColorDodge"] = "ColorDodge";
  BlendMode2["ColorBurn"] = "ColorBurn";
  BlendMode2["HardLight"] = "HardLight";
  BlendMode2["SoftLight"] = "SoftLight";
  BlendMode2["Difference"] = "Difference";
  BlendMode2["Exclusion"] = "Exclusion";
})(BlendMode || (BlendMode = {}));

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/api/PDFPage.js
var PDFPage = (
  /** @class */
  function() {
    function PDFPage2(leafNode, ref, doc) {
      this.fontSize = 24;
      this.fontColor = rgb(0, 0, 0);
      this.lineHeight = 24;
      this.x = 0;
      this.y = 0;
      assertIs(leafNode, "leafNode", [[PDFPageLeaf_default, "PDFPageLeaf"]]);
      assertIs(ref, "ref", [[PDFRef_default, "PDFRef"]]);
      assertIs(doc, "doc", [[PDFDocument_default, "PDFDocument"]]);
      this.node = leafNode;
      this.ref = ref;
      this.doc = doc;
    }
    PDFPage2.prototype.setRotation = function(angle) {
      var degreesAngle = toDegrees(angle);
      assertMultiple(degreesAngle, "degreesAngle", 90);
      this.node.set(PDFName_default.of("Rotate"), this.doc.context.obj(degreesAngle));
    };
    PDFPage2.prototype.getRotation = function() {
      var Rotate = this.node.Rotate();
      return degrees(Rotate ? Rotate.asNumber() : 0);
    };
    PDFPage2.prototype.setSize = function(width, height) {
      assertIs(width, "width", ["number"]);
      assertIs(height, "height", ["number"]);
      var mediaBox = this.getMediaBox();
      this.setMediaBox(mediaBox.x, mediaBox.y, width, height);
      var cropBox = this.getCropBox();
      var bleedBox = this.getBleedBox();
      var trimBox = this.getTrimBox();
      var artBox = this.getArtBox();
      var hasCropBox = this.node.CropBox();
      var hasBleedBox = this.node.BleedBox();
      var hasTrimBox = this.node.TrimBox();
      var hasArtBox = this.node.ArtBox();
      if (hasCropBox && rectanglesAreEqual(cropBox, mediaBox)) {
        this.setCropBox(mediaBox.x, mediaBox.y, width, height);
      }
      if (hasBleedBox && rectanglesAreEqual(bleedBox, mediaBox)) {
        this.setBleedBox(mediaBox.x, mediaBox.y, width, height);
      }
      if (hasTrimBox && rectanglesAreEqual(trimBox, mediaBox)) {
        this.setTrimBox(mediaBox.x, mediaBox.y, width, height);
      }
      if (hasArtBox && rectanglesAreEqual(artBox, mediaBox)) {
        this.setArtBox(mediaBox.x, mediaBox.y, width, height);
      }
    };
    PDFPage2.prototype.setWidth = function(width) {
      assertIs(width, "width", ["number"]);
      this.setSize(width, this.getSize().height);
    };
    PDFPage2.prototype.setHeight = function(height) {
      assertIs(height, "height", ["number"]);
      this.setSize(this.getSize().width, height);
    };
    PDFPage2.prototype.setMediaBox = function(x, y, width, height) {
      assertIs(x, "x", ["number"]);
      assertIs(y, "y", ["number"]);
      assertIs(width, "width", ["number"]);
      assertIs(height, "height", ["number"]);
      var mediaBox = this.doc.context.obj([x, y, x + width, y + height]);
      this.node.set(PDFName_default.MediaBox, mediaBox);
    };
    PDFPage2.prototype.setCropBox = function(x, y, width, height) {
      assertIs(x, "x", ["number"]);
      assertIs(y, "y", ["number"]);
      assertIs(width, "width", ["number"]);
      assertIs(height, "height", ["number"]);
      var cropBox = this.doc.context.obj([x, y, x + width, y + height]);
      this.node.set(PDFName_default.CropBox, cropBox);
    };
    PDFPage2.prototype.setBleedBox = function(x, y, width, height) {
      assertIs(x, "x", ["number"]);
      assertIs(y, "y", ["number"]);
      assertIs(width, "width", ["number"]);
      assertIs(height, "height", ["number"]);
      var bleedBox = this.doc.context.obj([x, y, x + width, y + height]);
      this.node.set(PDFName_default.BleedBox, bleedBox);
    };
    PDFPage2.prototype.setTrimBox = function(x, y, width, height) {
      assertIs(x, "x", ["number"]);
      assertIs(y, "y", ["number"]);
      assertIs(width, "width", ["number"]);
      assertIs(height, "height", ["number"]);
      var trimBox = this.doc.context.obj([x, y, x + width, y + height]);
      this.node.set(PDFName_default.TrimBox, trimBox);
    };
    PDFPage2.prototype.setArtBox = function(x, y, width, height) {
      assertIs(x, "x", ["number"]);
      assertIs(y, "y", ["number"]);
      assertIs(width, "width", ["number"]);
      assertIs(height, "height", ["number"]);
      var artBox = this.doc.context.obj([x, y, x + width, y + height]);
      this.node.set(PDFName_default.ArtBox, artBox);
    };
    PDFPage2.prototype.getSize = function() {
      var _a = this.getMediaBox(), width = _a.width, height = _a.height;
      return { width, height };
    };
    PDFPage2.prototype.getWidth = function() {
      return this.getSize().width;
    };
    PDFPage2.prototype.getHeight = function() {
      return this.getSize().height;
    };
    PDFPage2.prototype.getMediaBox = function() {
      var mediaBox = this.node.MediaBox();
      return mediaBox.asRectangle();
    };
    PDFPage2.prototype.getCropBox = function() {
      var _a;
      var cropBox = this.node.CropBox();
      return (_a = cropBox === null || cropBox === void 0 ? void 0 : cropBox.asRectangle()) !== null && _a !== void 0 ? _a : this.getMediaBox();
    };
    PDFPage2.prototype.getBleedBox = function() {
      var _a;
      var bleedBox = this.node.BleedBox();
      return (_a = bleedBox === null || bleedBox === void 0 ? void 0 : bleedBox.asRectangle()) !== null && _a !== void 0 ? _a : this.getCropBox();
    };
    PDFPage2.prototype.getTrimBox = function() {
      var _a;
      var trimBox = this.node.TrimBox();
      return (_a = trimBox === null || trimBox === void 0 ? void 0 : trimBox.asRectangle()) !== null && _a !== void 0 ? _a : this.getCropBox();
    };
    PDFPage2.prototype.getArtBox = function() {
      var _a;
      var artBox = this.node.ArtBox();
      return (_a = artBox === null || artBox === void 0 ? void 0 : artBox.asRectangle()) !== null && _a !== void 0 ? _a : this.getCropBox();
    };
    PDFPage2.prototype.translateContent = function(x, y) {
      assertIs(x, "x", ["number"]);
      assertIs(y, "y", ["number"]);
      this.node.normalize();
      this.getContentStream();
      var start = this.createContentStream(pushGraphicsState(), translate(x, y));
      var startRef = this.doc.context.register(start);
      var end = this.createContentStream(popGraphicsState());
      var endRef = this.doc.context.register(end);
      this.node.wrapContentStreams(startRef, endRef);
    };
    PDFPage2.prototype.scale = function(x, y) {
      assertIs(x, "x", ["number"]);
      assertIs(y, "y", ["number"]);
      this.setSize(this.getWidth() * x, this.getHeight() * y);
      this.scaleContent(x, y);
      this.scaleAnnotations(x, y);
    };
    PDFPage2.prototype.scaleContent = function(x, y) {
      assertIs(x, "x", ["number"]);
      assertIs(y, "y", ["number"]);
      this.node.normalize();
      this.getContentStream();
      var start = this.createContentStream(pushGraphicsState(), scale(x, y));
      var startRef = this.doc.context.register(start);
      var end = this.createContentStream(popGraphicsState());
      var endRef = this.doc.context.register(end);
      this.node.wrapContentStreams(startRef, endRef);
    };
    PDFPage2.prototype.scaleAnnotations = function(x, y) {
      assertIs(x, "x", ["number"]);
      assertIs(y, "y", ["number"]);
      var annots = this.node.Annots();
      if (!annots)
        return;
      for (var idx = 0; idx < annots.size(); idx++) {
        var annot = annots.lookup(idx);
        if (annot instanceof PDFDict_default)
          this.scaleAnnot(annot, x, y);
      }
    };
    PDFPage2.prototype.resetPosition = function() {
      this.getContentStream(false);
      this.x = 0;
      this.y = 0;
    };
    PDFPage2.prototype.setFont = function(font) {
      assertIs(font, "font", [[PDFFont_default, "PDFFont"]]);
      this.font = font;
      this.fontKey = this.node.newFontDictionary(this.font.name, this.font.ref);
    };
    PDFPage2.prototype.setFontSize = function(fontSize) {
      assertIs(fontSize, "fontSize", ["number"]);
      this.fontSize = fontSize;
    };
    PDFPage2.prototype.setFontColor = function(fontColor) {
      assertIs(fontColor, "fontColor", [[Object, "Color"]]);
      this.fontColor = fontColor;
    };
    PDFPage2.prototype.setLineHeight = function(lineHeight) {
      assertIs(lineHeight, "lineHeight", ["number"]);
      this.lineHeight = lineHeight;
    };
    PDFPage2.prototype.getPosition = function() {
      return { x: this.x, y: this.y };
    };
    PDFPage2.prototype.getX = function() {
      return this.x;
    };
    PDFPage2.prototype.getY = function() {
      return this.y;
    };
    PDFPage2.prototype.moveTo = function(x, y) {
      assertIs(x, "x", ["number"]);
      assertIs(y, "y", ["number"]);
      this.x = x;
      this.y = y;
    };
    PDFPage2.prototype.moveDown = function(yDecrease) {
      assertIs(yDecrease, "yDecrease", ["number"]);
      this.y -= yDecrease;
    };
    PDFPage2.prototype.moveUp = function(yIncrease) {
      assertIs(yIncrease, "yIncrease", ["number"]);
      this.y += yIncrease;
    };
    PDFPage2.prototype.moveLeft = function(xDecrease) {
      assertIs(xDecrease, "xDecrease", ["number"]);
      this.x -= xDecrease;
    };
    PDFPage2.prototype.moveRight = function(xIncrease) {
      assertIs(xIncrease, "xIncrease", ["number"]);
      this.x += xIncrease;
    };
    PDFPage2.prototype.pushOperators = function() {
      var operator = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        operator[_i] = arguments[_i];
      }
      assertEachIs(operator, "operator", [[PDFOperator_default, "PDFOperator"]]);
      var contentStream = this.getContentStream();
      contentStream.push.apply(contentStream, operator);
    };
    PDFPage2.prototype.drawText = function(text, options) {
      var _a, _b, _c, _d, _e, _f, _g;
      if (options === void 0) {
        options = {};
      }
      assertIs(text, "text", ["string"]);
      assertOrUndefined(options.color, "options.color", [[Object, "Color"]]);
      assertRangeOrUndefined(options.opacity, "opacity.opacity", 0, 1);
      assertOrUndefined(options.font, "options.font", [[PDFFont_default, "PDFFont"]]);
      assertOrUndefined(options.size, "options.size", ["number"]);
      assertOrUndefined(options.rotate, "options.rotate", [[Object, "Rotation"]]);
      assertOrUndefined(options.xSkew, "options.xSkew", [[Object, "Rotation"]]);
      assertOrUndefined(options.ySkew, "options.ySkew", [[Object, "Rotation"]]);
      assertOrUndefined(options.x, "options.x", ["number"]);
      assertOrUndefined(options.y, "options.y", ["number"]);
      assertOrUndefined(options.lineHeight, "options.lineHeight", ["number"]);
      assertOrUndefined(options.maxWidth, "options.maxWidth", ["number"]);
      assertOrUndefined(options.wordBreaks, "options.wordBreaks", [Array]);
      assertIsOneOfOrUndefined(options.blendMode, "options.blendMode", BlendMode);
      var _h = this.setOrEmbedFont(options.font), oldFont = _h.oldFont, newFont = _h.newFont, newFontKey = _h.newFontKey;
      var fontSize = options.size || this.fontSize;
      var wordBreaks = options.wordBreaks || this.doc.defaultWordBreaks;
      var textWidth = function(t) {
        return newFont.widthOfTextAtSize(t, fontSize);
      };
      var lines = options.maxWidth === void 0 ? lineSplit(cleanText(text)) : breakTextIntoLines(text, wordBreaks, options.maxWidth, textWidth);
      var encodedLines = new Array(lines.length);
      for (var idx = 0, len = lines.length; idx < len; idx++) {
        encodedLines[idx] = newFont.encodeText(lines[idx]);
      }
      var graphicsStateKey = this.maybeEmbedGraphicsState({
        opacity: options.opacity,
        blendMode: options.blendMode
      });
      var contentStream = this.getContentStream();
      contentStream.push.apply(contentStream, drawLinesOfText(encodedLines, {
        color: (_a = options.color) !== null && _a !== void 0 ? _a : this.fontColor,
        font: newFontKey,
        size: fontSize,
        rotate: (_b = options.rotate) !== null && _b !== void 0 ? _b : degrees(0),
        xSkew: (_c = options.xSkew) !== null && _c !== void 0 ? _c : degrees(0),
        ySkew: (_d = options.ySkew) !== null && _d !== void 0 ? _d : degrees(0),
        x: (_e = options.x) !== null && _e !== void 0 ? _e : this.x,
        y: (_f = options.y) !== null && _f !== void 0 ? _f : this.y,
        lineHeight: (_g = options.lineHeight) !== null && _g !== void 0 ? _g : this.lineHeight,
        graphicsState: graphicsStateKey
      }));
      if (options.font) {
        if (oldFont)
          this.setFont(oldFont);
        else
          this.resetFont();
      }
    };
    PDFPage2.prototype.drawImage = function(image, options) {
      var _a, _b, _c, _d, _e, _f, _g;
      if (options === void 0) {
        options = {};
      }
      assertIs(image, "image", [[PDFImage_default, "PDFImage"]]);
      assertOrUndefined(options.x, "options.x", ["number"]);
      assertOrUndefined(options.y, "options.y", ["number"]);
      assertOrUndefined(options.width, "options.width", ["number"]);
      assertOrUndefined(options.height, "options.height", ["number"]);
      assertOrUndefined(options.rotate, "options.rotate", [[Object, "Rotation"]]);
      assertOrUndefined(options.xSkew, "options.xSkew", [[Object, "Rotation"]]);
      assertOrUndefined(options.ySkew, "options.ySkew", [[Object, "Rotation"]]);
      assertRangeOrUndefined(options.opacity, "opacity.opacity", 0, 1);
      assertIsOneOfOrUndefined(options.blendMode, "options.blendMode", BlendMode);
      var xObjectKey = this.node.newXObject("Image", image.ref);
      var graphicsStateKey = this.maybeEmbedGraphicsState({
        opacity: options.opacity,
        blendMode: options.blendMode
      });
      var contentStream = this.getContentStream();
      contentStream.push.apply(contentStream, drawImage(xObjectKey, {
        x: (_a = options.x) !== null && _a !== void 0 ? _a : this.x,
        y: (_b = options.y) !== null && _b !== void 0 ? _b : this.y,
        width: (_c = options.width) !== null && _c !== void 0 ? _c : image.size().width,
        height: (_d = options.height) !== null && _d !== void 0 ? _d : image.size().height,
        rotate: (_e = options.rotate) !== null && _e !== void 0 ? _e : degrees(0),
        xSkew: (_f = options.xSkew) !== null && _f !== void 0 ? _f : degrees(0),
        ySkew: (_g = options.ySkew) !== null && _g !== void 0 ? _g : degrees(0),
        graphicsState: graphicsStateKey
      }));
    };
    PDFPage2.prototype.drawPage = function(embeddedPage, options) {
      var _a, _b, _c, _d, _e;
      if (options === void 0) {
        options = {};
      }
      assertIs(embeddedPage, "embeddedPage", [
        [PDFEmbeddedPage_default, "PDFEmbeddedPage"]
      ]);
      assertOrUndefined(options.x, "options.x", ["number"]);
      assertOrUndefined(options.y, "options.y", ["number"]);
      assertOrUndefined(options.xScale, "options.xScale", ["number"]);
      assertOrUndefined(options.yScale, "options.yScale", ["number"]);
      assertOrUndefined(options.width, "options.width", ["number"]);
      assertOrUndefined(options.height, "options.height", ["number"]);
      assertOrUndefined(options.rotate, "options.rotate", [[Object, "Rotation"]]);
      assertOrUndefined(options.xSkew, "options.xSkew", [[Object, "Rotation"]]);
      assertOrUndefined(options.ySkew, "options.ySkew", [[Object, "Rotation"]]);
      assertRangeOrUndefined(options.opacity, "opacity.opacity", 0, 1);
      assertIsOneOfOrUndefined(options.blendMode, "options.blendMode", BlendMode);
      var xObjectKey = this.node.newXObject("EmbeddedPdfPage", embeddedPage.ref);
      var graphicsStateKey = this.maybeEmbedGraphicsState({
        opacity: options.opacity,
        blendMode: options.blendMode
      });
      var xScale = options.width !== void 0 ? options.width / embeddedPage.width : options.xScale !== void 0 ? options.xScale : 1;
      var yScale = options.height !== void 0 ? options.height / embeddedPage.height : options.yScale !== void 0 ? options.yScale : 1;
      var contentStream = this.getContentStream();
      contentStream.push.apply(contentStream, drawPage(xObjectKey, {
        x: (_a = options.x) !== null && _a !== void 0 ? _a : this.x,
        y: (_b = options.y) !== null && _b !== void 0 ? _b : this.y,
        xScale,
        yScale,
        rotate: (_c = options.rotate) !== null && _c !== void 0 ? _c : degrees(0),
        xSkew: (_d = options.xSkew) !== null && _d !== void 0 ? _d : degrees(0),
        ySkew: (_e = options.ySkew) !== null && _e !== void 0 ? _e : degrees(0),
        graphicsState: graphicsStateKey
      }));
    };
    PDFPage2.prototype.drawSvgPath = function(path3, options) {
      var _a, _b, _c, _d, _e, _f, _g, _h, _j;
      if (options === void 0) {
        options = {};
      }
      assertIs(path3, "path", ["string"]);
      assertOrUndefined(options.x, "options.x", ["number"]);
      assertOrUndefined(options.y, "options.y", ["number"]);
      assertOrUndefined(options.scale, "options.scale", ["number"]);
      assertOrUndefined(options.rotate, "options.rotate", [[Object, "Rotation"]]);
      assertOrUndefined(options.borderWidth, "options.borderWidth", ["number"]);
      assertOrUndefined(options.color, "options.color", [[Object, "Color"]]);
      assertRangeOrUndefined(options.opacity, "opacity.opacity", 0, 1);
      assertOrUndefined(options.borderColor, "options.borderColor", [
        [Object, "Color"]
      ]);
      assertOrUndefined(options.borderDashArray, "options.borderDashArray", [
        Array
      ]);
      assertOrUndefined(options.borderDashPhase, "options.borderDashPhase", [
        "number"
      ]);
      assertIsOneOfOrUndefined(options.borderLineCap, "options.borderLineCap", LineCapStyle);
      assertRangeOrUndefined(options.borderOpacity, "options.borderOpacity", 0, 1);
      assertIsOneOfOrUndefined(options.blendMode, "options.blendMode", BlendMode);
      var graphicsStateKey = this.maybeEmbedGraphicsState({
        opacity: options.opacity,
        borderOpacity: options.borderOpacity,
        blendMode: options.blendMode
      });
      if (!("color" in options) && !("borderColor" in options)) {
        options.borderColor = rgb(0, 0, 0);
      }
      var contentStream = this.getContentStream();
      contentStream.push.apply(contentStream, drawSvgPath(path3, {
        x: (_a = options.x) !== null && _a !== void 0 ? _a : this.x,
        y: (_b = options.y) !== null && _b !== void 0 ? _b : this.y,
        scale: options.scale,
        rotate: (_c = options.rotate) !== null && _c !== void 0 ? _c : degrees(0),
        color: (_d = options.color) !== null && _d !== void 0 ? _d : void 0,
        borderColor: (_e = options.borderColor) !== null && _e !== void 0 ? _e : void 0,
        borderWidth: (_f = options.borderWidth) !== null && _f !== void 0 ? _f : 0,
        borderDashArray: (_g = options.borderDashArray) !== null && _g !== void 0 ? _g : void 0,
        borderDashPhase: (_h = options.borderDashPhase) !== null && _h !== void 0 ? _h : void 0,
        borderLineCap: (_j = options.borderLineCap) !== null && _j !== void 0 ? _j : void 0,
        graphicsState: graphicsStateKey
      }));
    };
    PDFPage2.prototype.drawLine = function(options) {
      var _a, _b, _c, _d, _e;
      assertIs(options.start, "options.start", [
        [Object, "{ x: number, y: number }"]
      ]);
      assertIs(options.end, "options.end", [
        [Object, "{ x: number, y: number }"]
      ]);
      assertIs(options.start.x, "options.start.x", ["number"]);
      assertIs(options.start.y, "options.start.y", ["number"]);
      assertIs(options.end.x, "options.end.x", ["number"]);
      assertIs(options.end.y, "options.end.y", ["number"]);
      assertOrUndefined(options.thickness, "options.thickness", ["number"]);
      assertOrUndefined(options.color, "options.color", [[Object, "Color"]]);
      assertOrUndefined(options.dashArray, "options.dashArray", [Array]);
      assertOrUndefined(options.dashPhase, "options.dashPhase", ["number"]);
      assertIsOneOfOrUndefined(options.lineCap, "options.lineCap", LineCapStyle);
      assertRangeOrUndefined(options.opacity, "opacity.opacity", 0, 1);
      assertIsOneOfOrUndefined(options.blendMode, "options.blendMode", BlendMode);
      var graphicsStateKey = this.maybeEmbedGraphicsState({
        borderOpacity: options.opacity,
        blendMode: options.blendMode
      });
      if (!("color" in options)) {
        options.color = rgb(0, 0, 0);
      }
      var contentStream = this.getContentStream();
      contentStream.push.apply(contentStream, drawLine({
        start: options.start,
        end: options.end,
        thickness: (_a = options.thickness) !== null && _a !== void 0 ? _a : 1,
        color: (_b = options.color) !== null && _b !== void 0 ? _b : void 0,
        dashArray: (_c = options.dashArray) !== null && _c !== void 0 ? _c : void 0,
        dashPhase: (_d = options.dashPhase) !== null && _d !== void 0 ? _d : void 0,
        lineCap: (_e = options.lineCap) !== null && _e !== void 0 ? _e : void 0,
        graphicsState: graphicsStateKey
      }));
    };
    PDFPage2.prototype.drawRectangle = function(options) {
      var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
      if (options === void 0) {
        options = {};
      }
      assertOrUndefined(options.x, "options.x", ["number"]);
      assertOrUndefined(options.y, "options.y", ["number"]);
      assertOrUndefined(options.width, "options.width", ["number"]);
      assertOrUndefined(options.height, "options.height", ["number"]);
      assertOrUndefined(options.rotate, "options.rotate", [[Object, "Rotation"]]);
      assertOrUndefined(options.xSkew, "options.xSkew", [[Object, "Rotation"]]);
      assertOrUndefined(options.ySkew, "options.ySkew", [[Object, "Rotation"]]);
      assertOrUndefined(options.borderWidth, "options.borderWidth", ["number"]);
      assertOrUndefined(options.color, "options.color", [[Object, "Color"]]);
      assertRangeOrUndefined(options.opacity, "opacity.opacity", 0, 1);
      assertOrUndefined(options.borderColor, "options.borderColor", [
        [Object, "Color"]
      ]);
      assertOrUndefined(options.borderDashArray, "options.borderDashArray", [
        Array
      ]);
      assertOrUndefined(options.borderDashPhase, "options.borderDashPhase", [
        "number"
      ]);
      assertIsOneOfOrUndefined(options.borderLineCap, "options.borderLineCap", LineCapStyle);
      assertRangeOrUndefined(options.borderOpacity, "options.borderOpacity", 0, 1);
      assertIsOneOfOrUndefined(options.blendMode, "options.blendMode", BlendMode);
      var graphicsStateKey = this.maybeEmbedGraphicsState({
        opacity: options.opacity,
        borderOpacity: options.borderOpacity,
        blendMode: options.blendMode
      });
      if (!("color" in options) && !("borderColor" in options)) {
        options.color = rgb(0, 0, 0);
      }
      var contentStream = this.getContentStream();
      contentStream.push.apply(contentStream, drawRectangle({
        x: (_a = options.x) !== null && _a !== void 0 ? _a : this.x,
        y: (_b = options.y) !== null && _b !== void 0 ? _b : this.y,
        width: (_c = options.width) !== null && _c !== void 0 ? _c : 150,
        height: (_d = options.height) !== null && _d !== void 0 ? _d : 100,
        rotate: (_e = options.rotate) !== null && _e !== void 0 ? _e : degrees(0),
        xSkew: (_f = options.xSkew) !== null && _f !== void 0 ? _f : degrees(0),
        ySkew: (_g = options.ySkew) !== null && _g !== void 0 ? _g : degrees(0),
        borderWidth: (_h = options.borderWidth) !== null && _h !== void 0 ? _h : 0,
        color: (_j = options.color) !== null && _j !== void 0 ? _j : void 0,
        borderColor: (_k = options.borderColor) !== null && _k !== void 0 ? _k : void 0,
        borderDashArray: (_l = options.borderDashArray) !== null && _l !== void 0 ? _l : void 0,
        borderDashPhase: (_m = options.borderDashPhase) !== null && _m !== void 0 ? _m : void 0,
        graphicsState: graphicsStateKey,
        borderLineCap: (_o = options.borderLineCap) !== null && _o !== void 0 ? _o : void 0
      }));
    };
    PDFPage2.prototype.drawSquare = function(options) {
      if (options === void 0) {
        options = {};
      }
      var size = options.size;
      assertOrUndefined(size, "size", ["number"]);
      this.drawRectangle(__assign(__assign({}, options), { width: size, height: size }));
    };
    PDFPage2.prototype.drawEllipse = function(options) {
      var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
      if (options === void 0) {
        options = {};
      }
      assertOrUndefined(options.x, "options.x", ["number"]);
      assertOrUndefined(options.y, "options.y", ["number"]);
      assertOrUndefined(options.xScale, "options.xScale", ["number"]);
      assertOrUndefined(options.yScale, "options.yScale", ["number"]);
      assertOrUndefined(options.rotate, "options.rotate", [[Object, "Rotation"]]);
      assertOrUndefined(options.color, "options.color", [[Object, "Color"]]);
      assertRangeOrUndefined(options.opacity, "opacity.opacity", 0, 1);
      assertOrUndefined(options.borderColor, "options.borderColor", [
        [Object, "Color"]
      ]);
      assertRangeOrUndefined(options.borderOpacity, "options.borderOpacity", 0, 1);
      assertOrUndefined(options.borderWidth, "options.borderWidth", ["number"]);
      assertOrUndefined(options.borderDashArray, "options.borderDashArray", [
        Array
      ]);
      assertOrUndefined(options.borderDashPhase, "options.borderDashPhase", [
        "number"
      ]);
      assertIsOneOfOrUndefined(options.borderLineCap, "options.borderLineCap", LineCapStyle);
      assertIsOneOfOrUndefined(options.blendMode, "options.blendMode", BlendMode);
      var graphicsStateKey = this.maybeEmbedGraphicsState({
        opacity: options.opacity,
        borderOpacity: options.borderOpacity,
        blendMode: options.blendMode
      });
      if (!("color" in options) && !("borderColor" in options)) {
        options.color = rgb(0, 0, 0);
      }
      var contentStream = this.getContentStream();
      contentStream.push.apply(contentStream, drawEllipse({
        x: (_a = options.x) !== null && _a !== void 0 ? _a : this.x,
        y: (_b = options.y) !== null && _b !== void 0 ? _b : this.y,
        xScale: (_c = options.xScale) !== null && _c !== void 0 ? _c : 100,
        yScale: (_d = options.yScale) !== null && _d !== void 0 ? _d : 100,
        rotate: (_e = options.rotate) !== null && _e !== void 0 ? _e : void 0,
        color: (_f = options.color) !== null && _f !== void 0 ? _f : void 0,
        borderColor: (_g = options.borderColor) !== null && _g !== void 0 ? _g : void 0,
        borderWidth: (_h = options.borderWidth) !== null && _h !== void 0 ? _h : 0,
        borderDashArray: (_j = options.borderDashArray) !== null && _j !== void 0 ? _j : void 0,
        borderDashPhase: (_k = options.borderDashPhase) !== null && _k !== void 0 ? _k : void 0,
        borderLineCap: (_l = options.borderLineCap) !== null && _l !== void 0 ? _l : void 0,
        graphicsState: graphicsStateKey
      }));
    };
    PDFPage2.prototype.drawCircle = function(options) {
      if (options === void 0) {
        options = {};
      }
      var _a = options.size, size = _a === void 0 ? 100 : _a;
      assertOrUndefined(size, "size", ["number"]);
      this.drawEllipse(__assign(__assign({}, options), { xScale: size, yScale: size }));
    };
    PDFPage2.prototype.setOrEmbedFont = function(font) {
      var oldFont = this.font;
      var oldFontKey = this.fontKey;
      if (font)
        this.setFont(font);
      else
        this.getFont();
      var newFont = this.font;
      var newFontKey = this.fontKey;
      return { oldFont, oldFontKey, newFont, newFontKey };
    };
    PDFPage2.prototype.getFont = function() {
      if (!this.font || !this.fontKey) {
        var font = this.doc.embedStandardFont(StandardFonts.Helvetica);
        this.setFont(font);
      }
      return [this.font, this.fontKey];
    };
    PDFPage2.prototype.resetFont = function() {
      this.font = void 0;
      this.fontKey = void 0;
    };
    PDFPage2.prototype.getContentStream = function(useExisting) {
      if (useExisting === void 0) {
        useExisting = true;
      }
      if (useExisting && this.contentStream)
        return this.contentStream;
      this.contentStream = this.createContentStream();
      this.contentStreamRef = this.doc.context.register(this.contentStream);
      this.node.addContentStream(this.contentStreamRef);
      return this.contentStream;
    };
    PDFPage2.prototype.createContentStream = function() {
      var operators = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        operators[_i] = arguments[_i];
      }
      var dict = this.doc.context.obj({});
      var contentStream = PDFContentStream_default.of(dict, operators);
      return contentStream;
    };
    PDFPage2.prototype.maybeEmbedGraphicsState = function(options) {
      var opacity = options.opacity, borderOpacity = options.borderOpacity, blendMode = options.blendMode;
      if (opacity === void 0 && borderOpacity === void 0 && blendMode === void 0) {
        return void 0;
      }
      var graphicsState = this.doc.context.obj({
        Type: "ExtGState",
        ca: opacity,
        CA: borderOpacity,
        BM: blendMode
      });
      var key = this.node.newExtGState("GS", graphicsState);
      return key;
    };
    PDFPage2.prototype.scaleAnnot = function(annot, x, y) {
      var selectors = ["RD", "CL", "Vertices", "QuadPoints", "L", "Rect"];
      for (var idx = 0, len = selectors.length; idx < len; idx++) {
        var list = annot.lookup(PDFName_default.of(selectors[idx]));
        if (list instanceof PDFArray_default)
          list.scalePDFNumbers(x, y);
      }
      var inkLists = annot.lookup(PDFName_default.of("InkList"));
      if (inkLists instanceof PDFArray_default) {
        for (var idx = 0, len = inkLists.size(); idx < len; idx++) {
          var arr = inkLists.lookup(idx);
          if (arr instanceof PDFArray_default)
            arr.scalePDFNumbers(x, y);
        }
      }
    };
    PDFPage2.of = function(leafNode, ref, doc) {
      return new PDFPage2(leafNode, ref, doc);
    };
    PDFPage2.create = function(doc) {
      assertIs(doc, "doc", [[PDFDocument_default, "PDFDocument"]]);
      var dummyRef = PDFRef_default.of(-1);
      var pageLeaf = PDFPageLeaf_default.withContextAndParent(doc.context, dummyRef);
      var pageRef = doc.context.register(pageLeaf);
      return new PDFPage2(pageLeaf, pageRef, doc);
    };
    return PDFPage2;
  }()
);
var PDFPage_default = PDFPage;

// node_modules/.pnpm/pdf-lib@1.17.1/node_modules/pdf-lib/es/api/form/PDFButton.js
var PDFButton = (
  /** @class */
  function(_super) {
    __extends(PDFButton2, _super);
    function PDFButton2(acroPushButton, ref, doc) {
      var _this = _super.call(this, acroPushButton, ref, doc) || this;
      assertIs(acroPushButton, "acroButton", [
        [PDFAcroPushButton_default, "PDFAcroPushButton"]
      ]);
      _this.acroField = acroPushButton;
      return _this;
    }
    PDFButton2.prototype.setImage = function(image, alignment) {
      if (alignment === void 0) {
        alignment = ImageAlignment.Center;
      }
      var widgets = this.acroField.getWidgets();
      for (var idx = 0, len = widgets.length; idx < len; idx++) {
        var widget = widgets[idx];
        var streamRef = this.createImageAppearanceStream(widget, image, alignment);
        this.updateWidgetAppearances(widget, { normal: streamRef });
      }
      this.markAsClean();
    };
    PDFButton2.prototype.setFontSize = function(fontSize) {
      assertPositive(fontSize, "fontSize");
      this.acroField.setFontSize(fontSize);
      this.markAsDirty();
    };
    PDFButton2.prototype.addToPage = function(text, page, options) {
      var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
      assertOrUndefined(text, "text", ["string"]);
      assertOrUndefined(page, "page", [[PDFPage_default, "PDFPage"]]);
      assertFieldAppearanceOptions(options);
      var widget = this.createWidget({
        x: ((_a = options === null || options === void 0 ? void 0 : options.x) !== null && _a !== void 0 ? _a : 0) - ((_b = options === null || options === void 0 ? void 0 : options.borderWidth) !== null && _b !== void 0 ? _b : 0) / 2,
        y: ((_c = options === null || options === void 0 ? void 0 : options.y) !== null && _c !== void 0 ? _c : 0) - ((_d = options === null || options === void 0 ? void 0 : options.borderWidth) !== null && _d !== void 0 ? _d : 0) / 2,
        width: (_e = options === null || options === void 0 ? void 0 : options.width) !== null && _e !== void 0 ? _e : 100,
        height: (_f = options === null || options === void 0 ? void 0 : options.height) !== null && _f !== void 0 ? _f : 50,
        textColor: (_g = options === null || options === void 0 ? void 0 : options.textColor) !== null && _g !== void 0 ? _g : rgb(0, 0, 0),
        backgroundColor: (_h = options === null || options === void 0 ? void 0 : options.backgroundColor) !== null && _h !== void 0 ? _h : rgb(0.75, 0.75, 0.75),
        borderColor: options === null || options === void 0 ? void 0 : options.borderColor,
        borderWidth: (_j = options === null || options === void 0 ? void 0 : options.borderWidth) !== null && _j !== void 0 ? _j : 0,
        rotate: (_k = options === null || options === void 0 ? void 0 : options.rotate) !== null && _k !== void 0 ? _k : degrees(0),
        caption: text,
        hidden: options === null || options === void 0 ? void 0 : options.hidden,
        page: page.ref
      });
      var widgetRef = this.doc.context.register(widget.dict);
      this.acroField.addWidget(widgetRef);
      var font = (_l = options === null || options === void 0 ? void 0 : options.font) !== null && _l !== void 0 ? _l : this.doc.getForm().getDefaultFont();
      this.updateWidgetAppearance(widget, font);
      page.node.addAnnot(widgetRef);
    };
    PDFButton2.prototype.needsAppearancesUpdate = function() {
      var _a;
      if (this.isDirty())
        return true;
      var widgets = this.acroField.getWidgets();
      for (var idx = 0, len = widgets.length; idx < len; idx++) {
        var widget = widgets[idx];
        var hasAppearances = ((_a = widget.getAppearances()) === null || _a === void 0 ? void 0 : _a.normal) instanceof PDFStream_default;
        if (!hasAppearances)
          return true;
      }
      return false;
    };
    PDFButton2.prototype.defaultUpdateAppearances = function(font) {
      assertIs(font, "font", [[PDFFont_default, "PDFFont"]]);
      this.updateAppearances(font);
    };
    PDFButton2.prototype.updateAppearances = function(font, provider) {
      assertIs(font, "font", [[PDFFont_default, "PDFFont"]]);
      assertOrUndefined(provider, "provider", [Function]);
      var widgets = this.acroField.getWidgets();
      for (var idx = 0, len = widgets.length; idx < len; idx++) {
        var widget = widgets[idx];
        this.updateWidgetAppearance(widget, font, provider);
      }
    };
    PDFButton2.prototype.updateWidgetAppearance = function(widget, font, provider) {
      var apProvider = provider !== null && provider !== void 0 ? provider : defaultButtonAppearanceProvider;
      var appearances = normalizeAppearance(apProvider(this, widget, font));
      this.updateWidgetAppearanceWithFont(widget, font, appearances);
    };
    PDFButton2.of = function(acroPushButton, ref, doc) {
      return new PDFButton2(acroPushButton, ref, doc);
    };
    return PDFButton2;
  }(PDFField_default)
);
var PDFButton_default = PDFButton;

// src/utils.ts
var import_obsidian = require("obsidian");
var TreeNode = class {
  constructor(key, title, level) {
    this.children = [];
    this.key = key;
    this.title = title;
    this.level = level;
    this.children = [];
  }
};
function getHeadingTree(doc = document) {
  const headings = doc.querySelectorAll("h1, h2, h3, h4, h5, h6");
  const root = new TreeNode("", "Root", 0);
  let prev = root;
  headings.forEach((heading) => {
    var _a;
    if (heading.style.display == "none") {
      return;
    }
    const level = parseInt(heading.tagName.slice(1));
    const link = heading.querySelector("a.md-print-anchor");
    const regexMatch = /^af:\/\/(.+)$/.exec((_a = link == null ? void 0 : link.href) != null ? _a : "");
    if (!regexMatch) {
      return;
    }
    const newNode = new TreeNode(regexMatch[1], heading.innerText, level);
    while (prev.level >= level) {
      prev = prev.parent;
    }
    prev.children.push(newNode);
    newNode.parent = prev;
    prev = newNode;
  });
  return root;
}
function modifyDest(doc) {
  const data = /* @__PURE__ */ new Map();
  doc.querySelectorAll("h1, h2, h3, h4, h5, h6").forEach((heading, i) => {
    const link = document.createElement("a");
    const flag3 = `${heading.tagName.toLowerCase()}-${i}`;
    link.href = `af://${flag3}`;
    link.className = "md-print-anchor";
    heading.appendChild(link);
    data.set(heading.dataset.heading, flag3);
  });
  return data;
}
function convertMapKeysToLowercase(map) {
  return new Map(Array.from(map).map(([key, value]) => [key == null ? void 0 : key.toLowerCase(), value]));
}
function fixAnchors(doc, dest, basename) {
  const lowerDest = convertMapKeysToLowercase(dest);
  doc.querySelectorAll("a.internal-link").forEach((el, i) => {
    var _a, _b, _c;
    const [title, anchor] = (_b = (_a = el.dataset.href) == null ? void 0 : _a.split("#")) != null ? _b : [];
    if (anchor == null ? void 0 : anchor.startsWith("^")) {
      el.href = (_c = el.dataset.href) == null ? void 0 : _c.toLowerCase();
    }
    if ((anchor == null ? void 0 : anchor.length) > 0) {
      if ((title == null ? void 0 : title.length) > 0 && title != basename) {
        return;
      }
      const flag3 = dest.get(anchor) || lowerDest.get(anchor == null ? void 0 : anchor.toLowerCase());
      if (flag3 && !anchor.startsWith("^")) {
        el.href = `an://${flag3}`;
      }
    }
  });
}
var px2mm = (px2) => {
  return Math.round(px2 * 0.26458333333719);
};
var mm2px = (mm) => {
  return Math.round(mm * 3.779527559);
};
function traverseFolder(path3) {
  if (path3 instanceof import_obsidian.TFile) {
    if (path3.extension == "md") {
      return [path3];
    } else {
      return [];
    }
  }
  const arr = [];
  for (const item of path3.children) {
    arr.push(...traverseFolder(item));
  }
  return arr;
}
function copyAttributes(node, attributes) {
  Array.from(attributes).forEach((attr) => {
    node.setAttribute(attr.name, attr.value);
  });
}
function isNumber(str) {
  return !isNaN(parseFloat(str));
}

// src/pdf.ts
async function getDestPosition(pdfDoc) {
  const pages = pdfDoc.getPages();
  const links = {};
  pages.forEach((page, pageIndex) => {
    var _a, _b;
    const annotations = page.node.Annots();
    if (!annotations) {
      return;
    }
    const numAnnotations = (_a = annotations == null ? void 0 : annotations.size()) != null ? _a : 0;
    for (let annotIndex = 0; annotIndex < numAnnotations; annotIndex++) {
      try {
        const annotation = annotations.lookup(annotIndex, PDFDict_default);
        const subtype = annotation.get(PDFName_default.of("Subtype"));
        if ((subtype == null ? void 0 : subtype.toString()) === "/Link") {
          const linkDict = annotation.get(PDFName_default.of("A"));
          const uri = linkDict == null ? void 0 : linkDict.get(PDFName_default.of("URI")).toString();
          console.debug("uri", uri);
          const regexMatch = /^\(af:\/\/(.+)\)$/.exec(uri || "");
          if (regexMatch) {
            const rect = (_b = annotation.get(PDFName_default.of("Rect"))) == null ? void 0 : _b.asRectangle();
            const linkUrl = regexMatch[1];
            const yPos = rect.y;
            links[linkUrl] = [pageIndex, yPos];
          }
        }
      } catch (err) {
        console.error(err);
      }
    }
  });
  return links;
}
async function setAnchors(pdfDoc, links) {
  const pages = pdfDoc.getPages();
  pages.forEach((page, _) => {
    var _a;
    const annots = page.node.Annots();
    if (!annots) {
      return;
    }
    const numAnnotations = (_a = annots == null ? void 0 : annots.size()) != null ? _a : 0;
    for (let idx = 0; idx < numAnnotations; idx++) {
      try {
        const linkAnnotRef = annots.get(idx);
        const linkAnnot = annots.lookup(idx, PDFDict_default);
        const subtype = linkAnnot.get(PDFName_default.of("Subtype"));
        if ((subtype == null ? void 0 : subtype.toString()) === "/Link") {
          const linkDict = linkAnnot.get(PDFName_default.of("A"));
          const uri = linkDict == null ? void 0 : linkDict.get(PDFName_default.of("URI")).toString();
          console.debug("uri", uri);
          const regexMatch = /^\(an:\/\/(.+)\)$/.exec(uri || "");
          const key = regexMatch == null ? void 0 : regexMatch[1];
          if (key && (links == null ? void 0 : links[key])) {
            const [pageIdx, yPos] = links[key];
            const newAnnot = pdfDoc.context.obj({
              Type: "Annot",
              Subtype: "Link",
              Rect: linkAnnot.lookup(PDFName_default.of("Rect")),
              Border: linkAnnot.lookup(PDFName_default.of("Border")),
              C: linkAnnot.lookup(PDFName_default.of("C")),
              Dest: [pages[pageIdx].ref, "XYZ", null, yPos, null]
            });
            pdfDoc.context.assign(linkAnnotRef, newAnnot);
          }
        }
      } catch (err) {
        console.error(err);
      }
    }
  });
  return links;
}
function generateOutlines(root, positions, maxLevel = 6) {
  var _a, _b;
  const _outline = (node) => {
    var _a2, _b2;
    if (node.level > maxLevel) {
      return;
    }
    const [pageIdx, pos] = (_a2 = positions == null ? void 0 : positions[node.key]) != null ? _a2 : [0, 0];
    const outline = {
      title: node.title,
      to: [pageIdx, 0, pos],
      open: false,
      children: []
    };
    if (((_b2 = node.children) == null ? void 0 : _b2.length) > 0) {
      for (const item of node.children) {
        const child = _outline(item);
        if (child) {
          outline.children.push(child);
        }
      }
    }
    return outline;
  };
  return (_b = (_a = _outline(root)) == null ? void 0 : _a.children) != null ? _b : [];
}
var walk = (outlines, callback) => {
  for (const outline of outlines) {
    const ret = callback(outline);
    if ("children" in outline && ret !== false) walk(outline.children, callback);
  }
};
var flatten = (outlines) => {
  const result = [];
  walk(outlines, (outline) => void result.push(outline));
  return result;
};
var getOpeningCount = (outlines) => {
  let count = 0;
  walk(outlines, (outline) => {
    count += 1;
    return !("open" in outline && !outline.open);
  });
  return count;
};
var setOutline = async (doc, outlines) => {
  const rootRef = doc.context.nextRef();
  const refMap = /* @__PURE__ */ new WeakMap();
  for (const outline of flatten(outlines)) {
    refMap.set(outline, doc.context.nextRef());
  }
  const pageRefs = (() => {
    const refs = [];
    doc.catalog.Pages().traverse((kid, ref) => {
      var _a;
      if (((_a = kid.get(kid.context.obj("Type"))) == null ? void 0 : _a.toString()) === "/Page") {
        refs.push(ref);
      }
    });
    return refs;
  })();
  const createOutline = (outlines2, parent) => {
    const { length } = outlines2;
    for (let i = 0; i < length; i += 1) {
      const outline = outlines2[i];
      const outlineRef = refMap.get(outline);
      const destOrAction = (() => {
        if (typeof outline.to === "number") {
          return { Dest: [pageRefs[outline.to], "Fit"] };
        } else if (Array.isArray(outline.to)) {
          return {
            Dest: [pageRefs[outline.to[0]], "XYZ", outline.to[1], outline.to[2], null]
          };
        }
        return {};
      })();
      const childrenDict = (() => {
        if ("children" in outline && outline.children.length > 0) {
          createOutline(outline.children, outlineRef);
          return {
            First: refMap.get(outline.children[0]),
            Last: refMap.get(outline.children[outline.children.length - 1]),
            Count: getOpeningCount(outline.children) * (outline.open ? 1 : -1)
          };
        }
        return {};
      })();
      doc.context.assign(
        outlineRef,
        doc.context.obj({
          Title: PDFHexString_default.fromText(outline.title),
          Parent: parent,
          ...i > 0 ? { Prev: refMap.get(outlines2[i - 1]) } : {},
          ...i < length - 1 ? { Next: refMap.get(outlines2[i + 1]) } : {},
          ...childrenDict,
          ...destOrAction,
          F: (outline.italic ? 1 : 0) | (outline.bold ? 2 : 0)
        })
      );
    }
  };
  createOutline(outlines, rootRef);
  const rootCount = getOpeningCount(outlines);
  doc.context.assign(
    rootRef,
    doc.context.obj({
      Type: "Outlines",
      ...rootCount > 0 ? {
        First: refMap.get(outlines[0]),
        Last: refMap.get(outlines[outlines.length - 1])
      } : {},
      Count: rootCount
    })
  );
  doc.catalog.set(doc.context.obj("Outlines"), rootRef);
};
async function editPDF(data, { headings, maxLevel, frontMatter, displayMetadata }) {
  const pdfDoc = await PDFDocument_default.load(data);
  const posistions = await getDestPosition(pdfDoc);
  setAnchors(pdfDoc, posistions);
  const outlines = generateOutlines(headings, posistions, maxLevel);
  setOutline(pdfDoc, outlines);
  if (displayMetadata) {
    setMetadata(pdfDoc, frontMatter != null ? frontMatter : {});
  }
  data = await pdfDoc.save();
  return data;
}
function setMetadata(pdfDoc, { title, author, keywords, subject, creator, created_at, updated_at }) {
  if (title) {
    pdfDoc.setTitle(title, { showInWindowTitleBar: true });
  }
  if (author) {
    if (Array.isArray(author)) {
      pdfDoc.setAuthor(author.join(", "));
    } else {
      pdfDoc.setAuthor(author.toString());
    }
  }
  if (keywords) {
    pdfDoc.setKeywords(typeof keywords == "string" ? [keywords] : keywords);
  }
  if (subject) {
    pdfDoc.setSubject(subject);
  }
  pdfDoc.setCreator(creator != null ? creator : "Obsidian");
  pdfDoc.setProducer("Obsidian");
  pdfDoc.setCreationDate(new Date(created_at != null ? created_at : /* @__PURE__ */ new Date()));
  pdfDoc.setModificationDate(new Date(updated_at != null ? updated_at : /* @__PURE__ */ new Date()));
}
async function exportToPDF(outputFile, config, w, { doc, frontMatter }) {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
  console.log("output pdf:", outputFile);
  let pageSize = config["pageSize"];
  if (config["pageSize"] == "Custom" && config["pageWidth"] && config["pageHeight"]) {
    pageSize = {
      width: parseFloat((_a = config["pageWidth"]) != null ? _a : "210") / 25.4,
      height: parseFloat((_b = config["pageHeight"]) != null ? _b : "297") / 25.4
    };
  }
  let scale2 = (_c = config == null ? void 0 : config["scale"]) != null ? _c : 100;
  if (scale2 > 200 || scale2 < 10) {
    scale2 = 100;
  }
  const printOptions = {
    landscape: config == null ? void 0 : config["landscape"],
    printBackground: config == null ? void 0 : config["printBackground"],
    generateTaggedPDF: config == null ? void 0 : config["generateTaggedPDF"],
    pageSize,
    scale: scale2 / 100,
    margins: {
      marginType: "default"
    },
    displayHeaderFooter: config["displayHeader"] || config["displayFooter"],
    headerTemplate: config["displayHeader"] ? (_d = frontMatter == null ? void 0 : frontMatter["headerTemplate"]) != null ? _d : config["headerTemplate"] : "<span></span>",
    footerTemplate: config["displayFooter"] ? (_e = frontMatter == null ? void 0 : frontMatter["footerTemplate"]) != null ? _e : config["footerTemplate"] : "<span></span>"
  };
  if (config.marginType == "0") {
    printOptions["margins"] = {
      marginType: "custom",
      top: 0,
      bottom: 0,
      left: 0,
      right: 0
    };
  } else if (config.marginType == "1") {
    printOptions["margins"] = {
      marginType: "default"
    };
  } else if (config.marginType == "2") {
    printOptions["margins"] = {
      marginType: "custom",
      top: 0.1,
      bottom: 0.1,
      left: 0.1,
      right: 0.1
    };
  } else if (config.marginType == "3") {
    printOptions["margins"] = {
      marginType: "custom",
      top: parseFloat((_f = config["marginTop"]) != null ? _f : "0") / 25.4,
      bottom: parseFloat((_g = config["marginBottom"]) != null ? _g : "0") / 25.4,
      left: parseFloat((_h = config["marginLeft"]) != null ? _h : "0") / 25.4,
      right: parseFloat((_i = config["marginRight"]) != null ? _i : "0") / 25.4
    };
  }
  try {
    let data = await w.printToPDF(printOptions);
    data = await editPDF(data, {
      headings: getHeadingTree(doc),
      frontMatter,
      displayMetadata: config == null ? void 0 : config.displayMetadata,
      maxLevel: parseInt((_j = config == null ? void 0 : config.maxLevel) != null ? _j : "6")
    });
    await fs.writeFile(outputFile, data);
    if (config.open) {
      import_electron.default.remote.shell.openPath(outputFile);
    }
  } catch (error2) {
    console.error(error2);
  }
}
async function getOutputFile(filename, isTimestamp) {
  const result = await import_electron.default.remote.dialog.showSaveDialog({
    title: "Export to PDF",
    defaultPath: filename + (isTimestamp ? "-" + Date.now() : "") + ".pdf",
    filters: [
      { name: "All Files", extensions: ["*"] },
      { name: "PDF", extensions: ["pdf"] }
    ],
    properties: ["showOverwriteConfirmation", "createDirectory"]
  });
  if (result.canceled) {
    return;
  }
  return result.filePath;
}
async function getOutputPath(filename, isTimestamp) {
  const result = await import_electron.default.remote.dialog.showOpenDialog({
    title: "Export to PDF",
    defaultPath: filename,
    properties: ["openDirectory"]
  });
  if (result.canceled) {
    return;
  }
  return result.filePaths[0];
}

// src/render.ts
var import_obsidian2 = require("obsidian");
function getAllStyles() {
  const cssTexts = [];
  Array.from(document.styleSheets).forEach((sheet) => {
    var _a, _b, _c;
    const id = (_a = sheet.ownerNode) == null ? void 0 : _a.id;
    if (id == null ? void 0 : id.startsWith("svelte-")) {
      return;
    }
    const href = (_b = sheet.ownerNode) == null ? void 0 : _b.href;
    const division = `/* ----------${id ? `id:${id}` : href ? `href:${href}` : ""}---------- */`;
    cssTexts.push(division);
    try {
      Array.from((_c = sheet == null ? void 0 : sheet.cssRules) != null ? _c : []).forEach((rule) => {
        cssTexts.push(rule.cssText);
      });
    } catch (error2) {
      console.error(error2);
    }
  });
  cssTexts.push(...getPatchStyle());
  return cssTexts;
}
var CSS_PATCH = `
/* ---------- css patch ---------- */

body {
  overflow: auto !important;
}
@media print {
  .print .markdown-preview-view {
    height: auto !important;
  }
  .md-print-anchor, .blockid {
    white-space: pre !important;
    border-left: none !important;
    border-right: none !important;
    border-top: none !important;
    border-bottom: none !important;
    display: inline-block !important;
    position: absolute !important;
    width: 1px !important;
    height: 1px !important;
    right: 0 !important;
    outline: 0 !important;
    background: 0 0 !important;
    text-decoration: initial !important;
    text-shadow: initial !important;
  }
}
@media print {
  table {
    break-inside: auto;
  }
  tr {
    break-inside: avoid;
    break-after: auto;
  }
}

img.__canvas__ {
  width: 100% !important;
  height: 100% !important;
}
`;
function getPatchStyle() {
  return [CSS_PATCH, ...getPrintStyle()];
}
function getPrintStyle() {
  const cssTexts = [];
  Array.from(document.styleSheets).forEach((sheet) => {
    var _a;
    try {
      const cssRules = (_a = sheet == null ? void 0 : sheet.cssRules) != null ? _a : [];
      Array.from(cssRules).forEach((rule) => {
        if (rule.constructor.name == "CSSMediaRule") {
          if (rule.conditionText === "print") {
            const res = rule.cssText.replace(/@media print\s*\{(.+)\}/gms, "$1");
            cssTexts.push(res);
          }
        }
      });
    } catch (error2) {
      console.error(error2);
    }
  });
  return cssTexts;
}
function generateDocId(n) {
  return Array.from({ length: n }, () => (16 * Math.random() | 0).toString(16)).join("");
}
function getFrontMatter(app, file) {
  var _a;
  const cache = app.metadataCache.getFileCache(file);
  return (_a = cache == null ? void 0 : cache.frontmatter) != null ? _a : {};
}
async function renderMarkdown(app, file, config, extra) {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i;
  const startTime = (/* @__PURE__ */ new Date()).getTime();
  const ws = app.workspace;
  if (((_a = ws.getActiveFile()) == null ? void 0 : _a.path) != file.path) {
    const leaf = ws.getLeaf();
    await leaf.openFile(file);
  }
  const view = ws.getActiveViewOfType(import_obsidian2.MarkdownView);
  const data = (_e = (_c = view == null ? void 0 : view.data) != null ? _c : (_b = ws == null ? void 0 : ws.getActiveFileView()) == null ? void 0 : _b.data) != null ? _e : (_d = ws.activeEditor) == null ? void 0 : _d.data;
  if (!data) {
    new import_obsidian2.Notice("data is empty!");
  }
  const frontMatter = getFrontMatter(app, file);
  const cssclasses = [];
  for (const [key, val] of Object.entries(frontMatter)) {
    if (key.toLowerCase() == "cssclass" || key.toLowerCase() == "cssclasses") {
      if (Array.isArray(val)) {
        cssclasses.push(...val);
      } else {
        cssclasses.push(val);
      }
    }
  }
  const comp = new import_obsidian2.Component();
  comp.load();
  const printEl = document.body.createDiv("print");
  const viewEl = printEl.createDiv({
    cls: "markdown-preview-view markdown-rendered " + cssclasses.join(" ")
  });
  app.vault.cachedRead(file);
  viewEl.toggleClass("rtl", app.vault.getConfig("rightToLeft"));
  viewEl.toggleClass("show-properties", "hidden" !== app.vault.getConfig("propertiesInDocument"));
  const title = (_g = (_f = extra == null ? void 0 : extra.title) != null ? _f : frontMatter == null ? void 0 : frontMatter.title) != null ? _g : file.basename;
  viewEl.createEl("h1", { text: title }, (e) => {
    var _a2;
    e.addClass("__title__");
    e.style.display = config.showTitle ? "block" : "none";
    e.id = (_a2 = extra == null ? void 0 : extra.id) != null ? _a2 : "";
  });
  const cache = app.metadataCache.getFileCache(file);
  const blocks = new Map(Object.entries((_h = cache == null ? void 0 : cache.blocks) != null ? _h : {}));
  const lines = ((_i = data == null ? void 0 : data.split("\n")) != null ? _i : []).map((line, i) => {
    for (const {
      id,
      position: { start, end }
    } of blocks.values()) {
      const blockid = `^${id}`;
      if (line.includes(blockid) && i >= start.line && i <= end.line) {
        blocks.delete(id);
        return line.replace(blockid, `<span id="${blockid}" class="blockid"></span> ${blockid}`);
      }
    }
    return line;
  });
  [...blocks.values()].forEach(({ id, position: { start, end } }) => {
    const idx = start.line;
    lines[idx] = `<span id="^${id}" class="blockid"></span>

` + lines[idx];
  });
  const fragment = {
    children: void 0,
    appendChild(e) {
      this.children = e == null ? void 0 : e.children;
      throw new Error("exit");
    }
  };
  const promises = [];
  try {
    await import_obsidian2.MarkdownRenderer.render(app, lines.join("\n"), fragment, file.path, comp);
  } catch (error2) {
  }
  const el = createFragment();
  Array.from(fragment.children).forEach((item) => {
    el.createDiv({}, (t) => {
      return t.appendChild(item);
    });
  });
  viewEl.appendChild(el);
  await import_obsidian2.MarkdownRenderer.postProcess(app, {
    docId: generateDocId(16),
    sourcePath: file.path,
    frontmatter: {},
    promises,
    addChild: function(e) {
      return comp.addChild(e);
    },
    getSectionInfo: function() {
      return null;
    },
    containerEl: viewEl,
    el: viewEl,
    displayMode: true
  });
  await Promise.all(promises);
  printEl.findAll("a.internal-link").forEach((el2) => {
    var _a2, _b2;
    const [title2, anchor] = (_b2 = (_a2 = el2.dataset.href) == null ? void 0 : _a2.split("#")) != null ? _b2 : [];
    if ((!title2 || (title2 == null ? void 0 : title2.length) == 0 || title2 == file.basename) && (anchor == null ? void 0 : anchor.startsWith("^"))) {
      return;
    }
    el2.removeAttribute("href");
  });
  try {
    await fixWaitRender(data, viewEl);
  } catch (error2) {
    console.warn("wait timeout");
  }
  fixCanvasToImage(viewEl);
  const doc = document.implementation.createHTMLDocument("document");
  doc.body.appendChild(printEl.cloneNode(true));
  printEl.detach();
  comp.unload();
  printEl.remove();
  doc.title = title;
  console.log(`md render time:${(/* @__PURE__ */ new Date()).getTime() - startTime}ms`);
  return { doc, frontMatter, file };
}
function fixDoc(doc, title) {
  const dest = modifyDest(doc);
  fixAnchors(doc, dest, title);
  encodeEmbeds(doc);
  return doc;
}
function encodeEmbeds(doc) {
  const spans = Array.from(doc.querySelectorAll("span.markdown-embed")).reverse();
  spans.forEach((span) => span.innerHTML = encodeURIComponent(span.innerHTML));
}
async function fixWaitRender(data, viewEl) {
  if (data.includes("```dataview") || data.includes("```gEvent") || data.includes("![[")) {
    await sleep(2e3);
  }
  try {
    await waitForDomChange(viewEl);
  } catch (error2) {
    await sleep(1e3);
  }
}
function fixCanvasToImage(el) {
  for (const canvas of Array.from(el.querySelectorAll("canvas"))) {
    const data = canvas.toDataURL();
    const img = document.createElement("img");
    img.src = data;
    copyAttributes(img, canvas.attributes);
    img.className = "__canvas__";
    canvas.replaceWith(img);
  }
}
function createWebview(scale2 = 1.25) {
  const webview = document.createElement("webview");
  webview.src = `app://obsidian.md/help.html`;
  webview.setAttribute(
    "style",
    `height:calc(${scale2} * 100%);
     width: calc(${scale2} * 100%);
     transform: scale(${1 / scale2}, ${1 / scale2});
     transform-origin: top left;
     border: 1px solid #f2f2f2;
    `
  );
  webview.nodeintegration = true;
  return webview;
}
function waitForDomChange(target, timeout = 2e3, interval = 200) {
  return new Promise((resolve, reject) => {
    let timer;
    const observer = new MutationObserver((m) => {
      clearTimeout(timer);
      timer = setTimeout(() => {
        observer.disconnect();
        resolve(true);
      }, interval);
    });
    observer.observe(target, {
      childList: true,
      subtree: true,
      attributes: true,
      characterData: true
    });
    setTimeout(() => {
      observer.disconnect();
      reject(new Error(`timeout ${timeout}ms`));
    }, timeout);
  });
}

// src/modal.ts
function fullWidthButton(button) {
  button.buttonEl.setAttribute("style", `margin: "0 auto"; width: -webkit-fill-available`);
}
function setInputWidth(inputEl) {
  inputEl.setAttribute("style", `width: 100px;`);
}
var ExportConfigModal = class extends import_obsidian3.Modal {
  constructor(plugin, file, multiplePdf) {
    var _a, _b, _c, _d, _e;
    super(plugin.app);
    this.canceled = true;
    this.plugin = plugin;
    this.file = file;
    this.completed = false;
    this.i18n = i18n_default.current;
    this.docs = [];
    this.scale = 0.75;
    this.webviews = [];
    this.multiplePdf = multiplePdf;
    this.config = {
      pageSize: "A4",
      marginType: "1",
      showTitle: (_a = plugin.settings.showTitle) != null ? _a : true,
      open: true,
      scale: 100,
      landscape: false,
      marginTop: "10",
      marginBottom: "10",
      marginLeft: "10",
      marginRight: "10",
      displayHeader: (_b = plugin.settings.displayHeader) != null ? _b : true,
      displayFooter: (_c = plugin.settings.displayHeader) != null ? _c : true,
      cssSnippet: "0",
      ...(_e = (_d = plugin.settings) == null ? void 0 : _d.prevConfig) != null ? _e : {}
    };
  }
  getFileCache(file) {
    return this.app.metadataCache.getFileCache(file);
  }
  async renderFiles() {
    var _a, _b;
    const app = this.plugin.app;
    let docs = [];
    if (this.file instanceof import_obsidian3.TFolder) {
      const files = traverseFolder(this.file);
      for (const file of files) {
        docs.push(await renderMarkdown(app, file, this.config));
      }
    } else {
      const { doc, frontMatter, file } = await renderMarkdown(app, this.file, this.config);
      docs.push({ doc, frontMatter, file });
      if (frontMatter.toc) {
        const cache = this.getFileCache(this.file);
        const files = (_b = (_a = cache == null ? void 0 : cache.links) == null ? void 0 : _a.map(({ link, displayText }) => {
          const id = crypto.randomUUID();
          const elem = doc.querySelector(`a[data-href="${link}"]`);
          if (elem) {
            elem.href = `#${id}`;
          }
          return {
            title: displayText,
            file: this.app.metadataCache.getFirstLinkpathDest(link, this.file.path),
            id
          };
        }).filter((item) => item.file instanceof import_obsidian3.TFile)) != null ? _b : [];
        for (const item of files) {
          docs.push(await renderMarkdown(app, item.file, this.config, item));
        }
        const leaf = this.app.workspace.getLeaf();
        await leaf.openFile(this.file);
      }
    }
    if (!this.multiplePdf) {
      docs = this.mergeDoc(docs);
    }
    this.docs = docs.map(({ doc, ...rest }) => {
      return { ...rest, doc: fixDoc(doc, doc.title) };
    });
  }
  mergeDoc(docs) {
    const { doc: doc0, frontMatter, file } = docs[0];
    const sections = [];
    for (const { doc } of docs) {
      const element = doc.querySelector(".markdown-preview-view");
      if (element) {
        const section = doc0.createElement("section");
        Array.from(element.children).forEach((child) => {
          section.appendChild(doc0.importNode(child, true));
        });
        sections.push(section);
      }
    }
    const root = doc0.querySelector(".markdown-preview-view");
    if (root) {
      root.innerHTML = "";
    }
    sections.forEach((section) => {
      root == null ? void 0 : root.appendChild(section);
    });
    return [{ doc: doc0, frontMatter, file }];
  }
  calcPageSize(element, config) {
    var _a, _b, _c;
    const { pageSize, pageWidth } = config != null ? config : this.config;
    const el = element != null ? element : this.previewDiv;
    let width = (_c = (_b = (_a = PageSize) == null ? void 0 : _a[pageSize]) == null ? void 0 : _b[0]) != null ? _c : parseFloat(pageWidth);
    if (isNaN(width)) {
      width = 210;
    }
    const scale2 = Math.floor(mm2px(width) / el.offsetWidth * 100) / 100;
    this.webviews.forEach((wb) => {
      wb.style.transform = `scale(${1 / scale2},${1 / scale2})`;
      wb.style.width = `calc(${scale2} * 100%)`;
      wb.style.height = `calc(${scale2} * 100%)`;
    });
    this.scale = scale2;
    return scale2;
  }
  async calcWebviewSize() {
    await sleep(500);
    this.webviews.forEach(async (e, i) => {
      var _a;
      const [width, height] = await e.executeJavaScript("[document.body.offsetWidth, document.body.offsetHeight]");
      const sizeEl = (_a = e.parentNode) == null ? void 0 : _a.querySelector(".print-size");
      if (sizeEl) {
        sizeEl.innerHTML = `${width}\xD7${height}px
${px2mm(width)}\xD7${px2mm(height)}mm`;
      }
    });
  }
  async togglePrintSize() {
    var _a;
    (_a = document.querySelectorAll(".print-size")) == null ? void 0 : _a.forEach((sizeEl) => {
      if (this.config["pageSize"] == "Custom") {
        sizeEl.style.visibility = "visible";
      } else {
        sizeEl.style.visibility = "hidden";
      }
    });
  }
  makeWebviewJs(doc) {
    return `
      document.body.innerHTML = decodeURIComponent(\`${encodeURIComponent(doc.body.innerHTML)}\`);
      document.head.innerHTML = decodeURIComponent(\`${encodeURIComponent(document.head.innerHTML)}\`);
      
      // Function to recursively decode and replace innerHTML of span.markdown-embed elements
      function decodeAndReplaceEmbed(element) {
				// Replace the innerHTML with the decoded content
				element.innerHTML = decodeURIComponent(element.innerHTML);
				// Check if the new content contains further span.markdown-embed elements
				const newEmbeds = element.querySelectorAll("span.markdown-embed");
				newEmbeds.forEach(decodeAndReplaceEmbed);
      }
      
      // Start the process with all span.markdown-embed elements in the document
      document.querySelectorAll("span.markdown-embed").forEach(decodeAndReplaceEmbed);

      document.body.setAttribute("class", \`${document.body.getAttribute("class")}\`)
      document.body.setAttribute("style", \`${document.body.getAttribute("style")}\`)
      document.body.addClass("theme-light");
      document.body.removeClass("theme-dark");
      document.title = \`${doc.title}\`;
      `;
  }
  /**
   * append webview
   * @param e HTMLDivElement
   * @param render Rerender or not
   */
  async appendWebview(e, doc) {
    const webview = createWebview(this.scale);
    const preview = e.appendChild(webview);
    this.webviews.push(preview);
    this.preview = preview;
    preview.addEventListener("dom-ready", async (e2) => {
      this.completed = true;
      getAllStyles().forEach(async (css) => {
        await preview.insertCSS(css);
      });
      if (this.config.cssSnippet && this.config.cssSnippet != "0") {
        try {
          const cssSnippet = await fs2.readFile(this.config.cssSnippet, { encoding: "utf8" });
          const printCss = cssSnippet.replaceAll(/@media print\s*{([^}]+)}/g, "$1");
          await preview.insertCSS(printCss);
          await preview.insertCSS(cssSnippet);
        } catch (error2) {
          console.warn(error2);
        }
      }
      await preview.executeJavaScript(this.makeWebviewJs(doc));
      getPatchStyle().forEach(async (css) => {
        await preview.insertCSS(css);
      });
    });
  }
  async appendWebviews(e, render = true) {
    var _a;
    if (render) {
      await this.renderFiles();
    }
    e.empty();
    await Promise.all(
      (_a = this.docs) == null ? void 0 : _a.map(async ({ doc }, i) => {
        if (this.multiplePdf) {
          e.createDiv({
            text: `${i + 1}-${doc.title}`,
            attr: { class: "filename" }
          });
        }
        const div = e.createDiv({ attr: { class: "webview-wrapper" } });
        div.createDiv({ attr: { class: "print-size" } });
        await this.appendWebview(div, doc);
      })
    );
    await this.calcWebviewSize();
  }
  async onOpen() {
    var _a, _b, _c;
    this.contentEl.empty();
    this.containerEl.style.setProperty("--dialog-width", "60vw");
    this.titleEl.setText("Export to PDF");
    const wrapper = this.contentEl.createDiv({ attr: { id: "better-export-pdf" } });
    const title = (_c = (_a = this.file) == null ? void 0 : _a.basename) != null ? _c : (_b = this.file) == null ? void 0 : _b.name;
    this.previewDiv = wrapper.createDiv({ attr: { class: "pdf-preview" } }, async (el) => {
      el.empty();
      const resizeObserver = new ResizeObserver(() => {
        this.calcPageSize(el);
      });
      resizeObserver.observe(el);
      await this.appendWebviews(el);
      this.togglePrintSize();
    });
    const contentEl = wrapper.createDiv({ attr: { class: "setting-wrapper" } });
    contentEl.addEventListener("keyup", (event) => {
      if (event.key === "Enter") {
        handleExport();
      }
    });
    this.generateForm(contentEl);
    const handleExport = async () => {
      var _a2, _b2;
      this.plugin.settings.prevConfig = this.config;
      await this.plugin.saveSettings();
      if (this.config["pageSize"] == "Custom") {
        if (!isNumber((_a2 = this.config["pageWidth"]) != null ? _a2 : "") || !isNumber((_b2 = this.config["pageHeight"]) != null ? _b2 : "")) {
          alert("When the page size is Custom, the Width/Height cannot be empty.");
          return;
        }
      }
      if (this.multiplePdf) {
        const outputPath = await getOutputPath(title);
        console.log("output:", outputPath);
        if (outputPath) {
          await Promise.all(
            this.webviews.map(async (wb, i) => {
              await exportToPDF(
                `${outputPath}/${this.docs[i].file.basename}.pdf`,
                { ...this.plugin.settings, ...this.config },
                wb,
                this.docs[i]
              );
            })
          );
          this.close();
        }
      } else {
        const outputFile = await getOutputFile(title, this.plugin.settings.isTimestamp);
        if (outputFile) {
          await exportToPDF(outputFile, { ...this.plugin.settings, ...this.config }, this.webviews[0], this.docs[0]);
          this.close();
        }
      }
    };
    new import_obsidian3.Setting(contentEl).setHeading().addButton((button) => {
      button.setButtonText("Export").onClick(handleExport);
      button.setCta();
      fullWidthButton(button);
    });
    new import_obsidian3.Setting(contentEl).setHeading().addButton((button) => {
      button.setButtonText("Refresh").onClick(async () => {
        await this.appendWebviews(this.previewDiv);
      });
      fullWidthButton(button);
    });
    const debugEl = new import_obsidian3.Setting(contentEl).setHeading().addButton((button) => {
      button.setButtonText("Debug").onClick(async () => {
        var _a2;
        (_a2 = this.preview) == null ? void 0 : _a2.openDevTools();
      });
      fullWidthButton(button);
    });
    debugEl.settingEl.hidden = !this.plugin.settings.debug;
  }
  generateForm(contentEl) {
    new import_obsidian3.Setting(contentEl).setName(this.i18n.exportDialog.filenameAsTitle).addToggle(
      (toggle) => toggle.setTooltip("Include file name as title").setValue(this.config["showTitle"]).onChange(async (value) => {
        this.config["showTitle"] = value;
        this.webviews.forEach((wv, i) => {
          var _a, _b;
          wv.executeJavaScript(`
              var _title = document.querySelector("h1.__title__");
              if (_title) {
              	_title.style.display = "${value ? "block" : "none"}";
              }
              `);
          const _title = (_b = (_a = this.docs[i]) == null ? void 0 : _a.doc) == null ? void 0 : _b.querySelector("h1.__title__");
          if (_title) {
            _title.style.display = value ? "block" : "none";
          }
        });
      })
    );
    const pageSizes = [
      "A0",
      "A1",
      "A2",
      "A3",
      "A4",
      "A5",
      "A6",
      "Legal",
      "Letter",
      "Tabloid",
      "Ledger",
      "Custom"
    ];
    new import_obsidian3.Setting(contentEl).setName(this.i18n.exportDialog.pageSize).addDropdown((dropdown) => {
      dropdown.addOptions(Object.fromEntries(pageSizes.map((size) => [size, size]))).setValue(this.config.pageSize).onChange(async (value) => {
        this.config["pageSize"] = value;
        if (value == "Custom") {
          sizeEl.settingEl.hidden = false;
        } else {
          sizeEl.settingEl.hidden = true;
        }
        this.togglePrintSize();
        this.calcPageSize();
        await this.calcWebviewSize();
      });
    });
    const sizeEl = new import_obsidian3.Setting(contentEl).setName("Width/Height").addText((text) => {
      setInputWidth(text.inputEl);
      text.setPlaceholder("width").setValue(this.config["pageWidth"]).onChange(
        (0, import_obsidian3.debounce)(
          async (value) => {
            this.config["pageWidth"] = value;
            this.calcPageSize();
            await this.calcWebviewSize();
          },
          500,
          true
        )
      );
    }).addText((text) => {
      setInputWidth(text.inputEl);
      text.setPlaceholder("height").setValue(this.config["pageHeight"]).onChange((value) => {
        this.config["pageHeight"] = value;
      });
    });
    sizeEl.settingEl.hidden = this.config["pageSize"] !== "Custom";
    new import_obsidian3.Setting(contentEl).setName(this.i18n.exportDialog.margin).setDesc("The unit is millimeters.").addDropdown((dropdown) => {
      dropdown.addOption("0", "None").addOption("1", "Default").addOption("2", "Small").addOption("3", "Custom").setValue(this.config["marginType"]).onChange(async (value) => {
        this.config["marginType"] = value;
        if (value == "3") {
          topEl.settingEl.hidden = false;
          btmEl.settingEl.hidden = false;
        } else {
          topEl.settingEl.hidden = true;
          btmEl.settingEl.hidden = true;
        }
      });
    });
    const topEl = new import_obsidian3.Setting(contentEl).setName("Top/Bottom").addText((text) => {
      setInputWidth(text.inputEl);
      text.setPlaceholder("margin top").setValue(this.config["marginTop"]).onChange((value) => {
        this.config["marginTop"] = value;
      });
    }).addText((text) => {
      setInputWidth(text.inputEl);
      text.setPlaceholder("margin bottom").setValue(this.config["marginBottom"]).onChange((value) => {
        this.config["marginBottom"] = value;
      });
    });
    topEl.settingEl.hidden = this.config["marginType"] != "3";
    const btmEl = new import_obsidian3.Setting(contentEl).setName("Left/Right").addText((text) => {
      setInputWidth(text.inputEl);
      text.setPlaceholder("margin left").setValue(this.config["marginLeft"]).onChange((value) => {
        this.config["marginLeft"] = value;
      });
    }).addText((text) => {
      setInputWidth(text.inputEl);
      text.setPlaceholder("margin right").setValue(this.config["marginRight"]).onChange((value) => {
        this.config["marginRight"] = value;
      });
    });
    btmEl.settingEl.hidden = this.config["marginType"] != "3";
    new import_obsidian3.Setting(contentEl).setName(this.i18n.exportDialog.downscalePercent).addSlider((slider) => {
      slider.setLimits(0, 100, 1).setValue(this.config["scale"]).onChange(async (value) => {
        this.config["scale"] = value;
        slider.showTooltip();
      });
    });
    new import_obsidian3.Setting(contentEl).setName(this.i18n.exportDialog.landscape).addToggle(
      (toggle) => toggle.setTooltip("landscape").setValue(this.config["landscape"]).onChange(async (value) => {
        this.config["landscape"] = value;
      })
    );
    new import_obsidian3.Setting(contentEl).setName(this.i18n.exportDialog.displayHeader).addToggle(
      (toggle) => toggle.setTooltip("Display header").setValue(this.config["displayHeader"]).onChange(async (value) => {
        this.config["displayHeader"] = value;
      })
    );
    new import_obsidian3.Setting(contentEl).setName(this.i18n.exportDialog.displayFooter).addToggle(
      (toggle) => toggle.setTooltip("Display footer").setValue(this.config["displayFooter"]).onChange(async (value) => {
        this.config["displayFooter"] = value;
      })
    );
    new import_obsidian3.Setting(contentEl).setName(this.i18n.exportDialog.openAfterExport).addToggle(
      (toggle) => toggle.setTooltip("Open the exported file after exporting.").setValue(this.config["open"]).onChange(async (value) => {
        this.config["open"] = value;
      })
    );
    const snippets = this.cssSnippets();
    if (Object.keys(snippets).length > 0 && this.plugin.settings.enabledCss) {
      new import_obsidian3.Setting(contentEl).setName(this.i18n.exportDialog.cssSnippets).addDropdown((dropdown) => {
        dropdown.addOption("0", "Not select").addOptions(snippets).setValue(this.config["cssSnippet"]).onChange(async (value) => {
          this.config["cssSnippet"] = value;
          await this.appendWebviews(this.previewDiv, false);
        });
      });
    }
  }
  onClose() {
    const { contentEl } = this;
    contentEl.empty();
  }
  cssSnippets() {
    var _a, _b;
    const { snippets, enabledSnippets } = (_b = (_a = this.app) == null ? void 0 : _a.customCss) != null ? _b : {};
    const basePath = this.app.vault.adapter.basePath;
    return Object.fromEntries(
      snippets == null ? void 0 : snippets.filter((item) => !enabledSnippets.has(item)).map((name) => {
        const file = import_path.default.join(basePath, ".obsidian/snippets", name + ".css");
        return [file, name];
      })
    );
  }
};

// src/setting.ts
var import_obsidian4 = require("obsidian");
function setAttributes(element, attributes) {
  for (const key in attributes) {
    element.setAttribute(key, attributes[key]);
  }
}
var renderBuyMeACoffeeBadge = (contentEl, width = 175) => {
  const linkEl = contentEl.createEl("a", {
    href: "https://www.buymeacoffee.com/l1xnan"
  });
  const imgEl = linkEl.createEl("img");
  imgEl.src = "https://img.buymeacoffee.com/button-api/?text=Buy me a coffee&emoji=&slug=nathangeorge&button_colour=6a8696&font_colour=ffffff&font_family=Poppins&outline_colour=000000&coffee_colour=FFDD00";
  imgEl.alt = "Buy me a coffee";
  imgEl.width = width;
};
var ConfigSettingTab = class extends import_obsidian4.PluginSettingTab {
  constructor(app, plugin) {
    super(app, plugin);
    this.plugin = plugin;
    this.i18n = i18n_default.current;
  }
  display() {
    const { containerEl } = this;
    containerEl.empty();
    const supportDesc = new DocumentFragment();
    supportDesc.createDiv({
      text: "Support the continued development of this plugin."
    });
    new import_obsidian4.Setting(containerEl).setDesc(supportDesc);
    renderBuyMeACoffeeBadge(containerEl);
    new import_obsidian4.Setting(containerEl).setName(this.i18n.settings.showTitle).addToggle(
      (toggle) => toggle.setTooltip(this.i18n.settings.showTitle).setValue(this.plugin.settings.showTitle).onChange(async (value) => {
        this.plugin.settings.showTitle = value;
        this.plugin.saveSettings();
      })
    );
    new import_obsidian4.Setting(containerEl).setName(this.i18n.settings.displayHeader).addToggle(
      (toggle) => toggle.setTooltip("Display header").setValue(this.plugin.settings.displayHeader).onChange(async (value) => {
        this.plugin.settings.displayHeader = value;
        this.plugin.saveSettings();
      })
    );
    new import_obsidian4.Setting(containerEl).setName(this.i18n.settings.displayFooter).addToggle(
      (toggle) => toggle.setTooltip("Display footer").setValue(this.plugin.settings.displayFooter).onChange(async (value) => {
        this.plugin.settings.displayFooter = value;
        this.plugin.saveSettings();
      })
    );
    new import_obsidian4.Setting(containerEl).setName(this.i18n.settings.printBackground).setDesc("Whether to print background graphics").addToggle(
      (toggle) => toggle.setValue(this.plugin.settings.printBackground).onChange(async (value) => {
        this.plugin.settings.printBackground = value;
        this.plugin.saveSettings();
      })
    );
    new import_obsidian4.Setting(containerEl).setName("Generate tagged PDF").setDesc(
      "Whether or not to generate a tagged (accessible) PDF. Defaults to false. As this property is experimental, the generated PDF may not adhere fully to PDF/UA and WCAG standards."
    ).addToggle(
      (toggle) => toggle.setValue(this.plugin.settings.generateTaggedPDF).onChange(async (value) => {
        this.plugin.settings.generateTaggedPDF = value;
        this.plugin.saveSettings();
      })
    );
    new import_obsidian4.Setting(containerEl).setName(this.i18n.settings.maxLevel).addDropdown((dropdown) => {
      dropdown.addOptions(Object.fromEntries(["1", "2", "3", "4", "5", "6"].map((level) => [level, `h${level}`]))).setValue(this.plugin.settings.maxLevel).onChange(async (value) => {
        this.plugin.settings.maxLevel = value;
        this.plugin.saveSettings();
      });
    });
    new import_obsidian4.Setting(containerEl).setName(this.i18n.settings.displayMetadata).setDesc("Add frontMatter(title, author, keywords, subject creator, etc) to pdf metadata").addToggle(
      (toggle) => toggle.setValue(this.plugin.settings.displayMetadata).onChange(async (value) => {
        this.plugin.settings.displayMetadata = value;
        this.plugin.saveSettings();
      })
    );
    new import_obsidian4.Setting(containerEl).setName("Advanced").setHeading();
    const headerContentAreaSetting = new import_obsidian4.Setting(containerEl);
    headerContentAreaSetting.settingEl.setAttribute("style", "display: grid; grid-template-columns: 1fr;");
    headerContentAreaSetting.setName(this.i18n.settings.headerTemplate).setDesc(
      'HTML template for the print header. Should be valid HTML markup with following classes used to inject printing values into them: date (formatted print date), title (document title), url (document location), pageNumber (current page number) and totalPages (total pages in the document). For example, <span class="title"></span> would generate span containing the title.'
    );
    const hederContentArea = new import_obsidian4.TextAreaComponent(headerContentAreaSetting.controlEl);
    setAttributes(hederContentArea.inputEl, {
      style: "margin-top: 12px; width: 100%; height: 6vh;"
    });
    hederContentArea.setValue(this.plugin.settings.headerTemplate).onChange(async (value) => {
      this.plugin.settings.headerTemplate = value;
      this.plugin.saveSettings();
    });
    const footerContentAreaSetting = new import_obsidian4.Setting(containerEl);
    footerContentAreaSetting.settingEl.setAttribute("style", "display: grid; grid-template-columns: 1fr;");
    footerContentAreaSetting.setName(this.i18n.settings.footerTemplate).setDesc("HTML template for the print footer. Should use the same format as the headerTemplate.");
    const footerContentArea = new import_obsidian4.TextAreaComponent(footerContentAreaSetting.controlEl);
    setAttributes(footerContentArea.inputEl, {
      style: "margin-top: 12px; width: 100%; height: 6vh;"
    });
    footerContentArea.setValue(this.plugin.settings.footerTemplate).onChange(async (value) => {
      this.plugin.settings.footerTemplate = value;
      this.plugin.saveSettings();
    });
    new import_obsidian4.Setting(containerEl).setName(this.i18n.settings.isTimestamp).setDesc("Add timestamp to output file name").addToggle((cb) => {
      cb.setValue(this.plugin.settings.isTimestamp).onChange(async (value) => {
        this.plugin.settings.isTimestamp = value;
        await this.plugin.saveSettings();
      });
    });
    new import_obsidian4.Setting(containerEl).setName(this.i18n.settings.enabledCss).setDesc("Select the css snippet that are not enabled").addToggle((cb) => {
      cb.setValue(this.plugin.settings.enabledCss).onChange(async (value) => {
        this.plugin.settings.enabledCss = value;
        await this.plugin.saveSettings();
      });
    });
    new import_obsidian4.Setting(containerEl).setName("Debug").setHeading();
    new import_obsidian4.Setting(containerEl).setName(this.i18n.settings.debugMode).setDesc("This is useful for troubleshooting.").addToggle((cb) => {
      cb.setValue(this.plugin.settings.debug).onChange(async (value) => {
        this.plugin.settings.debug = value;
        await this.plugin.saveSettings();
      });
    });
  }
};

// src/main.ts
var fs3 = __toESM(require("fs/promises"));
var import_path2 = __toESM(require("path"));
var isDev = false;
var DEFAULT_SETTINGS = {
  showTitle: true,
  maxLevel: "6",
  displayHeader: true,
  displayFooter: true,
  headerTemplate: `<div style="width: 100vw;font-size:10px;text-align:center;"><span class="title"></span></div>`,
  footerTemplate: `<div style="width: 100vw;font-size:10px;text-align:center;"><span class="pageNumber"></span> / <span class="totalPages"></span></div>`,
  printBackground: false,
  generateTaggedPDF: false,
  displayMetadata: false,
  debug: false,
  isTimestamp: false,
  enabledCss: false
};
var BetterExportPdfPlugin = class extends import_obsidian5.Plugin {
  constructor(app, manifest) {
    super(app, manifest);
    this.i18n = i18n_default.current;
  }
  async onload() {
    await this.loadSettings();
    this.registerCommand();
    this.registerSetting();
    this.registerEvents();
  }
  registerCommand() {
    this.addCommand({
      id: "export-current-file-to-pdf",
      name: this.i18n.exportCurrentFile,
      checkCallback: (checking) => {
        const view = this.app.workspace.getActiveViewOfType(import_obsidian5.MarkdownView);
        const file = view == null ? void 0 : view.file;
        if (!file) {
          return false;
        }
        if (checking) {
          return true;
        }
        new ExportConfigModal(this, file).open();
        return true;
      }
    });
  }
  registerSetting() {
    this.addSettingTab(new ConfigSettingTab(this.app, this));
  }
  registerEvents() {
    this.registerEvent(
      this.app.workspace.on("file-menu", (menu, file) => {
        let title = file instanceof import_obsidian5.TFolder ? "Export folder to PDF" : "Better Export PDF";
        if (isDev) {
          title = `${title} (dev)`;
        }
        menu.addItem((item) => {
          item.setTitle(title).setIcon("download").setSection("action").onClick(async () => {
            new ExportConfigModal(this, file).open();
          });
        });
      })
    );
    this.registerEvent(
      this.app.workspace.on("file-menu", (menu, file) => {
        if (file instanceof import_obsidian5.TFolder) {
          let title = "Export to PDF...";
          if (isDev) {
            title = `${title} (dev)`;
          }
          menu.addItem((item) => {
            item.setTitle(title).setIcon("lucide-folder-down").setSection("action");
            const subMenu = item.setSubmenu();
            subMenu.addItem(
              (item2) => item2.setTitle("Export each file to PDF").setIcon("lucide-file-stack").onClick(async () => {
                new ExportConfigModal(this, file, true).open();
              })
            );
            subMenu.addItem(
              (item2) => item2.setTitle("Generate TOC.md file").setIcon("lucide-file-text").onClick(async () => {
                await this.generateToc(file);
              })
            );
          });
        }
      })
    );
  }
  async generateToc(root) {
    const basePath = this.app.vault.adapter.basePath;
    const toc = import_path2.default.join(basePath, root.path, "_TOC_.md");
    const content = `---
toc: true
title: ${root.name}
---
`;
    await fs3.writeFile(toc, content);
    if (root instanceof import_obsidian5.TFolder) {
      const files = traverseFolder(root);
      for (const file of files) {
        if (file.name == "_TOC_.md") {
          continue;
        }
        await fs3.appendFile(toc, `[[${file.path}]]
`);
      }
    }
  }
  onunload() {
  }
  async loadSettings() {
    this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
  }
  async saveSettings() {
    await this.saveData(this.settings);
  }
  changeConfig() {
    var _a;
    const theme = "obsidian" === ((_a = this.app.vault) == null ? void 0 : _a.getConfig("theme"));
    if (theme) {
      document.body.addClass("theme-light");
      document.body.removeClass("theme-dark");
    }
    document.body.removeClass("theme-dark");
    const node = document.body.createDiv("print");
    const reset = function() {
      node.detach();
      if (theme) {
        document.body.removeClass("theme-light");
        document.body.addClass("theme-dark");
      }
    };
    node.addEventListener("click", reset);
    const el = document.body.createDiv("print");
    const el2 = el.createDiv("markdown-preview-view markdown-rendered");
    el2.toggleClass("rtl", this.app.vault.getConfig("rightToLeft"));
    el2.toggleClass("show-frontmatter", this.app.vault.getConfig("showFrontmatter"));
    el2.createEl("h1", {
      text: "xxxxx"
      // a.basename
    });
  }
};
/*! Bundled license information:

tslib/tslib.es6.js:
  (*! *****************************************************************************
  Copyright (c) Microsoft Corporation.
  
  Permission to use, copy, modify, and/or distribute this software for any
  purpose with or without fee is hereby granted.
  
  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  PERFORMANCE OF THIS SOFTWARE.
  ***************************************************************************** *)
*/

/* nosourcemap */